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 typedef struct cmdalias_s
26 struct cmdalias_s *next;
27 char name[MAX_ALIAS_NAME];
31 static cmdalias_t *cmd_alias;
33 static qboolean cmd_wait;
35 static mempool_t *cmd_mempool;
37 static char cmd_tokenizebuffer[CMD_TOKENIZELENGTH];
38 static int cmd_tokenizebufferpos = 0;
40 //=============================================================================
46 Causes execution of the remainder of the command buffer to be delayed until
47 next frame. This allows commands like:
48 bind g "impulse 5 ; +attack ; wait ; -attack ; impulse 2"
51 static void Cmd_Wait_f (void)
56 typedef struct cmddeferred_s
58 struct cmddeferred_s *next;
63 static cmddeferred_t *cmd_deferred_list = NULL;
69 Cause a command to be executed after a delay.
72 static void Cmd_Defer_f (void)
76 double time = Sys_DoubleTime();
77 cmddeferred_t *next = cmd_deferred_list;
79 Con_Printf("No commands are pending.\n");
82 Con_Printf("-> In %9.2f: %s\n", next->time-time, next->value);
85 } else if(Cmd_Argc() == 2 && !strcasecmp("clear", Cmd_Argv(1)))
87 while(cmd_deferred_list)
89 cmddeferred_t *cmd = cmd_deferred_list;
90 cmd_deferred_list = cmd->next;
94 } else if(Cmd_Argc() == 3)
96 const char *value = Cmd_Argv(2);
97 cmddeferred_t *defcmd = (cmddeferred_t*)Mem_Alloc(tempmempool, sizeof(*defcmd));
98 size_t len = strlen(value);
100 defcmd->time = Sys_DoubleTime() + atof(Cmd_Argv(1));
101 defcmd->value = (char*)Mem_Alloc(tempmempool, len+1);
102 memcpy(defcmd->value, value, len+1);
105 if(cmd_deferred_list)
107 cmddeferred_t *next = cmd_deferred_list;
112 cmd_deferred_list = defcmd;
113 /* Stupid me... this changes the order... so commands with the same delay go blub :S
114 defcmd->next = cmd_deferred_list;
115 cmd_deferred_list = defcmd;*/
117 Con_Printf("usage: defer <seconds> <command>\n"
127 Print something to the center of the screen using SCR_Centerprint
130 static void Cmd_Centerprint_f (void)
132 char msg[MAX_INPUTLINE];
133 unsigned int i, c, p;
137 strlcpy(msg, Cmd_Argv(1), sizeof(msg));
138 for(i = 2; i < c; ++i)
140 strlcat(msg, " ", sizeof(msg));
141 strlcat(msg, Cmd_Argv(i), sizeof(msg));
144 for(p = 0, i = 0; i < c; ++i)
150 else if(msg[i+1] == '\\')
162 SCR_CenterPrint(msg);
167 =============================================================================
171 =============================================================================
174 static sizebuf_t cmd_text;
175 static unsigned char cmd_text_buf[CMDBUFSIZE];
181 Adds command text at the end of the buffer
184 void Cbuf_AddText (const char *text)
188 l = (int)strlen (text);
190 if (cmd_text.cursize + l >= cmd_text.maxsize)
192 Con_Print("Cbuf_AddText: overflow\n");
196 SZ_Write (&cmd_text, (const unsigned char *)text, (int)strlen (text));
204 Adds command text immediately after the current command
205 Adds a \n to the text
206 FIXME: actually change the command buffer to do less copying
209 void Cbuf_InsertText (const char *text)
214 // copy off any commands still remaining in the exec buffer
215 templen = cmd_text.cursize;
218 temp = (char *)Mem_Alloc (tempmempool, templen);
219 memcpy (temp, cmd_text.data, templen);
220 SZ_Clear (&cmd_text);
225 // add the entire text of the file
228 // add the copied off data
231 SZ_Write (&cmd_text, (const unsigned char *)temp, templen);
238 Cbuf_Execute_Deferred --blub
241 void Cbuf_Execute_Deferred (void)
243 cmddeferred_t *cmd, *prev;
244 double time = Sys_DoubleTime();
246 cmd = cmd_deferred_list;
249 if(cmd->time <= time)
251 Cbuf_AddText(cmd->value);
253 Mem_Free(cmd->value);
256 prev->next = cmd->next;
260 cmd_deferred_list = cmd->next;
262 cmd = cmd_deferred_list;
276 static void Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias );
277 void Cbuf_Execute (void)
281 char line[MAX_INPUTLINE];
282 char preprocessed[MAX_INPUTLINE];
287 // LordHavoc: making sure the tokenizebuffer doesn't get filled up by repeated crashes
288 cmd_tokenizebufferpos = 0;
290 Cbuf_Execute_Deferred();
291 while (cmd_text.cursize)
293 // find a \n or ; line break
294 text = (char *)cmd_text.data;
298 for (i=0 ; i < cmd_text.cursize ; i++)
307 // make sure i doesn't get > cursize which causes a negative
308 // size in memmove, which is fatal --blub
309 if (i < (cmd_text.cursize-1) && (text[i] == '\\' && (text[i+1] == '"' || text[i+1] == '\\')))
314 if(text[i] == '/' && text[i + 1] == '/' && (i == 0 || ISWHITESPACE(text[i-1])))
317 break; // don't break if inside a quoted string or comment
321 if (text[i] == '\r' || text[i] == '\n')
325 // better than CRASHING on overlong input lines that may SOMEHOW enter the buffer
326 if(i >= MAX_INPUTLINE)
328 Con_Printf("Warning: console input buffer had an overlong line. Ignored.\n");
333 memcpy (line, text, comment ? (comment - text) : i);
334 line[comment ? (comment - text) : i] = 0;
337 // delete the text from the command buffer and move remaining commands down
338 // this is necessary because commands (exec, alias) can insert data at the
339 // beginning of the text buffer
341 if (i == cmd_text.cursize)
342 cmd_text.cursize = 0;
346 cmd_text.cursize -= i;
347 memmove (cmd_text.data, text+i, cmd_text.cursize);
350 // execute the command line
352 while(*firstchar && ISWHITESPACE(*firstchar))
355 (strncmp(firstchar, "alias", 5) || !ISWHITESPACE(firstchar[5]))
357 (strncmp(firstchar, "bind", 4) || !ISWHITESPACE(firstchar[4]))
359 (strncmp(firstchar, "in_bind", 7) || !ISWHITESPACE(firstchar[7]))
362 Cmd_PreprocessString( line, preprocessed, sizeof(preprocessed), NULL );
363 Cmd_ExecuteString (preprocessed, src_command);
367 Cmd_ExecuteString (line, src_command);
371 { // skip out while text still remains in buffer, leaving it
380 ==============================================================================
384 ==============================================================================
391 Adds command line parameters as script statements
392 Commands lead with a +, and continue until a - or another +
393 quake +prog jctest.qp +cmd amlev1
394 quake -nosound +cmd amlev1
397 qboolean host_stuffcmdsrun = false;
398 void Cmd_StuffCmds_f (void)
401 // this is for all commandline options combined (and is bounds checked)
402 char build[MAX_INPUTLINE];
404 if (Cmd_Argc () != 1)
406 Con_Print("stuffcmds : execute command line parameters\n");
410 // no reason to run the commandline arguments twice
411 if (host_stuffcmdsrun)
414 host_stuffcmdsrun = true;
417 for (i = 0;i < com_argc;i++)
419 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)
422 while (com_argv[i][j])
423 build[l++] = com_argv[i][j++];
425 for (;i < com_argc;i++)
429 if ((com_argv[i][0] == '+' || com_argv[i][0] == '-') && (com_argv[i][1] < '0' || com_argv[i][1] > '9'))
431 if (l + strlen(com_argv[i]) + 4 > sizeof(build) - 1)
434 if (strchr(com_argv[i], ' '))
436 for (j = 0;com_argv[i][j];j++)
437 build[l++] = com_argv[i][j];
438 if (strchr(com_argv[i], ' '))
445 // now terminate the combined string and prepend it to the command buffer
446 // we already reserved space for the terminator
448 Cbuf_InsertText (build);
457 static void Cmd_Exec_f (void)
460 const char *filename;
462 if (Cmd_Argc () != 2)
464 Con_Print("exec <filename> : execute a script file\n");
468 filename = Cmd_Argv(1);
469 if (!strcmp(filename, "config.cfg"))
471 filename = CONFIGFILENAME;
472 if (COM_CheckParm("-noconfig"))
473 return; // don't execute config.cfg
476 f = (char *)FS_LoadFile (filename, tempmempool, false, NULL);
479 Con_Printf("couldn't exec %s\n",filename);
482 Con_Printf("execing %s\n",filename);
484 // if executing default.cfg for the first time, lock the cvar defaults
485 // it may seem backwards to insert this text BEFORE the default.cfg
486 // but Cbuf_InsertText inserts before, so this actually ends up after it.
487 if (strlen(filename) >= 11 && !strcmp(filename + strlen(filename) - 11, "default.cfg"))
488 Cbuf_InsertText("\ncvar_lockdefaults\n");
490 // insert newline after the text to make sure the last line is terminated (some text editors omit the trailing newline)
491 // (note: insertion order here is backwards from execution order, so this adds it after the text, by calling it before...)
492 Cbuf_InsertText ("\n");
502 Just prints the rest of the line to the console
505 static void Cmd_Echo_f (void)
509 for (i=1 ; i<Cmd_Argc() ; i++)
510 Con_Printf("%s ",Cmd_Argv(i));
515 // Support Doom3-style Toggle Console Command
520 Toggles a specified console variable amongst the values specified (default is 0 and 1)
523 static void Cmd_Toggle_f(void)
525 // Acquire Number of Arguments
526 int nNumArgs = Cmd_Argc();
529 // No Arguments Specified; Print Usage
530 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");
532 { // Correct Arguments Specified
533 // Acquire Potential CVar
534 cvar_t* cvCVar = Cvar_FindVar( Cmd_Argv(1) );
541 Cvar_SetValueQuick(cvCVar, 0);
543 Cvar_SetValueQuick(cvCVar, 1);
547 { // 0 and Specified Usage
548 if(cvCVar->integer == atoi(Cmd_Argv(2) ) )
549 // CVar is Specified Value; // Reset to 0
550 Cvar_SetValueQuick(cvCVar, 0);
552 if(cvCVar->integer == 0)
553 // CVar is 0; Specify Value
554 Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
556 // CVar does not match; Reset to 0
557 Cvar_SetValueQuick(cvCVar, 0);
560 { // Variable Values Specified
564 for(nCnt = 2; nCnt < nNumArgs; nCnt++)
565 { // Cycle through Values
566 if( strcmp(cvCVar->string, Cmd_Argv(nCnt) ) == 0)
567 { // Current Value Located; Increment to Next
568 if( (nCnt + 1) == nNumArgs)
569 // Max Value Reached; Reset
570 Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
573 Cvar_SetQuick(cvCVar, Cmd_Argv(nCnt + 1) );
582 // Value not Found; Reset to Original
583 Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
589 Con_Printf("ERROR : CVar '%s' not found\n", Cmd_Argv(1) );
598 Creates a new command that executes a command string (possibly ; seperated)
601 static void Cmd_Alias_f (void)
604 char cmd[MAX_INPUTLINE];
611 Con_Print("Current alias commands:\n");
612 for (a = cmd_alias ; a ; a=a->next)
613 Con_Printf("%s : %s", a->name, a->value);
618 if (strlen(s) >= MAX_ALIAS_NAME)
620 Con_Print("Alias name is too long\n");
624 // if the alias already exists, reuse it
625 for (a = cmd_alias ; a ; a=a->next)
627 if (!strcmp(s, a->name))
636 cmdalias_t *prev, *current;
638 a = (cmdalias_t *)Z_Malloc (sizeof(cmdalias_t));
639 strlcpy (a->name, s, sizeof (a->name));
640 // insert it at the right alphanumeric position
641 for( prev = NULL, current = cmd_alias ; current && strcmp( current->name, a->name ) < 0 ; prev = current, current = current->next )
652 // copy the rest of the command line
653 cmd[0] = 0; // start out with a null string
655 for (i=2 ; i < c ; i++)
658 strlcat (cmd, " ", sizeof (cmd));
659 strlcat (cmd, Cmd_Argv(i), sizeof (cmd));
661 strlcat (cmd, "\n", sizeof (cmd));
663 alloclen = strlen (cmd) + 1;
665 cmd[alloclen - 2] = '\n'; // to make sure a newline is appended even if too long
666 a->value = (char *)Z_Malloc (alloclen);
667 memcpy (a->value, cmd, alloclen);
674 Remove existing aliases.
677 static void Cmd_UnAlias_f (void)
685 Con_Print("unalias: Usage: unalias alias1 [alias2 ...]\n");
689 for(i = 1; i < Cmd_Argc(); ++i)
693 for(a = cmd_alias; a; p = a, a = a->next)
695 if(!strcmp(s, a->name))
707 Con_Printf("unalias: %s alias not found\n", s);
712 =============================================================================
716 =============================================================================
719 typedef struct cmd_function_s
721 struct cmd_function_s *next;
723 const char *description;
724 xcommand_t consolefunction;
725 xcommand_t clientfunction;
730 static const char *cmd_argv[MAX_ARGS];
731 static const char *cmd_null_string = "";
732 static const char *cmd_args;
733 cmd_source_t cmd_source;
736 static cmd_function_t *cmd_functions; // possible commands to execute
738 static const char *Cmd_GetDirectCvarValue(const char *varname, cmdalias_t *alias, qboolean *is_multiple)
745 *is_multiple = false;
747 if(!varname || !*varname)
752 if(!strcmp(varname, "*"))
758 else if(!strcmp(varname, "#"))
760 return va("%d", Cmd_Argc());
762 else if(varname[strlen(varname) - 1] == '-')
764 argno = strtol(varname, &endptr, 10);
765 if(endptr == varname + strlen(varname) - 1)
767 // whole string is a number, apart from the -
768 const char *p = Cmd_Args();
769 for(; argno > 1; --argno)
770 if(!COM_ParseToken_Console(&p))
777 // kill pre-argument whitespace
778 for (;*p && ISWHITESPACE(*p);p++)
787 argno = strtol(varname, &endptr, 10);
790 // whole string is a number
791 // NOTE: we already made sure we don't have an empty cvar name!
792 if(argno >= 0 && argno < Cmd_Argc())
793 return Cmd_Argv(argno);
798 if((cvar = Cvar_FindVar(varname)) && !(cvar->flags & CVAR_PRIVATE))
804 qboolean Cmd_QuoteString(char *out, size_t outlen, const char *in, const char *quoteset, qboolean putquotes)
806 qboolean quote_quot = !!strchr(quoteset, '"');
807 qboolean quote_backslash = !!strchr(quoteset, '\\');
808 qboolean quote_dollar = !!strchr(quoteset, '$');
817 *out++ = '"'; --outlen;
823 if(*in == '"' && quote_quot)
827 *out++ = '\\'; --outlen;
828 *out++ = '"'; --outlen;
830 else if(*in == '\\' && quote_backslash)
834 *out++ = '\\'; --outlen;
835 *out++ = '\\'; --outlen;
837 else if(*in == '$' && quote_dollar)
841 *out++ = '$'; --outlen;
842 *out++ = '$'; --outlen;
848 *out++ = *in; --outlen;
863 static const char *Cmd_GetCvarValue(const char *var, size_t varlen, cmdalias_t *alias)
865 static char varname[MAX_INPUTLINE];
866 static char varval[MAX_INPUTLINE];
869 static char asis[] = "asis"; // just to suppress const char warnings
871 if(varlen >= MAX_INPUTLINE)
872 varlen = MAX_INPUTLINE - 1;
873 memcpy(varname, var, varlen);
875 varfunc = strchr(varname, ' ');
891 if(varname[0] == '$')
892 varstr = Cmd_GetDirectCvarValue(Cmd_GetDirectCvarValue(varname + 1, alias, NULL), alias, NULL);
895 qboolean is_multiple = false;
896 // Exception: $* and $n- don't use the quoted form by default
897 varstr = Cmd_GetDirectCvarValue(varname, alias, &is_multiple);
906 Con_Printf("Warning: Could not expand $%s in alias %s\n", varname, alias->name);
908 Con_Printf("Warning: Could not expand $%s\n", varname);
912 if(!varfunc || !strcmp(varfunc, "q")) // note: quoted form is default, use "asis" to override!
914 // quote it so it can be used inside double quotes
915 // we just need to replace " by \", and of course, double backslashes
916 Cmd_QuoteString(varval, sizeof(varval), varstr, "\"\\", false);
919 else if(!strcmp(varfunc, "asis"))
924 Con_Printf("Unknown variable function %s\n", varfunc);
932 Preprocesses strings and replaces $*, $param#, $cvar accordingly. Also strips comments.
934 static void Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias ) {
940 // don't crash if there's no room in the outtext buffer
941 if( maxoutlen == 0 ) {
944 maxoutlen--; // because of \0
949 while( *in && outlen < maxoutlen ) {
951 // this is some kind of expansion, see what comes after the $
954 // The console does the following preprocessing:
956 // - $$ is transformed to a single dollar sign.
957 // - $var or ${var} are expanded to the contents of the named cvar,
958 // with quotation marks and backslashes quoted so it can safely
959 // be used inside quotation marks (and it should always be used
961 // - ${var asis} inserts the cvar value as is, without doing this
963 // - prefix the cvar name with a dollar sign to do indirection;
964 // for example, if $x has the value timelimit, ${$x} will return
965 // the value of $timelimit
966 // - when expanding an alias, the special variable name $* refers
967 // to all alias parameters, and a number refers to that numbered
968 // alias parameter, where the name of the alias is $0, the first
969 // parameter is $1 and so on; as a special case, $* inserts all
970 // parameters, without extra quoting, so one can use $* to just
971 // pass all parameters around. All parameters starting from $n
972 // can be referred to as $n- (so $* is equivalent to $1-).
974 // Note: when expanding an alias, cvar expansion is done in the SAME step
975 // as alias expansion so that alias parameters or cvar values containing
976 // dollar signs have no unwanted bad side effects. However, this needs to
977 // be accounted for when writing complex aliases. For example,
978 // alias foo "set x NEW; echo $x"
979 // actually expands to
980 // "set x NEW; echo OLD"
981 // and will print OLD! To work around this, use a second alias:
982 // alias foo "set x NEW; foo2"
983 // alias foo2 "echo $x"
985 // Also note: lines starting with alias are exempt from cvar expansion.
986 // If you want cvar expansion, write "alias" instead:
989 // alias foo "echo $x"
990 // "alias" bar "echo $x"
993 // foo will print 2, because the variable $x will be expanded when the alias
994 // gets expanded. bar will print 1, because the variable $x was expanded
995 // at definition time. foo can be equivalently defined as
997 // "alias" foo "echo $$x"
999 // because at definition time, $$ will get replaced to a single $.
1004 } else if(*in == '{') {
1005 varlen = strcspn(in + 1, "}");
1006 if(in[varlen + 1] == '}')
1008 val = Cmd_GetCvarValue(in + 1, varlen, alias);
1018 varlen = strspn(in, "#*0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-");
1019 val = Cmd_GetCvarValue(in, varlen, alias);
1024 // insert the cvar value
1025 while(*val && outlen < maxoutlen)
1026 outtext[outlen++] = *val++;
1031 // copy the unexpanded text
1032 outtext[outlen++] = '$';
1033 while(eat && outlen < maxoutlen)
1035 outtext[outlen++] = *in++;
1041 outtext[outlen++] = *in++;
1043 outtext[outlen] = 0;
1050 Called for aliases and fills in the alias into the cbuffer
1053 static void Cmd_ExecuteAlias (cmdalias_t *alias)
1055 static char buffer[ MAX_INPUTLINE ];
1056 static char buffer2[ MAX_INPUTLINE ];
1057 Cmd_PreprocessString( alias->value, buffer, sizeof(buffer) - 2, alias );
1058 // insert at start of command buffer, so that aliases execute in order
1059 // (fixes bug introduced by Black on 20050705)
1061 // Note: Cbuf_PreprocessString will be called on this string AGAIN! So we
1062 // have to make sure that no second variable expansion takes place, otherwise
1063 // alias parameters containing dollar signs can have bad effects.
1064 Cmd_QuoteString(buffer2, sizeof(buffer2), buffer, "$", false);
1065 Cbuf_InsertText( buffer2 );
1072 CmdList Added by EvilTypeGuy eviltypeguy@qeradiant.com
1073 Thanks to Matthias "Maddes" Buecher, http://www.inside3d.com/qip/
1077 static void Cmd_List_f (void)
1079 cmd_function_t *cmd;
1080 const char *partial;
1087 partial = Cmd_Argv (1);
1088 len = strlen(partial);
1096 ispattern = partial && (strchr(partial, '*') || strchr(partial, '?'));
1099 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1101 if (partial && (ispattern ? !matchpattern_with_separator(cmd->name, partial, false, "", false) : strncmp(partial, cmd->name, len)))
1103 Con_Printf("%s : %s\n", cmd->name, cmd->description);
1110 Con_Printf("%i Command%s matching \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1112 Con_Printf("%i Command%s beginning with \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1115 Con_Printf("%i Command%s\n\n", count, (count > 1) ? "s" : "");
1118 static void Cmd_Apropos_f(void)
1120 cmd_function_t *cmd;
1123 const char *partial;
1128 partial = Cmd_Args();
1131 Con_Printf("usage: apropos <string>\n");
1135 ispattern = partial && (strchr(partial, '*') || strchr(partial, '?'));
1137 partial = va("*%s*", partial);
1140 for (cvar = cvar_vars; cvar; cvar = cvar->next)
1142 if (!matchpattern_with_separator(cvar->name, partial, true, "", false))
1143 if (!matchpattern_with_separator(cvar->description, partial, true, "", false))
1145 Con_Printf ("cvar ^3%s^7 is \"%s\" [\"%s\"] %s\n", cvar->name, cvar->string, cvar->defstring, cvar->description);
1148 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1150 if (!matchpattern_with_separator(cmd->name, partial, true, "", false))
1151 if (!matchpattern_with_separator(cmd->description, partial, true, "", false))
1153 Con_Printf("command ^2%s^7: %s\n", cmd->name, cmd->description);
1156 for (alias = cmd_alias; alias; alias = alias->next)
1158 // procede here a bit differently as an alias value always got a final \n
1159 if (!matchpattern_with_separator(alias->name, partial, true, "", false))
1160 if (!matchpattern_with_separator(alias->value, partial, true, "\n", false)) // when \n is as separator wildcards don't match it
1162 Con_Printf("alias ^5%s^7: %s", alias->name, alias->value); // do not print an extra \n
1165 Con_Printf("%i result%s\n\n", count, (count > 1) ? "s" : "");
1173 void Cmd_Init (void)
1175 cmd_mempool = Mem_AllocPool("commands", 0, NULL);
1176 // space for commands and script files
1177 cmd_text.data = cmd_text_buf;
1178 cmd_text.maxsize = sizeof(cmd_text_buf);
1179 cmd_text.cursize = 0;
1182 void Cmd_Init_Commands (void)
1185 // register our commands
1187 Cmd_AddCommand ("stuffcmds",Cmd_StuffCmds_f, "execute commandline parameters (must be present in quake.rc script)");
1188 Cmd_AddCommand ("exec",Cmd_Exec_f, "execute a script file");
1189 Cmd_AddCommand ("echo",Cmd_Echo_f, "print a message to the console (useful in scripts)");
1190 Cmd_AddCommand ("alias",Cmd_Alias_f, "create a script function (parameters are passed in as $X (being X a number), $* for all parameters, $X- for all parameters starting from $X). Without arguments show the list of all alias");
1191 Cmd_AddCommand ("unalias",Cmd_UnAlias_f, "remove an alias");
1192 Cmd_AddCommand ("cmd", Cmd_ForwardToServer, "send a console commandline to the server (used by some mods)");
1193 Cmd_AddCommand ("wait", Cmd_Wait_f, "make script execution wait for next rendered frame");
1194 Cmd_AddCommand ("set", Cvar_Set_f, "create or change the value of a console variable");
1195 Cmd_AddCommand ("seta", Cvar_SetA_f, "create or change the value of a console variable that will be saved to config.cfg");
1196 Cmd_AddCommand ("unset", Cvar_Del_f, "delete a cvar (does not work for static ones like _cl_name, or read-only ones)");
1197 #ifdef FILLALLCVARSWITHRUBBISH
1198 Cmd_AddCommand ("fillallcvarswithrubbish", Cvar_FillAll_f, "fill all cvars with a specified number of characters to provoke buffer overruns");
1199 #endif /* FILLALLCVARSWITHRUBBISH */
1201 // 2000-01-09 CmdList, CvarList commands By Matthias "Maddes" Buecher
1202 // Added/Modified by EvilTypeGuy eviltypeguy@qeradiant.com
1203 Cmd_AddCommand ("cmdlist", Cmd_List_f, "lists all console commands beginning with the specified prefix or matching the specified wildcard pattern");
1204 Cmd_AddCommand ("cvarlist", Cvar_List_f, "lists all console variables beginning with the specified prefix or matching the specified wildcard pattern");
1205 Cmd_AddCommand ("apropos", Cmd_Apropos_f, "lists all console variables/commands/aliases containing the specified string in the name or description");
1207 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");
1208 Cmd_AddCommand ("cvar_resettodefaults_all", Cvar_ResetToDefaults_All_f, "sets all cvars to their locked default values");
1209 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)");
1210 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)");
1212 Cmd_AddCommand ("cprint", Cmd_Centerprint_f, "print something at the screen center");
1213 Cmd_AddCommand ("defer", Cmd_Defer_f, "execute a command in the future");
1216 // Support Doom3-style Toggle Command
1217 Cmd_AddCommand( "toggle", Cmd_Toggle_f, "toggles a console variable's values (use for more info)");
1225 void Cmd_Shutdown(void)
1227 Mem_FreePool(&cmd_mempool);
1245 const char *Cmd_Argv (int arg)
1247 if (arg >= cmd_argc )
1248 return cmd_null_string;
1249 return cmd_argv[arg];
1257 const char *Cmd_Args (void)
1267 Parses the given string into command line tokens.
1270 // AK: This function should only be called from ExcuteString because the current design is a bit of an hack
1271 static void Cmd_TokenizeString (const char *text)
1280 // skip whitespace up to a /n
1281 while (*text && ISWHITESPACE(*text) && *text != '\r' && *text != '\n')
1288 if (*text == '\n' || *text == '\r')
1290 // a newline separates commands in the buffer
1291 if (*text == '\r' && text[1] == '\n')
1303 if (!COM_ParseToken_Console(&text))
1306 if (cmd_argc < MAX_ARGS)
1308 l = (int)strlen(com_token) + 1;
1309 if (cmd_tokenizebufferpos + l > CMD_TOKENIZELENGTH)
1311 Con_Printf("Cmd_TokenizeString: ran out of %i character buffer space for command arguements\n", CMD_TOKENIZELENGTH);
1314 memcpy (cmd_tokenizebuffer + cmd_tokenizebufferpos, com_token, l);
1315 cmd_argv[cmd_argc] = cmd_tokenizebuffer + cmd_tokenizebufferpos;
1316 cmd_tokenizebufferpos += l;
1328 void Cmd_AddCommand_WithClientCommand (const char *cmd_name, xcommand_t consolefunction, xcommand_t clientfunction, const char *description)
1330 cmd_function_t *cmd;
1331 cmd_function_t *prev, *current;
1333 // fail if the command is a variable name
1334 if (Cvar_FindVar( cmd_name ))
1336 Con_Printf("Cmd_AddCommand: %s already defined as a var\n", cmd_name);
1340 // fail if the command already exists
1341 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1343 if (!strcmp (cmd_name, cmd->name))
1345 if (consolefunction || clientfunction)
1347 Con_Printf("Cmd_AddCommand: %s already defined\n", cmd_name);
1352 cmd->csqcfunc = true;
1358 cmd = (cmd_function_t *)Mem_Alloc(cmd_mempool, sizeof(cmd_function_t));
1359 cmd->name = cmd_name;
1360 cmd->consolefunction = consolefunction;
1361 cmd->clientfunction = clientfunction;
1362 cmd->description = description;
1363 if(!consolefunction && !clientfunction) //[515]: csqc
1364 cmd->csqcfunc = true;
1365 cmd->next = cmd_functions;
1367 // insert it at the right alphanumeric position
1368 for( prev = NULL, current = cmd_functions ; current && strcmp( current->name, cmd->name ) < 0 ; prev = current, current = current->next )
1373 cmd_functions = cmd;
1375 cmd->next = current;
1378 void Cmd_AddCommand (const char *cmd_name, xcommand_t function, const char *description)
1380 Cmd_AddCommand_WithClientCommand (cmd_name, function, NULL, description);
1388 qboolean Cmd_Exists (const char *cmd_name)
1390 cmd_function_t *cmd;
1392 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1393 if (!strcmp (cmd_name,cmd->name))
1405 const char *Cmd_CompleteCommand (const char *partial)
1407 cmd_function_t *cmd;
1410 len = strlen(partial);
1416 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1417 if (!strncasecmp(partial, cmd->name, len))
1424 Cmd_CompleteCountPossible
1426 New function for tab-completion system
1427 Added by EvilTypeGuy
1428 Thanks to Fett erich@heintz.com
1432 int Cmd_CompleteCountPossible (const char *partial)
1434 cmd_function_t *cmd;
1439 len = strlen(partial);
1444 // Loop through the command list and count all partial matches
1445 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1446 if (!strncasecmp(partial, cmd->name, len))
1453 Cmd_CompleteBuildList
1455 New function for tab-completion system
1456 Added by EvilTypeGuy
1457 Thanks to Fett erich@heintz.com
1461 const char **Cmd_CompleteBuildList (const char *partial)
1463 cmd_function_t *cmd;
1466 size_t sizeofbuf = (Cmd_CompleteCountPossible (partial) + 1) * sizeof (const char *);
1469 len = strlen(partial);
1470 buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1471 // Loop through the alias list and print all matches
1472 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1473 if (!strncasecmp(partial, cmd->name, len))
1474 buf[bpos++] = cmd->name;
1480 // written by LordHavoc
1481 void Cmd_CompleteCommandPrint (const char *partial)
1483 cmd_function_t *cmd;
1484 size_t len = strlen(partial);
1485 // Loop through the command list and print all matches
1486 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1487 if (!strncasecmp(partial, cmd->name, len))
1488 Con_Printf("^2%s^7: %s\n", cmd->name, cmd->description);
1494 New function for tab-completion system
1495 Added by EvilTypeGuy
1496 Thanks to Fett erich@heintz.com
1500 const char *Cmd_CompleteAlias (const char *partial)
1505 len = strlen(partial);
1511 for (alias = cmd_alias; alias; alias = alias->next)
1512 if (!strncasecmp(partial, alias->name, len))
1518 // written by LordHavoc
1519 void Cmd_CompleteAliasPrint (const char *partial)
1522 size_t len = strlen(partial);
1523 // Loop through the alias list and print all matches
1524 for (alias = cmd_alias; alias; alias = alias->next)
1525 if (!strncasecmp(partial, alias->name, len))
1526 Con_Printf("^5%s^7: %s", alias->name, alias->value);
1531 Cmd_CompleteAliasCountPossible
1533 New function for tab-completion system
1534 Added by EvilTypeGuy
1535 Thanks to Fett erich@heintz.com
1539 int Cmd_CompleteAliasCountPossible (const char *partial)
1547 len = strlen(partial);
1552 // Loop through the command list and count all partial matches
1553 for (alias = cmd_alias; alias; alias = alias->next)
1554 if (!strncasecmp(partial, alias->name, len))
1561 Cmd_CompleteAliasBuildList
1563 New function for tab-completion system
1564 Added by EvilTypeGuy
1565 Thanks to Fett erich@heintz.com
1569 const char **Cmd_CompleteAliasBuildList (const char *partial)
1574 size_t sizeofbuf = (Cmd_CompleteAliasCountPossible (partial) + 1) * sizeof (const char *);
1577 len = strlen(partial);
1578 buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1579 // Loop through the alias list and print all matches
1580 for (alias = cmd_alias; alias; alias = alias->next)
1581 if (!strncasecmp(partial, alias->name, len))
1582 buf[bpos++] = alias->name;
1588 void Cmd_ClearCsqcFuncs (void)
1590 cmd_function_t *cmd;
1591 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1592 cmd->csqcfunc = false;
1595 qboolean CL_VM_ConsoleCommand (const char *cmd);
1600 A complete command line has been parsed, so try to execute it
1601 FIXME: lookupnoadd the token to speed search?
1604 void Cmd_ExecuteString (const char *text, cmd_source_t src)
1608 cmd_function_t *cmd;
1611 oldpos = cmd_tokenizebufferpos;
1615 Cmd_TokenizeString (text);
1617 // execute the command line
1620 cmd_tokenizebufferpos = oldpos;
1621 return; // no tokens
1625 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1627 if (!strcasecmp (cmd_argv[0],cmd->name))
1629 if (cmd->csqcfunc && CL_VM_ConsoleCommand (text)) //[515]: csqc
1634 if (cmd->consolefunction)
1635 cmd->consolefunction ();
1636 else if (cmd->clientfunction)
1638 if (cls.state == ca_connected)
1640 // forward remote commands to the server for execution
1641 Cmd_ForwardToServer();
1644 Con_Printf("Can not send command \"%s\", not connected.\n", Cmd_Argv(0));
1647 Con_Printf("Command \"%s\" can not be executed\n", Cmd_Argv(0));
1651 if (cmd->clientfunction)
1653 cmd->clientfunction ();
1654 cmd_tokenizebufferpos = oldpos;
1664 // if it's a client command and no command was found, say so.
1665 if (cmd_source == src_client)
1667 Con_Printf("player \"%s\" tried to %s\n", host_client->name, text);
1668 cmd_tokenizebufferpos = oldpos;
1673 for (a=cmd_alias ; a ; a=a->next)
1675 if (!strcasecmp (cmd_argv[0], a->name))
1677 Cmd_ExecuteAlias(a);
1678 cmd_tokenizebufferpos = oldpos;
1683 if(found) // if the command was hooked and found, all is good
1685 cmd_tokenizebufferpos = oldpos;
1690 if (!Cvar_Command () && host_framecount > 0)
1691 Con_Printf("Unknown command \"%s\"\n", Cmd_Argv(0));
1693 cmd_tokenizebufferpos = oldpos;
1699 Cmd_ForwardStringToServer
1701 Sends an entire command string over to the server, unprocessed
1704 void Cmd_ForwardStringToServer (const char *s)
1707 if (cls.state != ca_connected)
1709 Con_Printf("Can't \"%s\", not connected\n", s);
1716 // LordHavoc: thanks to Fuh for bringing the pure evil of SZ_Print to my
1717 // attention, it has been eradicated from here, its only (former) use in
1718 // all of darkplaces.
1719 if (cls.protocol == PROTOCOL_QUAKEWORLD)
1720 MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
1722 MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
1723 if ((!strncmp(s, "say ", 4) || !strncmp(s, "say_team ", 9)) && cl_locs_enable.integer)
1725 // say/say_team commands can replace % character codes with status info
1728 if (*s == '%' && s[1])
1730 // handle proquake message macros
1734 case 'l': // current location
1735 CL_Locs_FindLocationName(temp, sizeof(temp), cl.movement_origin);
1737 case 'h': // current health
1738 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_HEALTH]);
1740 case 'a': // current armor
1741 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ARMOR]);
1743 case 'x': // current rockets
1744 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ROCKETS]);
1746 case 'c': // current cells
1747 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_CELLS]);
1749 // silly proquake macros
1750 case 'd': // loc at last death
1751 CL_Locs_FindLocationName(temp, sizeof(temp), cl.lastdeathorigin);
1753 case 't': // current time
1754 dpsnprintf(temp, sizeof(temp), "%.0f:%.0f", floor(cl.time / 60), cl.time - floor(cl.time / 60) * 60);
1756 case 'r': // rocket launcher status ("I have RL", "I need rockets", "I need RL")
1757 if (!(cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER))
1758 dpsnprintf(temp, sizeof(temp), "I need RL");
1759 else if (!cl.stats[STAT_ROCKETS])
1760 dpsnprintf(temp, sizeof(temp), "I need rockets");
1762 dpsnprintf(temp, sizeof(temp), "I have RL");
1764 case 'p': // powerup status (outputs "quad" "pent" and "eyes" according to status)
1765 if (cl.stats[STAT_ITEMS] & IT_QUAD)
1768 strlcat(temp, " ", sizeof(temp));
1769 strlcat(temp, "quad", sizeof(temp));
1771 if (cl.stats[STAT_ITEMS] & IT_INVULNERABILITY)
1774 strlcat(temp, " ", sizeof(temp));
1775 strlcat(temp, "pent", sizeof(temp));
1777 if (cl.stats[STAT_ITEMS] & IT_INVISIBILITY)
1780 strlcat(temp, " ", sizeof(temp));
1781 strlcat(temp, "eyes", sizeof(temp));
1784 case 'w': // weapon status (outputs "SSG:NG:SNG:GL:RL:LG" with the text between : characters omitted if you lack the weapon)
1785 if (cl.stats[STAT_ITEMS] & IT_SUPER_SHOTGUN)
1786 strlcat(temp, "SSG", sizeof(temp));
1787 strlcat(temp, ":", sizeof(temp));
1788 if (cl.stats[STAT_ITEMS] & IT_NAILGUN)
1789 strlcat(temp, "NG", sizeof(temp));
1790 strlcat(temp, ":", sizeof(temp));
1791 if (cl.stats[STAT_ITEMS] & IT_SUPER_NAILGUN)
1792 strlcat(temp, "SNG", sizeof(temp));
1793 strlcat(temp, ":", sizeof(temp));
1794 if (cl.stats[STAT_ITEMS] & IT_GRENADE_LAUNCHER)
1795 strlcat(temp, "GL", sizeof(temp));
1796 strlcat(temp, ":", sizeof(temp));
1797 if (cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER)
1798 strlcat(temp, "RL", sizeof(temp));
1799 strlcat(temp, ":", sizeof(temp));
1800 if (cl.stats[STAT_ITEMS] & IT_LIGHTNING)
1801 strlcat(temp, "LG", sizeof(temp));
1804 // not a recognized macro, print it as-is...
1810 // write the resulting text
1811 SZ_Write(&cls.netcon->message, (unsigned char *)temp, strlen(temp));
1815 MSG_WriteByte(&cls.netcon->message, *s);
1818 MSG_WriteByte(&cls.netcon->message, 0);
1820 else // any other command is passed on as-is
1821 SZ_Write(&cls.netcon->message, (const unsigned char *)s, (int)strlen(s) + 1);
1828 Sends the entire command line over to the server
1831 void Cmd_ForwardToServer (void)
1834 if (!strcasecmp(Cmd_Argv(0), "cmd"))
1836 // we want to strip off "cmd", so just send the args
1837 s = Cmd_Argc() > 1 ? Cmd_Args() : "";
1841 // we need to keep the command name, so send Cmd_Argv(0), a space and then Cmd_Args()
1842 s = va("%s %s", Cmd_Argv(0), Cmd_Argc() > 1 ? Cmd_Args() : "");
1844 // don't send an empty forward message if the user tries "cmd" by itself
1847 Cmd_ForwardStringToServer(s);
1855 Returns the position (1 to argc-1) in the command's argument list
1856 where the given parameter apears, or 0 if not present
1860 int Cmd_CheckParm (const char *parm)
1866 Con_Printf ("Cmd_CheckParm: NULL");
1870 for (i = 1; i < Cmd_Argc (); i++)
1871 if (!strcasecmp (parm, Cmd_Argv (i)))