]> icculus.org git repositories - divverent/darkplaces.git/blob - cmd.c
use \n parsing on globals in savegames
[divverent/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 typedef struct cmddeferred_s
67 {
68         struct cmddeferred_s *next;
69         char *value;
70         double time;
71 } cmddeferred_t;
72
73 static cmddeferred_t *cmd_deferred_list;
74
75 /*
76 ============
77 Cmd_Defer_f
78
79 Cause a command to be executed after a delay.
80 ============
81 */
82 static void Cmd_Defer_f (void)
83 {
84         if(Cmd_Argc() == 1)
85         {
86                 double time = Sys_DoubleTime();
87                 cmddeferred_t *next = cmd_deferred_list;
88                 if(!next)
89                         Con_Printf("No commands are pending.\n");
90                 while(next)
91                 {
92                         Con_Printf("-> In %'9.2f: %s\n", next->time-time, next->value);
93                         next = next->next;
94                 }
95         } else if(Cmd_Argc() != 3)
96         {
97                 Con_Printf("usage: defer <seconds> <command>\n");
98                 return;
99         } else {
100                 const char *value = Cmd_Argv(2);
101                 cmddeferred_t *defcmd = (cmddeferred_t*)Mem_Alloc(tempmempool, sizeof(*defcmd));
102                 unsigned int len = strlen(value);
103
104                 defcmd->time = Sys_DoubleTime() + atof(Cmd_Argv(1));
105                 defcmd->value = (char*)Mem_Alloc(tempmempool, len+1);
106                 memcpy(defcmd->value, value, len);
107                 defcmd->value[len] = 0;
108
109                 defcmd->next = cmd_deferred_list;
110                 cmd_deferred_list = defcmd;
111         }
112 }
113
114 /*
115 ============
116 Cmd_Centerprint_f
117
118 Print something to the center of the screen using SCR_Centerprint
119 ============
120 */
121 static void Cmd_Centerprint_f (void)
122 {
123         char msg[MAX_INPUTLINE];
124         unsigned int i, c, p;
125         c = Cmd_Argc();
126         if(c >= 2)
127         {
128                 strlcpy(msg, Cmd_Argv(1), sizeof(msg));
129                 for(i = 2; i < c; ++i)
130                 {
131                         strlcat(msg, " ", sizeof(msg));
132                         strlcat(msg, Cmd_Argv(i), sizeof(msg));
133                 }
134                 c = strlen(msg);
135                 for(p = 0, i = 0; i < c; ++i)
136                 {
137                         if(msg[i] == '\\')
138                         {
139                                 if(msg[i+1] == 'n')
140                                         msg[p++] = '\n';
141                                 else if(msg[i+1] == '\\')
142                                         msg[p++] = '\\';
143                                 else {
144                                         msg[p++] = '\\';
145                                         msg[p++] = msg[i+1];
146                                 }
147                                 ++i;
148                         } else {
149                                 msg[p++] = msg[i];
150                         }
151                 }
152                 msg[p] = '\0';
153                 SCR_CenterPrint(msg);
154         }
155 }
156
157 /*
158 =============================================================================
159
160                                                 COMMAND BUFFER
161
162 =============================================================================
163 */
164
165 static sizebuf_t        cmd_text;
166 static unsigned char            cmd_text_buf[CMDBUFSIZE];
167
168 /*
169 ============
170 Cbuf_AddText
171
172 Adds command text at the end of the buffer
173 ============
174 */
175 void Cbuf_AddText (const char *text)
176 {
177         int             l;
178
179         l = (int)strlen (text);
180
181         if (cmd_text.cursize + l >= cmd_text.maxsize)
182         {
183                 Con_Print("Cbuf_AddText: overflow\n");
184                 return;
185         }
186
187         SZ_Write (&cmd_text, (const unsigned char *)text, (int)strlen (text));
188 }
189
190
191 /*
192 ============
193 Cbuf_InsertText
194
195 Adds command text immediately after the current command
196 Adds a \n to the text
197 FIXME: actually change the command buffer to do less copying
198 ============
199 */
200 void Cbuf_InsertText (const char *text)
201 {
202         char    *temp;
203         int             templen;
204
205         // copy off any commands still remaining in the exec buffer
206         templen = cmd_text.cursize;
207         if (templen)
208         {
209                 temp = (char *)Mem_Alloc (tempmempool, templen);
210                 memcpy (temp, cmd_text.data, templen);
211                 SZ_Clear (&cmd_text);
212         }
213         else
214                 temp = NULL;
215
216         // add the entire text of the file
217         Cbuf_AddText (text);
218
219         // add the copied off data
220         if (temp != NULL)
221         {
222                 SZ_Write (&cmd_text, (const unsigned char *)temp, templen);
223                 Mem_Free (temp);
224         }
225 }
226
227 /*
228 ============
229 Cbuf_Execute_Deferred --blub
230 ============
231 */
232 void Cbuf_Execute_Deferred (void)
233 {
234         cmddeferred_t *cmd, *prev;
235         double time = Sys_DoubleTime();
236         prev = NULL;
237         cmd = cmd_deferred_list;
238         while(cmd)
239         {
240                 if(cmd->time <= time)
241                 {
242                         Cbuf_AddText(cmd->value);
243                         Mem_Free(cmd->value);
244                         
245                         if(prev)
246                                 prev->next = cmd->next;
247                         else
248                                 cmd_deferred_list = cmd->next;
249                         
250                         Mem_Free(cmd);
251                         
252                         cmd = prev;
253                         if(!cmd)
254                                 return;
255                 }
256                 prev = cmd;
257                 cmd = cmd->next;
258         }
259 }
260
261 /*
262 ============
263 Cbuf_Execute
264 ============
265 */
266 static void Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias );
267 void Cbuf_Execute (void)
268 {
269         int i;
270         char *text;
271         char line[MAX_INPUTLINE];
272         char preprocessed[MAX_INPUTLINE];
273         char *firstchar;
274         int quotes;
275
276         // LordHavoc: making sure the tokenizebuffer doesn't get filled up by repeated crashes
277         cmd_tokenizebufferpos = 0;
278
279         Cbuf_Execute_Deferred();
280         while (cmd_text.cursize)
281         {
282 // find a \n or ; line break
283                 text = (char *)cmd_text.data;
284
285                 quotes = 0;
286                 for (i=0 ; i< cmd_text.cursize ; i++)
287                 {
288                         if (text[i] == '"')
289                                 quotes ^= 1;
290                         // make sure i doesn't get > cursize which causes a negative
291                         // size in memmove, which is fatal --blub
292                         if (i < (cmd_text.cursize-1) && (text[i] == '\\' && (text[i+1] == '"' || text[i+1] == '\\')))
293                                 i++;
294                         if ( !quotes &&  text[i] == ';')
295                                 break;  // don't break if inside a quoted string
296                         if (text[i] == '\r' || text[i] == '\n')
297                                 break;
298                 }
299
300                 // better than CRASHING on overlong input lines that may SOMEHOW enter the buffer
301                 if(i >= MAX_INPUTLINE)
302                 {
303                         Con_Printf("Warning: console input buffer had an overlong line. Ignored.\n");
304                         line[0] = 0;
305                 }
306                 else
307                 {
308                         memcpy (line, text, i);
309                         line[i] = 0;
310                 }
311
312 // delete the text from the command buffer and move remaining commands down
313 // this is necessary because commands (exec, alias) can insert data at the
314 // beginning of the text buffer
315
316                 if (i == cmd_text.cursize)
317                         cmd_text.cursize = 0;
318                 else
319                 {
320                         i++;
321                         cmd_text.cursize -= i;
322                         memmove (cmd_text.data, text+i, cmd_text.cursize);
323                 }
324
325 // execute the command line
326                 firstchar = line + strspn(line, " \t");
327                 if(
328                         (strncmp(firstchar, "alias", 5) || (firstchar[5] != ' ' && firstchar[5] != '\t'))
329                         &&
330                         (strncmp(firstchar, "bind", 4) || (firstchar[4] != ' ' && firstchar[4] != '\t'))
331                         &&
332                         (strncmp(firstchar, "in_bind", 7) || (firstchar[7] != ' ' && firstchar[7] != '\t'))
333                 )
334                 {
335                         Cmd_PreprocessString( line, preprocessed, sizeof(preprocessed), NULL );
336                         Cmd_ExecuteString (preprocessed, src_command);
337                 }
338                 else
339                 {
340                         Cmd_ExecuteString (line, src_command);
341                 }
342
343                 if (cmd_wait)
344                 {       // skip out while text still remains in buffer, leaving it
345                         // for next frame
346                         cmd_wait = false;
347                         break;
348                 }
349         }
350 }
351
352 /*
353 ==============================================================================
354
355                                                 SCRIPT COMMANDS
356
357 ==============================================================================
358 */
359
360 /*
361 ===============
362 Cmd_StuffCmds_f
363
364 Adds command line parameters as script statements
365 Commands lead with a +, and continue until a - or another +
366 quake +prog jctest.qp +cmd amlev1
367 quake -nosound +cmd amlev1
368 ===============
369 */
370 qboolean host_stuffcmdsrun = false;
371 void Cmd_StuffCmds_f (void)
372 {
373         int             i, j, l;
374         // this is for all commandline options combined (and is bounds checked)
375         char    build[MAX_INPUTLINE];
376
377         if (Cmd_Argc () != 1)
378         {
379                 Con_Print("stuffcmds : execute command line parameters\n");
380                 return;
381         }
382
383         // no reason to run the commandline arguments twice
384         if (host_stuffcmdsrun)
385                 return;
386
387         host_stuffcmdsrun = true;
388         build[0] = 0;
389         l = 0;
390         for (i = 0;i < com_argc;i++)
391         {
392                 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)
393                 {
394                         j = 1;
395                         while (com_argv[i][j])
396                                 build[l++] = com_argv[i][j++];
397                         i++;
398                         for (;i < com_argc;i++)
399                         {
400                                 if (!com_argv[i])
401                                         continue;
402                                 if ((com_argv[i][0] == '+' || com_argv[i][0] == '-') && (com_argv[i][1] < '0' || com_argv[i][1] > '9'))
403                                         break;
404                                 if (l + strlen(com_argv[i]) + 4 > sizeof(build) - 1)
405                                         break;
406                                 build[l++] = ' ';
407                                 if (strchr(com_argv[i], ' '))
408                                         build[l++] = '\"';
409                                 for (j = 0;com_argv[i][j];j++)
410                                         build[l++] = com_argv[i][j];
411                                 if (strchr(com_argv[i], ' '))
412                                         build[l++] = '\"';
413                         }
414                         build[l++] = '\n';
415                         i--;
416                 }
417         }
418         // now terminate the combined string and prepend it to the command buffer
419         // we already reserved space for the terminator
420         build[l++] = 0;
421         Cbuf_InsertText (build);
422 }
423
424
425 /*
426 ===============
427 Cmd_Exec_f
428 ===============
429 */
430 static void Cmd_Exec_f (void)
431 {
432         char *f;
433
434         if (Cmd_Argc () != 2)
435         {
436                 Con_Print("exec <filename> : execute a script file\n");
437                 return;
438         }
439
440         f = (char *)FS_LoadFile (Cmd_Argv(1), tempmempool, false, NULL);
441         if (!f)
442         {
443                 Con_Printf("couldn't exec %s\n",Cmd_Argv(1));
444                 return;
445         }
446         Con_Printf("execing %s\n",Cmd_Argv(1));
447
448         // if executing default.cfg for the first time, lock the cvar defaults
449         // it may seem backwards to insert this text BEFORE the default.cfg
450         // but Cbuf_InsertText inserts before, so this actually ends up after it.
451         if (!strcmp(Cmd_Argv(1), "default.cfg"))
452                 Cbuf_InsertText("\ncvar_lockdefaults\n");
453
454         // insert newline after the text to make sure the last line is terminated (some text editors omit the trailing newline)
455         // (note: insertion order here is backwards from execution order, so this adds it after the text, by calling it before...)
456         Cbuf_InsertText ("\n");
457         Cbuf_InsertText (f);
458         Mem_Free(f);
459 }
460
461
462 /*
463 ===============
464 Cmd_Echo_f
465
466 Just prints the rest of the line to the console
467 ===============
468 */
469 static void Cmd_Echo_f (void)
470 {
471         int             i;
472
473         for (i=1 ; i<Cmd_Argc() ; i++)
474                 Con_Printf("%s ",Cmd_Argv(i));
475         Con_Print("\n");
476 }
477
478 // DRESK - 5/14/06
479 // Support Doom3-style Toggle Console Command
480 /*
481 ===============
482 Cmd_Toggle_f
483
484 Toggles a specified console variable amongst the values specified (default is 0 and 1)
485 ===============
486 */
487 static void Cmd_Toggle_f(void)
488 {
489         // Acquire Number of Arguments
490         int nNumArgs = Cmd_Argc();
491
492         if(nNumArgs == 1)
493                 // No Arguments Specified; Print Usage
494                 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");
495         else
496         { // Correct Arguments Specified
497                 // Acquire Potential CVar
498                 cvar_t* cvCVar = Cvar_FindVar( Cmd_Argv(1) );
499
500                 if(cvCVar != NULL)
501                 { // Valid CVar
502                         if(nNumArgs == 2)
503                         { // Default Usage
504                                 if(cvCVar->integer)
505                                         Cvar_SetValueQuick(cvCVar, 0);
506                                 else
507                                         Cvar_SetValueQuick(cvCVar, 1);
508                         }
509                         else
510                         if(nNumArgs == 3)
511                         { // 0 and Specified Usage
512                                 if(cvCVar->integer == atoi(Cmd_Argv(2) ) )
513                                         // CVar is Specified Value; // Reset to 0
514                                         Cvar_SetValueQuick(cvCVar, 0);
515                                 else
516                                 if(cvCVar->integer == 0)
517                                         // CVar is 0; Specify Value
518                                         Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
519                                 else
520                                         // CVar does not match; Reset to 0
521                                         Cvar_SetValueQuick(cvCVar, 0);
522                         }
523                         else
524                         { // Variable Values Specified
525                                 int nCnt;
526                                 int bFound = 0;
527
528                                 for(nCnt = 2; nCnt < nNumArgs; nCnt++)
529                                 { // Cycle through Values
530                                         if( strcmp(cvCVar->string, Cmd_Argv(nCnt) ) == 0)
531                                         { // Current Value Located; Increment to Next
532                                                 if( (nCnt + 1) == nNumArgs)
533                                                         // Max Value Reached; Reset
534                                                         Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
535                                                 else
536                                                         // Next Value
537                                                         Cvar_SetQuick(cvCVar, Cmd_Argv(nCnt + 1) );
538
539                                                 // End Loop
540                                                 nCnt = nNumArgs;
541                                                 // Assign Found
542                                                 bFound = 1;
543                                         }
544                                 }
545                                 if(!bFound)
546                                         // Value not Found; Reset to Original
547                                         Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
548                         }
549
550                 }
551                 else
552                 { // Invalid CVar
553                         Con_Printf("ERROR : CVar '%s' not found\n", Cmd_Argv(1) );
554                 }
555         }
556 }
557
558 /*
559 ===============
560 Cmd_Alias_f
561
562 Creates a new command that executes a command string (possibly ; seperated)
563 ===============
564 */
565 static void Cmd_Alias_f (void)
566 {
567         cmdalias_t      *a;
568         char            cmd[MAX_INPUTLINE];
569         int                     i, c;
570         const char              *s;
571         size_t          alloclen;
572
573         if (Cmd_Argc() == 1)
574         {
575                 Con_Print("Current alias commands:\n");
576                 for (a = cmd_alias ; a ; a=a->next)
577                         Con_Printf("%s : %s\n", a->name, a->value);
578                 return;
579         }
580
581         s = Cmd_Argv(1);
582         if (strlen(s) >= MAX_ALIAS_NAME)
583         {
584                 Con_Print("Alias name is too long\n");
585                 return;
586         }
587
588         // if the alias already exists, reuse it
589         for (a = cmd_alias ; a ; a=a->next)
590         {
591                 if (!strcmp(s, a->name))
592                 {
593                         Z_Free (a->value);
594                         break;
595                 }
596         }
597
598         if (!a)
599         {
600                 cmdalias_t *prev, *current;
601
602                 a = (cmdalias_t *)Z_Malloc (sizeof(cmdalias_t));
603                 strlcpy (a->name, s, sizeof (a->name));
604                 // insert it at the right alphanumeric position
605                 for( prev = NULL, current = cmd_alias ; current && strcmp( current->name, a->name ) < 0 ; prev = current, current = current->next )
606                         ;
607                 if( prev ) {
608                         prev->next = a;
609                 } else {
610                         cmd_alias = a;
611                 }
612                 a->next = current;
613         }
614
615
616 // copy the rest of the command line
617         cmd[0] = 0;             // start out with a null string
618         c = Cmd_Argc();
619         for (i=2 ; i< c ; i++)
620         {
621                 strlcat (cmd, Cmd_Argv(i), sizeof (cmd));
622                 if (i != c)
623                         strlcat (cmd, " ", sizeof (cmd));
624         }
625         strlcat (cmd, "\n", sizeof (cmd));
626
627         alloclen = strlen (cmd) + 1;
628         a->value = (char *)Z_Malloc (alloclen);
629         memcpy (a->value, cmd, alloclen);
630 }
631
632 /*
633 =============================================================================
634
635                                         COMMAND EXECUTION
636
637 =============================================================================
638 */
639
640 typedef struct cmd_function_s
641 {
642         struct cmd_function_s *next;
643         const char *name;
644         const char *description;
645         xcommand_t consolefunction;
646         xcommand_t clientfunction;
647         qboolean csqcfunc;
648 } cmd_function_t;
649
650 static int cmd_argc;
651 static const char *cmd_argv[MAX_ARGS];
652 static const char *cmd_null_string = "";
653 static const char *cmd_args;
654 cmd_source_t cmd_source;
655
656
657 static cmd_function_t *cmd_functions;           // possible commands to execute
658
659 static const char *Cmd_GetDirectCvarValue(const char *varname, cmdalias_t *alias, qboolean *is_multiple)
660 {
661         cvar_t *cvar;
662         long argno;
663         char *endptr;
664
665         if(is_multiple)
666                 *is_multiple = false;
667
668         if(!varname || !*varname)
669                 return NULL;
670
671         if(alias)
672         {
673                 if(!strcmp(varname, "*"))
674                 {
675                         if(is_multiple)
676                                 *is_multiple = true;
677                         return Cmd_Args();
678                 }
679                 else if(varname[strlen(varname) - 1] == '-')
680                 {
681                         argno = strtol(varname, &endptr, 10);
682                         if(endptr == varname + strlen(varname) - 1)
683                         {
684                                 // whole string is a number, apart from the -
685                                 const char *p = Cmd_Args();
686                                 for(; argno > 1; --argno)
687                                         if(!COM_ParseToken_Console(&p))
688                                                 break;
689                                 if(p)
690                                 {
691                                         if(is_multiple)
692                                                 *is_multiple = true;
693
694                                         // kill pre-argument whitespace
695                                         for (;*p && *p <= ' ';p++)
696                                                 ;
697
698                                         return p;
699                                 }
700                         }
701                 }
702                 else
703                 {
704                         argno = strtol(varname, &endptr, 10);
705                         if(*endptr == 0)
706                         {
707                                 // whole string is a number
708                                 // NOTE: we already made sure we don't have an empty cvar name!
709                                 if(argno >= 0 && argno < Cmd_Argc())
710                                         return Cmd_Argv(argno);
711                         }
712                 }
713         }
714
715         if((cvar = Cvar_FindVar(varname)) && !(cvar->flags & CVAR_PRIVATE))
716                 return cvar->string;
717
718         return NULL;
719 }
720
721 qboolean Cmd_QuoteString(char *out, size_t outlen, const char *in, const char *quoteset)
722 {
723         qboolean quote_quot = !!strchr(quoteset, '"');
724         qboolean quote_backslash = !!strchr(quoteset, '\\');
725         qboolean quote_dollar = !!strchr(quoteset, '$');
726
727         while(*in)
728         {
729                 if(*in == '"' && quote_quot)
730                 {
731                         if(outlen <= 2)
732                         {
733                                 *out++ = 0;
734                                 return false;
735                         }
736                         *out++ = '\\'; --outlen;
737                         *out++ = '"'; --outlen;
738                 }
739                 else if(*in == '\\' && quote_backslash)
740                 {
741                         if(outlen <= 2)
742                         {
743                                 *out++ = 0;
744                                 return false;
745                         }
746                         *out++ = '\\'; --outlen;
747                         *out++ = '\\'; --outlen;
748                 }
749                 else if(*in == '$' && quote_dollar)
750                 {
751                         if(outlen <= 2)
752                         {
753                                 *out++ = 0;
754                                 return false;
755                         }
756                         *out++ = '$'; --outlen;
757                         *out++ = '$'; --outlen;
758                 }
759                 else
760                 {
761                         if(outlen <= 1)
762                         {
763                                 *out++ = 0;
764                                 return false;
765                         }
766                         *out++ = *in; --outlen;
767                 }
768                 ++in;
769         }
770         *out++ = 0;
771         return true;
772 }
773
774 static const char *Cmd_GetCvarValue(const char *var, size_t varlen, cmdalias_t *alias)
775 {
776         static char varname[MAX_INPUTLINE];
777         static char varval[MAX_INPUTLINE];
778         const char *varstr;
779         char *varfunc;
780
781         if(varlen >= MAX_INPUTLINE)
782                 varlen = MAX_INPUTLINE - 1;
783         memcpy(varname, var, varlen);
784         varname[varlen] = 0;
785         varfunc = strchr(varname, ' ');
786
787         if(varfunc)
788         {
789                 *varfunc = 0;
790                 ++varfunc;
791         }
792
793         if(*var == 0)
794         {
795                 // empty cvar name?
796                 return NULL;
797         }
798
799         varstr = NULL;
800
801         if(varname[0] == '$')
802                 varstr = Cmd_GetDirectCvarValue(Cmd_GetDirectCvarValue(varname + 1, alias, NULL), alias, NULL);
803         else
804         {
805                 qboolean is_multiple = false;
806                 // Exception: $* and $n- don't use the quoted form by default
807                 varstr = Cmd_GetDirectCvarValue(varname, alias, &is_multiple);
808                 if(is_multiple)
809                         varfunc = "asis";
810         }
811
812         if(!varstr)
813         {
814                 if(alias)
815                         Con_Printf("Warning: Could not expand $%s in alias %s\n", varname, alias->name);
816                 else
817                         Con_Printf("Warning: Could not expand $%s\n", varname);
818                 return NULL;
819         }
820
821         if(!varfunc || !strcmp(varfunc, "q")) // note: quoted form is default, use "asis" to override!
822         {
823                 // quote it so it can be used inside double quotes
824                 // we just need to replace " by \", and of course, double backslashes
825                 Cmd_QuoteString(varval, sizeof(varval), varstr, "\"\\");
826                 return varval;
827         }
828         else if(!strcmp(varfunc, "asis"))
829         {
830                 return varstr;
831         }
832         else
833                 Con_Printf("Unknown variable function %s\n", varfunc);
834
835         return varstr;
836 }
837
838 /*
839 Cmd_PreprocessString
840
841 Preprocesses strings and replaces $*, $param#, $cvar accordingly
842 */
843 static void Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias ) {
844         const char *in;
845         size_t eat, varlen;
846         unsigned outlen;
847         const char *val;
848
849         // don't crash if there's no room in the outtext buffer
850         if( maxoutlen == 0 ) {
851                 return;
852         }
853         maxoutlen--; // because of \0
854
855         in = intext;
856         outlen = 0;
857
858         while( *in && outlen < maxoutlen ) {
859                 if( *in == '$' ) {
860                         // this is some kind of expansion, see what comes after the $
861                         in++;
862
863                         // The console does the following preprocessing:
864                         //
865                         // - $$ is transformed to a single dollar sign.
866                         // - $var or ${var} are expanded to the contents of the named cvar,
867                         //   with quotation marks and backslashes quoted so it can safely
868                         //   be used inside quotation marks (and it should always be used
869                         //   that way)
870                         // - ${var asis} inserts the cvar value as is, without doing this
871                         //   quoting
872                         // - prefix the cvar name with a dollar sign to do indirection;
873                         //   for example, if $x has the value timelimit, ${$x} will return
874                         //   the value of $timelimit
875                         // - when expanding an alias, the special variable name $* refers
876                         //   to all alias parameters, and a number refers to that numbered
877                         //   alias parameter, where the name of the alias is $0, the first
878                         //   parameter is $1 and so on; as a special case, $* inserts all
879                         //   parameters, without extra quoting, so one can use $* to just
880                         //   pass all parameters around. All parameters starting from $n
881                         //   can be referred to as $n- (so $* is equivalent to $1-).
882                         //
883                         // Note: when expanding an alias, cvar expansion is done in the SAME step
884                         // as alias expansion so that alias parameters or cvar values containing
885                         // dollar signs have no unwanted bad side effects. However, this needs to
886                         // be accounted for when writing complex aliases. For example,
887                         //   alias foo "set x NEW; echo $x"
888                         // actually expands to
889                         //   "set x NEW; echo OLD"
890                         // and will print OLD! To work around this, use a second alias:
891                         //   alias foo "set x NEW; foo2"
892                         //   alias foo2 "echo $x"
893                         //
894                         // Also note: lines starting with alias are exempt from cvar expansion.
895                         // If you want cvar expansion, write "alias" instead:
896                         //
897                         //   set x 1
898                         //   alias foo "echo $x"
899                         //   "alias" bar "echo $x"
900                         //   set x 2
901                         //
902                         // foo will print 2, because the variable $x will be expanded when the alias
903                         // gets expanded. bar will print 1, because the variable $x was expanded
904                         // at definition time. foo can be equivalently defined as
905                         //
906                         //   "alias" foo "echo $$x"
907                         //
908                         // because at definition time, $$ will get replaced to a single $.
909
910                         if( *in == '$' ) {
911                                 val = "$";
912                                 eat = 1;
913                         } else if(*in == '{') {
914                                 varlen = strcspn(in + 1, "}");
915                                 if(in[varlen + 1] == '}')
916                                 {
917                                         val = Cmd_GetCvarValue(in + 1, varlen, alias);
918                                         eat = varlen + 2;
919                                 }
920                                 else
921                                 {
922                                         // ran out of data?
923                                         val = NULL;
924                                         eat = varlen + 1;
925                                 }
926                         } else {
927                                 varlen = strspn(in, "*0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-");
928                                 val = Cmd_GetCvarValue(in, varlen, alias);
929                                 eat = varlen;
930                         }
931                         if(val)
932                         {
933                                 // insert the cvar value
934                                 while(*val && outlen < maxoutlen)
935                                         outtext[outlen++] = *val++;
936                                 in += eat;
937                         }
938                         else
939                         {
940                                 // copy the unexpanded text
941                                 outtext[outlen++] = '$';
942                                 while(eat && outlen < maxoutlen)
943                                 {
944                                         outtext[outlen++] = *in++;
945                                         --eat;
946                                 }
947                         }
948                 } else {
949                         outtext[outlen++] = *in++;
950                 }
951         }
952         outtext[outlen] = 0;
953 }
954
955 /*
956 ============
957 Cmd_ExecuteAlias
958
959 Called for aliases and fills in the alias into the cbuffer
960 ============
961 */
962 static void Cmd_ExecuteAlias (cmdalias_t *alias)
963 {
964         static char buffer[ MAX_INPUTLINE ];
965         static char buffer2[ MAX_INPUTLINE ];
966         Cmd_PreprocessString( alias->value, buffer, sizeof(buffer) - 2, alias );
967         // insert at start of command buffer, so that aliases execute in order
968         // (fixes bug introduced by Black on 20050705)
969
970         // Note: Cbuf_PreprocessString will be called on this string AGAIN! So we
971         // have to make sure that no second variable expansion takes place, otherwise
972         // alias parameters containing dollar signs can have bad effects.
973         Cmd_QuoteString(buffer2, sizeof(buffer2), buffer, "$");
974         Cbuf_InsertText( buffer2 );
975 }
976
977 /*
978 ========
979 Cmd_List
980
981         CmdList Added by EvilTypeGuy eviltypeguy@qeradiant.com
982         Thanks to Matthias "Maddes" Buecher, http://www.inside3d.com/qip/
983
984 ========
985 */
986 static void Cmd_List_f (void)
987 {
988         cmd_function_t *cmd;
989         const char *partial;
990         int len, count;
991
992         if (Cmd_Argc() > 1)
993         {
994                 partial = Cmd_Argv (1);
995                 len = (int)strlen(partial);
996         }
997         else
998         {
999                 partial = NULL;
1000                 len = 0;
1001         }
1002
1003         count = 0;
1004         for (cmd = cmd_functions; cmd; cmd = cmd->next)
1005         {
1006                 if (partial && strncmp(partial, cmd->name, len))
1007                         continue;
1008                 Con_Printf("%s : %s\n", cmd->name, cmd->description);
1009                 count++;
1010         }
1011
1012         if (partial)
1013                 Con_Printf("%i Command%s beginning with \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1014         else
1015                 Con_Printf("%i Command%s\n\n", count, (count > 1) ? "s" : "");
1016 }
1017
1018 /*
1019 ============
1020 Cmd_Init
1021 ============
1022 */
1023 void Cmd_Init (void)
1024 {
1025         cmd_mempool = Mem_AllocPool("commands", 0, NULL);
1026         // space for commands and script files
1027         cmd_text.data = cmd_text_buf;
1028         cmd_text.maxsize = sizeof(cmd_text_buf);
1029         cmd_text.cursize = 0;
1030 }
1031
1032 void Cmd_Init_Commands (void)
1033 {
1034 //
1035 // register our commands
1036 //
1037         Cmd_AddCommand ("stuffcmds",Cmd_StuffCmds_f, "execute commandline parameters (must be present in quake.rc script)");
1038         Cmd_AddCommand ("exec",Cmd_Exec_f, "execute a script file");
1039         Cmd_AddCommand ("echo",Cmd_Echo_f, "print a message to the console (useful in scripts)");
1040         Cmd_AddCommand ("alias",Cmd_Alias_f, "create a script function (parameters are passed in as $1 through $9, and $* for all parameters)");
1041         Cmd_AddCommand ("cmd", Cmd_ForwardToServer, "send a console commandline to the server (used by some mods)");
1042         Cmd_AddCommand ("wait", Cmd_Wait_f, "make script execution wait for next rendered frame");
1043         Cmd_AddCommand ("set", Cvar_Set_f, "create or change the value of a console variable");
1044         Cmd_AddCommand ("seta", Cvar_SetA_f, "create or change the value of a console variable that will be saved to config.cfg");
1045
1046         // 2000-01-09 CmdList, CvarList commands By Matthias "Maddes" Buecher
1047         // Added/Modified by EvilTypeGuy eviltypeguy@qeradiant.com
1048         Cmd_AddCommand ("cmdlist", Cmd_List_f, "lists all console commands beginning with the specified prefix");
1049         Cmd_AddCommand ("cvarlist", Cvar_List_f, "lists all console variables beginning with the specified prefix");
1050
1051         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");
1052         Cmd_AddCommand ("cvar_resettodefaults_all", Cvar_ResetToDefaults_All_f, "sets all cvars to their locked default values");
1053         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)");
1054         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)");
1055
1056         Cmd_AddCommand ("cprint", Cmd_Centerprint_f, "print something at the screen center");
1057         Cmd_AddCommand ("defer", Cmd_Defer_f, "execute a command in the future");
1058
1059         // DRESK - 5/14/06
1060         // Support Doom3-style Toggle Command
1061         Cmd_AddCommand( "toggle", Cmd_Toggle_f, "toggles a console variable's values (use for more info)");
1062 }
1063
1064 /*
1065 ============
1066 Cmd_Shutdown
1067 ============
1068 */
1069 void Cmd_Shutdown(void)
1070 {
1071         Mem_FreePool(&cmd_mempool);
1072 }
1073
1074 /*
1075 ============
1076 Cmd_Argc
1077 ============
1078 */
1079 int             Cmd_Argc (void)
1080 {
1081         return cmd_argc;
1082 }
1083
1084 /*
1085 ============
1086 Cmd_Argv
1087 ============
1088 */
1089 const char *Cmd_Argv (int arg)
1090 {
1091         if (arg >= cmd_argc )
1092                 return cmd_null_string;
1093         return cmd_argv[arg];
1094 }
1095
1096 /*
1097 ============
1098 Cmd_Args
1099 ============
1100 */
1101 const char *Cmd_Args (void)
1102 {
1103         return cmd_args;
1104 }
1105
1106
1107 /*
1108 ============
1109 Cmd_TokenizeString
1110
1111 Parses the given string into command line tokens.
1112 ============
1113 */
1114 // AK: This function should only be called from ExcuteString because the current design is a bit of an hack
1115 static void Cmd_TokenizeString (const char *text)
1116 {
1117         int l;
1118
1119         cmd_argc = 0;
1120         cmd_args = NULL;
1121
1122         while (1)
1123         {
1124                 // skip whitespace up to a /n
1125                 while (*text && *text <= ' ' && *text != '\r' && *text != '\n')
1126                         text++;
1127
1128                 // line endings:
1129                 // UNIX: \n
1130                 // Mac: \r
1131                 // Windows: \r\n
1132                 if (*text == '\n' || *text == '\r')
1133                 {
1134                         // a newline separates commands in the buffer
1135                         if (*text == '\r' && text[1] == '\n')
1136                                 text++;
1137                         text++;
1138                         break;
1139                 }
1140
1141                 if (!*text)
1142                         return;
1143
1144                 if (cmd_argc == 1)
1145                         cmd_args = text;
1146
1147                 if (!COM_ParseToken_Console(&text))
1148                         return;
1149
1150                 if (cmd_argc < MAX_ARGS)
1151                 {
1152                         l = (int)strlen(com_token) + 1;
1153                         if (cmd_tokenizebufferpos + l > CMD_TOKENIZELENGTH)
1154                         {
1155                                 Con_Printf("Cmd_TokenizeString: ran out of %i character buffer space for command arguements\n", CMD_TOKENIZELENGTH);
1156                                 break;
1157                         }
1158                         memcpy (cmd_tokenizebuffer + cmd_tokenizebufferpos, com_token, l);
1159                         cmd_argv[cmd_argc] = cmd_tokenizebuffer + cmd_tokenizebufferpos;
1160                         cmd_tokenizebufferpos += l;
1161                         cmd_argc++;
1162                 }
1163         }
1164 }
1165
1166
1167 /*
1168 ============
1169 Cmd_AddCommand
1170 ============
1171 */
1172 void Cmd_AddCommand_WithClientCommand (const char *cmd_name, xcommand_t consolefunction, xcommand_t clientfunction, const char *description)
1173 {
1174         cmd_function_t *cmd;
1175         cmd_function_t *prev, *current;
1176
1177 // fail if the command is a variable name
1178         if (Cvar_FindVar( cmd_name ))
1179         {
1180                 Con_Printf("Cmd_AddCommand: %s already defined as a var\n", cmd_name);
1181                 return;
1182         }
1183
1184 // fail if the command already exists
1185         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1186         {
1187                 if (!strcmp (cmd_name, cmd->name))
1188                 {
1189                         if (consolefunction || clientfunction)
1190                         {
1191                                 Con_Printf("Cmd_AddCommand: %s already defined\n", cmd_name);
1192                                 return;
1193                         }
1194                         else    //[515]: csqc
1195                         {
1196                                 cmd->csqcfunc = true;
1197                                 return;
1198                         }
1199                 }
1200         }
1201
1202         cmd = (cmd_function_t *)Mem_Alloc(cmd_mempool, sizeof(cmd_function_t));
1203         cmd->name = cmd_name;
1204         cmd->consolefunction = consolefunction;
1205         cmd->clientfunction = clientfunction;
1206         cmd->description = description;
1207         if(!consolefunction && !clientfunction)                 //[515]: csqc
1208                 cmd->csqcfunc = true;
1209         cmd->next = cmd_functions;
1210
1211 // insert it at the right alphanumeric position
1212         for( prev = NULL, current = cmd_functions ; current && strcmp( current->name, cmd->name ) < 0 ; prev = current, current = current->next )
1213                 ;
1214         if( prev ) {
1215                 prev->next = cmd;
1216         } else {
1217                 cmd_functions = cmd;
1218         }
1219         cmd->next = current;
1220 }
1221
1222 void Cmd_AddCommand (const char *cmd_name, xcommand_t function, const char *description)
1223 {
1224         Cmd_AddCommand_WithClientCommand (cmd_name, function, NULL, description);
1225 }
1226
1227 /*
1228 ============
1229 Cmd_Exists
1230 ============
1231 */
1232 qboolean Cmd_Exists (const char *cmd_name)
1233 {
1234         cmd_function_t  *cmd;
1235
1236         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1237                 if (!strcmp (cmd_name,cmd->name))
1238                         return true;
1239
1240         return false;
1241 }
1242
1243
1244 /*
1245 ============
1246 Cmd_CompleteCommand
1247 ============
1248 */
1249 const char *Cmd_CompleteCommand (const char *partial)
1250 {
1251         cmd_function_t *cmd;
1252         size_t len;
1253
1254         len = strlen(partial);
1255
1256         if (!len)
1257                 return NULL;
1258
1259 // check functions
1260         for (cmd = cmd_functions; cmd; cmd = cmd->next)
1261                 if (!strncasecmp(partial, cmd->name, len))
1262                         return cmd->name;
1263
1264         return NULL;
1265 }
1266
1267 /*
1268         Cmd_CompleteCountPossible
1269
1270         New function for tab-completion system
1271         Added by EvilTypeGuy
1272         Thanks to Fett erich@heintz.com
1273         Thanks to taniwha
1274
1275 */
1276 int Cmd_CompleteCountPossible (const char *partial)
1277 {
1278         cmd_function_t *cmd;
1279         size_t len;
1280         int h;
1281
1282         h = 0;
1283         len = strlen(partial);
1284
1285         if (!len)
1286                 return 0;
1287
1288         // Loop through the command list and count all partial matches
1289         for (cmd = cmd_functions; cmd; cmd = cmd->next)
1290                 if (!strncasecmp(partial, cmd->name, len))
1291                         h++;
1292
1293         return h;
1294 }
1295
1296 /*
1297         Cmd_CompleteBuildList
1298
1299         New function for tab-completion system
1300         Added by EvilTypeGuy
1301         Thanks to Fett erich@heintz.com
1302         Thanks to taniwha
1303
1304 */
1305 const char **Cmd_CompleteBuildList (const char *partial)
1306 {
1307         cmd_function_t *cmd;
1308         size_t len = 0;
1309         size_t bpos = 0;
1310         size_t sizeofbuf = (Cmd_CompleteCountPossible (partial) + 1) * sizeof (const char *);
1311         const char **buf;
1312
1313         len = strlen(partial);
1314         buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1315         // Loop through the alias list and print all matches
1316         for (cmd = cmd_functions; cmd; cmd = cmd->next)
1317                 if (!strncasecmp(partial, cmd->name, len))
1318                         buf[bpos++] = cmd->name;
1319
1320         buf[bpos] = NULL;
1321         return buf;
1322 }
1323
1324 // written by LordHavoc
1325 void Cmd_CompleteCommandPrint (const char *partial)
1326 {
1327         cmd_function_t *cmd;
1328         size_t len = strlen(partial);
1329         // Loop through the command list and print all matches
1330         for (cmd = cmd_functions; cmd; cmd = cmd->next)
1331                 if (!strncasecmp(partial, cmd->name, len))
1332                         Con_Printf("%s : %s\n", cmd->name, cmd->description);
1333 }
1334
1335 /*
1336         Cmd_CompleteAlias
1337
1338         New function for tab-completion system
1339         Added by EvilTypeGuy
1340         Thanks to Fett erich@heintz.com
1341         Thanks to taniwha
1342
1343 */
1344 const char *Cmd_CompleteAlias (const char *partial)
1345 {
1346         cmdalias_t *alias;
1347         size_t len;
1348
1349         len = strlen(partial);
1350
1351         if (!len)
1352                 return NULL;
1353
1354         // Check functions
1355         for (alias = cmd_alias; alias; alias = alias->next)
1356                 if (!strncasecmp(partial, alias->name, len))
1357                         return alias->name;
1358
1359         return NULL;
1360 }
1361
1362 // written by LordHavoc
1363 void Cmd_CompleteAliasPrint (const char *partial)
1364 {
1365         cmdalias_t *alias;
1366         size_t len = strlen(partial);
1367         // Loop through the alias list and print all matches
1368         for (alias = cmd_alias; alias; alias = alias->next)
1369                 if (!strncasecmp(partial, alias->name, len))
1370                         Con_Printf("%s : %s\n", alias->name, alias->value);
1371 }
1372
1373
1374 /*
1375         Cmd_CompleteAliasCountPossible
1376
1377         New function for tab-completion system
1378         Added by EvilTypeGuy
1379         Thanks to Fett erich@heintz.com
1380         Thanks to taniwha
1381
1382 */
1383 int Cmd_CompleteAliasCountPossible (const char *partial)
1384 {
1385         cmdalias_t      *alias;
1386         size_t          len;
1387         int                     h;
1388
1389         h = 0;
1390
1391         len = strlen(partial);
1392
1393         if (!len)
1394                 return 0;
1395
1396         // Loop through the command list and count all partial matches
1397         for (alias = cmd_alias; alias; alias = alias->next)
1398                 if (!strncasecmp(partial, alias->name, len))
1399                         h++;
1400
1401         return h;
1402 }
1403
1404 /*
1405         Cmd_CompleteAliasBuildList
1406
1407         New function for tab-completion system
1408         Added by EvilTypeGuy
1409         Thanks to Fett erich@heintz.com
1410         Thanks to taniwha
1411
1412 */
1413 const char **Cmd_CompleteAliasBuildList (const char *partial)
1414 {
1415         cmdalias_t *alias;
1416         size_t len = 0;
1417         size_t bpos = 0;
1418         size_t sizeofbuf = (Cmd_CompleteAliasCountPossible (partial) + 1) * sizeof (const char *);
1419         const char **buf;
1420
1421         len = strlen(partial);
1422         buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1423         // Loop through the alias list and print all matches
1424         for (alias = cmd_alias; alias; alias = alias->next)
1425                 if (!strncasecmp(partial, alias->name, len))
1426                         buf[bpos++] = alias->name;
1427
1428         buf[bpos] = NULL;
1429         return buf;
1430 }
1431
1432 void Cmd_ClearCsqcFuncs (void)
1433 {
1434         cmd_function_t *cmd;
1435         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1436                 cmd->csqcfunc = false;
1437 }
1438
1439 qboolean CL_VM_ConsoleCommand (const char *cmd);
1440 /*
1441 ============
1442 Cmd_ExecuteString
1443
1444 A complete command line has been parsed, so try to execute it
1445 FIXME: lookupnoadd the token to speed search?
1446 ============
1447 */
1448 void Cmd_ExecuteString (const char *text, cmd_source_t src)
1449 {
1450         int oldpos;
1451         cmd_function_t *cmd;
1452         cmdalias_t *a;
1453
1454         oldpos = cmd_tokenizebufferpos;
1455         cmd_source = src;
1456
1457         Cmd_TokenizeString (text);
1458
1459 // execute the command line
1460         if (!Cmd_Argc())
1461         {
1462                 cmd_tokenizebufferpos = oldpos;
1463                 return;         // no tokens
1464         }
1465
1466 // check functions
1467         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1468         {
1469                 if (!strcasecmp (cmd_argv[0],cmd->name))
1470                 {
1471                         if (cmd->csqcfunc && CL_VM_ConsoleCommand (text))       //[515]: csqc
1472                                 return;
1473                         switch (src)
1474                         {
1475                         case src_command:
1476                                 if (cmd->consolefunction)
1477                                         cmd->consolefunction ();
1478                                 else if (cmd->clientfunction)
1479                                 {
1480                                         if (cls.state == ca_connected)
1481                                         {
1482                                                 // forward remote commands to the server for execution
1483                                                 Cmd_ForwardToServer();
1484                                         }
1485                                         else
1486                                                 Con_Printf("Can not send command \"%s\", not connected.\n", Cmd_Argv(0));
1487                                 }
1488                                 else
1489                                         Con_Printf("Command \"%s\" can not be executed\n", Cmd_Argv(0));
1490                                 cmd_tokenizebufferpos = oldpos;
1491                                 return;
1492                         case src_client:
1493                                 if (cmd->clientfunction)
1494                                 {
1495                                         cmd->clientfunction ();
1496                                         cmd_tokenizebufferpos = oldpos;
1497                                         return;
1498                                 }
1499                                 break;
1500                         }
1501                         break;
1502                 }
1503         }
1504
1505         // if it's a client command and no command was found, say so.
1506         if (cmd_source == src_client)
1507         {
1508                 Con_Printf("player \"%s\" tried to %s\n", host_client->name, text);
1509                 return;
1510         }
1511
1512 // check alias
1513         for (a=cmd_alias ; a ; a=a->next)
1514         {
1515                 if (!strcasecmp (cmd_argv[0], a->name))
1516                 {
1517                         Cmd_ExecuteAlias(a);
1518                         cmd_tokenizebufferpos = oldpos;
1519                         return;
1520                 }
1521         }
1522
1523 // check cvars
1524         if (!Cvar_Command () && host_framecount > 0)
1525                 Con_Printf("Unknown command \"%s\"\n", Cmd_Argv(0));
1526
1527         cmd_tokenizebufferpos = oldpos;
1528 }
1529
1530
1531 /*
1532 ===================
1533 Cmd_ForwardStringToServer
1534
1535 Sends an entire command string over to the server, unprocessed
1536 ===================
1537 */
1538 void Cmd_ForwardStringToServer (const char *s)
1539 {
1540         char temp[128];
1541         if (cls.state != ca_connected)
1542         {
1543                 Con_Printf("Can't \"%s\", not connected\n", s);
1544                 return;
1545         }
1546
1547         if (!cls.netcon)
1548                 return;
1549
1550         // LordHavoc: thanks to Fuh for bringing the pure evil of SZ_Print to my
1551         // attention, it has been eradicated from here, its only (former) use in
1552         // all of darkplaces.
1553         if (cls.protocol == PROTOCOL_QUAKEWORLD)
1554                 MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
1555         else
1556                 MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
1557         if ((!strncmp(s, "say ", 4) || !strncmp(s, "say_team ", 9)) && cl_locs_enable.integer)
1558         {
1559                 // say/say_team commands can replace % character codes with status info
1560                 while (*s)
1561                 {
1562                         if (*s == '%' && s[1])
1563                         {
1564                                 // handle proquake message macros
1565                                 temp[0] = 0;
1566                                 switch (s[1])
1567                                 {
1568                                 case 'l': // current location
1569                                         CL_Locs_FindLocationName(temp, sizeof(temp), cl.movement_origin);
1570                                         break;
1571                                 case 'h': // current health
1572                                         dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_HEALTH]);
1573                                         break;
1574                                 case 'a': // current armor
1575                                         dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ARMOR]);
1576                                         break;
1577                                 case 'x': // current rockets
1578                                         dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ROCKETS]);
1579                                         break;
1580                                 case 'c': // current cells
1581                                         dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_CELLS]);
1582                                         break;
1583                                 // silly proquake macros
1584                                 case 'd': // loc at last death
1585                                         CL_Locs_FindLocationName(temp, sizeof(temp), cl.lastdeathorigin);
1586                                         break;
1587                                 case 't': // current time
1588                                         dpsnprintf(temp, sizeof(temp), "%.0f:%.0f", floor(cl.time / 60), cl.time - floor(cl.time / 60) * 60);
1589                                         break;
1590                                 case 'r': // rocket launcher status ("I have RL", "I need rockets", "I need RL")
1591                                         if (!(cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER))
1592                                                 dpsnprintf(temp, sizeof(temp), "I need RL");
1593                                         else if (!cl.stats[STAT_ROCKETS])
1594                                                 dpsnprintf(temp, sizeof(temp), "I need rockets");
1595                                         else
1596                                                 dpsnprintf(temp, sizeof(temp), "I have RL");
1597                                         break;
1598                                 case 'p': // powerup status (outputs "quad" "pent" and "eyes" according to status)
1599                                         if (cl.stats[STAT_ITEMS] & IT_QUAD)
1600                                         {
1601                                                 if (temp[0])
1602                                                         strlcat(temp, " ", sizeof(temp));
1603                                                 strlcat(temp, "quad", sizeof(temp));
1604                                         }
1605                                         if (cl.stats[STAT_ITEMS] & IT_INVULNERABILITY)
1606                                         {
1607                                                 if (temp[0])
1608                                                         strlcat(temp, " ", sizeof(temp));
1609                                                 strlcat(temp, "pent", sizeof(temp));
1610                                         }
1611                                         if (cl.stats[STAT_ITEMS] & IT_INVISIBILITY)
1612                                         {
1613                                                 if (temp[0])
1614                                                         strlcat(temp, " ", sizeof(temp));
1615                                                 strlcat(temp, "eyes", sizeof(temp));
1616                                         }
1617                                         break;
1618                                 case 'w': // weapon status (outputs "SSG:NG:SNG:GL:RL:LG" with the text between : characters omitted if you lack the weapon)
1619                                         if (cl.stats[STAT_ITEMS] & IT_SUPER_SHOTGUN)
1620                                                 strlcat(temp, "SSG", sizeof(temp));
1621                                         strlcat(temp, ":", sizeof(temp));
1622                                         if (cl.stats[STAT_ITEMS] & IT_NAILGUN)
1623                                                 strlcat(temp, "NG", sizeof(temp));
1624                                         strlcat(temp, ":", sizeof(temp));
1625                                         if (cl.stats[STAT_ITEMS] & IT_SUPER_NAILGUN)
1626                                                 strlcat(temp, "SNG", sizeof(temp));
1627                                         strlcat(temp, ":", sizeof(temp));
1628                                         if (cl.stats[STAT_ITEMS] & IT_GRENADE_LAUNCHER)
1629                                                 strlcat(temp, "GL", sizeof(temp));
1630                                         strlcat(temp, ":", sizeof(temp));
1631                                         if (cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER)
1632                                                 strlcat(temp, "RL", sizeof(temp));
1633                                         strlcat(temp, ":", sizeof(temp));
1634                                         if (cl.stats[STAT_ITEMS] & IT_LIGHTNING)
1635                                                 strlcat(temp, "LG", sizeof(temp));
1636                                         break;
1637                                 default:
1638                                         // not a recognized macro, print it as-is...
1639                                         temp[0] = s[0];
1640                                         temp[1] = s[1];
1641                                         temp[2] = 0;
1642                                         break;
1643                                 }
1644                                 // write the resulting text
1645                                 SZ_Write(&cls.netcon->message, (unsigned char *)temp, strlen(temp));
1646                                 s += 2;
1647                                 continue;
1648                         }
1649                         MSG_WriteByte(&cls.netcon->message, *s);
1650                         s++;
1651                 }
1652                 MSG_WriteByte(&cls.netcon->message, 0);
1653         }
1654         else // any other command is passed on as-is
1655                 SZ_Write(&cls.netcon->message, (const unsigned char *)s, (int)strlen(s) + 1);
1656 }
1657
1658 /*
1659 ===================
1660 Cmd_ForwardToServer
1661
1662 Sends the entire command line over to the server
1663 ===================
1664 */
1665 void Cmd_ForwardToServer (void)
1666 {
1667         const char *s;
1668         if (!strcasecmp(Cmd_Argv(0), "cmd"))
1669         {
1670                 // we want to strip off "cmd", so just send the args
1671                 s = Cmd_Argc() > 1 ? Cmd_Args() : "";
1672         }
1673         else
1674         {
1675                 // we need to keep the command name, so send Cmd_Argv(0), a space and then Cmd_Args()
1676                 s = va("%s %s", Cmd_Argv(0), Cmd_Argc() > 1 ? Cmd_Args() : "");
1677         }
1678         // don't send an empty forward message if the user tries "cmd" by itself
1679         if (!s || !*s)
1680                 return;
1681         Cmd_ForwardStringToServer(s);
1682 }
1683
1684
1685 /*
1686 ================
1687 Cmd_CheckParm
1688
1689 Returns the position (1 to argc-1) in the command's argument list
1690 where the given parameter apears, or 0 if not present
1691 ================
1692 */
1693
1694 int Cmd_CheckParm (const char *parm)
1695 {
1696         int i;
1697
1698         if (!parm)
1699         {
1700                 Con_Printf ("Cmd_CheckParm: NULL");
1701                 return 0;
1702         }
1703
1704         for (i = 1; i < Cmd_Argc (); i++)
1705                 if (!strcasecmp (parm, Cmd_Argv (i)))
1706                         return i;
1707
1708         return 0;
1709 }
1710