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