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];
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;
306 for (i=0 ; i< cmd_text.cursize ; i++)
310 // make sure i doesn't get > cursize which causes a negative
311 // size in memmove, which is fatal --blub
312 if (i < (cmd_text.cursize-1) && (text[i] == '\\' && (text[i+1] == '"' || text[i+1] == '\\')))
314 if ( !quotes && text[i] == ';')
315 break; // don't break if inside a quoted string
316 if (text[i] == '\r' || text[i] == '\n')
320 // better than CRASHING on overlong input lines that may SOMEHOW enter the buffer
321 if(i >= MAX_INPUTLINE)
323 Con_Printf("Warning: console input buffer had an overlong line. Ignored.\n");
328 memcpy (line, text, i);
332 // delete the text from the command buffer and move remaining commands down
333 // this is necessary because commands (exec, alias) can insert data at the
334 // beginning of the text buffer
336 if (i == cmd_text.cursize)
337 cmd_text.cursize = 0;
341 cmd_text.cursize -= i;
342 memmove (cmd_text.data, text+i, cmd_text.cursize);
345 // execute the command line
346 firstchar = line + strspn(line, " \t");
348 (strncmp(firstchar, "alias", 5) || (firstchar[5] != ' ' && firstchar[5] != '\t'))
350 (strncmp(firstchar, "bind", 4) || (firstchar[4] != ' ' && firstchar[4] != '\t'))
352 (strncmp(firstchar, "in_bind", 7) || (firstchar[7] != ' ' && firstchar[7] != '\t'))
355 Cmd_PreprocessString( line, preprocessed, sizeof(preprocessed), NULL );
356 Cmd_ExecuteString (preprocessed, src_command);
360 Cmd_ExecuteString (line, src_command);
364 { // skip out while text still remains in buffer, leaving it
373 ==============================================================================
377 ==============================================================================
384 Adds command line parameters as script statements
385 Commands lead with a +, and continue until a - or another +
386 quake +prog jctest.qp +cmd amlev1
387 quake -nosound +cmd amlev1
390 qboolean host_stuffcmdsrun = false;
391 void Cmd_StuffCmds_f (void)
394 // this is for all commandline options combined (and is bounds checked)
395 char build[MAX_INPUTLINE];
397 if (Cmd_Argc () != 1)
399 Con_Print("stuffcmds : execute command line parameters\n");
403 // no reason to run the commandline arguments twice
404 if (host_stuffcmdsrun)
407 host_stuffcmdsrun = true;
410 for (i = 0;i < com_argc;i++)
412 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)
415 while (com_argv[i][j])
416 build[l++] = com_argv[i][j++];
418 for (;i < com_argc;i++)
422 if ((com_argv[i][0] == '+' || com_argv[i][0] == '-') && (com_argv[i][1] < '0' || com_argv[i][1] > '9'))
424 if (l + strlen(com_argv[i]) + 4 > sizeof(build) - 1)
427 if (strchr(com_argv[i], ' '))
429 for (j = 0;com_argv[i][j];j++)
430 build[l++] = com_argv[i][j];
431 if (strchr(com_argv[i], ' '))
438 // now terminate the combined string and prepend it to the command buffer
439 // we already reserved space for the terminator
441 Cbuf_InsertText (build);
450 static void Cmd_Exec_f (void)
454 if (Cmd_Argc () != 2)
456 Con_Print("exec <filename> : execute a script file\n");
460 f = (char *)FS_LoadFile (Cmd_Argv(1), tempmempool, false, NULL);
463 Con_Printf("couldn't exec %s\n",Cmd_Argv(1));
466 Con_Printf("execing %s\n",Cmd_Argv(1));
468 // if executing default.cfg for the first time, lock the cvar defaults
469 // it may seem backwards to insert this text BEFORE the default.cfg
470 // but Cbuf_InsertText inserts before, so this actually ends up after it.
471 if (!strcmp(Cmd_Argv(1), "default.cfg"))
472 Cbuf_InsertText("\ncvar_lockdefaults\n");
474 // insert newline after the text to make sure the last line is terminated (some text editors omit the trailing newline)
475 // (note: insertion order here is backwards from execution order, so this adds it after the text, by calling it before...)
476 Cbuf_InsertText ("\n");
486 Just prints the rest of the line to the console
489 static void Cmd_Echo_f (void)
493 for (i=1 ; i<Cmd_Argc() ; i++)
494 Con_Printf("%s ",Cmd_Argv(i));
499 // Support Doom3-style Toggle Console Command
504 Toggles a specified console variable amongst the values specified (default is 0 and 1)
507 static void Cmd_Toggle_f(void)
509 // Acquire Number of Arguments
510 int nNumArgs = Cmd_Argc();
513 // No Arguments Specified; Print Usage
514 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");
516 { // Correct Arguments Specified
517 // Acquire Potential CVar
518 cvar_t* cvCVar = Cvar_FindVar( Cmd_Argv(1) );
525 Cvar_SetValueQuick(cvCVar, 0);
527 Cvar_SetValueQuick(cvCVar, 1);
531 { // 0 and Specified Usage
532 if(cvCVar->integer == atoi(Cmd_Argv(2) ) )
533 // CVar is Specified Value; // Reset to 0
534 Cvar_SetValueQuick(cvCVar, 0);
536 if(cvCVar->integer == 0)
537 // CVar is 0; Specify Value
538 Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
540 // CVar does not match; Reset to 0
541 Cvar_SetValueQuick(cvCVar, 0);
544 { // Variable Values Specified
548 for(nCnt = 2; nCnt < nNumArgs; nCnt++)
549 { // Cycle through Values
550 if( strcmp(cvCVar->string, Cmd_Argv(nCnt) ) == 0)
551 { // Current Value Located; Increment to Next
552 if( (nCnt + 1) == nNumArgs)
553 // Max Value Reached; Reset
554 Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
557 Cvar_SetQuick(cvCVar, Cmd_Argv(nCnt + 1) );
566 // Value not Found; Reset to Original
567 Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
573 Con_Printf("ERROR : CVar '%s' not found\n", Cmd_Argv(1) );
582 Creates a new command that executes a command string (possibly ; seperated)
585 static void Cmd_Alias_f (void)
588 char cmd[MAX_INPUTLINE];
595 Con_Print("Current alias commands:\n");
596 for (a = cmd_alias ; a ; a=a->next)
597 Con_Printf("%s : %s\n", a->name, a->value);
602 if (strlen(s) >= MAX_ALIAS_NAME)
604 Con_Print("Alias name is too long\n");
608 // if the alias already exists, reuse it
609 for (a = cmd_alias ; a ; a=a->next)
611 if (!strcmp(s, a->name))
620 cmdalias_t *prev, *current;
622 a = (cmdalias_t *)Z_Malloc (sizeof(cmdalias_t));
623 strlcpy (a->name, s, sizeof (a->name));
624 // insert it at the right alphanumeric position
625 for( prev = NULL, current = cmd_alias ; current && strcmp( current->name, a->name ) < 0 ; prev = current, current = current->next )
636 // copy the rest of the command line
637 cmd[0] = 0; // start out with a null string
639 for (i=2 ; i< c ; i++)
641 strlcat (cmd, Cmd_Argv(i), sizeof (cmd));
643 strlcat (cmd, " ", sizeof (cmd));
645 strlcat (cmd, "\n", sizeof (cmd));
647 alloclen = strlen (cmd) + 1;
648 a->value = (char *)Z_Malloc (alloclen);
649 memcpy (a->value, cmd, alloclen);
653 =============================================================================
657 =============================================================================
660 typedef struct cmd_function_s
662 struct cmd_function_s *next;
664 const char *description;
665 xcommand_t consolefunction;
666 xcommand_t clientfunction;
671 static const char *cmd_argv[MAX_ARGS];
672 static const char *cmd_null_string = "";
673 static const char *cmd_args;
674 cmd_source_t cmd_source;
677 static cmd_function_t *cmd_functions; // possible commands to execute
679 static const char *Cmd_GetDirectCvarValue(const char *varname, cmdalias_t *alias, qboolean *is_multiple)
686 *is_multiple = false;
688 if(!varname || !*varname)
693 if(!strcmp(varname, "*"))
699 else if(varname[strlen(varname) - 1] == '-')
701 argno = strtol(varname, &endptr, 10);
702 if(endptr == varname + strlen(varname) - 1)
704 // whole string is a number, apart from the -
705 const char *p = Cmd_Args();
706 for(; argno > 1; --argno)
707 if(!COM_ParseToken_Console(&p))
714 // kill pre-argument whitespace
715 for (;*p && *p <= ' ';p++)
724 argno = strtol(varname, &endptr, 10);
727 // whole string is a number
728 // NOTE: we already made sure we don't have an empty cvar name!
729 if(argno >= 0 && argno < Cmd_Argc())
730 return Cmd_Argv(argno);
735 if((cvar = Cvar_FindVar(varname)) && !(cvar->flags & CVAR_PRIVATE))
741 qboolean Cmd_QuoteString(char *out, size_t outlen, const char *in, const char *quoteset)
743 qboolean quote_quot = !!strchr(quoteset, '"');
744 qboolean quote_backslash = !!strchr(quoteset, '\\');
745 qboolean quote_dollar = !!strchr(quoteset, '$');
749 if(*in == '"' && quote_quot)
756 *out++ = '\\'; --outlen;
757 *out++ = '"'; --outlen;
759 else if(*in == '\\' && quote_backslash)
766 *out++ = '\\'; --outlen;
767 *out++ = '\\'; --outlen;
769 else if(*in == '$' && quote_dollar)
776 *out++ = '$'; --outlen;
777 *out++ = '$'; --outlen;
786 *out++ = *in; --outlen;
794 static const char *Cmd_GetCvarValue(const char *var, size_t varlen, cmdalias_t *alias)
796 static char varname[MAX_INPUTLINE];
797 static char varval[MAX_INPUTLINE];
801 if(varlen >= MAX_INPUTLINE)
802 varlen = MAX_INPUTLINE - 1;
803 memcpy(varname, var, varlen);
805 varfunc = strchr(varname, ' ');
821 if(varname[0] == '$')
822 varstr = Cmd_GetDirectCvarValue(Cmd_GetDirectCvarValue(varname + 1, alias, NULL), alias, NULL);
825 qboolean is_multiple = false;
826 // Exception: $* and $n- don't use the quoted form by default
827 varstr = Cmd_GetDirectCvarValue(varname, alias, &is_multiple);
835 Con_Printf("Warning: Could not expand $%s in alias %s\n", varname, alias->name);
837 Con_Printf("Warning: Could not expand $%s\n", varname);
841 if(!varfunc || !strcmp(varfunc, "q")) // note: quoted form is default, use "asis" to override!
843 // quote it so it can be used inside double quotes
844 // we just need to replace " by \", and of course, double backslashes
845 Cmd_QuoteString(varval, sizeof(varval), varstr, "\"\\");
848 else if(!strcmp(varfunc, "asis"))
853 Con_Printf("Unknown variable function %s\n", varfunc);
861 Preprocesses strings and replaces $*, $param#, $cvar accordingly
863 static void Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias ) {
869 // don't crash if there's no room in the outtext buffer
870 if( maxoutlen == 0 ) {
873 maxoutlen--; // because of \0
878 while( *in && outlen < maxoutlen ) {
880 // this is some kind of expansion, see what comes after the $
883 // The console does the following preprocessing:
885 // - $$ is transformed to a single dollar sign.
886 // - $var or ${var} are expanded to the contents of the named cvar,
887 // with quotation marks and backslashes quoted so it can safely
888 // be used inside quotation marks (and it should always be used
890 // - ${var asis} inserts the cvar value as is, without doing this
892 // - prefix the cvar name with a dollar sign to do indirection;
893 // for example, if $x has the value timelimit, ${$x} will return
894 // the value of $timelimit
895 // - when expanding an alias, the special variable name $* refers
896 // to all alias parameters, and a number refers to that numbered
897 // alias parameter, where the name of the alias is $0, the first
898 // parameter is $1 and so on; as a special case, $* inserts all
899 // parameters, without extra quoting, so one can use $* to just
900 // pass all parameters around. All parameters starting from $n
901 // can be referred to as $n- (so $* is equivalent to $1-).
903 // Note: when expanding an alias, cvar expansion is done in the SAME step
904 // as alias expansion so that alias parameters or cvar values containing
905 // dollar signs have no unwanted bad side effects. However, this needs to
906 // be accounted for when writing complex aliases. For example,
907 // alias foo "set x NEW; echo $x"
908 // actually expands to
909 // "set x NEW; echo OLD"
910 // and will print OLD! To work around this, use a second alias:
911 // alias foo "set x NEW; foo2"
912 // alias foo2 "echo $x"
914 // Also note: lines starting with alias are exempt from cvar expansion.
915 // If you want cvar expansion, write "alias" instead:
918 // alias foo "echo $x"
919 // "alias" bar "echo $x"
922 // foo will print 2, because the variable $x will be expanded when the alias
923 // gets expanded. bar will print 1, because the variable $x was expanded
924 // at definition time. foo can be equivalently defined as
926 // "alias" foo "echo $$x"
928 // because at definition time, $$ will get replaced to a single $.
933 } else if(*in == '{') {
934 varlen = strcspn(in + 1, "}");
935 if(in[varlen + 1] == '}')
937 val = Cmd_GetCvarValue(in + 1, varlen, alias);
947 varlen = strspn(in, "*0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-");
948 val = Cmd_GetCvarValue(in, varlen, alias);
953 // insert the cvar value
954 while(*val && outlen < maxoutlen)
955 outtext[outlen++] = *val++;
960 // copy the unexpanded text
961 outtext[outlen++] = '$';
962 while(eat && outlen < maxoutlen)
964 outtext[outlen++] = *in++;
969 outtext[outlen++] = *in++;
979 Called for aliases and fills in the alias into the cbuffer
982 static void Cmd_ExecuteAlias (cmdalias_t *alias)
984 static char buffer[ MAX_INPUTLINE ];
985 static char buffer2[ MAX_INPUTLINE ];
986 Cmd_PreprocessString( alias->value, buffer, sizeof(buffer) - 2, alias );
987 // insert at start of command buffer, so that aliases execute in order
988 // (fixes bug introduced by Black on 20050705)
990 // Note: Cbuf_PreprocessString will be called on this string AGAIN! So we
991 // have to make sure that no second variable expansion takes place, otherwise
992 // alias parameters containing dollar signs can have bad effects.
993 Cmd_QuoteString(buffer2, sizeof(buffer2), buffer, "$");
994 Cbuf_InsertText( buffer2 );
1001 CmdList Added by EvilTypeGuy eviltypeguy@qeradiant.com
1002 Thanks to Matthias "Maddes" Buecher, http://www.inside3d.com/qip/
1006 static void Cmd_List_f (void)
1008 cmd_function_t *cmd;
1009 const char *partial;
1014 partial = Cmd_Argv (1);
1015 len = (int)strlen(partial);
1024 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1026 if (partial && strncmp(partial, cmd->name, len))
1028 Con_Printf("%s : %s\n", cmd->name, cmd->description);
1033 Con_Printf("%i Command%s beginning with \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1035 Con_Printf("%i Command%s\n\n", count, (count > 1) ? "s" : "");
1043 void Cmd_Init (void)
1045 cmd_mempool = Mem_AllocPool("commands", 0, NULL);
1046 // space for commands and script files
1047 cmd_text.data = cmd_text_buf;
1048 cmd_text.maxsize = sizeof(cmd_text_buf);
1049 cmd_text.cursize = 0;
1052 void Cmd_Init_Commands (void)
1055 // register our commands
1057 Cmd_AddCommand ("stuffcmds",Cmd_StuffCmds_f, "execute commandline parameters (must be present in quake.rc script)");
1058 Cmd_AddCommand ("exec",Cmd_Exec_f, "execute a script file");
1059 Cmd_AddCommand ("echo",Cmd_Echo_f, "print a message to the console (useful in scripts)");
1060 Cmd_AddCommand ("alias",Cmd_Alias_f, "create a script function (parameters are passed in as $1 through $9, and $* for all parameters)");
1061 Cmd_AddCommand ("cmd", Cmd_ForwardToServer, "send a console commandline to the server (used by some mods)");
1062 Cmd_AddCommand ("wait", Cmd_Wait_f, "make script execution wait for next rendered frame");
1063 Cmd_AddCommand ("set", Cvar_Set_f, "create or change the value of a console variable");
1064 Cmd_AddCommand ("seta", Cvar_SetA_f, "create or change the value of a console variable that will be saved to config.cfg");
1066 // 2000-01-09 CmdList, CvarList commands By Matthias "Maddes" Buecher
1067 // Added/Modified by EvilTypeGuy eviltypeguy@qeradiant.com
1068 Cmd_AddCommand ("cmdlist", Cmd_List_f, "lists all console commands beginning with the specified prefix");
1069 Cmd_AddCommand ("cvarlist", Cvar_List_f, "lists all console variables beginning with the specified prefix");
1071 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");
1072 Cmd_AddCommand ("cvar_resettodefaults_all", Cvar_ResetToDefaults_All_f, "sets all cvars to their locked default values");
1073 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)");
1074 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)");
1076 Cmd_AddCommand ("cprint", Cmd_Centerprint_f, "print something at the screen center");
1077 Cmd_AddCommand ("defer", Cmd_Defer_f, "execute a command in the future");
1080 // Support Doom3-style Toggle Command
1081 Cmd_AddCommand( "toggle", Cmd_Toggle_f, "toggles a console variable's values (use for more info)");
1089 void Cmd_Shutdown(void)
1091 Mem_FreePool(&cmd_mempool);
1109 const char *Cmd_Argv (int arg)
1111 if (arg >= cmd_argc )
1112 return cmd_null_string;
1113 return cmd_argv[arg];
1121 const char *Cmd_Args (void)
1131 Parses the given string into command line tokens.
1134 // AK: This function should only be called from ExcuteString because the current design is a bit of an hack
1135 static void Cmd_TokenizeString (const char *text)
1144 // skip whitespace up to a /n
1145 while (*text && *text <= ' ' && *text != '\r' && *text != '\n')
1152 if (*text == '\n' || *text == '\r')
1154 // a newline separates commands in the buffer
1155 if (*text == '\r' && text[1] == '\n')
1167 if (!COM_ParseToken_Console(&text))
1170 if (cmd_argc < MAX_ARGS)
1172 l = (int)strlen(com_token) + 1;
1173 if (cmd_tokenizebufferpos + l > CMD_TOKENIZELENGTH)
1175 Con_Printf("Cmd_TokenizeString: ran out of %i character buffer space for command arguements\n", CMD_TOKENIZELENGTH);
1178 memcpy (cmd_tokenizebuffer + cmd_tokenizebufferpos, com_token, l);
1179 cmd_argv[cmd_argc] = cmd_tokenizebuffer + cmd_tokenizebufferpos;
1180 cmd_tokenizebufferpos += l;
1192 void Cmd_AddCommand_WithClientCommand (const char *cmd_name, xcommand_t consolefunction, xcommand_t clientfunction, const char *description)
1194 cmd_function_t *cmd;
1195 cmd_function_t *prev, *current;
1197 // fail if the command is a variable name
1198 if (Cvar_FindVar( cmd_name ))
1200 Con_Printf("Cmd_AddCommand: %s already defined as a var\n", cmd_name);
1204 // fail if the command already exists
1205 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1207 if (!strcmp (cmd_name, cmd->name))
1209 if (consolefunction || clientfunction)
1211 Con_Printf("Cmd_AddCommand: %s already defined\n", cmd_name);
1216 cmd->csqcfunc = true;
1222 cmd = (cmd_function_t *)Mem_Alloc(cmd_mempool, sizeof(cmd_function_t));
1223 cmd->name = cmd_name;
1224 cmd->consolefunction = consolefunction;
1225 cmd->clientfunction = clientfunction;
1226 cmd->description = description;
1227 if(!consolefunction && !clientfunction) //[515]: csqc
1228 cmd->csqcfunc = true;
1229 cmd->next = cmd_functions;
1231 // insert it at the right alphanumeric position
1232 for( prev = NULL, current = cmd_functions ; current && strcmp( current->name, cmd->name ) < 0 ; prev = current, current = current->next )
1237 cmd_functions = cmd;
1239 cmd->next = current;
1242 void Cmd_AddCommand (const char *cmd_name, xcommand_t function, const char *description)
1244 Cmd_AddCommand_WithClientCommand (cmd_name, function, NULL, description);
1252 qboolean Cmd_Exists (const char *cmd_name)
1254 cmd_function_t *cmd;
1256 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1257 if (!strcmp (cmd_name,cmd->name))
1269 const char *Cmd_CompleteCommand (const char *partial)
1271 cmd_function_t *cmd;
1274 len = strlen(partial);
1280 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1281 if (!strncasecmp(partial, cmd->name, len))
1288 Cmd_CompleteCountPossible
1290 New function for tab-completion system
1291 Added by EvilTypeGuy
1292 Thanks to Fett erich@heintz.com
1296 int Cmd_CompleteCountPossible (const char *partial)
1298 cmd_function_t *cmd;
1303 len = strlen(partial);
1308 // Loop through the command list and count all partial matches
1309 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1310 if (!strncasecmp(partial, cmd->name, len))
1317 Cmd_CompleteBuildList
1319 New function for tab-completion system
1320 Added by EvilTypeGuy
1321 Thanks to Fett erich@heintz.com
1325 const char **Cmd_CompleteBuildList (const char *partial)
1327 cmd_function_t *cmd;
1330 size_t sizeofbuf = (Cmd_CompleteCountPossible (partial) + 1) * sizeof (const char *);
1333 len = strlen(partial);
1334 buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1335 // Loop through the alias list and print all matches
1336 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1337 if (!strncasecmp(partial, cmd->name, len))
1338 buf[bpos++] = cmd->name;
1344 // written by LordHavoc
1345 void Cmd_CompleteCommandPrint (const char *partial)
1347 cmd_function_t *cmd;
1348 size_t len = strlen(partial);
1349 // Loop through the command list and print all matches
1350 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1351 if (!strncasecmp(partial, cmd->name, len))
1352 Con_Printf("%s : %s\n", cmd->name, cmd->description);
1358 New function for tab-completion system
1359 Added by EvilTypeGuy
1360 Thanks to Fett erich@heintz.com
1364 const char *Cmd_CompleteAlias (const char *partial)
1369 len = strlen(partial);
1375 for (alias = cmd_alias; alias; alias = alias->next)
1376 if (!strncasecmp(partial, alias->name, len))
1382 // written by LordHavoc
1383 void Cmd_CompleteAliasPrint (const char *partial)
1386 size_t len = strlen(partial);
1387 // Loop through the alias list and print all matches
1388 for (alias = cmd_alias; alias; alias = alias->next)
1389 if (!strncasecmp(partial, alias->name, len))
1390 Con_Printf("%s : %s\n", alias->name, alias->value);
1395 Cmd_CompleteAliasCountPossible
1397 New function for tab-completion system
1398 Added by EvilTypeGuy
1399 Thanks to Fett erich@heintz.com
1403 int Cmd_CompleteAliasCountPossible (const char *partial)
1411 len = strlen(partial);
1416 // Loop through the command list and count all partial matches
1417 for (alias = cmd_alias; alias; alias = alias->next)
1418 if (!strncasecmp(partial, alias->name, len))
1425 Cmd_CompleteAliasBuildList
1427 New function for tab-completion system
1428 Added by EvilTypeGuy
1429 Thanks to Fett erich@heintz.com
1433 const char **Cmd_CompleteAliasBuildList (const char *partial)
1438 size_t sizeofbuf = (Cmd_CompleteAliasCountPossible (partial) + 1) * sizeof (const char *);
1441 len = strlen(partial);
1442 buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1443 // Loop through the alias list and print all matches
1444 for (alias = cmd_alias; alias; alias = alias->next)
1445 if (!strncasecmp(partial, alias->name, len))
1446 buf[bpos++] = alias->name;
1452 void Cmd_ClearCsqcFuncs (void)
1454 cmd_function_t *cmd;
1455 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1456 cmd->csqcfunc = false;
1459 qboolean CL_VM_ConsoleCommand (const char *cmd);
1464 A complete command line has been parsed, so try to execute it
1465 FIXME: lookupnoadd the token to speed search?
1468 void Cmd_ExecuteString (const char *text, cmd_source_t src)
1472 cmd_function_t *cmd;
1475 oldpos = cmd_tokenizebufferpos;
1479 Cmd_TokenizeString (text);
1481 // execute the command line
1484 cmd_tokenizebufferpos = oldpos;
1485 return; // no tokens
1489 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1491 if (!strcasecmp (cmd_argv[0],cmd->name))
1493 if (cmd->csqcfunc && CL_VM_ConsoleCommand (text)) //[515]: csqc
1498 if (cmd->consolefunction)
1499 cmd->consolefunction ();
1500 else if (cmd->clientfunction)
1502 if (cls.state == ca_connected)
1504 // forward remote commands to the server for execution
1505 Cmd_ForwardToServer();
1508 Con_Printf("Can not send command \"%s\", not connected.\n", Cmd_Argv(0));
1511 Con_Printf("Command \"%s\" can not be executed\n", Cmd_Argv(0));
1516 if (cmd->clientfunction)
1518 cmd->clientfunction ();
1519 cmd_tokenizebufferpos = oldpos;
1529 // if it's a client command and no command was found, say so.
1530 if (cmd_source == src_client)
1532 Con_Printf("player \"%s\" tried to %s\n", host_client->name, text);
1533 cmd_tokenizebufferpos = oldpos;
1538 for (a=cmd_alias ; a ; a=a->next)
1540 if (!strcasecmp (cmd_argv[0], a->name))
1542 Cmd_ExecuteAlias(a);
1543 cmd_tokenizebufferpos = oldpos;
1548 if(found) // if the command was hooked and found, all is good
1550 cmd_tokenizebufferpos = oldpos;
1555 if (!Cvar_Command () && host_framecount > 0)
1556 Con_Printf("Unknown command \"%s\"\n", Cmd_Argv(0));
1558 cmd_tokenizebufferpos = oldpos;
1564 Cmd_ForwardStringToServer
1566 Sends an entire command string over to the server, unprocessed
1569 void Cmd_ForwardStringToServer (const char *s)
1572 if (cls.state != ca_connected)
1574 Con_Printf("Can't \"%s\", not connected\n", s);
1581 // LordHavoc: thanks to Fuh for bringing the pure evil of SZ_Print to my
1582 // attention, it has been eradicated from here, its only (former) use in
1583 // all of darkplaces.
1584 if (cls.protocol == PROTOCOL_QUAKEWORLD)
1585 MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
1587 MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
1588 if ((!strncmp(s, "say ", 4) || !strncmp(s, "say_team ", 9)) && cl_locs_enable.integer)
1590 // say/say_team commands can replace % character codes with status info
1593 if (*s == '%' && s[1])
1595 // handle proquake message macros
1599 case 'l': // current location
1600 CL_Locs_FindLocationName(temp, sizeof(temp), cl.movement_origin);
1602 case 'h': // current health
1603 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_HEALTH]);
1605 case 'a': // current armor
1606 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ARMOR]);
1608 case 'x': // current rockets
1609 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ROCKETS]);
1611 case 'c': // current cells
1612 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_CELLS]);
1614 // silly proquake macros
1615 case 'd': // loc at last death
1616 CL_Locs_FindLocationName(temp, sizeof(temp), cl.lastdeathorigin);
1618 case 't': // current time
1619 dpsnprintf(temp, sizeof(temp), "%.0f:%.0f", floor(cl.time / 60), cl.time - floor(cl.time / 60) * 60);
1621 case 'r': // rocket launcher status ("I have RL", "I need rockets", "I need RL")
1622 if (!(cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER))
1623 dpsnprintf(temp, sizeof(temp), "I need RL");
1624 else if (!cl.stats[STAT_ROCKETS])
1625 dpsnprintf(temp, sizeof(temp), "I need rockets");
1627 dpsnprintf(temp, sizeof(temp), "I have RL");
1629 case 'p': // powerup status (outputs "quad" "pent" and "eyes" according to status)
1630 if (cl.stats[STAT_ITEMS] & IT_QUAD)
1633 strlcat(temp, " ", sizeof(temp));
1634 strlcat(temp, "quad", sizeof(temp));
1636 if (cl.stats[STAT_ITEMS] & IT_INVULNERABILITY)
1639 strlcat(temp, " ", sizeof(temp));
1640 strlcat(temp, "pent", sizeof(temp));
1642 if (cl.stats[STAT_ITEMS] & IT_INVISIBILITY)
1645 strlcat(temp, " ", sizeof(temp));
1646 strlcat(temp, "eyes", sizeof(temp));
1649 case 'w': // weapon status (outputs "SSG:NG:SNG:GL:RL:LG" with the text between : characters omitted if you lack the weapon)
1650 if (cl.stats[STAT_ITEMS] & IT_SUPER_SHOTGUN)
1651 strlcat(temp, "SSG", sizeof(temp));
1652 strlcat(temp, ":", sizeof(temp));
1653 if (cl.stats[STAT_ITEMS] & IT_NAILGUN)
1654 strlcat(temp, "NG", sizeof(temp));
1655 strlcat(temp, ":", sizeof(temp));
1656 if (cl.stats[STAT_ITEMS] & IT_SUPER_NAILGUN)
1657 strlcat(temp, "SNG", sizeof(temp));
1658 strlcat(temp, ":", sizeof(temp));
1659 if (cl.stats[STAT_ITEMS] & IT_GRENADE_LAUNCHER)
1660 strlcat(temp, "GL", sizeof(temp));
1661 strlcat(temp, ":", sizeof(temp));
1662 if (cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER)
1663 strlcat(temp, "RL", sizeof(temp));
1664 strlcat(temp, ":", sizeof(temp));
1665 if (cl.stats[STAT_ITEMS] & IT_LIGHTNING)
1666 strlcat(temp, "LG", sizeof(temp));
1669 // not a recognized macro, print it as-is...
1675 // write the resulting text
1676 SZ_Write(&cls.netcon->message, (unsigned char *)temp, strlen(temp));
1680 MSG_WriteByte(&cls.netcon->message, *s);
1683 MSG_WriteByte(&cls.netcon->message, 0);
1685 else // any other command is passed on as-is
1686 SZ_Write(&cls.netcon->message, (const unsigned char *)s, (int)strlen(s) + 1);
1693 Sends the entire command line over to the server
1696 void Cmd_ForwardToServer (void)
1699 if (!strcasecmp(Cmd_Argv(0), "cmd"))
1701 // we want to strip off "cmd", so just send the args
1702 s = Cmd_Argc() > 1 ? Cmd_Args() : "";
1706 // we need to keep the command name, so send Cmd_Argv(0), a space and then Cmd_Args()
1707 s = va("%s %s", Cmd_Argv(0), Cmd_Argc() > 1 ? Cmd_Args() : "");
1709 // don't send an empty forward message if the user tries "cmd" by itself
1712 Cmd_ForwardStringToServer(s);
1720 Returns the position (1 to argc-1) in the command's argument list
1721 where the given parameter apears, or 0 if not present
1725 int Cmd_CheckParm (const char *parm)
1731 Con_Printf ("Cmd_CheckParm: NULL");
1735 for (i = 1; i < Cmd_Argc (); i++)
1736 if (!strcasecmp (parm, Cmd_Argv (i)))