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 if (text[i] == '\\' && (text[i+1] == '"' || text[i+1] == '\\'))
166 if ( !quotes && text[i] == ';')
167 break; // don't break if inside a quoted string
168 if (text[i] == '\r' || text[i] == '\n')
172 /* should never happen
173 if(i >= MAX_INPUTLINE)
174 i = MAX_INPUTLINE - 1;
177 memcpy (line, text, i);
180 // delete the text from the command buffer and move remaining commands down
181 // this is necessary because commands (exec, alias) can insert data at the
182 // beginning of the text buffer
184 if (i == cmd_text.cursize)
185 cmd_text.cursize = 0;
189 cmd_text.cursize -= i;
190 memmove (cmd_text.data, text+i, cmd_text.cursize);
193 // execute the command line
194 firstchar = line + strspn(line, " \t");
196 (strncmp(firstchar, "alias", 5) || (firstchar[5] != ' ' && firstchar[5] != '\t'))
198 (strncmp(firstchar, "bind", 4) || (firstchar[4] != ' ' && firstchar[4] != '\t'))
200 (strncmp(firstchar, "in_bind", 7) || (firstchar[7] != ' ' && firstchar[7] != '\t'))
203 Cmd_PreprocessString( line, preprocessed, sizeof(preprocessed), NULL );
204 Cmd_ExecuteString (preprocessed, src_command);
208 Cmd_ExecuteString (line, src_command);
212 { // skip out while text still remains in buffer, leaving it
221 ==============================================================================
225 ==============================================================================
232 Adds command line parameters as script statements
233 Commands lead with a +, and continue until a - or another +
234 quake +prog jctest.qp +cmd amlev1
235 quake -nosound +cmd amlev1
238 qboolean host_stuffcmdsrun = false;
239 void Cmd_StuffCmds_f (void)
242 // this is for all commandline options combined (and is bounds checked)
243 char build[MAX_INPUTLINE];
245 if (Cmd_Argc () != 1)
247 Con_Print("stuffcmds : execute command line parameters\n");
251 // no reason to run the commandline arguments twice
252 if (host_stuffcmdsrun)
255 host_stuffcmdsrun = true;
258 for (i = 0;i < com_argc;i++)
260 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)
263 while (com_argv[i][j])
264 build[l++] = com_argv[i][j++];
266 for (;i < com_argc;i++)
270 if ((com_argv[i][0] == '+' || com_argv[i][0] == '-') && (com_argv[i][1] < '0' || com_argv[i][1] > '9'))
272 if (l + strlen(com_argv[i]) + 4 > sizeof(build) - 1)
275 if (strchr(com_argv[i], ' '))
277 for (j = 0;com_argv[i][j];j++)
278 build[l++] = com_argv[i][j];
279 if (strchr(com_argv[i], ' '))
286 // now terminate the combined string and prepend it to the command buffer
287 // we already reserved space for the terminator
289 Cbuf_InsertText (build);
298 static void Cmd_Exec_f (void)
302 if (Cmd_Argc () != 2)
304 Con_Print("exec <filename> : execute a script file\n");
308 f = (char *)FS_LoadFile (Cmd_Argv(1), tempmempool, false, NULL);
311 Con_Printf("couldn't exec %s\n",Cmd_Argv(1));
314 Con_Printf("execing %s\n",Cmd_Argv(1));
316 // if executing default.cfg for the first time, lock the cvar defaults
317 // it may seem backwards to insert this text BEFORE the default.cfg
318 // but Cbuf_InsertText inserts before, so this actually ends up after it.
319 if (!strcmp(Cmd_Argv(1), "default.cfg"))
320 Cbuf_InsertText("\ncvar_lockdefaults\n");
322 // insert newline after the text to make sure the last line is terminated (some text editors omit the trailing newline)
323 // (note: insertion order here is backwards from execution order, so this adds it after the text, by calling it before...)
324 Cbuf_InsertText ("\n");
334 Just prints the rest of the line to the console
337 static void Cmd_Echo_f (void)
341 for (i=1 ; i<Cmd_Argc() ; i++)
342 Con_Printf("%s ",Cmd_Argv(i));
347 // Support Doom3-style Toggle Console Command
352 Toggles a specified console variable amongst the values specified (default is 0 and 1)
355 static void Cmd_Toggle_f(void)
357 // Acquire Number of Arguments
358 int nNumArgs = Cmd_Argc();
361 // No Arguments Specified; Print Usage
362 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");
364 { // Correct Arguments Specified
365 // Acquire Potential CVar
366 cvar_t* cvCVar = Cvar_FindVar( Cmd_Argv(1) );
373 Cvar_SetValueQuick(cvCVar, 0);
375 Cvar_SetValueQuick(cvCVar, 1);
379 { // 0 and Specified Usage
380 if(cvCVar->integer == atoi(Cmd_Argv(2) ) )
381 // CVar is Specified Value; // Reset to 0
382 Cvar_SetValueQuick(cvCVar, 0);
384 if(cvCVar->integer == 0)
385 // CVar is 0; Specify Value
386 Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
388 // CVar does not match; Reset to 0
389 Cvar_SetValueQuick(cvCVar, 0);
392 { // Variable Values Specified
396 for(nCnt = 2; nCnt < nNumArgs; nCnt++)
397 { // Cycle through Values
398 if( strcmp(cvCVar->string, Cmd_Argv(nCnt) ) == 0)
399 { // Current Value Located; Increment to Next
400 if( (nCnt + 1) == nNumArgs)
401 // Max Value Reached; Reset
402 Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
405 Cvar_SetQuick(cvCVar, Cmd_Argv(nCnt + 1) );
414 // Value not Found; Reset to Original
415 Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
421 Con_Printf("ERROR : CVar '%s' not found\n", Cmd_Argv(1) );
430 Creates a new command that executes a command string (possibly ; seperated)
433 static void Cmd_Alias_f (void)
436 char cmd[MAX_INPUTLINE];
443 Con_Print("Current alias commands:\n");
444 for (a = cmd_alias ; a ; a=a->next)
445 Con_Printf("%s : %s\n", a->name, a->value);
450 if (strlen(s) >= MAX_ALIAS_NAME)
452 Con_Print("Alias name is too long\n");
456 // if the alias already exists, reuse it
457 for (a = cmd_alias ; a ; a=a->next)
459 if (!strcmp(s, a->name))
468 cmdalias_t *prev, *current;
470 a = (cmdalias_t *)Z_Malloc (sizeof(cmdalias_t));
471 strlcpy (a->name, s, sizeof (a->name));
472 // insert it at the right alphanumeric position
473 for( prev = NULL, current = cmd_alias ; current && strcmp( current->name, a->name ) < 0 ; prev = current, current = current->next )
484 // copy the rest of the command line
485 cmd[0] = 0; // start out with a null string
487 for (i=2 ; i< c ; i++)
489 strlcat (cmd, Cmd_Argv(i), sizeof (cmd));
491 strlcat (cmd, " ", sizeof (cmd));
493 strlcat (cmd, "\n", sizeof (cmd));
495 alloclen = strlen (cmd) + 1;
496 a->value = (char *)Z_Malloc (alloclen);
497 memcpy (a->value, cmd, alloclen);
501 =============================================================================
505 =============================================================================
508 typedef struct cmd_function_s
510 struct cmd_function_s *next;
512 const char *description;
513 xcommand_t consolefunction;
514 xcommand_t clientfunction;
519 static const char *cmd_argv[MAX_ARGS];
520 static const char *cmd_null_string = "";
521 static const char *cmd_args;
522 cmd_source_t cmd_source;
525 static cmd_function_t *cmd_functions; // possible commands to execute
527 static const char *Cmd_GetDirectCvarValue(const char *varname, cmdalias_t *alias, qboolean *is_multiple)
534 *is_multiple = false;
536 if(!varname || !*varname)
541 if(!strcmp(varname, "*"))
547 else if(varname[strlen(varname) - 1] == '-')
549 argno = strtol(varname, &endptr, 10);
550 if(endptr == varname + strlen(varname) - 1)
552 // whole string is a number, apart from the -
553 const char *p = Cmd_Args();
554 for(; argno > 1; --argno)
555 if(!COM_ParseToken_Console(&p))
562 // kill pre-argument whitespace
563 for (;*p && *p <= ' ';p++)
572 argno = strtol(varname, &endptr, 10);
575 // whole string is a number
576 // NOTE: we already made sure we don't have an empty cvar name!
577 if(argno >= 0 && argno < Cmd_Argc())
578 return Cmd_Argv(argno);
583 if((cvar = Cvar_FindVar(varname)) && !(cvar->flags & CVAR_PRIVATE))
589 qboolean Cmd_QuoteString(char *out, size_t outlen, const char *in, const char *quoteset)
591 qboolean quote_quot = !!strchr(quoteset, '"');
592 qboolean quote_backslash = !!strchr(quoteset, '\\');
593 qboolean quote_dollar = !!strchr(quoteset, '$');
597 if(*in == '"' && quote_quot)
604 *out++ = '\\'; --outlen;
605 *out++ = '"'; --outlen;
607 else if(*in == '\\' && quote_backslash)
614 *out++ = '\\'; --outlen;
615 *out++ = '\\'; --outlen;
617 else if(*in == '$' && quote_dollar)
624 *out++ = '$'; --outlen;
625 *out++ = '$'; --outlen;
634 *out++ = *in; --outlen;
642 static const char *Cmd_GetCvarValue(const char *var, size_t varlen, cmdalias_t *alias)
644 static char varname[MAX_INPUTLINE];
645 static char varval[MAX_INPUTLINE];
649 if(varlen >= MAX_INPUTLINE)
650 varlen = MAX_INPUTLINE - 1;
651 memcpy(varname, var, varlen);
653 varfunc = strchr(varname, ' ');
669 if(varname[0] == '$')
670 varstr = Cmd_GetDirectCvarValue(Cmd_GetDirectCvarValue(varname + 1, alias, NULL), alias, NULL);
673 qboolean is_multiple = false;
674 // Exception: $* and $n- don't use the quoted form by default
675 varstr = Cmd_GetDirectCvarValue(varname, alias, &is_multiple);
683 Con_Printf("Warning: Could not expand $%s in alias %s\n", varname, alias->name);
685 Con_Printf("Warning: Could not expand $%s\n", varname);
689 if(!varfunc || !strcmp(varfunc, "q")) // note: quoted form is default, use "asis" to override!
691 // quote it so it can be used inside double quotes
692 // we just need to replace " by \", and of course, double backslashes
693 Cmd_QuoteString(varval, sizeof(varval), varstr, "\"\\");
696 else if(!strcmp(varfunc, "asis"))
701 Con_Printf("Unknown variable function %s\n", varfunc);
709 Preprocesses strings and replaces $*, $param#, $cvar accordingly
711 static void Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias ) {
717 // don't crash if there's no room in the outtext buffer
718 if( maxoutlen == 0 ) {
721 maxoutlen--; // because of \0
726 while( *in && outlen < maxoutlen ) {
728 // this is some kind of expansion, see what comes after the $
731 // The console does the following preprocessing:
733 // - $$ is transformed to a single dollar sign.
734 // - $var or ${var} are expanded to the contents of the named cvar,
735 // with quotation marks and backslashes quoted so it can safely
736 // be used inside quotation marks (and it should always be used
738 // - ${var asis} inserts the cvar value as is, without doing this
740 // - prefix the cvar name with a dollar sign to do indirection;
741 // for example, if $x has the value timelimit, ${$x} will return
742 // the value of $timelimit
743 // - when expanding an alias, the special variable name $* refers
744 // to all alias parameters, and a number refers to that numbered
745 // alias parameter, where the name of the alias is $0, the first
746 // parameter is $1 and so on; as a special case, $* inserts all
747 // parameters, without extra quoting, so one can use $* to just
748 // pass all parameters around. All parameters starting from $n
749 // can be referred to as $n- (so $* is equivalent to $1-).
751 // Note: when expanding an alias, cvar expansion is done in the SAME step
752 // as alias expansion so that alias parameters or cvar values containing
753 // dollar signs have no unwanted bad side effects. However, this needs to
754 // be accounted for when writing complex aliases. For example,
755 // alias foo "set x NEW; echo $x"
756 // actually expands to
757 // "set x NEW; echo OLD"
758 // and will print OLD! To work around this, use a second alias:
759 // alias foo "set x NEW; foo2"
760 // alias foo2 "echo $x"
762 // Also note: lines starting with alias are exempt from cvar expansion.
763 // If you want cvar expansion, write "alias" instead:
766 // alias foo "echo $x"
767 // "alias" bar "echo $x"
770 // foo will print 2, because the variable $x will be expanded when the alias
771 // gets expanded. bar will print 1, because the variable $x was expanded
772 // at definition time. foo can be equivalently defined as
774 // "alias" foo "echo $$x"
776 // because at definition time, $$ will get replaced to a single $.
781 } else if(*in == '{') {
782 varlen = strcspn(in + 1, "}");
783 if(in[varlen + 1] == '}')
785 val = Cmd_GetCvarValue(in + 1, varlen, alias);
795 varlen = strspn(in, "*0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-");
796 val = Cmd_GetCvarValue(in, varlen, alias);
801 // insert the cvar value
802 while(*val && outlen < maxoutlen)
803 outtext[outlen++] = *val++;
808 // copy the unexpanded text
809 outtext[outlen++] = '$';
810 while(eat && outlen < maxoutlen)
812 outtext[outlen++] = *in++;
817 outtext[outlen++] = *in++;
827 Called for aliases and fills in the alias into the cbuffer
830 static void Cmd_ExecuteAlias (cmdalias_t *alias)
832 static char buffer[ MAX_INPUTLINE ];
833 static char buffer2[ MAX_INPUTLINE ];
834 Cmd_PreprocessString( alias->value, buffer, sizeof(buffer) - 2, alias );
835 // insert at start of command buffer, so that aliases execute in order
836 // (fixes bug introduced by Black on 20050705)
838 // Note: Cbuf_PreprocessString will be called on this string AGAIN! So we
839 // have to make sure that no second variable expansion takes place, otherwise
840 // alias parameters containing dollar signs can have bad effects.
841 Cmd_QuoteString(buffer2, sizeof(buffer2), buffer, "$");
842 Cbuf_InsertText( buffer2 );
849 CmdList Added by EvilTypeGuy eviltypeguy@qeradiant.com
850 Thanks to Matthias "Maddes" Buecher, http://www.inside3d.com/qip/
854 static void Cmd_List_f (void)
862 partial = Cmd_Argv (1);
863 len = (int)strlen(partial);
872 for (cmd = cmd_functions; cmd; cmd = cmd->next)
874 if (partial && strncmp(partial, cmd->name, len))
876 Con_Printf("%s : %s\n", cmd->name, cmd->description);
881 Con_Printf("%i Command%s beginning with \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
883 Con_Printf("%i Command%s\n\n", count, (count > 1) ? "s" : "");
893 cmd_mempool = Mem_AllocPool("commands", 0, NULL);
894 // space for commands and script files
895 cmd_text.data = cmd_text_buf;
896 cmd_text.maxsize = sizeof(cmd_text_buf);
897 cmd_text.cursize = 0;
900 void Cmd_Init_Commands (void)
903 // register our commands
905 Cmd_AddCommand ("stuffcmds",Cmd_StuffCmds_f, "execute commandline parameters (must be present in quake.rc script)");
906 Cmd_AddCommand ("exec",Cmd_Exec_f, "execute a script file");
907 Cmd_AddCommand ("echo",Cmd_Echo_f, "print a message to the console (useful in scripts)");
908 Cmd_AddCommand ("alias",Cmd_Alias_f, "create a script function (parameters are passed in as $1 through $9, and $* for all parameters)");
909 Cmd_AddCommand ("cmd", Cmd_ForwardToServer, "send a console commandline to the server (used by some mods)");
910 Cmd_AddCommand ("wait", Cmd_Wait_f, "make script execution wait for next rendered frame");
911 Cmd_AddCommand ("set", Cvar_Set_f, "create or change the value of a console variable");
912 Cmd_AddCommand ("seta", Cvar_SetA_f, "create or change the value of a console variable that will be saved to config.cfg");
914 // 2000-01-09 CmdList, CvarList commands By Matthias "Maddes" Buecher
915 // Added/Modified by EvilTypeGuy eviltypeguy@qeradiant.com
916 Cmd_AddCommand ("cmdlist", Cmd_List_f, "lists all console commands beginning with the specified prefix");
917 Cmd_AddCommand ("cvarlist", Cvar_List_f, "lists all console variables beginning with the specified prefix");
919 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");
920 Cmd_AddCommand ("cvar_resettodefaults_all", Cvar_ResetToDefaults_All_f, "sets all cvars to their locked default values");
921 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)");
922 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)");
925 // Support Doom3-style Toggle Command
926 Cmd_AddCommand( "toggle", Cmd_Toggle_f, "toggles a console variable's values (use for more info)");
934 void Cmd_Shutdown(void)
936 Mem_FreePool(&cmd_mempool);
954 const char *Cmd_Argv (int arg)
956 if (arg >= cmd_argc )
957 return cmd_null_string;
958 return cmd_argv[arg];
966 const char *Cmd_Args (void)
976 Parses the given string into command line tokens.
979 // AK: This function should only be called from ExcuteString because the current design is a bit of an hack
980 static void Cmd_TokenizeString (const char *text)
989 // skip whitespace up to a /n
990 while (*text && *text <= ' ' && *text != '\r' && *text != '\n')
997 if (*text == '\n' || *text == '\r')
999 // a newline separates commands in the buffer
1000 if (*text == '\r' && text[1] == '\n')
1012 if (!COM_ParseToken_Console(&text))
1015 if (cmd_argc < MAX_ARGS)
1017 l = (int)strlen(com_token) + 1;
1018 if (cmd_tokenizebufferpos + l > CMD_TOKENIZELENGTH)
1020 Con_Printf("Cmd_TokenizeString: ran out of %i character buffer space for command arguements\n", CMD_TOKENIZELENGTH);
1023 memcpy (cmd_tokenizebuffer + cmd_tokenizebufferpos, com_token, l);
1024 cmd_argv[cmd_argc] = cmd_tokenizebuffer + cmd_tokenizebufferpos;
1025 cmd_tokenizebufferpos += l;
1037 void Cmd_AddCommand_WithClientCommand (const char *cmd_name, xcommand_t consolefunction, xcommand_t clientfunction, const char *description)
1039 cmd_function_t *cmd;
1040 cmd_function_t *prev, *current;
1042 // fail if the command is a variable name
1043 if (Cvar_FindVar( cmd_name ))
1045 Con_Printf("Cmd_AddCommand: %s already defined as a var\n", cmd_name);
1049 // fail if the command already exists
1050 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1052 if (!strcmp (cmd_name, cmd->name))
1054 if (consolefunction || clientfunction)
1056 Con_Printf("Cmd_AddCommand: %s already defined\n", cmd_name);
1061 cmd->csqcfunc = true;
1067 cmd = (cmd_function_t *)Mem_Alloc(cmd_mempool, sizeof(cmd_function_t));
1068 cmd->name = cmd_name;
1069 cmd->consolefunction = consolefunction;
1070 cmd->clientfunction = clientfunction;
1071 cmd->description = description;
1072 if(!consolefunction && !clientfunction) //[515]: csqc
1073 cmd->csqcfunc = true;
1074 cmd->next = cmd_functions;
1076 // insert it at the right alphanumeric position
1077 for( prev = NULL, current = cmd_functions ; current && strcmp( current->name, cmd->name ) < 0 ; prev = current, current = current->next )
1082 cmd_functions = cmd;
1084 cmd->next = current;
1087 void Cmd_AddCommand (const char *cmd_name, xcommand_t function, const char *description)
1089 Cmd_AddCommand_WithClientCommand (cmd_name, function, NULL, description);
1097 qboolean Cmd_Exists (const char *cmd_name)
1099 cmd_function_t *cmd;
1101 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1102 if (!strcmp (cmd_name,cmd->name))
1114 const char *Cmd_CompleteCommand (const char *partial)
1116 cmd_function_t *cmd;
1119 len = strlen(partial);
1125 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1126 if (!strncasecmp(partial, cmd->name, len))
1133 Cmd_CompleteCountPossible
1135 New function for tab-completion system
1136 Added by EvilTypeGuy
1137 Thanks to Fett erich@heintz.com
1141 int Cmd_CompleteCountPossible (const char *partial)
1143 cmd_function_t *cmd;
1148 len = strlen(partial);
1153 // Loop through the command list and count all partial matches
1154 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1155 if (!strncasecmp(partial, cmd->name, len))
1162 Cmd_CompleteBuildList
1164 New function for tab-completion system
1165 Added by EvilTypeGuy
1166 Thanks to Fett erich@heintz.com
1170 const char **Cmd_CompleteBuildList (const char *partial)
1172 cmd_function_t *cmd;
1175 size_t sizeofbuf = (Cmd_CompleteCountPossible (partial) + 1) * sizeof (const char *);
1178 len = strlen(partial);
1179 buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1180 // Loop through the alias list and print all matches
1181 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1182 if (!strncasecmp(partial, cmd->name, len))
1183 buf[bpos++] = cmd->name;
1189 // written by LordHavoc
1190 void Cmd_CompleteCommandPrint (const char *partial)
1192 cmd_function_t *cmd;
1193 size_t len = strlen(partial);
1194 // Loop through the command list and print all matches
1195 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1196 if (!strncasecmp(partial, cmd->name, len))
1197 Con_Printf("%s : %s\n", cmd->name, cmd->description);
1203 New function for tab-completion system
1204 Added by EvilTypeGuy
1205 Thanks to Fett erich@heintz.com
1209 const char *Cmd_CompleteAlias (const char *partial)
1214 len = strlen(partial);
1220 for (alias = cmd_alias; alias; alias = alias->next)
1221 if (!strncasecmp(partial, alias->name, len))
1227 // written by LordHavoc
1228 void Cmd_CompleteAliasPrint (const char *partial)
1231 size_t len = strlen(partial);
1232 // Loop through the alias list and print all matches
1233 for (alias = cmd_alias; alias; alias = alias->next)
1234 if (!strncasecmp(partial, alias->name, len))
1235 Con_Printf("%s : %s\n", alias->name, alias->value);
1240 Cmd_CompleteAliasCountPossible
1242 New function for tab-completion system
1243 Added by EvilTypeGuy
1244 Thanks to Fett erich@heintz.com
1248 int Cmd_CompleteAliasCountPossible (const char *partial)
1256 len = strlen(partial);
1261 // Loop through the command list and count all partial matches
1262 for (alias = cmd_alias; alias; alias = alias->next)
1263 if (!strncasecmp(partial, alias->name, len))
1270 Cmd_CompleteAliasBuildList
1272 New function for tab-completion system
1273 Added by EvilTypeGuy
1274 Thanks to Fett erich@heintz.com
1278 const char **Cmd_CompleteAliasBuildList (const char *partial)
1283 size_t sizeofbuf = (Cmd_CompleteAliasCountPossible (partial) + 1) * sizeof (const char *);
1286 len = strlen(partial);
1287 buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1288 // Loop through the alias list and print all matches
1289 for (alias = cmd_alias; alias; alias = alias->next)
1290 if (!strncasecmp(partial, alias->name, len))
1291 buf[bpos++] = alias->name;
1297 void Cmd_ClearCsqcFuncs (void)
1299 cmd_function_t *cmd;
1300 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1301 cmd->csqcfunc = false;
1304 qboolean CL_VM_ConsoleCommand (const char *cmd);
1309 A complete command line has been parsed, so try to execute it
1310 FIXME: lookupnoadd the token to speed search?
1313 void Cmd_ExecuteString (const char *text, cmd_source_t src)
1316 cmd_function_t *cmd;
1319 oldpos = cmd_tokenizebufferpos;
1322 Cmd_TokenizeString (text);
1324 // execute the command line
1327 cmd_tokenizebufferpos = oldpos;
1328 return; // no tokens
1332 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1334 if (!strcasecmp (cmd_argv[0],cmd->name))
1336 if (cmd->csqcfunc && CL_VM_ConsoleCommand (text)) //[515]: csqc
1341 if (cmd->consolefunction)
1342 cmd->consolefunction ();
1343 else if (cmd->clientfunction)
1345 if (cls.state == ca_connected)
1347 // forward remote commands to the server for execution
1348 Cmd_ForwardToServer();
1351 Con_Printf("Can not send command \"%s\", not connected.\n", Cmd_Argv(0));
1354 Con_Printf("Command \"%s\" can not be executed\n", Cmd_Argv(0));
1355 cmd_tokenizebufferpos = oldpos;
1358 if (cmd->clientfunction)
1360 cmd->clientfunction ();
1361 cmd_tokenizebufferpos = oldpos;
1370 // if it's a client command and no command was found, say so.
1371 if (cmd_source == src_client)
1373 Con_Printf("player \"%s\" tried to %s\n", host_client->name, text);
1378 for (a=cmd_alias ; a ; a=a->next)
1380 if (!strcasecmp (cmd_argv[0], a->name))
1382 Cmd_ExecuteAlias(a);
1383 cmd_tokenizebufferpos = oldpos;
1389 if (!Cvar_Command () && host_framecount > 0)
1390 Con_Printf("Unknown command \"%s\"\n", Cmd_Argv(0));
1392 cmd_tokenizebufferpos = oldpos;
1398 Cmd_ForwardStringToServer
1400 Sends an entire command string over to the server, unprocessed
1403 void Cmd_ForwardStringToServer (const char *s)
1406 if (cls.state != ca_connected)
1408 Con_Printf("Can't \"%s\", not connected\n", s);
1415 // LordHavoc: thanks to Fuh for bringing the pure evil of SZ_Print to my
1416 // attention, it has been eradicated from here, its only (former) use in
1417 // all of darkplaces.
1418 if (cls.protocol == PROTOCOL_QUAKEWORLD)
1419 MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
1421 MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
1422 if ((!strncmp(s, "say ", 4) || !strncmp(s, "say_team ", 9)) && cl_locs_enable.integer)
1424 // say/say_team commands can replace % character codes with status info
1427 if (*s == '%' && s[1])
1429 // handle proquake message macros
1433 case 'l': // current location
1434 CL_Locs_FindLocationName(temp, sizeof(temp), cl.movement_origin);
1436 case 'h': // current health
1437 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_HEALTH]);
1439 case 'a': // current armor
1440 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ARMOR]);
1442 case 'x': // current rockets
1443 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ROCKETS]);
1445 case 'c': // current cells
1446 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_CELLS]);
1448 // silly proquake macros
1449 case 'd': // loc at last death
1450 CL_Locs_FindLocationName(temp, sizeof(temp), cl.lastdeathorigin);
1452 case 't': // current time
1453 dpsnprintf(temp, sizeof(temp), "%.0f:%.0f", floor(cl.time / 60), cl.time - floor(cl.time / 60) * 60);
1455 case 'r': // rocket launcher status ("I have RL", "I need rockets", "I need RL")
1456 if (!(cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER))
1457 dpsnprintf(temp, sizeof(temp), "I need RL");
1458 else if (!cl.stats[STAT_ROCKETS])
1459 dpsnprintf(temp, sizeof(temp), "I need rockets");
1461 dpsnprintf(temp, sizeof(temp), "I have RL");
1463 case 'p': // powerup status (outputs "quad" "pent" and "eyes" according to status)
1464 if (cl.stats[STAT_ITEMS] & IT_QUAD)
1467 strlcat(temp, " ", sizeof(temp));
1468 strlcat(temp, "quad", sizeof(temp));
1470 if (cl.stats[STAT_ITEMS] & IT_INVULNERABILITY)
1473 strlcat(temp, " ", sizeof(temp));
1474 strlcat(temp, "pent", sizeof(temp));
1476 if (cl.stats[STAT_ITEMS] & IT_INVISIBILITY)
1479 strlcat(temp, " ", sizeof(temp));
1480 strlcat(temp, "eyes", sizeof(temp));
1483 case 'w': // weapon status (outputs "SSG:NG:SNG:GL:RL:LG" with the text between : characters omitted if you lack the weapon)
1484 if (cl.stats[STAT_ITEMS] & IT_SUPER_SHOTGUN)
1485 strlcat(temp, "SSG", sizeof(temp));
1486 strlcat(temp, ":", sizeof(temp));
1487 if (cl.stats[STAT_ITEMS] & IT_NAILGUN)
1488 strlcat(temp, "NG", sizeof(temp));
1489 strlcat(temp, ":", sizeof(temp));
1490 if (cl.stats[STAT_ITEMS] & IT_SUPER_NAILGUN)
1491 strlcat(temp, "SNG", sizeof(temp));
1492 strlcat(temp, ":", sizeof(temp));
1493 if (cl.stats[STAT_ITEMS] & IT_GRENADE_LAUNCHER)
1494 strlcat(temp, "GL", sizeof(temp));
1495 strlcat(temp, ":", sizeof(temp));
1496 if (cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER)
1497 strlcat(temp, "RL", sizeof(temp));
1498 strlcat(temp, ":", sizeof(temp));
1499 if (cl.stats[STAT_ITEMS] & IT_LIGHTNING)
1500 strlcat(temp, "LG", sizeof(temp));
1503 // not a recognized macro, print it as-is...
1509 // write the resulting text
1510 SZ_Write(&cls.netcon->message, (unsigned char *)temp, strlen(temp));
1514 MSG_WriteByte(&cls.netcon->message, *s);
1517 MSG_WriteByte(&cls.netcon->message, 0);
1519 else // any other command is passed on as-is
1520 SZ_Write(&cls.netcon->message, (const unsigned char *)s, (int)strlen(s) + 1);
1527 Sends the entire command line over to the server
1530 void Cmd_ForwardToServer (void)
1533 if (!strcasecmp(Cmd_Argv(0), "cmd"))
1535 // we want to strip off "cmd", so just send the args
1536 s = Cmd_Argc() > 1 ? Cmd_Args() : "";
1540 // we need to keep the command name, so send Cmd_Argv(0), a space and then Cmd_Args()
1541 s = va("%s %s", Cmd_Argv(0), Cmd_Argc() > 1 ? Cmd_Args() : "");
1543 // don't send an empty forward message if the user tries "cmd" by itself
1546 Cmd_ForwardStringToServer(s);
1554 Returns the position (1 to argc-1) in the command's argument list
1555 where the given parameter apears, or 0 if not present
1559 int Cmd_CheckParm (const char *parm)
1565 Con_Printf ("Cmd_CheckParm: NULL");
1569 for (i = 1; i < Cmd_Argc (); i++)
1570 if (!strcasecmp (parm, Cmd_Argv (i)))