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