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