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 // div0: increased this from 128k to 640k which ought to be enough for anyone
29 #define CMDBUFSIZE 655360
30 // maximum number of parameters to a command
32 // maximum tokenizable commandline length (counting NUL terminations)
33 #define CMD_TOKENIZELENGTH (MAX_INPUTLINE + MAX_ARGS)
35 typedef struct cmdalias_s
37 struct cmdalias_s *next;
38 char name[MAX_ALIAS_NAME];
42 static cmdalias_t *cmd_alias;
44 static qboolean cmd_wait;
46 static mempool_t *cmd_mempool;
48 static char cmd_tokenizebuffer[CMD_TOKENIZELENGTH];
49 static int cmd_tokenizebufferpos = 0;
51 //=============================================================================
57 Causes execution of the remainder of the command buffer to be delayed until
58 next frame. This allows commands like:
59 bind g "impulse 5 ; +attack ; wait ; -attack ; impulse 2"
62 static void Cmd_Wait_f (void)
67 typedef struct cmddeferred_s
69 struct cmddeferred_s *next;
74 static cmddeferred_t *cmd_deferred_list = NULL;
80 Cause a command to be executed after a delay.
83 static void Cmd_Defer_f (void)
87 double time = Sys_DoubleTime();
88 cmddeferred_t *next = cmd_deferred_list;
90 Con_Printf("No commands are pending.\n");
93 Con_Printf("-> In %9.2f: %s\n", next->time-time, next->value);
96 } else if(Cmd_Argc() == 2 && !strcasecmp("clear", Cmd_Argv(1)))
98 while(cmd_deferred_list)
100 cmddeferred_t *cmd = cmd_deferred_list;
101 cmd_deferred_list = cmd->next;
102 Mem_Free(cmd->value);
105 } else if(Cmd_Argc() == 3)
107 const char *value = Cmd_Argv(2);
108 cmddeferred_t *defcmd = (cmddeferred_t*)Mem_Alloc(tempmempool, sizeof(*defcmd));
109 size_t len = strlen(value);
111 defcmd->time = Sys_DoubleTime() + atof(Cmd_Argv(1));
112 defcmd->value = (char*)Mem_Alloc(tempmempool, len+1);
113 memcpy(defcmd->value, value, len+1);
116 if(cmd_deferred_list)
118 cmddeferred_t *next = cmd_deferred_list;
123 cmd_deferred_list = defcmd;
124 /* Stupid me... this changes the order... so commands with the same delay go blub :S
125 defcmd->next = cmd_deferred_list;
126 cmd_deferred_list = defcmd;*/
128 Con_Printf("usage: defer <seconds> <command>\n"
138 Print something to the center of the screen using SCR_Centerprint
141 static void Cmd_Centerprint_f (void)
143 char msg[MAX_INPUTLINE];
144 unsigned int i, c, p;
148 strlcpy(msg, Cmd_Argv(1), sizeof(msg));
149 for(i = 2; i < c; ++i)
151 strlcat(msg, " ", sizeof(msg));
152 strlcat(msg, Cmd_Argv(i), sizeof(msg));
155 for(p = 0, i = 0; i < c; ++i)
161 else if(msg[i+1] == '\\')
173 SCR_CenterPrint(msg);
178 =============================================================================
182 =============================================================================
185 static sizebuf_t cmd_text;
186 static unsigned char cmd_text_buf[CMDBUFSIZE];
192 Adds command text at the end of the buffer
195 void Cbuf_AddText (const char *text)
199 l = (int)strlen (text);
201 if (cmd_text.cursize + l >= cmd_text.maxsize)
203 Con_Print("Cbuf_AddText: overflow\n");
207 SZ_Write (&cmd_text, (const unsigned char *)text, (int)strlen (text));
215 Adds command text immediately after the current command
216 Adds a \n to the text
217 FIXME: actually change the command buffer to do less copying
220 void Cbuf_InsertText (const char *text)
225 // copy off any commands still remaining in the exec buffer
226 templen = cmd_text.cursize;
229 temp = (char *)Mem_Alloc (tempmempool, templen);
230 memcpy (temp, cmd_text.data, templen);
231 SZ_Clear (&cmd_text);
236 // add the entire text of the file
239 // add the copied off data
242 SZ_Write (&cmd_text, (const unsigned char *)temp, templen);
249 Cbuf_Execute_Deferred --blub
252 void Cbuf_Execute_Deferred (void)
254 cmddeferred_t *cmd, *prev;
255 double time = Sys_DoubleTime();
257 cmd = cmd_deferred_list;
260 if(cmd->time <= time)
262 Cbuf_AddText(cmd->value);
264 Mem_Free(cmd->value);
267 prev->next = cmd->next;
271 cmd_deferred_list = cmd->next;
273 cmd = cmd_deferred_list;
287 static void Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias );
288 void Cbuf_Execute (void)
292 char line[MAX_INPUTLINE];
293 char preprocessed[MAX_INPUTLINE];
295 qboolean quotes, comment;
297 // LordHavoc: making sure the tokenizebuffer doesn't get filled up by repeated crashes
298 cmd_tokenizebufferpos = 0;
300 Cbuf_Execute_Deferred();
301 while (cmd_text.cursize)
303 // find a \n or ; line break
304 text = (char *)cmd_text.data;
308 for (i=0 ; i < cmd_text.cursize ; i++)
317 // make sure i doesn't get > cursize which causes a negative
318 // size in memmove, which is fatal --blub
319 if (i < (cmd_text.cursize-1) && (text[i] == '\\' && (text[i+1] == '"' || text[i+1] == '\\')))
324 if(text[i] == '/' && text[i + 1] == '/')
327 break; // don't break if inside a quoted string or comment
331 if (text[i] == '\r' || text[i] == '\n')
335 // better than CRASHING on overlong input lines that may SOMEHOW enter the buffer
336 if(i >= MAX_INPUTLINE)
338 Con_Printf("Warning: console input buffer had an overlong line. Ignored.\n");
343 memcpy (line, text, i);
347 // delete the text from the command buffer and move remaining commands down
348 // this is necessary because commands (exec, alias) can insert data at the
349 // beginning of the text buffer
351 if (i == cmd_text.cursize)
352 cmd_text.cursize = 0;
356 cmd_text.cursize -= i;
357 memmove (cmd_text.data, text+i, cmd_text.cursize);
360 // execute the command line
361 firstchar = line + strspn(line, " \t");
363 (strncmp(firstchar, "alias", 5) || (firstchar[5] != ' ' && firstchar[5] != '\t'))
365 (strncmp(firstchar, "bind", 4) || (firstchar[4] != ' ' && firstchar[4] != '\t'))
367 (strncmp(firstchar, "in_bind", 7) || (firstchar[7] != ' ' && firstchar[7] != '\t'))
370 Cmd_PreprocessString( line, preprocessed, sizeof(preprocessed), NULL );
371 Cmd_ExecuteString (preprocessed, src_command);
375 Cmd_ExecuteString (line, src_command);
379 { // skip out while text still remains in buffer, leaving it
388 ==============================================================================
392 ==============================================================================
399 Adds command line parameters as script statements
400 Commands lead with a +, and continue until a - or another +
401 quake +prog jctest.qp +cmd amlev1
402 quake -nosound +cmd amlev1
405 qboolean host_stuffcmdsrun = false;
406 void Cmd_StuffCmds_f (void)
409 // this is for all commandline options combined (and is bounds checked)
410 char build[MAX_INPUTLINE];
412 if (Cmd_Argc () != 1)
414 Con_Print("stuffcmds : execute command line parameters\n");
418 // no reason to run the commandline arguments twice
419 if (host_stuffcmdsrun)
422 host_stuffcmdsrun = true;
425 for (i = 0;i < com_argc;i++)
427 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)
430 while (com_argv[i][j])
431 build[l++] = com_argv[i][j++];
433 for (;i < com_argc;i++)
437 if ((com_argv[i][0] == '+' || com_argv[i][0] == '-') && (com_argv[i][1] < '0' || com_argv[i][1] > '9'))
439 if (l + strlen(com_argv[i]) + 4 > sizeof(build) - 1)
442 if (strchr(com_argv[i], ' '))
444 for (j = 0;com_argv[i][j];j++)
445 build[l++] = com_argv[i][j];
446 if (strchr(com_argv[i], ' '))
453 // now terminate the combined string and prepend it to the command buffer
454 // we already reserved space for the terminator
456 Cbuf_InsertText (build);
465 static void Cmd_Exec_f (void)
469 if (Cmd_Argc () != 2)
471 Con_Print("exec <filename> : execute a script file\n");
475 f = (char *)FS_LoadFile (Cmd_Argv(1), tempmempool, false, NULL);
478 Con_Printf("couldn't exec %s\n",Cmd_Argv(1));
481 Con_Printf("execing %s\n",Cmd_Argv(1));
483 // if executing default.cfg for the first time, lock the cvar defaults
484 // it may seem backwards to insert this text BEFORE the default.cfg
485 // but Cbuf_InsertText inserts before, so this actually ends up after it.
486 if (!strcmp(Cmd_Argv(1), "default.cfg"))
487 Cbuf_InsertText("\ncvar_lockdefaults\n");
489 // insert newline after the text to make sure the last line is terminated (some text editors omit the trailing newline)
490 // (note: insertion order here is backwards from execution order, so this adds it after the text, by calling it before...)
491 Cbuf_InsertText ("\n");
501 Just prints the rest of the line to the console
504 static void Cmd_Echo_f (void)
508 for (i=1 ; i<Cmd_Argc() ; i++)
509 Con_Printf("%s ",Cmd_Argv(i));
514 // Support Doom3-style Toggle Console Command
519 Toggles a specified console variable amongst the values specified (default is 0 and 1)
522 static void Cmd_Toggle_f(void)
524 // Acquire Number of Arguments
525 int nNumArgs = Cmd_Argc();
528 // No Arguments Specified; Print Usage
529 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");
531 { // Correct Arguments Specified
532 // Acquire Potential CVar
533 cvar_t* cvCVar = Cvar_FindVar( Cmd_Argv(1) );
540 Cvar_SetValueQuick(cvCVar, 0);
542 Cvar_SetValueQuick(cvCVar, 1);
546 { // 0 and Specified Usage
547 if(cvCVar->integer == atoi(Cmd_Argv(2) ) )
548 // CVar is Specified Value; // Reset to 0
549 Cvar_SetValueQuick(cvCVar, 0);
551 if(cvCVar->integer == 0)
552 // CVar is 0; Specify Value
553 Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
555 // CVar does not match; Reset to 0
556 Cvar_SetValueQuick(cvCVar, 0);
559 { // Variable Values Specified
563 for(nCnt = 2; nCnt < nNumArgs; nCnt++)
564 { // Cycle through Values
565 if( strcmp(cvCVar->string, Cmd_Argv(nCnt) ) == 0)
566 { // Current Value Located; Increment to Next
567 if( (nCnt + 1) == nNumArgs)
568 // Max Value Reached; Reset
569 Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
572 Cvar_SetQuick(cvCVar, Cmd_Argv(nCnt + 1) );
581 // Value not Found; Reset to Original
582 Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
588 Con_Printf("ERROR : CVar '%s' not found\n", Cmd_Argv(1) );
597 Creates a new command that executes a command string (possibly ; seperated)
600 static void Cmd_Alias_f (void)
603 char cmd[MAX_INPUTLINE];
610 Con_Print("Current alias commands:\n");
611 for (a = cmd_alias ; a ; a=a->next)
612 Con_Printf("%s : %s", a->name, a->value);
617 if (strlen(s) >= MAX_ALIAS_NAME)
619 Con_Print("Alias name is too long\n");
623 // if the alias already exists, reuse it
624 for (a = cmd_alias ; a ; a=a->next)
626 if (!strcmp(s, a->name))
635 cmdalias_t *prev, *current;
637 a = (cmdalias_t *)Z_Malloc (sizeof(cmdalias_t));
638 strlcpy (a->name, s, sizeof (a->name));
639 // insert it at the right alphanumeric position
640 for( prev = NULL, current = cmd_alias ; current && strcmp( current->name, a->name ) < 0 ; prev = current, current = current->next )
651 // copy the rest of the command line
652 cmd[0] = 0; // start out with a null string
654 for (i=2 ; i< c ; i++)
656 strlcat (cmd, Cmd_Argv(i), sizeof (cmd));
658 strlcat (cmd, " ", sizeof (cmd));
660 strlcat (cmd, "\n", sizeof (cmd));
662 alloclen = strlen (cmd) + 1;
664 cmd[alloclen - 2] = '\n'; // to make sure a newline is appended even if too long
665 a->value = (char *)Z_Malloc (alloclen);
666 memcpy (a->value, cmd, alloclen);
670 =============================================================================
674 =============================================================================
677 typedef struct cmd_function_s
679 struct cmd_function_s *next;
681 const char *description;
682 xcommand_t consolefunction;
683 xcommand_t clientfunction;
688 static const char *cmd_argv[MAX_ARGS];
689 static const char *cmd_null_string = "";
690 static const char *cmd_args;
691 cmd_source_t cmd_source;
694 static cmd_function_t *cmd_functions; // possible commands to execute
696 static const char *Cmd_GetDirectCvarValue(const char *varname, cmdalias_t *alias, qboolean *is_multiple)
703 *is_multiple = false;
705 if(!varname || !*varname)
710 if(!strcmp(varname, "*"))
716 else if(varname[strlen(varname) - 1] == '-')
718 argno = strtol(varname, &endptr, 10);
719 if(endptr == varname + strlen(varname) - 1)
721 // whole string is a number, apart from the -
722 const char *p = Cmd_Args();
723 for(; argno > 1; --argno)
724 if(!COM_ParseToken_Console(&p))
731 // kill pre-argument whitespace
732 for (;*p && ISWHITESPACE(*p);p++)
741 argno = strtol(varname, &endptr, 10);
744 // whole string is a number
745 // NOTE: we already made sure we don't have an empty cvar name!
746 if(argno >= 0 && argno < Cmd_Argc())
747 return Cmd_Argv(argno);
752 if((cvar = Cvar_FindVar(varname)) && !(cvar->flags & CVAR_PRIVATE))
758 qboolean Cmd_QuoteString(char *out, size_t outlen, const char *in, const char *quoteset)
760 qboolean quote_quot = !!strchr(quoteset, '"');
761 qboolean quote_backslash = !!strchr(quoteset, '\\');
762 qboolean quote_dollar = !!strchr(quoteset, '$');
766 if(*in == '"' && quote_quot)
773 *out++ = '\\'; --outlen;
774 *out++ = '"'; --outlen;
776 else if(*in == '\\' && quote_backslash)
783 *out++ = '\\'; --outlen;
784 *out++ = '\\'; --outlen;
786 else if(*in == '$' && quote_dollar)
793 *out++ = '$'; --outlen;
794 *out++ = '$'; --outlen;
803 *out++ = *in; --outlen;
811 static const char *Cmd_GetCvarValue(const char *var, size_t varlen, cmdalias_t *alias)
813 static char varname[MAX_INPUTLINE];
814 static char varval[MAX_INPUTLINE];
818 if(varlen >= MAX_INPUTLINE)
819 varlen = MAX_INPUTLINE - 1;
820 memcpy(varname, var, varlen);
822 varfunc = strchr(varname, ' ');
838 if(varname[0] == '$')
839 varstr = Cmd_GetDirectCvarValue(Cmd_GetDirectCvarValue(varname + 1, alias, NULL), alias, NULL);
842 qboolean is_multiple = false;
843 // Exception: $* and $n- don't use the quoted form by default
844 varstr = Cmd_GetDirectCvarValue(varname, alias, &is_multiple);
853 Con_Printf("Warning: Could not expand $%s in alias %s\n", varname, alias->name);
855 Con_Printf("Warning: Could not expand $%s\n", varname);
859 if(!varfunc || !strcmp(varfunc, "q")) // note: quoted form is default, use "asis" to override!
861 // quote it so it can be used inside double quotes
862 // we just need to replace " by \", and of course, double backslashes
863 Cmd_QuoteString(varval, sizeof(varval), varstr, "\"\\");
866 else if(!strcmp(varfunc, "asis"))
871 Con_Printf("Unknown variable function %s\n", varfunc);
879 Preprocesses strings and replaces $*, $param#, $cvar accordingly
881 static void Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias ) {
887 // don't crash if there's no room in the outtext buffer
888 if( maxoutlen == 0 ) {
891 maxoutlen--; // because of \0
896 while( *in && outlen < maxoutlen ) {
898 // this is some kind of expansion, see what comes after the $
901 // The console does the following preprocessing:
903 // - $$ is transformed to a single dollar sign.
904 // - $var or ${var} are expanded to the contents of the named cvar,
905 // with quotation marks and backslashes quoted so it can safely
906 // be used inside quotation marks (and it should always be used
908 // - ${var asis} inserts the cvar value as is, without doing this
910 // - prefix the cvar name with a dollar sign to do indirection;
911 // for example, if $x has the value timelimit, ${$x} will return
912 // the value of $timelimit
913 // - when expanding an alias, the special variable name $* refers
914 // to all alias parameters, and a number refers to that numbered
915 // alias parameter, where the name of the alias is $0, the first
916 // parameter is $1 and so on; as a special case, $* inserts all
917 // parameters, without extra quoting, so one can use $* to just
918 // pass all parameters around. All parameters starting from $n
919 // can be referred to as $n- (so $* is equivalent to $1-).
921 // Note: when expanding an alias, cvar expansion is done in the SAME step
922 // as alias expansion so that alias parameters or cvar values containing
923 // dollar signs have no unwanted bad side effects. However, this needs to
924 // be accounted for when writing complex aliases. For example,
925 // alias foo "set x NEW; echo $x"
926 // actually expands to
927 // "set x NEW; echo OLD"
928 // and will print OLD! To work around this, use a second alias:
929 // alias foo "set x NEW; foo2"
930 // alias foo2 "echo $x"
932 // Also note: lines starting with alias are exempt from cvar expansion.
933 // If you want cvar expansion, write "alias" instead:
936 // alias foo "echo $x"
937 // "alias" bar "echo $x"
940 // foo will print 2, because the variable $x will be expanded when the alias
941 // gets expanded. bar will print 1, because the variable $x was expanded
942 // at definition time. foo can be equivalently defined as
944 // "alias" foo "echo $$x"
946 // because at definition time, $$ will get replaced to a single $.
951 } else if(*in == '{') {
952 varlen = strcspn(in + 1, "}");
953 if(in[varlen + 1] == '}')
955 val = Cmd_GetCvarValue(in + 1, varlen, alias);
965 varlen = strspn(in, "*0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-");
966 val = Cmd_GetCvarValue(in, varlen, alias);
971 // insert the cvar value
972 while(*val && outlen < maxoutlen)
973 outtext[outlen++] = *val++;
978 // copy the unexpanded text
979 outtext[outlen++] = '$';
980 while(eat && outlen < maxoutlen)
982 outtext[outlen++] = *in++;
987 outtext[outlen++] = *in++;
997 Called for aliases and fills in the alias into the cbuffer
1000 static void Cmd_ExecuteAlias (cmdalias_t *alias)
1002 static char buffer[ MAX_INPUTLINE ];
1003 static char buffer2[ MAX_INPUTLINE ];
1004 Cmd_PreprocessString( alias->value, buffer, sizeof(buffer) - 2, alias );
1005 // insert at start of command buffer, so that aliases execute in order
1006 // (fixes bug introduced by Black on 20050705)
1008 // Note: Cbuf_PreprocessString will be called on this string AGAIN! So we
1009 // have to make sure that no second variable expansion takes place, otherwise
1010 // alias parameters containing dollar signs can have bad effects.
1011 Cmd_QuoteString(buffer2, sizeof(buffer2), buffer, "$");
1012 Cbuf_InsertText( buffer2 );
1019 CmdList Added by EvilTypeGuy eviltypeguy@qeradiant.com
1020 Thanks to Matthias "Maddes" Buecher, http://www.inside3d.com/qip/
1024 static void Cmd_List_f (void)
1026 cmd_function_t *cmd;
1027 const char *partial;
1034 partial = Cmd_Argv (1);
1035 len = strlen(partial);
1043 ispattern = partial && (strchr(partial, '*') || strchr(partial, '?'));
1046 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1048 if (partial && (ispattern ? !matchpattern_with_separator(cmd->name, partial, false, "", false) : strncmp(partial, cmd->name, len)))
1050 Con_Printf("%s : %s\n", cmd->name, cmd->description);
1057 Con_Printf("%i Command%s matching \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1059 Con_Printf("%i Command%s beginning with \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1062 Con_Printf("%i Command%s\n\n", count, (count > 1) ? "s" : "");
1065 static void Cmd_Apropos_f(void)
1067 cmd_function_t *cmd;
1070 const char *partial;
1077 partial = Cmd_Args();
1078 len = strlen(partial);
1082 Con_Printf("usage: apropos <string>\n");
1086 ispattern = partial && (strchr(partial, '*') || strchr(partial, '?'));
1089 partial = va("*%s*", partial);
1094 for (cvar = cvar_vars; cvar; cvar = cvar->next)
1096 if (!matchpattern_with_separator(cvar->name, partial, true, "", false))
1097 if (!matchpattern_with_separator(cvar->description, partial, true, "", false))
1099 Con_Printf ("cvar ^3%s^7 is \"%s\" [\"%s\"] %s\n", cvar->name, cvar->string, cvar->defstring, cvar->description);
1102 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1104 if (!matchpattern_with_separator(cmd->name, partial, true, "", false))
1105 if (!matchpattern_with_separator(cmd->description, partial, true, "", false))
1107 Con_Printf("command ^2%s^7: %s\n", cmd->name, cmd->description);
1110 for (alias = cmd_alias; alias; alias = alias->next)
1112 if (!matchpattern_with_separator(alias->name, partial, true, "", false))
1113 if (!matchpattern_with_separator(alias->value, partial, true, "", false))
1115 Con_Printf("alias ^5%s^7: %s", alias->name, alias->value);
1118 Con_Printf("%i result%s\n\n", count, (count > 1) ? "s" : "");
1126 void Cmd_Init (void)
1128 cmd_mempool = Mem_AllocPool("commands", 0, NULL);
1129 // space for commands and script files
1130 cmd_text.data = cmd_text_buf;
1131 cmd_text.maxsize = sizeof(cmd_text_buf);
1132 cmd_text.cursize = 0;
1135 void Cmd_Init_Commands (void)
1138 // register our commands
1140 Cmd_AddCommand ("stuffcmds",Cmd_StuffCmds_f, "execute commandline parameters (must be present in quake.rc script)");
1141 Cmd_AddCommand ("exec",Cmd_Exec_f, "execute a script file");
1142 Cmd_AddCommand ("echo",Cmd_Echo_f, "print a message to the console (useful in scripts)");
1143 Cmd_AddCommand ("alias",Cmd_Alias_f, "create a script function (parameters are passed in as $1 through $9, and $* for all parameters)");
1144 Cmd_AddCommand ("cmd", Cmd_ForwardToServer, "send a console commandline to the server (used by some mods)");
1145 Cmd_AddCommand ("wait", Cmd_Wait_f, "make script execution wait for next rendered frame");
1146 Cmd_AddCommand ("set", Cvar_Set_f, "create or change the value of a console variable");
1147 Cmd_AddCommand ("seta", Cvar_SetA_f, "create or change the value of a console variable that will be saved to config.cfg");
1149 // 2000-01-09 CmdList, CvarList commands By Matthias "Maddes" Buecher
1150 // Added/Modified by EvilTypeGuy eviltypeguy@qeradiant.com
1151 Cmd_AddCommand ("cmdlist", Cmd_List_f, "lists all console commands beginning with the specified prefix");
1152 Cmd_AddCommand ("cvarlist", Cvar_List_f, "lists all console variables beginning with the specified prefix");
1153 Cmd_AddCommand ("apropos", Cmd_Apropos_f, "lists all console variables/commands/aliases containing the specified string in the name or description");
1155 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");
1156 Cmd_AddCommand ("cvar_resettodefaults_all", Cvar_ResetToDefaults_All_f, "sets all cvars to their locked default values");
1157 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)");
1158 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)");
1160 Cmd_AddCommand ("cprint", Cmd_Centerprint_f, "print something at the screen center");
1161 Cmd_AddCommand ("defer", Cmd_Defer_f, "execute a command in the future");
1164 // Support Doom3-style Toggle Command
1165 Cmd_AddCommand( "toggle", Cmd_Toggle_f, "toggles a console variable's values (use for more info)");
1173 void Cmd_Shutdown(void)
1175 Mem_FreePool(&cmd_mempool);
1193 const char *Cmd_Argv (int arg)
1195 if (arg >= cmd_argc )
1196 return cmd_null_string;
1197 return cmd_argv[arg];
1205 const char *Cmd_Args (void)
1215 Parses the given string into command line tokens.
1218 // AK: This function should only be called from ExcuteString because the current design is a bit of an hack
1219 static void Cmd_TokenizeString (const char *text)
1228 // skip whitespace up to a /n
1229 while (*text && ISWHITESPACE(*text) && *text != '\r' && *text != '\n')
1236 if (*text == '\n' || *text == '\r')
1238 // a newline separates commands in the buffer
1239 if (*text == '\r' && text[1] == '\n')
1251 if (!COM_ParseToken_Console(&text))
1254 if (cmd_argc < MAX_ARGS)
1256 l = (int)strlen(com_token) + 1;
1257 if (cmd_tokenizebufferpos + l > CMD_TOKENIZELENGTH)
1259 Con_Printf("Cmd_TokenizeString: ran out of %i character buffer space for command arguements\n", CMD_TOKENIZELENGTH);
1262 memcpy (cmd_tokenizebuffer + cmd_tokenizebufferpos, com_token, l);
1263 cmd_argv[cmd_argc] = cmd_tokenizebuffer + cmd_tokenizebufferpos;
1264 cmd_tokenizebufferpos += l;
1276 void Cmd_AddCommand_WithClientCommand (const char *cmd_name, xcommand_t consolefunction, xcommand_t clientfunction, const char *description)
1278 cmd_function_t *cmd;
1279 cmd_function_t *prev, *current;
1281 // fail if the command is a variable name
1282 if (Cvar_FindVar( cmd_name ))
1284 Con_Printf("Cmd_AddCommand: %s already defined as a var\n", cmd_name);
1288 // fail if the command already exists
1289 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1291 if (!strcmp (cmd_name, cmd->name))
1293 if (consolefunction || clientfunction)
1295 Con_Printf("Cmd_AddCommand: %s already defined\n", cmd_name);
1300 cmd->csqcfunc = true;
1306 cmd = (cmd_function_t *)Mem_Alloc(cmd_mempool, sizeof(cmd_function_t));
1307 cmd->name = cmd_name;
1308 cmd->consolefunction = consolefunction;
1309 cmd->clientfunction = clientfunction;
1310 cmd->description = description;
1311 if(!consolefunction && !clientfunction) //[515]: csqc
1312 cmd->csqcfunc = true;
1313 cmd->next = cmd_functions;
1315 // insert it at the right alphanumeric position
1316 for( prev = NULL, current = cmd_functions ; current && strcmp( current->name, cmd->name ) < 0 ; prev = current, current = current->next )
1321 cmd_functions = cmd;
1323 cmd->next = current;
1326 void Cmd_AddCommand (const char *cmd_name, xcommand_t function, const char *description)
1328 Cmd_AddCommand_WithClientCommand (cmd_name, function, NULL, description);
1336 qboolean Cmd_Exists (const char *cmd_name)
1338 cmd_function_t *cmd;
1340 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1341 if (!strcmp (cmd_name,cmd->name))
1353 const char *Cmd_CompleteCommand (const char *partial)
1355 cmd_function_t *cmd;
1358 len = strlen(partial);
1364 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1365 if (!strncasecmp(partial, cmd->name, len))
1372 Cmd_CompleteCountPossible
1374 New function for tab-completion system
1375 Added by EvilTypeGuy
1376 Thanks to Fett erich@heintz.com
1380 int Cmd_CompleteCountPossible (const char *partial)
1382 cmd_function_t *cmd;
1387 len = strlen(partial);
1392 // Loop through the command list and count all partial matches
1393 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1394 if (!strncasecmp(partial, cmd->name, len))
1401 Cmd_CompleteBuildList
1403 New function for tab-completion system
1404 Added by EvilTypeGuy
1405 Thanks to Fett erich@heintz.com
1409 const char **Cmd_CompleteBuildList (const char *partial)
1411 cmd_function_t *cmd;
1414 size_t sizeofbuf = (Cmd_CompleteCountPossible (partial) + 1) * sizeof (const char *);
1417 len = strlen(partial);
1418 buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1419 // Loop through the alias list and print all matches
1420 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1421 if (!strncasecmp(partial, cmd->name, len))
1422 buf[bpos++] = cmd->name;
1428 // written by LordHavoc
1429 void Cmd_CompleteCommandPrint (const char *partial)
1431 cmd_function_t *cmd;
1432 size_t len = strlen(partial);
1433 // Loop through the command list and print all matches
1434 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1435 if (!strncasecmp(partial, cmd->name, len))
1436 Con_Printf("^2%s^7: %s\n", cmd->name, cmd->description);
1442 New function for tab-completion system
1443 Added by EvilTypeGuy
1444 Thanks to Fett erich@heintz.com
1448 const char *Cmd_CompleteAlias (const char *partial)
1453 len = strlen(partial);
1459 for (alias = cmd_alias; alias; alias = alias->next)
1460 if (!strncasecmp(partial, alias->name, len))
1466 // written by LordHavoc
1467 void Cmd_CompleteAliasPrint (const char *partial)
1470 size_t len = strlen(partial);
1471 // Loop through the alias list and print all matches
1472 for (alias = cmd_alias; alias; alias = alias->next)
1473 if (!strncasecmp(partial, alias->name, len))
1474 Con_Printf("^5%s^7: %s", alias->name, alias->value);
1479 Cmd_CompleteAliasCountPossible
1481 New function for tab-completion system
1482 Added by EvilTypeGuy
1483 Thanks to Fett erich@heintz.com
1487 int Cmd_CompleteAliasCountPossible (const char *partial)
1495 len = strlen(partial);
1500 // Loop through the command list and count all partial matches
1501 for (alias = cmd_alias; alias; alias = alias->next)
1502 if (!strncasecmp(partial, alias->name, len))
1509 Cmd_CompleteAliasBuildList
1511 New function for tab-completion system
1512 Added by EvilTypeGuy
1513 Thanks to Fett erich@heintz.com
1517 const char **Cmd_CompleteAliasBuildList (const char *partial)
1522 size_t sizeofbuf = (Cmd_CompleteAliasCountPossible (partial) + 1) * sizeof (const char *);
1525 len = strlen(partial);
1526 buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1527 // Loop through the alias list and print all matches
1528 for (alias = cmd_alias; alias; alias = alias->next)
1529 if (!strncasecmp(partial, alias->name, len))
1530 buf[bpos++] = alias->name;
1536 void Cmd_ClearCsqcFuncs (void)
1538 cmd_function_t *cmd;
1539 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1540 cmd->csqcfunc = false;
1543 qboolean CL_VM_ConsoleCommand (const char *cmd);
1548 A complete command line has been parsed, so try to execute it
1549 FIXME: lookupnoadd the token to speed search?
1552 void Cmd_ExecuteString (const char *text, cmd_source_t src)
1556 cmd_function_t *cmd;
1559 oldpos = cmd_tokenizebufferpos;
1563 Cmd_TokenizeString (text);
1565 // execute the command line
1568 cmd_tokenizebufferpos = oldpos;
1569 return; // no tokens
1573 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1575 if (!strcasecmp (cmd_argv[0],cmd->name))
1577 if (cmd->csqcfunc && CL_VM_ConsoleCommand (text)) //[515]: csqc
1582 if (cmd->consolefunction)
1583 cmd->consolefunction ();
1584 else if (cmd->clientfunction)
1586 if (cls.state == ca_connected)
1588 // forward remote commands to the server for execution
1589 Cmd_ForwardToServer();
1592 Con_Printf("Can not send command \"%s\", not connected.\n", Cmd_Argv(0));
1595 Con_Printf("Command \"%s\" can not be executed\n", Cmd_Argv(0));
1600 if (cmd->clientfunction)
1602 cmd->clientfunction ();
1603 cmd_tokenizebufferpos = oldpos;
1613 // if it's a client command and no command was found, say so.
1614 if (cmd_source == src_client)
1616 Con_Printf("player \"%s\" tried to %s\n", host_client->name, text);
1617 cmd_tokenizebufferpos = oldpos;
1622 for (a=cmd_alias ; a ; a=a->next)
1624 if (!strcasecmp (cmd_argv[0], a->name))
1626 Cmd_ExecuteAlias(a);
1627 cmd_tokenizebufferpos = oldpos;
1632 if(found) // if the command was hooked and found, all is good
1634 cmd_tokenizebufferpos = oldpos;
1639 if (!Cvar_Command () && host_framecount > 0)
1640 Con_Printf("Unknown command \"%s\"\n", Cmd_Argv(0));
1642 cmd_tokenizebufferpos = oldpos;
1648 Cmd_ForwardStringToServer
1650 Sends an entire command string over to the server, unprocessed
1653 void Cmd_ForwardStringToServer (const char *s)
1656 if (cls.state != ca_connected)
1658 Con_Printf("Can't \"%s\", not connected\n", s);
1665 // LordHavoc: thanks to Fuh for bringing the pure evil of SZ_Print to my
1666 // attention, it has been eradicated from here, its only (former) use in
1667 // all of darkplaces.
1668 if (cls.protocol == PROTOCOL_QUAKEWORLD)
1669 MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
1671 MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
1672 if ((!strncmp(s, "say ", 4) || !strncmp(s, "say_team ", 9)) && cl_locs_enable.integer)
1674 // say/say_team commands can replace % character codes with status info
1677 if (*s == '%' && s[1])
1679 // handle proquake message macros
1683 case 'l': // current location
1684 CL_Locs_FindLocationName(temp, sizeof(temp), cl.movement_origin);
1686 case 'h': // current health
1687 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_HEALTH]);
1689 case 'a': // current armor
1690 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ARMOR]);
1692 case 'x': // current rockets
1693 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ROCKETS]);
1695 case 'c': // current cells
1696 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_CELLS]);
1698 // silly proquake macros
1699 case 'd': // loc at last death
1700 CL_Locs_FindLocationName(temp, sizeof(temp), cl.lastdeathorigin);
1702 case 't': // current time
1703 dpsnprintf(temp, sizeof(temp), "%.0f:%.0f", floor(cl.time / 60), cl.time - floor(cl.time / 60) * 60);
1705 case 'r': // rocket launcher status ("I have RL", "I need rockets", "I need RL")
1706 if (!(cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER))
1707 dpsnprintf(temp, sizeof(temp), "I need RL");
1708 else if (!cl.stats[STAT_ROCKETS])
1709 dpsnprintf(temp, sizeof(temp), "I need rockets");
1711 dpsnprintf(temp, sizeof(temp), "I have RL");
1713 case 'p': // powerup status (outputs "quad" "pent" and "eyes" according to status)
1714 if (cl.stats[STAT_ITEMS] & IT_QUAD)
1717 strlcat(temp, " ", sizeof(temp));
1718 strlcat(temp, "quad", sizeof(temp));
1720 if (cl.stats[STAT_ITEMS] & IT_INVULNERABILITY)
1723 strlcat(temp, " ", sizeof(temp));
1724 strlcat(temp, "pent", sizeof(temp));
1726 if (cl.stats[STAT_ITEMS] & IT_INVISIBILITY)
1729 strlcat(temp, " ", sizeof(temp));
1730 strlcat(temp, "eyes", sizeof(temp));
1733 case 'w': // weapon status (outputs "SSG:NG:SNG:GL:RL:LG" with the text between : characters omitted if you lack the weapon)
1734 if (cl.stats[STAT_ITEMS] & IT_SUPER_SHOTGUN)
1735 strlcat(temp, "SSG", sizeof(temp));
1736 strlcat(temp, ":", sizeof(temp));
1737 if (cl.stats[STAT_ITEMS] & IT_NAILGUN)
1738 strlcat(temp, "NG", sizeof(temp));
1739 strlcat(temp, ":", sizeof(temp));
1740 if (cl.stats[STAT_ITEMS] & IT_SUPER_NAILGUN)
1741 strlcat(temp, "SNG", sizeof(temp));
1742 strlcat(temp, ":", sizeof(temp));
1743 if (cl.stats[STAT_ITEMS] & IT_GRENADE_LAUNCHER)
1744 strlcat(temp, "GL", sizeof(temp));
1745 strlcat(temp, ":", sizeof(temp));
1746 if (cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER)
1747 strlcat(temp, "RL", sizeof(temp));
1748 strlcat(temp, ":", sizeof(temp));
1749 if (cl.stats[STAT_ITEMS] & IT_LIGHTNING)
1750 strlcat(temp, "LG", sizeof(temp));
1753 // not a recognized macro, print it as-is...
1759 // write the resulting text
1760 SZ_Write(&cls.netcon->message, (unsigned char *)temp, strlen(temp));
1764 MSG_WriteByte(&cls.netcon->message, *s);
1767 MSG_WriteByte(&cls.netcon->message, 0);
1769 else // any other command is passed on as-is
1770 SZ_Write(&cls.netcon->message, (const unsigned char *)s, (int)strlen(s) + 1);
1777 Sends the entire command line over to the server
1780 void Cmd_ForwardToServer (void)
1783 if (!strcasecmp(Cmd_Argv(0), "cmd"))
1785 // we want to strip off "cmd", so just send the args
1786 s = Cmd_Argc() > 1 ? Cmd_Args() : "";
1790 // we need to keep the command name, so send Cmd_Argv(0), a space and then Cmd_Args()
1791 s = va("%s %s", Cmd_Argv(0), Cmd_Argc() > 1 ? Cmd_Args() : "");
1793 // don't send an empty forward message if the user tries "cmd" by itself
1796 Cmd_ForwardStringToServer(s);
1804 Returns the position (1 to argc-1) in the command's argument list
1805 where the given parameter apears, or 0 if not present
1809 int Cmd_CheckParm (const char *parm)
1815 Con_Printf ("Cmd_CheckParm: NULL");
1819 for (i = 1; i < Cmd_Argc (); i++)
1820 if (!strcasecmp (parm, Cmd_Argv (i)))