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
26 typedef struct cmdalias_s
28 struct cmdalias_s *next;
29 char name[MAX_ALIAS_NAME];
33 static cmdalias_t *cmd_alias;
35 static qboolean cmd_wait;
37 static mempool_t *cmd_mempool;
39 #define CMD_TOKENIZELENGTH 4096
40 static char cmd_tokenizebuffer[CMD_TOKENIZELENGTH];
41 static int cmd_tokenizebufferpos = 0;
43 //=============================================================================
49 Causes execution of the remainder of the command buffer to be delayed until
50 next frame. This allows commands like:
51 bind g "impulse 5 ; +attack ; wait ; -attack ; impulse 2"
54 static void Cmd_Wait_f (void)
60 =============================================================================
64 =============================================================================
67 // LordHavoc: inreased this from 8192 to 32768
68 static sizebuf_t cmd_text;
69 static unsigned char cmd_text_buf[32768];
75 Adds command text at the end of the buffer
78 void Cbuf_AddText (const char *text)
82 l = (int)strlen (text);
84 if (cmd_text.cursize + l >= cmd_text.maxsize)
86 Con_Print("Cbuf_AddText: overflow\n");
90 SZ_Write (&cmd_text, (const unsigned char *)text, (int)strlen (text));
98 Adds command text immediately after the current command
100 FIXME: actually change the command buffer to do less copying
103 void Cbuf_InsertText (const char *text)
108 // copy off any commands still remaining in the exec buffer
109 templen = cmd_text.cursize;
112 temp = (char *)Mem_Alloc (tempmempool, templen);
113 memcpy (temp, cmd_text.data, templen);
114 SZ_Clear (&cmd_text);
119 // add the entire text of the file
122 // add the copied off data
125 SZ_Write (&cmd_text, (const unsigned char *)temp, templen);
135 void Cbuf_Execute (void)
142 // LordHavoc: making sure the tokenizebuffer doesn't get filled up by repeated crashes
143 cmd_tokenizebufferpos = 0;
145 while (cmd_text.cursize)
147 // find a \n or ; line break
148 text = (char *)cmd_text.data;
151 for (i=0 ; i< cmd_text.cursize ; i++)
155 if ( !quotes && text[i] == ';')
156 break; // don't break if inside a quoted string
157 if (text[i] == '\r' || text[i] == '\n')
161 memcpy (line, text, i);
164 // delete the text from the command buffer and move remaining commands down
165 // this is necessary because commands (exec, alias) can insert data at the
166 // beginning of the text buffer
168 if (i == cmd_text.cursize)
169 cmd_text.cursize = 0;
173 cmd_text.cursize -= i;
174 memcpy (cmd_text.data, text+i, cmd_text.cursize);
177 // execute the command line
178 Cmd_ExecuteString (line, src_command);
181 { // skip out while text still remains in buffer, leaving it
190 ==============================================================================
194 ==============================================================================
201 Adds command line parameters as script statements
202 Commands lead with a +, and continue until a - or another +
203 quake +prog jctest.qp +cmd amlev1
204 quake -nosound +cmd amlev1
207 qboolean host_stuffcmdsrun = false;
208 void Cmd_StuffCmds_f (void)
211 // this is per command, and bounds checked (no buffer overflows)
214 if (Cmd_Argc () != 1)
216 Con_Print("stuffcmds : execute command line parameters\n");
220 host_stuffcmdsrun = true;
221 for (i = 0;i < com_argc;i++)
223 if (com_argv[i] && com_argv[i][0] == '+' && (com_argv[i][1] < '0' || com_argv[i][1] > '9'))
227 while (com_argv[i][j])
228 build[l++] = com_argv[i][j++];
230 for (;i < com_argc;i++)
234 if ((com_argv[i][0] == '+' || com_argv[i][0] == '-') && (com_argv[i][1] < '0' || com_argv[i][1] > '9'))
236 if (l + strlen(com_argv[i]) + 5 > sizeof(build))
240 for (j = 0;com_argv[i][j];j++)
241 build[l++] = com_argv[i][j];
246 Cbuf_InsertText (build);
258 static void Cmd_Exec_f (void)
262 if (Cmd_Argc () != 2)
264 Con_Print("exec <filename> : execute a script file\n");
268 f = (char *)FS_LoadFile (Cmd_Argv(1), tempmempool, false, NULL);
271 Con_Printf("couldn't exec %s\n",Cmd_Argv(1));
274 Con_DPrintf("execing %s\n",Cmd_Argv(1));
285 Just prints the rest of the line to the console
288 static void Cmd_Echo_f (void)
292 for (i=1 ; i<Cmd_Argc() ; i++)
293 Con_Printf("%s ",Cmd_Argv(i));
301 Creates a new command that executes a command string (possibly ; seperated)
304 static void Cmd_Alias_f (void)
313 Con_Print("Current alias commands:\n");
314 for (a = cmd_alias ; a ; a=a->next)
315 Con_Printf("%s : %s\n", a->name, a->value);
320 if (strlen(s) >= MAX_ALIAS_NAME)
322 Con_Print("Alias name is too long\n");
326 // if the alias already exists, reuse it
327 for (a = cmd_alias ; a ; a=a->next)
329 if (!strcmp(s, a->name))
338 cmdalias_t *prev, *current;
340 a = (cmdalias_t *)Z_Malloc (sizeof(cmdalias_t));
341 strlcpy (a->name, s, sizeof (a->name));
342 // insert it at the right alphanumeric position
343 for( prev = NULL, current = cmd_alias ; current && strcmp( current->name, a->name ) < 0 ; prev = current, current = current->next )
354 // copy the rest of the command line
355 cmd[0] = 0; // start out with a null string
357 for (i=2 ; i< c ; i++)
359 strlcat (cmd, Cmd_Argv(i), sizeof (cmd));
361 strlcat (cmd, " ", sizeof (cmd));
363 strlcat (cmd, "\n", sizeof (cmd));
365 a->value = (char *)Z_Malloc (strlen (cmd) + 1);
366 strcpy (a->value, cmd);
370 =============================================================================
374 =============================================================================
377 typedef struct cmd_function_s
379 struct cmd_function_s *next;
388 static const char *cmd_argv[MAX_ARGS];
389 static const char *cmd_null_string = "";
390 static const char *cmd_args = NULL;
392 cmd_source_t cmd_source;
395 static cmd_function_t *cmd_functions; // possible commands to execute
400 Preprocesses strings and replaces $*, $param#, $cvar accordingly
402 static void Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias ) {
409 if( maxoutlen == 0 ) {
412 maxoutlen--; // because of \0
419 while( *in && outlen < maxoutlen ) {
420 if( *in == '$' && !inquote ) {
423 // $* is replaced with all formal parameters, $num is parsed as an argument (or as $num if there arent enough parameters), $bla becomes $bla and $$bla becomes $$bla
424 if( *in == '*' && alias ) {
425 const char *linein = Cmd_Args();
426 // include all params
428 while( *linein && outlen < maxoutlen ) {
435 } else if( '0' <= *in && *in <= '9' && alias ) {
439 argnum = strtol( in, &nexttoken, 10 );
441 if( 0 < argnum && argnum < Cmd_Argc() ) {
442 const char *param = Cmd_Argv( argnum );
443 while( *param && outlen < maxoutlen ) {
448 } else if( argnum >= Cmd_Argc() ) {
449 Con_Printf( "Warning: Not enough parameters passed to alias '%s', at least %i expected:\n %s\n", alias->name, argnum, alias->value );
455 const char *tempin = in;
457 COM_ParseTokenConsole( &tempin );
458 cvar = Cvar_FindVar(&com_token[0]);
460 const char *cvarcontent = cvar->string;
461 while( *cvarcontent && outlen < maxoutlen ) {
462 *out++ = *cvarcontent++;
466 } else if( com_token[0] == '$' ) {
467 // remove the first $
468 char *pos = com_token;
469 while( *pos && outlen < maxoutlen ) {
491 Called for aliases and fills in the alias into the cbuffer
494 static void Cmd_ExecuteAlias (cmdalias_t *alias)
497 #define ALIAS_BUFFER 1024
498 static char buffer[ ALIAS_BUFFER + 2 ];
509 while( *in && outlen < ALIAS_BUFFER )
515 else if( *in == '$' && !inquote )
517 // $* is replaced with all formal parameters, $num is parsed as an argument (or as $num if there arent enough parameters), $bla becomes $bla and $$bla becomes $$bla
522 const char *linein = Cmd_Args();
523 // include all params
525 while( *linein && outlen < ALIAS_BUFFER ) {
536 argnum = strtol( in, &nexttoken, 10 );
538 if( 0 < argnum && argnum < Cmd_Argc() )
540 const char *param = Cmd_Argv( argnum );
541 while( *param && outlen < ALIAS_BUFFER ) {
547 else if( argnum >= Cmd_Argc() )
549 Con_Printf( "Warning: Not enough parameters passed to alias '%s', at least %i expected:\n %s\n", alias->name, argnum, alias->value );
554 else if( argnum == 0 )
567 #define ALIAS_BUFFER 1024
568 static char buffer[ ALIAS_BUFFER + 2 ];
569 Cmd_PreprocessString( alias->value, buffer, ALIAS_BUFFER, alias );
570 Cbuf_AddText( buffer );
577 CmdList Added by EvilTypeGuy eviltypeguy@qeradiant.com
578 Thanks to Matthias "Maddes" Buecher, http://www.inside3d.com/qip/
582 static void Cmd_List_f (void)
590 partial = Cmd_Argv (1);
591 len = (int)strlen(partial);
600 for (cmd = cmd_functions; cmd; cmd = cmd->next)
602 if (partial && strncmp(partial, cmd->name, len))
604 Con_Printf("%s\n", cmd->name);
608 Con_Printf("%i Command%s", count, (count > 1) ? "s" : "");
610 Con_Printf(" beginning with \"%s\"", partial);
622 cmd_mempool = Mem_AllocPool("commands", 0, NULL);
623 // space for commands and script files
624 cmd_text.data = cmd_text_buf;
625 cmd_text.maxsize = sizeof(cmd_text_buf);
626 cmd_text.cursize = 0;
629 void Cmd_Init_Commands (void)
632 // register our commands
634 Cmd_AddCommand ("stuffcmds",Cmd_StuffCmds_f);
635 Cmd_AddCommand ("exec",Cmd_Exec_f);
636 Cmd_AddCommand ("echo",Cmd_Echo_f);
637 Cmd_AddCommand ("alias",Cmd_Alias_f);
638 Cmd_AddCommand ("cmd", Cmd_ForwardToServer);
639 Cmd_AddCommand ("wait", Cmd_Wait_f);
640 Cmd_AddCommand ("cmdlist", Cmd_List_f); // Added/Modified by EvilTypeGuy eviltypeguy@qeradiant.com
641 Cmd_AddCommand ("cvarlist", Cvar_List_f); // 2000-01-09 CmdList, CvarList commands
642 // By Matthias "Maddes" Buecher
643 Cmd_AddCommand ("set", Cvar_Set_f);
644 Cmd_AddCommand ("seta", Cvar_SetA_f);
652 void Cmd_Shutdown(void)
654 Mem_FreePool(&cmd_mempool);
672 const char *Cmd_Argv (int arg)
674 if (arg >= cmd_argc )
675 return cmd_null_string;
676 return cmd_argv[arg];
684 const char *Cmd_Args (void)
694 Parses the given string into command line tokens.
697 // AK: This function should only be called from ExcuteString because the current design is a bit of an hack
698 static void Cmd_TokenizeString (const char *text)
707 // skip whitespace up to a /n
708 while (*text && *text <= ' ' && *text != '\r' && *text != '\n')
715 if (*text == '\n' || *text == '\r')
717 // a newline separates commands in the buffer
718 if (*text == '\r' && text[1] == '\n')
730 if (!COM_ParseTokenConsole(&text))
733 if (cmd_argc < MAX_ARGS)
735 l = (int)strlen(com_token) + 1;
736 if (cmd_tokenizebufferpos + l > CMD_TOKENIZELENGTH)
738 Con_Printf("Cmd_TokenizeString: ran out of %i character buffer space for command arguements\n", CMD_TOKENIZELENGTH);
741 strcpy (cmd_tokenizebuffer + cmd_tokenizebufferpos, com_token);
742 cmd_argv[cmd_argc] = cmd_tokenizebuffer + cmd_tokenizebufferpos;
743 cmd_tokenizebufferpos += l;
755 void Cmd_AddCommand (const char *cmd_name, xcommand_t function)
758 cmd_function_t *prev, *current;
760 // fail if the command is a variable name
761 if (Cvar_FindVar( cmd_name ))
763 Con_Printf("Cmd_AddCommand: %s already defined as a var\n", cmd_name);
767 // fail if the command already exists
768 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
770 if (!strcmp (cmd_name, cmd->name))
772 Con_Printf("Cmd_AddCommand: %s already defined\n", cmd_name);
777 cmd = (cmd_function_t *)Mem_Alloc(cmd_mempool, sizeof(cmd_function_t));
778 cmd->name = cmd_name;
779 cmd->function = function;
780 cmd->next = cmd_functions;
782 // insert it at the right alphanumeric position
783 for( prev = NULL, current = cmd_functions ; current && strcmp( current->name, cmd->name ) < 0 ; prev = current, current = current->next )
798 qboolean Cmd_Exists (const char *cmd_name)
802 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
803 if (!strcmp (cmd_name,cmd->name))
815 const char *Cmd_CompleteCommand (const char *partial)
820 len = strlen(partial);
826 for (cmd = cmd_functions; cmd; cmd = cmd->next)
827 if (!strncmp(partial, cmd->name, len))
834 Cmd_CompleteCountPossible
836 New function for tab-completion system
838 Thanks to Fett erich@heintz.com
842 int Cmd_CompleteCountPossible (const char *partial)
849 len = strlen(partial);
854 // Loop through the command list and count all partial matches
855 for (cmd = cmd_functions; cmd; cmd = cmd->next)
856 if (!strncasecmp(partial, cmd->name, len))
863 Cmd_CompleteBuildList
865 New function for tab-completion system
867 Thanks to Fett erich@heintz.com
871 const char **Cmd_CompleteBuildList (const char *partial)
876 size_t sizeofbuf = (Cmd_CompleteCountPossible (partial) + 1) * sizeof (const char *);
879 len = strlen(partial);
880 buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
881 // Loop through the alias list and print all matches
882 for (cmd = cmd_functions; cmd; cmd = cmd->next)
883 if (!strncasecmp(partial, cmd->name, len))
884 buf[bpos++] = cmd->name;
893 New function for tab-completion system
895 Thanks to Fett erich@heintz.com
899 const char *Cmd_CompleteAlias (const char *partial)
904 len = strlen(partial);
910 for (alias = cmd_alias; alias; alias = alias->next)
911 if (!strncasecmp(partial, alias->name, len))
918 Cmd_CompleteAliasCountPossible
920 New function for tab-completion system
922 Thanks to Fett erich@heintz.com
926 int Cmd_CompleteAliasCountPossible (const char *partial)
934 len = strlen(partial);
939 // Loop through the command list and count all partial matches
940 for (alias = cmd_alias; alias; alias = alias->next)
941 if (!strncasecmp(partial, alias->name, len))
948 Cmd_CompleteAliasBuildList
950 New function for tab-completion system
952 Thanks to Fett erich@heintz.com
956 const char **Cmd_CompleteAliasBuildList (const char *partial)
961 size_t sizeofbuf = (Cmd_CompleteAliasCountPossible (partial) + 1) * sizeof (const char *);
964 len = strlen(partial);
965 buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
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 buf[bpos++] = alias->name;
979 A complete command line has been parsed, so try to execute it
980 FIXME: lookupnoadd the token to speed search?
983 void Cmd_ExecuteString (const char *text, cmd_source_t src)
985 #define EXECUTESTRING_BUFFER 4096
986 static char buffer[ EXECUTESTRING_BUFFER ];
991 oldpos = cmd_tokenizebufferpos;
994 Cmd_PreprocessString( text, buffer, EXECUTESTRING_BUFFER, NULL );
995 Cmd_TokenizeString (buffer);
997 // execute the command line
1000 cmd_tokenizebufferpos = oldpos;
1001 return; // no tokens
1005 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1007 if (!strcasecmp (cmd_argv[0],cmd->name))
1010 cmd_tokenizebufferpos = oldpos;
1016 for (a=cmd_alias ; a ; a=a->next)
1018 if (!strcasecmp (cmd_argv[0], a->name))
1020 Cmd_ExecuteAlias(a);
1021 cmd_tokenizebufferpos = oldpos;
1027 if (!Cvar_Command () && host_framecount > 0)
1028 Con_Printf("Unknown command \"%s\"\n", Cmd_Argv(0));
1030 cmd_tokenizebufferpos = oldpos;
1036 Cmd_ForwardStringToServer
1038 Sends an entire command string over to the server, unprocessed
1041 void Cmd_ForwardStringToServer (const char *s)
1043 if (cls.state != ca_connected)
1045 Con_Printf("Can't \"%s\", not connected\n", s);
1049 if (cls.demoplayback)
1050 return; // not really connected
1052 // LordHavoc: thanks to Fuh for bringing the pure evil of SZ_Print to my
1053 // attention, it has been eradicated from here, its only (former) use in
1054 // all of darkplaces.
1055 MSG_WriteByte(&cls.message, clc_stringcmd);
1056 SZ_Write(&cls.message, (const unsigned char *)s, (int)strlen(s) + 1);
1063 Sends the entire command line over to the server
1066 void Cmd_ForwardToServer (void)
1069 if (!strcasecmp(Cmd_Argv(0), "cmd"))
1071 // we want to strip off "cmd", so just send the args
1072 s = Cmd_Argc() > 1 ? Cmd_Args() : "";
1076 // we need to keep the command name, so send Cmd_Argv(0), a space and then Cmd_Args()
1077 s = va("%s %s", Cmd_Argv(0), Cmd_Argc() > 1 ? Cmd_Args() : "");
1079 // don't send an empty forward message if the user tries "cmd" by itself
1082 Cmd_ForwardStringToServer(s);
1090 Returns the position (1 to argc-1) in the command's argument list
1091 where the given parameter apears, or 0 if not present
1095 int Cmd_CheckParm (const char *parm)
1101 Con_Printf ("Cmd_CheckParm: NULL");
1105 for (i = 1; i < Cmd_Argc (); i++)
1106 if (!strcasecmp (parm, Cmd_Argv (i)))