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