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)
997 if (Cmd_Argc () != 2)
999 Con_Print("exec <filename> : execute a script file\n");
1003 f = (char *)FS_LoadFile (Cmd_Argv(1), tempmempool, false, NULL);
1006 Con_Printf("couldn't exec %s\n",Cmd_Argv(1));
1009 Con_Printf("execing %s\n",Cmd_Argv(1));
1011 // if executing default.cfg for the first time, lock the cvar defaults
1012 // it may seem backwards to insert this text BEFORE the default.cfg
1013 // but Cbuf_InsertText inserts before, so this actually ends up after it.
1014 if (!strcmp(Cmd_Argv(1), "default.cfg"))
1015 Cbuf_InsertText("\ncvar_lockdefaults\n");
1017 // insert newline after the text to make sure the last line is terminated (some text editors omit the trailing newline)
1018 // (note: insertion order here is backwards from execution order, so this adds it after the text, by calling it before...)
1019 Cbuf_InsertText ("\n");
1020 Cbuf_InsertText (f);
1029 Just prints the rest of the line to the console
1032 static void Cmd_Echo_f (void)
1036 for (i=1 ; i<Cmd_Argc() ; i++)
1037 Con_Printf("%s ",Cmd_Argv(i));
1042 // Support Doom3-style Toggle Console Command
1047 Toggles a specified console variable amongst the values specified (default is 0 and 1)
1050 static void Cmd_Toggle_f(void)
1052 // Acquire Number of Arguments
1053 int nNumArgs = Cmd_Argc();
1056 // No Arguments Specified; Print Usage
1057 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");
1059 { // Correct Arguments Specified
1060 // Acquire Potential CVar
1061 cvar_t* cvCVar = Cvar_FindVar( Cmd_Argv(1) );
1068 Cvar_SetValueQuick(cvCVar, 0);
1070 Cvar_SetValueQuick(cvCVar, 1);
1074 { // 0 and Specified Usage
1075 if(cvCVar->integer == atoi(Cmd_Argv(2) ) )
1076 // CVar is Specified Value; // Reset to 0
1077 Cvar_SetValueQuick(cvCVar, 0);
1079 if(cvCVar->integer == 0)
1080 // CVar is 0; Specify Value
1081 Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
1083 // CVar does not match; Reset to 0
1084 Cvar_SetValueQuick(cvCVar, 0);
1087 { // Variable Values Specified
1091 for(nCnt = 2; nCnt < nNumArgs; nCnt++)
1092 { // Cycle through Values
1093 if( strcmp(cvCVar->string, Cmd_Argv(nCnt) ) == 0)
1094 { // Current Value Located; Increment to Next
1095 if( (nCnt + 1) == nNumArgs)
1096 // Max Value Reached; Reset
1097 Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
1100 Cvar_SetQuick(cvCVar, Cmd_Argv(nCnt + 1) );
1109 // Value not Found; Reset to Original
1110 Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
1116 Con_Printf("ERROR : CVar '%s' not found\n", Cmd_Argv(1) );
1125 Creates a new command that executes a command string (possibly ; seperated)
1128 static void Cmd_Alias_f (void)
1131 char cmd[MAX_INPUTLINE];
1136 if (Cmd_Argc() == 1)
1138 Con_Print("Current alias commands:\n");
1139 for (a = cmd_alias ; a ; a=a->next)
1140 Con_Printf("%s : %s", a->name, a->value);
1145 if (strlen(s) >= MAX_ALIAS_NAME)
1147 Con_Print("Alias name is too long\n");
1151 // if the alias already exists, reuse it
1152 for (a = cmd_alias ; a ; a=a->next)
1154 if (!strcmp(s, a->name))
1163 cmdalias_t *prev, *current;
1165 a = (cmdalias_t *)Z_Malloc (sizeof(cmdalias_t));
1166 strlcpy (a->name, s, sizeof (a->name));
1167 // insert it at the right alphanumeric position
1168 for( prev = NULL, current = cmd_alias ; current && strcmp( current->name, a->name ) < 0 ; prev = current, current = current->next )
1179 // copy the rest of the command line
1180 cmd[0] = 0; // start out with a null string
1182 for (i=2 ; i< c ; i++)
1184 strlcat (cmd, Cmd_Argv(i), sizeof (cmd));
1186 strlcat (cmd, " ", sizeof (cmd));
1188 strlcat (cmd, "\n", sizeof (cmd));
1190 alloclen = strlen (cmd) + 1;
1192 cmd[alloclen - 2] = '\n'; // to make sure a newline is appended even if too long
1193 a->value = (char *)Z_Malloc (alloclen);
1194 memcpy (a->value, cmd, alloclen);
1201 Remove existing aliases.
1204 static void Cmd_UnAlias_f (void)
1212 Con_Print("unalias: Usage: unalias alias1 [alias2 ...]\n");
1216 for(i = 1; i < Cmd_Argc(); ++i)
1220 for(a = cmd_alias; a; p = a, a = a->next)
1222 if(!strcmp(s, a->name))
1225 cmd_alias = a->next;
1234 Con_Printf("unalias: %s alias not found\n", s);
1239 =============================================================================
1243 =============================================================================
1246 typedef struct cmd_function_s
1248 struct cmd_function_s *next;
1250 const char *description;
1251 xcommand_t consolefunction;
1252 xcommand_t clientfunction;
1256 static int cmd_argc;
1257 static const char *cmd_argv[MAX_ARGS];
1258 static const char *cmd_null_string = "";
1259 static const char *cmd_args;
1260 cmd_source_t cmd_source;
1263 static cmd_function_t *cmd_functions; // possible commands to execute
1265 static const char *Cmd_GetDirectCvarValue(const char *varname, cmdalias_t *alias, qboolean *is_multiple)
1272 *is_multiple = false;
1274 if(!varname || !*varname)
1279 if(!strcmp(varname, "*"))
1282 *is_multiple = true;
1285 else if(varname[strlen(varname) - 1] == '-')
1287 argno = strtol(varname, &endptr, 10);
1288 if(endptr == varname + strlen(varname) - 1)
1290 // whole string is a number, apart from the -
1291 const char *p = Cmd_Args();
1292 for(; argno > 1; --argno)
1293 if(!COM_ParseToken_Console(&p))
1298 *is_multiple = true;
1300 // kill pre-argument whitespace
1301 for (;*p && ISWHITESPACE(*p);p++)
1310 argno = strtol(varname, &endptr, 10);
1313 // whole string is a number
1314 // NOTE: we already made sure we don't have an empty cvar name!
1315 if(argno >= 0 && argno < Cmd_Argc())
1316 return Cmd_Argv(argno);
1321 if((cvar = Cvar_FindVar(varname)) && !(cvar->flags & CVAR_PRIVATE))
1322 return cvar->string;
1327 qboolean Cmd_QuoteString(char *out, size_t outlen, const char *in, const char *quoteset)
1329 qboolean quote_quot = !!strchr(quoteset, '"');
1330 qboolean quote_backslash = !!strchr(quoteset, '\\');
1331 qboolean quote_dollar = !!strchr(quoteset, '$');
1335 if(*in == '"' && quote_quot)
1342 *out++ = '\\'; --outlen;
1343 *out++ = '"'; --outlen;
1345 else if(*in == '\\' && quote_backslash)
1352 *out++ = '\\'; --outlen;
1353 *out++ = '\\'; --outlen;
1355 else if(*in == '$' && quote_dollar)
1362 *out++ = '$'; --outlen;
1363 *out++ = '$'; --outlen;
1372 *out++ = *in; --outlen;
1380 static const char *Cmd_GetCvarValue(const char *var, size_t varlen, cmdalias_t *alias)
1382 static char varname[MAX_INPUTLINE];
1383 static char varval[MAX_INPUTLINE];
1387 if(varlen >= MAX_INPUTLINE)
1388 varlen = MAX_INPUTLINE - 1;
1389 memcpy(varname, var, varlen);
1390 varname[varlen] = 0;
1391 varfunc = strchr(varname, ' ');
1397 if (!memcmp(varfunc, "local", 5) && (varfunc[5] == ' ' || !varfunc[5]))
1399 static char tmp[MAX_INPUTLINE];
1401 len = dpsnprintf(tmp, sizeof(tmp), "_cin_%lu_", (unsigned long)cmd_tid);
1402 memcpy(tmp + len, varname, varfunc - varname - 1);
1403 strlcpy(tmp + len + (varfunc - varname - 1), varfunc + 5, sizeof(tmp) - len - (varfunc - varname - 1));
1404 memcpy(varname, tmp, sizeof(varname));
1405 varfunc = strchr(varname, ' ');
1422 if(varname[0] == '$')
1423 varstr = Cmd_GetDirectCvarValue(Cmd_GetDirectCvarValue(varname + 1, alias, NULL), alias, NULL);
1426 qboolean is_multiple = false;
1427 // Exception: $* and $n- don't use the quoted form by default
1428 varstr = Cmd_GetDirectCvarValue(varname, alias, &is_multiple);
1437 Con_Printf("Warning: Could not expand $%s in alias %s\n", varname, alias->name);
1439 Con_Printf("Warning: Could not expand $%s\n", varname);
1443 if(!varfunc || !strcmp(varfunc, "q")) // note: quoted form is default, use "asis" to override!
1445 // quote it so it can be used inside double quotes
1446 // we just need to replace " by \", and of course, double backslashes
1447 Cmd_QuoteString(varval, sizeof(varval), varstr, "\"\\");
1450 else if(!strcmp(varfunc, "asis"))
1455 Con_Printf("Unknown variable function %s\n", varfunc);
1461 Cmd_PreprocessString
1463 Preprocesses strings and replaces $*, $param#, $cvar accordingly. Also strips comments.
1465 static void Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias ) {
1471 // don't crash if there's no room in the outtext buffer
1472 if( maxoutlen == 0 ) {
1475 maxoutlen--; // because of \0
1480 while( *in && outlen < maxoutlen ) {
1482 // this is some kind of expansion, see what comes after the $
1485 // The console does the following preprocessing:
1487 // - $$ is transformed to a single dollar sign.
1488 // - $var or ${var} are expanded to the contents of the named cvar,
1489 // with quotation marks and backslashes quoted so it can safely
1490 // be used inside quotation marks (and it should always be used
1492 // - ${var asis} inserts the cvar value as is, without doing this
1494 // - prefix the cvar name with a dollar sign to do indirection;
1495 // for example, if $x has the value timelimit, ${$x} will return
1496 // the value of $timelimit
1497 // - when expanding an alias, the special variable name $* refers
1498 // to all alias parameters, and a number refers to that numbered
1499 // alias parameter, where the name of the alias is $0, the first
1500 // parameter is $1 and so on; as a special case, $* inserts all
1501 // parameters, without extra quoting, so one can use $* to just
1502 // pass all parameters around. All parameters starting from $n
1503 // can be referred to as $n- (so $* is equivalent to $1-).
1505 // Note: when expanding an alias, cvar expansion is done in the SAME step
1506 // as alias expansion so that alias parameters or cvar values containing
1507 // dollar signs have no unwanted bad side effects. However, this needs to
1508 // be accounted for when writing complex aliases. For example,
1509 // alias foo "set x NEW; echo $x"
1510 // actually expands to
1511 // "set x NEW; echo OLD"
1512 // and will print OLD! To work around this, use a second alias:
1513 // alias foo "set x NEW; foo2"
1514 // alias foo2 "echo $x"
1516 // Also note: lines starting with alias are exempt from cvar expansion.
1517 // If you want cvar expansion, write "alias" instead:
1520 // alias foo "echo $x"
1521 // "alias" bar "echo $x"
1524 // foo will print 2, because the variable $x will be expanded when the alias
1525 // gets expanded. bar will print 1, because the variable $x was expanded
1526 // at definition time. foo can be equivalently defined as
1528 // "alias" foo "echo $$x"
1530 // because at definition time, $$ will get replaced to a single $.
1535 } else if(*in == '{') {
1536 varlen = strcspn(in + 1, "}");
1537 if(in[varlen + 1] == '}')
1539 val = Cmd_GetCvarValue(in + 1, varlen, alias);
1549 varlen = strspn(in, "*0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-");
1550 val = Cmd_GetCvarValue(in, varlen, alias);
1555 // insert the cvar value
1556 while(*val && outlen < maxoutlen)
1557 outtext[outlen++] = *val++;
1562 // copy the unexpanded text
1563 outtext[outlen++] = '$';
1564 while(eat && outlen < maxoutlen)
1566 outtext[outlen++] = *in++;
1572 outtext[outlen++] = *in++;
1574 outtext[outlen] = 0;
1581 Called for aliases and fills in the alias into the cbuffer
1584 static void Cmd_ExecuteAlias (cmdalias_t *alias)
1586 static char buffer[ MAX_INPUTLINE ];
1587 static char buffer2[ MAX_INPUTLINE ];
1588 Cmd_PreprocessString( alias->value, buffer, sizeof(buffer) - 2, alias );
1589 // insert at start of command buffer, so that aliases execute in order
1590 // (fixes bug introduced by Black on 20050705)
1592 // Note: Cbuf_PreprocessString will be called on this string AGAIN! So we
1593 // have to make sure that no second variable expansion takes place, otherwise
1594 // alias parameters containing dollar signs can have bad effects.
1595 Cmd_QuoteString(buffer2, sizeof(buffer2), buffer, "$");
1596 Cbuf_InsertText( buffer2 );
1603 CmdList Added by EvilTypeGuy eviltypeguy@qeradiant.com
1604 Thanks to Matthias "Maddes" Buecher, http://www.inside3d.com/qip/
1608 static void Cmd_List_f (void)
1610 cmd_function_t *cmd;
1611 const char *partial;
1618 partial = Cmd_Argv (1);
1619 len = strlen(partial);
1627 ispattern = partial && (strchr(partial, '*') || strchr(partial, '?'));
1630 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1632 if (partial && (ispattern ? !matchpattern_with_separator(cmd->name, partial, false, "", false) : strncmp(partial, cmd->name, len)))
1634 Con_Printf("%s : %s\n", cmd->name, cmd->description);
1641 Con_Printf("%i Command%s matching \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1643 Con_Printf("%i Command%s beginning with \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1646 Con_Printf("%i Command%s\n\n", count, (count > 1) ? "s" : "");
1649 static void Cmd_Apropos_f(void)
1651 cmd_function_t *cmd;
1654 const char *partial;
1661 partial = Cmd_Args();
1662 len = strlen(partial);
1666 Con_Printf("usage: apropos <string>\n");
1670 ispattern = partial && (strchr(partial, '*') || strchr(partial, '?'));
1673 partial = va("*%s*", partial);
1678 for (cvar = cvar_vars; cvar; cvar = cvar->next)
1680 if (!matchpattern_with_separator(cvar->name, partial, true, "", false))
1681 if (!matchpattern_with_separator(cvar->description, partial, true, "", false))
1683 Con_Printf ("cvar ^3%s^7 is \"%s\" [\"%s\"] %s\n", cvar->name, cvar->string, cvar->defstring, cvar->description);
1686 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1688 if (!matchpattern_with_separator(cmd->name, partial, true, "", false))
1689 if (!matchpattern_with_separator(cmd->description, partial, true, "", false))
1691 Con_Printf("command ^2%s^7: %s\n", cmd->name, cmd->description);
1694 for (alias = cmd_alias; alias; alias = alias->next)
1696 if (!matchpattern_with_separator(alias->name, partial, true, "", false))
1697 if (!matchpattern_with_separator(alias->value, partial, true, "", false))
1699 Con_Printf("alias ^5%s^7: %s", alias->name, alias->value);
1702 Con_Printf("%i result%s\n\n", count, (count > 1) ? "s" : "");
1710 void Cmd_Init (void)
1712 cmd_mempool = Mem_AllocPool("commands", 0, NULL);
1713 Cvar_RegisterVariable(&con_this);
1714 // space for commands and script files
1715 Mem_ExpandableArray_NewArray(&cmd_exec_array, cmd_mempool, sizeof(cmd_executor_t), 4);
1717 cmd_ex = Con_Spawn(&cmd_tid);
1718 Con_SetTID(cmd_tid, false);
1722 cmd_text = &cmd_exec[cmd_tid].text;
1723 cmd_text->data = cmd_exec[cmd_tid].text_buf;
1724 cmd_text->maxsize = sizeof(cmd_exec[cmd_tid].text_buf);
1725 cmd_text->cursize = 0;
1729 void Cmd_Init_Commands (void)
1732 // register our commands
1734 Cmd_AddCommand ("stuffcmds",Cmd_StuffCmds_f, "execute commandline parameters (must be present in quake.rc script)");
1735 Cmd_AddCommand ("exec",Cmd_Exec_f, "execute a script file");
1736 Cmd_AddCommand ("echo",Cmd_Echo_f, "print a message to the console (useful in scripts)");
1737 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");
1738 Cmd_AddCommand ("unalias",Cmd_UnAlias_f, "remove an alias");
1739 Cmd_AddCommand ("cmd", Cmd_ForwardToServer, "send a console commandline to the server (used by some mods)");
1740 Cmd_AddCommand ("wait", Cmd_Wait_f, "make script execution wait for next rendered frame");
1741 Cmd_AddCommand ("set", Cvar_Set_f, "create or change the value of a console variable");
1742 Cmd_AddCommand ("seta", Cvar_SetA_f, "create or change the value of a console variable that will be saved to config.cfg");
1743 #ifdef FILLALLCVARSWITHRUBBISH
1744 Cmd_AddCommand ("fillallcvarswithrubbish", Cvar_FillAll_f, "fill all cvars with a specified number of characters to provoke buffer overruns");
1745 #endif /* FILLALLCVARSWITHRUBBISH */
1747 // 2000-01-09 CmdList, CvarList commands By Matthias "Maddes" Buecher
1748 // Added/Modified by EvilTypeGuy eviltypeguy@qeradiant.com
1749 Cmd_AddCommand ("cmdlist", Cmd_List_f, "lists all console commands beginning with the specified prefix or matching the specified wildcard pattern");
1750 Cmd_AddCommand ("cvarlist", Cvar_List_f, "lists all console variables beginning with the specified prefix or matching the specified wildcard pattern");
1751 Cmd_AddCommand ("apropos", Cmd_Apropos_f, "lists all console variables/commands/aliases containing the specified string in the name or description");
1753 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");
1754 Cmd_AddCommand ("cvar_resettodefaults_all", Cvar_ResetToDefaults_All_f, "sets all cvars to their locked default values");
1755 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)");
1756 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)");
1758 Cmd_AddCommand ("cprint", Cmd_Centerprint_f, "print something at the screen center");
1759 Cmd_AddCommand ("defer", Cmd_Defer_f, "execute a command in the future");
1761 Cmd_AddCommand ("conspawn", Cmd_Spawn_f, "spawn new console instances, their IDs are stored in the provided cvars");
1762 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");
1763 Cmd_AddCommand ("sleep", Cmd_Sleep_f, "let the current, or a specific console instance sleep for some time in the background");
1764 Cmd_AddCommand ("cond", Cmd_Cond_f, "suspend a console instance until a cvar becomes true (not-null)");
1765 Cmd_AddCommand ("condl", Cmd_CondLocal_f, "suspend a console instance until a local cvar becomes true (not-null)");
1766 Cmd_AddCommand ("suspend", Cmd_Suspend_f, "suspend a console instance, when suspending the current console, this also does 'setid 0'");
1767 Cmd_AddCommand ("resume", Cmd_Resume_f, "resume the execution of a console instance");
1768 Cmd_AddCommand ("term", Cmd_XKill_f, "kill a console instance (doesn't work on id 0)");
1769 Cmd_AddCommand ("termq", Cmd_XKill_f, "kill a console instance (doesn't work on id 0)");
1770 Cmd_AddCommand ("xadd", Cmd_XAdd_f, "add a command to a console instance");
1771 Cmd_AddCommand ("setlocal", Cmd_SetLocal_f, "set a instance-local cvar");
1772 Cmd_AddCommand ("setforeign", Cmd_SetForeign_f, "set an instance's local cvar");
1773 Cmd_AddCommand ("setcps", Cmd_SetCPS_f, "set the commands executed per second in a console instance");
1776 // Support Doom3-style Toggle Command
1777 Cmd_AddCommand( "toggle", Cmd_Toggle_f, "toggles a console variable's values (use for more info)");
1785 void Cmd_Shutdown(void)
1787 Mem_FreePool(&cmd_mempool);
1805 const char *Cmd_Argv (int arg)
1807 if (arg >= cmd_argc )
1808 return cmd_null_string;
1809 return cmd_argv[arg];
1817 const char *Cmd_Args (void)
1827 Parses the given string into command line tokens.
1830 // AK: This function should only be called from ExcuteString because the current design is a bit of an hack
1831 static void Cmd_TokenizeString (const char *text)
1840 // skip whitespace up to a /n
1841 while (*text && ISWHITESPACE(*text) && *text != '\r' && *text != '\n')
1848 if (*text == '\n' || *text == '\r')
1850 // a newline separates commands in the buffer
1851 if (*text == '\r' && text[1] == '\n')
1863 if (!COM_ParseToken_Console(&text))
1866 if (cmd_argc < MAX_ARGS)
1868 l = (int)strlen(com_token) + 1;
1869 if (cmd_tokenizebufferpos + l > CMD_TOKENIZELENGTH)
1871 Con_Printf("Cmd_TokenizeString: ran out of %i character buffer space for command arguements\n", CMD_TOKENIZELENGTH);
1874 memcpy (cmd_tokenizebuffer + cmd_tokenizebufferpos, com_token, l);
1875 cmd_argv[cmd_argc] = cmd_tokenizebuffer + cmd_tokenizebufferpos;
1876 cmd_tokenizebufferpos += l;
1888 void Cmd_AddCommand_WithClientCommand (const char *cmd_name, xcommand_t consolefunction, xcommand_t clientfunction, const char *description)
1890 cmd_function_t *cmd;
1891 cmd_function_t *prev, *current;
1893 // fail if the command is a variable name
1894 if (Cvar_FindVar( cmd_name ))
1896 Con_Printf("Cmd_AddCommand: %s already defined as a var\n", cmd_name);
1900 // fail if the command already exists
1901 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1903 if (!strcmp (cmd_name, cmd->name))
1905 if (consolefunction || clientfunction)
1907 Con_Printf("Cmd_AddCommand: %s already defined\n", cmd_name);
1912 cmd->csqcfunc = true;
1918 cmd = (cmd_function_t *)Mem_Alloc(cmd_mempool, sizeof(cmd_function_t));
1919 cmd->name = cmd_name;
1920 cmd->consolefunction = consolefunction;
1921 cmd->clientfunction = clientfunction;
1922 cmd->description = description;
1923 if(!consolefunction && !clientfunction) //[515]: csqc
1924 cmd->csqcfunc = true;
1925 cmd->next = cmd_functions;
1927 // insert it at the right alphanumeric position
1928 for( prev = NULL, current = cmd_functions ; current && strcmp( current->name, cmd->name ) < 0 ; prev = current, current = current->next )
1933 cmd_functions = cmd;
1935 cmd->next = current;
1938 void Cmd_AddCommand (const char *cmd_name, xcommand_t function, const char *description)
1940 Cmd_AddCommand_WithClientCommand (cmd_name, function, NULL, description);
1948 qboolean Cmd_Exists (const char *cmd_name)
1950 cmd_function_t *cmd;
1952 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1953 if (!strcmp (cmd_name,cmd->name))
1965 const char *Cmd_CompleteCommand (const char *partial)
1967 cmd_function_t *cmd;
1970 len = strlen(partial);
1976 for (cmd = cmd_functions; cmd; cmd = cmd->next)
1977 if (!strncasecmp(partial, cmd->name, len))
1984 Cmd_CompleteCountPossible
1986 New function for tab-completion system
1987 Added by EvilTypeGuy
1988 Thanks to Fett erich@heintz.com
1992 int Cmd_CompleteCountPossible (const char *partial)
1994 cmd_function_t *cmd;
1999 len = strlen(partial);
2004 // Loop through the command list and count all partial matches
2005 for (cmd = cmd_functions; cmd; cmd = cmd->next)
2006 if (!strncasecmp(partial, cmd->name, len))
2013 Cmd_CompleteBuildList
2015 New function for tab-completion system
2016 Added by EvilTypeGuy
2017 Thanks to Fett erich@heintz.com
2021 const char **Cmd_CompleteBuildList (const char *partial)
2023 cmd_function_t *cmd;
2026 size_t sizeofbuf = (Cmd_CompleteCountPossible (partial) + 1) * sizeof (const char *);
2029 len = strlen(partial);
2030 buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
2031 // Loop through the alias list and print all matches
2032 for (cmd = cmd_functions; cmd; cmd = cmd->next)
2033 if (!strncasecmp(partial, cmd->name, len))
2034 buf[bpos++] = cmd->name;
2040 // written by LordHavoc
2041 void Cmd_CompleteCommandPrint (const char *partial)
2043 cmd_function_t *cmd;
2044 size_t len = strlen(partial);
2045 // Loop through the command list and print all matches
2046 for (cmd = cmd_functions; cmd; cmd = cmd->next)
2047 if (!strncasecmp(partial, cmd->name, len))
2048 Con_Printf("^2%s^7: %s\n", cmd->name, cmd->description);
2054 New function for tab-completion system
2055 Added by EvilTypeGuy
2056 Thanks to Fett erich@heintz.com
2060 const char *Cmd_CompleteAlias (const char *partial)
2065 len = strlen(partial);
2071 for (alias = cmd_alias; alias; alias = alias->next)
2072 if (!strncasecmp(partial, alias->name, len))
2078 // written by LordHavoc
2079 void Cmd_CompleteAliasPrint (const char *partial)
2082 size_t len = strlen(partial);
2083 // Loop through the alias list and print all matches
2084 for (alias = cmd_alias; alias; alias = alias->next)
2085 if (!strncasecmp(partial, alias->name, len))
2086 Con_Printf("^5%s^7: %s", alias->name, alias->value);
2091 Cmd_CompleteAliasCountPossible
2093 New function for tab-completion system
2094 Added by EvilTypeGuy
2095 Thanks to Fett erich@heintz.com
2099 int Cmd_CompleteAliasCountPossible (const char *partial)
2107 len = strlen(partial);
2112 // Loop through the command list and count all partial matches
2113 for (alias = cmd_alias; alias; alias = alias->next)
2114 if (!strncasecmp(partial, alias->name, len))
2121 Cmd_CompleteAliasBuildList
2123 New function for tab-completion system
2124 Added by EvilTypeGuy
2125 Thanks to Fett erich@heintz.com
2129 const char **Cmd_CompleteAliasBuildList (const char *partial)
2134 size_t sizeofbuf = (Cmd_CompleteAliasCountPossible (partial) + 1) * sizeof (const char *);
2137 len = strlen(partial);
2138 buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
2139 // Loop through the alias list and print all matches
2140 for (alias = cmd_alias; alias; alias = alias->next)
2141 if (!strncasecmp(partial, alias->name, len))
2142 buf[bpos++] = alias->name;
2148 void Cmd_ClearCsqcFuncs (void)
2150 cmd_function_t *cmd;
2151 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
2152 cmd->csqcfunc = false;
2155 qboolean CL_VM_ConsoleCommand (const char *cmd);
2160 A complete command line has been parsed, so try to execute it
2161 FIXME: lookupnoadd the token to speed search?
2164 void Cmd_ExecuteString (const char *text, cmd_source_t src)
2168 cmd_function_t *cmd;
2171 oldpos = cmd_tokenizebufferpos;
2175 Cmd_TokenizeString (text);
2177 // execute the command line
2180 cmd_tokenizebufferpos = oldpos;
2181 return; // no tokens
2185 for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
2187 if (!strcasecmp (cmd_argv[0],cmd->name))
2189 if (cmd->csqcfunc && CL_VM_ConsoleCommand (text)) //[515]: csqc
2194 if (cmd->consolefunction)
2195 cmd->consolefunction ();
2196 else if (cmd->clientfunction)
2198 if (cls.state == ca_connected)
2200 // forward remote commands to the server for execution
2201 Cmd_ForwardToServer();
2204 Con_Printf("Can not send command \"%s\", not connected.\n", Cmd_Argv(0));
2207 Con_Printf("Command \"%s\" can not be executed\n", Cmd_Argv(0));
2212 if (cmd->clientfunction)
2214 cmd->clientfunction ();
2215 cmd_tokenizebufferpos = oldpos;
2225 // if it's a client command and no command was found, say so.
2226 if (cmd_source == src_client)
2228 Con_Printf("player \"%s\" tried to %s\n", host_client->name, text);
2229 cmd_tokenizebufferpos = oldpos;
2234 for (a=cmd_alias ; a ; a=a->next)
2236 if (!strcasecmp (cmd_argv[0], a->name))
2238 Cmd_ExecuteAlias(a);
2239 cmd_tokenizebufferpos = oldpos;
2244 if(found) // if the command was hooked and found, all is good
2246 cmd_tokenizebufferpos = oldpos;
2251 if (!Cvar_Command () && host_framecount > 0)
2252 Con_Printf("Unknown command \"%s\"\n", Cmd_Argv(0));
2254 cmd_tokenizebufferpos = oldpos;
2260 Cmd_ForwardStringToServer
2262 Sends an entire command string over to the server, unprocessed
2265 void Cmd_ForwardStringToServer (const char *s)
2268 if (cls.state != ca_connected)
2270 Con_Printf("Can't \"%s\", not connected\n", s);
2277 // LordHavoc: thanks to Fuh for bringing the pure evil of SZ_Print to my
2278 // attention, it has been eradicated from here, its only (former) use in
2279 // all of darkplaces.
2280 if (cls.protocol == PROTOCOL_QUAKEWORLD)
2281 MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
2283 MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
2284 if ((!strncmp(s, "say ", 4) || !strncmp(s, "say_team ", 9)) && cl_locs_enable.integer)
2286 // say/say_team commands can replace % character codes with status info
2289 if (*s == '%' && s[1])
2291 // handle proquake message macros
2295 case 'l': // current location
2296 CL_Locs_FindLocationName(temp, sizeof(temp), cl.movement_origin);
2298 case 'h': // current health
2299 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_HEALTH]);
2301 case 'a': // current armor
2302 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ARMOR]);
2304 case 'x': // current rockets
2305 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ROCKETS]);
2307 case 'c': // current cells
2308 dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_CELLS]);
2310 // silly proquake macros
2311 case 'd': // loc at last death
2312 CL_Locs_FindLocationName(temp, sizeof(temp), cl.lastdeathorigin);
2314 case 't': // current time
2315 dpsnprintf(temp, sizeof(temp), "%.0f:%.0f", floor(cl.time / 60), cl.time - floor(cl.time / 60) * 60);
2317 case 'r': // rocket launcher status ("I have RL", "I need rockets", "I need RL")
2318 if (!(cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER))
2319 dpsnprintf(temp, sizeof(temp), "I need RL");
2320 else if (!cl.stats[STAT_ROCKETS])
2321 dpsnprintf(temp, sizeof(temp), "I need rockets");
2323 dpsnprintf(temp, sizeof(temp), "I have RL");
2325 case 'p': // powerup status (outputs "quad" "pent" and "eyes" according to status)
2326 if (cl.stats[STAT_ITEMS] & IT_QUAD)
2329 strlcat(temp, " ", sizeof(temp));
2330 strlcat(temp, "quad", sizeof(temp));
2332 if (cl.stats[STAT_ITEMS] & IT_INVULNERABILITY)
2335 strlcat(temp, " ", sizeof(temp));
2336 strlcat(temp, "pent", sizeof(temp));
2338 if (cl.stats[STAT_ITEMS] & IT_INVISIBILITY)
2341 strlcat(temp, " ", sizeof(temp));
2342 strlcat(temp, "eyes", sizeof(temp));
2345 case 'w': // weapon status (outputs "SSG:NG:SNG:GL:RL:LG" with the text between : characters omitted if you lack the weapon)
2346 if (cl.stats[STAT_ITEMS] & IT_SUPER_SHOTGUN)
2347 strlcat(temp, "SSG", sizeof(temp));
2348 strlcat(temp, ":", sizeof(temp));
2349 if (cl.stats[STAT_ITEMS] & IT_NAILGUN)
2350 strlcat(temp, "NG", sizeof(temp));
2351 strlcat(temp, ":", sizeof(temp));
2352 if (cl.stats[STAT_ITEMS] & IT_SUPER_NAILGUN)
2353 strlcat(temp, "SNG", sizeof(temp));
2354 strlcat(temp, ":", sizeof(temp));
2355 if (cl.stats[STAT_ITEMS] & IT_GRENADE_LAUNCHER)
2356 strlcat(temp, "GL", sizeof(temp));
2357 strlcat(temp, ":", sizeof(temp));
2358 if (cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER)
2359 strlcat(temp, "RL", sizeof(temp));
2360 strlcat(temp, ":", sizeof(temp));
2361 if (cl.stats[STAT_ITEMS] & IT_LIGHTNING)
2362 strlcat(temp, "LG", sizeof(temp));
2365 // not a recognized macro, print it as-is...
2371 // write the resulting text
2372 SZ_Write(&cls.netcon->message, (unsigned char *)temp, strlen(temp));
2376 MSG_WriteByte(&cls.netcon->message, *s);
2379 MSG_WriteByte(&cls.netcon->message, 0);
2381 else // any other command is passed on as-is
2382 SZ_Write(&cls.netcon->message, (const unsigned char *)s, (int)strlen(s) + 1);
2389 Sends the entire command line over to the server
2392 void Cmd_ForwardToServer (void)
2395 if (!strcasecmp(Cmd_Argv(0), "cmd"))
2397 // we want to strip off "cmd", so just send the args
2398 s = Cmd_Argc() > 1 ? Cmd_Args() : "";
2402 // we need to keep the command name, so send Cmd_Argv(0), a space and then Cmd_Args()
2403 s = va("%s %s", Cmd_Argv(0), Cmd_Argc() > 1 ? Cmd_Args() : "");
2405 // don't send an empty forward message if the user tries "cmd" by itself
2408 Cmd_ForwardStringToServer(s);
2416 Returns the position (1 to argc-1) in the command's argument list
2417 where the given parameter apears, or 0 if not present
2421 int Cmd_CheckParm (const char *parm)
2427 Con_Printf ("Cmd_CheckParm: NULL");
2431 for (i = 1; i < Cmd_Argc (); i++)
2432 if (!strcasecmp (parm, Cmd_Argv (i)))