]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - cmd.c
b515dbb92d6cd747424a141ee21b15b8c2689f41
[xonotic/darkplaces.git] / cmd.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
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.
8
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.
12
13 See the GNU General Public License for more details.
14
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.
18
19 */
20 // cmd.c -- Quake script command processing module
21
22 #include "quakedef.h"
23
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
30 #define MAX_ARGS 80
31 // maximum tokenizable commandline length (counting NUL terminations)
32 #define CMD_TOKENIZELENGTH (MAX_INPUTLINE + MAX_ARGS)
33
34 typedef struct cmdalias_s
35 {
36         struct cmdalias_s *next;
37         char name[MAX_ALIAS_NAME];
38         char *value;
39 } cmdalias_t;
40
41 static cmdalias_t *cmd_alias;
42
43 static qboolean cmd_wait;
44
45 static mempool_t *cmd_mempool;
46
47 static char cmd_tokenizebuffer[CMD_TOKENIZELENGTH];
48 static int cmd_tokenizebufferpos = 0;
49
50 //=============================================================================
51
52 /*
53 ============
54 Cmd_Wait_f
55
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"
59 ============
60 */
61 static void Cmd_Wait_f (void)
62 {
63         cmd_wait = true;
64 }
65
66 /*
67 =============================================================================
68
69                                                 COMMAND BUFFER
70
71 =============================================================================
72 */
73
74 static sizebuf_t        cmd_text;
75 static unsigned char            cmd_text_buf[CMDBUFSIZE];
76
77 /*
78 ============
79 Cbuf_AddText
80
81 Adds command text at the end of the buffer
82 ============
83 */
84 void Cbuf_AddText (const char *text)
85 {
86         int             l;
87
88         l = (int)strlen (text);
89
90         if (cmd_text.cursize + l >= cmd_text.maxsize)
91         {
92                 Con_Print("Cbuf_AddText: overflow\n");
93                 return;
94         }
95
96         SZ_Write (&cmd_text, (const unsigned char *)text, (int)strlen (text));
97 }
98
99
100 /*
101 ============
102 Cbuf_InsertText
103
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
107 ============
108 */
109 void Cbuf_InsertText (const char *text)
110 {
111         char    *temp;
112         int             templen;
113
114         // copy off any commands still remaining in the exec buffer
115         templen = cmd_text.cursize;
116         if (templen)
117         {
118                 temp = (char *)Mem_Alloc (tempmempool, templen);
119                 memcpy (temp, cmd_text.data, templen);
120                 SZ_Clear (&cmd_text);
121         }
122         else
123                 temp = NULL;
124
125         // add the entire text of the file
126         Cbuf_AddText (text);
127
128         // add the copied off data
129         if (temp != NULL)
130         {
131                 SZ_Write (&cmd_text, (const unsigned char *)temp, templen);
132                 Mem_Free (temp);
133         }
134 }
135
136 /*
137 ============
138 Cbuf_Execute
139 ============
140 */
141 static void Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias );
142 void Cbuf_Execute (void)
143 {
144         int i;
145         char *text;
146         char line[MAX_INPUTLINE];
147         char preprocessed[MAX_INPUTLINE];
148         char *firstchar;
149         int quotes;
150
151         // LordHavoc: making sure the tokenizebuffer doesn't get filled up by repeated crashes
152         cmd_tokenizebufferpos = 0;
153
154         while (cmd_text.cursize)
155         {
156 // find a \n or ; line break
157                 text = (char *)cmd_text.data;
158
159                 quotes = 0;
160                 for (i=0 ; i< cmd_text.cursize ; i++)
161                 {
162                         if (text[i] == '"')
163                                 quotes ^= 1;
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] == '\\')))
167                                 i++;
168                         if ( !quotes &&  text[i] == ';')
169                                 break;  // don't break if inside a quoted string
170                         if (text[i] == '\r' || text[i] == '\n')
171                                 break;
172                 }
173
174                 // better than CRASHING on overlong input lines that may SOMEHOW enter the buffer
175                 if(i >= MAX_INPUTLINE)
176                 {
177                         Con_Printf("Warning: console input buffer had an overlong line. Ignored.\n");
178                         line[0] = 0;
179                 }
180                 else
181                 {
182                         memcpy (line, text, i);
183                         line[i] = 0;
184                 }
185
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
189
190                 if (i == cmd_text.cursize)
191                         cmd_text.cursize = 0;
192                 else
193                 {
194                         i++;
195                         cmd_text.cursize -= i;
196                         memmove (cmd_text.data, text+i, cmd_text.cursize);
197                 }
198
199 // execute the command line
200                 firstchar = line + strspn(line, " \t");
201                 if(
202                         (strncmp(firstchar, "alias", 5) || (firstchar[5] != ' ' && firstchar[5] != '\t'))
203                         &&
204                         (strncmp(firstchar, "bind", 4) || (firstchar[4] != ' ' && firstchar[4] != '\t'))
205                         &&
206                         (strncmp(firstchar, "in_bind", 7) || (firstchar[7] != ' ' && firstchar[7] != '\t'))
207                 )
208                 {
209                         Cmd_PreprocessString( line, preprocessed, sizeof(preprocessed), NULL );
210                         Cmd_ExecuteString (preprocessed, src_command);
211                 }
212                 else
213                 {
214                         Cmd_ExecuteString (line, src_command);
215                 }
216
217                 if (cmd_wait)
218                 {       // skip out while text still remains in buffer, leaving it
219                         // for next frame
220                         cmd_wait = false;
221                         break;
222                 }
223         }
224 }
225
226 /*
227 ==============================================================================
228
229                                                 SCRIPT COMMANDS
230
231 ==============================================================================
232 */
233
234 /*
235 ===============
236 Cmd_StuffCmds_f
237
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
242 ===============
243 */
244 qboolean host_stuffcmdsrun = false;
245 void Cmd_StuffCmds_f (void)
246 {
247         int             i, j, l;
248         // this is for all commandline options combined (and is bounds checked)
249         char    build[MAX_INPUTLINE];
250
251         if (Cmd_Argc () != 1)
252         {
253                 Con_Print("stuffcmds : execute command line parameters\n");
254                 return;
255         }
256
257         // no reason to run the commandline arguments twice
258         if (host_stuffcmdsrun)
259                 return;
260
261         host_stuffcmdsrun = true;
262         build[0] = 0;
263         l = 0;
264         for (i = 0;i < com_argc;i++)
265         {
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)
267                 {
268                         j = 1;
269                         while (com_argv[i][j])
270                                 build[l++] = com_argv[i][j++];
271                         i++;
272                         for (;i < com_argc;i++)
273                         {
274                                 if (!com_argv[i])
275                                         continue;
276                                 if ((com_argv[i][0] == '+' || com_argv[i][0] == '-') && (com_argv[i][1] < '0' || com_argv[i][1] > '9'))
277                                         break;
278                                 if (l + strlen(com_argv[i]) + 4 > sizeof(build) - 1)
279                                         break;
280                                 build[l++] = ' ';
281                                 if (strchr(com_argv[i], ' '))
282                                         build[l++] = '\"';
283                                 for (j = 0;com_argv[i][j];j++)
284                                         build[l++] = com_argv[i][j];
285                                 if (strchr(com_argv[i], ' '))
286                                         build[l++] = '\"';
287                         }
288                         build[l++] = '\n';
289                         i--;
290                 }
291         }
292         // now terminate the combined string and prepend it to the command buffer
293         // we already reserved space for the terminator
294         build[l++] = 0;
295         Cbuf_InsertText (build);
296 }
297
298
299 /*
300 ===============
301 Cmd_Exec_f
302 ===============
303 */
304 static void Cmd_Exec_f (void)
305 {
306         char *f;
307
308         if (Cmd_Argc () != 2)
309         {
310                 Con_Print("exec <filename> : execute a script file\n");
311                 return;
312         }
313
314         f = (char *)FS_LoadFile (Cmd_Argv(1), tempmempool, false, NULL);
315         if (!f)
316         {
317                 Con_Printf("couldn't exec %s\n",Cmd_Argv(1));
318                 return;
319         }
320         Con_Printf("execing %s\n",Cmd_Argv(1));
321
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");
327
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");
331         Cbuf_InsertText (f);
332         Mem_Free(f);
333 }
334
335
336 /*
337 ===============
338 Cmd_Echo_f
339
340 Just prints the rest of the line to the console
341 ===============
342 */
343 static void Cmd_Echo_f (void)
344 {
345         int             i;
346
347         for (i=1 ; i<Cmd_Argc() ; i++)
348                 Con_Printf("%s ",Cmd_Argv(i));
349         Con_Print("\n");
350 }
351
352 // DRESK - 5/14/06
353 // Support Doom3-style Toggle Console Command
354 /*
355 ===============
356 Cmd_Toggle_f
357
358 Toggles a specified console variable amongst the values specified (default is 0 and 1)
359 ===============
360 */
361 static void Cmd_Toggle_f(void)
362 {
363         // Acquire Number of Arguments
364         int nNumArgs = Cmd_Argc();
365
366         if(nNumArgs == 1)
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");
369         else
370         { // Correct Arguments Specified
371                 // Acquire Potential CVar
372                 cvar_t* cvCVar = Cvar_FindVar( Cmd_Argv(1) );
373
374                 if(cvCVar != NULL)
375                 { // Valid CVar
376                         if(nNumArgs == 2)
377                         { // Default Usage
378                                 if(cvCVar->integer)
379                                         Cvar_SetValueQuick(cvCVar, 0);
380                                 else
381                                         Cvar_SetValueQuick(cvCVar, 1);
382                         }
383                         else
384                         if(nNumArgs == 3)
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);
389                                 else
390                                 if(cvCVar->integer == 0)
391                                         // CVar is 0; Specify Value
392                                         Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
393                                 else
394                                         // CVar does not match; Reset to 0
395                                         Cvar_SetValueQuick(cvCVar, 0);
396                         }
397                         else
398                         { // Variable Values Specified
399                                 int nCnt;
400                                 int bFound = 0;
401
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) );
409                                                 else
410                                                         // Next Value
411                                                         Cvar_SetQuick(cvCVar, Cmd_Argv(nCnt + 1) );
412
413                                                 // End Loop
414                                                 nCnt = nNumArgs;
415                                                 // Assign Found
416                                                 bFound = 1;
417                                         }
418                                 }
419                                 if(!bFound)
420                                         // Value not Found; Reset to Original
421                                         Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
422                         }
423
424                 }
425                 else
426                 { // Invalid CVar
427                         Con_Printf("ERROR : CVar '%s' not found\n", Cmd_Argv(1) );
428                 }
429         }
430 }
431
432 /*
433 ===============
434 Cmd_Alias_f
435
436 Creates a new command that executes a command string (possibly ; seperated)
437 ===============
438 */
439 static void Cmd_Alias_f (void)
440 {
441         cmdalias_t      *a;
442         char            cmd[MAX_INPUTLINE];
443         int                     i, c;
444         const char              *s;
445         size_t          alloclen;
446
447         if (Cmd_Argc() == 1)
448         {
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);
452                 return;
453         }
454
455         s = Cmd_Argv(1);
456         if (strlen(s) >= MAX_ALIAS_NAME)
457         {
458                 Con_Print("Alias name is too long\n");
459                 return;
460         }
461
462         // if the alias already exists, reuse it
463         for (a = cmd_alias ; a ; a=a->next)
464         {
465                 if (!strcmp(s, a->name))
466                 {
467                         Z_Free (a->value);
468                         break;
469                 }
470         }
471
472         if (!a)
473         {
474                 cmdalias_t *prev, *current;
475
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 )
480                         ;
481                 if( prev ) {
482                         prev->next = a;
483                 } else {
484                         cmd_alias = a;
485                 }
486                 a->next = current;
487         }
488
489
490 // copy the rest of the command line
491         cmd[0] = 0;             // start out with a null string
492         c = Cmd_Argc();
493         for (i=2 ; i< c ; i++)
494         {
495                 strlcat (cmd, Cmd_Argv(i), sizeof (cmd));
496                 if (i != c)
497                         strlcat (cmd, " ", sizeof (cmd));
498         }
499         strlcat (cmd, "\n", sizeof (cmd));
500
501         alloclen = strlen (cmd) + 1;
502         a->value = (char *)Z_Malloc (alloclen);
503         memcpy (a->value, cmd, alloclen);
504 }
505
506 /*
507 =============================================================================
508
509                                         COMMAND EXECUTION
510
511 =============================================================================
512 */
513
514 typedef struct cmd_function_s
515 {
516         struct cmd_function_s *next;
517         const char *name;
518         const char *description;
519         xcommand_t consolefunction;
520         xcommand_t clientfunction;
521         qboolean csqcfunc;
522 } cmd_function_t;
523
524 static int cmd_argc;
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;
529
530
531 static cmd_function_t *cmd_functions;           // possible commands to execute
532
533 static const char *Cmd_GetDirectCvarValue(const char *varname, cmdalias_t *alias, qboolean *is_multiple)
534 {
535         cvar_t *cvar;
536         long argno;
537         char *endptr;
538
539         if(is_multiple)
540                 *is_multiple = false;
541
542         if(!varname || !*varname)
543                 return NULL;
544
545         if(alias)
546         {
547                 if(!strcmp(varname, "*"))
548                 {
549                         if(is_multiple)
550                                 *is_multiple = true;
551                         return Cmd_Args();
552                 }
553                 else if(varname[strlen(varname) - 1] == '-')
554                 {
555                         argno = strtol(varname, &endptr, 10);
556                         if(endptr == varname + strlen(varname) - 1)
557                         {
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))
562                                                 break;
563                                 if(p)
564                                 {
565                                         if(is_multiple)
566                                                 *is_multiple = true;
567
568                                         // kill pre-argument whitespace
569                                         for (;*p && *p <= ' ';p++)
570                                                 ;
571
572                                         return p;
573                                 }
574                         }
575                 }
576                 else
577                 {
578                         argno = strtol(varname, &endptr, 10);
579                         if(*endptr == 0)
580                         {
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);
585                         }
586                 }
587         }
588
589         if((cvar = Cvar_FindVar(varname)) && !(cvar->flags & CVAR_PRIVATE))
590                 return cvar->string;
591
592         return NULL;
593 }
594
595 qboolean Cmd_QuoteString(char *out, size_t outlen, const char *in, const char *quoteset)
596 {
597         qboolean quote_quot = !!strchr(quoteset, '"');
598         qboolean quote_backslash = !!strchr(quoteset, '\\');
599         qboolean quote_dollar = !!strchr(quoteset, '$');
600
601         while(*in)
602         {
603                 if(*in == '"' && quote_quot)
604                 {
605                         if(outlen <= 2)
606                         {
607                                 *out++ = 0;
608                                 return false;
609                         }
610                         *out++ = '\\'; --outlen;
611                         *out++ = '"'; --outlen;
612                 }
613                 else if(*in == '\\' && quote_backslash)
614                 {
615                         if(outlen <= 2)
616                         {
617                                 *out++ = 0;
618                                 return false;
619                         }
620                         *out++ = '\\'; --outlen;
621                         *out++ = '\\'; --outlen;
622                 }
623                 else if(*in == '$' && quote_dollar)
624                 {
625                         if(outlen <= 2)
626                         {
627                                 *out++ = 0;
628                                 return false;
629                         }
630                         *out++ = '$'; --outlen;
631                         *out++ = '$'; --outlen;
632                 }
633                 else
634                 {
635                         if(outlen <= 1)
636                         {
637                                 *out++ = 0;
638                                 return false;
639                         }
640                         *out++ = *in; --outlen;
641                 }
642                 ++in;
643         }
644         *out++ = 0;
645         return true;
646 }
647
648 static const char *Cmd_GetCvarValue(const char *var, size_t varlen, cmdalias_t *alias)
649 {
650         static char varname[MAX_INPUTLINE];
651         static char varval[MAX_INPUTLINE];
652         const char *varstr;
653         char *varfunc;
654
655         if(varlen >= MAX_INPUTLINE)
656                 varlen = MAX_INPUTLINE - 1;
657         memcpy(varname, var, varlen);
658         varname[varlen] = 0;
659         varfunc = strchr(varname, ' ');
660
661         if(varfunc)
662         {
663                 *varfunc = 0;
664                 ++varfunc;
665         }
666
667         if(*var == 0)
668         {
669                 // empty cvar name?
670                 return NULL;
671         }
672
673         varstr = NULL;
674
675         if(varname[0] == '$')
676                 varstr = Cmd_GetDirectCvarValue(Cmd_GetDirectCvarValue(varname + 1, alias, NULL), alias, NULL);
677         else
678         {
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);
682                 if(is_multiple)
683                         varfunc = "asis";
684         }
685
686         if(!varstr)
687         {
688                 if(alias)
689                         Con_Printf("Warning: Could not expand $%s in alias %s\n", varname, alias->name);
690                 else
691                         Con_Printf("Warning: Could not expand $%s\n", varname);
692                 return NULL;
693         }
694
695         if(!varfunc || !strcmp(varfunc, "q")) // note: quoted form is default, use "asis" to override!
696         {
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, "\"\\");
700                 return varval;
701         }
702         else if(!strcmp(varfunc, "asis"))
703         {
704                 return varstr;
705         }
706         else
707                 Con_Printf("Unknown variable function %s\n", varfunc);
708
709         return varstr;
710 }
711
712 /*
713 Cmd_PreprocessString
714
715 Preprocesses strings and replaces $*, $param#, $cvar accordingly
716 */
717 static void Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias ) {
718         const char *in;
719         size_t eat, varlen;
720         unsigned outlen;
721         const char *val;
722
723         // don't crash if there's no room in the outtext buffer
724         if( maxoutlen == 0 ) {
725                 return;
726         }
727         maxoutlen--; // because of \0
728
729         in = intext;
730         outlen = 0;
731
732         while( *in && outlen < maxoutlen ) {
733                 if( *in == '$' ) {
734                         // this is some kind of expansion, see what comes after the $
735                         in++;
736
737                         // The console does the following preprocessing:
738                         //
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
743                         //   that way)
744                         // - ${var asis} inserts the cvar value as is, without doing this
745                         //   quoting
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-).
756                         //
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"
767                         //
768                         // Also note: lines starting with alias are exempt from cvar expansion.
769                         // If you want cvar expansion, write "alias" instead:
770                         //
771                         //   set x 1
772                         //   alias foo "echo $x"
773                         //   "alias" bar "echo $x"
774                         //   set x 2
775                         //
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
779                         //
780                         //   "alias" foo "echo $$x"
781                         //
782                         // because at definition time, $$ will get replaced to a single $.
783
784                         if( *in == '$' ) {
785                                 val = "$";
786                                 eat = 1;
787                         } else if(*in == '{') {
788                                 varlen = strcspn(in + 1, "}");
789                                 if(in[varlen + 1] == '}')
790                                 {
791                                         val = Cmd_GetCvarValue(in + 1, varlen, alias);
792                                         eat = varlen + 2;
793                                 }
794                                 else
795                                 {
796                                         // ran out of data?
797                                         val = NULL;
798                                         eat = varlen + 1;
799                                 }
800                         } else {
801                                 varlen = strspn(in, "*0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-");
802                                 val = Cmd_GetCvarValue(in, varlen, alias);
803                                 eat = varlen;
804                         }
805                         if(val)
806                         {
807                                 // insert the cvar value
808                                 while(*val && outlen < maxoutlen)
809                                         outtext[outlen++] = *val++;
810                                 in += eat;
811                         }
812                         else
813                         {
814                                 // copy the unexpanded text
815                                 outtext[outlen++] = '$';
816                                 while(eat && outlen < maxoutlen)
817                                 {
818                                         outtext[outlen++] = *in++;
819                                         --eat;
820                                 }
821                         }
822                 } else {
823                         outtext[outlen++] = *in++;
824                 }
825         }
826         outtext[outlen] = 0;
827 }
828
829 /*
830 ============
831 Cmd_ExecuteAlias
832
833 Called for aliases and fills in the alias into the cbuffer
834 ============
835 */
836 static void Cmd_ExecuteAlias (cmdalias_t *alias)
837 {
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)
843
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 );
849 }
850
851 /*
852 ========
853 Cmd_List
854
855         CmdList Added by EvilTypeGuy eviltypeguy@qeradiant.com
856         Thanks to Matthias "Maddes" Buecher, http://www.inside3d.com/qip/
857
858 ========
859 */
860 static void Cmd_List_f (void)
861 {
862         cmd_function_t *cmd;
863         const char *partial;
864         int len, count;
865
866         if (Cmd_Argc() > 1)
867         {
868                 partial = Cmd_Argv (1);
869                 len = (int)strlen(partial);
870         }
871         else
872         {
873                 partial = NULL;
874                 len = 0;
875         }
876
877         count = 0;
878         for (cmd = cmd_functions; cmd; cmd = cmd->next)
879         {
880                 if (partial && strncmp(partial, cmd->name, len))
881                         continue;
882                 Con_Printf("%s : %s\n", cmd->name, cmd->description);
883                 count++;
884         }
885
886         if (partial)
887                 Con_Printf("%i Command%s beginning with \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
888         else
889                 Con_Printf("%i Command%s\n\n", count, (count > 1) ? "s" : "");
890 }
891
892 /*
893 ============
894 Cmd_Init
895 ============
896 */
897 void Cmd_Init (void)
898 {
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;
904 }
905
906 void Cmd_Init_Commands (void)
907 {
908 //
909 // register our commands
910 //
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");
919
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");
924
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)");
929
930         // DRESK - 5/14/06
931         // Support Doom3-style Toggle Command
932         Cmd_AddCommand( "toggle", Cmd_Toggle_f, "toggles a console variable's values (use for more info)");
933 }
934
935 /*
936 ============
937 Cmd_Shutdown
938 ============
939 */
940 void Cmd_Shutdown(void)
941 {
942         Mem_FreePool(&cmd_mempool);
943 }
944
945 /*
946 ============
947 Cmd_Argc
948 ============
949 */
950 int             Cmd_Argc (void)
951 {
952         return cmd_argc;
953 }
954
955 /*
956 ============
957 Cmd_Argv
958 ============
959 */
960 const char *Cmd_Argv (int arg)
961 {
962         if (arg >= cmd_argc )
963                 return cmd_null_string;
964         return cmd_argv[arg];
965 }
966
967 /*
968 ============
969 Cmd_Args
970 ============
971 */
972 const char *Cmd_Args (void)
973 {
974         return cmd_args;
975 }
976
977
978 /*
979 ============
980 Cmd_TokenizeString
981
982 Parses the given string into command line tokens.
983 ============
984 */
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)
987 {
988         int l;
989
990         cmd_argc = 0;
991         cmd_args = NULL;
992
993         while (1)
994         {
995                 // skip whitespace up to a /n
996                 while (*text && *text <= ' ' && *text != '\r' && *text != '\n')
997                         text++;
998
999                 // line endings:
1000                 // UNIX: \n
1001                 // Mac: \r
1002                 // Windows: \r\n
1003                 if (*text == '\n' || *text == '\r')
1004                 {
1005                         // a newline separates commands in the buffer
1006                         if (*text == '\r' && text[1] == '\n')
1007                                 text++;
1008                         text++;
1009                         break;
1010                 }
1011
1012                 if (!*text)
1013                         return;
1014
1015                 if (cmd_argc == 1)
1016                         cmd_args = text;
1017
1018                 if (!COM_ParseToken_Console(&text))
1019                         return;
1020
1021                 if (cmd_argc < MAX_ARGS)
1022                 {
1023                         l = (int)strlen(com_token) + 1;
1024                         if (cmd_tokenizebufferpos + l > CMD_TOKENIZELENGTH)
1025                         {
1026                                 Con_Printf("Cmd_TokenizeString: ran out of %i character buffer space for command arguements\n", CMD_TOKENIZELENGTH);
1027                                 break;
1028                         }
1029                         memcpy (cmd_tokenizebuffer + cmd_tokenizebufferpos, com_token, l);
1030                         cmd_argv[cmd_argc] = cmd_tokenizebuffer + cmd_tokenizebufferpos;
1031                         cmd_tokenizebufferpos += l;
1032                         cmd_argc++;
1033                 }
1034         }
1035 }
1036
1037
1038 /*
1039 ============
1040 Cmd_AddCommand
1041 ============
1042 */
1043 void Cmd_AddCommand_WithClientCommand (const char *cmd_name, xcommand_t consolefunction, xcommand_t clientfunction, const char *description)
1044 {
1045         cmd_function_t *cmd;
1046         cmd_function_t *prev, *current;
1047
1048 // fail if the command is a variable name
1049         if (Cvar_FindVar( cmd_name ))
1050         {
1051                 Con_Printf("Cmd_AddCommand: %s already defined as a var\n", cmd_name);
1052                 return;
1053         }
1054
1055 // fail if the command already exists
1056         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1057         {
1058                 if (!strcmp (cmd_name, cmd->name))
1059                 {
1060                         if (consolefunction || clientfunction)
1061                         {
1062                                 Con_Printf("Cmd_AddCommand: %s already defined\n", cmd_name);
1063                                 return;
1064                         }
1065                         else    //[515]: csqc
1066                         {
1067                                 cmd->csqcfunc = true;
1068                                 return;
1069                         }
1070                 }
1071         }
1072
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;
1081
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 )
1084                 ;
1085         if( prev ) {
1086                 prev->next = cmd;
1087         } else {
1088                 cmd_functions = cmd;
1089         }
1090         cmd->next = current;
1091 }
1092
1093 void Cmd_AddCommand (const char *cmd_name, xcommand_t function, const char *description)
1094 {
1095         Cmd_AddCommand_WithClientCommand (cmd_name, function, NULL, description);
1096 }
1097
1098 /*
1099 ============
1100 Cmd_Exists
1101 ============
1102 */
1103 qboolean Cmd_Exists (const char *cmd_name)
1104 {
1105         cmd_function_t  *cmd;
1106
1107         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1108                 if (!strcmp (cmd_name,cmd->name))
1109                         return true;
1110
1111         return false;
1112 }
1113
1114
1115 /*
1116 ============
1117 Cmd_CompleteCommand
1118 ============
1119 */
1120 const char *Cmd_CompleteCommand (const char *partial)
1121 {
1122         cmd_function_t *cmd;
1123         size_t len;
1124
1125         len = strlen(partial);
1126
1127         if (!len)
1128                 return NULL;
1129
1130 // check functions
1131         for (cmd = cmd_functions; cmd; cmd = cmd->next)
1132                 if (!strncasecmp(partial, cmd->name, len))
1133                         return cmd->name;
1134
1135         return NULL;
1136 }
1137
1138 /*
1139         Cmd_CompleteCountPossible
1140
1141         New function for tab-completion system
1142         Added by EvilTypeGuy
1143         Thanks to Fett erich@heintz.com
1144         Thanks to taniwha
1145
1146 */
1147 int Cmd_CompleteCountPossible (const char *partial)
1148 {
1149         cmd_function_t *cmd;
1150         size_t len;
1151         int h;
1152
1153         h = 0;
1154         len = strlen(partial);
1155
1156         if (!len)
1157                 return 0;
1158
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))
1162                         h++;
1163
1164         return h;
1165 }
1166
1167 /*
1168         Cmd_CompleteBuildList
1169
1170         New function for tab-completion system
1171         Added by EvilTypeGuy
1172         Thanks to Fett erich@heintz.com
1173         Thanks to taniwha
1174
1175 */
1176 const char **Cmd_CompleteBuildList (const char *partial)
1177 {
1178         cmd_function_t *cmd;
1179         size_t len = 0;
1180         size_t bpos = 0;
1181         size_t sizeofbuf = (Cmd_CompleteCountPossible (partial) + 1) * sizeof (const char *);
1182         const char **buf;
1183
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;
1190
1191         buf[bpos] = NULL;
1192         return buf;
1193 }
1194
1195 // written by LordHavoc
1196 void Cmd_CompleteCommandPrint (const char *partial)
1197 {
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);
1204 }
1205
1206 /*
1207         Cmd_CompleteAlias
1208
1209         New function for tab-completion system
1210         Added by EvilTypeGuy
1211         Thanks to Fett erich@heintz.com
1212         Thanks to taniwha
1213
1214 */
1215 const char *Cmd_CompleteAlias (const char *partial)
1216 {
1217         cmdalias_t *alias;
1218         size_t len;
1219
1220         len = strlen(partial);
1221
1222         if (!len)
1223                 return NULL;
1224
1225         // Check functions
1226         for (alias = cmd_alias; alias; alias = alias->next)
1227                 if (!strncasecmp(partial, alias->name, len))
1228                         return alias->name;
1229
1230         return NULL;
1231 }
1232
1233 // written by LordHavoc
1234 void Cmd_CompleteAliasPrint (const char *partial)
1235 {
1236         cmdalias_t *alias;
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);
1242 }
1243
1244
1245 /*
1246         Cmd_CompleteAliasCountPossible
1247
1248         New function for tab-completion system
1249         Added by EvilTypeGuy
1250         Thanks to Fett erich@heintz.com
1251         Thanks to taniwha
1252
1253 */
1254 int Cmd_CompleteAliasCountPossible (const char *partial)
1255 {
1256         cmdalias_t      *alias;
1257         size_t          len;
1258         int                     h;
1259
1260         h = 0;
1261
1262         len = strlen(partial);
1263
1264         if (!len)
1265                 return 0;
1266
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))
1270                         h++;
1271
1272         return h;
1273 }
1274
1275 /*
1276         Cmd_CompleteAliasBuildList
1277
1278         New function for tab-completion system
1279         Added by EvilTypeGuy
1280         Thanks to Fett erich@heintz.com
1281         Thanks to taniwha
1282
1283 */
1284 const char **Cmd_CompleteAliasBuildList (const char *partial)
1285 {
1286         cmdalias_t *alias;
1287         size_t len = 0;
1288         size_t bpos = 0;
1289         size_t sizeofbuf = (Cmd_CompleteAliasCountPossible (partial) + 1) * sizeof (const char *);
1290         const char **buf;
1291
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;
1298
1299         buf[bpos] = NULL;
1300         return buf;
1301 }
1302
1303 void Cmd_ClearCsqcFuncs (void)
1304 {
1305         cmd_function_t *cmd;
1306         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1307                 cmd->csqcfunc = false;
1308 }
1309
1310 qboolean CL_VM_ConsoleCommand (const char *cmd);
1311 /*
1312 ============
1313 Cmd_ExecuteString
1314
1315 A complete command line has been parsed, so try to execute it
1316 FIXME: lookupnoadd the token to speed search?
1317 ============
1318 */
1319 void Cmd_ExecuteString (const char *text, cmd_source_t src)
1320 {
1321         int oldpos;
1322         cmd_function_t *cmd;
1323         cmdalias_t *a;
1324
1325         oldpos = cmd_tokenizebufferpos;
1326         cmd_source = src;
1327
1328         Cmd_TokenizeString (text);
1329
1330 // execute the command line
1331         if (!Cmd_Argc())
1332         {
1333                 cmd_tokenizebufferpos = oldpos;
1334                 return;         // no tokens
1335         }
1336
1337 // check functions
1338         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1339         {
1340                 if (!strcasecmp (cmd_argv[0],cmd->name))
1341                 {
1342                         if (cmd->csqcfunc && CL_VM_ConsoleCommand (text))       //[515]: csqc
1343                                 return;
1344                         switch (src)
1345                         {
1346                         case src_command:
1347                                 if (cmd->consolefunction)
1348                                         cmd->consolefunction ();
1349                                 else if (cmd->clientfunction)
1350                                 {
1351                                         if (cls.state == ca_connected)
1352                                         {
1353                                                 // forward remote commands to the server for execution
1354                                                 Cmd_ForwardToServer();
1355                                         }
1356                                         else
1357                                                 Con_Printf("Can not send command \"%s\", not connected.\n", Cmd_Argv(0));
1358                                 }
1359                                 else
1360                                         Con_Printf("Command \"%s\" can not be executed\n", Cmd_Argv(0));
1361                                 cmd_tokenizebufferpos = oldpos;
1362                                 return;
1363                         case src_client:
1364                                 if (cmd->clientfunction)
1365                                 {
1366                                         cmd->clientfunction ();
1367                                         cmd_tokenizebufferpos = oldpos;
1368                                         return;
1369                                 }
1370                                 break;
1371                         }
1372                         break;
1373                 }
1374         }
1375
1376         // if it's a client command and no command was found, say so.
1377         if (cmd_source == src_client)
1378         {
1379                 Con_Printf("player \"%s\" tried to %s\n", host_client->name, text);
1380                 return;
1381         }
1382
1383 // check alias
1384         for (a=cmd_alias ; a ; a=a->next)
1385         {
1386                 if (!strcasecmp (cmd_argv[0], a->name))
1387                 {
1388                         Cmd_ExecuteAlias(a);
1389                         cmd_tokenizebufferpos = oldpos;
1390                         return;
1391                 }
1392         }
1393
1394 // check cvars
1395         if (!Cvar_Command () && host_framecount > 0)
1396                 Con_Printf("Unknown command \"%s\"\n", Cmd_Argv(0));
1397
1398         cmd_tokenizebufferpos = oldpos;
1399 }
1400
1401
1402 /*
1403 ===================
1404 Cmd_ForwardStringToServer
1405
1406 Sends an entire command string over to the server, unprocessed
1407 ===================
1408 */
1409 void Cmd_ForwardStringToServer (const char *s)
1410 {
1411         char temp[128];
1412         if (cls.state != ca_connected)
1413         {
1414                 Con_Printf("Can't \"%s\", not connected\n", s);
1415                 return;
1416         }
1417
1418         if (!cls.netcon)
1419                 return;
1420
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);
1426         else
1427                 MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
1428         if ((!strncmp(s, "say ", 4) || !strncmp(s, "say_team ", 9)) && cl_locs_enable.integer)
1429         {
1430                 // say/say_team commands can replace % character codes with status info
1431                 while (*s)
1432                 {
1433                         if (*s == '%' && s[1])
1434                         {
1435                                 // handle proquake message macros
1436                                 temp[0] = 0;
1437                                 switch (s[1])
1438                                 {
1439                                 case 'l': // current location
1440                                         CL_Locs_FindLocationName(temp, sizeof(temp), cl.movement_origin);
1441                                         break;
1442                                 case 'h': // current health
1443                                         dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_HEALTH]);
1444                                         break;
1445                                 case 'a': // current armor
1446                                         dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ARMOR]);
1447                                         break;
1448                                 case 'x': // current rockets
1449                                         dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ROCKETS]);
1450                                         break;
1451                                 case 'c': // current cells
1452                                         dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_CELLS]);
1453                                         break;
1454                                 // silly proquake macros
1455                                 case 'd': // loc at last death
1456                                         CL_Locs_FindLocationName(temp, sizeof(temp), cl.lastdeathorigin);
1457                                         break;
1458                                 case 't': // current time
1459                                         dpsnprintf(temp, sizeof(temp), "%.0f:%.0f", floor(cl.time / 60), cl.time - floor(cl.time / 60) * 60);
1460                                         break;
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");
1466                                         else
1467                                                 dpsnprintf(temp, sizeof(temp), "I have RL");
1468                                         break;
1469                                 case 'p': // powerup status (outputs "quad" "pent" and "eyes" according to status)
1470                                         if (cl.stats[STAT_ITEMS] & IT_QUAD)
1471                                         {
1472                                                 if (temp[0])
1473                                                         strlcat(temp, " ", sizeof(temp));
1474                                                 strlcat(temp, "quad", sizeof(temp));
1475                                         }
1476                                         if (cl.stats[STAT_ITEMS] & IT_INVULNERABILITY)
1477                                         {
1478                                                 if (temp[0])
1479                                                         strlcat(temp, " ", sizeof(temp));
1480                                                 strlcat(temp, "pent", sizeof(temp));
1481                                         }
1482                                         if (cl.stats[STAT_ITEMS] & IT_INVISIBILITY)
1483                                         {
1484                                                 if (temp[0])
1485                                                         strlcat(temp, " ", sizeof(temp));
1486                                                 strlcat(temp, "eyes", sizeof(temp));
1487                                         }
1488                                         break;
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));
1507                                         break;
1508                                 default:
1509                                         // not a recognized macro, print it as-is...
1510                                         temp[0] = s[0];
1511                                         temp[1] = s[1];
1512                                         temp[2] = 0;
1513                                         break;
1514                                 }
1515                                 // write the resulting text
1516                                 SZ_Write(&cls.netcon->message, (unsigned char *)temp, strlen(temp));
1517                                 s += 2;
1518                                 continue;
1519                         }
1520                         MSG_WriteByte(&cls.netcon->message, *s);
1521                         s++;
1522                 }
1523                 MSG_WriteByte(&cls.netcon->message, 0);
1524         }
1525         else // any other command is passed on as-is
1526                 SZ_Write(&cls.netcon->message, (const unsigned char *)s, (int)strlen(s) + 1);
1527 }
1528
1529 /*
1530 ===================
1531 Cmd_ForwardToServer
1532
1533 Sends the entire command line over to the server
1534 ===================
1535 */
1536 void Cmd_ForwardToServer (void)
1537 {
1538         const char *s;
1539         if (!strcasecmp(Cmd_Argv(0), "cmd"))
1540         {
1541                 // we want to strip off "cmd", so just send the args
1542                 s = Cmd_Argc() > 1 ? Cmd_Args() : "";
1543         }
1544         else
1545         {
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() : "");
1548         }
1549         // don't send an empty forward message if the user tries "cmd" by itself
1550         if (!s || !*s)
1551                 return;
1552         Cmd_ForwardStringToServer(s);
1553 }
1554
1555
1556 /*
1557 ================
1558 Cmd_CheckParm
1559
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
1562 ================
1563 */
1564
1565 int Cmd_CheckParm (const char *parm)
1566 {
1567         int i;
1568
1569         if (!parm)
1570         {
1571                 Con_Printf ("Cmd_CheckParm: NULL");
1572                 return 0;
1573         }
1574
1575         for (i = 1; i < Cmd_Argc (); i++)
1576                 if (!strcasecmp (parm, Cmd_Argv (i)))
1577                         return i;
1578
1579         return 0;
1580 }
1581