2 Copyright (C) 1996-1997 Id Software, Inc.
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13 See the GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20 // cmd.c -- Quake script command processing module
24 #define MAX_ALIAS_NAME 32
25 // this is the largest script file that can be executed in one step
26 // LordHavoc: inreased this from 8192 to 32768
27 // div0: increased this from 32k to 128k
28 #define CMDBUFSIZE 131072
29 // maximum number of parameters to a command
31 // maximum tokenizable commandline length (counting NUL terminations)
32 #define CMD_TOKENIZELENGTH (MAX_INPUTLINE + MAX_ARGS)
34 typedef struct cmdalias_s
36 struct cmdalias_s *next;
37 char name[MAX_ALIAS_NAME];
41 static cmdalias_t *cmd_alias;
43 static qboolean cmd_wait;
45 static mempool_t *cmd_mempool;
47 static char cmd_tokenizebuffer[CMD_TOKENIZELENGTH];
48 static int cmd_tokenizebufferpos = 0;
50 //=============================================================================
56 Causes execution of the remainder of the command buffer to be delayed until
57 next frame. This allows commands like:
58 bind g "impulse 5 ; +attack ; wait ; -attack ; impulse 2"
61 static void Cmd_Wait_f (void)
70 Print something to the center of the screen using SCR_Centerprint
73 static void Cmd_Centerprint_f (void)
75 char msg[MAX_INPUTLINE];
80 strlcpy(msg, Cmd_Argv(1), sizeof(msg));
81 for(i = 2; i < c; ++i)
83 strlcat(msg, " ", sizeof(msg));
84 strlcat(msg, Cmd_Argv(i), sizeof(msg));
87 for(p = 0, i = 0; i < c; ++i)
93 else if(msg[i+1] == '\\')
105 SCR_CenterPrint(msg);
110 =============================================================================
114 =============================================================================
117 static sizebuf_t cmd_text;
118 static unsigned char cmd_text_buf[CMDBUFSIZE];
124 Adds command text at the end of the buffer
127 void Cbuf_AddText (const char *text)
131 l = (int)strlen (text);
133 if (cmd_text.cursize + l >= cmd_text.maxsize)
135 Con_Print("Cbuf_AddText: overflow\n");
139 SZ_Write (&cmd_text, (const unsigned char *)text, (int)strlen (text));
147 Adds command text immediately after the current command
148 Adds a \n to the text
149 FIXME: actually change the command buffer to do less copying
152 void Cbuf_InsertText (const char *text)
157 // copy off any commands still remaining in the exec buffer
158 templen = cmd_text.cursize;
161 temp = (char *)Mem_Alloc (tempmempool, templen);
162 memcpy (temp, cmd_text.data, templen);
163 SZ_Clear (&cmd_text);
168 // add the entire text of the file
171 // add the copied off data
174 SZ_Write (&cmd_text, (const unsigned char *)temp, templen);
184 static void Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias );
185 void Cbuf_Execute (void)
189 char line[MAX_INPUTLINE];
190 char preprocessed[MAX_INPUTLINE];
194 // LordHavoc: making sure the tokenizebuffer doesn't get filled up by repeated crashes
195 cmd_tokenizebufferpos = 0;
197 while (cmd_text.cursize)
199 // find a \n or ; line break
200 text = (char *)cmd_text.data;
203 for (i=0 ; i< cmd_text.cursize ; i++)
207 // make sure i doesn't get > cursize which causes a negative
208 // size in memmove, which is fatal --blub
209 if (i < (cmd_text.cursize-1) && (text[i] == '\\' && (text[i+1] == '"' || text[i+1] == '\\')))
211 if ( !quotes && text[i] == ';')
212 break; // don't break if inside a quoted string
213 if (text[i] == '\r' || text[i] == '\n')
217 // better than CRASHING on overlong input lines that may SOMEHOW enter the buffer
218 if(i >= MAX_INPUTLINE)
220 Con_Printf("Warning: console input buffer had an overlong line. Ignored.\n");
225 memcpy (line, text, i);
229 // delete the text from the command buffer and move remaining commands down
230 // this is necessary because commands (exec, alias) can insert data at the
231 // beginning of the text buffer
233 if (i == cmd_text.cursize)
234 cmd_text.cursize = 0;
238 cmd_text.cursize -= i;
239 memmove (cmd_text.data, text+i, cmd_text.cursize);
242 // execute the command line
243 firstchar = line + strspn(line, " \t");
245 (strncmp(firstchar, "alias", 5) || (firstchar[5] != ' ' && firstchar[5] != '\t'))
247 (strncmp(firstchar, "bind", 4) || (firstchar[4] != ' ' && firstchar[4] != '\t'))
249 (strncmp(firstchar, "in_bind", 7) || (firstchar[7] != ' ' && firstchar[7] != '\t'))
252 Cmd_PreprocessString( line, preprocessed, sizeof(preprocessed), NULL );
253 Cmd_ExecuteString (preprocessed, src_command);
257 Cmd_ExecuteString (line, src_command);
261 { // skip out while text still remains in buffer, leaving it
270 ==============================================================================
274 ==============================================================================
281 Adds command line parameters as script statements
282 Commands lead with a +, and continue until a - or another +
283 quake +prog jctest.qp +cmd amlev1
284 quake -nosound +cmd amlev1
287 qboolean host_stuffcmdsrun = false;
288 void Cmd_StuffCmds_f (void)
291 // this is for all commandline options combined (and is bounds checked)
292 char build[MAX_INPUTLINE];
294 if (Cmd_Argc () != 1)
296 Con_Print("stuffcmds : execute command line parameters\n");
300 // no reason to run the commandline arguments twice
301 if (host_stuffcmdsrun)
304 host_stuffcmdsrun = true;
307 for (i = 0;i < com_argc;i++)
309 if (com_argv[i] && com_argv[i][0] == '+' && (com_argv[i][1] < '0' || com_argv[i][1] > '9') && l + strlen(com_argv[i]) - 1 <= sizeof(build) - 1)
312 while (com_argv[i][j])
313 build[l++] = com_argv[i][j++];
315 for (;i < com_argc;i++)
319 if ((com_argv[i][0] == '+' || com_argv[i][0] == '-') && (com_argv[i][1] < '0' || com_argv[i][1] > '9'))
321 if (l + strlen(com_argv[i]) + 4 > sizeof(build) - 1)
324 if (strchr(com_argv[i], ' '))
326 for (j = 0;com_argv[i][j];j++)
327 build[l++] = com_argv[i][j];
328 if (strchr(com_argv[i], ' '))
335 // now terminate the combined string and prepend it to the command buffer
336 // we already reserved space for the terminator
338 Cbuf_InsertText (build);
347 static void Cmd_Exec_f (void)
351 if (Cmd_Argc () != 2)
353 Con_Print("exec <filename> : execute a script file\n");
357 f = (char *)FS_LoadFile (Cmd_Argv(1), tempmempool, false, NULL);
360 Con_Printf("couldn't exec %s\n",Cmd_Argv(1));
363 Con_Printf("execing %s\n",Cmd_Argv(1));
365 // if executing default.cfg for the first time, lock the cvar defaults
366 // it may seem backwards to insert this text BEFORE the default.cfg
367 // but Cbuf_InsertText inserts before, so this actually ends up after it.
368 if (!strcmp(Cmd_Argv(1), "default.cfg"))
369 Cbuf_InsertText("\ncvar_lockdefaults\n");
371 // insert newline after the text to make sure the last line is terminated (some text editors omit the trailing newline)
372 // (note: insertion order here is backwards from execution order, so this adds it after the text, by calling it before...)
373 Cbuf_InsertText ("\n");
383 Just prints the rest of the line to the console
386 static void Cmd_Echo_f (void)
390 for (i=1 ; i<Cmd_Argc() ; i++)
391 Con_Printf("%s ",Cmd_Argv(i));
396 // Support Doom3-style Toggle Console Command
401 Toggles a specified console variable amongst the values specified (default is 0 and 1)
404 static void Cmd_Toggle_f(void)
406 // Acquire Number of Arguments
407 int nNumArgs = Cmd_Argc();
410 // No Arguments Specified; Print Usage
411 Con_Print("Toggle Console Variable - Usage\n toggle <variable> - toggles between 0 and 1\n toggle <variable> <value> - toggles between 0 and <value>\n toggle <variable> [string 1] [string 2]...[string n] - cycles through all strings\n");
413 { // Correct Arguments Specified
414 // Acquire Potential CVar
415 cvar_t* cvCVar = Cvar_FindVar( Cmd_Argv(1) );
422 Cvar_SetValueQuick(cvCVar, 0);
424 Cvar_SetValueQuick(cvCVar, 1);
428 { // 0 and Specified Usage
429 if(cvCVar->integer == atoi(Cmd_Argv(2) ) )
430 // CVar is Specified Value; // Reset to 0
431 Cvar_SetValueQuick(cvCVar, 0);
433 if(cvCVar->integer == 0)
434 // CVar is 0; Specify Value
435 Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
437 // CVar does not match; Reset to 0
438 Cvar_SetValueQuick(cvCVar, 0);
441 { // Variable Values Specified
445 for(nCnt = 2; nCnt < nNumArgs; nCnt++)
446 { // Cycle through Values
447 if( strcmp(cvCVar->string, Cmd_Argv(nCnt) ) == 0)
448 { // Current Value Located; Increment to Next
449 if( (nCnt + 1) == nNumArgs)
450 // Max Value Reached; Reset
451 Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
454 Cvar_SetQuick(cvCVar, Cmd_Argv(nCnt + 1) );
463 // Value not Found; Reset to Original
464 Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
470 Con_Printf("ERROR : CVar '%s' not found\n", Cmd_Argv(1) );
479 Creates a new command that executes a command string (possibly ; seperated)
482 static void Cmd_Alias_f (void)
485 char cmd[MAX_INPUTLINE];
492 Con_Print("Current alias commands:\n");
493 for (a = cmd_alias ; a ; a=a->next)
494 Con_Printf("%s : %s\n", a->name, a->value);
499 if (strlen(s) >= MAX_ALIAS_NAME)
501 Con_Print("Alias name is too long\n");
505 // if the alias already exists, reuse it
506 for (a = cmd_alias ; a ; a=a->next)
508 if (!strcmp(s, a->name))
517 cmdalias_t *prev, *current;
519 a = (cmdalias_t *)Z_Malloc (sizeof(cmdalias_t));
520 strlcpy (a->name, s, sizeof (a->name));
521 // insert it at the right alphanumeric position
522 for( prev = NULL, current = cmd_alias ; current && strcmp( current->name, a->name ) < 0 ; prev = current, current = current->next )
533 // copy the rest of the command line
534 cmd[0] = 0; // start out with a null string
536 for (i=2 ; i< c ; i++)
538 strlcat (cmd, Cmd_Argv(i), sizeof (cmd));
540 strlcat (cmd, " ", sizeof (cmd));
542 strlcat (cmd, "\n", sizeof (cmd));
544 alloclen = strlen (cmd) + 1;
545 a->value = (char *)Z_Malloc (alloclen);
546 memcpy (a->value, cmd, alloclen);
550 =============================================================================
554 =============================================================================
557 typedef struct cmd_function_s
559 struct cmd_function_s *next;
561 const char *description;
562 xcommand_t consolefunction;
563 xcommand_t clientfunction;
568 static const char *cmd_argv[MAX_ARGS];
569 static const char *cmd_null_string = "";
570 static const char *cmd_args;
571 cmd_source_t cmd_source;
574 static cmd_function_t *cmd_functions; // possible commands to execute
576 static const char *Cmd_GetDirectCvarValue(const char *varname, cmdalias_t *alias, qboolean *is_multiple)
583 *is_multiple = false;
585 if(!varname || !*varname)
590 if(!strcmp(varname, "*"))
596 else if(varname[strlen(varname) - 1] == '-')
598 argno = strtol(varname, &endptr, 10);
599 if(endptr == varname + strlen(varname) - 1)
601 // whole string is a number, apart from the -
602 const char *p = Cmd_Args();
603 for(; argno > 1; --argno)
604 if(!COM_ParseToken_Console(&p))
611 // kill pre-argument whitespace
612 for (;*p && *p <= ' ';p++)
621 argno = strtol(varname, &endptr, 10);
624 // whole string is a number
625 // NOTE: we already made sure we don't have an empty cvar name!
626 if(argno >= 0 && argno < Cmd_Argc())
627 return Cmd_Argv(argno);
632 if((cvar = Cvar_FindVar(varname)) && !(cvar->flags & CVAR_PRIVATE))
638 qboolean Cmd_QuoteString(char *out, size_t outlen, const char *in, const char *quoteset)
640 qboolean quote_quot = !!strchr(quoteset, '"');
641 qboolean quote_backslash = !!strchr(quoteset, '\\');
642 qboolean quote_dollar = !!strchr(quoteset, '$');
646 if(*in == '"' && quote_quot)
653 *out++ = '\\'; --outlen;
654 *out++ = '"'; --outlen;
656 else if(*in == '\\' && quote_backslash)
663 *out++ = '\\'; --outlen;
664 *out++ = '\\'; --outlen;
666 else if(*in == '$' && quote_dollar)
673 *out++ = '$'; --outlen;
674 *out++ = '$'; --outlen;
683 *out++ = *in; --outlen;
691 static const char *Cmd_GetCvarValue(const char *var, size_t varlen, cmdalias_t *alias)
693 static char varname[MAX_INPUTLINE];
694 static char varval[MAX_INPUTLINE];
698 if(varlen >= MAX_INPUTLINE)
699 varlen = MAX_INPUTLINE - 1;
700 memcpy(varname, var, varlen);
702 varfunc = strchr(varname, ' ');
718 if(varname[0] == '$')
719 varstr = Cmd_GetDirectCvarValue(Cmd_GetDirectCvarValue(varname + 1, alias, NULL), alias, NULL);
722 qboolean is_multiple = false;
723 // Exception: $* and $n- don't use the quoted form by default
724 varstr = Cmd_GetDirectCvarValue(varname, alias, &is_multiple);
732 Con_Printf("Warning: Could not expand $%s in alias %s\n", varname, alias->name);
734 Con_Printf("Warning: Could not expand $%s\n", varname);
738 if(!varfunc || !strcmp(varfunc, "q")) // note: quoted form is default, use "asis" to override!
740 // quote it so it can be used inside double quotes
741 // we just need to replace " by \", and of course, double backslashes
742 Cmd_QuoteString(varval, sizeof(varval), varstr, "\"\\");
745 else if(!strcmp(varfunc, "asis"))
750 Con_Printf("Unknown variable function %s\n", varfunc);
758 Preprocesses strings and replaces $*, $param#, $cvar accordingly
760 static void Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias ) {
766 // don't crash if there's no room in the outtext buffer
767 if( maxoutlen == 0 ) {
770 maxoutlen--; // because of \0
775 while( *in && outlen < maxoutlen ) {
777 // this is some kind of expansion, see what comes after the $
780 // The console does the following preprocessing:
782 // - $$ is transformed to a single dollar sign.
783 // - $var or ${var} are expanded to the contents of the named cvar,
784 // with quotation marks and backslashes quoted so it can safely
785 // be used inside quotation marks (and it should always be used
787 // - ${var asis} inserts the cvar value as is, without doing this
789 // - prefix the cvar name with a dollar sign to do indirection;
790 // for example, if $x has the value timelimit, ${$x} will return
791 // the value of $timelimit
792 // - when expanding an alias, the special variable name $* refers
793 // to all alias parameters, and a number refers to that numbered
794 // alias parameter, where the name of the alias is $0, the first
795 // parameter is $1 and so on; as a special case, $* inserts all
796 // parameters, without extra quoting, so one can use $* to just
797 // pass all parameters around. All parameters starting from $n
798 // can be referred to as $n- (so $* is equivalent to $1-).
800 // Note: when expanding an alias, cvar expansion is done in the SAME step
801 // as alias expansion so that alias parameters or cvar values containing
802 // dollar signs have no unwanted bad side effects. However, this needs to
803 // be accounted for when writing complex aliases. For example,
804 // alias foo "set x NEW; echo $x"
805 // actually expands to
806 // "set x NEW; echo OLD"
807 // and will print OLD! To work around this, use a second alias:
808 // alias foo "set x NEW; foo2"
809 // alias foo2 "echo $x"
811 // Also note: lines starting with alias are exempt from cvar expansion.
812 // If you want cvar expansion, write "alias" instead:
815 // alias foo "echo $x"
816 // "alias" bar "echo $x"
819 // foo will print 2, because the variable $x will be expanded when the alias
820 // gets expanded. bar will print 1, because the variable $x was expanded
821 // at definition time. foo can be equivalently defined as
823 // "alias" foo "echo $$x"
825 // because at definition time, $$ will get replaced to a single $.
830 } else if(*in == '{') {
831 varlen = strcspn(in + 1, "}");
832 if(in[varlen + 1] == '}')
834 val = Cmd_GetCvarValue(in + 1, varlen, alias);
844 varlen = strspn(in, "*0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-");
845 val = Cmd_GetCvarValue(in, varlen, alias);
850 // insert the cvar value
851 while(*val && outlen < maxoutlen)
852 outtext[outlen++] = *val++;
857 // copy the unexpanded text
858 outtext[outlen++] = '$';
859 while(eat && outlen < maxoutlen)
861 outtext[outlen++] = *in++;
866 outtext[outlen++] = *in++;
876 Called for aliases and fills in the alias into the cbuffer
879 static void Cmd_ExecuteAlias (cmdalias_t *alias)
881 static char buffer[ MAX_INPUTLINE ];
882 static char buffer2[ MAX_INPUTLINE ];
883 Cmd_PreprocessString( alias->value, buffer, sizeof(buffer) - 2, alias );
884 // insert at start of command buffer, so that aliases execute in order
885 // (fixes bug introduced by Black on 20050705)
887 // Note: Cbuf_PreprocessString will be called on this string AGAIN! So we
888 // have to make sure that no second variable expansion takes place, otherwise
889 // alias parameters containing dollar signs can have bad effects.
890 Cmd_QuoteString(buffer2, sizeof(buffer2), buffer, "$");
891 Cbuf_InsertText( buffer2 );
898 CmdList Added by EvilTypeGuy eviltypeguy@qeradiant.com
899 Thanks to Matthias "Maddes" Buecher, http://www.inside3d.com/qip/
903 static void Cmd_List_f (void)
911 partial = Cmd_Argv (1);
912 len = (int)strlen(partial);
921 for (cmd = cmd_functions; cmd; cmd = cmd->next)
923 if (partial && strncmp(partial, cmd->name, len))
925 Con_Printf("%s : %s\n", cmd->name, cmd->description);
930 Con_Printf("%i Command%s beginning with \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
932 Con_Printf("%i Command%s\n\n", count, (count > 1) ? "s" : "");
942 cmd_mempool = Mem_AllocPool("commands", 0, NULL);
943 // space for commands and script files
944 cmd_text.data = cmd_text_buf;
945 cmd_text.maxsize = sizeof(cmd_text_buf);
946 cmd_text.cursize = 0;
949 void Cmd_Init_Commands (void)
952 // register our commands
954 Cmd_AddCommand ("stuffcmds",Cmd_StuffCmds_f, "execute commandline parameters (must be present in quake.rc script)");
955 Cmd_AddCommand ("exec",Cmd_Exec_f, "execute a script file");
956 Cmd_AddCommand ("echo",Cmd_Echo_f, "print a message to the console (useful in scripts)");
957 Cmd_AddCommand ("alias",Cmd_Alias_f, "create a script function (parameters are passed in as $1 through $9, and $* for all parameters)");
958 Cmd_AddCommand ("cmd", Cmd_ForwardToServer, "send a console commandline to the server (used by some mods)");
959 Cmd_AddCommand ("wait", Cmd_Wait_f, "make script execution wait for next rendered frame");
960 Cmd_AddCommand ("set", Cvar_Set_f, "create or change the value of a console variable");
961 Cmd_AddCommand ("seta", Cvar_SetA_f, "create or change the value of a console variable that will be saved to config.cfg");
963 // 2000-01-09 CmdList, CvarList commands By Matthias "Maddes" Buecher
964 // Added/Modified by EvilTypeGuy eviltypeguy@qeradiant.com
965 Cmd_AddCommand ("cmdlist", Cmd_List_f, "lists all console commands beginning with the specified prefix");
966 Cmd_AddCommand ("cvarlist", Cvar_List_f, "lists all console variables beginning with the specified prefix");
968 Cmd_AddCommand ("cvar_lockdefaults", Cvar_LockDefaults_f, "stores the current values of all cvars into their default values, only used once during startup after parsing default.cfg");
969 Cmd_AddCommand ("cvar_resettodefaults_all", Cvar_ResetToDefaults_All_f, "sets all cvars to their locked default values");
970 Cmd_AddCommand ("cvar_resettodefaults_nosaveonly", Cvar_ResetToDefaults_NoSaveOnly_f, "sets all non-saved cvars to their locked default values (variables that will not be saved to config.cfg)");
971 Cmd_AddCommand ("cvar_resettodefaults_saveonly", Cvar_ResetToDefaults_SaveOnly_f, "sets all saved cvars to their locked default values (variables that will be saved to config.cfg)");
973 Cmd_AddCommand ("cprint", Cmd_Centerprint_f, "print something at the screen center");
976 // Support Doom3-style Toggle Command
977 Cmd_AddCommand( "toggle", Cmd_Toggle_f, "toggles a console variable's values (use for more info)");
985 void Cmd_Shutdown(void)
987 Mem_FreePool(&cmd_mempool);
1005 const char *Cmd_Argv (int arg)
1007 if (arg >= cmd_argc )
1008 return cmd_null_string;
1009 return cmd_argv[arg];
1017 const char *Cmd_Args (void)
1027 Parses the given string into command line tokens.
1030 // AK: This function should only be called from ExcuteString because the current design is a bit of an hack
1031 static void Cmd_TokenizeString (const char *text)
1040 // skip whitespace up to a /n
1041 while (*text && *text <= ' ' && *text != '\r' && *text != '\n')
1048 if (*text == '\n' || *text == '\r')
1050 // a newline separates commands in the buffer
1051 if (*text == '\r' && text[1] == '\n')
1063 if (!COM_ParseToken_Console(&text))
1066 if (cmd_argc < MAX_ARGS)
1068 l = (int)strlen(com_token) + 1;
1069 if (cmd_tokenizebufferpos + l > CMD_TOKENIZELENGTH)
1071 Con_Printf("Cmd_TokenizeString: ran out of %i character buffer space for command arguements\n", CMD_TOKENIZELENGTH);
1074 memcpy (cmd_tokenizebuffer + cmd_tokenizebufferpos, com_token, l);
1075 cmd_argv[cmd_argc] = cmd_tokenizebuffer + cmd_tokenizebufferpos;
1076 cmd_tokenizebufferpos += l;
1088 void Cmd_AddCommand_WithClientCommand (const char *cmd_name, xcommand_t consolefunction, xcommand_t clientfunction, const char *description)
1090 cmd_function_t *cmd;
1091 cmd_function_t *prev, *current;
1093 // fail if the command is a variable name
1094 if (Cvar_FindVar( cmd_name ))
1096 Con_Printf("Cmd_AddCommand: %s already defined as a var\n", cmd_name);
1100 // fail if the command already exists
1101 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1103 if (!strcmp (cmd_name, cmd->name))
1105 if (consolefunction || clientfunction)
1107 Con_Printf("Cmd_AddCommand: %s already defined\n", cmd_name);
1112 cmd->csqcfunc = true;
1118 cmd = (cmd_function_t *)Mem_Alloc(cmd_mempool, sizeof(cmd_function_t));
1119 cmd->name = cmd_name;
1120 cmd->consolefunction = consolefunction;
1121 cmd->clientfunction = clientfunction;
1122 cmd->description = description;
1123 if(!consolefunction && !clientfunction) //[515]: csqc
1124 cmd->csqcfunc = true;
1125 cmd->next = cmd_functions;
1127 // insert it at the right alphanumeric position
1128 for( prev = NULL, current = cmd_functions ; current && strcmp( current->name, cmd->name ) < 0 ; prev = current, current = current->next )
1133 cmd_functions = cmd;
1135 cmd->next = current;
1138 void Cmd_AddCommand (const char *cmd_name, xcommand_t function, const char *description)
1140 Cmd_AddCommand_WithClientCommand (cmd_name, function, NULL, description);
1148 qboolean Cmd_Exists (const char *cmd_name)
1150 cmd_function_t *cmd;
1152 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1153 if (!strcmp (cmd_name,cmd->name))
1165 const char *Cmd_CompleteCommand (const char *partial)
1167 cmd_function_t *cmd;
1170 len = strlen(partial);
1176 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1177 if (!strncasecmp(partial, cmd->name, len))
1184 Cmd_CompleteCountPossible
1186 New function for tab-completion system
1187 Added by EvilTypeGuy
1188 Thanks to Fett erich@heintz.com
1192 int Cmd_CompleteCountPossible (const char *partial)
1194 cmd_function_t *cmd;
1199 len = strlen(partial);
1204 // Loop through the command list and count all partial matches
1205 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1206 if (!strncasecmp(partial, cmd->name, len))
1213 Cmd_CompleteBuildList
1215 New function for tab-completion system
1216 Added by EvilTypeGuy
1217 Thanks to Fett erich@heintz.com
1221 const char **Cmd_CompleteBuildList (const char *partial)
1223 cmd_function_t *cmd;
1226 size_t sizeofbuf = (Cmd_CompleteCountPossible (partial) + 1) * sizeof (const char *);
1229 len = strlen(partial);
1230 buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1231 // Loop through the alias list and print all matches
1232 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1233 if (!strncasecmp(partial, cmd->name, len))
1234 buf[bpos++] = cmd->name;
1240 // written by LordHavoc
1241 void Cmd_CompleteCommandPrint (const char *partial)
1243 cmd_function_t *cmd;
1244 size_t len = strlen(partial);
1245 // Loop through the command list and print all matches
1246 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1247 if (!strncasecmp(partial, cmd->name, len))
1248 Con_Printf("%s : %s\n", cmd->name, cmd->description);
1254 New function for tab-completion system
1255 Added by EvilTypeGuy
1256 Thanks to Fett erich@heintz.com
1260 const char *Cmd_CompleteAlias (const char *partial)
1265 len = strlen(partial);
1271 for (alias = cmd_alias; alias; alias = alias->next)
1272 if (!strncasecmp(partial, alias->name, len))
1278 // written by LordHavoc
1279 void Cmd_CompleteAliasPrint (const char *partial)
1282 size_t len = strlen(partial);
1283 // Loop through the alias list and print all matches
1284 for (alias = cmd_alias; alias; alias = alias->next)
1285 if (!strncasecmp(partial, alias->name, len))
1286 Con_Printf("%s : %s\n", alias->name, alias->value);
1291 Cmd_CompleteAliasCountPossible
1293 New function for tab-completion system
1294 Added by EvilTypeGuy
1295 Thanks to Fett erich@heintz.com
1299 int Cmd_CompleteAliasCountPossible (const char *partial)
1307 len = strlen(partial);
1312 // Loop through the command list and count all partial matches
1313 for (alias = cmd_alias; alias; alias = alias->next)
1314 if (!strncasecmp(partial, alias->name, len))
1321 Cmd_CompleteAliasBuildList
1323 New function for tab-completion system
1324 Added by EvilTypeGuy
1325 Thanks to Fett erich@heintz.com
1329 const char **Cmd_CompleteAliasBuildList (const char *partial)
1334 size_t sizeofbuf = (Cmd_CompleteAliasCountPossible (partial) + 1) * sizeof (const char *);
1337 len = strlen(partial);
1338 buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1339 // Loop through the alias list and print all matches
1340 for (alias = cmd_alias; alias; alias = alias->next)
1341 if (!strncasecmp(partial, alias->name, len))
1342 buf[bpos++] = alias->name;
1348 void Cmd_ClearCsqcFuncs (void)
1350 cmd_function_t *cmd;
1351 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1352 cmd->csqcfunc = false;
1355 qboolean CL_VM_ConsoleCommand (const char *cmd);
1360 A complete command line has been parsed, so try to execute it
1361 FIXME: lookupnoadd the token to speed search?
1364 void Cmd_ExecuteString (const char *text, cmd_source_t src)
1367 cmd_function_t *cmd;
1370 oldpos = cmd_tokenizebufferpos;
1373 Cmd_TokenizeString (text);
1375 // execute the command line
1378 cmd_tokenizebufferpos = oldpos;
1379 return; // no tokens
1383 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1385 if (!strcasecmp (cmd_argv[0],cmd->name))
1387 if (cmd->csqcfunc && CL_VM_ConsoleCommand (text)) //[515]: csqc
1392 if (cmd->consolefunction)
1393 cmd->consolefunction ();
1394 else if (cmd->clientfunction)
1396 if (cls.state == ca_connected)
1398 // forward remote commands to the server for execution
1399 Cmd_ForwardToServer();
1402 Con_Printf("Can not send command \"%s\", not connected.\n", Cmd_Argv(0));
1405 Con_Printf("Command \"%s\" can not be executed\n", Cmd_Argv(0));
1406 cmd_tokenizebufferpos = oldpos;
1409 if (cmd->clientfunction)
1411 cmd->clientfunction ();
1412 cmd_tokenizebufferpos = oldpos;
1421 // if it's a client command and no command was found, say so.
1422 if (cmd_source == src_client)
1424 Con_Printf("player \"%s\" tried to %s\n", host_client->name, text);
1429 for (a=cmd_alias ; a ; a=a->next)
1431 if (!strcasecmp (cmd_argv[0], a->name))
1433 Cmd_ExecuteAlias(a);
1434 cmd_tokenizebufferpos = oldpos;
1440 if (!Cvar_Command () && host_framecount > 0)
1441 Con_Printf("Unknown command \"%s\"\n", Cmd_Argv(0));
1443 cmd_tokenizebufferpos = oldpos;
1449 Cmd_ForwardStringToServer
1451 Sends an entire command string over to the server, unprocessed
1454 void Cmd_ForwardStringToServer (const char *s)
1457 if (cls.state != ca_connected)
1459 Con_Printf("Can't \"%s\", not connected\n", s);
1466 // LordHavoc: thanks to Fuh for bringing the pure evil of SZ_Print to my
1467 // attention, it has been eradicated from here, its only (former) use in
1468 // all of darkplaces.
1469 if (cls.protocol == PROTOCOL_QUAKEWORLD)
1470 MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
1472 MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
1473 if ((!strncmp(s, "say ", 4) || !strncmp(s, "say_team ", 9)) && cl_locs_enable.integer)
1475 // say/say_team commands can replace % character codes with status info
1478 if (*s == '%' && s[1])
1480 // handle proquake message macros
1484 case 'l': // current location
1485 CL_Locs_FindLocationName(temp, sizeof(temp), cl.movement_origin);
1487 case 'h': // current health
1488 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_HEALTH]);
1490 case 'a': // current armor
1491 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ARMOR]);
1493 case 'x': // current rockets
1494 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ROCKETS]);
1496 case 'c': // current cells
1497 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_CELLS]);
1499 // silly proquake macros
1500 case 'd': // loc at last death
1501 CL_Locs_FindLocationName(temp, sizeof(temp), cl.lastdeathorigin);
1503 case 't': // current time
1504 dpsnprintf(temp, sizeof(temp), "%.0f:%.0f", floor(cl.time / 60), cl.time - floor(cl.time / 60) * 60);
1506 case 'r': // rocket launcher status ("I have RL", "I need rockets", "I need RL")
1507 if (!(cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER))
1508 dpsnprintf(temp, sizeof(temp), "I need RL");
1509 else if (!cl.stats[STAT_ROCKETS])
1510 dpsnprintf(temp, sizeof(temp), "I need rockets");
1512 dpsnprintf(temp, sizeof(temp), "I have RL");
1514 case 'p': // powerup status (outputs "quad" "pent" and "eyes" according to status)
1515 if (cl.stats[STAT_ITEMS] & IT_QUAD)
1518 strlcat(temp, " ", sizeof(temp));
1519 strlcat(temp, "quad", sizeof(temp));
1521 if (cl.stats[STAT_ITEMS] & IT_INVULNERABILITY)
1524 strlcat(temp, " ", sizeof(temp));
1525 strlcat(temp, "pent", sizeof(temp));
1527 if (cl.stats[STAT_ITEMS] & IT_INVISIBILITY)
1530 strlcat(temp, " ", sizeof(temp));
1531 strlcat(temp, "eyes", sizeof(temp));
1534 case 'w': // weapon status (outputs "SSG:NG:SNG:GL:RL:LG" with the text between : characters omitted if you lack the weapon)
1535 if (cl.stats[STAT_ITEMS] & IT_SUPER_SHOTGUN)
1536 strlcat(temp, "SSG", sizeof(temp));
1537 strlcat(temp, ":", sizeof(temp));
1538 if (cl.stats[STAT_ITEMS] & IT_NAILGUN)
1539 strlcat(temp, "NG", sizeof(temp));
1540 strlcat(temp, ":", sizeof(temp));
1541 if (cl.stats[STAT_ITEMS] & IT_SUPER_NAILGUN)
1542 strlcat(temp, "SNG", sizeof(temp));
1543 strlcat(temp, ":", sizeof(temp));
1544 if (cl.stats[STAT_ITEMS] & IT_GRENADE_LAUNCHER)
1545 strlcat(temp, "GL", sizeof(temp));
1546 strlcat(temp, ":", sizeof(temp));
1547 if (cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER)
1548 strlcat(temp, "RL", sizeof(temp));
1549 strlcat(temp, ":", sizeof(temp));
1550 if (cl.stats[STAT_ITEMS] & IT_LIGHTNING)
1551 strlcat(temp, "LG", sizeof(temp));
1554 // not a recognized macro, print it as-is...
1560 // write the resulting text
1561 SZ_Write(&cls.netcon->message, (unsigned char *)temp, strlen(temp));
1565 MSG_WriteByte(&cls.netcon->message, *s);
1568 MSG_WriteByte(&cls.netcon->message, 0);
1570 else // any other command is passed on as-is
1571 SZ_Write(&cls.netcon->message, (const unsigned char *)s, (int)strlen(s) + 1);
1578 Sends the entire command line over to the server
1581 void Cmd_ForwardToServer (void)
1584 if (!strcasecmp(Cmd_Argv(0), "cmd"))
1586 // we want to strip off "cmd", so just send the args
1587 s = Cmd_Argc() > 1 ? Cmd_Args() : "";
1591 // we need to keep the command name, so send Cmd_Argv(0), a space and then Cmd_Args()
1592 s = va("%s %s", Cmd_Argv(0), Cmd_Argc() > 1 ? Cmd_Args() : "");
1594 // don't send an empty forward message if the user tries "cmd" by itself
1597 Cmd_ForwardStringToServer(s);
1605 Returns the position (1 to argc-1) in the command's argument list
1606 where the given parameter apears, or 0 if not present
1610 int Cmd_CheckParm (const char *parm)
1616 Con_Printf ("Cmd_CheckParm: NULL");
1620 for (i = 1; i < Cmd_Argc (); i++)
1621 if (!strcasecmp (parm, Cmd_Argv (i)))