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