In the apropos command exclude \n from being filtered by wildcards for alias values...
[xonotic/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         const char *filename;
458
459         if (Cmd_Argc () != 2)
460         {
461                 Con_Print("exec <filename> : execute a script file\n");
462                 return;
463         }
464
465         filename = Cmd_Argv(1);
466         if (!strcmp(filename, "config.cfg"))
467         {
468                 filename = CONFIGFILENAME;
469                 if (COM_CheckParm("-noconfig"))
470                         return; // don't execute config.cfg
471         }
472
473         f = (char *)FS_LoadFile (filename, tempmempool, false, NULL);
474         if (!f)
475         {
476                 Con_Printf("couldn't exec %s\n",filename);
477                 return;
478         }
479         Con_Printf("execing %s\n",filename);
480
481         // if executing default.cfg for the first time, lock the cvar defaults
482         // it may seem backwards to insert this text BEFORE the default.cfg
483         // but Cbuf_InsertText inserts before, so this actually ends up after it.
484         if (strlen(filename) >= 11 && !strcmp(filename + strlen(filename) - 11, "default.cfg"))
485                 Cbuf_InsertText("\ncvar_lockdefaults\n");
486
487         // insert newline after the text to make sure the last line is terminated (some text editors omit the trailing newline)
488         // (note: insertion order here is backwards from execution order, so this adds it after the text, by calling it before...)
489         Cbuf_InsertText ("\n");
490         Cbuf_InsertText (f);
491         Mem_Free(f);
492 }
493
494
495 /*
496 ===============
497 Cmd_Echo_f
498
499 Just prints the rest of the line to the console
500 ===============
501 */
502 static void Cmd_Echo_f (void)
503 {
504         int             i;
505
506         for (i=1 ; i<Cmd_Argc() ; i++)
507                 Con_Printf("%s ",Cmd_Argv(i));
508         Con_Print("\n");
509 }
510
511 // DRESK - 5/14/06
512 // Support Doom3-style Toggle Console Command
513 /*
514 ===============
515 Cmd_Toggle_f
516
517 Toggles a specified console variable amongst the values specified (default is 0 and 1)
518 ===============
519 */
520 static void Cmd_Toggle_f(void)
521 {
522         // Acquire Number of Arguments
523         int nNumArgs = Cmd_Argc();
524
525         if(nNumArgs == 1)
526                 // No Arguments Specified; Print Usage
527                 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");
528         else
529         { // Correct Arguments Specified
530                 // Acquire Potential CVar
531                 cvar_t* cvCVar = Cvar_FindVar( Cmd_Argv(1) );
532
533                 if(cvCVar != NULL)
534                 { // Valid CVar
535                         if(nNumArgs == 2)
536                         { // Default Usage
537                                 if(cvCVar->integer)
538                                         Cvar_SetValueQuick(cvCVar, 0);
539                                 else
540                                         Cvar_SetValueQuick(cvCVar, 1);
541                         }
542                         else
543                         if(nNumArgs == 3)
544                         { // 0 and Specified Usage
545                                 if(cvCVar->integer == atoi(Cmd_Argv(2) ) )
546                                         // CVar is Specified Value; // Reset to 0
547                                         Cvar_SetValueQuick(cvCVar, 0);
548                                 else
549                                 if(cvCVar->integer == 0)
550                                         // CVar is 0; Specify Value
551                                         Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
552                                 else
553                                         // CVar does not match; Reset to 0
554                                         Cvar_SetValueQuick(cvCVar, 0);
555                         }
556                         else
557                         { // Variable Values Specified
558                                 int nCnt;
559                                 int bFound = 0;
560
561                                 for(nCnt = 2; nCnt < nNumArgs; nCnt++)
562                                 { // Cycle through Values
563                                         if( strcmp(cvCVar->string, Cmd_Argv(nCnt) ) == 0)
564                                         { // Current Value Located; Increment to Next
565                                                 if( (nCnt + 1) == nNumArgs)
566                                                         // Max Value Reached; Reset
567                                                         Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
568                                                 else
569                                                         // Next Value
570                                                         Cvar_SetQuick(cvCVar, Cmd_Argv(nCnt + 1) );
571
572                                                 // End Loop
573                                                 nCnt = nNumArgs;
574                                                 // Assign Found
575                                                 bFound = 1;
576                                         }
577                                 }
578                                 if(!bFound)
579                                         // Value not Found; Reset to Original
580                                         Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
581                         }
582
583                 }
584                 else
585                 { // Invalid CVar
586                         Con_Printf("ERROR : CVar '%s' not found\n", Cmd_Argv(1) );
587                 }
588         }
589 }
590
591 /*
592 ===============
593 Cmd_Alias_f
594
595 Creates a new command that executes a command string (possibly ; seperated)
596 ===============
597 */
598 static void Cmd_Alias_f (void)
599 {
600         cmdalias_t      *a;
601         char            cmd[MAX_INPUTLINE];
602         int                     i, c;
603         const char              *s;
604         size_t          alloclen;
605
606         if (Cmd_Argc() == 1)
607         {
608                 Con_Print("Current alias commands:\n");
609                 for (a = cmd_alias ; a ; a=a->next)
610                         Con_Printf("%s : %s", a->name, a->value);
611                 return;
612         }
613
614         s = Cmd_Argv(1);
615         if (strlen(s) >= MAX_ALIAS_NAME)
616         {
617                 Con_Print("Alias name is too long\n");
618                 return;
619         }
620
621         // if the alias already exists, reuse it
622         for (a = cmd_alias ; a ; a=a->next)
623         {
624                 if (!strcmp(s, a->name))
625                 {
626                         Z_Free (a->value);
627                         break;
628                 }
629         }
630
631         if (!a)
632         {
633                 cmdalias_t *prev, *current;
634
635                 a = (cmdalias_t *)Z_Malloc (sizeof(cmdalias_t));
636                 strlcpy (a->name, s, sizeof (a->name));
637                 // insert it at the right alphanumeric position
638                 for( prev = NULL, current = cmd_alias ; current && strcmp( current->name, a->name ) < 0 ; prev = current, current = current->next )
639                         ;
640                 if( prev ) {
641                         prev->next = a;
642                 } else {
643                         cmd_alias = a;
644                 }
645                 a->next = current;
646         }
647
648
649 // copy the rest of the command line
650         cmd[0] = 0;             // start out with a null string
651         c = Cmd_Argc();
652         for (i=2 ; i< c ; i++)
653         {
654                 strlcat (cmd, Cmd_Argv(i), sizeof (cmd));
655                 if (i != c)
656                         strlcat (cmd, " ", sizeof (cmd));
657         }
658         strlcat (cmd, "\n", sizeof (cmd));
659
660         alloclen = strlen (cmd) + 1;
661         if(alloclen >= 2)
662                 cmd[alloclen - 2] = '\n'; // to make sure a newline is appended even if too long
663         a->value = (char *)Z_Malloc (alloclen);
664         memcpy (a->value, cmd, alloclen);
665 }
666
667 /*
668 ===============
669 Cmd_UnAlias_f
670
671 Remove existing aliases.
672 ===============
673 */
674 static void Cmd_UnAlias_f (void)
675 {
676         cmdalias_t      *a, *p;
677         int i;
678         const char *s;
679
680         if(Cmd_Argc() == 1)
681         {
682                 Con_Print("unalias: Usage: unalias alias1 [alias2 ...]\n");
683                 return;
684         }
685
686         for(i = 1; i < Cmd_Argc(); ++i)
687         {
688                 s = Cmd_Argv(i);
689                 p = NULL;
690                 for(a = cmd_alias; a; p = a, a = a->next)
691                 {
692                         if(!strcmp(s, a->name))
693                         {
694                                 if(a == cmd_alias)
695                                         cmd_alias = a->next;
696                                 if(p)
697                                         p->next = a->next;
698                                 Z_Free(a->value);
699                                 Z_Free(a);
700                                 break;
701                         }
702                 }
703                 if(!a)
704                         Con_Printf("unalias: %s alias not found\n", s);
705         }
706 }
707
708 /*
709 =============================================================================
710
711                                         COMMAND EXECUTION
712
713 =============================================================================
714 */
715
716 typedef struct cmd_function_s
717 {
718         struct cmd_function_s *next;
719         const char *name;
720         const char *description;
721         xcommand_t consolefunction;
722         xcommand_t clientfunction;
723         qboolean csqcfunc;
724 } cmd_function_t;
725
726 static int cmd_argc;
727 static const char *cmd_argv[MAX_ARGS];
728 static const char *cmd_null_string = "";
729 static const char *cmd_args;
730 cmd_source_t cmd_source;
731
732
733 static cmd_function_t *cmd_functions;           // possible commands to execute
734
735 static const char *Cmd_GetDirectCvarValue(const char *varname, cmdalias_t *alias, qboolean *is_multiple)
736 {
737         cvar_t *cvar;
738         long argno;
739         char *endptr;
740
741         if(is_multiple)
742                 *is_multiple = false;
743
744         if(!varname || !*varname)
745                 return NULL;
746
747         if(alias)
748         {
749                 if(!strcmp(varname, "*"))
750                 {
751                         if(is_multiple)
752                                 *is_multiple = true;
753                         return Cmd_Args();
754                 }
755                 else if(!strcmp(varname, "#"))
756                 {
757                         return va("%d", Cmd_Argc());
758                 }
759                 else if(varname[strlen(varname) - 1] == '-')
760                 {
761                         argno = strtol(varname, &endptr, 10);
762                         if(endptr == varname + strlen(varname) - 1)
763                         {
764                                 // whole string is a number, apart from the -
765                                 const char *p = Cmd_Args();
766                                 for(; argno > 1; --argno)
767                                         if(!COM_ParseToken_Console(&p))
768                                                 break;
769                                 if(p)
770                                 {
771                                         if(is_multiple)
772                                                 *is_multiple = true;
773
774                                         // kill pre-argument whitespace
775                                         for (;*p && ISWHITESPACE(*p);p++)
776                                                 ;
777
778                                         return p;
779                                 }
780                         }
781                 }
782                 else
783                 {
784                         argno = strtol(varname, &endptr, 10);
785                         if(*endptr == 0)
786                         {
787                                 // whole string is a number
788                                 // NOTE: we already made sure we don't have an empty cvar name!
789                                 if(argno >= 0 && argno < Cmd_Argc())
790                                         return Cmd_Argv(argno);
791                         }
792                 }
793         }
794
795         if((cvar = Cvar_FindVar(varname)) && !(cvar->flags & CVAR_PRIVATE))
796                 return cvar->string;
797
798         return NULL;
799 }
800
801 qboolean Cmd_QuoteString(char *out, size_t outlen, const char *in, const char *quoteset)
802 {
803         qboolean quote_quot = !!strchr(quoteset, '"');
804         qboolean quote_backslash = !!strchr(quoteset, '\\');
805         qboolean quote_dollar = !!strchr(quoteset, '$');
806
807         while(*in)
808         {
809                 if(*in == '"' && quote_quot)
810                 {
811                         if(outlen <= 2)
812                         {
813                                 *out++ = 0;
814                                 return false;
815                         }
816                         *out++ = '\\'; --outlen;
817                         *out++ = '"'; --outlen;
818                 }
819                 else if(*in == '\\' && quote_backslash)
820                 {
821                         if(outlen <= 2)
822                         {
823                                 *out++ = 0;
824                                 return false;
825                         }
826                         *out++ = '\\'; --outlen;
827                         *out++ = '\\'; --outlen;
828                 }
829                 else if(*in == '$' && quote_dollar)
830                 {
831                         if(outlen <= 2)
832                         {
833                                 *out++ = 0;
834                                 return false;
835                         }
836                         *out++ = '$'; --outlen;
837                         *out++ = '$'; --outlen;
838                 }
839                 else
840                 {
841                         if(outlen <= 1)
842                         {
843                                 *out++ = 0;
844                                 return false;
845                         }
846                         *out++ = *in; --outlen;
847                 }
848                 ++in;
849         }
850         *out++ = 0;
851         return true;
852 }
853
854 static const char *Cmd_GetCvarValue(const char *var, size_t varlen, cmdalias_t *alias)
855 {
856         static char varname[MAX_INPUTLINE];
857         static char varval[MAX_INPUTLINE];
858         const char *varstr;
859         char *varfunc;
860
861         if(varlen >= MAX_INPUTLINE)
862                 varlen = MAX_INPUTLINE - 1;
863         memcpy(varname, var, varlen);
864         varname[varlen] = 0;
865         varfunc = strchr(varname, ' ');
866
867         if(varfunc)
868         {
869                 *varfunc = 0;
870                 ++varfunc;
871         }
872
873         if(*var == 0)
874         {
875                 // empty cvar name?
876                 return NULL;
877         }
878
879         varstr = NULL;
880
881         if(varname[0] == '$')
882                 varstr = Cmd_GetDirectCvarValue(Cmd_GetDirectCvarValue(varname + 1, alias, NULL), alias, NULL);
883         else
884         {
885                 qboolean is_multiple = false;
886                 // Exception: $* and $n- don't use the quoted form by default
887                 varstr = Cmd_GetDirectCvarValue(varname, alias, &is_multiple);
888                 if(is_multiple)
889                         if(!varfunc)
890                                 varfunc = "asis";
891         }
892
893         if(!varstr)
894         {
895                 if(alias)
896                         Con_Printf("Warning: Could not expand $%s in alias %s\n", varname, alias->name);
897                 else
898                         Con_Printf("Warning: Could not expand $%s\n", varname);
899                 return NULL;
900         }
901
902         if(!varfunc || !strcmp(varfunc, "q")) // note: quoted form is default, use "asis" to override!
903         {
904                 // quote it so it can be used inside double quotes
905                 // we just need to replace " by \", and of course, double backslashes
906                 Cmd_QuoteString(varval, sizeof(varval), varstr, "\"\\");
907                 return varval;
908         }
909         else if(!strcmp(varfunc, "asis"))
910         {
911                 return varstr;
912         }
913         else
914                 Con_Printf("Unknown variable function %s\n", varfunc);
915
916         return varstr;
917 }
918
919 /*
920 Cmd_PreprocessString
921
922 Preprocesses strings and replaces $*, $param#, $cvar accordingly. Also strips comments.
923 */
924 static void Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias ) {
925         const char *in;
926         size_t eat, varlen;
927         unsigned outlen;
928         const char *val;
929
930         // don't crash if there's no room in the outtext buffer
931         if( maxoutlen == 0 ) {
932                 return;
933         }
934         maxoutlen--; // because of \0
935
936         in = intext;
937         outlen = 0;
938
939         while( *in && outlen < maxoutlen ) {
940                 if( *in == '$' ) {
941                         // this is some kind of expansion, see what comes after the $
942                         in++;
943
944                         // The console does the following preprocessing:
945                         //
946                         // - $$ is transformed to a single dollar sign.
947                         // - $var or ${var} are expanded to the contents of the named cvar,
948                         //   with quotation marks and backslashes quoted so it can safely
949                         //   be used inside quotation marks (and it should always be used
950                         //   that way)
951                         // - ${var asis} inserts the cvar value as is, without doing this
952                         //   quoting
953                         // - prefix the cvar name with a dollar sign to do indirection;
954                         //   for example, if $x has the value timelimit, ${$x} will return
955                         //   the value of $timelimit
956                         // - when expanding an alias, the special variable name $* refers
957                         //   to all alias parameters, and a number refers to that numbered
958                         //   alias parameter, where the name of the alias is $0, the first
959                         //   parameter is $1 and so on; as a special case, $* inserts all
960                         //   parameters, without extra quoting, so one can use $* to just
961                         //   pass all parameters around. All parameters starting from $n
962                         //   can be referred to as $n- (so $* is equivalent to $1-).
963                         //
964                         // Note: when expanding an alias, cvar expansion is done in the SAME step
965                         // as alias expansion so that alias parameters or cvar values containing
966                         // dollar signs have no unwanted bad side effects. However, this needs to
967                         // be accounted for when writing complex aliases. For example,
968                         //   alias foo "set x NEW; echo $x"
969                         // actually expands to
970                         //   "set x NEW; echo OLD"
971                         // and will print OLD! To work around this, use a second alias:
972                         //   alias foo "set x NEW; foo2"
973                         //   alias foo2 "echo $x"
974                         //
975                         // Also note: lines starting with alias are exempt from cvar expansion.
976                         // If you want cvar expansion, write "alias" instead:
977                         //
978                         //   set x 1
979                         //   alias foo "echo $x"
980                         //   "alias" bar "echo $x"
981                         //   set x 2
982                         //
983                         // foo will print 2, because the variable $x will be expanded when the alias
984                         // gets expanded. bar will print 1, because the variable $x was expanded
985                         // at definition time. foo can be equivalently defined as
986                         //
987                         //   "alias" foo "echo $$x"
988                         //
989                         // because at definition time, $$ will get replaced to a single $.
990
991                         if( *in == '$' ) {
992                                 val = "$";
993                                 eat = 1;
994                         } else if(*in == '{') {
995                                 varlen = strcspn(in + 1, "}");
996                                 if(in[varlen + 1] == '}')
997                                 {
998                                         val = Cmd_GetCvarValue(in + 1, varlen, alias);
999                                         eat = varlen + 2;
1000                                 }
1001                                 else
1002                                 {
1003                                         // ran out of data?
1004                                         val = NULL;
1005                                         eat = varlen + 1;
1006                                 }
1007                         } else {
1008                                 varlen = strspn(in, "#*0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-");
1009                                 val = Cmd_GetCvarValue(in, varlen, alias);
1010                                 eat = varlen;
1011                         }
1012                         if(val)
1013                         {
1014                                 // insert the cvar value
1015                                 while(*val && outlen < maxoutlen)
1016                                         outtext[outlen++] = *val++;
1017                                 in += eat;
1018                         }
1019                         else
1020                         {
1021                                 // copy the unexpanded text
1022                                 outtext[outlen++] = '$';
1023                                 while(eat && outlen < maxoutlen)
1024                                 {
1025                                         outtext[outlen++] = *in++;
1026                                         --eat;
1027                                 }
1028                         }
1029                 }
1030                 else 
1031                         outtext[outlen++] = *in++;
1032         }
1033         outtext[outlen] = 0;
1034 }
1035
1036 /*
1037 ============
1038 Cmd_ExecuteAlias
1039
1040 Called for aliases and fills in the alias into the cbuffer
1041 ============
1042 */
1043 static void Cmd_ExecuteAlias (cmdalias_t *alias)
1044 {
1045         static char buffer[ MAX_INPUTLINE ];
1046         static char buffer2[ MAX_INPUTLINE ];
1047         Cmd_PreprocessString( alias->value, buffer, sizeof(buffer) - 2, alias );
1048         // insert at start of command buffer, so that aliases execute in order
1049         // (fixes bug introduced by Black on 20050705)
1050
1051         // Note: Cbuf_PreprocessString will be called on this string AGAIN! So we
1052         // have to make sure that no second variable expansion takes place, otherwise
1053         // alias parameters containing dollar signs can have bad effects.
1054         Cmd_QuoteString(buffer2, sizeof(buffer2), buffer, "$");
1055         Cbuf_InsertText( buffer2 );
1056 }
1057
1058 /*
1059 ========
1060 Cmd_List
1061
1062         CmdList Added by EvilTypeGuy eviltypeguy@qeradiant.com
1063         Thanks to Matthias "Maddes" Buecher, http://www.inside3d.com/qip/
1064
1065 ========
1066 */
1067 static void Cmd_List_f (void)
1068 {
1069         cmd_function_t *cmd;
1070         const char *partial;
1071         size_t len;
1072         int count;
1073         qboolean ispattern;
1074
1075         if (Cmd_Argc() > 1)
1076         {
1077                 partial = Cmd_Argv (1);
1078                 len = strlen(partial);
1079         }
1080         else
1081         {
1082                 partial = NULL;
1083                 len = 0;
1084         }
1085
1086         ispattern = partial && (strchr(partial, '*') || strchr(partial, '?'));
1087
1088         count = 0;
1089         for (cmd = cmd_functions; cmd; cmd = cmd->next)
1090         {
1091                 if (partial && (ispattern ? !matchpattern_with_separator(cmd->name, partial, false, "", false) : strncmp(partial, cmd->name, len)))
1092                         continue;
1093                 Con_Printf("%s : %s\n", cmd->name, cmd->description);
1094                 count++;
1095         }
1096
1097         if (len)
1098         {
1099                 if(ispattern)
1100                         Con_Printf("%i Command%s matching \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1101                 else
1102                         Con_Printf("%i Command%s beginning with \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1103         }
1104         else
1105                 Con_Printf("%i Command%s\n\n", count, (count > 1) ? "s" : "");
1106 }
1107
1108 static void Cmd_Apropos_f(void)
1109 {
1110         cmd_function_t *cmd;
1111         cvar_t *cvar;
1112         cmdalias_t *alias;
1113         const char *partial;
1114         int count;
1115         qboolean ispattern;
1116
1117         if (Cmd_Argc() > 1)
1118                 partial = Cmd_Args();
1119         else
1120         {
1121                 Con_Printf("usage: apropos <string>\n");
1122                 return;
1123         }
1124
1125         ispattern = partial && (strchr(partial, '*') || strchr(partial, '?'));
1126         if(!ispattern)
1127                 partial = va("*%s*", partial);
1128
1129         count = 0;
1130         for (cvar = cvar_vars; cvar; cvar = cvar->next)
1131         {
1132                 if (!matchpattern_with_separator(cvar->name, partial, true, "", false))
1133                 if (!matchpattern_with_separator(cvar->description, partial, true, "", false))
1134                         continue;
1135                 Con_Printf ("cvar ^3%s^7 is \"%s\" [\"%s\"] %s\n", cvar->name, cvar->string, cvar->defstring, cvar->description);
1136                 count++;
1137         }
1138         for (cmd = cmd_functions; cmd; cmd = cmd->next)
1139         {
1140                 if (!matchpattern_with_separator(cmd->name, partial, true, "", false))
1141                 if (!matchpattern_with_separator(cmd->description, partial, true, "", false))
1142                         continue;
1143                 Con_Printf("command ^2%s^7: %s\n", cmd->name, cmd->description);
1144                 count++;
1145         }
1146         for (alias = cmd_alias; alias; alias = alias->next)
1147         {
1148                 // procede here a bit differently as an alias value always got a final \n
1149                 if (!matchpattern_with_separator(alias->name, partial, true, "", false))
1150                 if (!matchpattern_with_separator(alias->value, partial, true, "\n", false)) // when \n is as separator wildcards don't match it
1151                         continue;
1152                 Con_Printf("alias ^5%s^7: %s", alias->name, alias->value); // do not print an extra \n
1153                 count++;
1154         }
1155         Con_Printf("%i result%s\n\n", count, (count > 1) ? "s" : "");
1156 }
1157
1158 /*
1159 ============
1160 Cmd_Init
1161 ============
1162 */
1163 void Cmd_Init (void)
1164 {
1165         cmd_mempool = Mem_AllocPool("commands", 0, NULL);
1166         // space for commands and script files
1167         cmd_text.data = cmd_text_buf;
1168         cmd_text.maxsize = sizeof(cmd_text_buf);
1169         cmd_text.cursize = 0;
1170 }
1171
1172 void Cmd_Init_Commands (void)
1173 {
1174 //
1175 // register our commands
1176 //
1177         Cmd_AddCommand ("stuffcmds",Cmd_StuffCmds_f, "execute commandline parameters (must be present in quake.rc script)");
1178         Cmd_AddCommand ("exec",Cmd_Exec_f, "execute a script file");
1179         Cmd_AddCommand ("echo",Cmd_Echo_f, "print a message to the console (useful in scripts)");
1180         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");
1181         Cmd_AddCommand ("unalias",Cmd_UnAlias_f, "remove an alias");
1182         Cmd_AddCommand ("cmd", Cmd_ForwardToServer, "send a console commandline to the server (used by some mods)");
1183         Cmd_AddCommand ("wait", Cmd_Wait_f, "make script execution wait for next rendered frame");
1184         Cmd_AddCommand ("set", Cvar_Set_f, "create or change the value of a console variable");
1185         Cmd_AddCommand ("seta", Cvar_SetA_f, "create or change the value of a console variable that will be saved to config.cfg");
1186         Cmd_AddCommand ("unset", Cvar_Del_f, "delete a cvar (does not work for static ones like _cl_name, or read-only ones)");
1187 #ifdef FILLALLCVARSWITHRUBBISH
1188         Cmd_AddCommand ("fillallcvarswithrubbish", Cvar_FillAll_f, "fill all cvars with a specified number of characters to provoke buffer overruns");
1189 #endif /* FILLALLCVARSWITHRUBBISH */
1190
1191         // 2000-01-09 CmdList, CvarList commands By Matthias "Maddes" Buecher
1192         // Added/Modified by EvilTypeGuy eviltypeguy@qeradiant.com
1193         Cmd_AddCommand ("cmdlist", Cmd_List_f, "lists all console commands beginning with the specified prefix or matching the specified wildcard pattern");
1194         Cmd_AddCommand ("cvarlist", Cvar_List_f, "lists all console variables beginning with the specified prefix or matching the specified wildcard pattern");
1195         Cmd_AddCommand ("apropos", Cmd_Apropos_f, "lists all console variables/commands/aliases containing the specified string in the name or description");
1196
1197         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");
1198         Cmd_AddCommand ("cvar_resettodefaults_all", Cvar_ResetToDefaults_All_f, "sets all cvars to their locked default values");
1199         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)");
1200         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)");
1201
1202         Cmd_AddCommand ("cprint", Cmd_Centerprint_f, "print something at the screen center");
1203         Cmd_AddCommand ("defer", Cmd_Defer_f, "execute a command in the future");
1204
1205         // DRESK - 5/14/06
1206         // Support Doom3-style Toggle Command
1207         Cmd_AddCommand( "toggle", Cmd_Toggle_f, "toggles a console variable's values (use for more info)");
1208 }
1209
1210 /*
1211 ============
1212 Cmd_Shutdown
1213 ============
1214 */
1215 void Cmd_Shutdown(void)
1216 {
1217         Mem_FreePool(&cmd_mempool);
1218 }
1219
1220 /*
1221 ============
1222 Cmd_Argc
1223 ============
1224 */
1225 int             Cmd_Argc (void)
1226 {
1227         return cmd_argc;
1228 }
1229
1230 /*
1231 ============
1232 Cmd_Argv
1233 ============
1234 */
1235 const char *Cmd_Argv (int arg)
1236 {
1237         if (arg >= cmd_argc )
1238                 return cmd_null_string;
1239         return cmd_argv[arg];
1240 }
1241
1242 /*
1243 ============
1244 Cmd_Args
1245 ============
1246 */
1247 const char *Cmd_Args (void)
1248 {
1249         return cmd_args;
1250 }
1251
1252
1253 /*
1254 ============
1255 Cmd_TokenizeString
1256
1257 Parses the given string into command line tokens.
1258 ============
1259 */
1260 // AK: This function should only be called from ExcuteString because the current design is a bit of an hack
1261 static void Cmd_TokenizeString (const char *text)
1262 {
1263         int l;
1264
1265         cmd_argc = 0;
1266         cmd_args = NULL;
1267
1268         while (1)
1269         {
1270                 // skip whitespace up to a /n
1271                 while (*text && ISWHITESPACE(*text) && *text != '\r' && *text != '\n')
1272                         text++;
1273
1274                 // line endings:
1275                 // UNIX: \n
1276                 // Mac: \r
1277                 // Windows: \r\n
1278                 if (*text == '\n' || *text == '\r')
1279                 {
1280                         // a newline separates commands in the buffer
1281                         if (*text == '\r' && text[1] == '\n')
1282                                 text++;
1283                         text++;
1284                         break;
1285                 }
1286
1287                 if (!*text)
1288                         return;
1289
1290                 if (cmd_argc == 1)
1291                         cmd_args = text;
1292
1293                 if (!COM_ParseToken_Console(&text))
1294                         return;
1295
1296                 if (cmd_argc < MAX_ARGS)
1297                 {
1298                         l = (int)strlen(com_token) + 1;
1299                         if (cmd_tokenizebufferpos + l > CMD_TOKENIZELENGTH)
1300                         {
1301                                 Con_Printf("Cmd_TokenizeString: ran out of %i character buffer space for command arguements\n", CMD_TOKENIZELENGTH);
1302                                 break;
1303                         }
1304                         memcpy (cmd_tokenizebuffer + cmd_tokenizebufferpos, com_token, l);
1305                         cmd_argv[cmd_argc] = cmd_tokenizebuffer + cmd_tokenizebufferpos;
1306                         cmd_tokenizebufferpos += l;
1307                         cmd_argc++;
1308                 }
1309         }
1310 }
1311
1312
1313 /*
1314 ============
1315 Cmd_AddCommand
1316 ============
1317 */
1318 void Cmd_AddCommand_WithClientCommand (const char *cmd_name, xcommand_t consolefunction, xcommand_t clientfunction, const char *description)
1319 {
1320         cmd_function_t *cmd;
1321         cmd_function_t *prev, *current;
1322
1323 // fail if the command is a variable name
1324         if (Cvar_FindVar( cmd_name ))
1325         {
1326                 Con_Printf("Cmd_AddCommand: %s already defined as a var\n", cmd_name);
1327                 return;
1328         }
1329
1330 // fail if the command already exists
1331         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1332         {
1333                 if (!strcmp (cmd_name, cmd->name))
1334                 {
1335                         if (consolefunction || clientfunction)
1336                         {
1337                                 Con_Printf("Cmd_AddCommand: %s already defined\n", cmd_name);
1338                                 return;
1339                         }
1340                         else    //[515]: csqc
1341                         {
1342                                 cmd->csqcfunc = true;
1343                                 return;
1344                         }
1345                 }
1346         }
1347
1348         cmd = (cmd_function_t *)Mem_Alloc(cmd_mempool, sizeof(cmd_function_t));
1349         cmd->name = cmd_name;
1350         cmd->consolefunction = consolefunction;
1351         cmd->clientfunction = clientfunction;
1352         cmd->description = description;
1353         if(!consolefunction && !clientfunction)                 //[515]: csqc
1354                 cmd->csqcfunc = true;
1355         cmd->next = cmd_functions;
1356
1357 // insert it at the right alphanumeric position
1358         for( prev = NULL, current = cmd_functions ; current && strcmp( current->name, cmd->name ) < 0 ; prev = current, current = current->next )
1359                 ;
1360         if( prev ) {
1361                 prev->next = cmd;
1362         } else {
1363                 cmd_functions = cmd;
1364         }
1365         cmd->next = current;
1366 }
1367
1368 void Cmd_AddCommand (const char *cmd_name, xcommand_t function, const char *description)
1369 {
1370         Cmd_AddCommand_WithClientCommand (cmd_name, function, NULL, description);
1371 }
1372
1373 /*
1374 ============
1375 Cmd_Exists
1376 ============
1377 */
1378 qboolean Cmd_Exists (const char *cmd_name)
1379 {
1380         cmd_function_t  *cmd;
1381
1382         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1383                 if (!strcmp (cmd_name,cmd->name))
1384                         return true;
1385
1386         return false;
1387 }
1388
1389
1390 /*
1391 ============
1392 Cmd_CompleteCommand
1393 ============
1394 */
1395 const char *Cmd_CompleteCommand (const char *partial)
1396 {
1397         cmd_function_t *cmd;
1398         size_t len;
1399
1400         len = strlen(partial);
1401
1402         if (!len)
1403                 return NULL;
1404
1405 // check functions
1406         for (cmd = cmd_functions; cmd; cmd = cmd->next)
1407                 if (!strncasecmp(partial, cmd->name, len))
1408                         return cmd->name;
1409
1410         return NULL;
1411 }
1412
1413 /*
1414         Cmd_CompleteCountPossible
1415
1416         New function for tab-completion system
1417         Added by EvilTypeGuy
1418         Thanks to Fett erich@heintz.com
1419         Thanks to taniwha
1420
1421 */
1422 int Cmd_CompleteCountPossible (const char *partial)
1423 {
1424         cmd_function_t *cmd;
1425         size_t len;
1426         int h;
1427
1428         h = 0;
1429         len = strlen(partial);
1430
1431         if (!len)
1432                 return 0;
1433
1434         // Loop through the command list and count all partial matches
1435         for (cmd = cmd_functions; cmd; cmd = cmd->next)
1436                 if (!strncasecmp(partial, cmd->name, len))
1437                         h++;
1438
1439         return h;
1440 }
1441
1442 /*
1443         Cmd_CompleteBuildList
1444
1445         New function for tab-completion system
1446         Added by EvilTypeGuy
1447         Thanks to Fett erich@heintz.com
1448         Thanks to taniwha
1449
1450 */
1451 const char **Cmd_CompleteBuildList (const char *partial)
1452 {
1453         cmd_function_t *cmd;
1454         size_t len = 0;
1455         size_t bpos = 0;
1456         size_t sizeofbuf = (Cmd_CompleteCountPossible (partial) + 1) * sizeof (const char *);
1457         const char **buf;
1458
1459         len = strlen(partial);
1460         buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1461         // Loop through the alias list and print all matches
1462         for (cmd = cmd_functions; cmd; cmd = cmd->next)
1463                 if (!strncasecmp(partial, cmd->name, len))
1464                         buf[bpos++] = cmd->name;
1465
1466         buf[bpos] = NULL;
1467         return buf;
1468 }
1469
1470 // written by LordHavoc
1471 void Cmd_CompleteCommandPrint (const char *partial)
1472 {
1473         cmd_function_t *cmd;
1474         size_t len = strlen(partial);
1475         // Loop through the command list and print all matches
1476         for (cmd = cmd_functions; cmd; cmd = cmd->next)
1477                 if (!strncasecmp(partial, cmd->name, len))
1478                         Con_Printf("^2%s^7: %s\n", cmd->name, cmd->description);
1479 }
1480
1481 /*
1482         Cmd_CompleteAlias
1483
1484         New function for tab-completion system
1485         Added by EvilTypeGuy
1486         Thanks to Fett erich@heintz.com
1487         Thanks to taniwha
1488
1489 */
1490 const char *Cmd_CompleteAlias (const char *partial)
1491 {
1492         cmdalias_t *alias;
1493         size_t len;
1494
1495         len = strlen(partial);
1496
1497         if (!len)
1498                 return NULL;
1499
1500         // Check functions
1501         for (alias = cmd_alias; alias; alias = alias->next)
1502                 if (!strncasecmp(partial, alias->name, len))
1503                         return alias->name;
1504
1505         return NULL;
1506 }
1507
1508 // written by LordHavoc
1509 void Cmd_CompleteAliasPrint (const char *partial)
1510 {
1511         cmdalias_t *alias;
1512         size_t len = strlen(partial);
1513         // Loop through the alias list and print all matches
1514         for (alias = cmd_alias; alias; alias = alias->next)
1515                 if (!strncasecmp(partial, alias->name, len))
1516                         Con_Printf("^5%s^7: %s", alias->name, alias->value);
1517 }
1518
1519
1520 /*
1521         Cmd_CompleteAliasCountPossible
1522
1523         New function for tab-completion system
1524         Added by EvilTypeGuy
1525         Thanks to Fett erich@heintz.com
1526         Thanks to taniwha
1527
1528 */
1529 int Cmd_CompleteAliasCountPossible (const char *partial)
1530 {
1531         cmdalias_t      *alias;
1532         size_t          len;
1533         int                     h;
1534
1535         h = 0;
1536
1537         len = strlen(partial);
1538
1539         if (!len)
1540                 return 0;
1541
1542         // Loop through the command list and count all partial matches
1543         for (alias = cmd_alias; alias; alias = alias->next)
1544                 if (!strncasecmp(partial, alias->name, len))
1545                         h++;
1546
1547         return h;
1548 }
1549
1550 /*
1551         Cmd_CompleteAliasBuildList
1552
1553         New function for tab-completion system
1554         Added by EvilTypeGuy
1555         Thanks to Fett erich@heintz.com
1556         Thanks to taniwha
1557
1558 */
1559 const char **Cmd_CompleteAliasBuildList (const char *partial)
1560 {
1561         cmdalias_t *alias;
1562         size_t len = 0;
1563         size_t bpos = 0;
1564         size_t sizeofbuf = (Cmd_CompleteAliasCountPossible (partial) + 1) * sizeof (const char *);
1565         const char **buf;
1566
1567         len = strlen(partial);
1568         buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1569         // Loop through the alias list and print all matches
1570         for (alias = cmd_alias; alias; alias = alias->next)
1571                 if (!strncasecmp(partial, alias->name, len))
1572                         buf[bpos++] = alias->name;
1573
1574         buf[bpos] = NULL;
1575         return buf;
1576 }
1577
1578 void Cmd_ClearCsqcFuncs (void)
1579 {
1580         cmd_function_t *cmd;
1581         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1582                 cmd->csqcfunc = false;
1583 }
1584
1585 qboolean CL_VM_ConsoleCommand (const char *cmd);
1586 /*
1587 ============
1588 Cmd_ExecuteString
1589
1590 A complete command line has been parsed, so try to execute it
1591 FIXME: lookupnoadd the token to speed search?
1592 ============
1593 */
1594 void Cmd_ExecuteString (const char *text, cmd_source_t src)
1595 {
1596         int oldpos;
1597         int found;
1598         cmd_function_t *cmd;
1599         cmdalias_t *a;
1600
1601         oldpos = cmd_tokenizebufferpos;
1602         cmd_source = src;
1603         found = false;
1604
1605         Cmd_TokenizeString (text);
1606
1607 // execute the command line
1608         if (!Cmd_Argc())
1609         {
1610                 cmd_tokenizebufferpos = oldpos;
1611                 return;         // no tokens
1612         }
1613
1614 // check functions
1615         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1616         {
1617                 if (!strcasecmp (cmd_argv[0],cmd->name))
1618                 {
1619                         if (cmd->csqcfunc && CL_VM_ConsoleCommand (text))       //[515]: csqc
1620                                 return;
1621                         switch (src)
1622                         {
1623                         case src_command:
1624                                 if (cmd->consolefunction)
1625                                         cmd->consolefunction ();
1626                                 else if (cmd->clientfunction)
1627                                 {
1628                                         if (cls.state == ca_connected)
1629                                         {
1630                                                 // forward remote commands to the server for execution
1631                                                 Cmd_ForwardToServer();
1632                                         }
1633                                         else
1634                                                 Con_Printf("Can not send command \"%s\", not connected.\n", Cmd_Argv(0));
1635                                 }
1636                                 else
1637                                         Con_Printf("Command \"%s\" can not be executed\n", Cmd_Argv(0));
1638                                 found = true;
1639                                 goto command_found;
1640                         case src_client:
1641                                 if (cmd->clientfunction)
1642                                 {
1643                                         cmd->clientfunction ();
1644                                         cmd_tokenizebufferpos = oldpos;
1645                                         return;
1646                                 }
1647                                 break;
1648                         }
1649                         break;
1650                 }
1651         }
1652 command_found:
1653
1654         // if it's a client command and no command was found, say so.
1655         if (cmd_source == src_client)
1656         {
1657                 Con_Printf("player \"%s\" tried to %s\n", host_client->name, text);
1658                 cmd_tokenizebufferpos = oldpos;
1659                 return;
1660         }
1661
1662 // check alias
1663         for (a=cmd_alias ; a ; a=a->next)
1664         {
1665                 if (!strcasecmp (cmd_argv[0], a->name))
1666                 {
1667                         Cmd_ExecuteAlias(a);
1668                         cmd_tokenizebufferpos = oldpos;
1669                         return;
1670                 }
1671         }
1672
1673         if(found) // if the command was hooked and found, all is good
1674         {
1675                 cmd_tokenizebufferpos = oldpos;
1676                 return;
1677         }
1678
1679 // check cvars
1680         if (!Cvar_Command () && host_framecount > 0)
1681                 Con_Printf("Unknown command \"%s\"\n", Cmd_Argv(0));
1682
1683         cmd_tokenizebufferpos = oldpos;
1684 }
1685
1686
1687 /*
1688 ===================
1689 Cmd_ForwardStringToServer
1690
1691 Sends an entire command string over to the server, unprocessed
1692 ===================
1693 */
1694 void Cmd_ForwardStringToServer (const char *s)
1695 {
1696         char temp[128];
1697         if (cls.state != ca_connected)
1698         {
1699                 Con_Printf("Can't \"%s\", not connected\n", s);
1700                 return;
1701         }
1702
1703         if (!cls.netcon)
1704                 return;
1705
1706         // LordHavoc: thanks to Fuh for bringing the pure evil of SZ_Print to my
1707         // attention, it has been eradicated from here, its only (former) use in
1708         // all of darkplaces.
1709         if (cls.protocol == PROTOCOL_QUAKEWORLD)
1710                 MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
1711         else
1712                 MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
1713         if ((!strncmp(s, "say ", 4) || !strncmp(s, "say_team ", 9)) && cl_locs_enable.integer)
1714         {
1715                 // say/say_team commands can replace % character codes with status info
1716                 while (*s)
1717                 {
1718                         if (*s == '%' && s[1])
1719                         {
1720                                 // handle proquake message macros
1721                                 temp[0] = 0;
1722                                 switch (s[1])
1723                                 {
1724                                 case 'l': // current location
1725                                         CL_Locs_FindLocationName(temp, sizeof(temp), cl.movement_origin);
1726                                         break;
1727                                 case 'h': // current health
1728                                         dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_HEALTH]);
1729                                         break;
1730                                 case 'a': // current armor
1731                                         dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ARMOR]);
1732                                         break;
1733                                 case 'x': // current rockets
1734                                         dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ROCKETS]);
1735                                         break;
1736                                 case 'c': // current cells
1737                                         dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_CELLS]);
1738                                         break;
1739                                 // silly proquake macros
1740                                 case 'd': // loc at last death
1741                                         CL_Locs_FindLocationName(temp, sizeof(temp), cl.lastdeathorigin);
1742                                         break;
1743                                 case 't': // current time
1744                                         dpsnprintf(temp, sizeof(temp), "%.0f:%.0f", floor(cl.time / 60), cl.time - floor(cl.time / 60) * 60);
1745                                         break;
1746                                 case 'r': // rocket launcher status ("I have RL", "I need rockets", "I need RL")
1747                                         if (!(cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER))
1748                                                 dpsnprintf(temp, sizeof(temp), "I need RL");
1749                                         else if (!cl.stats[STAT_ROCKETS])
1750                                                 dpsnprintf(temp, sizeof(temp), "I need rockets");
1751                                         else
1752                                                 dpsnprintf(temp, sizeof(temp), "I have RL");
1753                                         break;
1754                                 case 'p': // powerup status (outputs "quad" "pent" and "eyes" according to status)
1755                                         if (cl.stats[STAT_ITEMS] & IT_QUAD)
1756                                         {
1757                                                 if (temp[0])
1758                                                         strlcat(temp, " ", sizeof(temp));
1759                                                 strlcat(temp, "quad", sizeof(temp));
1760                                         }
1761                                         if (cl.stats[STAT_ITEMS] & IT_INVULNERABILITY)
1762                                         {
1763                                                 if (temp[0])
1764                                                         strlcat(temp, " ", sizeof(temp));
1765                                                 strlcat(temp, "pent", sizeof(temp));
1766                                         }
1767                                         if (cl.stats[STAT_ITEMS] & IT_INVISIBILITY)
1768                                         {
1769                                                 if (temp[0])
1770                                                         strlcat(temp, " ", sizeof(temp));
1771                                                 strlcat(temp, "eyes", sizeof(temp));
1772                                         }
1773                                         break;
1774                                 case 'w': // weapon status (outputs "SSG:NG:SNG:GL:RL:LG" with the text between : characters omitted if you lack the weapon)
1775                                         if (cl.stats[STAT_ITEMS] & IT_SUPER_SHOTGUN)
1776                                                 strlcat(temp, "SSG", sizeof(temp));
1777                                         strlcat(temp, ":", sizeof(temp));
1778                                         if (cl.stats[STAT_ITEMS] & IT_NAILGUN)
1779                                                 strlcat(temp, "NG", sizeof(temp));
1780                                         strlcat(temp, ":", sizeof(temp));
1781                                         if (cl.stats[STAT_ITEMS] & IT_SUPER_NAILGUN)
1782                                                 strlcat(temp, "SNG", sizeof(temp));
1783                                         strlcat(temp, ":", sizeof(temp));
1784                                         if (cl.stats[STAT_ITEMS] & IT_GRENADE_LAUNCHER)
1785                                                 strlcat(temp, "GL", sizeof(temp));
1786                                         strlcat(temp, ":", sizeof(temp));
1787                                         if (cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER)
1788                                                 strlcat(temp, "RL", sizeof(temp));
1789                                         strlcat(temp, ":", sizeof(temp));
1790                                         if (cl.stats[STAT_ITEMS] & IT_LIGHTNING)
1791                                                 strlcat(temp, "LG", sizeof(temp));
1792                                         break;
1793                                 default:
1794                                         // not a recognized macro, print it as-is...
1795                                         temp[0] = s[0];
1796                                         temp[1] = s[1];
1797                                         temp[2] = 0;
1798                                         break;
1799                                 }
1800                                 // write the resulting text
1801                                 SZ_Write(&cls.netcon->message, (unsigned char *)temp, strlen(temp));
1802                                 s += 2;
1803                                 continue;
1804                         }
1805                         MSG_WriteByte(&cls.netcon->message, *s);
1806                         s++;
1807                 }
1808                 MSG_WriteByte(&cls.netcon->message, 0);
1809         }
1810         else // any other command is passed on as-is
1811                 SZ_Write(&cls.netcon->message, (const unsigned char *)s, (int)strlen(s) + 1);
1812 }
1813
1814 /*
1815 ===================
1816 Cmd_ForwardToServer
1817
1818 Sends the entire command line over to the server
1819 ===================
1820 */
1821 void Cmd_ForwardToServer (void)
1822 {
1823         const char *s;
1824         if (!strcasecmp(Cmd_Argv(0), "cmd"))
1825         {
1826                 // we want to strip off "cmd", so just send the args
1827                 s = Cmd_Argc() > 1 ? Cmd_Args() : "";
1828         }
1829         else
1830         {
1831                 // we need to keep the command name, so send Cmd_Argv(0), a space and then Cmd_Args()
1832                 s = va("%s %s", Cmd_Argv(0), Cmd_Argc() > 1 ? Cmd_Args() : "");
1833         }
1834         // don't send an empty forward message if the user tries "cmd" by itself
1835         if (!s || !*s)
1836                 return;
1837         Cmd_ForwardStringToServer(s);
1838 }
1839
1840
1841 /*
1842 ================
1843 Cmd_CheckParm
1844
1845 Returns the position (1 to argc-1) in the command's argument list
1846 where the given parameter apears, or 0 if not present
1847 ================
1848 */
1849
1850 int Cmd_CheckParm (const char *parm)
1851 {
1852         int i;
1853
1854         if (!parm)
1855         {
1856                 Con_Printf ("Cmd_CheckParm: NULL");
1857                 return 0;
1858         }
1859
1860         for (i = 1; i < Cmd_Argc (); i++)
1861                 if (!strcasecmp (parm, Cmd_Argv (i)))
1862                         return i;
1863
1864         return 0;
1865 }
1866