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 = NULL;
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() == 2 && !strcasecmp("clear", Cmd_Argv(1)))
97 while(cmd_deferred_list)
99 cmddeferred_t *cmd = cmd_deferred_list;
100 cmd_deferred_list = cmd->next;
101 Mem_Free(cmd->value);
104 } else if(Cmd_Argc() == 3)
106 const char *value = Cmd_Argv(2);
107 cmddeferred_t *defcmd = (cmddeferred_t*)Mem_Alloc(tempmempool, sizeof(*defcmd));
108 size_t len = strlen(value);
110 defcmd->time = Sys_DoubleTime() + atof(Cmd_Argv(1));
111 defcmd->value = (char*)Mem_Alloc(tempmempool, len+1);
112 memcpy(defcmd->value, value, len+1);
115 if(cmd_deferred_list)
117 cmddeferred_t *next = cmd_deferred_list;
122 cmd_deferred_list = defcmd;
123 /* Stupid me... this changes the order... so commands with the same delay go blub :S
124 defcmd->next = cmd_deferred_list;
125 cmd_deferred_list = defcmd;*/
127 Con_Printf("usage: defer <seconds> <command>\n"
137 Print something to the center of the screen using SCR_Centerprint
140 static void Cmd_Centerprint_f (void)
142 char msg[MAX_INPUTLINE];
143 unsigned int i, c, p;
147 strlcpy(msg, Cmd_Argv(1), sizeof(msg));
148 for(i = 2; i < c; ++i)
150 strlcat(msg, " ", sizeof(msg));
151 strlcat(msg, Cmd_Argv(i), sizeof(msg));
154 for(p = 0, i = 0; i < c; ++i)
160 else if(msg[i+1] == '\\')
172 SCR_CenterPrint(msg);
177 =============================================================================
181 =============================================================================
184 static sizebuf_t cmd_text;
185 static unsigned char cmd_text_buf[CMDBUFSIZE];
191 Adds command text at the end of the buffer
194 void Cbuf_AddText (const char *text)
198 l = (int)strlen (text);
200 if (cmd_text.cursize + l >= cmd_text.maxsize)
202 Con_Print("Cbuf_AddText: overflow\n");
206 SZ_Write (&cmd_text, (const unsigned char *)text, (int)strlen (text));
214 Adds command text immediately after the current command
215 Adds a \n to the text
216 FIXME: actually change the command buffer to do less copying
219 void Cbuf_InsertText (const char *text)
224 // copy off any commands still remaining in the exec buffer
225 templen = cmd_text.cursize;
228 temp = (char *)Mem_Alloc (tempmempool, templen);
229 memcpy (temp, cmd_text.data, templen);
230 SZ_Clear (&cmd_text);
235 // add the entire text of the file
238 // add the copied off data
241 SZ_Write (&cmd_text, (const unsigned char *)temp, templen);
248 Cbuf_Execute_Deferred --blub
251 void Cbuf_Execute_Deferred (void)
253 cmddeferred_t *cmd, *prev;
254 double time = Sys_DoubleTime();
256 cmd = cmd_deferred_list;
259 if(cmd->time <= time)
261 Cbuf_AddText(cmd->value);
263 Mem_Free(cmd->value);
266 prev->next = cmd->next;
270 cmd_deferred_list = cmd->next;
272 cmd = cmd_deferred_list;
286 static void Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias );
287 void Cbuf_Execute (void)
291 char line[MAX_INPUTLINE];
292 char preprocessed[MAX_INPUTLINE];
294 qboolean quotes, comment;
296 // LordHavoc: making sure the tokenizebuffer doesn't get filled up by repeated crashes
297 cmd_tokenizebufferpos = 0;
299 Cbuf_Execute_Deferred();
300 while (cmd_text.cursize)
302 // find a \n or ; line break
303 text = (char *)cmd_text.data;
307 for (i=0 ; i < cmd_text.cursize ; i++)
316 // make sure i doesn't get > cursize which causes a negative
317 // size in memmove, which is fatal --blub
318 if (i < (cmd_text.cursize-1) && (text[i] == '\\' && (text[i+1] == '"' || text[i+1] == '\\')))
323 if(text[i] == '/' && text[i + 1] == '/')
326 break; // don't break if inside a quoted string or comment
330 if (text[i] == '\r' || text[i] == '\n')
334 // better than CRASHING on overlong input lines that may SOMEHOW enter the buffer
335 if(i >= MAX_INPUTLINE)
337 Con_Printf("Warning: console input buffer had an overlong line. Ignored.\n");
342 memcpy (line, text, i);
346 // delete the text from the command buffer and move remaining commands down
347 // this is necessary because commands (exec, alias) can insert data at the
348 // beginning of the text buffer
350 if (i == cmd_text.cursize)
351 cmd_text.cursize = 0;
355 cmd_text.cursize -= i;
356 memmove (cmd_text.data, text+i, cmd_text.cursize);
359 // execute the command line
360 firstchar = line + strspn(line, " \t");
362 (strncmp(firstchar, "alias", 5) || (firstchar[5] != ' ' && firstchar[5] != '\t'))
364 (strncmp(firstchar, "bind", 4) || (firstchar[4] != ' ' && firstchar[4] != '\t'))
366 (strncmp(firstchar, "in_bind", 7) || (firstchar[7] != ' ' && firstchar[7] != '\t'))
369 Cmd_PreprocessString( line, preprocessed, sizeof(preprocessed), NULL );
370 Cmd_ExecuteString (preprocessed, src_command);
374 Cmd_ExecuteString (line, src_command);
378 { // skip out while text still remains in buffer, leaving it
387 ==============================================================================
391 ==============================================================================
398 Adds command line parameters as script statements
399 Commands lead with a +, and continue until a - or another +
400 quake +prog jctest.qp +cmd amlev1
401 quake -nosound +cmd amlev1
404 qboolean host_stuffcmdsrun = false;
405 void Cmd_StuffCmds_f (void)
408 // this is for all commandline options combined (and is bounds checked)
409 char build[MAX_INPUTLINE];
411 if (Cmd_Argc () != 1)
413 Con_Print("stuffcmds : execute command line parameters\n");
417 // no reason to run the commandline arguments twice
418 if (host_stuffcmdsrun)
421 host_stuffcmdsrun = true;
424 for (i = 0;i < com_argc;i++)
426 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)
429 while (com_argv[i][j])
430 build[l++] = com_argv[i][j++];
432 for (;i < com_argc;i++)
436 if ((com_argv[i][0] == '+' || com_argv[i][0] == '-') && (com_argv[i][1] < '0' || com_argv[i][1] > '9'))
438 if (l + strlen(com_argv[i]) + 4 > sizeof(build) - 1)
441 if (strchr(com_argv[i], ' '))
443 for (j = 0;com_argv[i][j];j++)
444 build[l++] = com_argv[i][j];
445 if (strchr(com_argv[i], ' '))
452 // now terminate the combined string and prepend it to the command buffer
453 // we already reserved space for the terminator
455 Cbuf_InsertText (build);
464 static void Cmd_Exec_f (void)
468 if (Cmd_Argc () != 2)
470 Con_Print("exec <filename> : execute a script file\n");
474 f = (char *)FS_LoadFile (Cmd_Argv(1), tempmempool, false, NULL);
477 Con_Printf("couldn't exec %s\n",Cmd_Argv(1));
480 Con_Printf("execing %s\n",Cmd_Argv(1));
482 // if executing default.cfg for the first time, lock the cvar defaults
483 // it may seem backwards to insert this text BEFORE the default.cfg
484 // but Cbuf_InsertText inserts before, so this actually ends up after it.
485 if (!strcmp(Cmd_Argv(1), "default.cfg"))
486 Cbuf_InsertText("\ncvar_lockdefaults\n");
488 // insert newline after the text to make sure the last line is terminated (some text editors omit the trailing newline)
489 // (note: insertion order here is backwards from execution order, so this adds it after the text, by calling it before...)
490 Cbuf_InsertText ("\n");
500 Just prints the rest of the line to the console
503 static void Cmd_Echo_f (void)
507 for (i=1 ; i<Cmd_Argc() ; i++)
508 Con_Printf("%s ",Cmd_Argv(i));
513 // Support Doom3-style Toggle Console Command
518 Toggles a specified console variable amongst the values specified (default is 0 and 1)
521 static void Cmd_Toggle_f(void)
523 // Acquire Number of Arguments
524 int nNumArgs = Cmd_Argc();
527 // No Arguments Specified; Print Usage
528 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");
530 { // Correct Arguments Specified
531 // Acquire Potential CVar
532 cvar_t* cvCVar = Cvar_FindVar( Cmd_Argv(1) );
539 Cvar_SetValueQuick(cvCVar, 0);
541 Cvar_SetValueQuick(cvCVar, 1);
545 { // 0 and Specified Usage
546 if(cvCVar->integer == atoi(Cmd_Argv(2) ) )
547 // CVar is Specified Value; // Reset to 0
548 Cvar_SetValueQuick(cvCVar, 0);
550 if(cvCVar->integer == 0)
551 // CVar is 0; Specify Value
552 Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
554 // CVar does not match; Reset to 0
555 Cvar_SetValueQuick(cvCVar, 0);
558 { // Variable Values Specified
562 for(nCnt = 2; nCnt < nNumArgs; nCnt++)
563 { // Cycle through Values
564 if( strcmp(cvCVar->string, Cmd_Argv(nCnt) ) == 0)
565 { // Current Value Located; Increment to Next
566 if( (nCnt + 1) == nNumArgs)
567 // Max Value Reached; Reset
568 Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
571 Cvar_SetQuick(cvCVar, Cmd_Argv(nCnt + 1) );
580 // Value not Found; Reset to Original
581 Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
587 Con_Printf("ERROR : CVar '%s' not found\n", Cmd_Argv(1) );
596 Creates a new command that executes a command string (possibly ; seperated)
599 static void Cmd_Alias_f (void)
602 char cmd[MAX_INPUTLINE];
609 Con_Print("Current alias commands:\n");
610 for (a = cmd_alias ; a ; a=a->next)
611 Con_Printf("%s : %s\n", a->name, a->value);
616 if (strlen(s) >= MAX_ALIAS_NAME)
618 Con_Print("Alias name is too long\n");
622 // if the alias already exists, reuse it
623 for (a = cmd_alias ; a ; a=a->next)
625 if (!strcmp(s, a->name))
634 cmdalias_t *prev, *current;
636 a = (cmdalias_t *)Z_Malloc (sizeof(cmdalias_t));
637 strlcpy (a->name, s, sizeof (a->name));
638 // insert it at the right alphanumeric position
639 for( prev = NULL, current = cmd_alias ; current && strcmp( current->name, a->name ) < 0 ; prev = current, current = current->next )
650 // copy the rest of the command line
651 cmd[0] = 0; // start out with a null string
653 for (i=2 ; i< c ; i++)
655 strlcat (cmd, Cmd_Argv(i), sizeof (cmd));
657 strlcat (cmd, " ", sizeof (cmd));
659 strlcat (cmd, "\n", sizeof (cmd));
661 alloclen = strlen (cmd) + 1;
662 a->value = (char *)Z_Malloc (alloclen);
663 memcpy (a->value, cmd, alloclen);
667 =============================================================================
671 =============================================================================
674 typedef struct cmd_function_s
676 struct cmd_function_s *next;
678 const char *description;
679 xcommand_t consolefunction;
680 xcommand_t clientfunction;
685 static const char *cmd_argv[MAX_ARGS];
686 static const char *cmd_null_string = "";
687 static const char *cmd_args;
688 cmd_source_t cmd_source;
691 static cmd_function_t *cmd_functions; // possible commands to execute
693 static const char *Cmd_GetDirectCvarValue(const char *varname, cmdalias_t *alias, qboolean *is_multiple)
700 *is_multiple = false;
702 if(!varname || !*varname)
707 if(!strcmp(varname, "*"))
713 else if(varname[strlen(varname) - 1] == '-')
715 argno = strtol(varname, &endptr, 10);
716 if(endptr == varname + strlen(varname) - 1)
718 // whole string is a number, apart from the -
719 const char *p = Cmd_Args();
720 for(; argno > 1; --argno)
721 if(!COM_ParseToken_Console(&p))
728 // kill pre-argument whitespace
729 for (;*p && ISWHITESPACE(*p);p++)
738 argno = strtol(varname, &endptr, 10);
741 // whole string is a number
742 // NOTE: we already made sure we don't have an empty cvar name!
743 if(argno >= 0 && argno < Cmd_Argc())
744 return Cmd_Argv(argno);
749 if((cvar = Cvar_FindVar(varname)) && !(cvar->flags & CVAR_PRIVATE))
755 qboolean Cmd_QuoteString(char *out, size_t outlen, const char *in, const char *quoteset)
757 qboolean quote_quot = !!strchr(quoteset, '"');
758 qboolean quote_backslash = !!strchr(quoteset, '\\');
759 qboolean quote_dollar = !!strchr(quoteset, '$');
763 if(*in == '"' && quote_quot)
770 *out++ = '\\'; --outlen;
771 *out++ = '"'; --outlen;
773 else if(*in == '\\' && quote_backslash)
780 *out++ = '\\'; --outlen;
781 *out++ = '\\'; --outlen;
783 else if(*in == '$' && quote_dollar)
790 *out++ = '$'; --outlen;
791 *out++ = '$'; --outlen;
800 *out++ = *in; --outlen;
808 static const char *Cmd_GetCvarValue(const char *var, size_t varlen, cmdalias_t *alias)
810 static char varname[MAX_INPUTLINE];
811 static char varval[MAX_INPUTLINE];
815 if(varlen >= MAX_INPUTLINE)
816 varlen = MAX_INPUTLINE - 1;
817 memcpy(varname, var, varlen);
819 varfunc = strchr(varname, ' ');
835 if(varname[0] == '$')
836 varstr = Cmd_GetDirectCvarValue(Cmd_GetDirectCvarValue(varname + 1, alias, NULL), alias, NULL);
839 qboolean is_multiple = false;
840 // Exception: $* and $n- don't use the quoted form by default
841 varstr = Cmd_GetDirectCvarValue(varname, alias, &is_multiple);
850 Con_Printf("Warning: Could not expand $%s in alias %s\n", varname, alias->name);
852 Con_Printf("Warning: Could not expand $%s\n", varname);
856 if(!varfunc || !strcmp(varfunc, "q")) // note: quoted form is default, use "asis" to override!
858 // quote it so it can be used inside double quotes
859 // we just need to replace " by \", and of course, double backslashes
860 Cmd_QuoteString(varval, sizeof(varval), varstr, "\"\\");
863 else if(!strcmp(varfunc, "asis"))
868 Con_Printf("Unknown variable function %s\n", varfunc);
876 Preprocesses strings and replaces $*, $param#, $cvar accordingly
878 static void Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias ) {
884 // don't crash if there's no room in the outtext buffer
885 if( maxoutlen == 0 ) {
888 maxoutlen--; // because of \0
893 while( *in && outlen < maxoutlen ) {
895 // this is some kind of expansion, see what comes after the $
898 // The console does the following preprocessing:
900 // - $$ is transformed to a single dollar sign.
901 // - $var or ${var} are expanded to the contents of the named cvar,
902 // with quotation marks and backslashes quoted so it can safely
903 // be used inside quotation marks (and it should always be used
905 // - ${var asis} inserts the cvar value as is, without doing this
907 // - prefix the cvar name with a dollar sign to do indirection;
908 // for example, if $x has the value timelimit, ${$x} will return
909 // the value of $timelimit
910 // - when expanding an alias, the special variable name $* refers
911 // to all alias parameters, and a number refers to that numbered
912 // alias parameter, where the name of the alias is $0, the first
913 // parameter is $1 and so on; as a special case, $* inserts all
914 // parameters, without extra quoting, so one can use $* to just
915 // pass all parameters around. All parameters starting from $n
916 // can be referred to as $n- (so $* is equivalent to $1-).
918 // Note: when expanding an alias, cvar expansion is done in the SAME step
919 // as alias expansion so that alias parameters or cvar values containing
920 // dollar signs have no unwanted bad side effects. However, this needs to
921 // be accounted for when writing complex aliases. For example,
922 // alias foo "set x NEW; echo $x"
923 // actually expands to
924 // "set x NEW; echo OLD"
925 // and will print OLD! To work around this, use a second alias:
926 // alias foo "set x NEW; foo2"
927 // alias foo2 "echo $x"
929 // Also note: lines starting with alias are exempt from cvar expansion.
930 // If you want cvar expansion, write "alias" instead:
933 // alias foo "echo $x"
934 // "alias" bar "echo $x"
937 // foo will print 2, because the variable $x will be expanded when the alias
938 // gets expanded. bar will print 1, because the variable $x was expanded
939 // at definition time. foo can be equivalently defined as
941 // "alias" foo "echo $$x"
943 // because at definition time, $$ will get replaced to a single $.
948 } else if(*in == '{') {
949 varlen = strcspn(in + 1, "}");
950 if(in[varlen + 1] == '}')
952 val = Cmd_GetCvarValue(in + 1, varlen, alias);
962 varlen = strspn(in, "*0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-");
963 val = Cmd_GetCvarValue(in, varlen, alias);
968 // insert the cvar value
969 while(*val && outlen < maxoutlen)
970 outtext[outlen++] = *val++;
975 // copy the unexpanded text
976 outtext[outlen++] = '$';
977 while(eat && outlen < maxoutlen)
979 outtext[outlen++] = *in++;
984 outtext[outlen++] = *in++;
994 Called for aliases and fills in the alias into the cbuffer
997 static void Cmd_ExecuteAlias (cmdalias_t *alias)
999 static char buffer[ MAX_INPUTLINE ];
1000 static char buffer2[ MAX_INPUTLINE ];
1001 Cmd_PreprocessString( alias->value, buffer, sizeof(buffer) - 2, alias );
1002 // insert at start of command buffer, so that aliases execute in order
1003 // (fixes bug introduced by Black on 20050705)
1005 // Note: Cbuf_PreprocessString will be called on this string AGAIN! So we
1006 // have to make sure that no second variable expansion takes place, otherwise
1007 // alias parameters containing dollar signs can have bad effects.
1008 Cmd_QuoteString(buffer2, sizeof(buffer2), buffer, "$");
1009 Cbuf_InsertText( buffer2 );
1016 CmdList Added by EvilTypeGuy eviltypeguy@qeradiant.com
1017 Thanks to Matthias "Maddes" Buecher, http://www.inside3d.com/qip/
1021 static void Cmd_List_f (void)
1023 cmd_function_t *cmd;
1024 const char *partial;
1029 partial = Cmd_Argv (1);
1030 len = (int)strlen(partial);
1039 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1041 if (partial && strncmp(partial, cmd->name, len))
1043 Con_Printf("%s : %s\n", cmd->name, cmd->description);
1048 Con_Printf("%i Command%s beginning with \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1050 Con_Printf("%i Command%s\n\n", count, (count > 1) ? "s" : "");
1058 void Cmd_Init (void)
1060 cmd_mempool = Mem_AllocPool("commands", 0, NULL);
1061 // space for commands and script files
1062 cmd_text.data = cmd_text_buf;
1063 cmd_text.maxsize = sizeof(cmd_text_buf);
1064 cmd_text.cursize = 0;
1067 void Cmd_Init_Commands (void)
1070 // register our commands
1072 Cmd_AddCommand ("stuffcmds",Cmd_StuffCmds_f, "execute commandline parameters (must be present in quake.rc script)");
1073 Cmd_AddCommand ("exec",Cmd_Exec_f, "execute a script file");
1074 Cmd_AddCommand ("echo",Cmd_Echo_f, "print a message to the console (useful in scripts)");
1075 Cmd_AddCommand ("alias",Cmd_Alias_f, "create a script function (parameters are passed in as $1 through $9, and $* for all parameters)");
1076 Cmd_AddCommand ("cmd", Cmd_ForwardToServer, "send a console commandline to the server (used by some mods)");
1077 Cmd_AddCommand ("wait", Cmd_Wait_f, "make script execution wait for next rendered frame");
1078 Cmd_AddCommand ("set", Cvar_Set_f, "create or change the value of a console variable");
1079 Cmd_AddCommand ("seta", Cvar_SetA_f, "create or change the value of a console variable that will be saved to config.cfg");
1081 // 2000-01-09 CmdList, CvarList commands By Matthias "Maddes" Buecher
1082 // Added/Modified by EvilTypeGuy eviltypeguy@qeradiant.com
1083 Cmd_AddCommand ("cmdlist", Cmd_List_f, "lists all console commands beginning with the specified prefix");
1084 Cmd_AddCommand ("cvarlist", Cvar_List_f, "lists all console variables beginning with the specified prefix");
1086 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");
1087 Cmd_AddCommand ("cvar_resettodefaults_all", Cvar_ResetToDefaults_All_f, "sets all cvars to their locked default values");
1088 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)");
1089 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)");
1091 Cmd_AddCommand ("cprint", Cmd_Centerprint_f, "print something at the screen center");
1092 Cmd_AddCommand ("defer", Cmd_Defer_f, "execute a command in the future");
1095 // Support Doom3-style Toggle Command
1096 Cmd_AddCommand( "toggle", Cmd_Toggle_f, "toggles a console variable's values (use for more info)");
1104 void Cmd_Shutdown(void)
1106 Mem_FreePool(&cmd_mempool);
1124 const char *Cmd_Argv (int arg)
1126 if (arg >= cmd_argc )
1127 return cmd_null_string;
1128 return cmd_argv[arg];
1136 const char *Cmd_Args (void)
1146 Parses the given string into command line tokens.
1149 // AK: This function should only be called from ExcuteString because the current design is a bit of an hack
1150 static void Cmd_TokenizeString (const char *text)
1159 // skip whitespace up to a /n
1160 while (*text && ISWHITESPACE(*text) && *text != '\r' && *text != '\n')
1167 if (*text == '\n' || *text == '\r')
1169 // a newline separates commands in the buffer
1170 if (*text == '\r' && text[1] == '\n')
1182 if (!COM_ParseToken_Console(&text))
1185 if (cmd_argc < MAX_ARGS)
1187 l = (int)strlen(com_token) + 1;
1188 if (cmd_tokenizebufferpos + l > CMD_TOKENIZELENGTH)
1190 Con_Printf("Cmd_TokenizeString: ran out of %i character buffer space for command arguements\n", CMD_TOKENIZELENGTH);
1193 memcpy (cmd_tokenizebuffer + cmd_tokenizebufferpos, com_token, l);
1194 cmd_argv[cmd_argc] = cmd_tokenizebuffer + cmd_tokenizebufferpos;
1195 cmd_tokenizebufferpos += l;
1207 void Cmd_AddCommand_WithClientCommand (const char *cmd_name, xcommand_t consolefunction, xcommand_t clientfunction, const char *description)
1209 cmd_function_t *cmd;
1210 cmd_function_t *prev, *current;
1212 // fail if the command is a variable name
1213 if (Cvar_FindVar( cmd_name ))
1215 Con_Printf("Cmd_AddCommand: %s already defined as a var\n", cmd_name);
1219 // fail if the command already exists
1220 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1222 if (!strcmp (cmd_name, cmd->name))
1224 if (consolefunction || clientfunction)
1226 Con_Printf("Cmd_AddCommand: %s already defined\n", cmd_name);
1231 cmd->csqcfunc = true;
1237 cmd = (cmd_function_t *)Mem_Alloc(cmd_mempool, sizeof(cmd_function_t));
1238 cmd->name = cmd_name;
1239 cmd->consolefunction = consolefunction;
1240 cmd->clientfunction = clientfunction;
1241 cmd->description = description;
1242 if(!consolefunction && !clientfunction) //[515]: csqc
1243 cmd->csqcfunc = true;
1244 cmd->next = cmd_functions;
1246 // insert it at the right alphanumeric position
1247 for( prev = NULL, current = cmd_functions ; current && strcmp( current->name, cmd->name ) < 0 ; prev = current, current = current->next )
1252 cmd_functions = cmd;
1254 cmd->next = current;
1257 void Cmd_AddCommand (const char *cmd_name, xcommand_t function, const char *description)
1259 Cmd_AddCommand_WithClientCommand (cmd_name, function, NULL, description);
1267 qboolean Cmd_Exists (const char *cmd_name)
1269 cmd_function_t *cmd;
1271 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1272 if (!strcmp (cmd_name,cmd->name))
1284 const char *Cmd_CompleteCommand (const char *partial)
1286 cmd_function_t *cmd;
1289 len = strlen(partial);
1295 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1296 if (!strncasecmp(partial, cmd->name, len))
1303 Cmd_CompleteCountPossible
1305 New function for tab-completion system
1306 Added by EvilTypeGuy
1307 Thanks to Fett erich@heintz.com
1311 int Cmd_CompleteCountPossible (const char *partial)
1313 cmd_function_t *cmd;
1318 len = strlen(partial);
1323 // Loop through the command list and count all partial matches
1324 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1325 if (!strncasecmp(partial, cmd->name, len))
1332 Cmd_CompleteBuildList
1334 New function for tab-completion system
1335 Added by EvilTypeGuy
1336 Thanks to Fett erich@heintz.com
1340 const char **Cmd_CompleteBuildList (const char *partial)
1342 cmd_function_t *cmd;
1345 size_t sizeofbuf = (Cmd_CompleteCountPossible (partial) + 1) * sizeof (const char *);
1348 len = strlen(partial);
1349 buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1350 // Loop through the alias list and print all matches
1351 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1352 if (!strncasecmp(partial, cmd->name, len))
1353 buf[bpos++] = cmd->name;
1359 // written by LordHavoc
1360 void Cmd_CompleteCommandPrint (const char *partial)
1362 cmd_function_t *cmd;
1363 size_t len = strlen(partial);
1364 // Loop through the command list and print all matches
1365 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1366 if (!strncasecmp(partial, cmd->name, len))
1367 Con_Printf("%s : %s\n", cmd->name, cmd->description);
1373 New function for tab-completion system
1374 Added by EvilTypeGuy
1375 Thanks to Fett erich@heintz.com
1379 const char *Cmd_CompleteAlias (const char *partial)
1384 len = strlen(partial);
1390 for (alias = cmd_alias; alias; alias = alias->next)
1391 if (!strncasecmp(partial, alias->name, len))
1397 // written by LordHavoc
1398 void Cmd_CompleteAliasPrint (const char *partial)
1401 size_t len = strlen(partial);
1402 // Loop through the alias list and print all matches
1403 for (alias = cmd_alias; alias; alias = alias->next)
1404 if (!strncasecmp(partial, alias->name, len))
1405 Con_Printf("%s : %s\n", alias->name, alias->value);
1410 Cmd_CompleteAliasCountPossible
1412 New function for tab-completion system
1413 Added by EvilTypeGuy
1414 Thanks to Fett erich@heintz.com
1418 int Cmd_CompleteAliasCountPossible (const char *partial)
1426 len = strlen(partial);
1431 // Loop through the command list and count all partial matches
1432 for (alias = cmd_alias; alias; alias = alias->next)
1433 if (!strncasecmp(partial, alias->name, len))
1440 Cmd_CompleteAliasBuildList
1442 New function for tab-completion system
1443 Added by EvilTypeGuy
1444 Thanks to Fett erich@heintz.com
1448 const char **Cmd_CompleteAliasBuildList (const char *partial)
1453 size_t sizeofbuf = (Cmd_CompleteAliasCountPossible (partial) + 1) * sizeof (const char *);
1456 len = strlen(partial);
1457 buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1458 // Loop through the alias list and print all matches
1459 for (alias = cmd_alias; alias; alias = alias->next)
1460 if (!strncasecmp(partial, alias->name, len))
1461 buf[bpos++] = alias->name;
1467 void Cmd_ClearCsqcFuncs (void)
1469 cmd_function_t *cmd;
1470 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1471 cmd->csqcfunc = false;
1474 qboolean CL_VM_ConsoleCommand (const char *cmd);
1479 A complete command line has been parsed, so try to execute it
1480 FIXME: lookupnoadd the token to speed search?
1483 void Cmd_ExecuteString (const char *text, cmd_source_t src)
1487 cmd_function_t *cmd;
1490 oldpos = cmd_tokenizebufferpos;
1494 Cmd_TokenizeString (text);
1496 // execute the command line
1499 cmd_tokenizebufferpos = oldpos;
1500 return; // no tokens
1504 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1506 if (!strcasecmp (cmd_argv[0],cmd->name))
1508 if (cmd->csqcfunc && CL_VM_ConsoleCommand (text)) //[515]: csqc
1513 if (cmd->consolefunction)
1514 cmd->consolefunction ();
1515 else if (cmd->clientfunction)
1517 if (cls.state == ca_connected)
1519 // forward remote commands to the server for execution
1520 Cmd_ForwardToServer();
1523 Con_Printf("Can not send command \"%s\", not connected.\n", Cmd_Argv(0));
1526 Con_Printf("Command \"%s\" can not be executed\n", Cmd_Argv(0));
1531 if (cmd->clientfunction)
1533 cmd->clientfunction ();
1534 cmd_tokenizebufferpos = oldpos;
1544 // if it's a client command and no command was found, say so.
1545 if (cmd_source == src_client)
1547 Con_Printf("player \"%s\" tried to %s\n", host_client->name, text);
1548 cmd_tokenizebufferpos = oldpos;
1553 for (a=cmd_alias ; a ; a=a->next)
1555 if (!strcasecmp (cmd_argv[0], a->name))
1557 Cmd_ExecuteAlias(a);
1558 cmd_tokenizebufferpos = oldpos;
1563 if(found) // if the command was hooked and found, all is good
1565 cmd_tokenizebufferpos = oldpos;
1570 if (!Cvar_Command () && host_framecount > 0)
1571 Con_Printf("Unknown command \"%s\"\n", Cmd_Argv(0));
1573 cmd_tokenizebufferpos = oldpos;
1579 Cmd_ForwardStringToServer
1581 Sends an entire command string over to the server, unprocessed
1584 void Cmd_ForwardStringToServer (const char *s)
1587 if (cls.state != ca_connected)
1589 Con_Printf("Can't \"%s\", not connected\n", s);
1596 // LordHavoc: thanks to Fuh for bringing the pure evil of SZ_Print to my
1597 // attention, it has been eradicated from here, its only (former) use in
1598 // all of darkplaces.
1599 if (cls.protocol == PROTOCOL_QUAKEWORLD)
1600 MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
1602 MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
1603 if ((!strncmp(s, "say ", 4) || !strncmp(s, "say_team ", 9)) && cl_locs_enable.integer)
1605 // say/say_team commands can replace % character codes with status info
1608 if (*s == '%' && s[1])
1610 // handle proquake message macros
1614 case 'l': // current location
1615 CL_Locs_FindLocationName(temp, sizeof(temp), cl.movement_origin);
1617 case 'h': // current health
1618 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_HEALTH]);
1620 case 'a': // current armor
1621 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ARMOR]);
1623 case 'x': // current rockets
1624 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ROCKETS]);
1626 case 'c': // current cells
1627 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_CELLS]);
1629 // silly proquake macros
1630 case 'd': // loc at last death
1631 CL_Locs_FindLocationName(temp, sizeof(temp), cl.lastdeathorigin);
1633 case 't': // current time
1634 dpsnprintf(temp, sizeof(temp), "%.0f:%.0f", floor(cl.time / 60), cl.time - floor(cl.time / 60) * 60);
1636 case 'r': // rocket launcher status ("I have RL", "I need rockets", "I need RL")
1637 if (!(cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER))
1638 dpsnprintf(temp, sizeof(temp), "I need RL");
1639 else if (!cl.stats[STAT_ROCKETS])
1640 dpsnprintf(temp, sizeof(temp), "I need rockets");
1642 dpsnprintf(temp, sizeof(temp), "I have RL");
1644 case 'p': // powerup status (outputs "quad" "pent" and "eyes" according to status)
1645 if (cl.stats[STAT_ITEMS] & IT_QUAD)
1648 strlcat(temp, " ", sizeof(temp));
1649 strlcat(temp, "quad", sizeof(temp));
1651 if (cl.stats[STAT_ITEMS] & IT_INVULNERABILITY)
1654 strlcat(temp, " ", sizeof(temp));
1655 strlcat(temp, "pent", sizeof(temp));
1657 if (cl.stats[STAT_ITEMS] & IT_INVISIBILITY)
1660 strlcat(temp, " ", sizeof(temp));
1661 strlcat(temp, "eyes", sizeof(temp));
1664 case 'w': // weapon status (outputs "SSG:NG:SNG:GL:RL:LG" with the text between : characters omitted if you lack the weapon)
1665 if (cl.stats[STAT_ITEMS] & IT_SUPER_SHOTGUN)
1666 strlcat(temp, "SSG", sizeof(temp));
1667 strlcat(temp, ":", sizeof(temp));
1668 if (cl.stats[STAT_ITEMS] & IT_NAILGUN)
1669 strlcat(temp, "NG", sizeof(temp));
1670 strlcat(temp, ":", sizeof(temp));
1671 if (cl.stats[STAT_ITEMS] & IT_SUPER_NAILGUN)
1672 strlcat(temp, "SNG", sizeof(temp));
1673 strlcat(temp, ":", sizeof(temp));
1674 if (cl.stats[STAT_ITEMS] & IT_GRENADE_LAUNCHER)
1675 strlcat(temp, "GL", sizeof(temp));
1676 strlcat(temp, ":", sizeof(temp));
1677 if (cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER)
1678 strlcat(temp, "RL", sizeof(temp));
1679 strlcat(temp, ":", sizeof(temp));
1680 if (cl.stats[STAT_ITEMS] & IT_LIGHTNING)
1681 strlcat(temp, "LG", sizeof(temp));
1684 // not a recognized macro, print it as-is...
1690 // write the resulting text
1691 SZ_Write(&cls.netcon->message, (unsigned char *)temp, strlen(temp));
1695 MSG_WriteByte(&cls.netcon->message, *s);
1698 MSG_WriteByte(&cls.netcon->message, 0);
1700 else // any other command is passed on as-is
1701 SZ_Write(&cls.netcon->message, (const unsigned char *)s, (int)strlen(s) + 1);
1708 Sends the entire command line over to the server
1711 void Cmd_ForwardToServer (void)
1714 if (!strcasecmp(Cmd_Argv(0), "cmd"))
1716 // we want to strip off "cmd", so just send the args
1717 s = Cmd_Argc() > 1 ? Cmd_Args() : "";
1721 // we need to keep the command name, so send Cmd_Argv(0), a space and then Cmd_Args()
1722 s = va("%s %s", Cmd_Argv(0), Cmd_Argc() > 1 ? Cmd_Args() : "");
1724 // don't send an empty forward message if the user tries "cmd" by itself
1727 Cmd_ForwardStringToServer(s);
1735 Returns the position (1 to argc-1) in the command's argument list
1736 where the given parameter apears, or 0 if not present
1740 int Cmd_CheckParm (const char *parm)
1746 Con_Printf ("Cmd_CheckParm: NULL");
1750 for (i = 1; i < Cmd_Argc (); i++)
1751 if (!strcasecmp (parm, Cmd_Argv (i)))