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