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