2 Copyright (C) 1996-1997 Id Software, Inc.
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.
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.
13 See the GNU General Public License for more details.
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.
20 // cmd.c -- Quake script command processing module
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
30 // maximum tokenizable commandline length (counting NUL terminations)
31 #define CMD_TOKENIZELENGTH (MAX_INPUTLINE + 80)
33 typedef struct cmdalias_s
35 struct cmdalias_s *next;
36 char name[MAX_ALIAS_NAME];
40 static cmdalias_t *cmd_alias;
42 static qboolean cmd_wait;
44 static mempool_t *cmd_mempool;
46 static char cmd_tokenizebuffer[CMD_TOKENIZELENGTH];
47 static int cmd_tokenizebufferpos = 0;
49 //=============================================================================
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"
60 static void Cmd_Wait_f (void)
66 =============================================================================
70 =============================================================================
73 static sizebuf_t cmd_text;
74 static unsigned char cmd_text_buf[CMDBUFSIZE];
80 Adds command text at the end of the buffer
83 void Cbuf_AddText (const char *text)
87 l = (int)strlen (text);
89 if (cmd_text.cursize + l >= cmd_text.maxsize)
91 Con_Print("Cbuf_AddText: overflow\n");
95 SZ_Write (&cmd_text, (const unsigned char *)text, (int)strlen (text));
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
108 void Cbuf_InsertText (const char *text)
113 // copy off any commands still remaining in the exec buffer
114 templen = cmd_text.cursize;
117 temp = (char *)Mem_Alloc (tempmempool, templen);
118 memcpy (temp, cmd_text.data, templen);
119 SZ_Clear (&cmd_text);
124 // add the entire text of the file
127 // add the copied off data
130 SZ_Write (&cmd_text, (const unsigned char *)temp, templen);
140 static void Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias );
141 void Cbuf_Execute (void)
145 char line[MAX_INPUTLINE];
146 char preprocessed[MAX_INPUTLINE];
149 // LordHavoc: making sure the tokenizebuffer doesn't get filled up by repeated crashes
150 cmd_tokenizebufferpos = 0;
152 while (cmd_text.cursize)
154 // find a \n or ; line break
155 text = (char *)cmd_text.data;
158 for (i=0 ; i< cmd_text.cursize ; i++)
162 if ( !quotes && text[i] == ';')
163 break; // don't break if inside a quoted string
164 if (text[i] == '\r' || text[i] == '\n')
168 memcpy (line, text, i);
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
175 if (i == cmd_text.cursize)
176 cmd_text.cursize = 0;
180 cmd_text.cursize -= i;
181 memcpy (cmd_text.data, text+i, cmd_text.cursize);
184 // execute the command line
185 Cmd_PreprocessString( line, preprocessed, sizeof(preprocessed), NULL );
186 Cmd_ExecuteString (preprocessed, src_command);
189 { // skip out while text still remains in buffer, leaving it
198 ==============================================================================
202 ==============================================================================
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
215 qboolean host_stuffcmdsrun = false;
216 void Cmd_StuffCmds_f (void)
219 // this is per command, and bounds checked (no buffer overflows)
220 char build[MAX_INPUTLINE];
222 if (Cmd_Argc () != 1)
224 Con_Print("stuffcmds : execute command line parameters\n");
228 host_stuffcmdsrun = true;
229 for (i = 0;i < com_argc;i++)
231 if (com_argv[i] && com_argv[i][0] == '+' && (com_argv[i][1] < '0' || com_argv[i][1] > '9'))
235 while (com_argv[i][j])
236 build[l++] = com_argv[i][j++];
238 for (;i < com_argc;i++)
242 if ((com_argv[i][0] == '+' || com_argv[i][0] == '-') && (com_argv[i][1] < '0' || com_argv[i][1] > '9'))
244 if (l + strlen(com_argv[i]) + 5 > sizeof(build))
248 for (j = 0;com_argv[i][j];j++)
249 build[l++] = com_argv[i][j];
254 Cbuf_InsertText (build);
266 static void Cmd_Exec_f (void)
270 if (Cmd_Argc () != 2)
272 Con_Print("exec <filename> : execute a script file\n");
276 f = (char *)FS_LoadFile (Cmd_Argv(1), tempmempool, false, NULL);
279 Con_Printf("couldn't exec %s\n",Cmd_Argv(1));
282 Con_DPrintf("execing %s\n",Cmd_Argv(1));
293 Just prints the rest of the line to the console
296 static void Cmd_Echo_f (void)
300 for (i=1 ; i<Cmd_Argc() ; i++)
301 Con_Printf("%s ",Cmd_Argv(i));
309 Creates a new command that executes a command string (possibly ; seperated)
312 static void Cmd_Alias_f (void)
315 char cmd[MAX_INPUTLINE];
321 Con_Print("Current alias commands:\n");
322 for (a = cmd_alias ; a ; a=a->next)
323 Con_Printf("%s : %s\n", a->name, a->value);
328 if (strlen(s) >= MAX_ALIAS_NAME)
330 Con_Print("Alias name is too long\n");
334 // if the alias already exists, reuse it
335 for (a = cmd_alias ; a ; a=a->next)
337 if (!strcmp(s, a->name))
346 cmdalias_t *prev, *current;
348 a = (cmdalias_t *)Z_Malloc (sizeof(cmdalias_t));
349 strlcpy (a->name, s, sizeof (a->name));
350 // insert it at the right alphanumeric position
351 for( prev = NULL, current = cmd_alias ; current && strcmp( current->name, a->name ) < 0 ; prev = current, current = current->next )
362 // copy the rest of the command line
363 cmd[0] = 0; // start out with a null string
365 for (i=2 ; i< c ; i++)
367 strlcat (cmd, Cmd_Argv(i), sizeof (cmd));
369 strlcat (cmd, " ", sizeof (cmd));
371 strlcat (cmd, "\n", sizeof (cmd));
373 a->value = (char *)Z_Malloc (strlen (cmd) + 1);
374 strcpy (a->value, cmd);
378 =============================================================================
382 =============================================================================
385 typedef struct cmd_function_s
387 struct cmd_function_s *next;
394 static const char *cmd_argv[MAX_ARGS];
395 static const char *cmd_null_string = "";
396 static const char *cmd_args;
397 cmd_source_t cmd_source;
400 static cmd_function_t *cmd_functions; // possible commands to execute
405 Preprocesses strings and replaces $*, $param#, $cvar accordingly
407 static void Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias ) {
412 // don't crash if there's no room in the outtext buffer
413 if( maxoutlen == 0 ) {
416 maxoutlen--; // because of \0
422 while( *in && outlen < maxoutlen ) {
423 if( *in == '$' && !inquote ) {
424 // this is some kind of expansion, see what comes after the $
426 // replacements that can always be used:
427 // $$ is replaced with $, to allow escaping $
428 // $<cvarname> is replaced with the contents of the cvar
430 // the following can be used in aliases only:
431 // $* is replaced with all formal parameters (including name of the alias - this probably is not desirable)
432 // $0 is replaced with the name of this alias
433 // $<number> is replaced with an argument to this alias (or copied as-is if no such parameter exists), can be multiple digits
435 outtext[outlen++] = *in++;
436 } else if( *in == '*' && alias ) {
437 const char *linein = Cmd_Args();
438 // include all params
440 while( *linein && outlen < maxoutlen ) {
441 outtext[outlen++] = *linein++;
446 } else if( '0' <= *in && *in <= '9' && alias ) {
450 argnum = strtol( in, &nexttoken, 10 );
452 if( 0 <= argnum && argnum < Cmd_Argc() ) {
453 const char *param = Cmd_Argv( argnum );
454 while( *param && outlen < maxoutlen ) {
455 outtext[outlen++] = *param++;
458 } else if( argnum >= Cmd_Argc() ) {
459 Con_Printf( "Warning: Not enough parameters passed to alias '%s', at least %i expected:\n %s\n", alias->name, argnum, alias->value );
460 outtext[outlen++] = '$';
464 const char *tempin = in;
466 COM_ParseTokenConsole( &tempin );
467 if ((cvar = Cvar_FindVar(&com_token[0]))) {
468 const char *cvarcontent = cvar->string;
469 while( *cvarcontent && outlen < maxoutlen ) {
470 outtext[outlen++] = *cvarcontent++;
474 Con_Printf( "Warning: could not find cvar %s when expanding alias %s\n %s\n", com_token, alias->name, alias->value );
475 outtext[outlen++] = '$';
482 outtext[outlen++] = *in++;
492 Called for aliases and fills in the alias into the cbuffer
495 static void Cmd_ExecuteAlias (cmdalias_t *alias)
497 static char buffer[ MAX_INPUTLINE + 2 ];
498 Cmd_PreprocessString( alias->value, buffer, sizeof(buffer) - 2, alias );
499 Cbuf_AddText( buffer );
506 CmdList Added by EvilTypeGuy eviltypeguy@qeradiant.com
507 Thanks to Matthias "Maddes" Buecher, http://www.inside3d.com/qip/
511 static void Cmd_List_f (void)
519 partial = Cmd_Argv (1);
520 len = (int)strlen(partial);
529 for (cmd = cmd_functions; cmd; cmd = cmd->next)
531 if (partial && strncmp(partial, cmd->name, len))
533 Con_Printf("%s\n", cmd->name);
538 Con_Printf("%i Command%s beginning with \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
540 Con_Printf("%i Command%s\n\n", count, (count > 1) ? "s" : "");
550 cmd_mempool = Mem_AllocPool("commands", 0, NULL);
551 // space for commands and script files
552 cmd_text.data = cmd_text_buf;
553 cmd_text.maxsize = sizeof(cmd_text_buf);
554 cmd_text.cursize = 0;
557 void Cmd_Init_Commands (void)
560 // register our commands
562 Cmd_AddCommand ("stuffcmds",Cmd_StuffCmds_f);
563 Cmd_AddCommand ("exec",Cmd_Exec_f);
564 Cmd_AddCommand ("echo",Cmd_Echo_f);
565 Cmd_AddCommand ("alias",Cmd_Alias_f);
566 Cmd_AddCommand ("cmd", Cmd_ForwardToServer);
567 Cmd_AddCommand ("wait", Cmd_Wait_f);
568 Cmd_AddCommand ("cmdlist", Cmd_List_f); // Added/Modified by EvilTypeGuy eviltypeguy@qeradiant.com
569 Cmd_AddCommand ("cvarlist", Cvar_List_f); // 2000-01-09 CmdList, CvarList commands
570 // By Matthias "Maddes" Buecher
571 Cmd_AddCommand ("set", Cvar_Set_f);
572 Cmd_AddCommand ("seta", Cvar_SetA_f);
580 void Cmd_Shutdown(void)
582 Mem_FreePool(&cmd_mempool);
600 const char *Cmd_Argv (int arg)
602 if (arg >= cmd_argc )
603 return cmd_null_string;
604 return cmd_argv[arg];
612 const char *Cmd_Args (void)
622 Parses the given string into command line tokens.
625 // AK: This function should only be called from ExcuteString because the current design is a bit of an hack
626 static void Cmd_TokenizeString (const char *text)
635 // skip whitespace up to a /n
636 while (*text && *text <= ' ' && *text != '\r' && *text != '\n')
643 if (*text == '\n' || *text == '\r')
645 // a newline separates commands in the buffer
646 if (*text == '\r' && text[1] == '\n')
658 if (!COM_ParseTokenConsole(&text))
661 if (cmd_argc < MAX_ARGS)
663 l = (int)strlen(com_token) + 1;
664 if (cmd_tokenizebufferpos + l > CMD_TOKENIZELENGTH)
666 Con_Printf("Cmd_TokenizeString: ran out of %i character buffer space for command arguements\n", CMD_TOKENIZELENGTH);
669 strcpy (cmd_tokenizebuffer + cmd_tokenizebufferpos, com_token);
670 cmd_argv[cmd_argc] = cmd_tokenizebuffer + cmd_tokenizebufferpos;
671 cmd_tokenizebufferpos += l;
683 void Cmd_AddCommand (const char *cmd_name, xcommand_t function)
686 cmd_function_t *prev, *current;
688 // fail if the command is a variable name
689 if (Cvar_FindVar( cmd_name ))
691 Con_Printf("Cmd_AddCommand: %s already defined as a var\n", cmd_name);
695 // fail if the command already exists
696 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
698 if (!strcmp (cmd_name, cmd->name))
702 Con_Printf("Cmd_AddCommand: %s already defined\n", cmd_name);
707 cmd->csqcfunc = true;
713 cmd = (cmd_function_t *)Mem_Alloc(cmd_mempool, sizeof(cmd_function_t));
714 cmd->name = cmd_name;
715 cmd->function = function;
716 if(!function) //[515]: csqc
717 cmd->csqcfunc = true;
718 cmd->next = cmd_functions;
720 // insert it at the right alphanumeric position
721 for( prev = NULL, current = cmd_functions ; current && strcmp( current->name, cmd->name ) < 0 ; prev = current, current = current->next )
736 qboolean Cmd_Exists (const char *cmd_name)
740 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
741 if (!strcmp (cmd_name,cmd->name))
753 const char *Cmd_CompleteCommand (const char *partial)
758 len = strlen(partial);
764 for (cmd = cmd_functions; cmd; cmd = cmd->next)
765 if (!strncmp(partial, cmd->name, len))
772 Cmd_CompleteCountPossible
774 New function for tab-completion system
776 Thanks to Fett erich@heintz.com
780 int Cmd_CompleteCountPossible (const char *partial)
787 len = strlen(partial);
792 // Loop through the command list and count all partial matches
793 for (cmd = cmd_functions; cmd; cmd = cmd->next)
794 if (!strncasecmp(partial, cmd->name, len))
801 Cmd_CompleteBuildList
803 New function for tab-completion system
805 Thanks to Fett erich@heintz.com
809 const char **Cmd_CompleteBuildList (const char *partial)
814 size_t sizeofbuf = (Cmd_CompleteCountPossible (partial) + 1) * sizeof (const char *);
817 len = strlen(partial);
818 buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
819 // Loop through the alias list and print all matches
820 for (cmd = cmd_functions; cmd; cmd = cmd->next)
821 if (!strncasecmp(partial, cmd->name, len))
822 buf[bpos++] = cmd->name;
831 New function for tab-completion system
833 Thanks to Fett erich@heintz.com
837 const char *Cmd_CompleteAlias (const char *partial)
842 len = strlen(partial);
848 for (alias = cmd_alias; alias; alias = alias->next)
849 if (!strncasecmp(partial, alias->name, len))
856 Cmd_CompleteAliasCountPossible
858 New function for tab-completion system
860 Thanks to Fett erich@heintz.com
864 int Cmd_CompleteAliasCountPossible (const char *partial)
872 len = strlen(partial);
877 // Loop through the command list and count all partial matches
878 for (alias = cmd_alias; alias; alias = alias->next)
879 if (!strncasecmp(partial, alias->name, len))
886 Cmd_CompleteAliasBuildList
888 New function for tab-completion system
890 Thanks to Fett erich@heintz.com
894 const char **Cmd_CompleteAliasBuildList (const char *partial)
899 size_t sizeofbuf = (Cmd_CompleteAliasCountPossible (partial) + 1) * sizeof (const char *);
902 len = strlen(partial);
903 buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
904 // Loop through the alias list and print all matches
905 for (alias = cmd_alias; alias; alias = alias->next)
906 if (!strncasecmp(partial, alias->name, len))
907 buf[bpos++] = alias->name;
913 void Cmd_ClearCsqcFuncs (void)
916 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
917 cmd->csqcfunc = false;
920 qboolean CL_VM_ConsoleCommand (const char *cmd);
925 A complete command line has been parsed, so try to execute it
926 FIXME: lookupnoadd the token to speed search?
929 void Cmd_ExecuteString (const char *text, cmd_source_t src)
935 oldpos = cmd_tokenizebufferpos;
938 Cmd_TokenizeString (text);
940 // execute the command line
943 cmd_tokenizebufferpos = oldpos;
948 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
950 if (!strcasecmp (cmd_argv[0],cmd->name))
952 if(cmd->function && !cmd->csqcfunc)
955 if(CL_VM_ConsoleCommand (text)) //[515]: csqc
960 cmd_tokenizebufferpos = oldpos;
966 for (a=cmd_alias ; a ; a=a->next)
968 if (!strcasecmp (cmd_argv[0], a->name))
971 cmd_tokenizebufferpos = oldpos;
977 if (!Cvar_Command () && host_framecount > 0)
978 Con_Printf("Unknown command \"%s\"\n", Cmd_Argv(0));
980 cmd_tokenizebufferpos = oldpos;
986 Cmd_ForwardStringToServer
988 Sends an entire command string over to the server, unprocessed
991 void Cmd_ForwardStringToServer (const char *s)
993 if (cls.state != ca_connected)
995 Con_Printf("Can't \"%s\", not connected\n", s);
999 if (cls.demoplayback)
1000 return; // not really connected
1002 // LordHavoc: thanks to Fuh for bringing the pure evil of SZ_Print to my
1003 // attention, it has been eradicated from here, its only (former) use in
1004 // all of darkplaces.
1005 MSG_WriteByte(&cls.message, clc_stringcmd);
1006 SZ_Write(&cls.message, (const unsigned char *)s, (int)strlen(s) + 1);
1013 Sends the entire command line over to the server
1016 void Cmd_ForwardToServer (void)
1019 if (!strcasecmp(Cmd_Argv(0), "cmd"))
1021 // we want to strip off "cmd", so just send the args
1022 s = Cmd_Argc() > 1 ? Cmd_Args() : "";
1026 // we need to keep the command name, so send Cmd_Argv(0), a space and then Cmd_Args()
1027 s = va("%s %s", Cmd_Argv(0), Cmd_Argc() > 1 ? Cmd_Args() : "");
1029 // don't send an empty forward message if the user tries "cmd" by itself
1032 Cmd_ForwardStringToServer(s);
1040 Returns the position (1 to argc-1) in the command's argument list
1041 where the given parameter apears, or 0 if not present
1045 int Cmd_CheckParm (const char *parm)
1051 Con_Printf ("Cmd_CheckParm: NULL");
1055 for (i = 1; i < Cmd_Argc (); i++)
1056 if (!strcasecmp (parm, Cmd_Argv (i)))