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