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