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 // div0: increased this from 32k to 128k
28 // div0: increased this from 128k to 640k which ought to be enough for anyone
29 #define CMDBUFSIZE 655360
30 // maximum number of parameters to a command
32 // maximum tokenizable commandline length (counting NUL terminations)
33 #define CMD_TOKENIZELENGTH (MAX_INPUTLINE + MAX_ARGS)
35 typedef struct cmdalias_s
37 struct cmdalias_s *next;
38 char name[MAX_ALIAS_NAME];
42 static cmdalias_t *cmd_alias;
44 static qboolean cmd_wait;
46 static mempool_t *cmd_mempool;
48 static char cmd_tokenizebuffer[CMD_TOKENIZELENGTH];
49 static int cmd_tokenizebufferpos = 0;
51 //=============================================================================
57 Causes execution of the remainder of the command buffer to be delayed until
58 next frame. This allows commands like:
59 bind g "impulse 5 ; +attack ; wait ; -attack ; impulse 2"
62 static void Cmd_Wait_f (void)
67 typedef struct cmddeferred_s
69 struct cmddeferred_s *next;
74 static cmddeferred_t *cmd_deferred_list = NULL;
80 Cause a command to be executed after a delay.
83 static void Cmd_Defer_f (void)
87 double time = Sys_DoubleTime();
88 cmddeferred_t *next = cmd_deferred_list;
90 Con_Printf("No commands are pending.\n");
93 Con_Printf("-> In %9.2f: %s\n", next->time-time, next->value);
96 } else if(Cmd_Argc() == 2 && !strcasecmp("clear", Cmd_Argv(1)))
98 while(cmd_deferred_list)
100 cmddeferred_t *cmd = cmd_deferred_list;
101 cmd_deferred_list = cmd->next;
102 Mem_Free(cmd->value);
105 } else if(Cmd_Argc() == 3)
107 const char *value = Cmd_Argv(2);
108 cmddeferred_t *defcmd = (cmddeferred_t*)Mem_Alloc(tempmempool, sizeof(*defcmd));
109 size_t len = strlen(value);
111 defcmd->time = Sys_DoubleTime() + atof(Cmd_Argv(1));
112 defcmd->value = (char*)Mem_Alloc(tempmempool, len+1);
113 memcpy(defcmd->value, value, len+1);
116 if(cmd_deferred_list)
118 cmddeferred_t *next = cmd_deferred_list;
123 cmd_deferred_list = defcmd;
124 /* Stupid me... this changes the order... so commands with the same delay go blub :S
125 defcmd->next = cmd_deferred_list;
126 cmd_deferred_list = defcmd;*/
128 Con_Printf("usage: defer <seconds> <command>\n"
138 Print something to the center of the screen using SCR_Centerprint
141 static void Cmd_Centerprint_f (void)
143 char msg[MAX_INPUTLINE];
144 unsigned int i, c, p;
148 strlcpy(msg, Cmd_Argv(1), sizeof(msg));
149 for(i = 2; i < c; ++i)
151 strlcat(msg, " ", sizeof(msg));
152 strlcat(msg, Cmd_Argv(i), sizeof(msg));
155 for(p = 0, i = 0; i < c; ++i)
161 else if(msg[i+1] == '\\')
173 SCR_CenterPrint(msg);
178 =============================================================================
182 =============================================================================
185 #define MAX_CONSOLE_INSTANCES 16
188 unsigned char text_buf[CMDBUFSIZE];
195 static memexpandablearray_t cmd_exec_array;
196 static size_t cmd_tid = 0;
197 static sizebuf_t *cmd_text = NULL;
198 static cmd_executor_t *cmd_ex = NULL;
199 static size_t cmd_num_executors = 0;
201 cvar_t con_this = {CVAR_READONLY, "_cthis","0", "the current console instance id"};
203 qboolean Con_Running(cmd_executor_t *ex, double systime)
207 if (ex->suspended || ex->sleep > systime)
211 cvar_t *c = Cvar_FindVar(ex->condvar);
224 size_t Con_GetTID(void)
229 qboolean Con_SetTID (size_t tid, qboolean quiet)
233 ex = Mem_ExpandableArray_RecordAtIndex(&cmd_exec_array, tid);
237 Con_Printf("Con_SetTID: no such id: %lu\n", (unsigned long)tid);
242 cmd_text = &ex->text;
244 Cvar_SetValueQuick(&con_this, tid);
248 cmd_executor_t *Con_Spawn(size_t *out_id)
253 if (cmd_num_executors >= MAX_CONSOLE_INSTANCES)
255 Con_Printf("Reached the maximum amount of console instances\n");
259 ex = (cmd_executor_t*)Mem_ExpandableArray_AllocRecord_Id(&cmd_exec_array, &id);
262 Con_Printf("Cannot spawn any more instances\n");
267 ex->text.data = ex->text_buf;
269 ex->text.maxsize = sizeof(ex->text_buf);
270 ex->text.cursize = 0;
273 ex->suspended = false;
281 void Con_Kill(size_t id)
285 Con_Print("Con_Kill(): Cannot kill console instance 0\n");
289 Con_SetTID(0, false);
290 Mem_ExpandableArray_FreeRecord(&cmd_exec_array, Mem_ExpandableArray_RecordAtIndex(&cmd_exec_array, id));
294 void Cbuf_AddTo (size_t tid, const char *text)
296 size_t old = Con_GetTID();
297 if (Con_SetTID(tid, false))
300 Con_SetTID(old, false);
304 static void Cmd_Spawn_f (void)
311 Con_Print("conspawn <cvar1> [<cvar2>...] : Spawn console instances and store the id into the given cvars\n");
315 for (i = 1; i < Cmd_Argc(); ++i)
320 Con_Printf("Failed to spawn instance for: %s\n", Cmd_Argv(i));
323 //Cvar_Set(Cmd_Argv(i), va("%i", (int)id));
324 //Cvar_SetValue(Cmd_Argv(i), id);
325 Cvar_Get(Cmd_Argv(i), va("%i", (int)id), 0, "a console instance");
329 static qboolean Con_ForName(const char *name, size_t *out_id, cmd_executor_t **out_ex)
335 if (isdigit(name[0]))
336 id = (size_t)atoi(name);
339 c = Cvar_FindVar(name);
342 id = (size_t)c->integer;
345 x = Mem_ExpandableArray_RecordAtIndex(&cmd_exec_array, id);
355 static void Cmd_SetTID_f (void)
360 Con_Print("setid <id|cvar> : Use the specified console instance by ID or cvar containing an ID\n");
363 if (!Con_ForName(Cmd_Argv(1), &tid, NULL))
365 Con_Printf("setid: invalid name: %s\n", Cmd_Argv(1));
368 if (!Con_SetTID(tid, false))
369 Con_Printf("setid: invalid instance: %s\n", Cmd_Argv(1));
372 static void Cmd_Sleep_f (void)
374 cmd_executor_t *ex = NULL;
375 double sleeptime = 0;
376 double systime = Sys_DoubleTime();
381 sleeptime = atof(Cmd_Argv(1));
383 else if (Cmd_Argc() == 3)
385 Con_ForName(Cmd_Argv(1), NULL, &ex);
386 sleeptime = atof(Cmd_Argv(2));
390 Con_Print("sleep [<instance>] <sleeptime> : let a console instance sleep for an amount of time\n"
391 "the time is added to the current sleep time\n");
396 Con_Print("sleep: cannot suspend instance 0\n");
400 if (ex->sleep < systime)
401 ex->sleep = systime + sleeptime;
403 ex->sleep += sleeptime;
404 if (ex->tid == cmd_ex->tid)
405 Con_SetTID(0, false);
408 static void Cmd_Suspend_f (void)
419 Con_Print("suspend [<instance1> [<instance2>...]] : Suspend the current or specified console instances\n"
420 "Error: you cannot suspend instance 0\n");
423 cmd_ex->suspended = true;
424 Con_SetTID(0, false);
428 for (i = 1; i < Cmd_Argc(); ++i)
430 if (!Con_ForName(Cmd_Argv(i), &id, &ex))
433 Con_Print("suspend: cannot suspend instance 0\n");
435 ex->suspended = true;
439 static void Cmd_Resume_f (void)
447 // No, we don't resume the current instance here, resume wouldn't be executed in the "current" instance...
448 Con_Print("resume <instance1> [<instance2>...] : Resume the specified console instances\n");
452 for (i = 1; i < Cmd_Argc(); ++i)
454 if (!Con_ForName(Cmd_Argv(i), &id, &ex))
456 ex->suspended = false;
460 static void Cmd_Cond_f (void)
469 Con_Print("xcond <cvar> [<instance>...] : Suspend a console instance until cvar becomes not-null\n");
474 if (!Cvar_FindVar(cvar))
476 Con_Printf("xcond: no such cvar \"%s\"\n", cvar);
485 Con_Print("xcond: Cannot suspend instance 0\n");
488 strlcpy(cmd_ex->condvar, cvar, sizeof(cmd_ex->condvar));
492 for (i = 2; i < Cmd_Argc(); ++i)
494 if (!Con_ForName(Cmd_Argv(i), NULL, &ex))
496 strlcpy(ex->condvar, cvar, sizeof(ex->condvar));
500 static void Cmd_CondLocal_f (void)
509 Con_Print("xcondl <cvar> [<instance>...] : Suspend a console instance until cvar becomes not-null\n");
520 Con_Print("xcondl: Cannot suspend instance 0\n");
523 dpsnprintf(cmd_ex->condvar, sizeof(cmd_ex->condvar), "_cin_%lu_%s", (unsigned long)cmd_tid, cvar);
527 for (i = 2; i < Cmd_Argc(); ++i)
529 if (!Con_ForName(Cmd_Argv(i), NULL, &ex))
531 dpsnprintf(ex->condvar, sizeof(ex->condvar), "_cin_%lu_%s",(unsigned long) ex->tid, cvar);
535 static void Cmd_XKill_f (void)
545 // termq = quiet, no warning when killing 0
546 if (strcmp(Cmd_Argv(0), "termq"))
547 Con_Print("term: cannot kill instance 0\n");
548 SZ_Clear(&cmd_ex->text);
555 for (i = 1; i < Cmd_Argc(); ++i)
557 if (!Con_ForName(Cmd_Argv(i), &id, NULL))
561 // termq = quiet, no warning when killing 0
562 if (strcmp(Cmd_Argv(0), "termq"))
563 Con_Print("term: cannot kill instance 0\n");
571 static void Cmd_XAdd_f (void)
578 Con_Print("xadd <instance> <command> : Append <command> to a console instance's command buffer\n");
582 if (!Con_ForName(Cmd_Argv(1), &id, NULL))
584 Con_Printf("xadd: invalid instance: %s\n", Cmd_Argv(1));
588 oldid = Con_GetTID();
589 if (!Con_SetTID(id, false))
591 Con_Printf("xadd: cannot append to %s\n", Cmd_Argv(1));
594 Cbuf_AddText(Cmd_Argv(2));
596 Con_SetTID(oldid, false);
599 static void Cmd_SetLocal_f (void)
601 static char varname[MAX_INPUTLINE];
604 // make sure it's the right number of parameters
607 Con_Printf("setlocal: wrong number of parameters, usage: setlocal <variablename> <value> [<description>]\n");
611 // check if it's read-only
612 cvar = Cvar_FindVar(Cmd_Argv(1));
613 if (cvar && cvar->flags & CVAR_READONLY)
615 Con_Printf("setlocal: %s is read-only\n", cvar->name);
619 if (developer.integer >= 100)
622 // all looks ok, create/modify the cvar
623 dpsnprintf(varname, sizeof(varname), "_cin_%lu_%s", (unsigned long)cmd_tid, Cmd_Argv(1));
624 Cvar_Get(varname, Cmd_Argv(2), 0, Cmd_Argc() > 3 ? Cmd_Argv(3) : NULL);
627 static void Cmd_SetForeign_f (void)
629 static char varname[MAX_INPUTLINE];
633 // make sure it's the right number of parameters
636 Con_Printf("setforeign: wrong number of parameters, usage: setforeign <instance> <variablename> <value> [<description>]\n");
640 if (!Con_ForName(Cmd_Argv(1), &id, NULL))
642 Con_Printf("setforeign: invalid instance: %s\n", Cmd_Argv(1));
646 // check if it's read-only
647 cvar = Cvar_FindVar(Cmd_Argv(2));
648 if (cvar && cvar->flags & CVAR_READONLY)
650 Con_Printf("setforeign: %s is read-only\n", cvar->name);
654 if (developer.integer >= 100)
657 // all looks ok, create/modify the cvar
658 dpsnprintf(varname, sizeof(varname), "_cin_%lu_%s", (unsigned long)id, Cmd_Argv(2));
659 Cvar_Get(varname, Cmd_Argv(3), 0, Cmd_Argc() > 4 ? Cmd_Argv(4) : NULL);
666 Adds command text at the end of the buffer
669 void Cbuf_AddText (const char *text)
673 l = (int)strlen (text);
675 if (cmd_text->cursize + l >= cmd_text->maxsize)
677 Con_Print("Cbuf_AddText: overflow\n");
681 SZ_Write (cmd_text, (const unsigned char *)text, (int)strlen (text));
689 Adds command text immediately after the current command
690 Adds a \n to the text
691 FIXME: actually change the command buffer to do less copying
694 void Cbuf_InsertText (const char *text)
699 // copy off any commands still remaining in the exec buffer
700 templen = cmd_text->cursize;
703 temp = (char *)Mem_Alloc (tempmempool, templen);
704 memcpy (temp, cmd_text->data, templen);
710 // add the entire text of the file
713 // add the copied off data
716 SZ_Write (cmd_text, (const unsigned char *)temp, templen);
723 Cbuf_Execute_Deferred --blub
726 void Cbuf_Execute_Deferred (void)
728 cmddeferred_t *cmd, *prev;
729 double time = Sys_DoubleTime();
731 cmd = cmd_deferred_list;
734 if(cmd->time <= time)
736 Cbuf_AddText(cmd->value);
738 Mem_Free(cmd->value);
741 prev->next = cmd->next;
745 cmd_deferred_list = cmd->next;
747 cmd = cmd_deferred_list;
761 static void Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias );
762 static void Cbuf_Execute_Instance (double systime);
763 void Cbuf_Execute (void)
768 double systime = Sys_DoubleTime();
770 Cbuf_Execute_Deferred();
772 oldid = Con_GetTID();
773 numtids = Mem_ExpandableArray_IndexRange(&cmd_exec_array);
774 for (tid = 0; tid < numtids; ++tid)
776 if (!Con_SetTID(tid, true))
778 if (!Con_Running(cmd_ex, systime))
780 Cbuf_Execute_Instance(systime);
782 if (!Con_SetTID(oldid, true))
783 Con_SetTID(0, false);
786 static void Cbuf_Execute_Instance (double systime)
790 char line[MAX_INPUTLINE];
791 char preprocessed[MAX_INPUTLINE];
793 qboolean quotes, comment;
797 // LordHavoc: making sure the tokenizebuffer doesn't get filled up by repeated crashes
798 cmd_tokenizebufferpos = 0;
801 while (cmd_ex->tid == id && Con_Running(cmd_ex, systime) && cmd_text->cursize && (cmd_ex->tid == 0 || ++runaway < 1000))
803 // find a \n or ; line break
804 text = (char *)cmd_text->data;
808 for (i=0 ; i < cmd_text->cursize ; i++)
817 // make sure i doesn't get > cursize which causes a negative
818 // size in memmove, which is fatal --blub
819 if (i < (cmd_text->cursize-1) && (text[i] == '\\' && (text[i+1] == '"' || text[i+1] == '\\')))
824 if(text[i] == '/' && text[i + 1] == '/' && (i == 0 || ISWHITESPACE(text[i-1])))
827 break; // don't break if inside a quoted string or comment
831 if (text[i] == '\r' || text[i] == '\n')
835 // better than CRASHING on overlong input lines that may SOMEHOW enter the buffer
836 if(i >= MAX_INPUTLINE)
838 Con_Printf("Warning: console input buffer had an overlong line. Ignored.\n");
843 memcpy (line, text, i);
847 // delete the text from the command buffer and move remaining commands down
848 // this is necessary because commands (exec, alias) can insert data at the
849 // beginning of the text buffer
851 if (i == cmd_text->cursize)
852 cmd_text->cursize = 0;
856 cmd_text->cursize -= i;
857 memmove (cmd_text->data, text+i, cmd_text->cursize);
860 // execute the command line
861 firstchar = line + strspn(line, " \t");
863 (strncmp(firstchar, "alias", 5) || (firstchar[5] != ' ' && firstchar[5] != '\t'))
865 (strncmp(firstchar, "bind", 4) || (firstchar[4] != ' ' && firstchar[4] != '\t'))
867 (strncmp(firstchar, "in_bind", 7) || (firstchar[7] != ' ' && firstchar[7] != '\t'))
870 Cmd_PreprocessString( line, preprocessed, sizeof(preprocessed), NULL );
871 Cmd_ExecuteString (preprocessed, src_command);
875 Cmd_ExecuteString (line, src_command);
879 { // skip out while text still remains in buffer, leaving it
888 ==============================================================================
892 ==============================================================================
899 Adds command line parameters as script statements
900 Commands lead with a +, and continue until a - or another +
901 quake +prog jctest.qp +cmd amlev1
902 quake -nosound +cmd amlev1
905 qboolean host_stuffcmdsrun = false;
906 void Cmd_StuffCmds_f (void)
909 // this is for all commandline options combined (and is bounds checked)
910 char build[MAX_INPUTLINE];
912 if (Cmd_Argc () != 1)
914 Con_Print("stuffcmds : execute command line parameters\n");
918 // no reason to run the commandline arguments twice
919 if (host_stuffcmdsrun)
922 host_stuffcmdsrun = true;
925 for (i = 0;i < com_argc;i++)
927 if (com_argv[i] && com_argv[i][0] == '+' && (com_argv[i][1] < '0' || com_argv[i][1] > '9') && l + strlen(com_argv[i]) - 1 <= sizeof(build) - 1)
930 while (com_argv[i][j])
931 build[l++] = com_argv[i][j++];
933 for (;i < com_argc;i++)
937 if ((com_argv[i][0] == '+' || com_argv[i][0] == '-') && (com_argv[i][1] < '0' || com_argv[i][1] > '9'))
939 if (l + strlen(com_argv[i]) + 4 > sizeof(build) - 1)
942 if (strchr(com_argv[i], ' '))
944 for (j = 0;com_argv[i][j];j++)
945 build[l++] = com_argv[i][j];
946 if (strchr(com_argv[i], ' '))
953 // now terminate the combined string and prepend it to the command buffer
954 // we already reserved space for the terminator
956 Cbuf_InsertText (build);
965 static void Cmd_Exec_f (void)
969 if (Cmd_Argc () != 2)
971 Con_Print("exec <filename> : execute a script file\n");
975 f = (char *)FS_LoadFile (Cmd_Argv(1), tempmempool, false, NULL);
978 Con_Printf("couldn't exec %s\n",Cmd_Argv(1));
981 Con_Printf("execing %s\n",Cmd_Argv(1));
983 // if executing default.cfg for the first time, lock the cvar defaults
984 // it may seem backwards to insert this text BEFORE the default.cfg
985 // but Cbuf_InsertText inserts before, so this actually ends up after it.
986 if (!strcmp(Cmd_Argv(1), "default.cfg"))
987 Cbuf_InsertText("\ncvar_lockdefaults\n");
989 // insert newline after the text to make sure the last line is terminated (some text editors omit the trailing newline)
990 // (note: insertion order here is backwards from execution order, so this adds it after the text, by calling it before...)
991 Cbuf_InsertText ("\n");
1001 Just prints the rest of the line to the console
1004 static void Cmd_Echo_f (void)
1008 for (i=1 ; i<Cmd_Argc() ; i++)
1009 Con_Printf("%s ",Cmd_Argv(i));
1014 // Support Doom3-style Toggle Console Command
1019 Toggles a specified console variable amongst the values specified (default is 0 and 1)
1022 static void Cmd_Toggle_f(void)
1024 // Acquire Number of Arguments
1025 int nNumArgs = Cmd_Argc();
1028 // No Arguments Specified; Print Usage
1029 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");
1031 { // Correct Arguments Specified
1032 // Acquire Potential CVar
1033 cvar_t* cvCVar = Cvar_FindVar( Cmd_Argv(1) );
1040 Cvar_SetValueQuick(cvCVar, 0);
1042 Cvar_SetValueQuick(cvCVar, 1);
1046 { // 0 and Specified Usage
1047 if(cvCVar->integer == atoi(Cmd_Argv(2) ) )
1048 // CVar is Specified Value; // Reset to 0
1049 Cvar_SetValueQuick(cvCVar, 0);
1051 if(cvCVar->integer == 0)
1052 // CVar is 0; Specify Value
1053 Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
1055 // CVar does not match; Reset to 0
1056 Cvar_SetValueQuick(cvCVar, 0);
1059 { // Variable Values Specified
1063 for(nCnt = 2; nCnt < nNumArgs; nCnt++)
1064 { // Cycle through Values
1065 if( strcmp(cvCVar->string, Cmd_Argv(nCnt) ) == 0)
1066 { // Current Value Located; Increment to Next
1067 if( (nCnt + 1) == nNumArgs)
1068 // Max Value Reached; Reset
1069 Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
1072 Cvar_SetQuick(cvCVar, Cmd_Argv(nCnt + 1) );
1081 // Value not Found; Reset to Original
1082 Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
1088 Con_Printf("ERROR : CVar '%s' not found\n", Cmd_Argv(1) );
1097 Creates a new command that executes a command string (possibly ; seperated)
1100 static void Cmd_Alias_f (void)
1103 char cmd[MAX_INPUTLINE];
1108 if (Cmd_Argc() == 1)
1110 Con_Print("Current alias commands:\n");
1111 for (a = cmd_alias ; a ; a=a->next)
1112 Con_Printf("%s : %s", a->name, a->value);
1117 if (strlen(s) >= MAX_ALIAS_NAME)
1119 Con_Print("Alias name is too long\n");
1123 // if the alias already exists, reuse it
1124 for (a = cmd_alias ; a ; a=a->next)
1126 if (!strcmp(s, a->name))
1135 cmdalias_t *prev, *current;
1137 a = (cmdalias_t *)Z_Malloc (sizeof(cmdalias_t));
1138 strlcpy (a->name, s, sizeof (a->name));
1139 // insert it at the right alphanumeric position
1140 for( prev = NULL, current = cmd_alias ; current && strcmp( current->name, a->name ) < 0 ; prev = current, current = current->next )
1151 // copy the rest of the command line
1152 cmd[0] = 0; // start out with a null string
1154 for (i=2 ; i< c ; i++)
1156 strlcat (cmd, Cmd_Argv(i), sizeof (cmd));
1158 strlcat (cmd, " ", sizeof (cmd));
1160 strlcat (cmd, "\n", sizeof (cmd));
1162 alloclen = strlen (cmd) + 1;
1164 cmd[alloclen - 2] = '\n'; // to make sure a newline is appended even if too long
1165 a->value = (char *)Z_Malloc (alloclen);
1166 memcpy (a->value, cmd, alloclen);
1173 Remove existing aliases.
1176 static void Cmd_UnAlias_f (void)
1184 Con_Print("unalias: Usage: unalias alias1 [alias2 ...]\n");
1188 for(i = 1; i < Cmd_Argc(); ++i)
1192 for(a = cmd_alias; a; p = a, a = a->next)
1194 if(!strcmp(s, a->name))
1197 cmd_alias = a->next;
1206 Con_Printf("unalias: %s alias not found\n", s);
1211 =============================================================================
1215 =============================================================================
1218 typedef struct cmd_function_s
1220 struct cmd_function_s *next;
1222 const char *description;
1223 xcommand_t consolefunction;
1224 xcommand_t clientfunction;
1228 static int cmd_argc;
1229 static const char *cmd_argv[MAX_ARGS];
1230 static const char *cmd_null_string = "";
1231 static const char *cmd_args;
1232 cmd_source_t cmd_source;
1235 static cmd_function_t *cmd_functions; // possible commands to execute
1237 static const char *Cmd_GetDirectCvarValue(const char *varname, cmdalias_t *alias, qboolean *is_multiple)
1244 *is_multiple = false;
1246 if(!varname || !*varname)
1251 if(!strcmp(varname, "*"))
1254 *is_multiple = true;
1257 else if(varname[strlen(varname) - 1] == '-')
1259 argno = strtol(varname, &endptr, 10);
1260 if(endptr == varname + strlen(varname) - 1)
1262 // whole string is a number, apart from the -
1263 const char *p = Cmd_Args();
1264 for(; argno > 1; --argno)
1265 if(!COM_ParseToken_Console(&p))
1270 *is_multiple = true;
1272 // kill pre-argument whitespace
1273 for (;*p && ISWHITESPACE(*p);p++)
1282 argno = strtol(varname, &endptr, 10);
1285 // whole string is a number
1286 // NOTE: we already made sure we don't have an empty cvar name!
1287 if(argno >= 0 && argno < Cmd_Argc())
1288 return Cmd_Argv(argno);
1293 if((cvar = Cvar_FindVar(varname)) && !(cvar->flags & CVAR_PRIVATE))
1294 return cvar->string;
1299 qboolean Cmd_QuoteString(char *out, size_t outlen, const char *in, const char *quoteset)
1301 qboolean quote_quot = !!strchr(quoteset, '"');
1302 qboolean quote_backslash = !!strchr(quoteset, '\\');
1303 qboolean quote_dollar = !!strchr(quoteset, '$');
1307 if(*in == '"' && quote_quot)
1314 *out++ = '\\'; --outlen;
1315 *out++ = '"'; --outlen;
1317 else if(*in == '\\' && quote_backslash)
1324 *out++ = '\\'; --outlen;
1325 *out++ = '\\'; --outlen;
1327 else if(*in == '$' && quote_dollar)
1334 *out++ = '$'; --outlen;
1335 *out++ = '$'; --outlen;
1344 *out++ = *in; --outlen;
1352 static const char *Cmd_GetCvarValue(const char *var, size_t varlen, cmdalias_t *alias)
1354 static char varname[MAX_INPUTLINE];
1355 static char varval[MAX_INPUTLINE];
1359 if(varlen >= MAX_INPUTLINE)
1360 varlen = MAX_INPUTLINE - 1;
1361 memcpy(varname, var, varlen);
1362 varname[varlen] = 0;
1363 varfunc = strchr(varname, ' ');
1369 if (!memcmp(varfunc, "local", 5) && (varfunc[5] == ' ' || !varfunc[5]))
1371 static char tmp[MAX_INPUTLINE];
1373 len = dpsnprintf(tmp, sizeof(tmp), "_cin_%lu_", (unsigned long)cmd_tid);
1374 memcpy(tmp + len, varname, varfunc - varname - 1);
1375 strlcpy(tmp + len + (varfunc - varname - 1), varfunc + 5, sizeof(tmp) - len - (varfunc - varname - 1));
1376 memcpy(varname, tmp, sizeof(varname));
1377 varfunc = strchr(varname, ' ');
1394 if(varname[0] == '$')
1395 varstr = Cmd_GetDirectCvarValue(Cmd_GetDirectCvarValue(varname + 1, alias, NULL), alias, NULL);
1398 qboolean is_multiple = false;
1399 // Exception: $* and $n- don't use the quoted form by default
1400 varstr = Cmd_GetDirectCvarValue(varname, alias, &is_multiple);
1409 Con_Printf("Warning: Could not expand $%s in alias %s\n", varname, alias->name);
1411 Con_Printf("Warning: Could not expand $%s\n", varname);
1415 if(!varfunc || !strcmp(varfunc, "q")) // note: quoted form is default, use "asis" to override!
1417 // quote it so it can be used inside double quotes
1418 // we just need to replace " by \", and of course, double backslashes
1419 Cmd_QuoteString(varval, sizeof(varval), varstr, "\"\\");
1422 else if(!strcmp(varfunc, "asis"))
1427 Con_Printf("Unknown variable function %s\n", varfunc);
1433 Cmd_PreprocessString
1435 Preprocesses strings and replaces $*, $param#, $cvar accordingly. Also strips comments.
1437 static void Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias ) {
1443 // don't crash if there's no room in the outtext buffer
1444 if( maxoutlen == 0 ) {
1447 maxoutlen--; // because of \0
1452 while( *in && outlen < maxoutlen ) {
1454 // this is some kind of expansion, see what comes after the $
1457 // The console does the following preprocessing:
1459 // - $$ is transformed to a single dollar sign.
1460 // - $var or ${var} are expanded to the contents of the named cvar,
1461 // with quotation marks and backslashes quoted so it can safely
1462 // be used inside quotation marks (and it should always be used
1464 // - ${var asis} inserts the cvar value as is, without doing this
1466 // - prefix the cvar name with a dollar sign to do indirection;
1467 // for example, if $x has the value timelimit, ${$x} will return
1468 // the value of $timelimit
1469 // - when expanding an alias, the special variable name $* refers
1470 // to all alias parameters, and a number refers to that numbered
1471 // alias parameter, where the name of the alias is $0, the first
1472 // parameter is $1 and so on; as a special case, $* inserts all
1473 // parameters, without extra quoting, so one can use $* to just
1474 // pass all parameters around. All parameters starting from $n
1475 // can be referred to as $n- (so $* is equivalent to $1-).
1477 // Note: when expanding an alias, cvar expansion is done in the SAME step
1478 // as alias expansion so that alias parameters or cvar values containing
1479 // dollar signs have no unwanted bad side effects. However, this needs to
1480 // be accounted for when writing complex aliases. For example,
1481 // alias foo "set x NEW; echo $x"
1482 // actually expands to
1483 // "set x NEW; echo OLD"
1484 // and will print OLD! To work around this, use a second alias:
1485 // alias foo "set x NEW; foo2"
1486 // alias foo2 "echo $x"
1488 // Also note: lines starting with alias are exempt from cvar expansion.
1489 // If you want cvar expansion, write "alias" instead:
1492 // alias foo "echo $x"
1493 // "alias" bar "echo $x"
1496 // foo will print 2, because the variable $x will be expanded when the alias
1497 // gets expanded. bar will print 1, because the variable $x was expanded
1498 // at definition time. foo can be equivalently defined as
1500 // "alias" foo "echo $$x"
1502 // because at definition time, $$ will get replaced to a single $.
1507 } else if(*in == '{') {
1508 varlen = strcspn(in + 1, "}");
1509 if(in[varlen + 1] == '}')
1511 val = Cmd_GetCvarValue(in + 1, varlen, alias);
1521 varlen = strspn(in, "*0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-");
1522 val = Cmd_GetCvarValue(in, varlen, alias);
1527 // insert the cvar value
1528 while(*val && outlen < maxoutlen)
1529 outtext[outlen++] = *val++;
1534 // copy the unexpanded text
1535 outtext[outlen++] = '$';
1536 while(eat && outlen < maxoutlen)
1538 outtext[outlen++] = *in++;
1544 outtext[outlen++] = *in++;
1546 outtext[outlen] = 0;
1553 Called for aliases and fills in the alias into the cbuffer
1556 static void Cmd_ExecuteAlias (cmdalias_t *alias)
1558 static char buffer[ MAX_INPUTLINE ];
1559 static char buffer2[ MAX_INPUTLINE ];
1560 Cmd_PreprocessString( alias->value, buffer, sizeof(buffer) - 2, alias );
1561 // insert at start of command buffer, so that aliases execute in order
1562 // (fixes bug introduced by Black on 20050705)
1564 // Note: Cbuf_PreprocessString will be called on this string AGAIN! So we
1565 // have to make sure that no second variable expansion takes place, otherwise
1566 // alias parameters containing dollar signs can have bad effects.
1567 Cmd_QuoteString(buffer2, sizeof(buffer2), buffer, "$");
1568 Cbuf_InsertText( buffer2 );
1575 CmdList Added by EvilTypeGuy eviltypeguy@qeradiant.com
1576 Thanks to Matthias "Maddes" Buecher, http://www.inside3d.com/qip/
1580 static void Cmd_List_f (void)
1582 cmd_function_t *cmd;
1583 const char *partial;
1590 partial = Cmd_Argv (1);
1591 len = strlen(partial);
1599 ispattern = partial && (strchr(partial, '*') || strchr(partial, '?'));
1602 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1604 if (partial && (ispattern ? !matchpattern_with_separator(cmd->name, partial, false, "", false) : strncmp(partial, cmd->name, len)))
1606 Con_Printf("%s : %s\n", cmd->name, cmd->description);
1613 Con_Printf("%i Command%s matching \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1615 Con_Printf("%i Command%s beginning with \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1618 Con_Printf("%i Command%s\n\n", count, (count > 1) ? "s" : "");
1621 static void Cmd_Apropos_f(void)
1623 cmd_function_t *cmd;
1626 const char *partial;
1633 partial = Cmd_Args();
1634 len = strlen(partial);
1638 Con_Printf("usage: apropos <string>\n");
1642 ispattern = partial && (strchr(partial, '*') || strchr(partial, '?'));
1645 partial = va("*%s*", partial);
1650 for (cvar = cvar_vars; cvar; cvar = cvar->next)
1652 if (!matchpattern_with_separator(cvar->name, partial, true, "", false))
1653 if (!matchpattern_with_separator(cvar->description, partial, true, "", false))
1655 Con_Printf ("cvar ^3%s^7 is \"%s\" [\"%s\"] %s\n", cvar->name, cvar->string, cvar->defstring, cvar->description);
1658 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1660 if (!matchpattern_with_separator(cmd->name, partial, true, "", false))
1661 if (!matchpattern_with_separator(cmd->description, partial, true, "", false))
1663 Con_Printf("command ^2%s^7: %s\n", cmd->name, cmd->description);
1666 for (alias = cmd_alias; alias; alias = alias->next)
1668 if (!matchpattern_with_separator(alias->name, partial, true, "", false))
1669 if (!matchpattern_with_separator(alias->value, partial, true, "", false))
1671 Con_Printf("alias ^5%s^7: %s", alias->name, alias->value);
1674 Con_Printf("%i result%s\n\n", count, (count > 1) ? "s" : "");
1682 void Cmd_Init (void)
1684 cmd_mempool = Mem_AllocPool("commands", 0, NULL);
1685 Cvar_RegisterVariable(&con_this);
1686 // space for commands and script files
1687 Mem_ExpandableArray_NewArray(&cmd_exec_array, cmd_mempool, sizeof(cmd_executor_t), 4);
1689 cmd_ex = Con_Spawn(&cmd_tid);
1690 Con_SetTID(cmd_tid, false);
1694 cmd_text = &cmd_exec[cmd_tid].text;
1695 cmd_text->data = cmd_exec[cmd_tid].text_buf;
1696 cmd_text->maxsize = sizeof(cmd_exec[cmd_tid].text_buf);
1697 cmd_text->cursize = 0;
1701 void Cmd_Init_Commands (void)
1704 // register our commands
1706 Cmd_AddCommand ("stuffcmds",Cmd_StuffCmds_f, "execute commandline parameters (must be present in quake.rc script)");
1707 Cmd_AddCommand ("exec",Cmd_Exec_f, "execute a script file");
1708 Cmd_AddCommand ("echo",Cmd_Echo_f, "print a message to the console (useful in scripts)");
1709 Cmd_AddCommand ("alias",Cmd_Alias_f, "create a script function (parameters are passed in as $X (being X a number), $* for all parameters, $X- for all parameters starting from $X). Without arguments show the list of all alias");
1710 Cmd_AddCommand ("unalias",Cmd_UnAlias_f, "remove an alias");
1711 Cmd_AddCommand ("cmd", Cmd_ForwardToServer, "send a console commandline to the server (used by some mods)");
1712 Cmd_AddCommand ("wait", Cmd_Wait_f, "make script execution wait for next rendered frame");
1713 Cmd_AddCommand ("set", Cvar_Set_f, "create or change the value of a console variable");
1714 Cmd_AddCommand ("seta", Cvar_SetA_f, "create or change the value of a console variable that will be saved to config.cfg");
1715 #ifdef FILLALLCVARSWITHRUBBISH
1716 Cmd_AddCommand ("fillallcvarswithrubbish", Cvar_FillAll_f, "fill all cvars with a specified number of characters to provoke buffer overruns");
1717 #endif /* FILLALLCVARSWITHRUBBISH */
1719 // 2000-01-09 CmdList, CvarList commands By Matthias "Maddes" Buecher
1720 // Added/Modified by EvilTypeGuy eviltypeguy@qeradiant.com
1721 Cmd_AddCommand ("cmdlist", Cmd_List_f, "lists all console commands beginning with the specified prefix or matching the specified wildcard pattern");
1722 Cmd_AddCommand ("cvarlist", Cvar_List_f, "lists all console variables beginning with the specified prefix or matching the specified wildcard pattern");
1723 Cmd_AddCommand ("apropos", Cmd_Apropos_f, "lists all console variables/commands/aliases containing the specified string in the name or description");
1725 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");
1726 Cmd_AddCommand ("cvar_resettodefaults_all", Cvar_ResetToDefaults_All_f, "sets all cvars to their locked default values");
1727 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)");
1728 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)");
1730 Cmd_AddCommand ("cprint", Cmd_Centerprint_f, "print something at the screen center");
1731 Cmd_AddCommand ("defer", Cmd_Defer_f, "execute a command in the future");
1733 Cmd_AddCommand ("conspawn", Cmd_Spawn_f, "spawn new console instances, their IDs are stored in the provided cvars");
1734 Cmd_AddCommand ("setid", Cmd_SetTID_f, "experts only! set the console-ID to which new input-commands are being added, has no effect when an invalid id is provided");
1735 Cmd_AddCommand ("sleep", Cmd_Sleep_f, "let the current, or a specific console instance sleep for some time in the background");
1736 Cmd_AddCommand ("cond", Cmd_Cond_f, "suspend a console instance until a cvar becomes true (not-null)");
1737 Cmd_AddCommand ("condl", Cmd_CondLocal_f, "suspend a console instance until a local cvar becomes true (not-null)");
1738 Cmd_AddCommand ("suspend", Cmd_Suspend_f, "suspend a console instance, when suspending the current console, this also does 'setid 0'");
1739 Cmd_AddCommand ("resume", Cmd_Resume_f, "resume the execution of a console instance");
1740 Cmd_AddCommand ("term", Cmd_XKill_f, "kill a console instance (doesn't work on id 0)");
1741 Cmd_AddCommand ("termq", Cmd_XKill_f, "kill a console instance (doesn't work on id 0)");
1742 Cmd_AddCommand ("xadd", Cmd_XAdd_f, "add a command to a console instance");
1743 Cmd_AddCommand ("setlocal", Cmd_SetLocal_f, "set a instance-local cvar");
1744 Cmd_AddCommand ("setforeign", Cmd_SetForeign_f, "set an instance's local cvar");
1747 // Support Doom3-style Toggle Command
1748 Cmd_AddCommand( "toggle", Cmd_Toggle_f, "toggles a console variable's values (use for more info)");
1756 void Cmd_Shutdown(void)
1758 Mem_FreePool(&cmd_mempool);
1776 const char *Cmd_Argv (int arg)
1778 if (arg >= cmd_argc )
1779 return cmd_null_string;
1780 return cmd_argv[arg];
1788 const char *Cmd_Args (void)
1798 Parses the given string into command line tokens.
1801 // AK: This function should only be called from ExcuteString because the current design is a bit of an hack
1802 static void Cmd_TokenizeString (const char *text)
1811 // skip whitespace up to a /n
1812 while (*text && ISWHITESPACE(*text) && *text != '\r' && *text != '\n')
1819 if (*text == '\n' || *text == '\r')
1821 // a newline separates commands in the buffer
1822 if (*text == '\r' && text[1] == '\n')
1834 if (!COM_ParseToken_Console(&text))
1837 if (cmd_argc < MAX_ARGS)
1839 l = (int)strlen(com_token) + 1;
1840 if (cmd_tokenizebufferpos + l > CMD_TOKENIZELENGTH)
1842 Con_Printf("Cmd_TokenizeString: ran out of %i character buffer space for command arguements\n", CMD_TOKENIZELENGTH);
1845 memcpy (cmd_tokenizebuffer + cmd_tokenizebufferpos, com_token, l);
1846 cmd_argv[cmd_argc] = cmd_tokenizebuffer + cmd_tokenizebufferpos;
1847 cmd_tokenizebufferpos += l;
1859 void Cmd_AddCommand_WithClientCommand (const char *cmd_name, xcommand_t consolefunction, xcommand_t clientfunction, const char *description)
1861 cmd_function_t *cmd;
1862 cmd_function_t *prev, *current;
1864 // fail if the command is a variable name
1865 if (Cvar_FindVar( cmd_name ))
1867 Con_Printf("Cmd_AddCommand: %s already defined as a var\n", cmd_name);
1871 // fail if the command already exists
1872 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1874 if (!strcmp (cmd_name, cmd->name))
1876 if (consolefunction || clientfunction)
1878 Con_Printf("Cmd_AddCommand: %s already defined\n", cmd_name);
1883 cmd->csqcfunc = true;
1889 cmd = (cmd_function_t *)Mem_Alloc(cmd_mempool, sizeof(cmd_function_t));
1890 cmd->name = cmd_name;
1891 cmd->consolefunction = consolefunction;
1892 cmd->clientfunction = clientfunction;
1893 cmd->description = description;
1894 if(!consolefunction && !clientfunction) //[515]: csqc
1895 cmd->csqcfunc = true;
1896 cmd->next = cmd_functions;
1898 // insert it at the right alphanumeric position
1899 for( prev = NULL, current = cmd_functions ; current && strcmp( current->name, cmd->name ) < 0 ; prev = current, current = current->next )
1904 cmd_functions = cmd;
1906 cmd->next = current;
1909 void Cmd_AddCommand (const char *cmd_name, xcommand_t function, const char *description)
1911 Cmd_AddCommand_WithClientCommand (cmd_name, function, NULL, description);
1919 qboolean Cmd_Exists (const char *cmd_name)
1921 cmd_function_t *cmd;
1923 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1924 if (!strcmp (cmd_name,cmd->name))
1936 const char *Cmd_CompleteCommand (const char *partial)
1938 cmd_function_t *cmd;
1941 len = strlen(partial);
1947 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1948 if (!strncasecmp(partial, cmd->name, len))
1955 Cmd_CompleteCountPossible
1957 New function for tab-completion system
1958 Added by EvilTypeGuy
1959 Thanks to Fett erich@heintz.com
1963 int Cmd_CompleteCountPossible (const char *partial)
1965 cmd_function_t *cmd;
1970 len = strlen(partial);
1975 // Loop through the command list and count all partial matches
1976 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1977 if (!strncasecmp(partial, cmd->name, len))
1984 Cmd_CompleteBuildList
1986 New function for tab-completion system
1987 Added by EvilTypeGuy
1988 Thanks to Fett erich@heintz.com
1992 const char **Cmd_CompleteBuildList (const char *partial)
1994 cmd_function_t *cmd;
1997 size_t sizeofbuf = (Cmd_CompleteCountPossible (partial) + 1) * sizeof (const char *);
2000 len = strlen(partial);
2001 buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
2002 // Loop through the alias list and print all matches
2003 for (cmd = cmd_functions; cmd; cmd = cmd->next)
2004 if (!strncasecmp(partial, cmd->name, len))
2005 buf[bpos++] = cmd->name;
2011 // written by LordHavoc
2012 void Cmd_CompleteCommandPrint (const char *partial)
2014 cmd_function_t *cmd;
2015 size_t len = strlen(partial);
2016 // Loop through the command list and print all matches
2017 for (cmd = cmd_functions; cmd; cmd = cmd->next)
2018 if (!strncasecmp(partial, cmd->name, len))
2019 Con_Printf("^2%s^7: %s\n", cmd->name, cmd->description);
2025 New function for tab-completion system
2026 Added by EvilTypeGuy
2027 Thanks to Fett erich@heintz.com
2031 const char *Cmd_CompleteAlias (const char *partial)
2036 len = strlen(partial);
2042 for (alias = cmd_alias; alias; alias = alias->next)
2043 if (!strncasecmp(partial, alias->name, len))
2049 // written by LordHavoc
2050 void Cmd_CompleteAliasPrint (const char *partial)
2053 size_t len = strlen(partial);
2054 // Loop through the alias list and print all matches
2055 for (alias = cmd_alias; alias; alias = alias->next)
2056 if (!strncasecmp(partial, alias->name, len))
2057 Con_Printf("^5%s^7: %s", alias->name, alias->value);
2062 Cmd_CompleteAliasCountPossible
2064 New function for tab-completion system
2065 Added by EvilTypeGuy
2066 Thanks to Fett erich@heintz.com
2070 int Cmd_CompleteAliasCountPossible (const char *partial)
2078 len = strlen(partial);
2083 // Loop through the command list and count all partial matches
2084 for (alias = cmd_alias; alias; alias = alias->next)
2085 if (!strncasecmp(partial, alias->name, len))
2092 Cmd_CompleteAliasBuildList
2094 New function for tab-completion system
2095 Added by EvilTypeGuy
2096 Thanks to Fett erich@heintz.com
2100 const char **Cmd_CompleteAliasBuildList (const char *partial)
2105 size_t sizeofbuf = (Cmd_CompleteAliasCountPossible (partial) + 1) * sizeof (const char *);
2108 len = strlen(partial);
2109 buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
2110 // Loop through the alias list and print all matches
2111 for (alias = cmd_alias; alias; alias = alias->next)
2112 if (!strncasecmp(partial, alias->name, len))
2113 buf[bpos++] = alias->name;
2119 void Cmd_ClearCsqcFuncs (void)
2121 cmd_function_t *cmd;
2122 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
2123 cmd->csqcfunc = false;
2126 qboolean CL_VM_ConsoleCommand (const char *cmd);
2131 A complete command line has been parsed, so try to execute it
2132 FIXME: lookupnoadd the token to speed search?
2135 void Cmd_ExecuteString (const char *text, cmd_source_t src)
2139 cmd_function_t *cmd;
2142 oldpos = cmd_tokenizebufferpos;
2146 Cmd_TokenizeString (text);
2148 // execute the command line
2151 cmd_tokenizebufferpos = oldpos;
2152 return; // no tokens
2156 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
2158 if (!strcasecmp (cmd_argv[0],cmd->name))
2160 if (cmd->csqcfunc && CL_VM_ConsoleCommand (text)) //[515]: csqc
2165 if (cmd->consolefunction)
2166 cmd->consolefunction ();
2167 else if (cmd->clientfunction)
2169 if (cls.state == ca_connected)
2171 // forward remote commands to the server for execution
2172 Cmd_ForwardToServer();
2175 Con_Printf("Can not send command \"%s\", not connected.\n", Cmd_Argv(0));
2178 Con_Printf("Command \"%s\" can not be executed\n", Cmd_Argv(0));
2183 if (cmd->clientfunction)
2185 cmd->clientfunction ();
2186 cmd_tokenizebufferpos = oldpos;
2196 // if it's a client command and no command was found, say so.
2197 if (cmd_source == src_client)
2199 Con_Printf("player \"%s\" tried to %s\n", host_client->name, text);
2200 cmd_tokenizebufferpos = oldpos;
2205 for (a=cmd_alias ; a ; a=a->next)
2207 if (!strcasecmp (cmd_argv[0], a->name))
2209 Cmd_ExecuteAlias(a);
2210 cmd_tokenizebufferpos = oldpos;
2215 if(found) // if the command was hooked and found, all is good
2217 cmd_tokenizebufferpos = oldpos;
2222 if (!Cvar_Command () && host_framecount > 0)
2223 Con_Printf("Unknown command \"%s\"\n", Cmd_Argv(0));
2225 cmd_tokenizebufferpos = oldpos;
2231 Cmd_ForwardStringToServer
2233 Sends an entire command string over to the server, unprocessed
2236 void Cmd_ForwardStringToServer (const char *s)
2239 if (cls.state != ca_connected)
2241 Con_Printf("Can't \"%s\", not connected\n", s);
2248 // LordHavoc: thanks to Fuh for bringing the pure evil of SZ_Print to my
2249 // attention, it has been eradicated from here, its only (former) use in
2250 // all of darkplaces.
2251 if (cls.protocol == PROTOCOL_QUAKEWORLD)
2252 MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
2254 MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
2255 if ((!strncmp(s, "say ", 4) || !strncmp(s, "say_team ", 9)) && cl_locs_enable.integer)
2257 // say/say_team commands can replace % character codes with status info
2260 if (*s == '%' && s[1])
2262 // handle proquake message macros
2266 case 'l': // current location
2267 CL_Locs_FindLocationName(temp, sizeof(temp), cl.movement_origin);
2269 case 'h': // current health
2270 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_HEALTH]);
2272 case 'a': // current armor
2273 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ARMOR]);
2275 case 'x': // current rockets
2276 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ROCKETS]);
2278 case 'c': // current cells
2279 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_CELLS]);
2281 // silly proquake macros
2282 case 'd': // loc at last death
2283 CL_Locs_FindLocationName(temp, sizeof(temp), cl.lastdeathorigin);
2285 case 't': // current time
2286 dpsnprintf(temp, sizeof(temp), "%.0f:%.0f", floor(cl.time / 60), cl.time - floor(cl.time / 60) * 60);
2288 case 'r': // rocket launcher status ("I have RL", "I need rockets", "I need RL")
2289 if (!(cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER))
2290 dpsnprintf(temp, sizeof(temp), "I need RL");
2291 else if (!cl.stats[STAT_ROCKETS])
2292 dpsnprintf(temp, sizeof(temp), "I need rockets");
2294 dpsnprintf(temp, sizeof(temp), "I have RL");
2296 case 'p': // powerup status (outputs "quad" "pent" and "eyes" according to status)
2297 if (cl.stats[STAT_ITEMS] & IT_QUAD)
2300 strlcat(temp, " ", sizeof(temp));
2301 strlcat(temp, "quad", sizeof(temp));
2303 if (cl.stats[STAT_ITEMS] & IT_INVULNERABILITY)
2306 strlcat(temp, " ", sizeof(temp));
2307 strlcat(temp, "pent", sizeof(temp));
2309 if (cl.stats[STAT_ITEMS] & IT_INVISIBILITY)
2312 strlcat(temp, " ", sizeof(temp));
2313 strlcat(temp, "eyes", sizeof(temp));
2316 case 'w': // weapon status (outputs "SSG:NG:SNG:GL:RL:LG" with the text between : characters omitted if you lack the weapon)
2317 if (cl.stats[STAT_ITEMS] & IT_SUPER_SHOTGUN)
2318 strlcat(temp, "SSG", sizeof(temp));
2319 strlcat(temp, ":", sizeof(temp));
2320 if (cl.stats[STAT_ITEMS] & IT_NAILGUN)
2321 strlcat(temp, "NG", sizeof(temp));
2322 strlcat(temp, ":", sizeof(temp));
2323 if (cl.stats[STAT_ITEMS] & IT_SUPER_NAILGUN)
2324 strlcat(temp, "SNG", sizeof(temp));
2325 strlcat(temp, ":", sizeof(temp));
2326 if (cl.stats[STAT_ITEMS] & IT_GRENADE_LAUNCHER)
2327 strlcat(temp, "GL", sizeof(temp));
2328 strlcat(temp, ":", sizeof(temp));
2329 if (cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER)
2330 strlcat(temp, "RL", sizeof(temp));
2331 strlcat(temp, ":", sizeof(temp));
2332 if (cl.stats[STAT_ITEMS] & IT_LIGHTNING)
2333 strlcat(temp, "LG", sizeof(temp));
2336 // not a recognized macro, print it as-is...
2342 // write the resulting text
2343 SZ_Write(&cls.netcon->message, (unsigned char *)temp, strlen(temp));
2347 MSG_WriteByte(&cls.netcon->message, *s);
2350 MSG_WriteByte(&cls.netcon->message, 0);
2352 else // any other command is passed on as-is
2353 SZ_Write(&cls.netcon->message, (const unsigned char *)s, (int)strlen(s) + 1);
2360 Sends the entire command line over to the server
2363 void Cmd_ForwardToServer (void)
2366 if (!strcasecmp(Cmd_Argv(0), "cmd"))
2368 // we want to strip off "cmd", so just send the args
2369 s = Cmd_Argc() > 1 ? Cmd_Args() : "";
2373 // we need to keep the command name, so send Cmd_Argv(0), a space and then Cmd_Args()
2374 s = va("%s %s", Cmd_Argv(0), Cmd_Argc() > 1 ? Cmd_Args() : "");
2376 // don't send an empty forward message if the user tries "cmd" by itself
2379 Cmd_ForwardStringToServer(s);
2387 Returns the position (1 to argc-1) in the command's argument list
2388 where the given parameter apears, or 0 if not present
2392 int Cmd_CheckParm (const char *parm)
2398 Con_Printf ("Cmd_CheckParm: NULL");
2402 for (i = 1; i < Cmd_Argc (); i++)
2403 if (!strcasecmp (parm, Cmd_Argv (i)))