2 Copyright (C) 1996-1997 Id Software, Inc.
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13 See the GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20 // cmd.c -- Quake script command processing module
24 typedef struct cmdalias_s
26 struct cmdalias_s *next;
27 char name[MAX_ALIAS_NAME];
29 qboolean initstate; // indicates this command existed at init
30 char *initialvalue; // backup copy of value at init
33 static cmdalias_t *cmd_alias;
35 static qboolean cmd_wait;
37 static mempool_t *cmd_mempool;
39 static char cmd_tokenizebuffer[CMD_TOKENIZELENGTH];
40 static int cmd_tokenizebufferpos = 0;
42 //=============================================================================
48 Causes execution of the remainder of the command buffer to be delayed until
49 next frame. This allows commands like:
50 bind g "impulse 5 ; +attack ; wait ; -attack ; impulse 2"
53 static void Cmd_Wait_f (void)
58 typedef struct cmddeferred_s
60 struct cmddeferred_s *next;
65 static cmddeferred_t *cmd_deferred_list = NULL;
71 Cause a command to be executed after a delay.
74 static void Cmd_Defer_f (void)
78 double time = Sys_DoubleTime();
79 cmddeferred_t *next = cmd_deferred_list;
81 Con_Printf("No commands are pending.\n");
84 Con_Printf("-> In %9.2f: %s\n", next->time-time, next->value);
87 } else if(Cmd_Argc() == 2 && !strcasecmp("clear", Cmd_Argv(1)))
89 while(cmd_deferred_list)
91 cmddeferred_t *cmd = cmd_deferred_list;
92 cmd_deferred_list = cmd->next;
96 } else if(Cmd_Argc() == 3)
98 const char *value = Cmd_Argv(2);
99 cmddeferred_t *defcmd = (cmddeferred_t*)Mem_Alloc(tempmempool, sizeof(*defcmd));
100 size_t len = strlen(value);
102 defcmd->time = Sys_DoubleTime() + atof(Cmd_Argv(1));
103 defcmd->value = (char*)Mem_Alloc(tempmempool, len+1);
104 memcpy(defcmd->value, value, len+1);
107 if(cmd_deferred_list)
109 cmddeferred_t *next = cmd_deferred_list;
114 cmd_deferred_list = defcmd;
115 /* Stupid me... this changes the order... so commands with the same delay go blub :S
116 defcmd->next = cmd_deferred_list;
117 cmd_deferred_list = defcmd;*/
119 Con_Printf("usage: defer <seconds> <command>\n"
129 Print something to the center of the screen using SCR_Centerprint
132 static void Cmd_Centerprint_f (void)
134 char msg[MAX_INPUTLINE];
135 unsigned int i, c, p;
139 strlcpy(msg, Cmd_Argv(1), sizeof(msg));
140 for(i = 2; i < c; ++i)
142 strlcat(msg, " ", sizeof(msg));
143 strlcat(msg, Cmd_Argv(i), sizeof(msg));
146 for(p = 0, i = 0; i < c; ++i)
152 else if(msg[i+1] == '\\')
164 SCR_CenterPrint(msg);
169 =============================================================================
173 =============================================================================
176 static sizebuf_t cmd_text;
177 static unsigned char cmd_text_buf[CMDBUFSIZE];
183 Adds command text at the end of the buffer
186 void Cbuf_AddText (const char *text)
190 l = (int)strlen (text);
192 if (cmd_text.cursize + l >= cmd_text.maxsize)
194 Con_Print("Cbuf_AddText: overflow\n");
198 SZ_Write (&cmd_text, (const unsigned char *)text, (int)strlen (text));
206 Adds command text immediately after the current command
207 Adds a \n to the text
208 FIXME: actually change the command buffer to do less copying
211 void Cbuf_InsertText (const char *text)
216 // copy off any commands still remaining in the exec buffer
217 templen = cmd_text.cursize;
220 temp = (char *)Mem_Alloc (tempmempool, templen);
221 memcpy (temp, cmd_text.data, templen);
222 SZ_Clear (&cmd_text);
227 // add the entire text of the file
230 // add the copied off data
233 SZ_Write (&cmd_text, (const unsigned char *)temp, templen);
240 Cbuf_Execute_Deferred --blub
243 void Cbuf_Execute_Deferred (void)
245 cmddeferred_t *cmd, *prev;
246 double time = Sys_DoubleTime();
248 cmd = cmd_deferred_list;
251 if(cmd->time <= time)
253 Cbuf_AddText(cmd->value);
255 Mem_Free(cmd->value);
258 prev->next = cmd->next;
262 cmd_deferred_list = cmd->next;
264 cmd = cmd_deferred_list;
278 static void Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias );
279 void Cbuf_Execute (void)
283 char line[MAX_INPUTLINE];
284 char preprocessed[MAX_INPUTLINE];
289 // LordHavoc: making sure the tokenizebuffer doesn't get filled up by repeated crashes
290 cmd_tokenizebufferpos = 0;
292 Cbuf_Execute_Deferred();
293 while (cmd_text.cursize)
295 // find a \n or ; line break
296 text = (char *)cmd_text.data;
300 for (i=0 ; i < cmd_text.cursize ; i++)
309 // make sure i doesn't get > cursize which causes a negative
310 // size in memmove, which is fatal --blub
311 if (i < (cmd_text.cursize-1) && (text[i] == '\\' && (text[i+1] == '"' || text[i+1] == '\\')))
316 if(text[i] == '/' && text[i + 1] == '/' && (i == 0 || ISWHITESPACE(text[i-1])))
319 break; // don't break if inside a quoted string or comment
323 if (text[i] == '\r' || text[i] == '\n')
327 // better than CRASHING on overlong input lines that may SOMEHOW enter the buffer
328 if(i >= MAX_INPUTLINE)
330 Con_Printf("Warning: console input buffer had an overlong line. Ignored.\n");
335 memcpy (line, text, comment ? (comment - text) : i);
336 line[comment ? (comment - text) : i] = 0;
339 // delete the text from the command buffer and move remaining commands down
340 // this is necessary because commands (exec, alias) can insert data at the
341 // beginning of the text buffer
343 if (i == cmd_text.cursize)
344 cmd_text.cursize = 0;
348 cmd_text.cursize -= i;
349 memmove (cmd_text.data, text+i, cmd_text.cursize);
352 // execute the command line
354 while(*firstchar && ISWHITESPACE(*firstchar))
357 (strncmp(firstchar, "alias", 5) || !ISWHITESPACE(firstchar[5]))
359 (strncmp(firstchar, "bind", 4) || !ISWHITESPACE(firstchar[4]))
361 (strncmp(firstchar, "in_bind", 7) || !ISWHITESPACE(firstchar[7]))
364 Cmd_PreprocessString( line, preprocessed, sizeof(preprocessed), NULL );
365 Cmd_ExecuteString (preprocessed, src_command);
369 Cmd_ExecuteString (line, src_command);
373 { // skip out while text still remains in buffer, leaving it
382 ==============================================================================
386 ==============================================================================
393 Adds command line parameters as script statements
394 Commands lead with a +, and continue until a - or another +
395 quake +prog jctest.qp +cmd amlev1
396 quake -nosound +cmd amlev1
399 qboolean host_stuffcmdsrun = false;
400 void Cmd_StuffCmds_f (void)
403 // this is for all commandline options combined (and is bounds checked)
404 char build[MAX_INPUTLINE];
406 if (Cmd_Argc () != 1)
408 Con_Print("stuffcmds : execute command line parameters\n");
412 // no reason to run the commandline arguments twice
413 if (host_stuffcmdsrun)
416 host_stuffcmdsrun = true;
419 for (i = 0;i < com_argc;i++)
421 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)
424 while (com_argv[i][j])
425 build[l++] = com_argv[i][j++];
427 for (;i < com_argc;i++)
431 if ((com_argv[i][0] == '+' || com_argv[i][0] == '-') && (com_argv[i][1] < '0' || com_argv[i][1] > '9'))
433 if (l + strlen(com_argv[i]) + 4 > sizeof(build) - 1)
436 if (strchr(com_argv[i], ' '))
438 for (j = 0;com_argv[i][j];j++)
439 build[l++] = com_argv[i][j];
440 if (strchr(com_argv[i], ' '))
447 // now terminate the combined string and prepend it to the command buffer
448 // we already reserved space for the terminator
450 Cbuf_InsertText (build);
453 static void Cmd_Exec(const char *filename)
456 qboolean isdefaultcfg = strlen(filename) >= 11 && !strcmp(filename + strlen(filename) - 11, "default.cfg");
458 if (!strcmp(filename, "config.cfg"))
460 filename = CONFIGFILENAME;
461 if (COM_CheckParm("-noconfig"))
462 return; // don't execute config.cfg
465 f = (char *)FS_LoadFile (filename, tempmempool, false, NULL);
468 Con_Printf("couldn't exec %s\n",filename);
471 Con_Printf("execing %s\n",filename);
473 // if executing default.cfg for the first time, lock the cvar defaults
474 // it may seem backwards to insert this text BEFORE the default.cfg
475 // but Cbuf_InsertText inserts before, so this actually ends up after it.
477 Cbuf_InsertText("\ncvar_lockdefaults\n");
479 // insert newline after the text to make sure the last line is terminated (some text editors omit the trailing newline)
480 // (note: insertion order here is backwards from execution order, so this adds it after the text, by calling it before...)
481 Cbuf_InsertText ("\n");
487 // special defaults for specific games go here, these execute before default.cfg
488 // Nehahra pushable crates malfunction in some levels if this is on
489 // Nehahra NPC AI is confused by blowupfallenzombies
490 if (gamemode == GAME_NEHAHRA)
491 Cbuf_InsertText("\nsv_gameplayfix_upwardvelocityclearsongroundflag 0\nsv_gameplayfix_blowupfallenzombies 0\n\n");
492 // hipnotic mission pack has issues in their 'friendly monster' ai, which seem to attempt to attack themselves for some reason when findradius() returns non-solid entities.
493 // hipnotic mission pack has issues with bobbing water entities 'jittering' between different heights on alternate frames at the default 0.0138889 ticrate, 0.02 avoids this issue
494 // hipnotic mission pack has issues in their proximity mine sticking code, which causes them to bounce off.
495 if (gamemode == GAME_HIPNOTIC)
496 Cbuf_InsertText("\nsv_gameplayfix_blowupfallenzombies 0\nsys_ticrate 0.02\nsv_gameplayfix_slidemoveprojectiles 0\n\n");
497 // rogue mission pack has a guardian boss that does not wake up if findradius returns one of the entities around its spawn area
498 if (gamemode == GAME_ROGUE)
499 Cbuf_InsertText("\nsv_gameplayfix_findradiusdistancetobox 0\n\n");
500 if (gamemode == GAME_NEXUIZ)
501 Cbuf_InsertText("\nsv_gameplayfix_q2airaccelerate 1\nsv_gameplayfix_stepmultipletimes 1\n\n");
502 if (gamemode == GAME_TENEBRAE)
503 Cbuf_InsertText("\nr_shadow_gloss 2\nr_shadow_bumpscale_basetexture 4\n\n");
504 // Steel Storm: Burning Retribution csqc misinterprets CSQC_InputEvent if type is a value other than 0 or 1
505 if (gamemode == GAME_STEELSTORM)
506 Cbuf_InsertText("\ncl_csqc_generatemousemoveevents 0\n\n");
515 static void Cmd_Exec_f (void)
520 if (Cmd_Argc () != 2)
522 Con_Print("exec <filename> : execute a script file\n");
526 s = FS_Search(Cmd_Argv(1), true, true);
527 if(!s || !s->numfilenames)
529 Con_Printf("couldn't exec %s\n",Cmd_Argv(1));
533 for(i = 0; i < s->numfilenames; ++i)
534 Cmd_Exec(s->filenames[i]);
544 Just prints the rest of the line to the console
547 static void Cmd_Echo_f (void)
551 for (i=1 ; i<Cmd_Argc() ; i++)
552 Con_Printf("%s ",Cmd_Argv(i));
557 // Support Doom3-style Toggle Console Command
562 Toggles a specified console variable amongst the values specified (default is 0 and 1)
565 static void Cmd_Toggle_f(void)
567 // Acquire Number of Arguments
568 int nNumArgs = Cmd_Argc();
571 // No Arguments Specified; Print Usage
572 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");
574 { // Correct Arguments Specified
575 // Acquire Potential CVar
576 cvar_t* cvCVar = Cvar_FindVar( Cmd_Argv(1) );
583 Cvar_SetValueQuick(cvCVar, 0);
585 Cvar_SetValueQuick(cvCVar, 1);
589 { // 0 and Specified Usage
590 if(cvCVar->integer == atoi(Cmd_Argv(2) ) )
591 // CVar is Specified Value; // Reset to 0
592 Cvar_SetValueQuick(cvCVar, 0);
594 if(cvCVar->integer == 0)
595 // CVar is 0; Specify Value
596 Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
598 // CVar does not match; Reset to 0
599 Cvar_SetValueQuick(cvCVar, 0);
602 { // Variable Values Specified
606 for(nCnt = 2; nCnt < nNumArgs; nCnt++)
607 { // Cycle through Values
608 if( strcmp(cvCVar->string, Cmd_Argv(nCnt) ) == 0)
609 { // Current Value Located; Increment to Next
610 if( (nCnt + 1) == nNumArgs)
611 // Max Value Reached; Reset
612 Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
615 Cvar_SetQuick(cvCVar, Cmd_Argv(nCnt + 1) );
624 // Value not Found; Reset to Original
625 Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
631 Con_Printf("ERROR : CVar '%s' not found\n", Cmd_Argv(1) );
640 Creates a new command that executes a command string (possibly ; seperated)
643 static void Cmd_Alias_f (void)
646 char cmd[MAX_INPUTLINE];
653 Con_Print("Current alias commands:\n");
654 for (a = cmd_alias ; a ; a=a->next)
655 Con_Printf("%s : %s", a->name, a->value);
660 if (strlen(s) >= MAX_ALIAS_NAME)
662 Con_Print("Alias name is too long\n");
666 // if the alias already exists, reuse it
667 for (a = cmd_alias ; a ; a=a->next)
669 if (!strcmp(s, a->name))
678 cmdalias_t *prev, *current;
680 a = (cmdalias_t *)Z_Malloc (sizeof(cmdalias_t));
681 strlcpy (a->name, s, sizeof (a->name));
682 // insert it at the right alphanumeric position
683 for( prev = NULL, current = cmd_alias ; current && strcmp( current->name, a->name ) < 0 ; prev = current, current = current->next )
694 // copy the rest of the command line
695 cmd[0] = 0; // start out with a null string
697 for (i=2 ; i < c ; i++)
700 strlcat (cmd, " ", sizeof (cmd));
701 strlcat (cmd, Cmd_Argv(i), sizeof (cmd));
703 strlcat (cmd, "\n", sizeof (cmd));
705 alloclen = strlen (cmd) + 1;
707 cmd[alloclen - 2] = '\n'; // to make sure a newline is appended even if too long
708 a->value = (char *)Z_Malloc (alloclen);
709 memcpy (a->value, cmd, alloclen);
716 Remove existing aliases.
719 static void Cmd_UnAlias_f (void)
727 Con_Print("unalias: Usage: unalias alias1 [alias2 ...]\n");
731 for(i = 1; i < Cmd_Argc(); ++i)
735 for(a = cmd_alias; a; p = a, a = a->next)
737 if(!strcmp(s, a->name))
739 if (a->initstate) // we can not remove init aliases
751 Con_Printf("unalias: %s alias not found\n", s);
756 =============================================================================
760 =============================================================================
763 typedef struct cmd_function_s
765 struct cmd_function_s *next;
767 const char *description;
768 xcommand_t consolefunction;
769 xcommand_t clientfunction;
771 qboolean initstate; // indicates this command existed at init
775 static const char *cmd_argv[MAX_ARGS];
776 static const char *cmd_null_string = "";
777 static const char *cmd_args;
778 cmd_source_t cmd_source;
781 static cmd_function_t *cmd_functions; // possible commands to execute
783 static const char *Cmd_GetDirectCvarValue(const char *varname, cmdalias_t *alias, qboolean *is_multiple)
790 *is_multiple = false;
792 if(!varname || !*varname)
797 if(!strcmp(varname, "*"))
803 else if(!strcmp(varname, "#"))
805 return va("%d", Cmd_Argc());
807 else if(varname[strlen(varname) - 1] == '-')
809 argno = strtol(varname, &endptr, 10);
810 if(endptr == varname + strlen(varname) - 1)
812 // whole string is a number, apart from the -
813 const char *p = Cmd_Args();
814 for(; argno > 1; --argno)
815 if(!COM_ParseToken_Console(&p))
822 // kill pre-argument whitespace
823 for (;*p && ISWHITESPACE(*p);p++)
832 argno = strtol(varname, &endptr, 10);
835 // whole string is a number
836 // NOTE: we already made sure we don't have an empty cvar name!
837 if(argno >= 0 && argno < Cmd_Argc())
838 return Cmd_Argv(argno);
843 if((cvar = Cvar_FindVar(varname)) && !(cvar->flags & CVAR_PRIVATE))
849 qboolean Cmd_QuoteString(char *out, size_t outlen, const char *in, const char *quoteset, qboolean putquotes)
851 qboolean quote_quot = !!strchr(quoteset, '"');
852 qboolean quote_backslash = !!strchr(quoteset, '\\');
853 qboolean quote_dollar = !!strchr(quoteset, '$');
862 *out++ = '"'; --outlen;
868 if(*in == '"' && quote_quot)
872 *out++ = '\\'; --outlen;
873 *out++ = '"'; --outlen;
875 else if(*in == '\\' && quote_backslash)
879 *out++ = '\\'; --outlen;
880 *out++ = '\\'; --outlen;
882 else if(*in == '$' && quote_dollar)
886 *out++ = '$'; --outlen;
887 *out++ = '$'; --outlen;
893 *out++ = *in; --outlen;
908 static const char *Cmd_GetCvarValue(const char *var, size_t varlen, cmdalias_t *alias)
910 static char varname[MAX_INPUTLINE];
911 static char varval[MAX_INPUTLINE];
914 static char asis[] = "asis"; // just to suppress const char warnings
916 if(varlen >= MAX_INPUTLINE)
917 varlen = MAX_INPUTLINE - 1;
918 memcpy(varname, var, varlen);
920 varfunc = strchr(varname, ' ');
936 if(varname[0] == '$')
937 varstr = Cmd_GetDirectCvarValue(Cmd_GetDirectCvarValue(varname + 1, alias, NULL), alias, NULL);
940 qboolean is_multiple = false;
941 // Exception: $* and $n- don't use the quoted form by default
942 varstr = Cmd_GetDirectCvarValue(varname, alias, &is_multiple);
951 Con_Printf("Warning: Could not expand $%s in alias %s\n", varname, alias->name);
953 Con_Printf("Warning: Could not expand $%s\n", varname);
957 if(!varfunc || !strcmp(varfunc, "q")) // note: quoted form is default, use "asis" to override!
959 // quote it so it can be used inside double quotes
960 // we just need to replace " by \", and of course, double backslashes
961 Cmd_QuoteString(varval, sizeof(varval), varstr, "\"\\", false);
964 else if(!strcmp(varfunc, "asis"))
969 Con_Printf("Unknown variable function %s\n", varfunc);
977 Preprocesses strings and replaces $*, $param#, $cvar accordingly. Also strips comments.
979 static void Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias ) {
985 // don't crash if there's no room in the outtext buffer
986 if( maxoutlen == 0 ) {
989 maxoutlen--; // because of \0
994 while( *in && outlen < maxoutlen ) {
996 // this is some kind of expansion, see what comes after the $
999 // The console does the following preprocessing:
1001 // - $$ is transformed to a single dollar sign.
1002 // - $var or ${var} are expanded to the contents of the named cvar,
1003 // with quotation marks and backslashes quoted so it can safely
1004 // be used inside quotation marks (and it should always be used
1006 // - ${var asis} inserts the cvar value as is, without doing this
1008 // - prefix the cvar name with a dollar sign to do indirection;
1009 // for example, if $x has the value timelimit, ${$x} will return
1010 // the value of $timelimit
1011 // - when expanding an alias, the special variable name $* refers
1012 // to all alias parameters, and a number refers to that numbered
1013 // alias parameter, where the name of the alias is $0, the first
1014 // parameter is $1 and so on; as a special case, $* inserts all
1015 // parameters, without extra quoting, so one can use $* to just
1016 // pass all parameters around. All parameters starting from $n
1017 // can be referred to as $n- (so $* is equivalent to $1-).
1019 // Note: when expanding an alias, cvar expansion is done in the SAME step
1020 // as alias expansion so that alias parameters or cvar values containing
1021 // dollar signs have no unwanted bad side effects. However, this needs to
1022 // be accounted for when writing complex aliases. For example,
1023 // alias foo "set x NEW; echo $x"
1024 // actually expands to
1025 // "set x NEW; echo OLD"
1026 // and will print OLD! To work around this, use a second alias:
1027 // alias foo "set x NEW; foo2"
1028 // alias foo2 "echo $x"
1030 // Also note: lines starting with alias are exempt from cvar expansion.
1031 // If you want cvar expansion, write "alias" instead:
1034 // alias foo "echo $x"
1035 // "alias" bar "echo $x"
1038 // foo will print 2, because the variable $x will be expanded when the alias
1039 // gets expanded. bar will print 1, because the variable $x was expanded
1040 // at definition time. foo can be equivalently defined as
1042 // "alias" foo "echo $$x"
1044 // because at definition time, $$ will get replaced to a single $.
1049 } else if(*in == '{') {
1050 varlen = strcspn(in + 1, "}");
1051 if(in[varlen + 1] == '}')
1053 val = Cmd_GetCvarValue(in + 1, varlen, alias);
1063 varlen = strspn(in, "#*0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-");
1064 val = Cmd_GetCvarValue(in, varlen, alias);
1069 // insert the cvar value
1070 while(*val && outlen < maxoutlen)
1071 outtext[outlen++] = *val++;
1076 // copy the unexpanded text
1077 outtext[outlen++] = '$';
1078 while(eat && outlen < maxoutlen)
1080 outtext[outlen++] = *in++;
1086 outtext[outlen++] = *in++;
1088 outtext[outlen] = 0;
1095 Called for aliases and fills in the alias into the cbuffer
1098 static void Cmd_ExecuteAlias (cmdalias_t *alias)
1100 static char buffer[ MAX_INPUTLINE ];
1101 static char buffer2[ MAX_INPUTLINE ];
1102 Cmd_PreprocessString( alias->value, buffer, sizeof(buffer) - 2, alias );
1103 // insert at start of command buffer, so that aliases execute in order
1104 // (fixes bug introduced by Black on 20050705)
1106 // Note: Cbuf_PreprocessString will be called on this string AGAIN! So we
1107 // have to make sure that no second variable expansion takes place, otherwise
1108 // alias parameters containing dollar signs can have bad effects.
1109 Cmd_QuoteString(buffer2, sizeof(buffer2), buffer, "$", false);
1110 Cbuf_InsertText( buffer2 );
1117 CmdList Added by EvilTypeGuy eviltypeguy@qeradiant.com
1118 Thanks to Matthias "Maddes" Buecher, http://www.inside3d.com/qip/
1122 static void Cmd_List_f (void)
1124 cmd_function_t *cmd;
1125 const char *partial;
1132 partial = Cmd_Argv (1);
1133 len = strlen(partial);
1141 ispattern = partial && (strchr(partial, '*') || strchr(partial, '?'));
1144 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1146 if (partial && (ispattern ? !matchpattern_with_separator(cmd->name, partial, false, "", false) : strncmp(partial, cmd->name, len)))
1148 Con_Printf("%s : %s\n", cmd->name, cmd->description);
1155 Con_Printf("%i Command%s matching \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1157 Con_Printf("%i Command%s beginning with \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1160 Con_Printf("%i Command%s\n\n", count, (count > 1) ? "s" : "");
1163 static void Cmd_Apropos_f(void)
1165 cmd_function_t *cmd;
1168 const char *partial;
1173 partial = Cmd_Args();
1176 Con_Printf("usage: apropos <string>\n");
1180 ispattern = partial && (strchr(partial, '*') || strchr(partial, '?'));
1182 partial = va("*%s*", partial);
1185 for (cvar = cvar_vars; cvar; cvar = cvar->next)
1187 if (!matchpattern_with_separator(cvar->name, partial, true, "", false))
1188 if (!matchpattern_with_separator(cvar->description, partial, true, "", false))
1190 Con_Printf ("cvar ^3%s^7 is \"%s\" [\"%s\"] %s\n", cvar->name, cvar->string, cvar->defstring, cvar->description);
1193 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1195 if (!matchpattern_with_separator(cmd->name, partial, true, "", false))
1196 if (!matchpattern_with_separator(cmd->description, partial, true, "", false))
1198 Con_Printf("command ^2%s^7: %s\n", cmd->name, cmd->description);
1201 for (alias = cmd_alias; alias; alias = alias->next)
1203 // procede here a bit differently as an alias value always got a final \n
1204 if (!matchpattern_with_separator(alias->name, partial, true, "", false))
1205 if (!matchpattern_with_separator(alias->value, partial, true, "\n", false)) // when \n is as separator wildcards don't match it
1207 Con_Printf("alias ^5%s^7: %s", alias->name, alias->value); // do not print an extra \n
1210 Con_Printf("%i result%s\n\n", count, (count > 1) ? "s" : "");
1218 void Cmd_Init (void)
1220 cmd_mempool = Mem_AllocPool("commands", 0, NULL);
1221 // space for commands and script files
1222 cmd_text.data = cmd_text_buf;
1223 cmd_text.maxsize = sizeof(cmd_text_buf);
1224 cmd_text.cursize = 0;
1227 void Cmd_Init_Commands (void)
1230 // register our commands
1232 Cmd_AddCommand ("stuffcmds",Cmd_StuffCmds_f, "execute commandline parameters (must be present in quake.rc script)");
1233 Cmd_AddCommand ("exec",Cmd_Exec_f, "execute a script file");
1234 Cmd_AddCommand ("echo",Cmd_Echo_f, "print a message to the console (useful in scripts)");
1235 Cmd_AddCommand ("alias",Cmd_Alias_f, "create a script function (parameters are passed in as $X (being X a number), $* for all parameters, $X- for all parameters starting from $X). Without arguments show the list of all alias");
1236 Cmd_AddCommand ("unalias",Cmd_UnAlias_f, "remove an alias");
1237 Cmd_AddCommand ("cmd", Cmd_ForwardToServer, "send a console commandline to the server (used by some mods)");
1238 Cmd_AddCommand ("wait", Cmd_Wait_f, "make script execution wait for next rendered frame");
1239 Cmd_AddCommand ("set", Cvar_Set_f, "create or change the value of a console variable");
1240 Cmd_AddCommand ("seta", Cvar_SetA_f, "create or change the value of a console variable that will be saved to config.cfg");
1241 Cmd_AddCommand ("unset", Cvar_Del_f, "delete a cvar (does not work for static ones like _cl_name, or read-only ones)");
1242 #ifdef FILLALLCVARSWITHRUBBISH
1243 Cmd_AddCommand ("fillallcvarswithrubbish", Cvar_FillAll_f, "fill all cvars with a specified number of characters to provoke buffer overruns");
1244 #endif /* FILLALLCVARSWITHRUBBISH */
1246 // 2000-01-09 CmdList, CvarList commands By Matthias "Maddes" Buecher
1247 // Added/Modified by EvilTypeGuy eviltypeguy@qeradiant.com
1248 Cmd_AddCommand ("cmdlist", Cmd_List_f, "lists all console commands beginning with the specified prefix or matching the specified wildcard pattern");
1249 Cmd_AddCommand ("cvarlist", Cvar_List_f, "lists all console variables beginning with the specified prefix or matching the specified wildcard pattern");
1250 Cmd_AddCommand ("apropos", Cmd_Apropos_f, "lists all console variables/commands/aliases containing the specified string in the name or description");
1252 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");
1253 Cmd_AddCommand ("cvar_resettodefaults_all", Cvar_ResetToDefaults_All_f, "sets all cvars to their locked default values");
1254 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)");
1255 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)");
1257 Cmd_AddCommand ("cprint", Cmd_Centerprint_f, "print something at the screen center");
1258 Cmd_AddCommand ("defer", Cmd_Defer_f, "execute a command in the future");
1261 // Support Doom3-style Toggle Command
1262 Cmd_AddCommand( "toggle", Cmd_Toggle_f, "toggles a console variable's values (use for more info)");
1270 void Cmd_Shutdown(void)
1272 Mem_FreePool(&cmd_mempool);
1290 const char *Cmd_Argv (int arg)
1292 if (arg >= cmd_argc )
1293 return cmd_null_string;
1294 return cmd_argv[arg];
1302 const char *Cmd_Args (void)
1312 Parses the given string into command line tokens.
1315 // AK: This function should only be called from ExcuteString because the current design is a bit of an hack
1316 static void Cmd_TokenizeString (const char *text)
1325 // skip whitespace up to a /n
1326 while (*text && ISWHITESPACE(*text) && *text != '\r' && *text != '\n')
1333 if (*text == '\n' || *text == '\r')
1335 // a newline separates commands in the buffer
1336 if (*text == '\r' && text[1] == '\n')
1348 if (!COM_ParseToken_Console(&text))
1351 if (cmd_argc < MAX_ARGS)
1353 l = (int)strlen(com_token) + 1;
1354 if (cmd_tokenizebufferpos + l > CMD_TOKENIZELENGTH)
1356 Con_Printf("Cmd_TokenizeString: ran out of %i character buffer space for command arguements\n", CMD_TOKENIZELENGTH);
1359 memcpy (cmd_tokenizebuffer + cmd_tokenizebufferpos, com_token, l);
1360 cmd_argv[cmd_argc] = cmd_tokenizebuffer + cmd_tokenizebufferpos;
1361 cmd_tokenizebufferpos += l;
1373 void Cmd_AddCommand_WithClientCommand (const char *cmd_name, xcommand_t consolefunction, xcommand_t clientfunction, const char *description)
1375 cmd_function_t *cmd;
1376 cmd_function_t *prev, *current;
1378 // fail if the command is a variable name
1379 if (Cvar_FindVar( cmd_name ))
1381 Con_Printf("Cmd_AddCommand: %s already defined as a var\n", cmd_name);
1385 // fail if the command already exists
1386 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1388 if (!strcmp (cmd_name, cmd->name))
1390 if (consolefunction || clientfunction)
1392 Con_Printf("Cmd_AddCommand: %s already defined\n", cmd_name);
1397 cmd->csqcfunc = true;
1403 cmd = (cmd_function_t *)Mem_Alloc(cmd_mempool, sizeof(cmd_function_t));
1404 cmd->name = cmd_name;
1405 cmd->consolefunction = consolefunction;
1406 cmd->clientfunction = clientfunction;
1407 cmd->description = description;
1408 if(!consolefunction && !clientfunction) //[515]: csqc
1409 cmd->csqcfunc = true;
1410 cmd->next = cmd_functions;
1412 // insert it at the right alphanumeric position
1413 for( prev = NULL, current = cmd_functions ; current && strcmp( current->name, cmd->name ) < 0 ; prev = current, current = current->next )
1418 cmd_functions = cmd;
1420 cmd->next = current;
1423 void Cmd_AddCommand (const char *cmd_name, xcommand_t function, const char *description)
1425 Cmd_AddCommand_WithClientCommand (cmd_name, function, NULL, description);
1433 qboolean Cmd_Exists (const char *cmd_name)
1435 cmd_function_t *cmd;
1437 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1438 if (!strcmp (cmd_name,cmd->name))
1450 const char *Cmd_CompleteCommand (const char *partial)
1452 cmd_function_t *cmd;
1455 len = strlen(partial);
1461 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1462 if (!strncasecmp(partial, cmd->name, len))
1469 Cmd_CompleteCountPossible
1471 New function for tab-completion system
1472 Added by EvilTypeGuy
1473 Thanks to Fett erich@heintz.com
1477 int Cmd_CompleteCountPossible (const char *partial)
1479 cmd_function_t *cmd;
1484 len = strlen(partial);
1489 // Loop through the command list and count all partial matches
1490 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1491 if (!strncasecmp(partial, cmd->name, len))
1498 Cmd_CompleteBuildList
1500 New function for tab-completion system
1501 Added by EvilTypeGuy
1502 Thanks to Fett erich@heintz.com
1506 const char **Cmd_CompleteBuildList (const char *partial)
1508 cmd_function_t *cmd;
1511 size_t sizeofbuf = (Cmd_CompleteCountPossible (partial) + 1) * sizeof (const char *);
1514 len = strlen(partial);
1515 buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1516 // Loop through the alias list and print all matches
1517 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1518 if (!strncasecmp(partial, cmd->name, len))
1519 buf[bpos++] = cmd->name;
1525 // written by LordHavoc
1526 void Cmd_CompleteCommandPrint (const char *partial)
1528 cmd_function_t *cmd;
1529 size_t len = strlen(partial);
1530 // Loop through the command list and print all matches
1531 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1532 if (!strncasecmp(partial, cmd->name, len))
1533 Con_Printf("^2%s^7: %s\n", cmd->name, cmd->description);
1539 New function for tab-completion system
1540 Added by EvilTypeGuy
1541 Thanks to Fett erich@heintz.com
1545 const char *Cmd_CompleteAlias (const char *partial)
1550 len = strlen(partial);
1556 for (alias = cmd_alias; alias; alias = alias->next)
1557 if (!strncasecmp(partial, alias->name, len))
1563 // written by LordHavoc
1564 void Cmd_CompleteAliasPrint (const char *partial)
1567 size_t len = strlen(partial);
1568 // Loop through the alias list and print all matches
1569 for (alias = cmd_alias; alias; alias = alias->next)
1570 if (!strncasecmp(partial, alias->name, len))
1571 Con_Printf("^5%s^7: %s", alias->name, alias->value);
1576 Cmd_CompleteAliasCountPossible
1578 New function for tab-completion system
1579 Added by EvilTypeGuy
1580 Thanks to Fett erich@heintz.com
1584 int Cmd_CompleteAliasCountPossible (const char *partial)
1592 len = strlen(partial);
1597 // Loop through the command list and count all partial matches
1598 for (alias = cmd_alias; alias; alias = alias->next)
1599 if (!strncasecmp(partial, alias->name, len))
1606 Cmd_CompleteAliasBuildList
1608 New function for tab-completion system
1609 Added by EvilTypeGuy
1610 Thanks to Fett erich@heintz.com
1614 const char **Cmd_CompleteAliasBuildList (const char *partial)
1619 size_t sizeofbuf = (Cmd_CompleteAliasCountPossible (partial) + 1) * sizeof (const char *);
1622 len = strlen(partial);
1623 buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1624 // Loop through the alias list and print all matches
1625 for (alias = cmd_alias; alias; alias = alias->next)
1626 if (!strncasecmp(partial, alias->name, len))
1627 buf[bpos++] = alias->name;
1633 void Cmd_ClearCsqcFuncs (void)
1635 cmd_function_t *cmd;
1636 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1637 cmd->csqcfunc = false;
1640 qboolean CL_VM_ConsoleCommand (const char *cmd);
1645 A complete command line has been parsed, so try to execute it
1646 FIXME: lookupnoadd the token to speed search?
1649 void Cmd_ExecuteString (const char *text, cmd_source_t src)
1653 cmd_function_t *cmd;
1656 oldpos = cmd_tokenizebufferpos;
1660 Cmd_TokenizeString (text);
1662 // execute the command line
1665 cmd_tokenizebufferpos = oldpos;
1666 return; // no tokens
1670 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1672 if (!strcasecmp (cmd_argv[0],cmd->name))
1674 if (cmd->csqcfunc && CL_VM_ConsoleCommand (text)) //[515]: csqc
1679 if (cmd->consolefunction)
1680 cmd->consolefunction ();
1681 else if (cmd->clientfunction)
1683 if (cls.state == ca_connected)
1685 // forward remote commands to the server for execution
1686 Cmd_ForwardToServer();
1689 Con_Printf("Can not send command \"%s\", not connected.\n", Cmd_Argv(0));
1692 Con_Printf("Command \"%s\" can not be executed\n", Cmd_Argv(0));
1696 if (cmd->clientfunction)
1698 cmd->clientfunction ();
1699 cmd_tokenizebufferpos = oldpos;
1709 // if it's a client command and no command was found, say so.
1710 if (cmd_source == src_client)
1712 Con_Printf("player \"%s\" tried to %s\n", host_client->name, text);
1713 cmd_tokenizebufferpos = oldpos;
1718 for (a=cmd_alias ; a ; a=a->next)
1720 if (!strcasecmp (cmd_argv[0], a->name))
1722 Cmd_ExecuteAlias(a);
1723 cmd_tokenizebufferpos = oldpos;
1728 if(found) // if the command was hooked and found, all is good
1730 cmd_tokenizebufferpos = oldpos;
1735 if (!Cvar_Command () && host_framecount > 0)
1736 Con_Printf("Unknown command \"%s\"\n", Cmd_Argv(0));
1738 cmd_tokenizebufferpos = oldpos;
1744 Cmd_ForwardStringToServer
1746 Sends an entire command string over to the server, unprocessed
1749 void Cmd_ForwardStringToServer (const char *s)
1752 if (cls.state != ca_connected)
1754 Con_Printf("Can't \"%s\", not connected\n", s);
1761 // LordHavoc: thanks to Fuh for bringing the pure evil of SZ_Print to my
1762 // attention, it has been eradicated from here, its only (former) use in
1763 // all of darkplaces.
1764 if (cls.protocol == PROTOCOL_QUAKEWORLD)
1765 MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
1767 MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
1768 if ((!strncmp(s, "say ", 4) || !strncmp(s, "say_team ", 9)) && cl_locs_enable.integer)
1770 // say/say_team commands can replace % character codes with status info
1773 if (*s == '%' && s[1])
1775 // handle proquake message macros
1779 case 'l': // current location
1780 CL_Locs_FindLocationName(temp, sizeof(temp), cl.movement_origin);
1782 case 'h': // current health
1783 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_HEALTH]);
1785 case 'a': // current armor
1786 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ARMOR]);
1788 case 'x': // current rockets
1789 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ROCKETS]);
1791 case 'c': // current cells
1792 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_CELLS]);
1794 // silly proquake macros
1795 case 'd': // loc at last death
1796 CL_Locs_FindLocationName(temp, sizeof(temp), cl.lastdeathorigin);
1798 case 't': // current time
1799 dpsnprintf(temp, sizeof(temp), "%.0f:%.0f", floor(cl.time / 60), cl.time - floor(cl.time / 60) * 60);
1801 case 'r': // rocket launcher status ("I have RL", "I need rockets", "I need RL")
1802 if (!(cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER))
1803 dpsnprintf(temp, sizeof(temp), "I need RL");
1804 else if (!cl.stats[STAT_ROCKETS])
1805 dpsnprintf(temp, sizeof(temp), "I need rockets");
1807 dpsnprintf(temp, sizeof(temp), "I have RL");
1809 case 'p': // powerup status (outputs "quad" "pent" and "eyes" according to status)
1810 if (cl.stats[STAT_ITEMS] & IT_QUAD)
1813 strlcat(temp, " ", sizeof(temp));
1814 strlcat(temp, "quad", sizeof(temp));
1816 if (cl.stats[STAT_ITEMS] & IT_INVULNERABILITY)
1819 strlcat(temp, " ", sizeof(temp));
1820 strlcat(temp, "pent", sizeof(temp));
1822 if (cl.stats[STAT_ITEMS] & IT_INVISIBILITY)
1825 strlcat(temp, " ", sizeof(temp));
1826 strlcat(temp, "eyes", sizeof(temp));
1829 case 'w': // weapon status (outputs "SSG:NG:SNG:GL:RL:LG" with the text between : characters omitted if you lack the weapon)
1830 if (cl.stats[STAT_ITEMS] & IT_SUPER_SHOTGUN)
1831 strlcat(temp, "SSG", sizeof(temp));
1832 strlcat(temp, ":", sizeof(temp));
1833 if (cl.stats[STAT_ITEMS] & IT_NAILGUN)
1834 strlcat(temp, "NG", sizeof(temp));
1835 strlcat(temp, ":", sizeof(temp));
1836 if (cl.stats[STAT_ITEMS] & IT_SUPER_NAILGUN)
1837 strlcat(temp, "SNG", sizeof(temp));
1838 strlcat(temp, ":", sizeof(temp));
1839 if (cl.stats[STAT_ITEMS] & IT_GRENADE_LAUNCHER)
1840 strlcat(temp, "GL", sizeof(temp));
1841 strlcat(temp, ":", sizeof(temp));
1842 if (cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER)
1843 strlcat(temp, "RL", sizeof(temp));
1844 strlcat(temp, ":", sizeof(temp));
1845 if (cl.stats[STAT_ITEMS] & IT_LIGHTNING)
1846 strlcat(temp, "LG", sizeof(temp));
1849 // not a recognized macro, print it as-is...
1855 // write the resulting text
1856 SZ_Write(&cls.netcon->message, (unsigned char *)temp, strlen(temp));
1860 MSG_WriteByte(&cls.netcon->message, *s);
1863 MSG_WriteByte(&cls.netcon->message, 0);
1865 else // any other command is passed on as-is
1866 SZ_Write(&cls.netcon->message, (const unsigned char *)s, (int)strlen(s) + 1);
1873 Sends the entire command line over to the server
1876 void Cmd_ForwardToServer (void)
1879 if (!strcasecmp(Cmd_Argv(0), "cmd"))
1881 // we want to strip off "cmd", so just send the args
1882 s = Cmd_Argc() > 1 ? Cmd_Args() : "";
1886 // we need to keep the command name, so send Cmd_Argv(0), a space and then Cmd_Args()
1887 s = va("%s %s", Cmd_Argv(0), Cmd_Argc() > 1 ? Cmd_Args() : "");
1889 // don't send an empty forward message if the user tries "cmd" by itself
1892 Cmd_ForwardStringToServer(s);
1900 Returns the position (1 to argc-1) in the command's argument list
1901 where the given parameter apears, or 0 if not present
1905 int Cmd_CheckParm (const char *parm)
1911 Con_Printf ("Cmd_CheckParm: NULL");
1915 for (i = 1; i < Cmd_Argc (); i++)
1916 if (!strcasecmp (parm, Cmd_Argv (i)))
1924 void Cmd_SaveInitState(void)
1928 for (f = cmd_functions;f;f = f->next)
1929 f->initstate = true;
1930 for (a = cmd_alias;a;a = a->next)
1932 a->initstate = true;
1933 a->initialvalue = Mem_strdup(zonemempool, a->value);
1935 Cvar_SaveInitState();
1938 void Cmd_RestoreInitState(void)
1940 cmd_function_t *f, **fp;
1941 cmdalias_t *a, **ap;
1942 for (fp = &cmd_functions;(f = *fp);)
1948 // destroy this command, it didn't exist at init
1949 Con_DPrintf("Cmd_RestoreInitState: Destroying command %s\n", f->name);
1954 for (ap = &cmd_alias;(a = *ap);)
1958 // restore this alias, it existed at init
1959 if (strcmp(a->value ? a->value : "", a->initialvalue ? a->initialvalue : ""))
1961 Con_DPrintf("Cmd_RestoreInitState: Restoring alias %s\n", a->name);
1964 a->value = Mem_strdup(zonemempool, a->initialvalue);
1970 // free this alias, it didn't exist at init...
1971 Con_DPrintf("Cmd_RestoreInitState: Destroying alias %s\n", a->name);
1978 Cvar_RestoreInitState();