]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - cmd.c
a911fb346fd6de24a57f7af1912593cffa637ce3
[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 ( !quotes &&  text[i] == ';')
163                                 break;  // don't break if inside a quoted string
164                         if (text[i] == '\r' || text[i] == '\n')
165                                 break;
166                 }
167
168                 memcpy (line, text, i);
169                 line[i] = 0;
170
171 // delete the text from the command buffer and move remaining commands down
172 // this is necessary because commands (exec, alias) can insert data at the
173 // beginning of the text buffer
174
175                 if (i == cmd_text.cursize)
176                         cmd_text.cursize = 0;
177                 else
178                 {
179                         i++;
180                         cmd_text.cursize -= i;
181                         memcpy (cmd_text.data, text+i, cmd_text.cursize);
182                 }
183
184 // execute the command line
185                 Cmd_PreprocessString( line, preprocessed, sizeof(preprocessed), NULL );
186                 Cmd_ExecuteString (preprocessed, src_command);
187
188                 if (cmd_wait)
189                 {       // skip out while text still remains in buffer, leaving it
190                         // for next frame
191                         cmd_wait = false;
192                         break;
193                 }
194         }
195 }
196
197 /*
198 ==============================================================================
199
200                                                 SCRIPT COMMANDS
201
202 ==============================================================================
203 */
204
205 /*
206 ===============
207 Cmd_StuffCmds_f
208
209 Adds command line parameters as script statements
210 Commands lead with a +, and continue until a - or another +
211 quake +prog jctest.qp +cmd amlev1
212 quake -nosound +cmd amlev1
213 ===============
214 */
215 qboolean host_stuffcmdsrun = false;
216 void Cmd_StuffCmds_f (void)
217 {
218         int             i, j, l;
219         // this is per command, and bounds checked (no buffer overflows)
220         char    build[MAX_INPUTLINE];
221
222         if (Cmd_Argc () != 1)
223         {
224                 Con_Print("stuffcmds : execute command line parameters\n");
225                 return;
226         }
227
228         host_stuffcmdsrun = true;
229         for (i = 0;i < com_argc;i++)
230         {
231                 if (com_argv[i] && com_argv[i][0] == '+' && (com_argv[i][1] < '0' || com_argv[i][1] > '9'))
232                 {
233                         l = 0;
234                         j = 1;
235                         while (com_argv[i][j])
236                                 build[l++] = com_argv[i][j++];
237                         i++;
238                         for (;i < com_argc;i++)
239                         {
240                                 if (!com_argv[i])
241                                         continue;
242                                 if ((com_argv[i][0] == '+' || com_argv[i][0] == '-') && (com_argv[i][1] < '0' || com_argv[i][1] > '9'))
243                                         break;
244                                 if (l + strlen(com_argv[i]) + 5 > sizeof(build))
245                                         break;
246                                 build[l++] = ' ';
247                                 build[l++] = '\"';
248                                 for (j = 0;com_argv[i][j];j++)
249                                         build[l++] = com_argv[i][j];
250                                 build[l++] = '\"';
251                         }
252                         build[l++] = '\n';
253                         build[l++] = 0;
254                         Cbuf_InsertText (build);
255                         i--;
256                 }
257         }
258 }
259
260
261 /*
262 ===============
263 Cmd_Exec_f
264 ===============
265 */
266 static void Cmd_Exec_f (void)
267 {
268         char *f;
269
270         if (Cmd_Argc () != 2)
271         {
272                 Con_Print("exec <filename> : execute a script file\n");
273                 return;
274         }
275
276         f = (char *)FS_LoadFile (Cmd_Argv(1), tempmempool, false, NULL);
277         if (!f)
278         {
279                 Con_Printf("couldn't exec %s\n",Cmd_Argv(1));
280                 return;
281         }
282         Con_DPrintf("execing %s\n",Cmd_Argv(1));
283
284         // if executing default.cfg for the first time, lock the cvar defaults
285         // it may seem backwards to insert this text BEFORE the default.cfg
286         // but Cbuf_InsertText inserts before, so this actually ends up after it.
287         if (!strcmp(Cmd_Argv(1), "default.cfg"))
288                 Cbuf_InsertText("\ncvar_lockdefaults\n");
289
290         // insert newline after the text to make sure the last line is terminated (some text editors omit the trailing newline)
291         // (note: insertion order here is backwards from execution order, so this adds it after the text, by calling it before...)
292         Cbuf_InsertText ("\n");
293         Cbuf_InsertText (f);
294         Mem_Free(f);
295 }
296
297
298 /*
299 ===============
300 Cmd_Echo_f
301
302 Just prints the rest of the line to the console
303 ===============
304 */
305 static void Cmd_Echo_f (void)
306 {
307         int             i;
308
309         for (i=1 ; i<Cmd_Argc() ; i++)
310                 Con_Printf("%s ",Cmd_Argv(i));
311         Con_Print("\n");
312 }
313
314 // DRESK - 5/14/06
315 // Support Doom3-style Toggle Console Command
316 /*
317 ===============
318 Cmd_Toggle_f
319
320 Toggles a specified console variable amongst the values specified (default is 0 and 1)
321 ===============
322 */
323 static void Cmd_Toggle_f(void)
324 {
325         // Acquire Number of Arguments
326         int nNumArgs = Cmd_Argc();
327
328         if(nNumArgs == 1)
329                 // No Arguments Specified; Print Usage
330                 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");
331         else
332         { // Correct Arguments Specified
333                 // Acquire Potential CVar
334                 cvar_t* cvCVar = Cvar_FindVar( Cmd_Argv(1) );
335
336                 if(cvCVar != NULL)
337                 { // Valid CVar
338                         if(nNumArgs == 2)
339                         { // Default Usage
340                                 if(cvCVar->integer)
341                                         Cvar_SetValueQuick(cvCVar, 0);
342                                 else
343                                         Cvar_SetValueQuick(cvCVar, 1);
344                         }
345                         else
346                         if(nNumArgs == 3)
347                         { // 0 and Specified Usage
348                                 if(cvCVar->integer == atoi(Cmd_Argv(2) ) )
349                                         // CVar is Specified Value; // Reset to 0
350                                         Cvar_SetValueQuick(cvCVar, 0);
351                                 else
352                                 if(cvCVar->integer == 0)
353                                         // CVar is 0; Specify Value
354                                         Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
355                                 else
356                                         // CVar does not match; Reset to 0
357                                         Cvar_SetValueQuick(cvCVar, 0);
358                         }
359                         else
360                         { // Variable Values Specified
361                                 int nCnt;
362                                 int bFound = 0;
363
364                                 for(nCnt = 2; nCnt < nNumArgs; nCnt++)
365                                 { // Cycle through Values
366                                         if( strcmp(cvCVar->string, Cmd_Argv(nCnt) ) == 0)
367                                         { // Current Value Located; Increment to Next
368                                                 if( (nCnt + 1) == nNumArgs)
369                                                         // Max Value Reached; Reset
370                                                         Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
371                                                 else
372                                                         // Next Value
373                                                         Cvar_SetQuick(cvCVar, Cmd_Argv(nCnt + 1) );
374
375                                                 // End Loop
376                                                 nCnt = nNumArgs;
377                                                 // Assign Found
378                                                 bFound = 1;
379                                         }
380                                 }
381                                 if(!bFound)
382                                         // Value not Found; Reset to Original
383                                         Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
384                         }
385
386                 }
387                 else
388                 { // Invalid CVar
389                         Con_Printf("ERROR : CVar '%s' not found\n", Cmd_Argv(2) );
390                 }
391         }
392 }
393
394 /*
395 ===============
396 Cmd_Alias_f
397
398 Creates a new command that executes a command string (possibly ; seperated)
399 ===============
400 */
401 static void Cmd_Alias_f (void)
402 {
403         cmdalias_t      *a;
404         char            cmd[MAX_INPUTLINE];
405         int                     i, c;
406         const char              *s;
407         size_t          alloclen;
408
409         if (Cmd_Argc() == 1)
410         {
411                 Con_Print("Current alias commands:\n");
412                 for (a = cmd_alias ; a ; a=a->next)
413                         Con_Printf("%s : %s\n", a->name, a->value);
414                 return;
415         }
416
417         s = Cmd_Argv(1);
418         if (strlen(s) >= MAX_ALIAS_NAME)
419         {
420                 Con_Print("Alias name is too long\n");
421                 return;
422         }
423
424         // if the alias already exists, reuse it
425         for (a = cmd_alias ; a ; a=a->next)
426         {
427                 if (!strcmp(s, a->name))
428                 {
429                         Z_Free (a->value);
430                         break;
431                 }
432         }
433
434         if (!a)
435         {
436                 cmdalias_t *prev, *current;
437
438                 a = (cmdalias_t *)Z_Malloc (sizeof(cmdalias_t));
439                 strlcpy (a->name, s, sizeof (a->name));
440                 // insert it at the right alphanumeric position
441                 for( prev = NULL, current = cmd_alias ; current && strcmp( current->name, a->name ) < 0 ; prev = current, current = current->next )
442                         ;
443                 if( prev ) {
444                         prev->next = a;
445                 } else {
446                         cmd_alias = a;
447                 }
448                 a->next = current;
449         }
450
451
452 // copy the rest of the command line
453         cmd[0] = 0;             // start out with a null string
454         c = Cmd_Argc();
455         for (i=2 ; i< c ; i++)
456         {
457                 strlcat (cmd, Cmd_Argv(i), sizeof (cmd));
458                 if (i != c)
459                         strlcat (cmd, " ", sizeof (cmd));
460         }
461         strlcat (cmd, "\n", sizeof (cmd));
462
463         alloclen = strlen (cmd) + 1;
464         a->value = (char *)Z_Malloc (alloclen);
465         memcpy (a->value, cmd, alloclen);
466 }
467
468 /*
469 =============================================================================
470
471                                         COMMAND EXECUTION
472
473 =============================================================================
474 */
475
476 typedef struct cmd_function_s
477 {
478         struct cmd_function_s *next;
479         const char *name;
480         const char *description;
481         xcommand_t function;
482         qboolean csqcfunc;
483 } cmd_function_t;
484
485 static int cmd_argc;
486 static const char *cmd_argv[MAX_ARGS];
487 static const char *cmd_null_string = "";
488 static const char *cmd_args;
489 cmd_source_t cmd_source;
490
491
492 static cmd_function_t *cmd_functions;           // possible commands to execute
493
494 /*
495 Cmd_PreprocessString
496
497 Preprocesses strings and replaces $*, $param#, $cvar accordingly
498 */
499 static void Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias ) {
500         const char *in;
501         unsigned outlen;
502         int inquote;
503
504         // don't crash if there's no room in the outtext buffer
505         if( maxoutlen == 0 ) {
506                 return;
507         }
508         maxoutlen--; // because of \0
509
510         in = intext;
511         outlen = 0;
512         inquote = 0;
513
514         while( *in && outlen < maxoutlen ) {
515                 if( *in == '$' && !inquote ) {
516                         // this is some kind of expansion, see what comes after the $
517                         in++;
518                         // replacements that can always be used:
519                         // $$ is replaced with $, to allow escaping $
520                         // $<cvarname> is replaced with the contents of the cvar
521                         //
522                         // the following can be used in aliases only:
523                         // $* is replaced with all formal parameters (including name of the alias - this probably is not desirable)
524                         // $0 is replaced with the name of this alias
525                         // $<number> is replaced with an argument to this alias (or copied as-is if no such parameter exists), can be multiple digits
526                         if( *in == '$' ) {
527                                 outtext[outlen++] = *in++;
528                         } else if( *in == '*' && alias ) {
529                                 const char *linein = Cmd_Args();
530
531                                 // include all parameters
532                                 if (linein) {
533                                         while( *linein && outlen < maxoutlen ) {
534                                                 outtext[outlen++] = *linein++;
535                                         }
536                                 }
537
538                                 in++;
539                         } else if( '0' <= *in && *in <= '9' && alias ) {
540                                 char *nexttoken;
541                                 int argnum;
542
543                                 argnum = strtol( in, &nexttoken, 10 );
544
545                                 if( 0 <= argnum && argnum < Cmd_Argc() ) {
546                                         const char *param = Cmd_Argv( argnum );
547                                         while( *param && outlen < maxoutlen ) {
548                                                 outtext[outlen++] = *param++;
549                                         }
550                                         in = nexttoken;
551                                 } else if( argnum >= Cmd_Argc() ) {
552                                         Con_Printf( "Warning: Not enough parameters passed to alias '%s', at least %i expected:\n    %s\n", alias->name, argnum, alias->value );
553                                         outtext[outlen++] = '$';
554                                 }
555                         } else {
556                                 cvar_t *cvar;
557                                 const char *tempin = in;
558
559                                 COM_ParseTokenConsole( &tempin );
560                                 // don't expand rcon_password or similar cvars (CVAR_PRIVATE flag)
561                                 if ((cvar = Cvar_FindVar(&com_token[0])) && !(cvar->flags & CVAR_PRIVATE)) {
562                                         const char *cvarcontent = cvar->string;
563                                         while( *cvarcontent && outlen < maxoutlen ) {
564                                                 outtext[outlen++] = *cvarcontent++;
565                                         }
566                                         in = tempin;
567                                 } else {
568                                         if( alias ) {
569                                                 Con_Printf( "Warning: could not find cvar %s when expanding alias %s\n    %s\n", com_token, alias->name, alias->value );
570                                         } else {
571                                                 Con_Printf( "Warning: could not find cvar %s\n", com_token );
572                                         }
573                                         outtext[outlen++] = '$';
574                                 }
575                         }
576                 } else {
577                         if( *in == '"' ) {
578                                 inquote ^= 1;
579                         }
580                         outtext[outlen++] = *in++;
581                 }
582         }
583         outtext[outlen] = 0;
584 }
585
586 /*
587 ============
588 Cmd_ExecuteAlias
589
590 Called for aliases and fills in the alias into the cbuffer
591 ============
592 */
593 static void Cmd_ExecuteAlias (cmdalias_t *alias)
594 {
595         static char buffer[ MAX_INPUTLINE + 2 ];
596         Cmd_PreprocessString( alias->value, buffer, sizeof(buffer) - 2, alias );
597         // insert at start of command buffer, so that aliases execute in order
598         // (fixes bug introduced by Black on 20050705)
599         Cbuf_InsertText( buffer );
600 }
601
602 /*
603 ========
604 Cmd_List
605
606         CmdList Added by EvilTypeGuy eviltypeguy@qeradiant.com
607         Thanks to Matthias "Maddes" Buecher, http://www.inside3d.com/qip/
608
609 ========
610 */
611 static void Cmd_List_f (void)
612 {
613         cmd_function_t *cmd;
614         const char *partial;
615         int len, count;
616
617         if (Cmd_Argc() > 1)
618         {
619                 partial = Cmd_Argv (1);
620                 len = (int)strlen(partial);
621         }
622         else
623         {
624                 partial = NULL;
625                 len = 0;
626         }
627
628         count = 0;
629         for (cmd = cmd_functions; cmd; cmd = cmd->next)
630         {
631                 if (partial && strncmp(partial, cmd->name, len))
632                         continue;
633                 Con_Printf("%s : %s\n", cmd->name, cmd->description);
634                 count++;
635         }
636
637         if (partial)
638                 Con_Printf("%i Command%s beginning with \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
639         else
640                 Con_Printf("%i Command%s\n\n", count, (count > 1) ? "s" : "");
641 }
642
643 /*
644 ============
645 Cmd_Init
646 ============
647 */
648 void Cmd_Init (void)
649 {
650         cmd_mempool = Mem_AllocPool("commands", 0, NULL);
651         // space for commands and script files
652         cmd_text.data = cmd_text_buf;
653         cmd_text.maxsize = sizeof(cmd_text_buf);
654         cmd_text.cursize = 0;
655 }
656
657 void Cmd_Init_Commands (void)
658 {
659 //
660 // register our commands
661 //
662         Cmd_AddCommand ("stuffcmds",Cmd_StuffCmds_f, "execute commandline parameters (must be present in quake.rc script)");
663         Cmd_AddCommand ("exec",Cmd_Exec_f, "execute a script file");
664         Cmd_AddCommand ("echo",Cmd_Echo_f, "print a message to the console (useful in scripts)");
665         Cmd_AddCommand ("alias",Cmd_Alias_f, "create a script function (parameters are passed in as $1 through $9, and $* for all parameters)");
666         Cmd_AddCommand ("cmd", Cmd_ForwardToServer, "send a console commandline to the server (used by some mods)");
667         Cmd_AddCommand ("wait", Cmd_Wait_f, "make script execution wait for next rendered frame");
668         Cmd_AddCommand ("set", Cvar_Set_f, "create or change the value of a console variable");
669         Cmd_AddCommand ("seta", Cvar_SetA_f, "create or change the value of a console variable that will be saved to config.cfg");
670
671         // 2000-01-09 CmdList, CvarList commands By Matthias "Maddes" Buecher
672         // Added/Modified by EvilTypeGuy eviltypeguy@qeradiant.com
673         Cmd_AddCommand ("cmdlist", Cmd_List_f, "lists all console commands beginning with the specified prefix");
674         Cmd_AddCommand ("cvarlist", Cvar_List_f, "lists all console variables beginning with the specified prefix");
675
676         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");
677         Cmd_AddCommand ("cvar_resettodefaults_all", Cvar_ResetToDefaults_All_f, "sets all cvars to their locked default values");
678         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)");
679         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)");
680
681         // DRESK - 5/14/06
682         // Support Doom3-style Toggle Command
683         Cmd_AddCommand( "toggle", Cmd_Toggle_f, "toggles a console variable's values (use for more info)");
684 }
685
686 /*
687 ============
688 Cmd_Shutdown
689 ============
690 */
691 void Cmd_Shutdown(void)
692 {
693         Mem_FreePool(&cmd_mempool);
694 }
695
696 /*
697 ============
698 Cmd_Argc
699 ============
700 */
701 int             Cmd_Argc (void)
702 {
703         return cmd_argc;
704 }
705
706 /*
707 ============
708 Cmd_Argv
709 ============
710 */
711 const char *Cmd_Argv (int arg)
712 {
713         if (arg >= cmd_argc )
714                 return cmd_null_string;
715         return cmd_argv[arg];
716 }
717
718 /*
719 ============
720 Cmd_Args
721 ============
722 */
723 const char *Cmd_Args (void)
724 {
725         return cmd_args;
726 }
727
728
729 /*
730 ============
731 Cmd_TokenizeString
732
733 Parses the given string into command line tokens.
734 ============
735 */
736 // AK: This function should only be called from ExcuteString because the current design is a bit of an hack
737 static void Cmd_TokenizeString (const char *text)
738 {
739         int l;
740
741         cmd_argc = 0;
742         cmd_args = NULL;
743
744         while (1)
745         {
746                 // skip whitespace up to a /n
747                 while (*text && *text <= ' ' && *text != '\r' && *text != '\n')
748                         text++;
749
750                 // line endings:
751                 // UNIX: \n
752                 // Mac: \r
753                 // Windows: \r\n
754                 if (*text == '\n' || *text == '\r')
755                 {
756                         // a newline separates commands in the buffer
757                         if (*text == '\r' && text[1] == '\n')
758                                 text++;
759                         text++;
760                         break;
761                 }
762
763                 if (!*text)
764                         return;
765
766                 if (cmd_argc == 1)
767                         cmd_args = text;
768
769                 if (!COM_ParseTokenConsole(&text))
770                         return;
771
772                 if (cmd_argc < MAX_ARGS)
773                 {
774                         l = (int)strlen(com_token) + 1;
775                         if (cmd_tokenizebufferpos + l > CMD_TOKENIZELENGTH)
776                         {
777                                 Con_Printf("Cmd_TokenizeString: ran out of %i character buffer space for command arguements\n", CMD_TOKENIZELENGTH);
778                                 break;
779                         }
780                         memcpy (cmd_tokenizebuffer + cmd_tokenizebufferpos, com_token, l);
781                         cmd_argv[cmd_argc] = cmd_tokenizebuffer + cmd_tokenizebufferpos;
782                         cmd_tokenizebufferpos += l;
783                         cmd_argc++;
784                 }
785         }
786 }
787
788
789 /*
790 ============
791 Cmd_AddCommand
792 ============
793 */
794 void Cmd_AddCommand (const char *cmd_name, xcommand_t function, const char *description)
795 {
796         cmd_function_t *cmd;
797         cmd_function_t *prev, *current;
798
799 // fail if the command is a variable name
800         if (Cvar_FindVar( cmd_name ))
801         {
802                 Con_Printf("Cmd_AddCommand: %s already defined as a var\n", cmd_name);
803                 return;
804         }
805
806 // fail if the command already exists
807         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
808         {
809                 if (!strcmp (cmd_name, cmd->name))
810                 {
811                         if (function)
812                         {
813                                 Con_Printf("Cmd_AddCommand: %s already defined\n", cmd_name);
814                                 return;
815                         }
816                         else    //[515]: csqc
817                         {
818                                 cmd->csqcfunc = true;
819                                 return;
820                         }
821                 }
822         }
823
824         cmd = (cmd_function_t *)Mem_Alloc(cmd_mempool, sizeof(cmd_function_t));
825         cmd->name = cmd_name;
826         cmd->function = function;
827         cmd->description = description;
828         if(!function)                   //[515]: csqc
829                 cmd->csqcfunc = true;
830         cmd->next = cmd_functions;
831
832 // insert it at the right alphanumeric position
833         for( prev = NULL, current = cmd_functions ; current && strcmp( current->name, cmd->name ) < 0 ; prev = current, current = current->next )
834                 ;
835         if( prev ) {
836                 prev->next = cmd;
837         } else {
838                 cmd_functions = cmd;
839         }
840         cmd->next = current;
841 }
842
843 /*
844 ============
845 Cmd_Exists
846 ============
847 */
848 qboolean Cmd_Exists (const char *cmd_name)
849 {
850         cmd_function_t  *cmd;
851
852         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
853                 if (!strcmp (cmd_name,cmd->name))
854                         return true;
855
856         return false;
857 }
858
859
860 /*
861 ============
862 Cmd_CompleteCommand
863 ============
864 */
865 const char *Cmd_CompleteCommand (const char *partial)
866 {
867         cmd_function_t *cmd;
868         size_t len;
869
870         len = strlen(partial);
871
872         if (!len)
873                 return NULL;
874
875 // check functions
876         for (cmd = cmd_functions; cmd; cmd = cmd->next)
877                 if (!strncasecmp(partial, cmd->name, len))
878                         return cmd->name;
879
880         return NULL;
881 }
882
883 /*
884         Cmd_CompleteCountPossible
885
886         New function for tab-completion system
887         Added by EvilTypeGuy
888         Thanks to Fett erich@heintz.com
889         Thanks to taniwha
890
891 */
892 int Cmd_CompleteCountPossible (const char *partial)
893 {
894         cmd_function_t *cmd;
895         size_t len;
896         int h;
897
898         h = 0;
899         len = strlen(partial);
900
901         if (!len)
902                 return 0;
903
904         // Loop through the command list and count all partial matches
905         for (cmd = cmd_functions; cmd; cmd = cmd->next)
906                 if (!strncasecmp(partial, cmd->name, len))
907                         h++;
908
909         return h;
910 }
911
912 /*
913         Cmd_CompleteBuildList
914
915         New function for tab-completion system
916         Added by EvilTypeGuy
917         Thanks to Fett erich@heintz.com
918         Thanks to taniwha
919
920 */
921 const char **Cmd_CompleteBuildList (const char *partial)
922 {
923         cmd_function_t *cmd;
924         size_t len = 0;
925         size_t bpos = 0;
926         size_t sizeofbuf = (Cmd_CompleteCountPossible (partial) + 1) * sizeof (const char *);
927         const char **buf;
928
929         len = strlen(partial);
930         buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
931         // Loop through the alias list and print all matches
932         for (cmd = cmd_functions; cmd; cmd = cmd->next)
933                 if (!strncasecmp(partial, cmd->name, len))
934                         buf[bpos++] = cmd->name;
935
936         buf[bpos] = NULL;
937         return buf;
938 }
939
940 // written by LordHavoc
941 void Cmd_CompleteCommandPrint (const char *partial)
942 {
943         cmd_function_t *cmd;
944         size_t len = strlen(partial);
945         // Loop through the command list and print all matches
946         for (cmd = cmd_functions; cmd; cmd = cmd->next)
947                 if (!strncasecmp(partial, cmd->name, len))
948                         Con_Printf("%s : %s\n", cmd->name, cmd->description);
949 }
950
951 /*
952         Cmd_CompleteAlias
953
954         New function for tab-completion system
955         Added by EvilTypeGuy
956         Thanks to Fett erich@heintz.com
957         Thanks to taniwha
958
959 */
960 const char *Cmd_CompleteAlias (const char *partial)
961 {
962         cmdalias_t *alias;
963         size_t len;
964
965         len = strlen(partial);
966
967         if (!len)
968                 return NULL;
969
970         // Check functions
971         for (alias = cmd_alias; alias; alias = alias->next)
972                 if (!strncasecmp(partial, alias->name, len))
973                         return alias->name;
974
975         return NULL;
976 }
977
978 // written by LordHavoc
979 void Cmd_CompleteAliasPrint (const char *partial)
980 {
981         cmdalias_t *alias;
982         size_t len = strlen(partial);
983         // Loop through the alias list and print all matches
984         for (alias = cmd_alias; alias; alias = alias->next)
985                 if (!strncasecmp(partial, alias->name, len))
986                         Con_Printf("%s : %s\n", alias->name, alias->value);
987 }
988
989
990 /*
991         Cmd_CompleteAliasCountPossible
992
993         New function for tab-completion system
994         Added by EvilTypeGuy
995         Thanks to Fett erich@heintz.com
996         Thanks to taniwha
997
998 */
999 int Cmd_CompleteAliasCountPossible (const char *partial)
1000 {
1001         cmdalias_t      *alias;
1002         size_t          len;
1003         int                     h;
1004
1005         h = 0;
1006
1007         len = strlen(partial);
1008
1009         if (!len)
1010                 return 0;
1011
1012         // Loop through the command list and count all partial matches
1013         for (alias = cmd_alias; alias; alias = alias->next)
1014                 if (!strncasecmp(partial, alias->name, len))
1015                         h++;
1016
1017         return h;
1018 }
1019
1020 /*
1021         Cmd_CompleteAliasBuildList
1022
1023         New function for tab-completion system
1024         Added by EvilTypeGuy
1025         Thanks to Fett erich@heintz.com
1026         Thanks to taniwha
1027
1028 */
1029 const char **Cmd_CompleteAliasBuildList (const char *partial)
1030 {
1031         cmdalias_t *alias;
1032         size_t len = 0;
1033         size_t bpos = 0;
1034         size_t sizeofbuf = (Cmd_CompleteAliasCountPossible (partial) + 1) * sizeof (const char *);
1035         const char **buf;
1036
1037         len = strlen(partial);
1038         buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1039         // Loop through the alias list and print all matches
1040         for (alias = cmd_alias; alias; alias = alias->next)
1041                 if (!strncasecmp(partial, alias->name, len))
1042                         buf[bpos++] = alias->name;
1043
1044         buf[bpos] = NULL;
1045         return buf;
1046 }
1047
1048 void Cmd_ClearCsqcFuncs (void)
1049 {
1050         cmd_function_t *cmd;
1051         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1052                 cmd->csqcfunc = false;
1053 }
1054
1055 qboolean CL_VM_ConsoleCommand (const char *cmd);
1056 /*
1057 ============
1058 Cmd_ExecuteString
1059
1060 A complete command line has been parsed, so try to execute it
1061 FIXME: lookupnoadd the token to speed search?
1062 ============
1063 */
1064 void Cmd_ExecuteString (const char *text, cmd_source_t src)
1065 {
1066         int oldpos;
1067         cmd_function_t *cmd;
1068         cmdalias_t *a;
1069
1070         oldpos = cmd_tokenizebufferpos;
1071         cmd_source = src;
1072
1073         Cmd_TokenizeString (text);
1074
1075 // execute the command line
1076         if (!Cmd_Argc())
1077         {
1078                 cmd_tokenizebufferpos = oldpos;
1079                 return;         // no tokens
1080         }
1081
1082 // check functions
1083         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1084         {
1085                 if (!strcasecmp (cmd_argv[0],cmd->name))
1086                 {
1087                         if(cmd->function && !cmd->csqcfunc)
1088                                 cmd->function ();
1089                         else
1090                                 if(CL_VM_ConsoleCommand (text)) //[515]: csqc
1091                                         return;
1092                                 else
1093                                         if(cmd->function)
1094                                                 cmd->function ();
1095                         cmd_tokenizebufferpos = oldpos;
1096                         return;
1097                 }
1098         }
1099
1100 // check alias
1101         for (a=cmd_alias ; a ; a=a->next)
1102         {
1103                 if (!strcasecmp (cmd_argv[0], a->name))
1104                 {
1105                         Cmd_ExecuteAlias(a);
1106                         cmd_tokenizebufferpos = oldpos;
1107                         return;
1108                 }
1109         }
1110
1111 // check cvars
1112         if (!Cvar_Command () && host_framecount > 0)
1113                 Con_Printf("Unknown command \"%s\"\n", Cmd_Argv(0));
1114
1115         cmd_tokenizebufferpos = oldpos;
1116 }
1117
1118
1119 /*
1120 ===================
1121 Cmd_ForwardStringToServer
1122
1123 Sends an entire command string over to the server, unprocessed
1124 ===================
1125 */
1126 void Cmd_ForwardStringToServer (const char *s)
1127 {
1128         if (cls.state != ca_connected)
1129         {
1130                 Con_Printf("Can't \"%s\", not connected\n", s);
1131                 return;
1132         }
1133
1134         if (!cls.netcon)
1135                 return;
1136
1137         // LordHavoc: thanks to Fuh for bringing the pure evil of SZ_Print to my
1138         // attention, it has been eradicated from here, its only (former) use in
1139         // all of darkplaces.
1140         if (cls.protocol == PROTOCOL_QUAKEWORLD)
1141                 MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
1142         else
1143                 MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
1144         SZ_Write(&cls.netcon->message, (const unsigned char *)s, (int)strlen(s) + 1);
1145 }
1146
1147 /*
1148 ===================
1149 Cmd_ForwardToServer
1150
1151 Sends the entire command line over to the server
1152 ===================
1153 */
1154 void Cmd_ForwardToServer (void)
1155 {
1156         const char *s;
1157         if (!strcasecmp(Cmd_Argv(0), "cmd"))
1158         {
1159                 // we want to strip off "cmd", so just send the args
1160                 s = Cmd_Argc() > 1 ? Cmd_Args() : "";
1161         }
1162         else
1163         {
1164                 // we need to keep the command name, so send Cmd_Argv(0), a space and then Cmd_Args()
1165                 s = va("%s %s", Cmd_Argv(0), Cmd_Argc() > 1 ? Cmd_Args() : "");
1166         }
1167         // don't send an empty forward message if the user tries "cmd" by itself
1168         if (!s || !*s)
1169                 return;
1170         Cmd_ForwardStringToServer(s);
1171 }
1172
1173
1174 /*
1175 ================
1176 Cmd_CheckParm
1177
1178 Returns the position (1 to argc-1) in the command's argument list
1179 where the given parameter apears, or 0 if not present
1180 ================
1181 */
1182
1183 int Cmd_CheckParm (const char *parm)
1184 {
1185         int i;
1186
1187         if (!parm)
1188         {
1189                 Con_Printf ("Cmd_CheckParm: NULL");
1190                 return 0;
1191         }
1192
1193         for (i = 1; i < Cmd_Argc (); i++)
1194                 if (!strcasecmp (parm, Cmd_Argv (i)))
1195                         return i;
1196
1197         return 0;
1198 }
1199