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