fix $cvar expansion to work in quotes
[xonotic/darkplaces.git] / cmd.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20 // cmd.c -- Quake script command processing module
21
22 #include "quakedef.h"
23
24 #define MAX_ALIAS_NAME  32
25 // this is the largest script file that can be executed in one step
26 // LordHavoc: inreased this from 8192 to 32768
27 #define CMDBUFSIZE 32768
28 // maximum number of parameters to a command
29 #define MAX_ARGS 80
30 // maximum tokenizable commandline length (counting NUL terminations)
31 #define CMD_TOKENIZELENGTH (MAX_INPUTLINE + 80)
32
33 typedef struct cmdalias_s
34 {
35         struct cmdalias_s *next;
36         char name[MAX_ALIAS_NAME];
37         char *value;
38 } cmdalias_t;
39
40 static cmdalias_t *cmd_alias;
41
42 static qboolean cmd_wait;
43
44 static mempool_t *cmd_mempool;
45
46 static char cmd_tokenizebuffer[CMD_TOKENIZELENGTH];
47 static int cmd_tokenizebufferpos = 0;
48
49 //=============================================================================
50
51 /*
52 ============
53 Cmd_Wait_f
54
55 Causes execution of the remainder of the command buffer to be delayed until
56 next frame.  This allows commands like:
57 bind g "impulse 5 ; +attack ; wait ; -attack ; impulse 2"
58 ============
59 */
60 static void Cmd_Wait_f (void)
61 {
62         cmd_wait = true;
63 }
64
65 /*
66 =============================================================================
67
68                                                 COMMAND BUFFER
69
70 =============================================================================
71 */
72
73 static sizebuf_t        cmd_text;
74 static unsigned char            cmd_text_buf[CMDBUFSIZE];
75
76 /*
77 ============
78 Cbuf_AddText
79
80 Adds command text at the end of the buffer
81 ============
82 */
83 void Cbuf_AddText (const char *text)
84 {
85         int             l;
86
87         l = (int)strlen (text);
88
89         if (cmd_text.cursize + l >= cmd_text.maxsize)
90         {
91                 Con_Print("Cbuf_AddText: overflow\n");
92                 return;
93         }
94
95         SZ_Write (&cmd_text, (const unsigned char *)text, (int)strlen (text));
96 }
97
98
99 /*
100 ============
101 Cbuf_InsertText
102
103 Adds command text immediately after the current command
104 Adds a \n to the text
105 FIXME: actually change the command buffer to do less copying
106 ============
107 */
108 void Cbuf_InsertText (const char *text)
109 {
110         char    *temp;
111         int             templen;
112
113         // copy off any commands still remaining in the exec buffer
114         templen = cmd_text.cursize;
115         if (templen)
116         {
117                 temp = (char *)Mem_Alloc (tempmempool, templen);
118                 memcpy (temp, cmd_text.data, templen);
119                 SZ_Clear (&cmd_text);
120         }
121         else
122                 temp = NULL;
123
124         // add the entire text of the file
125         Cbuf_AddText (text);
126
127         // add the copied off data
128         if (temp != NULL)
129         {
130                 SZ_Write (&cmd_text, (const unsigned char *)temp, templen);
131                 Mem_Free (temp);
132         }
133 }
134
135 /*
136 ============
137 Cbuf_Execute
138 ============
139 */
140 static void Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias );
141 void Cbuf_Execute (void)
142 {
143         int i;
144         char *text;
145         char line[MAX_INPUTLINE];
146         char preprocessed[MAX_INPUTLINE];
147         int quotes;
148
149         // LordHavoc: making sure the tokenizebuffer doesn't get filled up by repeated crashes
150         cmd_tokenizebufferpos = 0;
151
152         while (cmd_text.cursize)
153         {
154 // find a \n or ; line break
155                 text = (char *)cmd_text.data;
156
157                 quotes = 0;
158                 for (i=0 ; i< cmd_text.cursize ; i++)
159                 {
160                         if (text[i] == '"')
161                                 quotes ^= 1;
162                         if (text[i] == '\\' && text[i+1] == '"')
163                                 i++;
164                         if ( !quotes &&  text[i] == ';')
165                                 break;  // don't break if inside a quoted string
166                         if (text[i] == '\r' || text[i] == '\n')
167                                 break;
168                 }
169
170                 memcpy (line, text, i);
171                 line[i] = 0;
172
173 // delete the text from the command buffer and move remaining commands down
174 // this is necessary because commands (exec, alias) can insert data at the
175 // beginning of the text buffer
176
177                 if (i == cmd_text.cursize)
178                         cmd_text.cursize = 0;
179                 else
180                 {
181                         i++;
182                         cmd_text.cursize -= i;
183                         memcpy (cmd_text.data, text+i, cmd_text.cursize);
184                 }
185
186 // execute the command line
187                 Cmd_PreprocessString( line, preprocessed, sizeof(preprocessed), NULL );
188                 Cmd_ExecuteString (preprocessed, src_command);
189
190                 if (cmd_wait)
191                 {       // skip out while text still remains in buffer, leaving it
192                         // for next frame
193                         cmd_wait = false;
194                         break;
195                 }
196         }
197 }
198
199 /*
200 ==============================================================================
201
202                                                 SCRIPT COMMANDS
203
204 ==============================================================================
205 */
206
207 /*
208 ===============
209 Cmd_StuffCmds_f
210
211 Adds command line parameters as script statements
212 Commands lead with a +, and continue until a - or another +
213 quake +prog jctest.qp +cmd amlev1
214 quake -nosound +cmd amlev1
215 ===============
216 */
217 qboolean host_stuffcmdsrun = false;
218 void Cmd_StuffCmds_f (void)
219 {
220         int             i, j, l;
221         // this is for all commandline options combined (and is bounds checked)
222         char    build[MAX_INPUTLINE];
223
224         if (Cmd_Argc () != 1)
225         {
226                 Con_Print("stuffcmds : execute command line parameters\n");
227                 return;
228         }
229
230         // no reason to run the commandline arguments twice
231         if (host_stuffcmdsrun)
232                 return;
233
234         host_stuffcmdsrun = true;
235         build[0] = 0;
236         l = 0;
237         for (i = 0;i < com_argc;i++)
238         {
239                 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)
240                 {
241                         j = 1;
242                         while (com_argv[i][j])
243                                 build[l++] = com_argv[i][j++];
244                         i++;
245                         for (;i < com_argc;i++)
246                         {
247                                 if (!com_argv[i])
248                                         continue;
249                                 if ((com_argv[i][0] == '+' || com_argv[i][0] == '-') && (com_argv[i][1] < '0' || com_argv[i][1] > '9'))
250                                         break;
251                                 if (l + strlen(com_argv[i]) + 4 > sizeof(build) - 1)
252                                         break;
253                                 build[l++] = ' ';
254                                 if (strchr(com_argv[i], ' '))
255                                         build[l++] = '\"';
256                                 for (j = 0;com_argv[i][j];j++)
257                                         build[l++] = com_argv[i][j];
258                                 if (strchr(com_argv[i], ' '))
259                                         build[l++] = '\"';
260                         }
261                         build[l++] = '\n';
262                         i--;
263                 }
264         }
265         // now terminate the combined string and prepend it to the command buffer
266         // we already reserved space for the terminator
267         build[l++] = 0;
268         Cbuf_InsertText (build);
269 }
270
271
272 /*
273 ===============
274 Cmd_Exec_f
275 ===============
276 */
277 static void Cmd_Exec_f (void)
278 {
279         char *f;
280
281         if (Cmd_Argc () != 2)
282         {
283                 Con_Print("exec <filename> : execute a script file\n");
284                 return;
285         }
286
287         f = (char *)FS_LoadFile (Cmd_Argv(1), tempmempool, false, NULL);
288         if (!f)
289         {
290                 Con_Printf("couldn't exec %s\n",Cmd_Argv(1));
291                 return;
292         }
293         Con_DPrintf("execing %s\n",Cmd_Argv(1));
294
295         // if executing default.cfg for the first time, lock the cvar defaults
296         // it may seem backwards to insert this text BEFORE the default.cfg
297         // but Cbuf_InsertText inserts before, so this actually ends up after it.
298         if (!strcmp(Cmd_Argv(1), "default.cfg"))
299                 Cbuf_InsertText("\ncvar_lockdefaults\n");
300
301         // insert newline after the text to make sure the last line is terminated (some text editors omit the trailing newline)
302         // (note: insertion order here is backwards from execution order, so this adds it after the text, by calling it before...)
303         Cbuf_InsertText ("\n");
304         Cbuf_InsertText (f);
305         Mem_Free(f);
306 }
307
308
309 /*
310 ===============
311 Cmd_Echo_f
312
313 Just prints the rest of the line to the console
314 ===============
315 */
316 static void Cmd_Echo_f (void)
317 {
318         int             i;
319
320         for (i=1 ; i<Cmd_Argc() ; i++)
321                 Con_Printf("%s ",Cmd_Argv(i));
322         Con_Print("\n");
323 }
324
325 // DRESK - 5/14/06
326 // Support Doom3-style Toggle Console Command
327 /*
328 ===============
329 Cmd_Toggle_f
330
331 Toggles a specified console variable amongst the values specified (default is 0 and 1)
332 ===============
333 */
334 static void Cmd_Toggle_f(void)
335 {
336         // Acquire Number of Arguments
337         int nNumArgs = Cmd_Argc();
338
339         if(nNumArgs == 1)
340                 // No Arguments Specified; Print Usage
341                 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");
342         else
343         { // Correct Arguments Specified
344                 // Acquire Potential CVar
345                 cvar_t* cvCVar = Cvar_FindVar( Cmd_Argv(1) );
346
347                 if(cvCVar != NULL)
348                 { // Valid CVar
349                         if(nNumArgs == 2)
350                         { // Default Usage
351                                 if(cvCVar->integer)
352                                         Cvar_SetValueQuick(cvCVar, 0);
353                                 else
354                                         Cvar_SetValueQuick(cvCVar, 1);
355                         }
356                         else
357                         if(nNumArgs == 3)
358                         { // 0 and Specified Usage
359                                 if(cvCVar->integer == atoi(Cmd_Argv(2) ) )
360                                         // CVar is Specified Value; // Reset to 0
361                                         Cvar_SetValueQuick(cvCVar, 0);
362                                 else
363                                 if(cvCVar->integer == 0)
364                                         // CVar is 0; Specify Value
365                                         Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
366                                 else
367                                         // CVar does not match; Reset to 0
368                                         Cvar_SetValueQuick(cvCVar, 0);
369                         }
370                         else
371                         { // Variable Values Specified
372                                 int nCnt;
373                                 int bFound = 0;
374
375                                 for(nCnt = 2; nCnt < nNumArgs; nCnt++)
376                                 { // Cycle through Values
377                                         if( strcmp(cvCVar->string, Cmd_Argv(nCnt) ) == 0)
378                                         { // Current Value Located; Increment to Next
379                                                 if( (nCnt + 1) == nNumArgs)
380                                                         // Max Value Reached; Reset
381                                                         Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
382                                                 else
383                                                         // Next Value
384                                                         Cvar_SetQuick(cvCVar, Cmd_Argv(nCnt + 1) );
385
386                                                 // End Loop
387                                                 nCnt = nNumArgs;
388                                                 // Assign Found
389                                                 bFound = 1;
390                                         }
391                                 }
392                                 if(!bFound)
393                                         // Value not Found; Reset to Original
394                                         Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
395                         }
396
397                 }
398                 else
399                 { // Invalid CVar
400                         Con_Printf("ERROR : CVar '%s' not found\n", Cmd_Argv(2) );
401                 }
402         }
403 }
404
405 /*
406 ===============
407 Cmd_Alias_f
408
409 Creates a new command that executes a command string (possibly ; seperated)
410 ===============
411 */
412 static void Cmd_Alias_f (void)
413 {
414         cmdalias_t      *a;
415         char            cmd[MAX_INPUTLINE];
416         int                     i, c;
417         const char              *s;
418         size_t          alloclen;
419
420         if (Cmd_Argc() == 1)
421         {
422                 Con_Print("Current alias commands:\n");
423                 for (a = cmd_alias ; a ; a=a->next)
424                         Con_Printf("%s : %s\n", a->name, a->value);
425                 return;
426         }
427
428         s = Cmd_Argv(1);
429         if (strlen(s) >= MAX_ALIAS_NAME)
430         {
431                 Con_Print("Alias name is too long\n");
432                 return;
433         }
434
435         // if the alias already exists, reuse it
436         for (a = cmd_alias ; a ; a=a->next)
437         {
438                 if (!strcmp(s, a->name))
439                 {
440                         Z_Free (a->value);
441                         break;
442                 }
443         }
444
445         if (!a)
446         {
447                 cmdalias_t *prev, *current;
448
449                 a = (cmdalias_t *)Z_Malloc (sizeof(cmdalias_t));
450                 strlcpy (a->name, s, sizeof (a->name));
451                 // insert it at the right alphanumeric position
452                 for( prev = NULL, current = cmd_alias ; current && strcmp( current->name, a->name ) < 0 ; prev = current, current = current->next )
453                         ;
454                 if( prev ) {
455                         prev->next = a;
456                 } else {
457                         cmd_alias = a;
458                 }
459                 a->next = current;
460         }
461
462
463 // copy the rest of the command line
464         cmd[0] = 0;             // start out with a null string
465         c = Cmd_Argc();
466         for (i=2 ; i< c ; i++)
467         {
468                 strlcat (cmd, Cmd_Argv(i), sizeof (cmd));
469                 if (i != c)
470                         strlcat (cmd, " ", sizeof (cmd));
471         }
472         strlcat (cmd, "\n", sizeof (cmd));
473
474         alloclen = strlen (cmd) + 1;
475         a->value = (char *)Z_Malloc (alloclen);
476         memcpy (a->value, cmd, alloclen);
477 }
478
479 /*
480 =============================================================================
481
482                                         COMMAND EXECUTION
483
484 =============================================================================
485 */
486
487 typedef struct cmd_function_s
488 {
489         struct cmd_function_s *next;
490         const char *name;
491         const char *description;
492         xcommand_t consolefunction;
493         xcommand_t clientfunction;
494         qboolean csqcfunc;
495 } cmd_function_t;
496
497 static int cmd_argc;
498 static const char *cmd_argv[MAX_ARGS];
499 static const char *cmd_null_string = "";
500 static const char *cmd_args;
501 cmd_source_t cmd_source;
502
503
504 static cmd_function_t *cmd_functions;           // possible commands to execute
505
506 /*
507 Cmd_PreprocessString
508
509 Preprocesses strings and replaces $*, $param#, $cvar accordingly
510 */
511 static void Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias ) {
512         const char *in;
513         unsigned outlen;
514
515         // don't crash if there's no room in the outtext buffer
516         if( maxoutlen == 0 ) {
517                 return;
518         }
519         maxoutlen--; // because of \0
520
521         in = intext;
522         outlen = 0;
523
524         while( *in && outlen < maxoutlen ) {
525                 if( *in == '$' ) {
526                         // this is some kind of expansion, see what comes after the $
527                         in++;
528                         // replacements that can always be used:
529                         // $$ is replaced with $, to allow escaping $
530                         // $<cvarname> is replaced with the contents of the cvar
531                         //
532                         // the following can be used in aliases only:
533                         // $* is replaced with all formal parameters (including name of the alias - this probably is not desirable)
534                         // $0 is replaced with the name of this alias
535                         // $<number> is replaced with an argument to this alias (or copied as-is if no such parameter exists), can be multiple digits
536                         if( *in == '$' ) {
537                                 outtext[outlen++] = *in++;
538                         } else if( *in == '*' && alias ) {
539                                 const char *linein = Cmd_Args();
540
541                                 // include all parameters
542                                 if (linein) {
543                                         while( *linein && outlen < maxoutlen ) {
544                                                 outtext[outlen++] = *linein++;
545                                         }
546                                 }
547
548                                 in++;
549                         } else if( '0' <= *in && *in <= '9' && alias ) {
550                                 char *nexttoken;
551                                 int argnum;
552
553                                 argnum = strtol( in, &nexttoken, 10 );
554
555                                 if( 0 <= argnum && argnum < Cmd_Argc() ) {
556                                         const char *param = Cmd_Argv( argnum );
557                                         while( *param && outlen < maxoutlen ) {
558                                                 outtext[outlen++] = *param++;
559                                         }
560                                         in = nexttoken;
561                                 } else if( argnum >= Cmd_Argc() ) {
562                                         Con_Printf( "Warning: Not enough parameters passed to alias '%s', at least %i expected:\n    %s\n", alias->name, argnum, alias->value );
563                                         outtext[outlen++] = '$';
564                                 }
565                         } else {
566                                 cvar_t *cvar;
567                                 const char *tempin = in;
568
569                                 COM_ParseToken_Console( &tempin );
570                                 // don't expand rcon_password or similar cvars (CVAR_PRIVATE flag)
571                                 if ((cvar = Cvar_FindVar(&com_token[0])) && !(cvar->flags & CVAR_PRIVATE)) {
572                                         const char *cvarcontent = cvar->string;
573                                         while( *cvarcontent && outlen < maxoutlen ) {
574                                                 outtext[outlen++] = *cvarcontent++;
575                                         }
576                                         in = tempin;
577                                 } else {
578                                         if( alias ) {
579                                                 Con_Printf( "Warning: could not find cvar %s when expanding alias %s\n    %s\n", com_token, alias->name, alias->value );
580                                         } else {
581                                                 Con_Printf( "Warning: could not find cvar %s\n", com_token );
582                                         }
583                                         outtext[outlen++] = '$';
584                                 }
585                         }
586                 } else {
587                         outtext[outlen++] = *in++;
588                 }
589         }
590         outtext[outlen] = 0;
591 }
592
593 /*
594 ============
595 Cmd_ExecuteAlias
596
597 Called for aliases and fills in the alias into the cbuffer
598 ============
599 */
600 static void Cmd_ExecuteAlias (cmdalias_t *alias)
601 {
602         static char buffer[ MAX_INPUTLINE + 2 ];
603         Cmd_PreprocessString( alias->value, buffer, sizeof(buffer) - 2, alias );
604         // insert at start of command buffer, so that aliases execute in order
605         // (fixes bug introduced by Black on 20050705)
606         Cbuf_InsertText( buffer );
607 }
608
609 /*
610 ========
611 Cmd_List
612
613         CmdList Added by EvilTypeGuy eviltypeguy@qeradiant.com
614         Thanks to Matthias "Maddes" Buecher, http://www.inside3d.com/qip/
615
616 ========
617 */
618 static void Cmd_List_f (void)
619 {
620         cmd_function_t *cmd;
621         const char *partial;
622         int len, count;
623
624         if (Cmd_Argc() > 1)
625         {
626                 partial = Cmd_Argv (1);
627                 len = (int)strlen(partial);
628         }
629         else
630         {
631                 partial = NULL;
632                 len = 0;
633         }
634
635         count = 0;
636         for (cmd = cmd_functions; cmd; cmd = cmd->next)
637         {
638                 if (partial && strncmp(partial, cmd->name, len))
639                         continue;
640                 Con_Printf("%s : %s\n", cmd->name, cmd->description);
641                 count++;
642         }
643
644         if (partial)
645                 Con_Printf("%i Command%s beginning with \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
646         else
647                 Con_Printf("%i Command%s\n\n", count, (count > 1) ? "s" : "");
648 }
649
650 /*
651 ============
652 Cmd_Init
653 ============
654 */
655 void Cmd_Init (void)
656 {
657         cmd_mempool = Mem_AllocPool("commands", 0, NULL);
658         // space for commands and script files
659         cmd_text.data = cmd_text_buf;
660         cmd_text.maxsize = sizeof(cmd_text_buf);
661         cmd_text.cursize = 0;
662 }
663
664 void Cmd_Init_Commands (void)
665 {
666 //
667 // register our commands
668 //
669         Cmd_AddCommand ("stuffcmds",Cmd_StuffCmds_f, "execute commandline parameters (must be present in quake.rc script)");
670         Cmd_AddCommand ("exec",Cmd_Exec_f, "execute a script file");
671         Cmd_AddCommand ("echo",Cmd_Echo_f, "print a message to the console (useful in scripts)");
672         Cmd_AddCommand ("alias",Cmd_Alias_f, "create a script function (parameters are passed in as $1 through $9, and $* for all parameters)");
673         Cmd_AddCommand ("cmd", Cmd_ForwardToServer, "send a console commandline to the server (used by some mods)");
674         Cmd_AddCommand ("wait", Cmd_Wait_f, "make script execution wait for next rendered frame");
675         Cmd_AddCommand ("set", Cvar_Set_f, "create or change the value of a console variable");
676         Cmd_AddCommand ("seta", Cvar_SetA_f, "create or change the value of a console variable that will be saved to config.cfg");
677
678         // 2000-01-09 CmdList, CvarList commands By Matthias "Maddes" Buecher
679         // Added/Modified by EvilTypeGuy eviltypeguy@qeradiant.com
680         Cmd_AddCommand ("cmdlist", Cmd_List_f, "lists all console commands beginning with the specified prefix");
681         Cmd_AddCommand ("cvarlist", Cvar_List_f, "lists all console variables beginning with the specified prefix");
682
683         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");
684         Cmd_AddCommand ("cvar_resettodefaults_all", Cvar_ResetToDefaults_All_f, "sets all cvars to their locked default values");
685         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)");
686         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)");
687
688         // DRESK - 5/14/06
689         // Support Doom3-style Toggle Command
690         Cmd_AddCommand( "toggle", Cmd_Toggle_f, "toggles a console variable's values (use for more info)");
691 }
692
693 /*
694 ============
695 Cmd_Shutdown
696 ============
697 */
698 void Cmd_Shutdown(void)
699 {
700         Mem_FreePool(&cmd_mempool);
701 }
702
703 /*
704 ============
705 Cmd_Argc
706 ============
707 */
708 int             Cmd_Argc (void)
709 {
710         return cmd_argc;
711 }
712
713 /*
714 ============
715 Cmd_Argv
716 ============
717 */
718 const char *Cmd_Argv (int arg)
719 {
720         if (arg >= cmd_argc )
721                 return cmd_null_string;
722         return cmd_argv[arg];
723 }
724
725 /*
726 ============
727 Cmd_Args
728 ============
729 */
730 const char *Cmd_Args (void)
731 {
732         return cmd_args;
733 }
734
735
736 /*
737 ============
738 Cmd_TokenizeString
739
740 Parses the given string into command line tokens.
741 ============
742 */
743 // AK: This function should only be called from ExcuteString because the current design is a bit of an hack
744 static void Cmd_TokenizeString (const char *text)
745 {
746         int l;
747
748         cmd_argc = 0;
749         cmd_args = NULL;
750
751         while (1)
752         {
753                 // skip whitespace up to a /n
754                 while (*text && *text <= ' ' && *text != '\r' && *text != '\n')
755                         text++;
756
757                 // line endings:
758                 // UNIX: \n
759                 // Mac: \r
760                 // Windows: \r\n
761                 if (*text == '\n' || *text == '\r')
762                 {
763                         // a newline separates commands in the buffer
764                         if (*text == '\r' && text[1] == '\n')
765                                 text++;
766                         text++;
767                         break;
768                 }
769
770                 if (!*text)
771                         return;
772
773                 if (cmd_argc == 1)
774                         cmd_args = text;
775
776                 if (!COM_ParseToken_Console(&text))
777                         return;
778
779                 if (cmd_argc < MAX_ARGS)
780                 {
781                         l = (int)strlen(com_token) + 1;
782                         if (cmd_tokenizebufferpos + l > CMD_TOKENIZELENGTH)
783                         {
784                                 Con_Printf("Cmd_TokenizeString: ran out of %i character buffer space for command arguements\n", CMD_TOKENIZELENGTH);
785                                 break;
786                         }
787                         memcpy (cmd_tokenizebuffer + cmd_tokenizebufferpos, com_token, l);
788                         cmd_argv[cmd_argc] = cmd_tokenizebuffer + cmd_tokenizebufferpos;
789                         cmd_tokenizebufferpos += l;
790                         cmd_argc++;
791                 }
792         }
793 }
794
795
796 /*
797 ============
798 Cmd_AddCommand
799 ============
800 */
801 void Cmd_AddCommand_WithClientCommand (const char *cmd_name, xcommand_t consolefunction, xcommand_t clientfunction, const char *description)
802 {
803         cmd_function_t *cmd;
804         cmd_function_t *prev, *current;
805
806 // fail if the command is a variable name
807         if (Cvar_FindVar( cmd_name ))
808         {
809                 Con_Printf("Cmd_AddCommand: %s already defined as a var\n", cmd_name);
810                 return;
811         }
812
813 // fail if the command already exists
814         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
815         {
816                 if (!strcmp (cmd_name, cmd->name))
817                 {
818                         if (consolefunction || clientfunction)
819                         {
820                                 Con_Printf("Cmd_AddCommand: %s already defined\n", cmd_name);
821                                 return;
822                         }
823                         else    //[515]: csqc
824                         {
825                                 cmd->csqcfunc = true;
826                                 return;
827                         }
828                 }
829         }
830
831         cmd = (cmd_function_t *)Mem_Alloc(cmd_mempool, sizeof(cmd_function_t));
832         cmd->name = cmd_name;
833         cmd->consolefunction = consolefunction;
834         cmd->clientfunction = clientfunction;
835         cmd->description = description;
836         if(!consolefunction && !clientfunction)                 //[515]: csqc
837                 cmd->csqcfunc = true;
838         cmd->next = cmd_functions;
839
840 // insert it at the right alphanumeric position
841         for( prev = NULL, current = cmd_functions ; current && strcmp( current->name, cmd->name ) < 0 ; prev = current, current = current->next )
842                 ;
843         if( prev ) {
844                 prev->next = cmd;
845         } else {
846                 cmd_functions = cmd;
847         }
848         cmd->next = current;
849 }
850
851 void Cmd_AddCommand (const char *cmd_name, xcommand_t function, const char *description)
852 {
853         Cmd_AddCommand_WithClientCommand (cmd_name, function, NULL, description);
854 }
855
856 /*
857 ============
858 Cmd_Exists
859 ============
860 */
861 qboolean Cmd_Exists (const char *cmd_name)
862 {
863         cmd_function_t  *cmd;
864
865         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
866                 if (!strcmp (cmd_name,cmd->name))
867                         return true;
868
869         return false;
870 }
871
872
873 /*
874 ============
875 Cmd_CompleteCommand
876 ============
877 */
878 const char *Cmd_CompleteCommand (const char *partial)
879 {
880         cmd_function_t *cmd;
881         size_t len;
882
883         len = strlen(partial);
884
885         if (!len)
886                 return NULL;
887
888 // check functions
889         for (cmd = cmd_functions; cmd; cmd = cmd->next)
890                 if (!strncasecmp(partial, cmd->name, len))
891                         return cmd->name;
892
893         return NULL;
894 }
895
896 /*
897         Cmd_CompleteCountPossible
898
899         New function for tab-completion system
900         Added by EvilTypeGuy
901         Thanks to Fett erich@heintz.com
902         Thanks to taniwha
903
904 */
905 int Cmd_CompleteCountPossible (const char *partial)
906 {
907         cmd_function_t *cmd;
908         size_t len;
909         int h;
910
911         h = 0;
912         len = strlen(partial);
913
914         if (!len)
915                 return 0;
916
917         // Loop through the command list and count all partial matches
918         for (cmd = cmd_functions; cmd; cmd = cmd->next)
919                 if (!strncasecmp(partial, cmd->name, len))
920                         h++;
921
922         return h;
923 }
924
925 /*
926         Cmd_CompleteBuildList
927
928         New function for tab-completion system
929         Added by EvilTypeGuy
930         Thanks to Fett erich@heintz.com
931         Thanks to taniwha
932
933 */
934 const char **Cmd_CompleteBuildList (const char *partial)
935 {
936         cmd_function_t *cmd;
937         size_t len = 0;
938         size_t bpos = 0;
939         size_t sizeofbuf = (Cmd_CompleteCountPossible (partial) + 1) * sizeof (const char *);
940         const char **buf;
941
942         len = strlen(partial);
943         buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
944         // Loop through the alias list and print all matches
945         for (cmd = cmd_functions; cmd; cmd = cmd->next)
946                 if (!strncasecmp(partial, cmd->name, len))
947                         buf[bpos++] = cmd->name;
948
949         buf[bpos] = NULL;
950         return buf;
951 }
952
953 // written by LordHavoc
954 void Cmd_CompleteCommandPrint (const char *partial)
955 {
956         cmd_function_t *cmd;
957         size_t len = strlen(partial);
958         // Loop through the command list and print all matches
959         for (cmd = cmd_functions; cmd; cmd = cmd->next)
960                 if (!strncasecmp(partial, cmd->name, len))
961                         Con_Printf("%s : %s\n", cmd->name, cmd->description);
962 }
963
964 /*
965         Cmd_CompleteAlias
966
967         New function for tab-completion system
968         Added by EvilTypeGuy
969         Thanks to Fett erich@heintz.com
970         Thanks to taniwha
971
972 */
973 const char *Cmd_CompleteAlias (const char *partial)
974 {
975         cmdalias_t *alias;
976         size_t len;
977
978         len = strlen(partial);
979
980         if (!len)
981                 return NULL;
982
983         // Check functions
984         for (alias = cmd_alias; alias; alias = alias->next)
985                 if (!strncasecmp(partial, alias->name, len))
986                         return alias->name;
987
988         return NULL;
989 }
990
991 // written by LordHavoc
992 void Cmd_CompleteAliasPrint (const char *partial)
993 {
994         cmdalias_t *alias;
995         size_t len = strlen(partial);
996         // Loop through the alias list and print all matches
997         for (alias = cmd_alias; alias; alias = alias->next)
998                 if (!strncasecmp(partial, alias->name, len))
999                         Con_Printf("%s : %s\n", alias->name, alias->value);
1000 }
1001
1002
1003 /*
1004         Cmd_CompleteAliasCountPossible
1005
1006         New function for tab-completion system
1007         Added by EvilTypeGuy
1008         Thanks to Fett erich@heintz.com
1009         Thanks to taniwha
1010
1011 */
1012 int Cmd_CompleteAliasCountPossible (const char *partial)
1013 {
1014         cmdalias_t      *alias;
1015         size_t          len;
1016         int                     h;
1017
1018         h = 0;
1019
1020         len = strlen(partial);
1021
1022         if (!len)
1023                 return 0;
1024
1025         // Loop through the command list and count all partial matches
1026         for (alias = cmd_alias; alias; alias = alias->next)
1027                 if (!strncasecmp(partial, alias->name, len))
1028                         h++;
1029
1030         return h;
1031 }
1032
1033 /*
1034         Cmd_CompleteAliasBuildList
1035
1036         New function for tab-completion system
1037         Added by EvilTypeGuy
1038         Thanks to Fett erich@heintz.com
1039         Thanks to taniwha
1040
1041 */
1042 const char **Cmd_CompleteAliasBuildList (const char *partial)
1043 {
1044         cmdalias_t *alias;
1045         size_t len = 0;
1046         size_t bpos = 0;
1047         size_t sizeofbuf = (Cmd_CompleteAliasCountPossible (partial) + 1) * sizeof (const char *);
1048         const char **buf;
1049
1050         len = strlen(partial);
1051         buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1052         // Loop through the alias list and print all matches
1053         for (alias = cmd_alias; alias; alias = alias->next)
1054                 if (!strncasecmp(partial, alias->name, len))
1055                         buf[bpos++] = alias->name;
1056
1057         buf[bpos] = NULL;
1058         return buf;
1059 }
1060
1061 void Cmd_ClearCsqcFuncs (void)
1062 {
1063         cmd_function_t *cmd;
1064         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1065                 cmd->csqcfunc = false;
1066 }
1067
1068 qboolean CL_VM_ConsoleCommand (const char *cmd);
1069 /*
1070 ============
1071 Cmd_ExecuteString
1072
1073 A complete command line has been parsed, so try to execute it
1074 FIXME: lookupnoadd the token to speed search?
1075 ============
1076 */
1077 void Cmd_ExecuteString (const char *text, cmd_source_t src)
1078 {
1079         int oldpos;
1080         cmd_function_t *cmd;
1081         cmdalias_t *a;
1082
1083         oldpos = cmd_tokenizebufferpos;
1084         cmd_source = src;
1085
1086         Cmd_TokenizeString (text);
1087
1088 // execute the command line
1089         if (!Cmd_Argc())
1090         {
1091                 cmd_tokenizebufferpos = oldpos;
1092                 return;         // no tokens
1093         }
1094
1095 // check functions
1096         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1097         {
1098                 if (!strcasecmp (cmd_argv[0],cmd->name))
1099                 {
1100                         if (cmd->csqcfunc && CL_VM_ConsoleCommand (text))       //[515]: csqc
1101                                 return;
1102                         switch (src)
1103                         {
1104                         case src_command:
1105                                 if (cmd->consolefunction)
1106                                         cmd->consolefunction ();
1107                                 else if (cmd->clientfunction)
1108                                 {
1109                                         if (cls.state == ca_connected)
1110                                         {
1111                                                 // forward remote commands to the server for execution
1112                                                 Cmd_ForwardToServer();
1113                                         }
1114                                         else
1115                                                 Con_Printf("Can not send command \"%s\", not connected.\n", Cmd_Argv(0));
1116                                 }
1117                                 else
1118                                         Con_Printf("Command \"%s\" can not be executed\n", Cmd_Argv(0));
1119                                 cmd_tokenizebufferpos = oldpos;
1120                                 return;
1121                         case src_client:
1122                                 if (cmd->clientfunction)
1123                                 {
1124                                         cmd->clientfunction ();
1125                                         cmd_tokenizebufferpos = oldpos;
1126                                         return;
1127                                 }
1128                                 break;
1129                         }
1130                         break;
1131                 }
1132         }
1133
1134         // if it's a client command and no command was found, say so.
1135         if (cmd_source == src_client)
1136         {
1137                 Con_Printf("player \"%s\" tried to %s\n", host_client->name, text);
1138                 return;
1139         }
1140
1141 // check alias
1142         for (a=cmd_alias ; a ; a=a->next)
1143         {
1144                 if (!strcasecmp (cmd_argv[0], a->name))
1145                 {
1146                         Cmd_ExecuteAlias(a);
1147                         cmd_tokenizebufferpos = oldpos;
1148                         return;
1149                 }
1150         }
1151
1152 // check cvars
1153         if (!Cvar_Command () && host_framecount > 0)
1154                 Con_Printf("Unknown command \"%s\"\n", Cmd_Argv(0));
1155
1156         cmd_tokenizebufferpos = oldpos;
1157 }
1158
1159
1160 /*
1161 ===================
1162 Cmd_ForwardStringToServer
1163
1164 Sends an entire command string over to the server, unprocessed
1165 ===================
1166 */
1167 void Cmd_ForwardStringToServer (const char *s)
1168 {
1169         char temp[128];
1170         if (cls.state != ca_connected)
1171         {
1172                 Con_Printf("Can't \"%s\", not connected\n", s);
1173                 return;
1174         }
1175
1176         if (!cls.netcon)
1177                 return;
1178
1179         // LordHavoc: thanks to Fuh for bringing the pure evil of SZ_Print to my
1180         // attention, it has been eradicated from here, its only (former) use in
1181         // all of darkplaces.
1182         if (cls.protocol == PROTOCOL_QUAKEWORLD)
1183                 MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
1184         else
1185                 MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
1186         if ((!strncmp(s, "say ", 4) || !strncmp(s, "say_team ", 9)) && cl_locs_enable.integer)
1187         {
1188                 // say/say_team commands can replace % character codes with status info
1189                 while (*s)
1190                 {
1191                         if (*s == '%' && s[1])
1192                         {
1193                                 // handle proquake message macros
1194                                 temp[0] = 0;
1195                                 switch (s[1])
1196                                 {
1197                                 case 'l': // current location
1198                                         CL_Locs_FindLocationName(temp, sizeof(temp), cl.movement_origin);
1199                                         break;
1200                                 case 'h': // current health
1201                                         dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_HEALTH]);
1202                                         break;
1203                                 case 'a': // current armor
1204                                         dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ARMOR]);
1205                                         break;
1206                                 case 'x': // current rockets
1207                                         dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ROCKETS]);
1208                                         break;
1209                                 case 'c': // current cells
1210                                         dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_CELLS]);
1211                                         break;
1212                                 // silly proquake macros
1213                                 case 'd': // loc at last death
1214                                         CL_Locs_FindLocationName(temp, sizeof(temp), cl.lastdeathorigin);
1215                                         break;
1216                                 case 't': // current time
1217                                         dpsnprintf(temp, sizeof(temp), "%.0f:%.0f", floor(cl.time / 60), cl.time - floor(cl.time / 60) * 60);
1218                                         break;
1219                                 case 'r': // rocket launcher status ("I have RL", "I need rockets", "I need RL")
1220                                         if (!(cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER))
1221                                                 dpsnprintf(temp, sizeof(temp), "I need RL");
1222                                         else if (!cl.stats[STAT_ROCKETS])
1223                                                 dpsnprintf(temp, sizeof(temp), "I need rockets");
1224                                         else
1225                                                 dpsnprintf(temp, sizeof(temp), "I have RL");
1226                                         break;
1227                                 case 'p': // powerup status (outputs "quad" "pent" and "eyes" according to status)
1228                                         if (cl.stats[STAT_ITEMS] & IT_QUAD)
1229                                         {
1230                                                 if (temp[0])
1231                                                         strlcat(temp, " ", sizeof(temp));
1232                                                 strlcat(temp, "quad", sizeof(temp));
1233                                         }
1234                                         if (cl.stats[STAT_ITEMS] & IT_INVULNERABILITY)
1235                                         {
1236                                                 if (temp[0])
1237                                                         strlcat(temp, " ", sizeof(temp));
1238                                                 strlcat(temp, "pent", sizeof(temp));
1239                                         }
1240                                         if (cl.stats[STAT_ITEMS] & IT_INVISIBILITY)
1241                                         {
1242                                                 if (temp[0])
1243                                                         strlcat(temp, " ", sizeof(temp));
1244                                                 strlcat(temp, "eyes", sizeof(temp));
1245                                         }
1246                                         break;
1247                                 case 'w': // weapon status (outputs "SSG:NG:SNG:GL:RL:LG" with the text between : characters omitted if you lack the weapon)
1248                                         if (cl.stats[STAT_ITEMS] & IT_SUPER_SHOTGUN)
1249                                                 strlcat(temp, "SSG", sizeof(temp));
1250                                         strlcat(temp, ":", sizeof(temp));
1251                                         if (cl.stats[STAT_ITEMS] & IT_NAILGUN)
1252                                                 strlcat(temp, "NG", sizeof(temp));
1253                                         strlcat(temp, ":", sizeof(temp));
1254                                         if (cl.stats[STAT_ITEMS] & IT_SUPER_NAILGUN)
1255                                                 strlcat(temp, "SNG", sizeof(temp));
1256                                         strlcat(temp, ":", sizeof(temp));
1257                                         if (cl.stats[STAT_ITEMS] & IT_GRENADE_LAUNCHER)
1258                                                 strlcat(temp, "GL", sizeof(temp));
1259                                         strlcat(temp, ":", sizeof(temp));
1260                                         if (cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER)
1261                                                 strlcat(temp, "RL", sizeof(temp));
1262                                         strlcat(temp, ":", sizeof(temp));
1263                                         if (cl.stats[STAT_ITEMS] & IT_LIGHTNING)
1264                                                 strlcat(temp, "LG", sizeof(temp));
1265                                         break;
1266                                 default:
1267                                         // not a recognized macro, print it as-is...
1268                                         temp[0] = s[0];
1269                                         temp[1] = s[1];
1270                                         temp[2] = 0;
1271                                         break;
1272                                 }
1273                                 // write the resulting text
1274                                 SZ_Write(&cls.netcon->message, (unsigned char *)temp, strlen(temp));
1275                                 s += 2;
1276                                 continue;
1277                         }
1278                         MSG_WriteByte(&cls.netcon->message, *s);
1279                         s++;
1280                 }
1281                 MSG_WriteByte(&cls.netcon->message, 0);
1282         }
1283         else // any other command is passed on as-is
1284                 SZ_Write(&cls.netcon->message, (const unsigned char *)s, (int)strlen(s) + 1);
1285 }
1286
1287 /*
1288 ===================
1289 Cmd_ForwardToServer
1290
1291 Sends the entire command line over to the server
1292 ===================
1293 */
1294 void Cmd_ForwardToServer (void)
1295 {
1296         const char *s;
1297         if (!strcasecmp(Cmd_Argv(0), "cmd"))
1298         {
1299                 // we want to strip off "cmd", so just send the args
1300                 s = Cmd_Argc() > 1 ? Cmd_Args() : "";
1301         }
1302         else
1303         {
1304                 // we need to keep the command name, so send Cmd_Argv(0), a space and then Cmd_Args()
1305                 s = va("%s %s", Cmd_Argv(0), Cmd_Argc() > 1 ? Cmd_Args() : "");
1306         }
1307         // don't send an empty forward message if the user tries "cmd" by itself
1308         if (!s || !*s)
1309                 return;
1310         Cmd_ForwardStringToServer(s);
1311 }
1312
1313
1314 /*
1315 ================
1316 Cmd_CheckParm
1317
1318 Returns the position (1 to argc-1) in the command's argument list
1319 where the given parameter apears, or 0 if not present
1320 ================
1321 */
1322
1323 int Cmd_CheckParm (const char *parm)
1324 {
1325         int i;
1326
1327         if (!parm)
1328         {
1329                 Con_Printf ("Cmd_CheckParm: NULL");
1330                 return 0;
1331         }
1332
1333         for (i = 1; i < Cmd_Argc (); i++)
1334                 if (!strcasecmp (parm, Cmd_Argv (i)))
1335                         return i;
1336
1337         return 0;
1338 }
1339