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