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)
66 typedef struct cmddeferred_s
68 struct cmddeferred_s *next;
73 static cmddeferred_t *cmd_deferred_list;
79 Cause a command to be executed after a delay.
82 static void Cmd_Defer_f (void)
86 double time = Sys_DoubleTime();
87 cmddeferred_t *next = cmd_deferred_list;
89 Con_Printf("No commands are pending.\n");
92 Con_Printf("-> In %'9.2f: %s\n", next->time-time, next->value);
95 } else if(Cmd_Argc() != 3)
97 Con_Printf("usage: defer <seconds> <command>\n");
100 const char *value = Cmd_Argv(2);
101 cmddeferred_t *defcmd = (cmddeferred_t*)Mem_Alloc(tempmempool, sizeof(*defcmd));
102 unsigned int len = strlen(value);
104 defcmd->time = Sys_DoubleTime() + atof(Cmd_Argv(1));
105 defcmd->value = (char*)Mem_Alloc(tempmempool, len+1);
106 memcpy(defcmd->value, value, len);
107 defcmd->value[len] = 0;
109 defcmd->next = cmd_deferred_list;
110 cmd_deferred_list = defcmd;
118 Print something to the center of the screen using SCR_Centerprint
121 static void Cmd_Centerprint_f (void)
123 char msg[MAX_INPUTLINE];
124 unsigned int i, c, p;
128 strlcpy(msg, Cmd_Argv(1), sizeof(msg));
129 for(i = 2; i < c; ++i)
131 strlcat(msg, " ", sizeof(msg));
132 strlcat(msg, Cmd_Argv(i), sizeof(msg));
135 for(p = 0, i = 0; i < c; ++i)
141 else if(msg[i+1] == '\\')
153 SCR_CenterPrint(msg);
158 =============================================================================
162 =============================================================================
165 static sizebuf_t cmd_text;
166 static unsigned char cmd_text_buf[CMDBUFSIZE];
172 Adds command text at the end of the buffer
175 void Cbuf_AddText (const char *text)
179 l = (int)strlen (text);
181 if (cmd_text.cursize + l >= cmd_text.maxsize)
183 Con_Print("Cbuf_AddText: overflow\n");
187 SZ_Write (&cmd_text, (const unsigned char *)text, (int)strlen (text));
195 Adds command text immediately after the current command
196 Adds a \n to the text
197 FIXME: actually change the command buffer to do less copying
200 void Cbuf_InsertText (const char *text)
205 // copy off any commands still remaining in the exec buffer
206 templen = cmd_text.cursize;
209 temp = (char *)Mem_Alloc (tempmempool, templen);
210 memcpy (temp, cmd_text.data, templen);
211 SZ_Clear (&cmd_text);
216 // add the entire text of the file
219 // add the copied off data
222 SZ_Write (&cmd_text, (const unsigned char *)temp, templen);
229 Cbuf_Execute_Deferred --blub
232 void Cbuf_Execute_Deferred (void)
234 cmddeferred_t *cmd, *prev;
235 double time = Sys_DoubleTime();
237 cmd = cmd_deferred_list;
240 if(cmd->time <= time)
242 Cbuf_AddText(cmd->value);
243 Mem_Free(cmd->value);
246 prev->next = cmd->next;
248 cmd_deferred_list = cmd->next;
266 static void Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias );
267 void Cbuf_Execute (void)
271 char line[MAX_INPUTLINE];
272 char preprocessed[MAX_INPUTLINE];
276 // LordHavoc: making sure the tokenizebuffer doesn't get filled up by repeated crashes
277 cmd_tokenizebufferpos = 0;
279 Cbuf_Execute_Deferred();
280 while (cmd_text.cursize)
282 // find a \n or ; line break
283 text = (char *)cmd_text.data;
286 for (i=0 ; i< cmd_text.cursize ; i++)
290 // make sure i doesn't get > cursize which causes a negative
291 // size in memmove, which is fatal --blub
292 if (i < (cmd_text.cursize-1) && (text[i] == '\\' && (text[i+1] == '"' || text[i+1] == '\\')))
294 if ( !quotes && text[i] == ';')
295 break; // don't break if inside a quoted string
296 if (text[i] == '\r' || text[i] == '\n')
300 // better than CRASHING on overlong input lines that may SOMEHOW enter the buffer
301 if(i >= MAX_INPUTLINE)
303 Con_Printf("Warning: console input buffer had an overlong line. Ignored.\n");
308 memcpy (line, text, i);
312 // delete the text from the command buffer and move remaining commands down
313 // this is necessary because commands (exec, alias) can insert data at the
314 // beginning of the text buffer
316 if (i == cmd_text.cursize)
317 cmd_text.cursize = 0;
321 cmd_text.cursize -= i;
322 memmove (cmd_text.data, text+i, cmd_text.cursize);
325 // execute the command line
326 firstchar = line + strspn(line, " \t");
328 (strncmp(firstchar, "alias", 5) || (firstchar[5] != ' ' && firstchar[5] != '\t'))
330 (strncmp(firstchar, "bind", 4) || (firstchar[4] != ' ' && firstchar[4] != '\t'))
332 (strncmp(firstchar, "in_bind", 7) || (firstchar[7] != ' ' && firstchar[7] != '\t'))
335 Cmd_PreprocessString( line, preprocessed, sizeof(preprocessed), NULL );
336 Cmd_ExecuteString (preprocessed, src_command);
340 Cmd_ExecuteString (line, src_command);
344 { // skip out while text still remains in buffer, leaving it
353 ==============================================================================
357 ==============================================================================
364 Adds command line parameters as script statements
365 Commands lead with a +, and continue until a - or another +
366 quake +prog jctest.qp +cmd amlev1
367 quake -nosound +cmd amlev1
370 qboolean host_stuffcmdsrun = false;
371 void Cmd_StuffCmds_f (void)
374 // this is for all commandline options combined (and is bounds checked)
375 char build[MAX_INPUTLINE];
377 if (Cmd_Argc () != 1)
379 Con_Print("stuffcmds : execute command line parameters\n");
383 // no reason to run the commandline arguments twice
384 if (host_stuffcmdsrun)
387 host_stuffcmdsrun = true;
390 for (i = 0;i < com_argc;i++)
392 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)
395 while (com_argv[i][j])
396 build[l++] = com_argv[i][j++];
398 for (;i < com_argc;i++)
402 if ((com_argv[i][0] == '+' || com_argv[i][0] == '-') && (com_argv[i][1] < '0' || com_argv[i][1] > '9'))
404 if (l + strlen(com_argv[i]) + 4 > sizeof(build) - 1)
407 if (strchr(com_argv[i], ' '))
409 for (j = 0;com_argv[i][j];j++)
410 build[l++] = com_argv[i][j];
411 if (strchr(com_argv[i], ' '))
418 // now terminate the combined string and prepend it to the command buffer
419 // we already reserved space for the terminator
421 Cbuf_InsertText (build);
430 static void Cmd_Exec_f (void)
434 if (Cmd_Argc () != 2)
436 Con_Print("exec <filename> : execute a script file\n");
440 f = (char *)FS_LoadFile (Cmd_Argv(1), tempmempool, false, NULL);
443 Con_Printf("couldn't exec %s\n",Cmd_Argv(1));
446 Con_Printf("execing %s\n",Cmd_Argv(1));
448 // if executing default.cfg for the first time, lock the cvar defaults
449 // it may seem backwards to insert this text BEFORE the default.cfg
450 // but Cbuf_InsertText inserts before, so this actually ends up after it.
451 if (!strcmp(Cmd_Argv(1), "default.cfg"))
452 Cbuf_InsertText("\ncvar_lockdefaults\n");
454 // insert newline after the text to make sure the last line is terminated (some text editors omit the trailing newline)
455 // (note: insertion order here is backwards from execution order, so this adds it after the text, by calling it before...)
456 Cbuf_InsertText ("\n");
466 Just prints the rest of the line to the console
469 static void Cmd_Echo_f (void)
473 for (i=1 ; i<Cmd_Argc() ; i++)
474 Con_Printf("%s ",Cmd_Argv(i));
479 // Support Doom3-style Toggle Console Command
484 Toggles a specified console variable amongst the values specified (default is 0 and 1)
487 static void Cmd_Toggle_f(void)
489 // Acquire Number of Arguments
490 int nNumArgs = Cmd_Argc();
493 // No Arguments Specified; Print Usage
494 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");
496 { // Correct Arguments Specified
497 // Acquire Potential CVar
498 cvar_t* cvCVar = Cvar_FindVar( Cmd_Argv(1) );
505 Cvar_SetValueQuick(cvCVar, 0);
507 Cvar_SetValueQuick(cvCVar, 1);
511 { // 0 and Specified Usage
512 if(cvCVar->integer == atoi(Cmd_Argv(2) ) )
513 // CVar is Specified Value; // Reset to 0
514 Cvar_SetValueQuick(cvCVar, 0);
516 if(cvCVar->integer == 0)
517 // CVar is 0; Specify Value
518 Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
520 // CVar does not match; Reset to 0
521 Cvar_SetValueQuick(cvCVar, 0);
524 { // Variable Values Specified
528 for(nCnt = 2; nCnt < nNumArgs; nCnt++)
529 { // Cycle through Values
530 if( strcmp(cvCVar->string, Cmd_Argv(nCnt) ) == 0)
531 { // Current Value Located; Increment to Next
532 if( (nCnt + 1) == nNumArgs)
533 // Max Value Reached; Reset
534 Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
537 Cvar_SetQuick(cvCVar, Cmd_Argv(nCnt + 1) );
546 // Value not Found; Reset to Original
547 Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
553 Con_Printf("ERROR : CVar '%s' not found\n", Cmd_Argv(1) );
562 Creates a new command that executes a command string (possibly ; seperated)
565 static void Cmd_Alias_f (void)
568 char cmd[MAX_INPUTLINE];
575 Con_Print("Current alias commands:\n");
576 for (a = cmd_alias ; a ; a=a->next)
577 Con_Printf("%s : %s\n", a->name, a->value);
582 if (strlen(s) >= MAX_ALIAS_NAME)
584 Con_Print("Alias name is too long\n");
588 // if the alias already exists, reuse it
589 for (a = cmd_alias ; a ; a=a->next)
591 if (!strcmp(s, a->name))
600 cmdalias_t *prev, *current;
602 a = (cmdalias_t *)Z_Malloc (sizeof(cmdalias_t));
603 strlcpy (a->name, s, sizeof (a->name));
604 // insert it at the right alphanumeric position
605 for( prev = NULL, current = cmd_alias ; current && strcmp( current->name, a->name ) < 0 ; prev = current, current = current->next )
616 // copy the rest of the command line
617 cmd[0] = 0; // start out with a null string
619 for (i=2 ; i< c ; i++)
621 strlcat (cmd, Cmd_Argv(i), sizeof (cmd));
623 strlcat (cmd, " ", sizeof (cmd));
625 strlcat (cmd, "\n", sizeof (cmd));
627 alloclen = strlen (cmd) + 1;
628 a->value = (char *)Z_Malloc (alloclen);
629 memcpy (a->value, cmd, alloclen);
633 =============================================================================
637 =============================================================================
640 typedef struct cmd_function_s
642 struct cmd_function_s *next;
644 const char *description;
645 xcommand_t consolefunction;
646 xcommand_t clientfunction;
651 static const char *cmd_argv[MAX_ARGS];
652 static const char *cmd_null_string = "";
653 static const char *cmd_args;
654 cmd_source_t cmd_source;
657 static cmd_function_t *cmd_functions; // possible commands to execute
659 static const char *Cmd_GetDirectCvarValue(const char *varname, cmdalias_t *alias, qboolean *is_multiple)
666 *is_multiple = false;
668 if(!varname || !*varname)
673 if(!strcmp(varname, "*"))
679 else if(varname[strlen(varname) - 1] == '-')
681 argno = strtol(varname, &endptr, 10);
682 if(endptr == varname + strlen(varname) - 1)
684 // whole string is a number, apart from the -
685 const char *p = Cmd_Args();
686 for(; argno > 1; --argno)
687 if(!COM_ParseToken_Console(&p))
694 // kill pre-argument whitespace
695 for (;*p && *p <= ' ';p++)
704 argno = strtol(varname, &endptr, 10);
707 // whole string is a number
708 // NOTE: we already made sure we don't have an empty cvar name!
709 if(argno >= 0 && argno < Cmd_Argc())
710 return Cmd_Argv(argno);
715 if((cvar = Cvar_FindVar(varname)) && !(cvar->flags & CVAR_PRIVATE))
721 qboolean Cmd_QuoteString(char *out, size_t outlen, const char *in, const char *quoteset)
723 qboolean quote_quot = !!strchr(quoteset, '"');
724 qboolean quote_backslash = !!strchr(quoteset, '\\');
725 qboolean quote_dollar = !!strchr(quoteset, '$');
729 if(*in == '"' && quote_quot)
736 *out++ = '\\'; --outlen;
737 *out++ = '"'; --outlen;
739 else if(*in == '\\' && quote_backslash)
746 *out++ = '\\'; --outlen;
747 *out++ = '\\'; --outlen;
749 else if(*in == '$' && quote_dollar)
756 *out++ = '$'; --outlen;
757 *out++ = '$'; --outlen;
766 *out++ = *in; --outlen;
774 static const char *Cmd_GetCvarValue(const char *var, size_t varlen, cmdalias_t *alias)
776 static char varname[MAX_INPUTLINE];
777 static char varval[MAX_INPUTLINE];
781 if(varlen >= MAX_INPUTLINE)
782 varlen = MAX_INPUTLINE - 1;
783 memcpy(varname, var, varlen);
785 varfunc = strchr(varname, ' ');
801 if(varname[0] == '$')
802 varstr = Cmd_GetDirectCvarValue(Cmd_GetDirectCvarValue(varname + 1, alias, NULL), alias, NULL);
805 qboolean is_multiple = false;
806 // Exception: $* and $n- don't use the quoted form by default
807 varstr = Cmd_GetDirectCvarValue(varname, alias, &is_multiple);
815 Con_Printf("Warning: Could not expand $%s in alias %s\n", varname, alias->name);
817 Con_Printf("Warning: Could not expand $%s\n", varname);
821 if(!varfunc || !strcmp(varfunc, "q")) // note: quoted form is default, use "asis" to override!
823 // quote it so it can be used inside double quotes
824 // we just need to replace " by \", and of course, double backslashes
825 Cmd_QuoteString(varval, sizeof(varval), varstr, "\"\\");
828 else if(!strcmp(varfunc, "asis"))
833 Con_Printf("Unknown variable function %s\n", varfunc);
841 Preprocesses strings and replaces $*, $param#, $cvar accordingly
843 static void Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias ) {
849 // don't crash if there's no room in the outtext buffer
850 if( maxoutlen == 0 ) {
853 maxoutlen--; // because of \0
858 while( *in && outlen < maxoutlen ) {
860 // this is some kind of expansion, see what comes after the $
863 // The console does the following preprocessing:
865 // - $$ is transformed to a single dollar sign.
866 // - $var or ${var} are expanded to the contents of the named cvar,
867 // with quotation marks and backslashes quoted so it can safely
868 // be used inside quotation marks (and it should always be used
870 // - ${var asis} inserts the cvar value as is, without doing this
872 // - prefix the cvar name with a dollar sign to do indirection;
873 // for example, if $x has the value timelimit, ${$x} will return
874 // the value of $timelimit
875 // - when expanding an alias, the special variable name $* refers
876 // to all alias parameters, and a number refers to that numbered
877 // alias parameter, where the name of the alias is $0, the first
878 // parameter is $1 and so on; as a special case, $* inserts all
879 // parameters, without extra quoting, so one can use $* to just
880 // pass all parameters around. All parameters starting from $n
881 // can be referred to as $n- (so $* is equivalent to $1-).
883 // Note: when expanding an alias, cvar expansion is done in the SAME step
884 // as alias expansion so that alias parameters or cvar values containing
885 // dollar signs have no unwanted bad side effects. However, this needs to
886 // be accounted for when writing complex aliases. For example,
887 // alias foo "set x NEW; echo $x"
888 // actually expands to
889 // "set x NEW; echo OLD"
890 // and will print OLD! To work around this, use a second alias:
891 // alias foo "set x NEW; foo2"
892 // alias foo2 "echo $x"
894 // Also note: lines starting with alias are exempt from cvar expansion.
895 // If you want cvar expansion, write "alias" instead:
898 // alias foo "echo $x"
899 // "alias" bar "echo $x"
902 // foo will print 2, because the variable $x will be expanded when the alias
903 // gets expanded. bar will print 1, because the variable $x was expanded
904 // at definition time. foo can be equivalently defined as
906 // "alias" foo "echo $$x"
908 // because at definition time, $$ will get replaced to a single $.
913 } else if(*in == '{') {
914 varlen = strcspn(in + 1, "}");
915 if(in[varlen + 1] == '}')
917 val = Cmd_GetCvarValue(in + 1, varlen, alias);
927 varlen = strspn(in, "*0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-");
928 val = Cmd_GetCvarValue(in, varlen, alias);
933 // insert the cvar value
934 while(*val && outlen < maxoutlen)
935 outtext[outlen++] = *val++;
940 // copy the unexpanded text
941 outtext[outlen++] = '$';
942 while(eat && outlen < maxoutlen)
944 outtext[outlen++] = *in++;
949 outtext[outlen++] = *in++;
959 Called for aliases and fills in the alias into the cbuffer
962 static void Cmd_ExecuteAlias (cmdalias_t *alias)
964 static char buffer[ MAX_INPUTLINE ];
965 static char buffer2[ MAX_INPUTLINE ];
966 Cmd_PreprocessString( alias->value, buffer, sizeof(buffer) - 2, alias );
967 // insert at start of command buffer, so that aliases execute in order
968 // (fixes bug introduced by Black on 20050705)
970 // Note: Cbuf_PreprocessString will be called on this string AGAIN! So we
971 // have to make sure that no second variable expansion takes place, otherwise
972 // alias parameters containing dollar signs can have bad effects.
973 Cmd_QuoteString(buffer2, sizeof(buffer2), buffer, "$");
974 Cbuf_InsertText( buffer2 );
981 CmdList Added by EvilTypeGuy eviltypeguy@qeradiant.com
982 Thanks to Matthias "Maddes" Buecher, http://www.inside3d.com/qip/
986 static void Cmd_List_f (void)
994 partial = Cmd_Argv (1);
995 len = (int)strlen(partial);
1004 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1006 if (partial && strncmp(partial, cmd->name, len))
1008 Con_Printf("%s : %s\n", cmd->name, cmd->description);
1013 Con_Printf("%i Command%s beginning with \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1015 Con_Printf("%i Command%s\n\n", count, (count > 1) ? "s" : "");
1023 void Cmd_Init (void)
1025 cmd_mempool = Mem_AllocPool("commands", 0, NULL);
1026 // space for commands and script files
1027 cmd_text.data = cmd_text_buf;
1028 cmd_text.maxsize = sizeof(cmd_text_buf);
1029 cmd_text.cursize = 0;
1032 void Cmd_Init_Commands (void)
1035 // register our commands
1037 Cmd_AddCommand ("stuffcmds",Cmd_StuffCmds_f, "execute commandline parameters (must be present in quake.rc script)");
1038 Cmd_AddCommand ("exec",Cmd_Exec_f, "execute a script file");
1039 Cmd_AddCommand ("echo",Cmd_Echo_f, "print a message to the console (useful in scripts)");
1040 Cmd_AddCommand ("alias",Cmd_Alias_f, "create a script function (parameters are passed in as $1 through $9, and $* for all parameters)");
1041 Cmd_AddCommand ("cmd", Cmd_ForwardToServer, "send a console commandline to the server (used by some mods)");
1042 Cmd_AddCommand ("wait", Cmd_Wait_f, "make script execution wait for next rendered frame");
1043 Cmd_AddCommand ("set", Cvar_Set_f, "create or change the value of a console variable");
1044 Cmd_AddCommand ("seta", Cvar_SetA_f, "create or change the value of a console variable that will be saved to config.cfg");
1046 // 2000-01-09 CmdList, CvarList commands By Matthias "Maddes" Buecher
1047 // Added/Modified by EvilTypeGuy eviltypeguy@qeradiant.com
1048 Cmd_AddCommand ("cmdlist", Cmd_List_f, "lists all console commands beginning with the specified prefix");
1049 Cmd_AddCommand ("cvarlist", Cvar_List_f, "lists all console variables beginning with the specified prefix");
1051 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");
1052 Cmd_AddCommand ("cvar_resettodefaults_all", Cvar_ResetToDefaults_All_f, "sets all cvars to their locked default values");
1053 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)");
1054 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)");
1056 Cmd_AddCommand ("cprint", Cmd_Centerprint_f, "print something at the screen center");
1057 Cmd_AddCommand ("defer", Cmd_Defer_f, "execute a command in the future");
1060 // Support Doom3-style Toggle Command
1061 Cmd_AddCommand( "toggle", Cmd_Toggle_f, "toggles a console variable's values (use for more info)");
1069 void Cmd_Shutdown(void)
1071 Mem_FreePool(&cmd_mempool);
1089 const char *Cmd_Argv (int arg)
1091 if (arg >= cmd_argc )
1092 return cmd_null_string;
1093 return cmd_argv[arg];
1101 const char *Cmd_Args (void)
1111 Parses the given string into command line tokens.
1114 // AK: This function should only be called from ExcuteString because the current design is a bit of an hack
1115 static void Cmd_TokenizeString (const char *text)
1124 // skip whitespace up to a /n
1125 while (*text && *text <= ' ' && *text != '\r' && *text != '\n')
1132 if (*text == '\n' || *text == '\r')
1134 // a newline separates commands in the buffer
1135 if (*text == '\r' && text[1] == '\n')
1147 if (!COM_ParseToken_Console(&text))
1150 if (cmd_argc < MAX_ARGS)
1152 l = (int)strlen(com_token) + 1;
1153 if (cmd_tokenizebufferpos + l > CMD_TOKENIZELENGTH)
1155 Con_Printf("Cmd_TokenizeString: ran out of %i character buffer space for command arguements\n", CMD_TOKENIZELENGTH);
1158 memcpy (cmd_tokenizebuffer + cmd_tokenizebufferpos, com_token, l);
1159 cmd_argv[cmd_argc] = cmd_tokenizebuffer + cmd_tokenizebufferpos;
1160 cmd_tokenizebufferpos += l;
1172 void Cmd_AddCommand_WithClientCommand (const char *cmd_name, xcommand_t consolefunction, xcommand_t clientfunction, const char *description)
1174 cmd_function_t *cmd;
1175 cmd_function_t *prev, *current;
1177 // fail if the command is a variable name
1178 if (Cvar_FindVar( cmd_name ))
1180 Con_Printf("Cmd_AddCommand: %s already defined as a var\n", cmd_name);
1184 // fail if the command already exists
1185 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1187 if (!strcmp (cmd_name, cmd->name))
1189 if (consolefunction || clientfunction)
1191 Con_Printf("Cmd_AddCommand: %s already defined\n", cmd_name);
1196 cmd->csqcfunc = true;
1202 cmd = (cmd_function_t *)Mem_Alloc(cmd_mempool, sizeof(cmd_function_t));
1203 cmd->name = cmd_name;
1204 cmd->consolefunction = consolefunction;
1205 cmd->clientfunction = clientfunction;
1206 cmd->description = description;
1207 if(!consolefunction && !clientfunction) //[515]: csqc
1208 cmd->csqcfunc = true;
1209 cmd->next = cmd_functions;
1211 // insert it at the right alphanumeric position
1212 for( prev = NULL, current = cmd_functions ; current && strcmp( current->name, cmd->name ) < 0 ; prev = current, current = current->next )
1217 cmd_functions = cmd;
1219 cmd->next = current;
1222 void Cmd_AddCommand (const char *cmd_name, xcommand_t function, const char *description)
1224 Cmd_AddCommand_WithClientCommand (cmd_name, function, NULL, description);
1232 qboolean Cmd_Exists (const char *cmd_name)
1234 cmd_function_t *cmd;
1236 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1237 if (!strcmp (cmd_name,cmd->name))
1249 const char *Cmd_CompleteCommand (const char *partial)
1251 cmd_function_t *cmd;
1254 len = strlen(partial);
1260 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1261 if (!strncasecmp(partial, cmd->name, len))
1268 Cmd_CompleteCountPossible
1270 New function for tab-completion system
1271 Added by EvilTypeGuy
1272 Thanks to Fett erich@heintz.com
1276 int Cmd_CompleteCountPossible (const char *partial)
1278 cmd_function_t *cmd;
1283 len = strlen(partial);
1288 // Loop through the command list and count all partial matches
1289 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1290 if (!strncasecmp(partial, cmd->name, len))
1297 Cmd_CompleteBuildList
1299 New function for tab-completion system
1300 Added by EvilTypeGuy
1301 Thanks to Fett erich@heintz.com
1305 const char **Cmd_CompleteBuildList (const char *partial)
1307 cmd_function_t *cmd;
1310 size_t sizeofbuf = (Cmd_CompleteCountPossible (partial) + 1) * sizeof (const char *);
1313 len = strlen(partial);
1314 buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1315 // Loop through the alias list and print all matches
1316 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1317 if (!strncasecmp(partial, cmd->name, len))
1318 buf[bpos++] = cmd->name;
1324 // written by LordHavoc
1325 void Cmd_CompleteCommandPrint (const char *partial)
1327 cmd_function_t *cmd;
1328 size_t len = strlen(partial);
1329 // Loop through the command list and print all matches
1330 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1331 if (!strncasecmp(partial, cmd->name, len))
1332 Con_Printf("%s : %s\n", cmd->name, cmd->description);
1338 New function for tab-completion system
1339 Added by EvilTypeGuy
1340 Thanks to Fett erich@heintz.com
1344 const char *Cmd_CompleteAlias (const char *partial)
1349 len = strlen(partial);
1355 for (alias = cmd_alias; alias; alias = alias->next)
1356 if (!strncasecmp(partial, alias->name, len))
1362 // written by LordHavoc
1363 void Cmd_CompleteAliasPrint (const char *partial)
1366 size_t len = strlen(partial);
1367 // Loop through the alias list and print all matches
1368 for (alias = cmd_alias; alias; alias = alias->next)
1369 if (!strncasecmp(partial, alias->name, len))
1370 Con_Printf("%s : %s\n", alias->name, alias->value);
1375 Cmd_CompleteAliasCountPossible
1377 New function for tab-completion system
1378 Added by EvilTypeGuy
1379 Thanks to Fett erich@heintz.com
1383 int Cmd_CompleteAliasCountPossible (const char *partial)
1391 len = strlen(partial);
1396 // Loop through the command list and count all partial matches
1397 for (alias = cmd_alias; alias; alias = alias->next)
1398 if (!strncasecmp(partial, alias->name, len))
1405 Cmd_CompleteAliasBuildList
1407 New function for tab-completion system
1408 Added by EvilTypeGuy
1409 Thanks to Fett erich@heintz.com
1413 const char **Cmd_CompleteAliasBuildList (const char *partial)
1418 size_t sizeofbuf = (Cmd_CompleteAliasCountPossible (partial) + 1) * sizeof (const char *);
1421 len = strlen(partial);
1422 buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1423 // Loop through the alias list and print all matches
1424 for (alias = cmd_alias; alias; alias = alias->next)
1425 if (!strncasecmp(partial, alias->name, len))
1426 buf[bpos++] = alias->name;
1432 void Cmd_ClearCsqcFuncs (void)
1434 cmd_function_t *cmd;
1435 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1436 cmd->csqcfunc = false;
1439 qboolean CL_VM_ConsoleCommand (const char *cmd);
1444 A complete command line has been parsed, so try to execute it
1445 FIXME: lookupnoadd the token to speed search?
1448 void Cmd_ExecuteString (const char *text, cmd_source_t src)
1451 cmd_function_t *cmd;
1454 oldpos = cmd_tokenizebufferpos;
1457 Cmd_TokenizeString (text);
1459 // execute the command line
1462 cmd_tokenizebufferpos = oldpos;
1463 return; // no tokens
1467 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1469 if (!strcasecmp (cmd_argv[0],cmd->name))
1471 if (cmd->csqcfunc && CL_VM_ConsoleCommand (text)) //[515]: csqc
1476 if (cmd->consolefunction)
1477 cmd->consolefunction ();
1478 else if (cmd->clientfunction)
1480 if (cls.state == ca_connected)
1482 // forward remote commands to the server for execution
1483 Cmd_ForwardToServer();
1486 Con_Printf("Can not send command \"%s\", not connected.\n", Cmd_Argv(0));
1489 Con_Printf("Command \"%s\" can not be executed\n", Cmd_Argv(0));
1490 cmd_tokenizebufferpos = oldpos;
1493 if (cmd->clientfunction)
1495 cmd->clientfunction ();
1496 cmd_tokenizebufferpos = oldpos;
1505 // if it's a client command and no command was found, say so.
1506 if (cmd_source == src_client)
1508 Con_Printf("player \"%s\" tried to %s\n", host_client->name, text);
1513 for (a=cmd_alias ; a ; a=a->next)
1515 if (!strcasecmp (cmd_argv[0], a->name))
1517 Cmd_ExecuteAlias(a);
1518 cmd_tokenizebufferpos = oldpos;
1524 if (!Cvar_Command () && host_framecount > 0)
1525 Con_Printf("Unknown command \"%s\"\n", Cmd_Argv(0));
1527 cmd_tokenizebufferpos = oldpos;
1533 Cmd_ForwardStringToServer
1535 Sends an entire command string over to the server, unprocessed
1538 void Cmd_ForwardStringToServer (const char *s)
1541 if (cls.state != ca_connected)
1543 Con_Printf("Can't \"%s\", not connected\n", s);
1550 // LordHavoc: thanks to Fuh for bringing the pure evil of SZ_Print to my
1551 // attention, it has been eradicated from here, its only (former) use in
1552 // all of darkplaces.
1553 if (cls.protocol == PROTOCOL_QUAKEWORLD)
1554 MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
1556 MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
1557 if ((!strncmp(s, "say ", 4) || !strncmp(s, "say_team ", 9)) && cl_locs_enable.integer)
1559 // say/say_team commands can replace % character codes with status info
1562 if (*s == '%' && s[1])
1564 // handle proquake message macros
1568 case 'l': // current location
1569 CL_Locs_FindLocationName(temp, sizeof(temp), cl.movement_origin);
1571 case 'h': // current health
1572 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_HEALTH]);
1574 case 'a': // current armor
1575 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ARMOR]);
1577 case 'x': // current rockets
1578 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ROCKETS]);
1580 case 'c': // current cells
1581 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_CELLS]);
1583 // silly proquake macros
1584 case 'd': // loc at last death
1585 CL_Locs_FindLocationName(temp, sizeof(temp), cl.lastdeathorigin);
1587 case 't': // current time
1588 dpsnprintf(temp, sizeof(temp), "%.0f:%.0f", floor(cl.time / 60), cl.time - floor(cl.time / 60) * 60);
1590 case 'r': // rocket launcher status ("I have RL", "I need rockets", "I need RL")
1591 if (!(cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER))
1592 dpsnprintf(temp, sizeof(temp), "I need RL");
1593 else if (!cl.stats[STAT_ROCKETS])
1594 dpsnprintf(temp, sizeof(temp), "I need rockets");
1596 dpsnprintf(temp, sizeof(temp), "I have RL");
1598 case 'p': // powerup status (outputs "quad" "pent" and "eyes" according to status)
1599 if (cl.stats[STAT_ITEMS] & IT_QUAD)
1602 strlcat(temp, " ", sizeof(temp));
1603 strlcat(temp, "quad", sizeof(temp));
1605 if (cl.stats[STAT_ITEMS] & IT_INVULNERABILITY)
1608 strlcat(temp, " ", sizeof(temp));
1609 strlcat(temp, "pent", sizeof(temp));
1611 if (cl.stats[STAT_ITEMS] & IT_INVISIBILITY)
1614 strlcat(temp, " ", sizeof(temp));
1615 strlcat(temp, "eyes", sizeof(temp));
1618 case 'w': // weapon status (outputs "SSG:NG:SNG:GL:RL:LG" with the text between : characters omitted if you lack the weapon)
1619 if (cl.stats[STAT_ITEMS] & IT_SUPER_SHOTGUN)
1620 strlcat(temp, "SSG", sizeof(temp));
1621 strlcat(temp, ":", sizeof(temp));
1622 if (cl.stats[STAT_ITEMS] & IT_NAILGUN)
1623 strlcat(temp, "NG", sizeof(temp));
1624 strlcat(temp, ":", sizeof(temp));
1625 if (cl.stats[STAT_ITEMS] & IT_SUPER_NAILGUN)
1626 strlcat(temp, "SNG", sizeof(temp));
1627 strlcat(temp, ":", sizeof(temp));
1628 if (cl.stats[STAT_ITEMS] & IT_GRENADE_LAUNCHER)
1629 strlcat(temp, "GL", sizeof(temp));
1630 strlcat(temp, ":", sizeof(temp));
1631 if (cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER)
1632 strlcat(temp, "RL", sizeof(temp));
1633 strlcat(temp, ":", sizeof(temp));
1634 if (cl.stats[STAT_ITEMS] & IT_LIGHTNING)
1635 strlcat(temp, "LG", sizeof(temp));
1638 // not a recognized macro, print it as-is...
1644 // write the resulting text
1645 SZ_Write(&cls.netcon->message, (unsigned char *)temp, strlen(temp));
1649 MSG_WriteByte(&cls.netcon->message, *s);
1652 MSG_WriteByte(&cls.netcon->message, 0);
1654 else // any other command is passed on as-is
1655 SZ_Write(&cls.netcon->message, (const unsigned char *)s, (int)strlen(s) + 1);
1662 Sends the entire command line over to the server
1665 void Cmd_ForwardToServer (void)
1668 if (!strcasecmp(Cmd_Argv(0), "cmd"))
1670 // we want to strip off "cmd", so just send the args
1671 s = Cmd_Argc() > 1 ? Cmd_Args() : "";
1675 // we need to keep the command name, so send Cmd_Argv(0), a space and then Cmd_Args()
1676 s = va("%s %s", Cmd_Argv(0), Cmd_Argc() > 1 ? Cmd_Args() : "");
1678 // don't send an empty forward message if the user tries "cmd" by itself
1681 Cmd_ForwardStringToServer(s);
1689 Returns the position (1 to argc-1) in the command's argument list
1690 where the given parameter apears, or 0 if not present
1694 int Cmd_CheckParm (const char *parm)
1700 Con_Printf ("Cmd_CheckParm: NULL");
1704 for (i = 1; i < Cmd_Argc (); i++)
1705 if (!strcasecmp (parm, Cmd_Argv (i)))