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 typedef struct cmdalias_s
26 struct cmdalias_s *next;
27 char name[MAX_ALIAS_NAME];
31 static cmdalias_t *cmd_alias;
33 static qboolean cmd_wait;
35 static mempool_t *cmd_mempool;
37 static char cmd_tokenizebuffer[CMD_TOKENIZELENGTH];
38 static int cmd_tokenizebufferpos = 0;
40 //=============================================================================
46 Causes execution of the remainder of the command buffer to be delayed until
47 next frame. This allows commands like:
48 bind g "impulse 5 ; +attack ; wait ; -attack ; impulse 2"
51 static void Cmd_Wait_f (void)
56 typedef struct cmddeferred_s
58 struct cmddeferred_s *next;
63 static cmddeferred_t *cmd_deferred_list = NULL;
69 Cause a command to be executed after a delay.
72 static void Cmd_Defer_f (void)
76 double time = Sys_DoubleTime();
77 cmddeferred_t *next = cmd_deferred_list;
79 Con_Printf("No commands are pending.\n");
82 Con_Printf("-> In %9.2f: %s\n", next->time-time, next->value);
85 } else if(Cmd_Argc() == 2 && !strcasecmp("clear", Cmd_Argv(1)))
87 while(cmd_deferred_list)
89 cmddeferred_t *cmd = cmd_deferred_list;
90 cmd_deferred_list = cmd->next;
94 } else if(Cmd_Argc() == 3)
96 const char *value = Cmd_Argv(2);
97 cmddeferred_t *defcmd = (cmddeferred_t*)Mem_Alloc(tempmempool, sizeof(*defcmd));
98 size_t len = strlen(value);
100 defcmd->time = Sys_DoubleTime() + atof(Cmd_Argv(1));
101 defcmd->value = (char*)Mem_Alloc(tempmempool, len+1);
102 memcpy(defcmd->value, value, len+1);
105 if(cmd_deferred_list)
107 cmddeferred_t *next = cmd_deferred_list;
112 cmd_deferred_list = defcmd;
113 /* Stupid me... this changes the order... so commands with the same delay go blub :S
114 defcmd->next = cmd_deferred_list;
115 cmd_deferred_list = defcmd;*/
117 Con_Printf("usage: defer <seconds> <command>\n"
127 Print something to the center of the screen using SCR_Centerprint
130 static void Cmd_Centerprint_f (void)
132 char msg[MAX_INPUTLINE];
133 unsigned int i, c, p;
137 strlcpy(msg, Cmd_Argv(1), sizeof(msg));
138 for(i = 2; i < c; ++i)
140 strlcat(msg, " ", sizeof(msg));
141 strlcat(msg, Cmd_Argv(i), sizeof(msg));
144 for(p = 0, i = 0; i < c; ++i)
150 else if(msg[i+1] == '\\')
162 SCR_CenterPrint(msg);
167 =============================================================================
171 =============================================================================
174 #define MAX_CONSOLE_INSTANCES 16
177 unsigned char text_buf[CMDBUFSIZE];
182 double cps; // commands per second
186 static memexpandablearray_t cmd_exec_array;
187 static size_t cmd_tid = 0;
188 static sizebuf_t *cmd_text = NULL;
189 static cmd_executor_t *cmd_ex = NULL;
190 static size_t cmd_num_executors = 0;
192 cvar_t con_this = {CVAR_READONLY, "_cthis","0", "the current console instance id"};
194 qboolean Con_Running(cmd_executor_t *ex, double systime)
198 if (ex->suspended || ex->sleep > systime)
202 cvar_t *c = Cvar_FindVar(ex->condvar);
215 size_t Con_GetTID(void)
220 qboolean Con_SetTID (size_t tid, qboolean quiet)
224 ex = Mem_ExpandableArray_RecordAtIndex(&cmd_exec_array, tid);
228 Con_Printf("Con_SetTID: no such id: %lu\n", (unsigned long)tid);
233 cmd_text = &ex->text;
235 Cvar_SetValueQuick(&con_this, tid);
239 cmd_executor_t *Con_Spawn(size_t *out_id)
244 if (cmd_num_executors >= MAX_CONSOLE_INSTANCES)
246 Con_Printf("Reached the maximum amount of console instances\n");
250 ex = (cmd_executor_t*)Mem_ExpandableArray_AllocRecord_Id(&cmd_exec_array, &id);
253 Con_Printf("Cannot spawn any more instances\n");
258 ex->text.data = ex->text_buf;
260 ex->text.maxsize = sizeof(ex->text_buf);
261 ex->text.cursize = 0;
264 ex->suspended = false;
267 ex->lastTime = Sys_DoubleTime();
274 void Con_Kill(size_t id)
278 Con_Print("Con_Kill(): Cannot kill console instance 0\n");
282 Con_SetTID(0, false);
283 Mem_ExpandableArray_FreeRecord(&cmd_exec_array, Mem_ExpandableArray_RecordAtIndex(&cmd_exec_array, id));
287 void Cbuf_AddTo (size_t tid, const char *text)
289 size_t old = Con_GetTID();
290 if (Con_SetTID(tid, false))
293 Con_SetTID(old, false);
297 static void Cmd_Spawn_f (void)
304 Con_Print("conspawn <cvar1> [<cvar2>...] : Spawn console instances and store the id into the given cvars\n");
308 for (i = 1; i < Cmd_Argc(); ++i)
313 Con_Printf("Failed to spawn instance for: %s\n", Cmd_Argv(i));
316 //Cvar_Set(Cmd_Argv(i), va("%i", (int)id));
317 //Cvar_SetValue(Cmd_Argv(i), id);
318 Cvar_Get(Cmd_Argv(i), va("%i", (int)id), 0, "a console instance");
322 static qboolean Con_ForName(const char *name, size_t *out_id, cmd_executor_t **out_ex)
328 if (isdigit(name[0]))
329 id = (size_t)atoi(name);
332 c = Cvar_FindVar(name);
335 id = (size_t)c->integer;
338 x = Mem_ExpandableArray_RecordAtIndex(&cmd_exec_array, id);
348 static void Cmd_SetCPS_f (void)
356 Con_Print("setcps <cps> <instances>... : Set the CPS of the given instances to <cps>\n");
360 cps = atof(Cmd_Argv(1));
361 for (i = 2; i < Cmd_Argc(); ++i)
363 if(!Con_ForName(Cmd_Argv(i), NULL, &ex)) {
364 Con_Printf("setcps: unknown console: %s\n", Cmd_Argv(i));
371 static void Cmd_SetTID_f (void)
376 Con_Print("setid <id|cvar> : Use the specified console instance by ID or cvar containing an ID\n");
379 if (!Con_ForName(Cmd_Argv(1), &tid, NULL))
381 Con_Printf("setid: invalid name: %s\n", Cmd_Argv(1));
384 if (!Con_SetTID(tid, false))
385 Con_Printf("setid: invalid instance: %s\n", Cmd_Argv(1));
388 static void Cmd_Sleep_f (void)
390 cmd_executor_t *ex = NULL;
391 double sleeptime = 0;
392 double systime = Sys_DoubleTime();
397 sleeptime = atof(Cmd_Argv(1));
399 else if (Cmd_Argc() == 3)
401 Con_ForName(Cmd_Argv(1), NULL, &ex);
402 sleeptime = atof(Cmd_Argv(2));
406 Con_Print("sleep [<instance>] <sleeptime> : let a console instance sleep for an amount of time\n"
407 "the time is added to the current sleep time\n");
412 Con_Print("sleep: cannot suspend instance 0\n");
416 if (ex->sleep < systime)
417 ex->sleep = systime + sleeptime;
419 ex->sleep += sleeptime;
420 if (ex->tid == cmd_ex->tid)
421 Con_SetTID(0, false);
424 static void Cmd_Suspend_f (void)
435 Con_Print("suspend [<instance1> [<instance2>...]] : Suspend the current or specified console instances\n"
436 "Error: you cannot suspend instance 0\n");
439 cmd_ex->suspended = true;
440 Con_SetTID(0, false);
444 for (i = 1; i < Cmd_Argc(); ++i)
446 if (!Con_ForName(Cmd_Argv(i), &id, &ex))
449 Con_Print("suspend: cannot suspend instance 0\n");
451 ex->suspended = true;
455 static void Cmd_Resume_f (void)
463 // No, we don't resume the current instance here, resume wouldn't be executed in the "current" instance...
464 Con_Print("resume <instance1> [<instance2>...] : Resume the specified console instances\n");
468 for (i = 1; i < Cmd_Argc(); ++i)
470 if (!Con_ForName(Cmd_Argv(i), &id, &ex))
472 ex->suspended = false;
476 static void Cmd_Cond_f (void)
485 Con_Print("xcond <cvar> [<instance>...] : Suspend a console instance until cvar becomes not-null\n");
490 if (!Cvar_FindVar(cvar))
492 Con_Printf("xcond: no such cvar \"%s\"\n", cvar);
501 Con_Print("xcond: Cannot suspend instance 0\n");
504 strlcpy(cmd_ex->condvar, cvar, sizeof(cmd_ex->condvar));
508 for (i = 2; i < Cmd_Argc(); ++i)
510 if (!Con_ForName(Cmd_Argv(i), NULL, &ex))
512 strlcpy(ex->condvar, cvar, sizeof(ex->condvar));
516 static void Cmd_CondLocal_f (void)
525 Con_Print("xcondl <cvar> [<instance>...] : Suspend a console instance until cvar becomes not-null\n");
536 Con_Print("xcondl: Cannot suspend instance 0\n");
539 dpsnprintf(cmd_ex->condvar, sizeof(cmd_ex->condvar), "_cin_%lu_%s", (unsigned long)cmd_tid, cvar);
543 for (i = 2; i < Cmd_Argc(); ++i)
545 if (!Con_ForName(Cmd_Argv(i), NULL, &ex))
547 dpsnprintf(ex->condvar, sizeof(ex->condvar), "_cin_%lu_%s",(unsigned long) ex->tid, cvar);
551 static void Cmd_XKill_f (void)
561 // termq = quiet, no warning when killing 0
562 if (strcmp(Cmd_Argv(0), "termq"))
563 Con_Print("term: cannot kill instance 0\n");
564 SZ_Clear(&cmd_ex->text);
571 for (i = 1; i < Cmd_Argc(); ++i)
573 if (!Con_ForName(Cmd_Argv(i), &id, NULL))
577 // termq = quiet, no warning when killing 0
578 if (strcmp(Cmd_Argv(0), "termq"))
579 Con_Print("term: cannot kill instance 0\n");
587 static void Cmd_XAdd_f (void)
594 Con_Print("xadd <instance> <command> : Append <command> to a console instance's command buffer\n");
598 if (!Con_ForName(Cmd_Argv(1), &id, NULL))
600 Con_Printf("xadd: invalid instance: %s\n", Cmd_Argv(1));
604 oldid = Con_GetTID();
605 if (!Con_SetTID(id, false))
607 Con_Printf("xadd: cannot append to %s\n", Cmd_Argv(1));
610 Cbuf_AddText(Cmd_Argv(2));
612 Con_SetTID(oldid, false);
615 static void Cmd_SetLocal_f (void)
617 static char varname[MAX_INPUTLINE];
620 // make sure it's the right number of parameters
623 Con_Printf("setlocal: wrong number of parameters, usage: setlocal <variablename> <value> [<description>]\n");
627 // check if it's read-only
628 cvar = Cvar_FindVar(Cmd_Argv(1));
629 if (cvar && cvar->flags & CVAR_READONLY)
631 Con_Printf("setlocal: %s is read-only\n", cvar->name);
635 if (developer.integer >= 100)
638 // all looks ok, create/modify the cvar
639 dpsnprintf(varname, sizeof(varname), "_cin_%lu_%s", (unsigned long)cmd_tid, Cmd_Argv(1));
640 Cvar_Get(varname, Cmd_Argv(2), 0, Cmd_Argc() > 3 ? Cmd_Argv(3) : NULL);
643 static void Cmd_SetForeign_f (void)
645 static char varname[MAX_INPUTLINE];
649 // make sure it's the right number of parameters
652 Con_Printf("setforeign: wrong number of parameters, usage: setforeign <instance> <variablename> <value> [<description>]\n");
656 if (!Con_ForName(Cmd_Argv(1), &id, NULL))
658 Con_Printf("setforeign: invalid instance: %s\n", Cmd_Argv(1));
662 // check if it's read-only
663 cvar = Cvar_FindVar(Cmd_Argv(2));
664 if (cvar && cvar->flags & CVAR_READONLY)
666 Con_Printf("setforeign: %s is read-only\n", cvar->name);
670 if (developer.integer >= 100)
673 // all looks ok, create/modify the cvar
674 dpsnprintf(varname, sizeof(varname), "_cin_%lu_%s", (unsigned long)id, Cmd_Argv(2));
675 Cvar_Get(varname, Cmd_Argv(3), 0, Cmd_Argc() > 4 ? Cmd_Argv(4) : NULL);
682 Adds command text at the end of the buffer
685 void Cbuf_AddText (const char *text)
689 l = (int)strlen (text);
691 if (cmd_text->cursize + l >= cmd_text->maxsize)
693 Con_Print("Cbuf_AddText: overflow\n");
697 SZ_Write (cmd_text, (const unsigned char *)text, (int)strlen (text));
705 Adds command text immediately after the current command
706 Adds a \n to the text
707 FIXME: actually change the command buffer to do less copying
710 void Cbuf_InsertText (const char *text)
715 // copy off any commands still remaining in the exec buffer
716 templen = cmd_text->cursize;
719 temp = (char *)Mem_Alloc (tempmempool, templen);
720 memcpy (temp, cmd_text->data, templen);
726 // add the entire text of the file
729 // add the copied off data
732 SZ_Write (cmd_text, (const unsigned char *)temp, templen);
739 Cbuf_Execute_Deferred --blub
742 void Cbuf_Execute_Deferred (void)
744 cmddeferred_t *cmd, *prev;
745 double time = Sys_DoubleTime();
747 cmd = cmd_deferred_list;
750 if(cmd->time <= time)
752 Cbuf_AddText(cmd->value);
754 Mem_Free(cmd->value);
757 prev->next = cmd->next;
761 cmd_deferred_list = cmd->next;
763 cmd = cmd_deferred_list;
777 static void Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias );
778 static void Cbuf_Execute_Instance (double systime);
779 void Cbuf_Execute (void)
784 double systime = Sys_DoubleTime();
786 Cbuf_Execute_Deferred();
788 oldid = Con_GetTID();
789 numtids = Mem_ExpandableArray_IndexRange(&cmd_exec_array);
790 for (tid = 0; tid < numtids; ++tid)
792 if (!Con_SetTID(tid, true))
794 if (!Con_Running(cmd_ex, systime))
796 Cbuf_Execute_Instance(systime);
798 if (!Con_SetTID(oldid, true))
799 Con_SetTID(0, false);
802 static void Cbuf_Execute_Instance (double systime)
806 char line[MAX_INPUTLINE];
807 char preprocessed[MAX_INPUTLINE];
809 qboolean quotes, comment;
812 size_t runawaylimit = 1000;
814 // LordHavoc: making sure the tokenizebuffer doesn't get filled up by repeated crashes
815 cmd_tokenizebufferpos = 0;
817 // let's see how many commands we are allowed to execute:
818 if (cmd_ex->tid != 0 && cmd_ex->cps > 0) {
819 if (systime < cmd_ex->lastTime)
820 cmd_ex->lastTime = systime;
822 runawaylimit = cmd_ex->cps * (systime - cmd_ex->lastTime);
823 if (runawaylimit < 1)
825 cmd_ex->lastTime += runawaylimit / cmd_ex->cps;
829 while (cmd_ex->tid == id && Con_Running(cmd_ex, systime) && cmd_text->cursize && (cmd_ex->tid == 0 || runaway++ < runawaylimit))
831 // find a \n or ; line break
832 text = (char *)cmd_text->data;
836 for (i=0 ; i < cmd_text->cursize ; i++)
845 // make sure i doesn't get > cursize which causes a negative
846 // size in memmove, which is fatal --blub
847 if (i < (cmd_text->cursize-1) && (text[i] == '\\' && (text[i+1] == '"' || text[i+1] == '\\')))
852 if(text[i] == '/' && text[i + 1] == '/' && (i == 0 || ISWHITESPACE(text[i-1])))
855 break; // don't break if inside a quoted string or comment
859 if (text[i] == '\r' || text[i] == '\n')
863 // better than CRASHING on overlong input lines that may SOMEHOW enter the buffer
864 if(i >= MAX_INPUTLINE)
866 Con_Printf("Warning: console input buffer had an overlong line. Ignored.\n");
871 memcpy (line, text, i);
875 // delete the text from the command buffer and move remaining commands down
876 // this is necessary because commands (exec, alias) can insert data at the
877 // beginning of the text buffer
879 if (i == cmd_text->cursize)
880 cmd_text->cursize = 0;
884 cmd_text->cursize -= i;
885 memmove (cmd_text->data, text+i, cmd_text->cursize);
888 // execute the command line
889 firstchar = line + strspn(line, " \t");
891 (strncmp(firstchar, "alias", 5) || (firstchar[5] != ' ' && firstchar[5] != '\t'))
893 (strncmp(firstchar, "bind", 4) || (firstchar[4] != ' ' && firstchar[4] != '\t'))
895 (strncmp(firstchar, "in_bind", 7) || (firstchar[7] != ' ' && firstchar[7] != '\t'))
898 Cmd_PreprocessString( line, preprocessed, sizeof(preprocessed), NULL );
899 Cmd_ExecuteString (preprocessed, src_command);
903 Cmd_ExecuteString (line, src_command);
907 { // skip out while text still remains in buffer, leaving it
916 ==============================================================================
920 ==============================================================================
927 Adds command line parameters as script statements
928 Commands lead with a +, and continue until a - or another +
929 quake +prog jctest.qp +cmd amlev1
930 quake -nosound +cmd amlev1
933 qboolean host_stuffcmdsrun = false;
934 void Cmd_StuffCmds_f (void)
937 // this is for all commandline options combined (and is bounds checked)
938 char build[MAX_INPUTLINE];
940 if (Cmd_Argc () != 1)
942 Con_Print("stuffcmds : execute command line parameters\n");
946 // no reason to run the commandline arguments twice
947 if (host_stuffcmdsrun)
950 host_stuffcmdsrun = true;
953 for (i = 0;i < com_argc;i++)
955 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)
958 while (com_argv[i][j])
959 build[l++] = com_argv[i][j++];
961 for (;i < com_argc;i++)
965 if ((com_argv[i][0] == '+' || com_argv[i][0] == '-') && (com_argv[i][1] < '0' || com_argv[i][1] > '9'))
967 if (l + strlen(com_argv[i]) + 4 > sizeof(build) - 1)
970 if (strchr(com_argv[i], ' '))
972 for (j = 0;com_argv[i][j];j++)
973 build[l++] = com_argv[i][j];
974 if (strchr(com_argv[i], ' '))
981 // now terminate the combined string and prepend it to the command buffer
982 // we already reserved space for the terminator
984 Cbuf_InsertText (build);
993 static void Cmd_Exec_f (void)
996 const char *filename;
998 if (Cmd_Argc () != 2)
1000 Con_Print("exec <filename> : execute a script file\n");
1004 filename = Cmd_Argv(1);
1005 if (!strcmp(filename, "config.cfg"))
1006 filename = CONFIGFILENAME;
1008 f = (char *)FS_LoadFile (filename, tempmempool, false, NULL);
1011 Con_Printf("couldn't exec %s\n",filename);
1014 Con_Printf("execing %s\n",filename);
1016 // if executing default.cfg for the first time, lock the cvar defaults
1017 // it may seem backwards to insert this text BEFORE the default.cfg
1018 // but Cbuf_InsertText inserts before, so this actually ends up after it.
1019 if (strlen(filename) >= 11 && !strcmp(filename + strlen(filename) - 11, "default.cfg"))
1020 Cbuf_InsertText("\ncvar_lockdefaults\n");
1022 // insert newline after the text to make sure the last line is terminated (some text editors omit the trailing newline)
1023 // (note: insertion order here is backwards from execution order, so this adds it after the text, by calling it before...)
1024 Cbuf_InsertText ("\n");
1025 Cbuf_InsertText (f);
1034 Just prints the rest of the line to the console
1037 static void Cmd_Echo_f (void)
1041 for (i=1 ; i<Cmd_Argc() ; i++)
1042 Con_Printf("%s ",Cmd_Argv(i));
1047 // Support Doom3-style Toggle Console Command
1052 Toggles a specified console variable amongst the values specified (default is 0 and 1)
1055 static void Cmd_Toggle_f(void)
1057 // Acquire Number of Arguments
1058 int nNumArgs = Cmd_Argc();
1061 // No Arguments Specified; Print Usage
1062 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");
1064 { // Correct Arguments Specified
1065 // Acquire Potential CVar
1066 cvar_t* cvCVar = Cvar_FindVar( Cmd_Argv(1) );
1073 Cvar_SetValueQuick(cvCVar, 0);
1075 Cvar_SetValueQuick(cvCVar, 1);
1079 { // 0 and Specified Usage
1080 if(cvCVar->integer == atoi(Cmd_Argv(2) ) )
1081 // CVar is Specified Value; // Reset to 0
1082 Cvar_SetValueQuick(cvCVar, 0);
1084 if(cvCVar->integer == 0)
1085 // CVar is 0; Specify Value
1086 Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
1088 // CVar does not match; Reset to 0
1089 Cvar_SetValueQuick(cvCVar, 0);
1092 { // Variable Values Specified
1096 for(nCnt = 2; nCnt < nNumArgs; nCnt++)
1097 { // Cycle through Values
1098 if( strcmp(cvCVar->string, Cmd_Argv(nCnt) ) == 0)
1099 { // Current Value Located; Increment to Next
1100 if( (nCnt + 1) == nNumArgs)
1101 // Max Value Reached; Reset
1102 Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
1105 Cvar_SetQuick(cvCVar, Cmd_Argv(nCnt + 1) );
1114 // Value not Found; Reset to Original
1115 Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
1121 Con_Printf("ERROR : CVar '%s' not found\n", Cmd_Argv(1) );
1130 Creates a new command that executes a command string (possibly ; seperated)
1133 static void Cmd_Alias_f (void)
1136 char cmd[MAX_INPUTLINE];
1141 if (Cmd_Argc() == 1)
1143 Con_Print("Current alias commands:\n");
1144 for (a = cmd_alias ; a ; a=a->next)
1145 Con_Printf("%s : %s", a->name, a->value);
1150 if (strlen(s) >= MAX_ALIAS_NAME)
1152 Con_Print("Alias name is too long\n");
1156 // if the alias already exists, reuse it
1157 for (a = cmd_alias ; a ; a=a->next)
1159 if (!strcmp(s, a->name))
1168 cmdalias_t *prev, *current;
1170 a = (cmdalias_t *)Z_Malloc (sizeof(cmdalias_t));
1171 strlcpy (a->name, s, sizeof (a->name));
1172 // insert it at the right alphanumeric position
1173 for( prev = NULL, current = cmd_alias ; current && strcmp( current->name, a->name ) < 0 ; prev = current, current = current->next )
1184 // copy the rest of the command line
1185 cmd[0] = 0; // start out with a null string
1187 for (i=2 ; i< c ; i++)
1189 strlcat (cmd, Cmd_Argv(i), sizeof (cmd));
1191 strlcat (cmd, " ", sizeof (cmd));
1193 strlcat (cmd, "\n", sizeof (cmd));
1195 alloclen = strlen (cmd) + 1;
1197 cmd[alloclen - 2] = '\n'; // to make sure a newline is appended even if too long
1198 a->value = (char *)Z_Malloc (alloclen);
1199 memcpy (a->value, cmd, alloclen);
1206 Remove existing aliases.
1209 static void Cmd_UnAlias_f (void)
1217 Con_Print("unalias: Usage: unalias alias1 [alias2 ...]\n");
1221 for(i = 1; i < Cmd_Argc(); ++i)
1225 for(a = cmd_alias; a; p = a, a = a->next)
1227 if(!strcmp(s, a->name))
1230 cmd_alias = a->next;
1239 Con_Printf("unalias: %s alias not found\n", s);
1244 =============================================================================
1248 =============================================================================
1251 typedef struct cmd_function_s
1253 struct cmd_function_s *next;
1255 const char *description;
1256 xcommand_t consolefunction;
1257 xcommand_t clientfunction;
1261 static int cmd_argc;
1262 static const char *cmd_argv[MAX_ARGS];
1263 static const char *cmd_null_string = "";
1264 static const char *cmd_args;
1265 cmd_source_t cmd_source;
1268 static cmd_function_t *cmd_functions; // possible commands to execute
1270 static const char *Cmd_GetDirectCvarValue(const char *varname, cmdalias_t *alias, qboolean *is_multiple)
1277 *is_multiple = false;
1279 if(!varname || !*varname)
1284 if(!strcmp(varname, "*"))
1287 *is_multiple = true;
1290 else if(!strcmp(varname, "#"))
1292 return va("%d", Cmd_Argc());
1294 else if(varname[strlen(varname) - 1] == '-')
1296 argno = strtol(varname, &endptr, 10);
1297 if(endptr == varname + strlen(varname) - 1)
1299 // whole string is a number, apart from the -
1300 const char *p = Cmd_Args();
1301 for(; argno > 1; --argno)
1302 if(!COM_ParseToken_Console(&p))
1307 *is_multiple = true;
1309 // kill pre-argument whitespace
1310 for (;*p && ISWHITESPACE(*p);p++)
1319 argno = strtol(varname, &endptr, 10);
1322 // whole string is a number
1323 // NOTE: we already made sure we don't have an empty cvar name!
1324 if(argno >= 0 && argno < Cmd_Argc())
1325 return Cmd_Argv(argno);
1330 if((cvar = Cvar_FindVar(varname)) && !(cvar->flags & CVAR_PRIVATE))
1331 return cvar->string;
1336 qboolean Cmd_QuoteString(char *out, size_t outlen, const char *in, const char *quoteset)
1338 qboolean quote_quot = !!strchr(quoteset, '"');
1339 qboolean quote_backslash = !!strchr(quoteset, '\\');
1340 qboolean quote_dollar = !!strchr(quoteset, '$');
1344 if(*in == '"' && quote_quot)
1351 *out++ = '\\'; --outlen;
1352 *out++ = '"'; --outlen;
1354 else if(*in == '\\' && quote_backslash)
1361 *out++ = '\\'; --outlen;
1362 *out++ = '\\'; --outlen;
1364 else if(*in == '$' && quote_dollar)
1371 *out++ = '$'; --outlen;
1372 *out++ = '$'; --outlen;
1381 *out++ = *in; --outlen;
1389 static const char *Cmd_GetCvarValue(const char *var, size_t varlen, cmdalias_t *alias)
1391 static char varname[MAX_INPUTLINE];
1392 static char varval[MAX_INPUTLINE];
1396 if(varlen >= MAX_INPUTLINE)
1397 varlen = MAX_INPUTLINE - 1;
1398 memcpy(varname, var, varlen);
1399 varname[varlen] = 0;
1400 varfunc = strchr(varname, ' ');
1406 if (!memcmp(varfunc, "local", 5) && (varfunc[5] == ' ' || !varfunc[5]))
1408 static char tmp[MAX_INPUTLINE];
1410 len = dpsnprintf(tmp, sizeof(tmp), "_cin_%lu_", (unsigned long)cmd_tid);
1411 memcpy(tmp + len, varname, varfunc - varname - 1);
1412 strlcpy(tmp + len + (varfunc - varname - 1), varfunc + 5, sizeof(tmp) - len - (varfunc - varname - 1));
1413 memcpy(varname, tmp, sizeof(varname));
1414 varfunc = strchr(varname, ' ');
1431 if(varname[0] == '$')
1432 varstr = Cmd_GetDirectCvarValue(Cmd_GetDirectCvarValue(varname + 1, alias, NULL), alias, NULL);
1435 qboolean is_multiple = false;
1436 // Exception: $* and $n- don't use the quoted form by default
1437 varstr = Cmd_GetDirectCvarValue(varname, alias, &is_multiple);
1446 Con_Printf("Warning: Could not expand $%s in alias %s\n", varname, alias->name);
1448 Con_Printf("Warning: Could not expand $%s\n", varname);
1452 if(!varfunc || !strcmp(varfunc, "q")) // note: quoted form is default, use "asis" to override!
1454 // quote it so it can be used inside double quotes
1455 // we just need to replace " by \", and of course, double backslashes
1456 Cmd_QuoteString(varval, sizeof(varval), varstr, "\"\\");
1459 else if(!strcmp(varfunc, "asis"))
1464 Con_Printf("Unknown variable function %s\n", varfunc);
1470 Cmd_PreprocessString
1472 Preprocesses strings and replaces $*, $param#, $cvar accordingly. Also strips comments.
1474 static void Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias ) {
1480 // don't crash if there's no room in the outtext buffer
1481 if( maxoutlen == 0 ) {
1484 maxoutlen--; // because of \0
1489 while( *in && outlen < maxoutlen ) {
1491 // this is some kind of expansion, see what comes after the $
1494 // The console does the following preprocessing:
1496 // - $$ is transformed to a single dollar sign.
1497 // - $var or ${var} are expanded to the contents of the named cvar,
1498 // with quotation marks and backslashes quoted so it can safely
1499 // be used inside quotation marks (and it should always be used
1501 // - ${var asis} inserts the cvar value as is, without doing this
1503 // - prefix the cvar name with a dollar sign to do indirection;
1504 // for example, if $x has the value timelimit, ${$x} will return
1505 // the value of $timelimit
1506 // - when expanding an alias, the special variable name $* refers
1507 // to all alias parameters, and a number refers to that numbered
1508 // alias parameter, where the name of the alias is $0, the first
1509 // parameter is $1 and so on; as a special case, $* inserts all
1510 // parameters, without extra quoting, so one can use $* to just
1511 // pass all parameters around. All parameters starting from $n
1512 // can be referred to as $n- (so $* is equivalent to $1-).
1514 // Note: when expanding an alias, cvar expansion is done in the SAME step
1515 // as alias expansion so that alias parameters or cvar values containing
1516 // dollar signs have no unwanted bad side effects. However, this needs to
1517 // be accounted for when writing complex aliases. For example,
1518 // alias foo "set x NEW; echo $x"
1519 // actually expands to
1520 // "set x NEW; echo OLD"
1521 // and will print OLD! To work around this, use a second alias:
1522 // alias foo "set x NEW; foo2"
1523 // alias foo2 "echo $x"
1525 // Also note: lines starting with alias are exempt from cvar expansion.
1526 // If you want cvar expansion, write "alias" instead:
1529 // alias foo "echo $x"
1530 // "alias" bar "echo $x"
1533 // foo will print 2, because the variable $x will be expanded when the alias
1534 // gets expanded. bar will print 1, because the variable $x was expanded
1535 // at definition time. foo can be equivalently defined as
1537 // "alias" foo "echo $$x"
1539 // because at definition time, $$ will get replaced to a single $.
1544 } else if(*in == '{') {
1545 varlen = strcspn(in + 1, "}");
1546 if(in[varlen + 1] == '}')
1548 val = Cmd_GetCvarValue(in + 1, varlen, alias);
1558 varlen = strspn(in, "#*0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-");
1559 val = Cmd_GetCvarValue(in, varlen, alias);
1564 // insert the cvar value
1565 while(*val && outlen < maxoutlen)
1566 outtext[outlen++] = *val++;
1571 // copy the unexpanded text
1572 outtext[outlen++] = '$';
1573 while(eat && outlen < maxoutlen)
1575 outtext[outlen++] = *in++;
1581 outtext[outlen++] = *in++;
1583 outtext[outlen] = 0;
1590 Called for aliases and fills in the alias into the cbuffer
1593 static void Cmd_ExecuteAlias (cmdalias_t *alias)
1595 static char buffer[ MAX_INPUTLINE ];
1596 static char buffer2[ MAX_INPUTLINE ];
1597 Cmd_PreprocessString( alias->value, buffer, sizeof(buffer) - 2, alias );
1598 // insert at start of command buffer, so that aliases execute in order
1599 // (fixes bug introduced by Black on 20050705)
1601 // Note: Cbuf_PreprocessString will be called on this string AGAIN! So we
1602 // have to make sure that no second variable expansion takes place, otherwise
1603 // alias parameters containing dollar signs can have bad effects.
1604 Cmd_QuoteString(buffer2, sizeof(buffer2), buffer, "$");
1605 Cbuf_InsertText( buffer2 );
1612 CmdList Added by EvilTypeGuy eviltypeguy@qeradiant.com
1613 Thanks to Matthias "Maddes" Buecher, http://www.inside3d.com/qip/
1617 static void Cmd_List_f (void)
1619 cmd_function_t *cmd;
1620 const char *partial;
1627 partial = Cmd_Argv (1);
1628 len = strlen(partial);
1636 ispattern = partial && (strchr(partial, '*') || strchr(partial, '?'));
1639 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1641 if (partial && (ispattern ? !matchpattern_with_separator(cmd->name, partial, false, "", false) : strncmp(partial, cmd->name, len)))
1643 Con_Printf("%s : %s\n", cmd->name, cmd->description);
1650 Con_Printf("%i Command%s matching \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1652 Con_Printf("%i Command%s beginning with \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1655 Con_Printf("%i Command%s\n\n", count, (count > 1) ? "s" : "");
1658 static void Cmd_Apropos_f(void)
1660 cmd_function_t *cmd;
1663 const char *partial;
1670 partial = Cmd_Args();
1671 len = strlen(partial);
1675 Con_Printf("usage: apropos <string>\n");
1679 ispattern = partial && (strchr(partial, '*') || strchr(partial, '?'));
1682 partial = va("*%s*", partial);
1687 for (cvar = cvar_vars; cvar; cvar = cvar->next)
1689 if (!matchpattern_with_separator(cvar->name, partial, true, "", false))
1690 if (!matchpattern_with_separator(cvar->description, partial, true, "", false))
1692 Con_Printf ("cvar ^3%s^7 is \"%s\" [\"%s\"] %s\n", cvar->name, cvar->string, cvar->defstring, cvar->description);
1695 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1697 if (!matchpattern_with_separator(cmd->name, partial, true, "", false))
1698 if (!matchpattern_with_separator(cmd->description, partial, true, "", false))
1700 Con_Printf("command ^2%s^7: %s\n", cmd->name, cmd->description);
1703 for (alias = cmd_alias; alias; alias = alias->next)
1705 if (!matchpattern_with_separator(alias->name, partial, true, "", false))
1706 if (!matchpattern_with_separator(alias->value, partial, true, "", false))
1708 Con_Printf("alias ^5%s^7: %s", alias->name, alias->value);
1711 Con_Printf("%i result%s\n\n", count, (count > 1) ? "s" : "");
1719 void Cmd_Init (void)
1721 cmd_mempool = Mem_AllocPool("commands", 0, NULL);
1722 Cvar_RegisterVariable(&con_this);
1723 // space for commands and script files
1724 Mem_ExpandableArray_NewArray(&cmd_exec_array, cmd_mempool, sizeof(cmd_executor_t), 4);
1726 cmd_ex = Con_Spawn(&cmd_tid);
1727 Con_SetTID(cmd_tid, false);
1731 cmd_text = &cmd_exec[cmd_tid].text;
1732 cmd_text->data = cmd_exec[cmd_tid].text_buf;
1733 cmd_text->maxsize = sizeof(cmd_exec[cmd_tid].text_buf);
1734 cmd_text->cursize = 0;
1738 void Cmd_Init_Commands (void)
1741 // register our commands
1743 Cmd_AddCommand ("stuffcmds",Cmd_StuffCmds_f, "execute commandline parameters (must be present in quake.rc script)");
1744 Cmd_AddCommand ("exec",Cmd_Exec_f, "execute a script file");
1745 Cmd_AddCommand ("echo",Cmd_Echo_f, "print a message to the console (useful in scripts)");
1746 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");
1747 Cmd_AddCommand ("unalias",Cmd_UnAlias_f, "remove an alias");
1748 Cmd_AddCommand ("cmd", Cmd_ForwardToServer, "send a console commandline to the server (used by some mods)");
1749 Cmd_AddCommand ("wait", Cmd_Wait_f, "make script execution wait for next rendered frame");
1750 Cmd_AddCommand ("set", Cvar_Set_f, "create or change the value of a console variable");
1751 Cmd_AddCommand ("seta", Cvar_SetA_f, "create or change the value of a console variable that will be saved to config.cfg");
1752 #ifdef FILLALLCVARSWITHRUBBISH
1753 Cmd_AddCommand ("fillallcvarswithrubbish", Cvar_FillAll_f, "fill all cvars with a specified number of characters to provoke buffer overruns");
1754 #endif /* FILLALLCVARSWITHRUBBISH */
1756 // 2000-01-09 CmdList, CvarList commands By Matthias "Maddes" Buecher
1757 // Added/Modified by EvilTypeGuy eviltypeguy@qeradiant.com
1758 Cmd_AddCommand ("cmdlist", Cmd_List_f, "lists all console commands beginning with the specified prefix or matching the specified wildcard pattern");
1759 Cmd_AddCommand ("cvarlist", Cvar_List_f, "lists all console variables beginning with the specified prefix or matching the specified wildcard pattern");
1760 Cmd_AddCommand ("apropos", Cmd_Apropos_f, "lists all console variables/commands/aliases containing the specified string in the name or description");
1762 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");
1763 Cmd_AddCommand ("cvar_resettodefaults_all", Cvar_ResetToDefaults_All_f, "sets all cvars to their locked default values");
1764 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)");
1765 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)");
1767 Cmd_AddCommand ("cprint", Cmd_Centerprint_f, "print something at the screen center");
1768 Cmd_AddCommand ("defer", Cmd_Defer_f, "execute a command in the future");
1770 Cmd_AddCommand ("conspawn", Cmd_Spawn_f, "spawn new console instances, their IDs are stored in the provided cvars");
1771 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");
1772 Cmd_AddCommand ("sleep", Cmd_Sleep_f, "let the current, or a specific console instance sleep for some time in the background");
1773 Cmd_AddCommand ("cond", Cmd_Cond_f, "suspend a console instance until a cvar becomes true (not-null)");
1774 Cmd_AddCommand ("condl", Cmd_CondLocal_f, "suspend a console instance until a local cvar becomes true (not-null)");
1775 Cmd_AddCommand ("suspend", Cmd_Suspend_f, "suspend a console instance, when suspending the current console, this also does 'setid 0'");
1776 Cmd_AddCommand ("resume", Cmd_Resume_f, "resume the execution of a console instance");
1777 Cmd_AddCommand ("term", Cmd_XKill_f, "kill a console instance (doesn't work on id 0)");
1778 Cmd_AddCommand ("termq", Cmd_XKill_f, "kill a console instance (doesn't work on id 0)");
1779 Cmd_AddCommand ("xadd", Cmd_XAdd_f, "add a command to a console instance");
1780 Cmd_AddCommand ("setlocal", Cmd_SetLocal_f, "set a instance-local cvar");
1781 Cmd_AddCommand ("setforeign", Cmd_SetForeign_f, "set an instance's local cvar");
1782 Cmd_AddCommand ("setcps", Cmd_SetCPS_f, "set the commands executed per second in a console instance");
1785 // Support Doom3-style Toggle Command
1786 Cmd_AddCommand( "toggle", Cmd_Toggle_f, "toggles a console variable's values (use for more info)");
1794 void Cmd_Shutdown(void)
1796 Mem_FreePool(&cmd_mempool);
1814 const char *Cmd_Argv (int arg)
1816 if (arg >= cmd_argc )
1817 return cmd_null_string;
1818 return cmd_argv[arg];
1826 const char *Cmd_Args (void)
1836 Parses the given string into command line tokens.
1839 // AK: This function should only be called from ExcuteString because the current design is a bit of an hack
1840 static void Cmd_TokenizeString (const char *text)
1849 // skip whitespace up to a /n
1850 while (*text && ISWHITESPACE(*text) && *text != '\r' && *text != '\n')
1857 if (*text == '\n' || *text == '\r')
1859 // a newline separates commands in the buffer
1860 if (*text == '\r' && text[1] == '\n')
1872 if (!COM_ParseToken_Console(&text))
1875 if (cmd_argc < MAX_ARGS)
1877 l = (int)strlen(com_token) + 1;
1878 if (cmd_tokenizebufferpos + l > CMD_TOKENIZELENGTH)
1880 Con_Printf("Cmd_TokenizeString: ran out of %i character buffer space for command arguements\n", CMD_TOKENIZELENGTH);
1883 memcpy (cmd_tokenizebuffer + cmd_tokenizebufferpos, com_token, l);
1884 cmd_argv[cmd_argc] = cmd_tokenizebuffer + cmd_tokenizebufferpos;
1885 cmd_tokenizebufferpos += l;
1897 void Cmd_AddCommand_WithClientCommand (const char *cmd_name, xcommand_t consolefunction, xcommand_t clientfunction, const char *description)
1899 cmd_function_t *cmd;
1900 cmd_function_t *prev, *current;
1902 // fail if the command is a variable name
1903 if (Cvar_FindVar( cmd_name ))
1905 Con_Printf("Cmd_AddCommand: %s already defined as a var\n", cmd_name);
1909 // fail if the command already exists
1910 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1912 if (!strcmp (cmd_name, cmd->name))
1914 if (consolefunction || clientfunction)
1916 Con_Printf("Cmd_AddCommand: %s already defined\n", cmd_name);
1921 cmd->csqcfunc = true;
1927 cmd = (cmd_function_t *)Mem_Alloc(cmd_mempool, sizeof(cmd_function_t));
1928 cmd->name = cmd_name;
1929 cmd->consolefunction = consolefunction;
1930 cmd->clientfunction = clientfunction;
1931 cmd->description = description;
1932 if(!consolefunction && !clientfunction) //[515]: csqc
1933 cmd->csqcfunc = true;
1934 cmd->next = cmd_functions;
1936 // insert it at the right alphanumeric position
1937 for( prev = NULL, current = cmd_functions ; current && strcmp( current->name, cmd->name ) < 0 ; prev = current, current = current->next )
1942 cmd_functions = cmd;
1944 cmd->next = current;
1947 void Cmd_AddCommand (const char *cmd_name, xcommand_t function, const char *description)
1949 Cmd_AddCommand_WithClientCommand (cmd_name, function, NULL, description);
1957 qboolean Cmd_Exists (const char *cmd_name)
1959 cmd_function_t *cmd;
1961 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1962 if (!strcmp (cmd_name,cmd->name))
1974 const char *Cmd_CompleteCommand (const char *partial)
1976 cmd_function_t *cmd;
1979 len = strlen(partial);
1985 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1986 if (!strncasecmp(partial, cmd->name, len))
1993 Cmd_CompleteCountPossible
1995 New function for tab-completion system
1996 Added by EvilTypeGuy
1997 Thanks to Fett erich@heintz.com
2001 int Cmd_CompleteCountPossible (const char *partial)
2003 cmd_function_t *cmd;
2008 len = strlen(partial);
2013 // Loop through the command list and count all partial matches
2014 for (cmd = cmd_functions; cmd; cmd = cmd->next)
2015 if (!strncasecmp(partial, cmd->name, len))
2022 Cmd_CompleteBuildList
2024 New function for tab-completion system
2025 Added by EvilTypeGuy
2026 Thanks to Fett erich@heintz.com
2030 const char **Cmd_CompleteBuildList (const char *partial)
2032 cmd_function_t *cmd;
2035 size_t sizeofbuf = (Cmd_CompleteCountPossible (partial) + 1) * sizeof (const char *);
2038 len = strlen(partial);
2039 buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
2040 // Loop through the alias list and print all matches
2041 for (cmd = cmd_functions; cmd; cmd = cmd->next)
2042 if (!strncasecmp(partial, cmd->name, len))
2043 buf[bpos++] = cmd->name;
2049 // written by LordHavoc
2050 void Cmd_CompleteCommandPrint (const char *partial)
2052 cmd_function_t *cmd;
2053 size_t len = strlen(partial);
2054 // Loop through the command list and print all matches
2055 for (cmd = cmd_functions; cmd; cmd = cmd->next)
2056 if (!strncasecmp(partial, cmd->name, len))
2057 Con_Printf("^2%s^7: %s\n", cmd->name, cmd->description);
2063 New function for tab-completion system
2064 Added by EvilTypeGuy
2065 Thanks to Fett erich@heintz.com
2069 const char *Cmd_CompleteAlias (const char *partial)
2074 len = strlen(partial);
2080 for (alias = cmd_alias; alias; alias = alias->next)
2081 if (!strncasecmp(partial, alias->name, len))
2087 // written by LordHavoc
2088 void Cmd_CompleteAliasPrint (const char *partial)
2091 size_t len = strlen(partial);
2092 // Loop through the alias list and print all matches
2093 for (alias = cmd_alias; alias; alias = alias->next)
2094 if (!strncasecmp(partial, alias->name, len))
2095 Con_Printf("^5%s^7: %s", alias->name, alias->value);
2100 Cmd_CompleteAliasCountPossible
2102 New function for tab-completion system
2103 Added by EvilTypeGuy
2104 Thanks to Fett erich@heintz.com
2108 int Cmd_CompleteAliasCountPossible (const char *partial)
2116 len = strlen(partial);
2121 // Loop through the command list and count all partial matches
2122 for (alias = cmd_alias; alias; alias = alias->next)
2123 if (!strncasecmp(partial, alias->name, len))
2130 Cmd_CompleteAliasBuildList
2132 New function for tab-completion system
2133 Added by EvilTypeGuy
2134 Thanks to Fett erich@heintz.com
2138 const char **Cmd_CompleteAliasBuildList (const char *partial)
2143 size_t sizeofbuf = (Cmd_CompleteAliasCountPossible (partial) + 1) * sizeof (const char *);
2146 len = strlen(partial);
2147 buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
2148 // Loop through the alias list and print all matches
2149 for (alias = cmd_alias; alias; alias = alias->next)
2150 if (!strncasecmp(partial, alias->name, len))
2151 buf[bpos++] = alias->name;
2157 void Cmd_ClearCsqcFuncs (void)
2159 cmd_function_t *cmd;
2160 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
2161 cmd->csqcfunc = false;
2164 qboolean CL_VM_ConsoleCommand (const char *cmd);
2169 A complete command line has been parsed, so try to execute it
2170 FIXME: lookupnoadd the token to speed search?
2173 void Cmd_ExecuteString (const char *text, cmd_source_t src)
2177 cmd_function_t *cmd;
2180 oldpos = cmd_tokenizebufferpos;
2184 Cmd_TokenizeString (text);
2186 // execute the command line
2189 cmd_tokenizebufferpos = oldpos;
2190 return; // no tokens
2194 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
2196 if (!strcasecmp (cmd_argv[0],cmd->name))
2198 if (cmd->csqcfunc && CL_VM_ConsoleCommand (text)) //[515]: csqc
2203 if (cmd->consolefunction)
2204 cmd->consolefunction ();
2205 else if (cmd->clientfunction)
2207 if (cls.state == ca_connected)
2209 // forward remote commands to the server for execution
2210 Cmd_ForwardToServer();
2213 Con_Printf("Can not send command \"%s\", not connected.\n", Cmd_Argv(0));
2216 Con_Printf("Command \"%s\" can not be executed\n", Cmd_Argv(0));
2220 if (cmd->clientfunction)
2222 cmd->clientfunction ();
2223 cmd_tokenizebufferpos = oldpos;
2233 // if it's a client command and no command was found, say so.
2234 if (cmd_source == src_client)
2236 Con_Printf("player \"%s\" tried to %s\n", host_client->name, text);
2237 cmd_tokenizebufferpos = oldpos;
2242 for (a=cmd_alias ; a ; a=a->next)
2244 if (!strcasecmp (cmd_argv[0], a->name))
2246 Cmd_ExecuteAlias(a);
2247 cmd_tokenizebufferpos = oldpos;
2252 if(found) // if the command was hooked and found, all is good
2254 cmd_tokenizebufferpos = oldpos;
2259 if (!Cvar_Command () && host_framecount > 0)
2260 Con_Printf("Unknown command \"%s\"\n", Cmd_Argv(0));
2262 cmd_tokenizebufferpos = oldpos;
2268 Cmd_ForwardStringToServer
2270 Sends an entire command string over to the server, unprocessed
2273 void Cmd_ForwardStringToServer (const char *s)
2276 if (cls.state != ca_connected)
2278 Con_Printf("Can't \"%s\", not connected\n", s);
2285 // LordHavoc: thanks to Fuh for bringing the pure evil of SZ_Print to my
2286 // attention, it has been eradicated from here, its only (former) use in
2287 // all of darkplaces.
2288 if (cls.protocol == PROTOCOL_QUAKEWORLD)
2289 MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
2291 MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
2292 if ((!strncmp(s, "say ", 4) || !strncmp(s, "say_team ", 9)) && cl_locs_enable.integer)
2294 // say/say_team commands can replace % character codes with status info
2297 if (*s == '%' && s[1])
2299 // handle proquake message macros
2303 case 'l': // current location
2304 CL_Locs_FindLocationName(temp, sizeof(temp), cl.movement_origin);
2306 case 'h': // current health
2307 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_HEALTH]);
2309 case 'a': // current armor
2310 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ARMOR]);
2312 case 'x': // current rockets
2313 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ROCKETS]);
2315 case 'c': // current cells
2316 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_CELLS]);
2318 // silly proquake macros
2319 case 'd': // loc at last death
2320 CL_Locs_FindLocationName(temp, sizeof(temp), cl.lastdeathorigin);
2322 case 't': // current time
2323 dpsnprintf(temp, sizeof(temp), "%.0f:%.0f", floor(cl.time / 60), cl.time - floor(cl.time / 60) * 60);
2325 case 'r': // rocket launcher status ("I have RL", "I need rockets", "I need RL")
2326 if (!(cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER))
2327 dpsnprintf(temp, sizeof(temp), "I need RL");
2328 else if (!cl.stats[STAT_ROCKETS])
2329 dpsnprintf(temp, sizeof(temp), "I need rockets");
2331 dpsnprintf(temp, sizeof(temp), "I have RL");
2333 case 'p': // powerup status (outputs "quad" "pent" and "eyes" according to status)
2334 if (cl.stats[STAT_ITEMS] & IT_QUAD)
2337 strlcat(temp, " ", sizeof(temp));
2338 strlcat(temp, "quad", sizeof(temp));
2340 if (cl.stats[STAT_ITEMS] & IT_INVULNERABILITY)
2343 strlcat(temp, " ", sizeof(temp));
2344 strlcat(temp, "pent", sizeof(temp));
2346 if (cl.stats[STAT_ITEMS] & IT_INVISIBILITY)
2349 strlcat(temp, " ", sizeof(temp));
2350 strlcat(temp, "eyes", sizeof(temp));
2353 case 'w': // weapon status (outputs "SSG:NG:SNG:GL:RL:LG" with the text between : characters omitted if you lack the weapon)
2354 if (cl.stats[STAT_ITEMS] & IT_SUPER_SHOTGUN)
2355 strlcat(temp, "SSG", sizeof(temp));
2356 strlcat(temp, ":", sizeof(temp));
2357 if (cl.stats[STAT_ITEMS] & IT_NAILGUN)
2358 strlcat(temp, "NG", sizeof(temp));
2359 strlcat(temp, ":", sizeof(temp));
2360 if (cl.stats[STAT_ITEMS] & IT_SUPER_NAILGUN)
2361 strlcat(temp, "SNG", sizeof(temp));
2362 strlcat(temp, ":", sizeof(temp));
2363 if (cl.stats[STAT_ITEMS] & IT_GRENADE_LAUNCHER)
2364 strlcat(temp, "GL", sizeof(temp));
2365 strlcat(temp, ":", sizeof(temp));
2366 if (cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER)
2367 strlcat(temp, "RL", sizeof(temp));
2368 strlcat(temp, ":", sizeof(temp));
2369 if (cl.stats[STAT_ITEMS] & IT_LIGHTNING)
2370 strlcat(temp, "LG", sizeof(temp));
2373 // not a recognized macro, print it as-is...
2379 // write the resulting text
2380 SZ_Write(&cls.netcon->message, (unsigned char *)temp, strlen(temp));
2384 MSG_WriteByte(&cls.netcon->message, *s);
2387 MSG_WriteByte(&cls.netcon->message, 0);
2389 else // any other command is passed on as-is
2390 SZ_Write(&cls.netcon->message, (const unsigned char *)s, (int)strlen(s) + 1);
2397 Sends the entire command line over to the server
2400 void Cmd_ForwardToServer (void)
2403 if (!strcasecmp(Cmd_Argv(0), "cmd"))
2405 // we want to strip off "cmd", so just send the args
2406 s = Cmd_Argc() > 1 ? Cmd_Args() : "";
2410 // we need to keep the command name, so send Cmd_Argv(0), a space and then Cmd_Args()
2411 s = va("%s %s", Cmd_Argv(0), Cmd_Argc() > 1 ? Cmd_Args() : "");
2413 // don't send an empty forward message if the user tries "cmd" by itself
2416 Cmd_ForwardStringToServer(s);
2424 Returns the position (1 to argc-1) in the command's argument list
2425 where the given parameter apears, or 0 if not present
2429 int Cmd_CheckParm (const char *parm)
2435 Con_Printf ("Cmd_CheckParm: NULL");
2439 for (i = 1; i < Cmd_Argc (); i++)
2440 if (!strcasecmp (parm, Cmd_Argv (i)))