changed the Sys_Error to a Con_Printf. LordHavoc, please check if the equation REALLY...
[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 && *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                         varfunc = "asis";
830         }
831
832         if(!varstr)
833         {
834                 if(alias)
835                         Con_Printf("Warning: Could not expand $%s in alias %s\n", varname, alias->name);
836                 else
837                         Con_Printf("Warning: Could not expand $%s\n", varname);
838                 return NULL;
839         }
840
841         if(!varfunc || !strcmp(varfunc, "q")) // note: quoted form is default, use "asis" to override!
842         {
843                 // quote it so it can be used inside double quotes
844                 // we just need to replace " by \", and of course, double backslashes
845                 Cmd_QuoteString(varval, sizeof(varval), varstr, "\"\\");
846                 return varval;
847         }
848         else if(!strcmp(varfunc, "asis"))
849         {
850                 return varstr;
851         }
852         else
853                 Con_Printf("Unknown variable function %s\n", varfunc);
854
855         return varstr;
856 }
857
858 /*
859 Cmd_PreprocessString
860
861 Preprocesses strings and replaces $*, $param#, $cvar accordingly
862 */
863 static void Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias ) {
864         const char *in;
865         size_t eat, varlen;
866         unsigned outlen;
867         const char *val;
868
869         // don't crash if there's no room in the outtext buffer
870         if( maxoutlen == 0 ) {
871                 return;
872         }
873         maxoutlen--; // because of \0
874
875         in = intext;
876         outlen = 0;
877
878         while( *in && outlen < maxoutlen ) {
879                 if( *in == '$' ) {
880                         // this is some kind of expansion, see what comes after the $
881                         in++;
882
883                         // The console does the following preprocessing:
884                         //
885                         // - $$ is transformed to a single dollar sign.
886                         // - $var or ${var} are expanded to the contents of the named cvar,
887                         //   with quotation marks and backslashes quoted so it can safely
888                         //   be used inside quotation marks (and it should always be used
889                         //   that way)
890                         // - ${var asis} inserts the cvar value as is, without doing this
891                         //   quoting
892                         // - prefix the cvar name with a dollar sign to do indirection;
893                         //   for example, if $x has the value timelimit, ${$x} will return
894                         //   the value of $timelimit
895                         // - when expanding an alias, the special variable name $* refers
896                         //   to all alias parameters, and a number refers to that numbered
897                         //   alias parameter, where the name of the alias is $0, the first
898                         //   parameter is $1 and so on; as a special case, $* inserts all
899                         //   parameters, without extra quoting, so one can use $* to just
900                         //   pass all parameters around. All parameters starting from $n
901                         //   can be referred to as $n- (so $* is equivalent to $1-).
902                         //
903                         // Note: when expanding an alias, cvar expansion is done in the SAME step
904                         // as alias expansion so that alias parameters or cvar values containing
905                         // dollar signs have no unwanted bad side effects. However, this needs to
906                         // be accounted for when writing complex aliases. For example,
907                         //   alias foo "set x NEW; echo $x"
908                         // actually expands to
909                         //   "set x NEW; echo OLD"
910                         // and will print OLD! To work around this, use a second alias:
911                         //   alias foo "set x NEW; foo2"
912                         //   alias foo2 "echo $x"
913                         //
914                         // Also note: lines starting with alias are exempt from cvar expansion.
915                         // If you want cvar expansion, write "alias" instead:
916                         //
917                         //   set x 1
918                         //   alias foo "echo $x"
919                         //   "alias" bar "echo $x"
920                         //   set x 2
921                         //
922                         // foo will print 2, because the variable $x will be expanded when the alias
923                         // gets expanded. bar will print 1, because the variable $x was expanded
924                         // at definition time. foo can be equivalently defined as
925                         //
926                         //   "alias" foo "echo $$x"
927                         //
928                         // because at definition time, $$ will get replaced to a single $.
929
930                         if( *in == '$' ) {
931                                 val = "$";
932                                 eat = 1;
933                         } else if(*in == '{') {
934                                 varlen = strcspn(in + 1, "}");
935                                 if(in[varlen + 1] == '}')
936                                 {
937                                         val = Cmd_GetCvarValue(in + 1, varlen, alias);
938                                         eat = varlen + 2;
939                                 }
940                                 else
941                                 {
942                                         // ran out of data?
943                                         val = NULL;
944                                         eat = varlen + 1;
945                                 }
946                         } else {
947                                 varlen = strspn(in, "*0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-");
948                                 val = Cmd_GetCvarValue(in, varlen, alias);
949                                 eat = varlen;
950                         }
951                         if(val)
952                         {
953                                 // insert the cvar value
954                                 while(*val && outlen < maxoutlen)
955                                         outtext[outlen++] = *val++;
956                                 in += eat;
957                         }
958                         else
959                         {
960                                 // copy the unexpanded text
961                                 outtext[outlen++] = '$';
962                                 while(eat && outlen < maxoutlen)
963                                 {
964                                         outtext[outlen++] = *in++;
965                                         --eat;
966                                 }
967                         }
968                 } else {
969                         outtext[outlen++] = *in++;
970                 }
971         }
972         outtext[outlen] = 0;
973 }
974
975 /*
976 ============
977 Cmd_ExecuteAlias
978
979 Called for aliases and fills in the alias into the cbuffer
980 ============
981 */
982 static void Cmd_ExecuteAlias (cmdalias_t *alias)
983 {
984         static char buffer[ MAX_INPUTLINE ];
985         static char buffer2[ MAX_INPUTLINE ];
986         Cmd_PreprocessString( alias->value, buffer, sizeof(buffer) - 2, alias );
987         // insert at start of command buffer, so that aliases execute in order
988         // (fixes bug introduced by Black on 20050705)
989
990         // Note: Cbuf_PreprocessString will be called on this string AGAIN! So we
991         // have to make sure that no second variable expansion takes place, otherwise
992         // alias parameters containing dollar signs can have bad effects.
993         Cmd_QuoteString(buffer2, sizeof(buffer2), buffer, "$");
994         Cbuf_InsertText( buffer2 );
995 }
996
997 /*
998 ========
999 Cmd_List
1000
1001         CmdList Added by EvilTypeGuy eviltypeguy@qeradiant.com
1002         Thanks to Matthias "Maddes" Buecher, http://www.inside3d.com/qip/
1003
1004 ========
1005 */
1006 static void Cmd_List_f (void)
1007 {
1008         cmd_function_t *cmd;
1009         const char *partial;
1010         int len, count;
1011
1012         if (Cmd_Argc() > 1)
1013         {
1014                 partial = Cmd_Argv (1);
1015                 len = (int)strlen(partial);
1016         }
1017         else
1018         {
1019                 partial = NULL;
1020                 len = 0;
1021         }
1022
1023         count = 0;
1024         for (cmd = cmd_functions; cmd; cmd = cmd->next)
1025         {
1026                 if (partial && strncmp(partial, cmd->name, len))
1027                         continue;
1028                 Con_Printf("%s : %s\n", cmd->name, cmd->description);
1029                 count++;
1030         }
1031
1032         if (partial)
1033                 Con_Printf("%i Command%s beginning with \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1034         else
1035                 Con_Printf("%i Command%s\n\n", count, (count > 1) ? "s" : "");
1036 }
1037
1038 /*
1039 ============
1040 Cmd_Init
1041 ============
1042 */
1043 void Cmd_Init (void)
1044 {
1045         cmd_mempool = Mem_AllocPool("commands", 0, NULL);
1046         // space for commands and script files
1047         cmd_text.data = cmd_text_buf;
1048         cmd_text.maxsize = sizeof(cmd_text_buf);
1049         cmd_text.cursize = 0;
1050 }
1051
1052 void Cmd_Init_Commands (void)
1053 {
1054 //
1055 // register our commands
1056 //
1057         Cmd_AddCommand ("stuffcmds",Cmd_StuffCmds_f, "execute commandline parameters (must be present in quake.rc script)");
1058         Cmd_AddCommand ("exec",Cmd_Exec_f, "execute a script file");
1059         Cmd_AddCommand ("echo",Cmd_Echo_f, "print a message to the console (useful in scripts)");
1060         Cmd_AddCommand ("alias",Cmd_Alias_f, "create a script function (parameters are passed in as $1 through $9, and $* for all parameters)");
1061         Cmd_AddCommand ("cmd", Cmd_ForwardToServer, "send a console commandline to the server (used by some mods)");
1062         Cmd_AddCommand ("wait", Cmd_Wait_f, "make script execution wait for next rendered frame");
1063         Cmd_AddCommand ("set", Cvar_Set_f, "create or change the value of a console variable");
1064         Cmd_AddCommand ("seta", Cvar_SetA_f, "create or change the value of a console variable that will be saved to config.cfg");
1065
1066         // 2000-01-09 CmdList, CvarList commands By Matthias "Maddes" Buecher
1067         // Added/Modified by EvilTypeGuy eviltypeguy@qeradiant.com
1068         Cmd_AddCommand ("cmdlist", Cmd_List_f, "lists all console commands beginning with the specified prefix");
1069         Cmd_AddCommand ("cvarlist", Cvar_List_f, "lists all console variables beginning with the specified prefix");
1070
1071         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");
1072         Cmd_AddCommand ("cvar_resettodefaults_all", Cvar_ResetToDefaults_All_f, "sets all cvars to their locked default values");
1073         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)");
1074         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)");
1075
1076         Cmd_AddCommand ("cprint", Cmd_Centerprint_f, "print something at the screen center");
1077         Cmd_AddCommand ("defer", Cmd_Defer_f, "execute a command in the future");
1078
1079         // DRESK - 5/14/06
1080         // Support Doom3-style Toggle Command
1081         Cmd_AddCommand( "toggle", Cmd_Toggle_f, "toggles a console variable's values (use for more info)");
1082 }
1083
1084 /*
1085 ============
1086 Cmd_Shutdown
1087 ============
1088 */
1089 void Cmd_Shutdown(void)
1090 {
1091         Mem_FreePool(&cmd_mempool);
1092 }
1093
1094 /*
1095 ============
1096 Cmd_Argc
1097 ============
1098 */
1099 int             Cmd_Argc (void)
1100 {
1101         return cmd_argc;
1102 }
1103
1104 /*
1105 ============
1106 Cmd_Argv
1107 ============
1108 */
1109 const char *Cmd_Argv (int arg)
1110 {
1111         if (arg >= cmd_argc )
1112                 return cmd_null_string;
1113         return cmd_argv[arg];
1114 }
1115
1116 /*
1117 ============
1118 Cmd_Args
1119 ============
1120 */
1121 const char *Cmd_Args (void)
1122 {
1123         return cmd_args;
1124 }
1125
1126
1127 /*
1128 ============
1129 Cmd_TokenizeString
1130
1131 Parses the given string into command line tokens.
1132 ============
1133 */
1134 // AK: This function should only be called from ExcuteString because the current design is a bit of an hack
1135 static void Cmd_TokenizeString (const char *text)
1136 {
1137         int l;
1138
1139         cmd_argc = 0;
1140         cmd_args = NULL;
1141
1142         while (1)
1143         {
1144                 // skip whitespace up to a /n
1145                 while (*text && *text <= ' ' && *text != '\r' && *text != '\n')
1146                         text++;
1147
1148                 // line endings:
1149                 // UNIX: \n
1150                 // Mac: \r
1151                 // Windows: \r\n
1152                 if (*text == '\n' || *text == '\r')
1153                 {
1154                         // a newline separates commands in the buffer
1155                         if (*text == '\r' && text[1] == '\n')
1156                                 text++;
1157                         text++;
1158                         break;
1159                 }
1160
1161                 if (!*text)
1162                         return;
1163
1164                 if (cmd_argc == 1)
1165                         cmd_args = text;
1166
1167                 if (!COM_ParseToken_Console(&text))
1168                         return;
1169
1170                 if (cmd_argc < MAX_ARGS)
1171                 {
1172                         l = (int)strlen(com_token) + 1;
1173                         if (cmd_tokenizebufferpos + l > CMD_TOKENIZELENGTH)
1174                         {
1175                                 Con_Printf("Cmd_TokenizeString: ran out of %i character buffer space for command arguements\n", CMD_TOKENIZELENGTH);
1176                                 break;
1177                         }
1178                         memcpy (cmd_tokenizebuffer + cmd_tokenizebufferpos, com_token, l);
1179                         cmd_argv[cmd_argc] = cmd_tokenizebuffer + cmd_tokenizebufferpos;
1180                         cmd_tokenizebufferpos += l;
1181                         cmd_argc++;
1182                 }
1183         }
1184 }
1185
1186
1187 /*
1188 ============
1189 Cmd_AddCommand
1190 ============
1191 */
1192 void Cmd_AddCommand_WithClientCommand (const char *cmd_name, xcommand_t consolefunction, xcommand_t clientfunction, const char *description)
1193 {
1194         cmd_function_t *cmd;
1195         cmd_function_t *prev, *current;
1196
1197 // fail if the command is a variable name
1198         if (Cvar_FindVar( cmd_name ))
1199         {
1200                 Con_Printf("Cmd_AddCommand: %s already defined as a var\n", cmd_name);
1201                 return;
1202         }
1203
1204 // fail if the command already exists
1205         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1206         {
1207                 if (!strcmp (cmd_name, cmd->name))
1208                 {
1209                         if (consolefunction || clientfunction)
1210                         {
1211                                 Con_Printf("Cmd_AddCommand: %s already defined\n", cmd_name);
1212                                 return;
1213                         }
1214                         else    //[515]: csqc
1215                         {
1216                                 cmd->csqcfunc = true;
1217                                 return;
1218                         }
1219                 }
1220         }
1221
1222         cmd = (cmd_function_t *)Mem_Alloc(cmd_mempool, sizeof(cmd_function_t));
1223         cmd->name = cmd_name;
1224         cmd->consolefunction = consolefunction;
1225         cmd->clientfunction = clientfunction;
1226         cmd->description = description;
1227         if(!consolefunction && !clientfunction)                 //[515]: csqc
1228                 cmd->csqcfunc = true;
1229         cmd->next = cmd_functions;
1230
1231 // insert it at the right alphanumeric position
1232         for( prev = NULL, current = cmd_functions ; current && strcmp( current->name, cmd->name ) < 0 ; prev = current, current = current->next )
1233                 ;
1234         if( prev ) {
1235                 prev->next = cmd;
1236         } else {
1237                 cmd_functions = cmd;
1238         }
1239         cmd->next = current;
1240 }
1241
1242 void Cmd_AddCommand (const char *cmd_name, xcommand_t function, const char *description)
1243 {
1244         Cmd_AddCommand_WithClientCommand (cmd_name, function, NULL, description);
1245 }
1246
1247 /*
1248 ============
1249 Cmd_Exists
1250 ============
1251 */
1252 qboolean Cmd_Exists (const char *cmd_name)
1253 {
1254         cmd_function_t  *cmd;
1255
1256         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1257                 if (!strcmp (cmd_name,cmd->name))
1258                         return true;
1259
1260         return false;
1261 }
1262
1263
1264 /*
1265 ============
1266 Cmd_CompleteCommand
1267 ============
1268 */
1269 const char *Cmd_CompleteCommand (const char *partial)
1270 {
1271         cmd_function_t *cmd;
1272         size_t len;
1273
1274         len = strlen(partial);
1275
1276         if (!len)
1277                 return NULL;
1278
1279 // check functions
1280         for (cmd = cmd_functions; cmd; cmd = cmd->next)
1281                 if (!strncasecmp(partial, cmd->name, len))
1282                         return cmd->name;
1283
1284         return NULL;
1285 }
1286
1287 /*
1288         Cmd_CompleteCountPossible
1289
1290         New function for tab-completion system
1291         Added by EvilTypeGuy
1292         Thanks to Fett erich@heintz.com
1293         Thanks to taniwha
1294
1295 */
1296 int Cmd_CompleteCountPossible (const char *partial)
1297 {
1298         cmd_function_t *cmd;
1299         size_t len;
1300         int h;
1301
1302         h = 0;
1303         len = strlen(partial);
1304
1305         if (!len)
1306                 return 0;
1307
1308         // Loop through the command list and count all partial matches
1309         for (cmd = cmd_functions; cmd; cmd = cmd->next)
1310                 if (!strncasecmp(partial, cmd->name, len))
1311                         h++;
1312
1313         return h;
1314 }
1315
1316 /*
1317         Cmd_CompleteBuildList
1318
1319         New function for tab-completion system
1320         Added by EvilTypeGuy
1321         Thanks to Fett erich@heintz.com
1322         Thanks to taniwha
1323
1324 */
1325 const char **Cmd_CompleteBuildList (const char *partial)
1326 {
1327         cmd_function_t *cmd;
1328         size_t len = 0;
1329         size_t bpos = 0;
1330         size_t sizeofbuf = (Cmd_CompleteCountPossible (partial) + 1) * sizeof (const char *);
1331         const char **buf;
1332
1333         len = strlen(partial);
1334         buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1335         // Loop through the alias list and print all matches
1336         for (cmd = cmd_functions; cmd; cmd = cmd->next)
1337                 if (!strncasecmp(partial, cmd->name, len))
1338                         buf[bpos++] = cmd->name;
1339
1340         buf[bpos] = NULL;
1341         return buf;
1342 }
1343
1344 // written by LordHavoc
1345 void Cmd_CompleteCommandPrint (const char *partial)
1346 {
1347         cmd_function_t *cmd;
1348         size_t len = strlen(partial);
1349         // Loop through the command list and print all matches
1350         for (cmd = cmd_functions; cmd; cmd = cmd->next)
1351                 if (!strncasecmp(partial, cmd->name, len))
1352                         Con_Printf("%s : %s\n", cmd->name, cmd->description);
1353 }
1354
1355 /*
1356         Cmd_CompleteAlias
1357
1358         New function for tab-completion system
1359         Added by EvilTypeGuy
1360         Thanks to Fett erich@heintz.com
1361         Thanks to taniwha
1362
1363 */
1364 const char *Cmd_CompleteAlias (const char *partial)
1365 {
1366         cmdalias_t *alias;
1367         size_t len;
1368
1369         len = strlen(partial);
1370
1371         if (!len)
1372                 return NULL;
1373
1374         // Check functions
1375         for (alias = cmd_alias; alias; alias = alias->next)
1376                 if (!strncasecmp(partial, alias->name, len))
1377                         return alias->name;
1378
1379         return NULL;
1380 }
1381
1382 // written by LordHavoc
1383 void Cmd_CompleteAliasPrint (const char *partial)
1384 {
1385         cmdalias_t *alias;
1386         size_t len = strlen(partial);
1387         // Loop through the alias list and print all matches
1388         for (alias = cmd_alias; alias; alias = alias->next)
1389                 if (!strncasecmp(partial, alias->name, len))
1390                         Con_Printf("%s : %s\n", alias->name, alias->value);
1391 }
1392
1393
1394 /*
1395         Cmd_CompleteAliasCountPossible
1396
1397         New function for tab-completion system
1398         Added by EvilTypeGuy
1399         Thanks to Fett erich@heintz.com
1400         Thanks to taniwha
1401
1402 */
1403 int Cmd_CompleteAliasCountPossible (const char *partial)
1404 {
1405         cmdalias_t      *alias;
1406         size_t          len;
1407         int                     h;
1408
1409         h = 0;
1410
1411         len = strlen(partial);
1412
1413         if (!len)
1414                 return 0;
1415
1416         // Loop through the command list and count all partial matches
1417         for (alias = cmd_alias; alias; alias = alias->next)
1418                 if (!strncasecmp(partial, alias->name, len))
1419                         h++;
1420
1421         return h;
1422 }
1423
1424 /*
1425         Cmd_CompleteAliasBuildList
1426
1427         New function for tab-completion system
1428         Added by EvilTypeGuy
1429         Thanks to Fett erich@heintz.com
1430         Thanks to taniwha
1431
1432 */
1433 const char **Cmd_CompleteAliasBuildList (const char *partial)
1434 {
1435         cmdalias_t *alias;
1436         size_t len = 0;
1437         size_t bpos = 0;
1438         size_t sizeofbuf = (Cmd_CompleteAliasCountPossible (partial) + 1) * sizeof (const char *);
1439         const char **buf;
1440
1441         len = strlen(partial);
1442         buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1443         // Loop through the alias list and print all matches
1444         for (alias = cmd_alias; alias; alias = alias->next)
1445                 if (!strncasecmp(partial, alias->name, len))
1446                         buf[bpos++] = alias->name;
1447
1448         buf[bpos] = NULL;
1449         return buf;
1450 }
1451
1452 void Cmd_ClearCsqcFuncs (void)
1453 {
1454         cmd_function_t *cmd;
1455         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1456                 cmd->csqcfunc = false;
1457 }
1458
1459 qboolean CL_VM_ConsoleCommand (const char *cmd);
1460 /*
1461 ============
1462 Cmd_ExecuteString
1463
1464 A complete command line has been parsed, so try to execute it
1465 FIXME: lookupnoadd the token to speed search?
1466 ============
1467 */
1468 void Cmd_ExecuteString (const char *text, cmd_source_t src)
1469 {
1470         int oldpos;
1471         int found;
1472         cmd_function_t *cmd;
1473         cmdalias_t *a;
1474
1475         oldpos = cmd_tokenizebufferpos;
1476         cmd_source = src;
1477         found = false;
1478
1479         Cmd_TokenizeString (text);
1480
1481 // execute the command line
1482         if (!Cmd_Argc())
1483         {
1484                 cmd_tokenizebufferpos = oldpos;
1485                 return;         // no tokens
1486         }
1487
1488 // check functions
1489         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1490         {
1491                 if (!strcasecmp (cmd_argv[0],cmd->name))
1492                 {
1493                         if (cmd->csqcfunc && CL_VM_ConsoleCommand (text))       //[515]: csqc
1494                                 return;
1495                         switch (src)
1496                         {
1497                         case src_command:
1498                                 if (cmd->consolefunction)
1499                                         cmd->consolefunction ();
1500                                 else if (cmd->clientfunction)
1501                                 {
1502                                         if (cls.state == ca_connected)
1503                                         {
1504                                                 // forward remote commands to the server for execution
1505                                                 Cmd_ForwardToServer();
1506                                         }
1507                                         else
1508                                                 Con_Printf("Can not send command \"%s\", not connected.\n", Cmd_Argv(0));
1509                                 }
1510                                 else
1511                                         Con_Printf("Command \"%s\" can not be executed\n", Cmd_Argv(0));
1512                                 found = true;
1513                                 goto command_found;
1514                                 break;
1515                         case src_client:
1516                                 if (cmd->clientfunction)
1517                                 {
1518                                         cmd->clientfunction ();
1519                                         cmd_tokenizebufferpos = oldpos;
1520                                         return;
1521                                 }
1522                                 break;
1523                         }
1524                         break;
1525                 }
1526         }
1527 command_found:
1528
1529         // if it's a client command and no command was found, say so.
1530         if (cmd_source == src_client)
1531         {
1532                 Con_Printf("player \"%s\" tried to %s\n", host_client->name, text);
1533                 cmd_tokenizebufferpos = oldpos;
1534                 return;
1535         }
1536
1537 // check alias
1538         for (a=cmd_alias ; a ; a=a->next)
1539         {
1540                 if (!strcasecmp (cmd_argv[0], a->name))
1541                 {
1542                         Cmd_ExecuteAlias(a);
1543                         cmd_tokenizebufferpos = oldpos;
1544                         return;
1545                 }
1546         }
1547
1548         if(found) // if the command was hooked and found, all is good
1549         {
1550                 cmd_tokenizebufferpos = oldpos;
1551                 return;
1552         }
1553
1554 // check cvars
1555         if (!Cvar_Command () && host_framecount > 0)
1556                 Con_Printf("Unknown command \"%s\"\n", Cmd_Argv(0));
1557
1558         cmd_tokenizebufferpos = oldpos;
1559 }
1560
1561
1562 /*
1563 ===================
1564 Cmd_ForwardStringToServer
1565
1566 Sends an entire command string over to the server, unprocessed
1567 ===================
1568 */
1569 void Cmd_ForwardStringToServer (const char *s)
1570 {
1571         char temp[128];
1572         if (cls.state != ca_connected)
1573         {
1574                 Con_Printf("Can't \"%s\", not connected\n", s);
1575                 return;
1576         }
1577
1578         if (!cls.netcon)
1579                 return;
1580
1581         // LordHavoc: thanks to Fuh for bringing the pure evil of SZ_Print to my
1582         // attention, it has been eradicated from here, its only (former) use in
1583         // all of darkplaces.
1584         if (cls.protocol == PROTOCOL_QUAKEWORLD)
1585                 MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
1586         else
1587                 MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
1588         if ((!strncmp(s, "say ", 4) || !strncmp(s, "say_team ", 9)) && cl_locs_enable.integer)
1589         {
1590                 // say/say_team commands can replace % character codes with status info
1591                 while (*s)
1592                 {
1593                         if (*s == '%' && s[1])
1594                         {
1595                                 // handle proquake message macros
1596                                 temp[0] = 0;
1597                                 switch (s[1])
1598                                 {
1599                                 case 'l': // current location
1600                                         CL_Locs_FindLocationName(temp, sizeof(temp), cl.movement_origin);
1601                                         break;
1602                                 case 'h': // current health
1603                                         dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_HEALTH]);
1604                                         break;
1605                                 case 'a': // current armor
1606                                         dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ARMOR]);
1607                                         break;
1608                                 case 'x': // current rockets
1609                                         dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ROCKETS]);
1610                                         break;
1611                                 case 'c': // current cells
1612                                         dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_CELLS]);
1613                                         break;
1614                                 // silly proquake macros
1615                                 case 'd': // loc at last death
1616                                         CL_Locs_FindLocationName(temp, sizeof(temp), cl.lastdeathorigin);
1617                                         break;
1618                                 case 't': // current time
1619                                         dpsnprintf(temp, sizeof(temp), "%.0f:%.0f", floor(cl.time / 60), cl.time - floor(cl.time / 60) * 60);
1620                                         break;
1621                                 case 'r': // rocket launcher status ("I have RL", "I need rockets", "I need RL")
1622                                         if (!(cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER))
1623                                                 dpsnprintf(temp, sizeof(temp), "I need RL");
1624                                         else if (!cl.stats[STAT_ROCKETS])
1625                                                 dpsnprintf(temp, sizeof(temp), "I need rockets");
1626                                         else
1627                                                 dpsnprintf(temp, sizeof(temp), "I have RL");
1628                                         break;
1629                                 case 'p': // powerup status (outputs "quad" "pent" and "eyes" according to status)
1630                                         if (cl.stats[STAT_ITEMS] & IT_QUAD)
1631                                         {
1632                                                 if (temp[0])
1633                                                         strlcat(temp, " ", sizeof(temp));
1634                                                 strlcat(temp, "quad", sizeof(temp));
1635                                         }
1636                                         if (cl.stats[STAT_ITEMS] & IT_INVULNERABILITY)
1637                                         {
1638                                                 if (temp[0])
1639                                                         strlcat(temp, " ", sizeof(temp));
1640                                                 strlcat(temp, "pent", sizeof(temp));
1641                                         }
1642                                         if (cl.stats[STAT_ITEMS] & IT_INVISIBILITY)
1643                                         {
1644                                                 if (temp[0])
1645                                                         strlcat(temp, " ", sizeof(temp));
1646                                                 strlcat(temp, "eyes", sizeof(temp));
1647                                         }
1648                                         break;
1649                                 case 'w': // weapon status (outputs "SSG:NG:SNG:GL:RL:LG" with the text between : characters omitted if you lack the weapon)
1650                                         if (cl.stats[STAT_ITEMS] & IT_SUPER_SHOTGUN)
1651                                                 strlcat(temp, "SSG", sizeof(temp));
1652                                         strlcat(temp, ":", sizeof(temp));
1653                                         if (cl.stats[STAT_ITEMS] & IT_NAILGUN)
1654                                                 strlcat(temp, "NG", sizeof(temp));
1655                                         strlcat(temp, ":", sizeof(temp));
1656                                         if (cl.stats[STAT_ITEMS] & IT_SUPER_NAILGUN)
1657                                                 strlcat(temp, "SNG", sizeof(temp));
1658                                         strlcat(temp, ":", sizeof(temp));
1659                                         if (cl.stats[STAT_ITEMS] & IT_GRENADE_LAUNCHER)
1660                                                 strlcat(temp, "GL", sizeof(temp));
1661                                         strlcat(temp, ":", sizeof(temp));
1662                                         if (cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER)
1663                                                 strlcat(temp, "RL", sizeof(temp));
1664                                         strlcat(temp, ":", sizeof(temp));
1665                                         if (cl.stats[STAT_ITEMS] & IT_LIGHTNING)
1666                                                 strlcat(temp, "LG", sizeof(temp));
1667                                         break;
1668                                 default:
1669                                         // not a recognized macro, print it as-is...
1670                                         temp[0] = s[0];
1671                                         temp[1] = s[1];
1672                                         temp[2] = 0;
1673                                         break;
1674                                 }
1675                                 // write the resulting text
1676                                 SZ_Write(&cls.netcon->message, (unsigned char *)temp, strlen(temp));
1677                                 s += 2;
1678                                 continue;
1679                         }
1680                         MSG_WriteByte(&cls.netcon->message, *s);
1681                         s++;
1682                 }
1683                 MSG_WriteByte(&cls.netcon->message, 0);
1684         }
1685         else // any other command is passed on as-is
1686                 SZ_Write(&cls.netcon->message, (const unsigned char *)s, (int)strlen(s) + 1);
1687 }
1688
1689 /*
1690 ===================
1691 Cmd_ForwardToServer
1692
1693 Sends the entire command line over to the server
1694 ===================
1695 */
1696 void Cmd_ForwardToServer (void)
1697 {
1698         const char *s;
1699         if (!strcasecmp(Cmd_Argv(0), "cmd"))
1700         {
1701                 // we want to strip off "cmd", so just send the args
1702                 s = Cmd_Argc() > 1 ? Cmd_Args() : "";
1703         }
1704         else
1705         {
1706                 // we need to keep the command name, so send Cmd_Argv(0), a space and then Cmd_Args()
1707                 s = va("%s %s", Cmd_Argv(0), Cmd_Argc() > 1 ? Cmd_Args() : "");
1708         }
1709         // don't send an empty forward message if the user tries "cmd" by itself
1710         if (!s || !*s)
1711                 return;
1712         Cmd_ForwardStringToServer(s);
1713 }
1714
1715
1716 /*
1717 ================
1718 Cmd_CheckParm
1719
1720 Returns the position (1 to argc-1) in the command's argument list
1721 where the given parameter apears, or 0 if not present
1722 ================
1723 */
1724
1725 int Cmd_CheckParm (const char *parm)
1726 {
1727         int i;
1728
1729         if (!parm)
1730         {
1731                 Con_Printf ("Cmd_CheckParm: NULL");
1732                 return 0;
1733         }
1734
1735         for (i = 1; i < Cmd_Argc (); i++)
1736                 if (!strcasecmp (parm, Cmd_Argv (i)))
1737                         return i;
1738
1739         return 0;
1740 }
1741