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)
67 =============================================================================
71 =============================================================================
74 static sizebuf_t cmd_text;
75 static unsigned char cmd_text_buf[CMDBUFSIZE];
81 Adds command text at the end of the buffer
84 void Cbuf_AddText (const char *text)
88 l = (int)strlen (text);
90 if (cmd_text.cursize + l >= cmd_text.maxsize)
92 Con_Print("Cbuf_AddText: overflow\n");
96 SZ_Write (&cmd_text, (const unsigned char *)text, (int)strlen (text));
104 Adds command text immediately after the current command
105 Adds a \n to the text
106 FIXME: actually change the command buffer to do less copying
109 void Cbuf_InsertText (const char *text)
114 // copy off any commands still remaining in the exec buffer
115 templen = cmd_text.cursize;
118 temp = (char *)Mem_Alloc (tempmempool, templen);
119 memcpy (temp, cmd_text.data, templen);
120 SZ_Clear (&cmd_text);
125 // add the entire text of the file
128 // add the copied off data
131 SZ_Write (&cmd_text, (const unsigned char *)temp, templen);
141 static void Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias );
142 void Cbuf_Execute (void)
146 char line[MAX_INPUTLINE];
147 char preprocessed[MAX_INPUTLINE];
151 // LordHavoc: making sure the tokenizebuffer doesn't get filled up by repeated crashes
152 cmd_tokenizebufferpos = 0;
154 while (cmd_text.cursize)
156 // find a \n or ; line break
157 text = (char *)cmd_text.data;
160 for (i=0 ; i< cmd_text.cursize ; i++)
164 // make sure i doesn't get > cursize which causes a negative
165 // size in memmove, which is fatal --blub
166 if (i < (cmd_text.cursize-1) && (text[i] == '\\' && (text[i+1] == '"' || text[i+1] == '\\')))
168 if ( !quotes && text[i] == ';')
169 break; // don't break if inside a quoted string
170 if (text[i] == '\r' || text[i] == '\n')
174 // better than CRASHING on overlong input lines that may SOMEHOW enter the buffer
175 if(i >= MAX_INPUTLINE)
177 Con_Printf("Warning: console input buffer had an overlong line. Ignored.\n");
182 memcpy (line, text, i);
186 // delete the text from the command buffer and move remaining commands down
187 // this is necessary because commands (exec, alias) can insert data at the
188 // beginning of the text buffer
190 if (i == cmd_text.cursize)
191 cmd_text.cursize = 0;
195 cmd_text.cursize -= i;
196 memmove (cmd_text.data, text+i, cmd_text.cursize);
199 // execute the command line
200 firstchar = line + strspn(line, " \t");
202 (strncmp(firstchar, "alias", 5) || (firstchar[5] != ' ' && firstchar[5] != '\t'))
204 (strncmp(firstchar, "bind", 4) || (firstchar[4] != ' ' && firstchar[4] != '\t'))
206 (strncmp(firstchar, "in_bind", 7) || (firstchar[7] != ' ' && firstchar[7] != '\t'))
209 Cmd_PreprocessString( line, preprocessed, sizeof(preprocessed), NULL );
210 Cmd_ExecuteString (preprocessed, src_command);
214 Cmd_ExecuteString (line, src_command);
218 { // skip out while text still remains in buffer, leaving it
227 ==============================================================================
231 ==============================================================================
238 Adds command line parameters as script statements
239 Commands lead with a +, and continue until a - or another +
240 quake +prog jctest.qp +cmd amlev1
241 quake -nosound +cmd amlev1
244 qboolean host_stuffcmdsrun = false;
245 void Cmd_StuffCmds_f (void)
248 // this is for all commandline options combined (and is bounds checked)
249 char build[MAX_INPUTLINE];
251 if (Cmd_Argc () != 1)
253 Con_Print("stuffcmds : execute command line parameters\n");
257 // no reason to run the commandline arguments twice
258 if (host_stuffcmdsrun)
261 host_stuffcmdsrun = true;
264 for (i = 0;i < com_argc;i++)
266 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)
269 while (com_argv[i][j])
270 build[l++] = com_argv[i][j++];
272 for (;i < com_argc;i++)
276 if ((com_argv[i][0] == '+' || com_argv[i][0] == '-') && (com_argv[i][1] < '0' || com_argv[i][1] > '9'))
278 if (l + strlen(com_argv[i]) + 4 > sizeof(build) - 1)
281 if (strchr(com_argv[i], ' '))
283 for (j = 0;com_argv[i][j];j++)
284 build[l++] = com_argv[i][j];
285 if (strchr(com_argv[i], ' '))
292 // now terminate the combined string and prepend it to the command buffer
293 // we already reserved space for the terminator
295 Cbuf_InsertText (build);
304 static void Cmd_Exec_f (void)
308 if (Cmd_Argc () != 2)
310 Con_Print("exec <filename> : execute a script file\n");
314 f = (char *)FS_LoadFile (Cmd_Argv(1), tempmempool, false, NULL);
317 Con_Printf("couldn't exec %s\n",Cmd_Argv(1));
320 Con_Printf("execing %s\n",Cmd_Argv(1));
322 // if executing default.cfg for the first time, lock the cvar defaults
323 // it may seem backwards to insert this text BEFORE the default.cfg
324 // but Cbuf_InsertText inserts before, so this actually ends up after it.
325 if (!strcmp(Cmd_Argv(1), "default.cfg"))
326 Cbuf_InsertText("\ncvar_lockdefaults\n");
328 // insert newline after the text to make sure the last line is terminated (some text editors omit the trailing newline)
329 // (note: insertion order here is backwards from execution order, so this adds it after the text, by calling it before...)
330 Cbuf_InsertText ("\n");
340 Just prints the rest of the line to the console
343 static void Cmd_Echo_f (void)
347 for (i=1 ; i<Cmd_Argc() ; i++)
348 Con_Printf("%s ",Cmd_Argv(i));
353 // Support Doom3-style Toggle Console Command
358 Toggles a specified console variable amongst the values specified (default is 0 and 1)
361 static void Cmd_Toggle_f(void)
363 // Acquire Number of Arguments
364 int nNumArgs = Cmd_Argc();
367 // No Arguments Specified; Print Usage
368 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");
370 { // Correct Arguments Specified
371 // Acquire Potential CVar
372 cvar_t* cvCVar = Cvar_FindVar( Cmd_Argv(1) );
379 Cvar_SetValueQuick(cvCVar, 0);
381 Cvar_SetValueQuick(cvCVar, 1);
385 { // 0 and Specified Usage
386 if(cvCVar->integer == atoi(Cmd_Argv(2) ) )
387 // CVar is Specified Value; // Reset to 0
388 Cvar_SetValueQuick(cvCVar, 0);
390 if(cvCVar->integer == 0)
391 // CVar is 0; Specify Value
392 Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
394 // CVar does not match; Reset to 0
395 Cvar_SetValueQuick(cvCVar, 0);
398 { // Variable Values Specified
402 for(nCnt = 2; nCnt < nNumArgs; nCnt++)
403 { // Cycle through Values
404 if( strcmp(cvCVar->string, Cmd_Argv(nCnt) ) == 0)
405 { // Current Value Located; Increment to Next
406 if( (nCnt + 1) == nNumArgs)
407 // Max Value Reached; Reset
408 Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
411 Cvar_SetQuick(cvCVar, Cmd_Argv(nCnt + 1) );
420 // Value not Found; Reset to Original
421 Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
427 Con_Printf("ERROR : CVar '%s' not found\n", Cmd_Argv(1) );
436 Creates a new command that executes a command string (possibly ; seperated)
439 static void Cmd_Alias_f (void)
442 char cmd[MAX_INPUTLINE];
449 Con_Print("Current alias commands:\n");
450 for (a = cmd_alias ; a ; a=a->next)
451 Con_Printf("%s : %s\n", a->name, a->value);
456 if (strlen(s) >= MAX_ALIAS_NAME)
458 Con_Print("Alias name is too long\n");
462 // if the alias already exists, reuse it
463 for (a = cmd_alias ; a ; a=a->next)
465 if (!strcmp(s, a->name))
474 cmdalias_t *prev, *current;
476 a = (cmdalias_t *)Z_Malloc (sizeof(cmdalias_t));
477 strlcpy (a->name, s, sizeof (a->name));
478 // insert it at the right alphanumeric position
479 for( prev = NULL, current = cmd_alias ; current && strcmp( current->name, a->name ) < 0 ; prev = current, current = current->next )
490 // copy the rest of the command line
491 cmd[0] = 0; // start out with a null string
493 for (i=2 ; i< c ; i++)
495 strlcat (cmd, Cmd_Argv(i), sizeof (cmd));
497 strlcat (cmd, " ", sizeof (cmd));
499 strlcat (cmd, "\n", sizeof (cmd));
501 alloclen = strlen (cmd) + 1;
502 a->value = (char *)Z_Malloc (alloclen);
503 memcpy (a->value, cmd, alloclen);
507 =============================================================================
511 =============================================================================
514 typedef struct cmd_function_s
516 struct cmd_function_s *next;
518 const char *description;
519 xcommand_t consolefunction;
520 xcommand_t clientfunction;
525 static const char *cmd_argv[MAX_ARGS];
526 static const char *cmd_null_string = "";
527 static const char *cmd_args;
528 cmd_source_t cmd_source;
531 static cmd_function_t *cmd_functions; // possible commands to execute
533 static const char *Cmd_GetDirectCvarValue(const char *varname, cmdalias_t *alias, qboolean *is_multiple)
540 *is_multiple = false;
542 if(!varname || !*varname)
547 if(!strcmp(varname, "*"))
553 else if(varname[strlen(varname) - 1] == '-')
555 argno = strtol(varname, &endptr, 10);
556 if(endptr == varname + strlen(varname) - 1)
558 // whole string is a number, apart from the -
559 const char *p = Cmd_Args();
560 for(; argno > 1; --argno)
561 if(!COM_ParseToken_Console(&p))
568 // kill pre-argument whitespace
569 for (;*p && *p <= ' ';p++)
578 argno = strtol(varname, &endptr, 10);
581 // whole string is a number
582 // NOTE: we already made sure we don't have an empty cvar name!
583 if(argno >= 0 && argno < Cmd_Argc())
584 return Cmd_Argv(argno);
589 if((cvar = Cvar_FindVar(varname)) && !(cvar->flags & CVAR_PRIVATE))
595 qboolean Cmd_QuoteString(char *out, size_t outlen, const char *in, const char *quoteset)
597 qboolean quote_quot = !!strchr(quoteset, '"');
598 qboolean quote_backslash = !!strchr(quoteset, '\\');
599 qboolean quote_dollar = !!strchr(quoteset, '$');
603 if(*in == '"' && quote_quot)
610 *out++ = '\\'; --outlen;
611 *out++ = '"'; --outlen;
613 else if(*in == '\\' && quote_backslash)
620 *out++ = '\\'; --outlen;
621 *out++ = '\\'; --outlen;
623 else if(*in == '$' && quote_dollar)
630 *out++ = '$'; --outlen;
631 *out++ = '$'; --outlen;
640 *out++ = *in; --outlen;
648 static const char *Cmd_GetCvarValue(const char *var, size_t varlen, cmdalias_t *alias)
650 static char varname[MAX_INPUTLINE];
651 static char varval[MAX_INPUTLINE];
655 if(varlen >= MAX_INPUTLINE)
656 varlen = MAX_INPUTLINE - 1;
657 memcpy(varname, var, varlen);
659 varfunc = strchr(varname, ' ');
675 if(varname[0] == '$')
676 varstr = Cmd_GetDirectCvarValue(Cmd_GetDirectCvarValue(varname + 1, alias, NULL), alias, NULL);
679 qboolean is_multiple = false;
680 // Exception: $* and $n- don't use the quoted form by default
681 varstr = Cmd_GetDirectCvarValue(varname, alias, &is_multiple);
689 Con_Printf("Warning: Could not expand $%s in alias %s\n", varname, alias->name);
691 Con_Printf("Warning: Could not expand $%s\n", varname);
695 if(!varfunc || !strcmp(varfunc, "q")) // note: quoted form is default, use "asis" to override!
697 // quote it so it can be used inside double quotes
698 // we just need to replace " by \", and of course, double backslashes
699 Cmd_QuoteString(varval, sizeof(varval), varstr, "\"\\");
702 else if(!strcmp(varfunc, "asis"))
707 Con_Printf("Unknown variable function %s\n", varfunc);
715 Preprocesses strings and replaces $*, $param#, $cvar accordingly
717 static void Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias ) {
723 // don't crash if there's no room in the outtext buffer
724 if( maxoutlen == 0 ) {
727 maxoutlen--; // because of \0
732 while( *in && outlen < maxoutlen ) {
734 // this is some kind of expansion, see what comes after the $
737 // The console does the following preprocessing:
739 // - $$ is transformed to a single dollar sign.
740 // - $var or ${var} are expanded to the contents of the named cvar,
741 // with quotation marks and backslashes quoted so it can safely
742 // be used inside quotation marks (and it should always be used
744 // - ${var asis} inserts the cvar value as is, without doing this
746 // - prefix the cvar name with a dollar sign to do indirection;
747 // for example, if $x has the value timelimit, ${$x} will return
748 // the value of $timelimit
749 // - when expanding an alias, the special variable name $* refers
750 // to all alias parameters, and a number refers to that numbered
751 // alias parameter, where the name of the alias is $0, the first
752 // parameter is $1 and so on; as a special case, $* inserts all
753 // parameters, without extra quoting, so one can use $* to just
754 // pass all parameters around. All parameters starting from $n
755 // can be referred to as $n- (so $* is equivalent to $1-).
757 // Note: when expanding an alias, cvar expansion is done in the SAME step
758 // as alias expansion so that alias parameters or cvar values containing
759 // dollar signs have no unwanted bad side effects. However, this needs to
760 // be accounted for when writing complex aliases. For example,
761 // alias foo "set x NEW; echo $x"
762 // actually expands to
763 // "set x NEW; echo OLD"
764 // and will print OLD! To work around this, use a second alias:
765 // alias foo "set x NEW; foo2"
766 // alias foo2 "echo $x"
768 // Also note: lines starting with alias are exempt from cvar expansion.
769 // If you want cvar expansion, write "alias" instead:
772 // alias foo "echo $x"
773 // "alias" bar "echo $x"
776 // foo will print 2, because the variable $x will be expanded when the alias
777 // gets expanded. bar will print 1, because the variable $x was expanded
778 // at definition time. foo can be equivalently defined as
780 // "alias" foo "echo $$x"
782 // because at definition time, $$ will get replaced to a single $.
787 } else if(*in == '{') {
788 varlen = strcspn(in + 1, "}");
789 if(in[varlen + 1] == '}')
791 val = Cmd_GetCvarValue(in + 1, varlen, alias);
801 varlen = strspn(in, "*0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-");
802 val = Cmd_GetCvarValue(in, varlen, alias);
807 // insert the cvar value
808 while(*val && outlen < maxoutlen)
809 outtext[outlen++] = *val++;
814 // copy the unexpanded text
815 outtext[outlen++] = '$';
816 while(eat && outlen < maxoutlen)
818 outtext[outlen++] = *in++;
823 outtext[outlen++] = *in++;
833 Called for aliases and fills in the alias into the cbuffer
836 static void Cmd_ExecuteAlias (cmdalias_t *alias)
838 static char buffer[ MAX_INPUTLINE ];
839 static char buffer2[ MAX_INPUTLINE ];
840 Cmd_PreprocessString( alias->value, buffer, sizeof(buffer) - 2, alias );
841 // insert at start of command buffer, so that aliases execute in order
842 // (fixes bug introduced by Black on 20050705)
844 // Note: Cbuf_PreprocessString will be called on this string AGAIN! So we
845 // have to make sure that no second variable expansion takes place, otherwise
846 // alias parameters containing dollar signs can have bad effects.
847 Cmd_QuoteString(buffer2, sizeof(buffer2), buffer, "$");
848 Cbuf_InsertText( buffer2 );
855 CmdList Added by EvilTypeGuy eviltypeguy@qeradiant.com
856 Thanks to Matthias "Maddes" Buecher, http://www.inside3d.com/qip/
860 static void Cmd_List_f (void)
868 partial = Cmd_Argv (1);
869 len = (int)strlen(partial);
878 for (cmd = cmd_functions; cmd; cmd = cmd->next)
880 if (partial && strncmp(partial, cmd->name, len))
882 Con_Printf("%s : %s\n", cmd->name, cmd->description);
887 Con_Printf("%i Command%s beginning with \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
889 Con_Printf("%i Command%s\n\n", count, (count > 1) ? "s" : "");
899 cmd_mempool = Mem_AllocPool("commands", 0, NULL);
900 // space for commands and script files
901 cmd_text.data = cmd_text_buf;
902 cmd_text.maxsize = sizeof(cmd_text_buf);
903 cmd_text.cursize = 0;
906 void Cmd_Init_Commands (void)
909 // register our commands
911 Cmd_AddCommand ("stuffcmds",Cmd_StuffCmds_f, "execute commandline parameters (must be present in quake.rc script)");
912 Cmd_AddCommand ("exec",Cmd_Exec_f, "execute a script file");
913 Cmd_AddCommand ("echo",Cmd_Echo_f, "print a message to the console (useful in scripts)");
914 Cmd_AddCommand ("alias",Cmd_Alias_f, "create a script function (parameters are passed in as $1 through $9, and $* for all parameters)");
915 Cmd_AddCommand ("cmd", Cmd_ForwardToServer, "send a console commandline to the server (used by some mods)");
916 Cmd_AddCommand ("wait", Cmd_Wait_f, "make script execution wait for next rendered frame");
917 Cmd_AddCommand ("set", Cvar_Set_f, "create or change the value of a console variable");
918 Cmd_AddCommand ("seta", Cvar_SetA_f, "create or change the value of a console variable that will be saved to config.cfg");
920 // 2000-01-09 CmdList, CvarList commands By Matthias "Maddes" Buecher
921 // Added/Modified by EvilTypeGuy eviltypeguy@qeradiant.com
922 Cmd_AddCommand ("cmdlist", Cmd_List_f, "lists all console commands beginning with the specified prefix");
923 Cmd_AddCommand ("cvarlist", Cvar_List_f, "lists all console variables beginning with the specified prefix");
925 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");
926 Cmd_AddCommand ("cvar_resettodefaults_all", Cvar_ResetToDefaults_All_f, "sets all cvars to their locked default values");
927 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)");
928 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)");
931 // Support Doom3-style Toggle Command
932 Cmd_AddCommand( "toggle", Cmd_Toggle_f, "toggles a console variable's values (use for more info)");
940 void Cmd_Shutdown(void)
942 Mem_FreePool(&cmd_mempool);
960 const char *Cmd_Argv (int arg)
962 if (arg >= cmd_argc )
963 return cmd_null_string;
964 return cmd_argv[arg];
972 const char *Cmd_Args (void)
982 Parses the given string into command line tokens.
985 // AK: This function should only be called from ExcuteString because the current design is a bit of an hack
986 static void Cmd_TokenizeString (const char *text)
995 // skip whitespace up to a /n
996 while (*text && *text <= ' ' && *text != '\r' && *text != '\n')
1003 if (*text == '\n' || *text == '\r')
1005 // a newline separates commands in the buffer
1006 if (*text == '\r' && text[1] == '\n')
1018 if (!COM_ParseToken_Console(&text))
1021 if (cmd_argc < MAX_ARGS)
1023 l = (int)strlen(com_token) + 1;
1024 if (cmd_tokenizebufferpos + l > CMD_TOKENIZELENGTH)
1026 Con_Printf("Cmd_TokenizeString: ran out of %i character buffer space for command arguements\n", CMD_TOKENIZELENGTH);
1029 memcpy (cmd_tokenizebuffer + cmd_tokenizebufferpos, com_token, l);
1030 cmd_argv[cmd_argc] = cmd_tokenizebuffer + cmd_tokenizebufferpos;
1031 cmd_tokenizebufferpos += l;
1043 void Cmd_AddCommand_WithClientCommand (const char *cmd_name, xcommand_t consolefunction, xcommand_t clientfunction, const char *description)
1045 cmd_function_t *cmd;
1046 cmd_function_t *prev, *current;
1048 // fail if the command is a variable name
1049 if (Cvar_FindVar( cmd_name ))
1051 Con_Printf("Cmd_AddCommand: %s already defined as a var\n", cmd_name);
1055 // fail if the command already exists
1056 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1058 if (!strcmp (cmd_name, cmd->name))
1060 if (consolefunction || clientfunction)
1062 Con_Printf("Cmd_AddCommand: %s already defined\n", cmd_name);
1067 cmd->csqcfunc = true;
1073 cmd = (cmd_function_t *)Mem_Alloc(cmd_mempool, sizeof(cmd_function_t));
1074 cmd->name = cmd_name;
1075 cmd->consolefunction = consolefunction;
1076 cmd->clientfunction = clientfunction;
1077 cmd->description = description;
1078 if(!consolefunction && !clientfunction) //[515]: csqc
1079 cmd->csqcfunc = true;
1080 cmd->next = cmd_functions;
1082 // insert it at the right alphanumeric position
1083 for( prev = NULL, current = cmd_functions ; current && strcmp( current->name, cmd->name ) < 0 ; prev = current, current = current->next )
1088 cmd_functions = cmd;
1090 cmd->next = current;
1093 void Cmd_AddCommand (const char *cmd_name, xcommand_t function, const char *description)
1095 Cmd_AddCommand_WithClientCommand (cmd_name, function, NULL, description);
1103 qboolean Cmd_Exists (const char *cmd_name)
1105 cmd_function_t *cmd;
1107 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1108 if (!strcmp (cmd_name,cmd->name))
1120 const char *Cmd_CompleteCommand (const char *partial)
1122 cmd_function_t *cmd;
1125 len = strlen(partial);
1131 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1132 if (!strncasecmp(partial, cmd->name, len))
1139 Cmd_CompleteCountPossible
1141 New function for tab-completion system
1142 Added by EvilTypeGuy
1143 Thanks to Fett erich@heintz.com
1147 int Cmd_CompleteCountPossible (const char *partial)
1149 cmd_function_t *cmd;
1154 len = strlen(partial);
1159 // Loop through the command list and count all partial matches
1160 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1161 if (!strncasecmp(partial, cmd->name, len))
1168 Cmd_CompleteBuildList
1170 New function for tab-completion system
1171 Added by EvilTypeGuy
1172 Thanks to Fett erich@heintz.com
1176 const char **Cmd_CompleteBuildList (const char *partial)
1178 cmd_function_t *cmd;
1181 size_t sizeofbuf = (Cmd_CompleteCountPossible (partial) + 1) * sizeof (const char *);
1184 len = strlen(partial);
1185 buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1186 // Loop through the alias list and print all matches
1187 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1188 if (!strncasecmp(partial, cmd->name, len))
1189 buf[bpos++] = cmd->name;
1195 // written by LordHavoc
1196 void Cmd_CompleteCommandPrint (const char *partial)
1198 cmd_function_t *cmd;
1199 size_t len = strlen(partial);
1200 // Loop through the command list and print all matches
1201 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1202 if (!strncasecmp(partial, cmd->name, len))
1203 Con_Printf("%s : %s\n", cmd->name, cmd->description);
1209 New function for tab-completion system
1210 Added by EvilTypeGuy
1211 Thanks to Fett erich@heintz.com
1215 const char *Cmd_CompleteAlias (const char *partial)
1220 len = strlen(partial);
1226 for (alias = cmd_alias; alias; alias = alias->next)
1227 if (!strncasecmp(partial, alias->name, len))
1233 // written by LordHavoc
1234 void Cmd_CompleteAliasPrint (const char *partial)
1237 size_t len = strlen(partial);
1238 // Loop through the alias list and print all matches
1239 for (alias = cmd_alias; alias; alias = alias->next)
1240 if (!strncasecmp(partial, alias->name, len))
1241 Con_Printf("%s : %s\n", alias->name, alias->value);
1246 Cmd_CompleteAliasCountPossible
1248 New function for tab-completion system
1249 Added by EvilTypeGuy
1250 Thanks to Fett erich@heintz.com
1254 int Cmd_CompleteAliasCountPossible (const char *partial)
1262 len = strlen(partial);
1267 // Loop through the command list and count all partial matches
1268 for (alias = cmd_alias; alias; alias = alias->next)
1269 if (!strncasecmp(partial, alias->name, len))
1276 Cmd_CompleteAliasBuildList
1278 New function for tab-completion system
1279 Added by EvilTypeGuy
1280 Thanks to Fett erich@heintz.com
1284 const char **Cmd_CompleteAliasBuildList (const char *partial)
1289 size_t sizeofbuf = (Cmd_CompleteAliasCountPossible (partial) + 1) * sizeof (const char *);
1292 len = strlen(partial);
1293 buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1294 // Loop through the alias list and print all matches
1295 for (alias = cmd_alias; alias; alias = alias->next)
1296 if (!strncasecmp(partial, alias->name, len))
1297 buf[bpos++] = alias->name;
1303 void Cmd_ClearCsqcFuncs (void)
1305 cmd_function_t *cmd;
1306 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1307 cmd->csqcfunc = false;
1310 qboolean CL_VM_ConsoleCommand (const char *cmd);
1315 A complete command line has been parsed, so try to execute it
1316 FIXME: lookupnoadd the token to speed search?
1319 void Cmd_ExecuteString (const char *text, cmd_source_t src)
1322 cmd_function_t *cmd;
1325 oldpos = cmd_tokenizebufferpos;
1328 Cmd_TokenizeString (text);
1330 // execute the command line
1333 cmd_tokenizebufferpos = oldpos;
1334 return; // no tokens
1338 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1340 if (!strcasecmp (cmd_argv[0],cmd->name))
1342 if (cmd->csqcfunc && CL_VM_ConsoleCommand (text)) //[515]: csqc
1347 if (cmd->consolefunction)
1348 cmd->consolefunction ();
1349 else if (cmd->clientfunction)
1351 if (cls.state == ca_connected)
1353 // forward remote commands to the server for execution
1354 Cmd_ForwardToServer();
1357 Con_Printf("Can not send command \"%s\", not connected.\n", Cmd_Argv(0));
1360 Con_Printf("Command \"%s\" can not be executed\n", Cmd_Argv(0));
1361 cmd_tokenizebufferpos = oldpos;
1364 if (cmd->clientfunction)
1366 cmd->clientfunction ();
1367 cmd_tokenizebufferpos = oldpos;
1376 // if it's a client command and no command was found, say so.
1377 if (cmd_source == src_client)
1379 Con_Printf("player \"%s\" tried to %s\n", host_client->name, text);
1384 for (a=cmd_alias ; a ; a=a->next)
1386 if (!strcasecmp (cmd_argv[0], a->name))
1388 Cmd_ExecuteAlias(a);
1389 cmd_tokenizebufferpos = oldpos;
1395 if (!Cvar_Command () && host_framecount > 0)
1396 Con_Printf("Unknown command \"%s\"\n", Cmd_Argv(0));
1398 cmd_tokenizebufferpos = oldpos;
1404 Cmd_ForwardStringToServer
1406 Sends an entire command string over to the server, unprocessed
1409 void Cmd_ForwardStringToServer (const char *s)
1412 if (cls.state != ca_connected)
1414 Con_Printf("Can't \"%s\", not connected\n", s);
1421 // LordHavoc: thanks to Fuh for bringing the pure evil of SZ_Print to my
1422 // attention, it has been eradicated from here, its only (former) use in
1423 // all of darkplaces.
1424 if (cls.protocol == PROTOCOL_QUAKEWORLD)
1425 MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
1427 MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
1428 if ((!strncmp(s, "say ", 4) || !strncmp(s, "say_team ", 9)) && cl_locs_enable.integer)
1430 // say/say_team commands can replace % character codes with status info
1433 if (*s == '%' && s[1])
1435 // handle proquake message macros
1439 case 'l': // current location
1440 CL_Locs_FindLocationName(temp, sizeof(temp), cl.movement_origin);
1442 case 'h': // current health
1443 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_HEALTH]);
1445 case 'a': // current armor
1446 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ARMOR]);
1448 case 'x': // current rockets
1449 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ROCKETS]);
1451 case 'c': // current cells
1452 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_CELLS]);
1454 // silly proquake macros
1455 case 'd': // loc at last death
1456 CL_Locs_FindLocationName(temp, sizeof(temp), cl.lastdeathorigin);
1458 case 't': // current time
1459 dpsnprintf(temp, sizeof(temp), "%.0f:%.0f", floor(cl.time / 60), cl.time - floor(cl.time / 60) * 60);
1461 case 'r': // rocket launcher status ("I have RL", "I need rockets", "I need RL")
1462 if (!(cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER))
1463 dpsnprintf(temp, sizeof(temp), "I need RL");
1464 else if (!cl.stats[STAT_ROCKETS])
1465 dpsnprintf(temp, sizeof(temp), "I need rockets");
1467 dpsnprintf(temp, sizeof(temp), "I have RL");
1469 case 'p': // powerup status (outputs "quad" "pent" and "eyes" according to status)
1470 if (cl.stats[STAT_ITEMS] & IT_QUAD)
1473 strlcat(temp, " ", sizeof(temp));
1474 strlcat(temp, "quad", sizeof(temp));
1476 if (cl.stats[STAT_ITEMS] & IT_INVULNERABILITY)
1479 strlcat(temp, " ", sizeof(temp));
1480 strlcat(temp, "pent", sizeof(temp));
1482 if (cl.stats[STAT_ITEMS] & IT_INVISIBILITY)
1485 strlcat(temp, " ", sizeof(temp));
1486 strlcat(temp, "eyes", sizeof(temp));
1489 case 'w': // weapon status (outputs "SSG:NG:SNG:GL:RL:LG" with the text between : characters omitted if you lack the weapon)
1490 if (cl.stats[STAT_ITEMS] & IT_SUPER_SHOTGUN)
1491 strlcat(temp, "SSG", sizeof(temp));
1492 strlcat(temp, ":", sizeof(temp));
1493 if (cl.stats[STAT_ITEMS] & IT_NAILGUN)
1494 strlcat(temp, "NG", sizeof(temp));
1495 strlcat(temp, ":", sizeof(temp));
1496 if (cl.stats[STAT_ITEMS] & IT_SUPER_NAILGUN)
1497 strlcat(temp, "SNG", sizeof(temp));
1498 strlcat(temp, ":", sizeof(temp));
1499 if (cl.stats[STAT_ITEMS] & IT_GRENADE_LAUNCHER)
1500 strlcat(temp, "GL", sizeof(temp));
1501 strlcat(temp, ":", sizeof(temp));
1502 if (cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER)
1503 strlcat(temp, "RL", sizeof(temp));
1504 strlcat(temp, ":", sizeof(temp));
1505 if (cl.stats[STAT_ITEMS] & IT_LIGHTNING)
1506 strlcat(temp, "LG", sizeof(temp));
1509 // not a recognized macro, print it as-is...
1515 // write the resulting text
1516 SZ_Write(&cls.netcon->message, (unsigned char *)temp, strlen(temp));
1520 MSG_WriteByte(&cls.netcon->message, *s);
1523 MSG_WriteByte(&cls.netcon->message, 0);
1525 else // any other command is passed on as-is
1526 SZ_Write(&cls.netcon->message, (const unsigned char *)s, (int)strlen(s) + 1);
1533 Sends the entire command line over to the server
1536 void Cmd_ForwardToServer (void)
1539 if (!strcasecmp(Cmd_Argv(0), "cmd"))
1541 // we want to strip off "cmd", so just send the args
1542 s = Cmd_Argc() > 1 ? Cmd_Args() : "";
1546 // we need to keep the command name, so send Cmd_Argv(0), a space and then Cmd_Args()
1547 s = va("%s %s", Cmd_Argv(0), Cmd_Argc() > 1 ? Cmd_Args() : "");
1549 // don't send an empty forward message if the user tries "cmd" by itself
1552 Cmd_ForwardStringToServer(s);
1560 Returns the position (1 to argc-1) in the command's argument list
1561 where the given parameter apears, or 0 if not present
1565 int Cmd_CheckParm (const char *parm)
1571 Con_Printf ("Cmd_CheckParm: NULL");
1575 for (i = 1; i < Cmd_Argc (); i++)
1576 if (!strcasecmp (parm, Cmd_Argv (i)))