]> icculus.org git repositories - divverent/darkplaces.git/blob - cmd.c
Merge branch 'ft2' into ft2uim
[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(varname[strlen(varname) - 1] == '-')
1286                 {
1287                         argno = strtol(varname, &endptr, 10);
1288                         if(endptr == varname + strlen(varname) - 1)
1289                         {
1290                                 // whole string is a number, apart from the -
1291                                 const char *p = Cmd_Args();
1292                                 for(; argno > 1; --argno)
1293                                         if(!COM_ParseToken_Console(&p))
1294                                                 break;
1295                                 if(p)
1296                                 {
1297                                         if(is_multiple)
1298                                                 *is_multiple = true;
1299
1300                                         // kill pre-argument whitespace
1301                                         for (;*p && ISWHITESPACE(*p);p++)
1302                                                 ;
1303
1304                                         return p;
1305                                 }
1306                         }
1307                 }
1308                 else
1309                 {
1310                         argno = strtol(varname, &endptr, 10);
1311                         if(*endptr == 0)
1312                         {
1313                                 // whole string is a number
1314                                 // NOTE: we already made sure we don't have an empty cvar name!
1315                                 if(argno >= 0 && argno < Cmd_Argc())
1316                                         return Cmd_Argv(argno);
1317                         }
1318                 }
1319         }
1320
1321         if((cvar = Cvar_FindVar(varname)) && !(cvar->flags & CVAR_PRIVATE))
1322                 return cvar->string;
1323
1324         return NULL;
1325 }
1326
1327 qboolean Cmd_QuoteString(char *out, size_t outlen, const char *in, const char *quoteset)
1328 {
1329         qboolean quote_quot = !!strchr(quoteset, '"');
1330         qboolean quote_backslash = !!strchr(quoteset, '\\');
1331         qboolean quote_dollar = !!strchr(quoteset, '$');
1332
1333         while(*in)
1334         {
1335                 if(*in == '"' && quote_quot)
1336                 {
1337                         if(outlen <= 2)
1338                         {
1339                                 *out++ = 0;
1340                                 return false;
1341                         }
1342                         *out++ = '\\'; --outlen;
1343                         *out++ = '"'; --outlen;
1344                 }
1345                 else if(*in == '\\' && quote_backslash)
1346                 {
1347                         if(outlen <= 2)
1348                         {
1349                                 *out++ = 0;
1350                                 return false;
1351                         }
1352                         *out++ = '\\'; --outlen;
1353                         *out++ = '\\'; --outlen;
1354                 }
1355                 else if(*in == '$' && quote_dollar)
1356                 {
1357                         if(outlen <= 2)
1358                         {
1359                                 *out++ = 0;
1360                                 return false;
1361                         }
1362                         *out++ = '$'; --outlen;
1363                         *out++ = '$'; --outlen;
1364                 }
1365                 else
1366                 {
1367                         if(outlen <= 1)
1368                         {
1369                                 *out++ = 0;
1370                                 return false;
1371                         }
1372                         *out++ = *in; --outlen;
1373                 }
1374                 ++in;
1375         }
1376         *out++ = 0;
1377         return true;
1378 }
1379
1380 static const char *Cmd_GetCvarValue(const char *var, size_t varlen, cmdalias_t *alias)
1381 {
1382         static char varname[MAX_INPUTLINE];
1383         static char varval[MAX_INPUTLINE];
1384         const char *varstr;
1385         char *varfunc;
1386
1387         if(varlen >= MAX_INPUTLINE)
1388                 varlen = MAX_INPUTLINE - 1;
1389         memcpy(varname, var, varlen);
1390         varname[varlen] = 0;
1391         varfunc = strchr(varname, ' ');
1392
1393         if(varfunc)
1394         {
1395                 *varfunc = 0;
1396                 ++varfunc;
1397                 if (!memcmp(varfunc, "local", 5) && (varfunc[5] == ' ' || !varfunc[5]))
1398                 {
1399                         static char tmp[MAX_INPUTLINE];
1400                         int len;
1401                         len = dpsnprintf(tmp, sizeof(tmp), "_cin_%lu_", (unsigned long)cmd_tid);
1402                         memcpy(tmp + len, varname, varfunc - varname - 1);
1403                         strlcpy(tmp + len + (varfunc - varname - 1), varfunc + 5, sizeof(tmp) - len - (varfunc - varname - 1));
1404                         memcpy(varname, tmp, sizeof(varname));
1405                         varfunc = strchr(varname, ' ');
1406                         if(varfunc)
1407                         {
1408                                 *varfunc = 0;
1409                                 ++varfunc;
1410                         }
1411                 }
1412         }
1413
1414         if(*var == 0)
1415         {
1416                 // empty cvar name?
1417                 return NULL;
1418         }
1419
1420         varstr = NULL;
1421
1422         if(varname[0] == '$')
1423                 varstr = Cmd_GetDirectCvarValue(Cmd_GetDirectCvarValue(varname + 1, alias, NULL), alias, NULL);
1424         else
1425         {
1426                 qboolean is_multiple = false;
1427                 // Exception: $* and $n- don't use the quoted form by default
1428                 varstr = Cmd_GetDirectCvarValue(varname, alias, &is_multiple);
1429                 if(is_multiple)
1430                         if(!varfunc)
1431                                 varfunc = "asis";
1432         }
1433
1434         if(!varstr)
1435         {
1436                 if(alias)
1437                         Con_Printf("Warning: Could not expand $%s in alias %s\n", varname, alias->name);
1438                 else
1439                         Con_Printf("Warning: Could not expand $%s\n", varname);
1440                 return NULL;
1441         }
1442
1443         if(!varfunc || !strcmp(varfunc, "q")) // note: quoted form is default, use "asis" to override!
1444         {
1445                 // quote it so it can be used inside double quotes
1446                 // we just need to replace " by \", and of course, double backslashes
1447                 Cmd_QuoteString(varval, sizeof(varval), varstr, "\"\\");
1448                 return varval;
1449         }
1450         else if(!strcmp(varfunc, "asis"))
1451         {
1452                 return varstr;
1453         }
1454         else
1455                 Con_Printf("Unknown variable function %s\n", varfunc);
1456
1457         return varstr;
1458 }
1459
1460 /*
1461 Cmd_PreprocessString
1462
1463 Preprocesses strings and replaces $*, $param#, $cvar accordingly. Also strips comments.
1464 */
1465 static void Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias ) {
1466         const char *in;
1467         size_t eat, varlen;
1468         unsigned outlen;
1469         const char *val;
1470
1471         // don't crash if there's no room in the outtext buffer
1472         if( maxoutlen == 0 ) {
1473                 return;
1474         }
1475         maxoutlen--; // because of \0
1476
1477         in = intext;
1478         outlen = 0;
1479
1480         while( *in && outlen < maxoutlen ) {
1481                 if( *in == '$' ) {
1482                         // this is some kind of expansion, see what comes after the $
1483                         in++;
1484
1485                         // The console does the following preprocessing:
1486                         //
1487                         // - $$ is transformed to a single dollar sign.
1488                         // - $var or ${var} are expanded to the contents of the named cvar,
1489                         //   with quotation marks and backslashes quoted so it can safely
1490                         //   be used inside quotation marks (and it should always be used
1491                         //   that way)
1492                         // - ${var asis} inserts the cvar value as is, without doing this
1493                         //   quoting
1494                         // - prefix the cvar name with a dollar sign to do indirection;
1495                         //   for example, if $x has the value timelimit, ${$x} will return
1496                         //   the value of $timelimit
1497                         // - when expanding an alias, the special variable name $* refers
1498                         //   to all alias parameters, and a number refers to that numbered
1499                         //   alias parameter, where the name of the alias is $0, the first
1500                         //   parameter is $1 and so on; as a special case, $* inserts all
1501                         //   parameters, without extra quoting, so one can use $* to just
1502                         //   pass all parameters around. All parameters starting from $n
1503                         //   can be referred to as $n- (so $* is equivalent to $1-).
1504                         //
1505                         // Note: when expanding an alias, cvar expansion is done in the SAME step
1506                         // as alias expansion so that alias parameters or cvar values containing
1507                         // dollar signs have no unwanted bad side effects. However, this needs to
1508                         // be accounted for when writing complex aliases. For example,
1509                         //   alias foo "set x NEW; echo $x"
1510                         // actually expands to
1511                         //   "set x NEW; echo OLD"
1512                         // and will print OLD! To work around this, use a second alias:
1513                         //   alias foo "set x NEW; foo2"
1514                         //   alias foo2 "echo $x"
1515                         //
1516                         // Also note: lines starting with alias are exempt from cvar expansion.
1517                         // If you want cvar expansion, write "alias" instead:
1518                         //
1519                         //   set x 1
1520                         //   alias foo "echo $x"
1521                         //   "alias" bar "echo $x"
1522                         //   set x 2
1523                         //
1524                         // foo will print 2, because the variable $x will be expanded when the alias
1525                         // gets expanded. bar will print 1, because the variable $x was expanded
1526                         // at definition time. foo can be equivalently defined as
1527                         //
1528                         //   "alias" foo "echo $$x"
1529                         //
1530                         // because at definition time, $$ will get replaced to a single $.
1531
1532                         if( *in == '$' ) {
1533                                 val = "$";
1534                                 eat = 1;
1535                         } else if(*in == '{') {
1536                                 varlen = strcspn(in + 1, "}");
1537                                 if(in[varlen + 1] == '}')
1538                                 {
1539                                         val = Cmd_GetCvarValue(in + 1, varlen, alias);
1540                                         eat = varlen + 2;
1541                                 }
1542                                 else
1543                                 {
1544                                         // ran out of data?
1545                                         val = NULL;
1546                                         eat = varlen + 1;
1547                                 }
1548                         } else {
1549                                 varlen = strspn(in, "*0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-");
1550                                 val = Cmd_GetCvarValue(in, varlen, alias);
1551                                 eat = varlen;
1552                         }
1553                         if(val)
1554                         {
1555                                 // insert the cvar value
1556                                 while(*val && outlen < maxoutlen)
1557                                         outtext[outlen++] = *val++;
1558                                 in += eat;
1559                         }
1560                         else
1561                         {
1562                                 // copy the unexpanded text
1563                                 outtext[outlen++] = '$';
1564                                 while(eat && outlen < maxoutlen)
1565                                 {
1566                                         outtext[outlen++] = *in++;
1567                                         --eat;
1568                                 }
1569                         }
1570                 }
1571                 else 
1572                         outtext[outlen++] = *in++;
1573         }
1574         outtext[outlen] = 0;
1575 }
1576
1577 /*
1578 ============
1579 Cmd_ExecuteAlias
1580
1581 Called for aliases and fills in the alias into the cbuffer
1582 ============
1583 */
1584 static void Cmd_ExecuteAlias (cmdalias_t *alias)
1585 {
1586         static char buffer[ MAX_INPUTLINE ];
1587         static char buffer2[ MAX_INPUTLINE ];
1588         Cmd_PreprocessString( alias->value, buffer, sizeof(buffer) - 2, alias );
1589         // insert at start of command buffer, so that aliases execute in order
1590         // (fixes bug introduced by Black on 20050705)
1591
1592         // Note: Cbuf_PreprocessString will be called on this string AGAIN! So we
1593         // have to make sure that no second variable expansion takes place, otherwise
1594         // alias parameters containing dollar signs can have bad effects.
1595         Cmd_QuoteString(buffer2, sizeof(buffer2), buffer, "$");
1596         Cbuf_InsertText( buffer2 );
1597 }
1598
1599 /*
1600 ========
1601 Cmd_List
1602
1603         CmdList Added by EvilTypeGuy eviltypeguy@qeradiant.com
1604         Thanks to Matthias "Maddes" Buecher, http://www.inside3d.com/qip/
1605
1606 ========
1607 */
1608 static void Cmd_List_f (void)
1609 {
1610         cmd_function_t *cmd;
1611         const char *partial;
1612         size_t len;
1613         int count;
1614         qboolean ispattern;
1615
1616         if (Cmd_Argc() > 1)
1617         {
1618                 partial = Cmd_Argv (1);
1619                 len = strlen(partial);
1620         }
1621         else
1622         {
1623                 partial = NULL;
1624                 len = 0;
1625         }
1626
1627         ispattern = partial && (strchr(partial, '*') || strchr(partial, '?'));
1628
1629         count = 0;
1630         for (cmd = cmd_functions; cmd; cmd = cmd->next)
1631         {
1632                 if (partial && (ispattern ? !matchpattern_with_separator(cmd->name, partial, false, "", false) : strncmp(partial, cmd->name, len)))
1633                         continue;
1634                 Con_Printf("%s : %s\n", cmd->name, cmd->description);
1635                 count++;
1636         }
1637
1638         if (len)
1639         {
1640                 if(ispattern)
1641                         Con_Printf("%i Command%s matching \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1642                 else
1643                         Con_Printf("%i Command%s beginning with \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1644         }
1645         else
1646                 Con_Printf("%i Command%s\n\n", count, (count > 1) ? "s" : "");
1647 }
1648
1649 static void Cmd_Apropos_f(void)
1650 {
1651         cmd_function_t *cmd;
1652         cvar_t *cvar;
1653         cmdalias_t *alias;
1654         const char *partial;
1655         size_t len;
1656         int count;
1657         qboolean ispattern;
1658
1659         if (Cmd_Argc() > 1)
1660         {
1661                 partial = Cmd_Args();
1662                 len = strlen(partial);
1663         }
1664         else
1665         {
1666                 Con_Printf("usage: apropos <string>\n");
1667                 return;
1668         }
1669
1670         ispattern = partial && (strchr(partial, '*') || strchr(partial, '?'));
1671         if(!ispattern)
1672         {
1673                 partial = va("*%s*", partial);
1674                 len += 2;
1675         }
1676
1677         count = 0;
1678         for (cvar = cvar_vars; cvar; cvar = cvar->next)
1679         {
1680                 if (!matchpattern_with_separator(cvar->name, partial, true, "", false))
1681                 if (!matchpattern_with_separator(cvar->description, partial, true, "", false))
1682                         continue;
1683                 Con_Printf ("cvar ^3%s^7 is \"%s\" [\"%s\"] %s\n", cvar->name, cvar->string, cvar->defstring, cvar->description);
1684                 count++;
1685         }
1686         for (cmd = cmd_functions; cmd; cmd = cmd->next)
1687         {
1688                 if (!matchpattern_with_separator(cmd->name, partial, true, "", false))
1689                 if (!matchpattern_with_separator(cmd->description, partial, true, "", false))
1690                         continue;
1691                 Con_Printf("command ^2%s^7: %s\n", cmd->name, cmd->description);
1692                 count++;
1693         }
1694         for (alias = cmd_alias; alias; alias = alias->next)
1695         {
1696                 if (!matchpattern_with_separator(alias->name, partial, true, "", false))
1697                 if (!matchpattern_with_separator(alias->value, partial, true, "", false))
1698                         continue;
1699                 Con_Printf("alias ^5%s^7: %s", alias->name, alias->value);
1700                 count++;
1701         }
1702         Con_Printf("%i result%s\n\n", count, (count > 1) ? "s" : "");
1703 }
1704
1705 /*
1706 ============
1707 Cmd_Init
1708 ============
1709 */
1710 void Cmd_Init (void)
1711 {
1712         cmd_mempool = Mem_AllocPool("commands", 0, NULL);
1713         Cvar_RegisterVariable(&con_this);
1714         // space for commands and script files
1715         Mem_ExpandableArray_NewArray(&cmd_exec_array, cmd_mempool, sizeof(cmd_executor_t), 4);
1716
1717         cmd_ex = Con_Spawn(&cmd_tid);
1718         Con_SetTID(cmd_tid, false);
1719
1720         /*
1721         cmd_tid = 0;
1722         cmd_text = &cmd_exec[cmd_tid].text;
1723         cmd_text->data = cmd_exec[cmd_tid].text_buf;
1724         cmd_text->maxsize = sizeof(cmd_exec[cmd_tid].text_buf);
1725         cmd_text->cursize = 0;
1726         */
1727 }
1728
1729 void Cmd_Init_Commands (void)
1730 {
1731 //
1732 // register our commands
1733 //
1734         Cmd_AddCommand ("stuffcmds",Cmd_StuffCmds_f, "execute commandline parameters (must be present in quake.rc script)");
1735         Cmd_AddCommand ("exec",Cmd_Exec_f, "execute a script file");
1736         Cmd_AddCommand ("echo",Cmd_Echo_f, "print a message to the console (useful in scripts)");
1737         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");
1738         Cmd_AddCommand ("unalias",Cmd_UnAlias_f, "remove an alias");
1739         Cmd_AddCommand ("cmd", Cmd_ForwardToServer, "send a console commandline to the server (used by some mods)");
1740         Cmd_AddCommand ("wait", Cmd_Wait_f, "make script execution wait for next rendered frame");
1741         Cmd_AddCommand ("set", Cvar_Set_f, "create or change the value of a console variable");
1742         Cmd_AddCommand ("seta", Cvar_SetA_f, "create or change the value of a console variable that will be saved to config.cfg");
1743 #ifdef FILLALLCVARSWITHRUBBISH
1744         Cmd_AddCommand ("fillallcvarswithrubbish", Cvar_FillAll_f, "fill all cvars with a specified number of characters to provoke buffer overruns");
1745 #endif /* FILLALLCVARSWITHRUBBISH */
1746
1747         // 2000-01-09 CmdList, CvarList commands By Matthias "Maddes" Buecher
1748         // Added/Modified by EvilTypeGuy eviltypeguy@qeradiant.com
1749         Cmd_AddCommand ("cmdlist", Cmd_List_f, "lists all console commands beginning with the specified prefix or matching the specified wildcard pattern");
1750         Cmd_AddCommand ("cvarlist", Cvar_List_f, "lists all console variables beginning with the specified prefix or matching the specified wildcard pattern");
1751         Cmd_AddCommand ("apropos", Cmd_Apropos_f, "lists all console variables/commands/aliases containing the specified string in the name or description");
1752
1753         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");
1754         Cmd_AddCommand ("cvar_resettodefaults_all", Cvar_ResetToDefaults_All_f, "sets all cvars to their locked default values");
1755         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)");
1756         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)");
1757
1758         Cmd_AddCommand ("cprint", Cmd_Centerprint_f, "print something at the screen center");
1759         Cmd_AddCommand ("defer", Cmd_Defer_f, "execute a command in the future");
1760
1761         Cmd_AddCommand ("conspawn", Cmd_Spawn_f, "spawn new console instances, their IDs are stored in the provided cvars");
1762         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");
1763         Cmd_AddCommand ("sleep", Cmd_Sleep_f, "let the current, or a specific console instance sleep for some time in the background");
1764         Cmd_AddCommand ("cond", Cmd_Cond_f, "suspend a console instance until a cvar becomes true (not-null)");
1765         Cmd_AddCommand ("condl", Cmd_CondLocal_f, "suspend a console instance until a local cvar becomes true (not-null)");
1766         Cmd_AddCommand ("suspend", Cmd_Suspend_f, "suspend a console instance, when suspending the current console, this also does 'setid 0'");
1767         Cmd_AddCommand ("resume", Cmd_Resume_f, "resume the execution of a console instance");
1768         Cmd_AddCommand ("term", Cmd_XKill_f, "kill a console instance (doesn't work on id 0)");
1769         Cmd_AddCommand ("termq", Cmd_XKill_f, "kill a console instance (doesn't work on id 0)");
1770         Cmd_AddCommand ("xadd", Cmd_XAdd_f, "add a command to a console instance");
1771         Cmd_AddCommand ("setlocal", Cmd_SetLocal_f, "set a instance-local cvar");
1772         Cmd_AddCommand ("setforeign", Cmd_SetForeign_f, "set an instance's local cvar");
1773         Cmd_AddCommand ("setcps", Cmd_SetCPS_f, "set the commands executed per second in a console instance");
1774
1775         // DRESK - 5/14/06
1776         // Support Doom3-style Toggle Command
1777         Cmd_AddCommand( "toggle", Cmd_Toggle_f, "toggles a console variable's values (use for more info)");
1778 }
1779
1780 /*
1781 ============
1782 Cmd_Shutdown
1783 ============
1784 */
1785 void Cmd_Shutdown(void)
1786 {
1787         Mem_FreePool(&cmd_mempool);
1788 }
1789
1790 /*
1791 ============
1792 Cmd_Argc
1793 ============
1794 */
1795 int             Cmd_Argc (void)
1796 {
1797         return cmd_argc;
1798 }
1799
1800 /*
1801 ============
1802 Cmd_Argv
1803 ============
1804 */
1805 const char *Cmd_Argv (int arg)
1806 {
1807         if (arg >= cmd_argc )
1808                 return cmd_null_string;
1809         return cmd_argv[arg];
1810 }
1811
1812 /*
1813 ============
1814 Cmd_Args
1815 ============
1816 */
1817 const char *Cmd_Args (void)
1818 {
1819         return cmd_args;
1820 }
1821
1822
1823 /*
1824 ============
1825 Cmd_TokenizeString
1826
1827 Parses the given string into command line tokens.
1828 ============
1829 */
1830 // AK: This function should only be called from ExcuteString because the current design is a bit of an hack
1831 static void Cmd_TokenizeString (const char *text)
1832 {
1833         int l;
1834
1835         cmd_argc = 0;
1836         cmd_args = NULL;
1837
1838         while (1)
1839         {
1840                 // skip whitespace up to a /n
1841                 while (*text && ISWHITESPACE(*text) && *text != '\r' && *text != '\n')
1842                         text++;
1843
1844                 // line endings:
1845                 // UNIX: \n
1846                 // Mac: \r
1847                 // Windows: \r\n
1848                 if (*text == '\n' || *text == '\r')
1849                 {
1850                         // a newline separates commands in the buffer
1851                         if (*text == '\r' && text[1] == '\n')
1852                                 text++;
1853                         text++;
1854                         break;
1855                 }
1856
1857                 if (!*text)
1858                         return;
1859
1860                 if (cmd_argc == 1)
1861                         cmd_args = text;
1862
1863                 if (!COM_ParseToken_Console(&text))
1864                         return;
1865
1866                 if (cmd_argc < MAX_ARGS)
1867                 {
1868                         l = (int)strlen(com_token) + 1;
1869                         if (cmd_tokenizebufferpos + l > CMD_TOKENIZELENGTH)
1870                         {
1871                                 Con_Printf("Cmd_TokenizeString: ran out of %i character buffer space for command arguements\n", CMD_TOKENIZELENGTH);
1872                                 break;
1873                         }
1874                         memcpy (cmd_tokenizebuffer + cmd_tokenizebufferpos, com_token, l);
1875                         cmd_argv[cmd_argc] = cmd_tokenizebuffer + cmd_tokenizebufferpos;
1876                         cmd_tokenizebufferpos += l;
1877                         cmd_argc++;
1878                 }
1879         }
1880 }
1881
1882
1883 /*
1884 ============
1885 Cmd_AddCommand
1886 ============
1887 */
1888 void Cmd_AddCommand_WithClientCommand (const char *cmd_name, xcommand_t consolefunction, xcommand_t clientfunction, const char *description)
1889 {
1890         cmd_function_t *cmd;
1891         cmd_function_t *prev, *current;
1892
1893 // fail if the command is a variable name
1894         if (Cvar_FindVar( cmd_name ))
1895         {
1896                 Con_Printf("Cmd_AddCommand: %s already defined as a var\n", cmd_name);
1897                 return;
1898         }
1899
1900 // fail if the command already exists
1901         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1902         {
1903                 if (!strcmp (cmd_name, cmd->name))
1904                 {
1905                         if (consolefunction || clientfunction)
1906                         {
1907                                 Con_Printf("Cmd_AddCommand: %s already defined\n", cmd_name);
1908                                 return;
1909                         }
1910                         else    //[515]: csqc
1911                         {
1912                                 cmd->csqcfunc = true;
1913                                 return;
1914                         }
1915                 }
1916         }
1917
1918         cmd = (cmd_function_t *)Mem_Alloc(cmd_mempool, sizeof(cmd_function_t));
1919         cmd->name = cmd_name;
1920         cmd->consolefunction = consolefunction;
1921         cmd->clientfunction = clientfunction;
1922         cmd->description = description;
1923         if(!consolefunction && !clientfunction)                 //[515]: csqc
1924                 cmd->csqcfunc = true;
1925         cmd->next = cmd_functions;
1926
1927 // insert it at the right alphanumeric position
1928         for( prev = NULL, current = cmd_functions ; current && strcmp( current->name, cmd->name ) < 0 ; prev = current, current = current->next )
1929                 ;
1930         if( prev ) {
1931                 prev->next = cmd;
1932         } else {
1933                 cmd_functions = cmd;
1934         }
1935         cmd->next = current;
1936 }
1937
1938 void Cmd_AddCommand (const char *cmd_name, xcommand_t function, const char *description)
1939 {
1940         Cmd_AddCommand_WithClientCommand (cmd_name, function, NULL, description);
1941 }
1942
1943 /*
1944 ============
1945 Cmd_Exists
1946 ============
1947 */
1948 qboolean Cmd_Exists (const char *cmd_name)
1949 {
1950         cmd_function_t  *cmd;
1951
1952         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1953                 if (!strcmp (cmd_name,cmd->name))
1954                         return true;
1955
1956         return false;
1957 }
1958
1959
1960 /*
1961 ============
1962 Cmd_CompleteCommand
1963 ============
1964 */
1965 const char *Cmd_CompleteCommand (const char *partial)
1966 {
1967         cmd_function_t *cmd;
1968         size_t len;
1969
1970         len = strlen(partial);
1971
1972         if (!len)
1973                 return NULL;
1974
1975 // check functions
1976         for (cmd = cmd_functions; cmd; cmd = cmd->next)
1977                 if (!strncasecmp(partial, cmd->name, len))
1978                         return cmd->name;
1979
1980         return NULL;
1981 }
1982
1983 /*
1984         Cmd_CompleteCountPossible
1985
1986         New function for tab-completion system
1987         Added by EvilTypeGuy
1988         Thanks to Fett erich@heintz.com
1989         Thanks to taniwha
1990
1991 */
1992 int Cmd_CompleteCountPossible (const char *partial)
1993 {
1994         cmd_function_t *cmd;
1995         size_t len;
1996         int h;
1997
1998         h = 0;
1999         len = strlen(partial);
2000
2001         if (!len)
2002                 return 0;
2003
2004         // Loop through the command list and count all partial matches
2005         for (cmd = cmd_functions; cmd; cmd = cmd->next)
2006                 if (!strncasecmp(partial, cmd->name, len))
2007                         h++;
2008
2009         return h;
2010 }
2011
2012 /*
2013         Cmd_CompleteBuildList
2014
2015         New function for tab-completion system
2016         Added by EvilTypeGuy
2017         Thanks to Fett erich@heintz.com
2018         Thanks to taniwha
2019
2020 */
2021 const char **Cmd_CompleteBuildList (const char *partial)
2022 {
2023         cmd_function_t *cmd;
2024         size_t len = 0;
2025         size_t bpos = 0;
2026         size_t sizeofbuf = (Cmd_CompleteCountPossible (partial) + 1) * sizeof (const char *);
2027         const char **buf;
2028
2029         len = strlen(partial);
2030         buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
2031         // Loop through the alias list and print all matches
2032         for (cmd = cmd_functions; cmd; cmd = cmd->next)
2033                 if (!strncasecmp(partial, cmd->name, len))
2034                         buf[bpos++] = cmd->name;
2035
2036         buf[bpos] = NULL;
2037         return buf;
2038 }
2039
2040 // written by LordHavoc
2041 void Cmd_CompleteCommandPrint (const char *partial)
2042 {
2043         cmd_function_t *cmd;
2044         size_t len = strlen(partial);
2045         // Loop through the command list and print all matches
2046         for (cmd = cmd_functions; cmd; cmd = cmd->next)
2047                 if (!strncasecmp(partial, cmd->name, len))
2048                         Con_Printf("^2%s^7: %s\n", cmd->name, cmd->description);
2049 }
2050
2051 /*
2052         Cmd_CompleteAlias
2053
2054         New function for tab-completion system
2055         Added by EvilTypeGuy
2056         Thanks to Fett erich@heintz.com
2057         Thanks to taniwha
2058
2059 */
2060 const char *Cmd_CompleteAlias (const char *partial)
2061 {
2062         cmdalias_t *alias;
2063         size_t len;
2064
2065         len = strlen(partial);
2066
2067         if (!len)
2068                 return NULL;
2069
2070         // Check functions
2071         for (alias = cmd_alias; alias; alias = alias->next)
2072                 if (!strncasecmp(partial, alias->name, len))
2073                         return alias->name;
2074
2075         return NULL;
2076 }
2077
2078 // written by LordHavoc
2079 void Cmd_CompleteAliasPrint (const char *partial)
2080 {
2081         cmdalias_t *alias;
2082         size_t len = strlen(partial);
2083         // Loop through the alias list and print all matches
2084         for (alias = cmd_alias; alias; alias = alias->next)
2085                 if (!strncasecmp(partial, alias->name, len))
2086                         Con_Printf("^5%s^7: %s", alias->name, alias->value);
2087 }
2088
2089
2090 /*
2091         Cmd_CompleteAliasCountPossible
2092
2093         New function for tab-completion system
2094         Added by EvilTypeGuy
2095         Thanks to Fett erich@heintz.com
2096         Thanks to taniwha
2097
2098 */
2099 int Cmd_CompleteAliasCountPossible (const char *partial)
2100 {
2101         cmdalias_t      *alias;
2102         size_t          len;
2103         int                     h;
2104
2105         h = 0;
2106
2107         len = strlen(partial);
2108
2109         if (!len)
2110                 return 0;
2111
2112         // Loop through the command list and count all partial matches
2113         for (alias = cmd_alias; alias; alias = alias->next)
2114                 if (!strncasecmp(partial, alias->name, len))
2115                         h++;
2116
2117         return h;
2118 }
2119
2120 /*
2121         Cmd_CompleteAliasBuildList
2122
2123         New function for tab-completion system
2124         Added by EvilTypeGuy
2125         Thanks to Fett erich@heintz.com
2126         Thanks to taniwha
2127
2128 */
2129 const char **Cmd_CompleteAliasBuildList (const char *partial)
2130 {
2131         cmdalias_t *alias;
2132         size_t len = 0;
2133         size_t bpos = 0;
2134         size_t sizeofbuf = (Cmd_CompleteAliasCountPossible (partial) + 1) * sizeof (const char *);
2135         const char **buf;
2136
2137         len = strlen(partial);
2138         buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
2139         // Loop through the alias list and print all matches
2140         for (alias = cmd_alias; alias; alias = alias->next)
2141                 if (!strncasecmp(partial, alias->name, len))
2142                         buf[bpos++] = alias->name;
2143
2144         buf[bpos] = NULL;
2145         return buf;
2146 }
2147
2148 void Cmd_ClearCsqcFuncs (void)
2149 {
2150         cmd_function_t *cmd;
2151         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
2152                 cmd->csqcfunc = false;
2153 }
2154
2155 qboolean CL_VM_ConsoleCommand (const char *cmd);
2156 /*
2157 ============
2158 Cmd_ExecuteString
2159
2160 A complete command line has been parsed, so try to execute it
2161 FIXME: lookupnoadd the token to speed search?
2162 ============
2163 */
2164 void Cmd_ExecuteString (const char *text, cmd_source_t src)
2165 {
2166         int oldpos;
2167         int found;
2168         cmd_function_t *cmd;
2169         cmdalias_t *a;
2170
2171         oldpos = cmd_tokenizebufferpos;
2172         cmd_source = src;
2173         found = false;
2174
2175         Cmd_TokenizeString (text);
2176
2177 // execute the command line
2178         if (!Cmd_Argc())
2179         {
2180                 cmd_tokenizebufferpos = oldpos;
2181                 return;         // no tokens
2182         }
2183
2184 // check functions
2185         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
2186         {
2187                 if (!strcasecmp (cmd_argv[0],cmd->name))
2188                 {
2189                         if (cmd->csqcfunc && CL_VM_ConsoleCommand (text))       //[515]: csqc
2190                                 return;
2191                         switch (src)
2192                         {
2193                         case src_command:
2194                                 if (cmd->consolefunction)
2195                                         cmd->consolefunction ();
2196                                 else if (cmd->clientfunction)
2197                                 {
2198                                         if (cls.state == ca_connected)
2199                                         {
2200                                                 // forward remote commands to the server for execution
2201                                                 Cmd_ForwardToServer();
2202                                         }
2203                                         else
2204                                                 Con_Printf("Can not send command \"%s\", not connected.\n", Cmd_Argv(0));
2205                                 }
2206                                 else
2207                                         Con_Printf("Command \"%s\" can not be executed\n", Cmd_Argv(0));
2208                                 found = true;
2209                                 goto command_found;
2210                                 break;
2211                         case src_client:
2212                                 if (cmd->clientfunction)
2213                                 {
2214                                         cmd->clientfunction ();
2215                                         cmd_tokenizebufferpos = oldpos;
2216                                         return;
2217                                 }
2218                                 break;
2219                         }
2220                         break;
2221                 }
2222         }
2223 command_found:
2224
2225         // if it's a client command and no command was found, say so.
2226         if (cmd_source == src_client)
2227         {
2228                 Con_Printf("player \"%s\" tried to %s\n", host_client->name, text);
2229                 cmd_tokenizebufferpos = oldpos;
2230                 return;
2231         }
2232
2233 // check alias
2234         for (a=cmd_alias ; a ; a=a->next)
2235         {
2236                 if (!strcasecmp (cmd_argv[0], a->name))
2237                 {
2238                         Cmd_ExecuteAlias(a);
2239                         cmd_tokenizebufferpos = oldpos;
2240                         return;
2241                 }
2242         }
2243
2244         if(found) // if the command was hooked and found, all is good
2245         {
2246                 cmd_tokenizebufferpos = oldpos;
2247                 return;
2248         }
2249
2250 // check cvars
2251         if (!Cvar_Command () && host_framecount > 0)
2252                 Con_Printf("Unknown command \"%s\"\n", Cmd_Argv(0));
2253
2254         cmd_tokenizebufferpos = oldpos;
2255 }
2256
2257
2258 /*
2259 ===================
2260 Cmd_ForwardStringToServer
2261
2262 Sends an entire command string over to the server, unprocessed
2263 ===================
2264 */
2265 void Cmd_ForwardStringToServer (const char *s)
2266 {
2267         char temp[128];
2268         if (cls.state != ca_connected)
2269         {
2270                 Con_Printf("Can't \"%s\", not connected\n", s);
2271                 return;
2272         }
2273
2274         if (!cls.netcon)
2275                 return;
2276
2277         // LordHavoc: thanks to Fuh for bringing the pure evil of SZ_Print to my
2278         // attention, it has been eradicated from here, its only (former) use in
2279         // all of darkplaces.
2280         if (cls.protocol == PROTOCOL_QUAKEWORLD)
2281                 MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
2282         else
2283                 MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
2284         if ((!strncmp(s, "say ", 4) || !strncmp(s, "say_team ", 9)) && cl_locs_enable.integer)
2285         {
2286                 // say/say_team commands can replace % character codes with status info
2287                 while (*s)
2288                 {
2289                         if (*s == '%' && s[1])
2290                         {
2291                                 // handle proquake message macros
2292                                 temp[0] = 0;
2293                                 switch (s[1])
2294                                 {
2295                                 case 'l': // current location
2296                                         CL_Locs_FindLocationName(temp, sizeof(temp), cl.movement_origin);
2297                                         break;
2298                                 case 'h': // current health
2299                                         dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_HEALTH]);
2300                                         break;
2301                                 case 'a': // current armor
2302                                         dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ARMOR]);
2303                                         break;
2304                                 case 'x': // current rockets
2305                                         dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ROCKETS]);
2306                                         break;
2307                                 case 'c': // current cells
2308                                         dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_CELLS]);
2309                                         break;
2310                                 // silly proquake macros
2311                                 case 'd': // loc at last death
2312                                         CL_Locs_FindLocationName(temp, sizeof(temp), cl.lastdeathorigin);
2313                                         break;
2314                                 case 't': // current time
2315                                         dpsnprintf(temp, sizeof(temp), "%.0f:%.0f", floor(cl.time / 60), cl.time - floor(cl.time / 60) * 60);
2316                                         break;
2317                                 case 'r': // rocket launcher status ("I have RL", "I need rockets", "I need RL")
2318                                         if (!(cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER))
2319                                                 dpsnprintf(temp, sizeof(temp), "I need RL");
2320                                         else if (!cl.stats[STAT_ROCKETS])
2321                                                 dpsnprintf(temp, sizeof(temp), "I need rockets");
2322                                         else
2323                                                 dpsnprintf(temp, sizeof(temp), "I have RL");
2324                                         break;
2325                                 case 'p': // powerup status (outputs "quad" "pent" and "eyes" according to status)
2326                                         if (cl.stats[STAT_ITEMS] & IT_QUAD)
2327                                         {
2328                                                 if (temp[0])
2329                                                         strlcat(temp, " ", sizeof(temp));
2330                                                 strlcat(temp, "quad", sizeof(temp));
2331                                         }
2332                                         if (cl.stats[STAT_ITEMS] & IT_INVULNERABILITY)
2333                                         {
2334                                                 if (temp[0])
2335                                                         strlcat(temp, " ", sizeof(temp));
2336                                                 strlcat(temp, "pent", sizeof(temp));
2337                                         }
2338                                         if (cl.stats[STAT_ITEMS] & IT_INVISIBILITY)
2339                                         {
2340                                                 if (temp[0])
2341                                                         strlcat(temp, " ", sizeof(temp));
2342                                                 strlcat(temp, "eyes", sizeof(temp));
2343                                         }
2344                                         break;
2345                                 case 'w': // weapon status (outputs "SSG:NG:SNG:GL:RL:LG" with the text between : characters omitted if you lack the weapon)
2346                                         if (cl.stats[STAT_ITEMS] & IT_SUPER_SHOTGUN)
2347                                                 strlcat(temp, "SSG", sizeof(temp));
2348                                         strlcat(temp, ":", sizeof(temp));
2349                                         if (cl.stats[STAT_ITEMS] & IT_NAILGUN)
2350                                                 strlcat(temp, "NG", sizeof(temp));
2351                                         strlcat(temp, ":", sizeof(temp));
2352                                         if (cl.stats[STAT_ITEMS] & IT_SUPER_NAILGUN)
2353                                                 strlcat(temp, "SNG", sizeof(temp));
2354                                         strlcat(temp, ":", sizeof(temp));
2355                                         if (cl.stats[STAT_ITEMS] & IT_GRENADE_LAUNCHER)
2356                                                 strlcat(temp, "GL", sizeof(temp));
2357                                         strlcat(temp, ":", sizeof(temp));
2358                                         if (cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER)
2359                                                 strlcat(temp, "RL", sizeof(temp));
2360                                         strlcat(temp, ":", sizeof(temp));
2361                                         if (cl.stats[STAT_ITEMS] & IT_LIGHTNING)
2362                                                 strlcat(temp, "LG", sizeof(temp));
2363                                         break;
2364                                 default:
2365                                         // not a recognized macro, print it as-is...
2366                                         temp[0] = s[0];
2367                                         temp[1] = s[1];
2368                                         temp[2] = 0;
2369                                         break;
2370                                 }
2371                                 // write the resulting text
2372                                 SZ_Write(&cls.netcon->message, (unsigned char *)temp, strlen(temp));
2373                                 s += 2;
2374                                 continue;
2375                         }
2376                         MSG_WriteByte(&cls.netcon->message, *s);
2377                         s++;
2378                 }
2379                 MSG_WriteByte(&cls.netcon->message, 0);
2380         }
2381         else // any other command is passed on as-is
2382                 SZ_Write(&cls.netcon->message, (const unsigned char *)s, (int)strlen(s) + 1);
2383 }
2384
2385 /*
2386 ===================
2387 Cmd_ForwardToServer
2388
2389 Sends the entire command line over to the server
2390 ===================
2391 */
2392 void Cmd_ForwardToServer (void)
2393 {
2394         const char *s;
2395         if (!strcasecmp(Cmd_Argv(0), "cmd"))
2396         {
2397                 // we want to strip off "cmd", so just send the args
2398                 s = Cmd_Argc() > 1 ? Cmd_Args() : "";
2399         }
2400         else
2401         {
2402                 // we need to keep the command name, so send Cmd_Argv(0), a space and then Cmd_Args()
2403                 s = va("%s %s", Cmd_Argv(0), Cmd_Argc() > 1 ? Cmd_Args() : "");
2404         }
2405         // don't send an empty forward message if the user tries "cmd" by itself
2406         if (!s || !*s)
2407                 return;
2408         Cmd_ForwardStringToServer(s);
2409 }
2410
2411
2412 /*
2413 ================
2414 Cmd_CheckParm
2415
2416 Returns the position (1 to argc-1) in the command's argument list
2417 where the given parameter apears, or 0 if not present
2418 ================
2419 */
2420
2421 int Cmd_CheckParm (const char *parm)
2422 {
2423         int i;
2424
2425         if (!parm)
2426         {
2427                 Con_Printf ("Cmd_CheckParm: NULL");
2428                 return 0;
2429         }
2430
2431         for (i = 1; i < Cmd_Argc (); i++)
2432                 if (!strcasecmp (parm, Cmd_Argv (i)))
2433                         return i;
2434
2435         return 0;
2436 }
2437