blob: 6516cf7735ac72c69e5de88b6913a3fae5e42f4c [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- CommandInterpreter.cpp ----------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include <string>
11
12#include <getopt.h>
13#include <stdlib.h>
14
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000015#include "../Commands/CommandObjectAlias.h"
16#include "../Commands/CommandObjectAppend.h"
17#include "../Commands/CommandObjectApropos.h"
18#include "../Commands/CommandObjectArgs.h"
19#include "../Commands/CommandObjectBreakpoint.h"
20#include "../Commands/CommandObjectCall.h"
21#include "../Commands/CommandObjectDelete.h"
22#include "../Commands/CommandObjectDisassemble.h"
23#include "../Commands/CommandObjectExpression.h"
24#include "../Commands/CommandObjectFile.h"
25#include "../Commands/CommandObjectFrame.h"
26#include "../Commands/CommandObjectHelp.h"
27#include "../Commands/CommandObjectImage.h"
28#include "../Commands/CommandObjectInfo.h"
29#include "../Commands/CommandObjectLog.h"
30#include "../Commands/CommandObjectMemory.h"
31#include "../Commands/CommandObjectProcess.h"
32#include "../Commands/CommandObjectQuit.h"
Eli Friedmanb34d2a22010-06-09 22:08:29 +000033#include "lldb/Interpreter/CommandObjectRegexCommand.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000034#include "../Commands/CommandObjectRegister.h"
Chris Lattner24943d22010-06-08 16:52:24 +000035#include "CommandObjectScript.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000036#include "../Commands/CommandObjectSelect.h"
37#include "../Commands/CommandObjectSet.h"
38#include "../Commands/CommandObjectSettings.h"
39#include "../Commands/CommandObjectShow.h"
40#include "../Commands/CommandObjectSource.h"
41#include "../Commands/CommandObjectSourceFile.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000042#include "../Commands/CommandObjectSyntax.h"
43#include "../Commands/CommandObjectTarget.h"
44#include "../Commands/CommandObjectThread.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000045#include "../Commands/CommandObjectUnalias.h"
46#include "../Commands/CommandObjectVariable.h"
Chris Lattner24943d22010-06-08 16:52:24 +000047
Jim Ingham84cdc152010-06-15 19:49:27 +000048#include "lldb/Interpreter/Args.h"
Chris Lattner24943d22010-06-08 16:52:24 +000049#include "lldb/Core/Debugger.h"
50#include "lldb/Core/Stream.h"
51#include "lldb/Core/Timer.h"
52#include "lldb/Target/Process.h"
53#include "lldb/Target/Thread.h"
54#include "lldb/Target/TargetList.h"
55
56#include "lldb/Interpreter/CommandReturnObject.h"
57#include "lldb/Interpreter/CommandInterpreter.h"
58
59using namespace lldb;
60using namespace lldb_private;
61
62CommandInterpreter::CommandInterpreter
63(
Greg Clayton63094e02010-06-23 01:19:29 +000064 Debugger &debugger,
Chris Lattner24943d22010-06-08 16:52:24 +000065 ScriptLanguage script_language,
Greg Clayton63094e02010-06-23 01:19:29 +000066 bool synchronous_execution
Chris Lattner24943d22010-06-08 16:52:24 +000067) :
68 Broadcaster ("CommandInterpreter"),
Greg Clayton63094e02010-06-23 01:19:29 +000069 m_debugger (debugger),
Chris Lattner24943d22010-06-08 16:52:24 +000070 m_script_language (script_language),
Greg Clayton63094e02010-06-23 01:19:29 +000071 m_synchronous_execution (synchronous_execution)
Chris Lattner24943d22010-06-08 16:52:24 +000072{
73}
74
75void
76CommandInterpreter::Initialize ()
77{
78 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
79
80 CommandReturnObject result;
81
82 LoadCommandDictionary ();
83
84 InitializeVariables ();
85
86 // Set up some initial aliases.
87 result.Clear(); HandleCommand ("alias q quit", false, result);
88 result.Clear(); HandleCommand ("alias run process launch", false, result);
89 result.Clear(); HandleCommand ("alias r process launch", false, result);
90 result.Clear(); HandleCommand ("alias c process continue", false, result);
91 result.Clear(); HandleCommand ("alias continue process continue", false, result);
92 result.Clear(); HandleCommand ("alias expr expression", false, result);
93 result.Clear(); HandleCommand ("alias exit quit", false, result);
Jim Inghamd40f8a62010-07-06 22:46:59 +000094 result.Clear(); HandleCommand ("alias b breakpoint", false, result);
Chris Lattner24943d22010-06-08 16:52:24 +000095 result.Clear(); HandleCommand ("alias bt thread backtrace", false, result);
96 result.Clear(); HandleCommand ("alias si thread step-inst", false, result);
97 result.Clear(); HandleCommand ("alias step thread step-in", false, result);
98 result.Clear(); HandleCommand ("alias s thread step-in", false, result);
99 result.Clear(); HandleCommand ("alias next thread step-over", false, result);
100 result.Clear(); HandleCommand ("alias n thread step-over", false, result);
101 result.Clear(); HandleCommand ("alias finish thread step-out", false, result);
102 result.Clear(); HandleCommand ("alias x memory read", false, result);
103 result.Clear(); HandleCommand ("alias l source-file", false, result);
104 result.Clear(); HandleCommand ("alias list source-file", false, result);
105}
106
107void
108CommandInterpreter::InitializeVariables ()
109{
110 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
111
112 m_variables["prompt"] =
113 StateVariableSP (new StateVariable ("prompt",
114 "(lldb) ",
115 false,
116 "The debugger prompt displayed for the user.",
117 StateVariable::BroadcastPromptChange));
118
119 m_variables["run-args"] =
120 StateVariableSP (new StateVariable ("run-args",
121 (Args*)NULL,
122 "An argument list containing the arguments to be passed to the executable when it is launched."));
123
124
125 m_variables["env-vars"] =
126 StateVariableSP (new StateVariable ("env-vars",
127 (Args*)NULL,
128 "A list of strings containing the environment variables to be passed to the executable's environment."));
129
130 m_variables["input-path"] =
131 StateVariableSP (new StateVariable ("input-path",
132 "/dev/stdin",
133 false,
134 "The file/path to be used by the executable program for reading its input."));
135
136 m_variables["output-path"] =
137 StateVariableSP (new StateVariable ( "output-path",
138 "/dev/stdout",
139 false,
140 "The file/path to be used by the executable program for writing its output."));
141
142 m_variables["error-path"] =
143 StateVariableSP (new StateVariable ("error-path",
144 "/dev/stderr",
145 false,
146 "The file/path to be used by the executable program for writing its error messages."));
147
148 m_variables["arch"] =
149 StateVariableSP (new StateVariable ("arch",
150 "",
151 false,
152 "The architecture to be used for running the executable (e.g. i386, x86_64, etc)."));
153
154 m_variables["script-lang"] =
155 StateVariableSP (new StateVariable ("script-lang",
156 "Python",
157 false,
158 "The script language to be used for evaluating user-written scripts.",
159 StateVariable::VerifyScriptLanguage));
160
161 m_variables["term-width"] =
162 StateVariableSP (new StateVariable ("term-width",
163 80,
164 "The maximum number of columns to use for displaying text."));
165
166}
167
168const char *
169CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
170{
171 // This function has not yet been implemented.
172
173 // Look for any embedded script command
174 // If found,
175 // get interpreter object from the command dictionary,
176 // call execute_one_command on it,
177 // get the results as a string,
178 // substitute that string for current stuff.
179
180 return arg;
181}
182
183
184void
185CommandInterpreter::LoadCommandDictionary ()
186{
187 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
188
189 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
190 //
191 // Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref)
192 // *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use
193 // the cross-referencing stuff) are created!!!
194 //
195 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
196
197
198 // Command objects that inherit from CommandObjectCrossref must be created before other command objects
199 // are created. This is so that when another command is created that needs to go into a crossref object,
200 // the crossref object exists and is ready to take the cross reference. Put the cross referencing command
201 // objects into the CommandDictionary now, so they are ready for use when the other commands get created.
202
Greg Clayton63094e02010-06-23 01:19:29 +0000203 m_command_dict["select"] = CommandObjectSP (new CommandObjectSelect ());
204 m_command_dict["info"] = CommandObjectSP (new CommandObjectInfo ());
205 m_command_dict["delete"] = CommandObjectSP (new CommandObjectDelete ());
Chris Lattner24943d22010-06-08 16:52:24 +0000206
207 // Non-CommandObjectCrossref commands can now be created.
208
Chris Lattner24943d22010-06-08 16:52:24 +0000209 m_command_dict["alias"] = CommandObjectSP (new CommandObjectAlias ());
210 m_command_dict["append"] = CommandObjectSP (new CommandObjectAppend ());
211 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos ());
Greg Clayton63094e02010-06-23 01:19:29 +0000212 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000213 m_command_dict["call"] = CommandObjectSP (new CommandObjectCall ());
214 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble ());
215 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression ());
216 m_command_dict["file"] = CommandObjectSP (new CommandObjectFile ());
Greg Clayton63094e02010-06-23 01:19:29 +0000217 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000218 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp ());
Greg Clayton63094e02010-06-23 01:19:29 +0000219 m_command_dict["image"] = CommandObjectSP (new CommandObjectImage (*this));
220 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
221 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
222 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000223 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit ());
Greg Clayton63094e02010-06-23 01:19:29 +0000224 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000225 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (m_script_language));
226 m_command_dict["set"] = CommandObjectSP (new CommandObjectSet ());
227 m_command_dict["settings"] = CommandObjectSP (new CommandObjectSettings ());
228 m_command_dict["show"] = CommandObjectSP (new CommandObjectShow ());
229 m_command_dict["source"] = CommandObjectSP (new CommandObjectSource ());
230 m_command_dict["source-file"] = CommandObjectSP (new CommandObjectSourceFile ());
Greg Clayton63094e02010-06-23 01:19:29 +0000231 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
232 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000233 m_command_dict["unalias"] = CommandObjectSP (new CommandObjectUnalias ());
Greg Clayton63094e02010-06-23 01:19:29 +0000234 m_command_dict["variable"] = CommandObjectSP (new CommandObjectVariable (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000235
236 std::auto_ptr<CommandObjectRegexCommand>
237 break_regex_cmd_ap(new CommandObjectRegexCommand ("regexp-break",
238 "Smart breakpoint command (using regular expressions).",
239 "regexp-break [<file>:<line>]\nregexp-break [<address>]\nregexp-break <...>", 2));
240 if (break_regex_cmd_ap.get())
241 {
242 if (break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2") &&
243 break_regex_cmd_ap->AddRegexCommand("^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1") &&
244 break_regex_cmd_ap->AddRegexCommand("^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'") &&
245 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list") &&
246 break_regex_cmd_ap->AddRegexCommand("^(-.*)$", "breakpoint set %1") &&
247 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"))
248 {
249 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
250 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
251 }
252 }
253}
254
255int
256CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
257 StringList &matches)
258{
259 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
260
261 if (include_aliases)
262 {
263 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
264 }
265
266 return matches.GetSize();
267}
268
269CommandObjectSP
270CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
271{
272 CommandObject::CommandMap::iterator pos;
273 CommandObjectSP ret_val;
274
275 std::string cmd(cmd_cstr);
276
277 if (HasCommands())
278 {
279 pos = m_command_dict.find(cmd);
280 if (pos != m_command_dict.end())
281 ret_val = pos->second;
282 }
283
284 if (include_aliases && HasAliases())
285 {
286 pos = m_alias_dict.find(cmd);
287 if (pos != m_alias_dict.end())
288 ret_val = pos->second;
289 }
290
291 if (HasUserCommands())
292 {
293 pos = m_user_dict.find(cmd);
294 if (pos != m_user_dict.end())
295 ret_val = pos->second;
296 }
297
298 if (!exact && ret_val == NULL)
299 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000300 // We will only get into here if we didn't find any exact matches.
301
302 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
303
Chris Lattner24943d22010-06-08 16:52:24 +0000304 StringList local_matches;
305 if (matches == NULL)
306 matches = &local_matches;
307
Jim Inghamd40f8a62010-07-06 22:46:59 +0000308 unsigned int num_cmd_matches = 0;
309 unsigned int num_alias_matches = 0;
310 unsigned int num_user_matches = 0;
311
312 // Look through the command dictionaries one by one, and if we get only one match from any of
313 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
314
Chris Lattner24943d22010-06-08 16:52:24 +0000315 if (HasCommands())
316 {
317 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
318 }
319
320 if (num_cmd_matches == 1)
321 {
322 cmd.assign(matches->GetStringAtIndex(0));
323 pos = m_command_dict.find(cmd);
324 if (pos != m_command_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000325 real_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000326 }
327
Jim Ingham9a574172010-06-24 20:28:42 +0000328 if (include_aliases && HasAliases())
Chris Lattner24943d22010-06-08 16:52:24 +0000329 {
330 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
331
332 }
333
Jim Inghamd40f8a62010-07-06 22:46:59 +0000334 if (num_alias_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000335 {
336 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
337 pos = m_alias_dict.find(cmd);
338 if (pos != m_alias_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000339 alias_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000340 }
341
Jim Ingham9a574172010-06-24 20:28:42 +0000342 if (HasUserCommands())
Chris Lattner24943d22010-06-08 16:52:24 +0000343 {
344 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
345 }
346
Jim Inghamd40f8a62010-07-06 22:46:59 +0000347 if (num_user_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000348 {
349 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
350
351 pos = m_user_dict.find (cmd);
352 if (pos != m_user_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000353 user_match_sp = pos->second;
354 }
355
356 // If we got exactly one match, return that, otherwise return the match list.
357
358 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
359 {
360 if (num_cmd_matches)
361 return real_match_sp;
362 else if (num_alias_matches)
363 return alias_match_sp;
364 else
365 return user_match_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000366 }
367 }
Jim Inghamd40f8a62010-07-06 22:46:59 +0000368 else if (matches && ret_val != NULL)
369 {
370 matches->AppendString (cmd_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +0000371 }
372
373
374 return ret_val;
375}
376
Jim Inghamd40f8a62010-07-06 22:46:59 +0000377CommandObjectSP
378CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner24943d22010-06-08 16:52:24 +0000379{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000380 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
381}
382
383CommandObject *
384CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
385{
386 return GetCommandSPExact (cmd_cstr, include_aliases).get();
387}
388
389CommandObject *
390CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
391{
392 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
393
394 // If we didn't find an exact match to the command string in the commands, look in
395 // the aliases.
396
397 if (command_obj == NULL)
398 {
399 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
400 }
401
402 // Finally, if there wasn't an exact match among the aliases, look for an inexact match
403 // in both the commands and the aliases.
404
405 if (command_obj == NULL)
406 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
407
408 return command_obj;
Chris Lattner24943d22010-06-08 16:52:24 +0000409}
410
411bool
412CommandInterpreter::CommandExists (const char *cmd)
413{
414 return m_command_dict.find(cmd) != m_command_dict.end();
415}
416
417bool
418CommandInterpreter::AliasExists (const char *cmd)
419{
420 return m_alias_dict.find(cmd) != m_alias_dict.end();
421}
422
423bool
424CommandInterpreter::UserCommandExists (const char *cmd)
425{
426 return m_user_dict.find(cmd) != m_user_dict.end();
427}
428
429void
430CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
431{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000432 command_obj_sp->SetIsAlias (true);
Chris Lattner24943d22010-06-08 16:52:24 +0000433 m_alias_dict[alias_name] = command_obj_sp;
434}
435
436bool
437CommandInterpreter::RemoveAlias (const char *alias_name)
438{
439 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
440 if (pos != m_alias_dict.end())
441 {
442 m_alias_dict.erase(pos);
443 return true;
444 }
445 return false;
446}
447bool
448CommandInterpreter::RemoveUser (const char *alias_name)
449{
450 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
451 if (pos != m_user_dict.end())
452 {
453 m_user_dict.erase(pos);
454 return true;
455 }
456 return false;
457}
458
459StateVariable *
460CommandInterpreter::GetStateVariable(const char *name)
461{
462 VariableMap::const_iterator pos = m_variables.find(name);
463 if (pos != m_variables.end())
464 return pos->second.get();
465 return NULL;
466}
467
468void
469CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
470{
471 help_string.Printf ("'%s", command_name);
472 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
473
474 if (option_arg_vector_sp != NULL)
475 {
476 OptionArgVector *options = option_arg_vector_sp.get();
477 for (int i = 0; i < options->size(); ++i)
478 {
479 OptionArgPair cur_option = (*options)[i];
480 std::string opt = cur_option.first;
481 std::string value = cur_option.second;
482 if (opt.compare("<argument>") == 0)
483 {
484 help_string.Printf (" %s", value.c_str());
485 }
486 else
487 {
488 help_string.Printf (" %s", opt.c_str());
489 if ((value.compare ("<no-argument>") != 0)
490 && (value.compare ("<need-argument") != 0))
491 {
492 help_string.Printf (" %s", value.c_str());
493 }
494 }
495 }
496 }
497
498 help_string.Printf ("'");
499}
500
501std::string
502CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
503{
504 CommandObject::CommandMap::const_iterator pos;
505 int max_len = 0;
506 CommandObjectSP cmd_sp;
507 std::string longest_word;
508
509 for (pos = dict.begin(); pos != dict.end(); ++pos)
510 {
511 if ((max_len == 0)
512 || (strlen (pos->first.c_str()) > max_len))
513 {
514 longest_word = pos->first;
515 max_len = strlen (longest_word.c_str());
516 }
517 }
518
519 return longest_word;
520}
521
522void
523CommandInterpreter::GetHelp (CommandReturnObject &result)
524{
525 CommandObject::CommandMap::const_iterator pos;
526 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
527 result.AppendMessage("");
528 std::string longest_word = FindLongestCommandWord (m_command_dict);
529 uint32_t max_len = strlen (longest_word.c_str());
530
531 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
532 {
533 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
534 max_len);
535 }
536 result.AppendMessage("");
537
538 if (m_alias_dict.size() > 0)
539 {
540 result.AppendMessage("The following is a list of your current command abbreviations (see 'alias' for more info):");
541 result.AppendMessage("");
542 longest_word = FindLongestCommandWord (m_alias_dict);
543 max_len = strlen (longest_word.c_str());
544 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
545 {
546 StreamString sstr;
547 StreamString translation_and_help;
548 std::string entry_name = pos->first;
549 std::string second_entry = pos->second.get()->GetCommandName();
550 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
551
552 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
553 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
554 translation_and_help.GetData(), max_len);
555 }
556 result.AppendMessage("");
557 }
558
559 if (m_user_dict.size() > 0)
560 {
561 result.AppendMessage ("The following is a list of your current user-defined commands:");
562 result.AppendMessage("");
563 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
564 {
565 result.AppendMessageWithFormat ("%s -- %s\n", pos->first.c_str(), pos->second->GetHelp());
566 }
567 result.AppendMessage("");
568 }
569
570 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
571}
572
573void
574CommandInterpreter::ShowVariableValues (CommandReturnObject &result)
575{
576 result.AppendMessage ("Below is a list of all the debugger setting variables and their values:");
577
578 for (VariableMap::const_iterator pos = m_variables.begin(); pos != m_variables.end(); ++pos)
579 {
580 StateVariable *var = pos->second.get();
581 var->AppendVariableInformation (result);
582 }
583}
584
585void
586CommandInterpreter::ShowVariableHelp (CommandReturnObject &result)
587{
588 result.AppendMessage ("Below is a list of all the internal debugger variables that are settable:");
589 for (VariableMap::const_iterator pos = m_variables.begin(); pos != m_variables.end(); ++pos)
590 {
591 StateVariable *var = pos->second.get();
592 result.AppendMessageWithFormat (" %s -- %s \n", var->GetName(), var->GetHelp());
593 }
594}
595
596// Main entry point into the command_interpreter; this function takes a text
597// line containing a debugger command, with all its flags, options, etc,
598// parses the line and takes the appropriate actions.
599
600bool
Greg Clayton63094e02010-06-23 01:19:29 +0000601CommandInterpreter::HandleCommand
602(
603 const char *command_line,
604 bool add_to_history,
605 CommandReturnObject &result,
606 ExecutionContext *override_context
607)
Chris Lattner24943d22010-06-08 16:52:24 +0000608{
609 // FIXME: there should probably be a mutex to make sure only one thread can
610 // run the interpreter at a time.
611
612 // TODO: this should be a logging channel in lldb.
613// if (DebugSelf())
614// {
615// result.AppendMessageWithFormat ("Processing command: %s\n", command_line);
616// }
617
Greg Clayton63094e02010-06-23 01:19:29 +0000618 m_debugger.UpdateExecutionContext (override_context);
Chris Lattner24943d22010-06-08 16:52:24 +0000619
620 if (command_line == NULL || command_line[0] == '\0')
621 {
622 if (m_command_history.empty())
623 {
624 result.AppendError ("empty command");
625 result.SetStatus(eReturnStatusFailed);
626 return false;
627 }
628 else
629 {
630 command_line = m_command_history.back().c_str();
631 }
632 add_to_history = false;
633 }
634
635 Args command_args(command_line);
636
637 if (command_args.GetArgumentCount() > 0)
638 {
639 const char *command_cstr = command_args.GetArgumentAtIndex(0);
640 if (command_cstr)
641 {
642
643 // We're looking up the command object here. So first find an exact match to the
644 // command in the commands.
Jim Inghamd40f8a62010-07-06 22:46:59 +0000645 CommandObject *command_obj = GetCommandObject(command_cstr);
646
647 if (command_obj != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000648 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000649 if (command_obj->IsAlias())
Chris Lattner24943d22010-06-08 16:52:24 +0000650 {
651 BuildAliasCommandArgs (command_obj, command_cstr, command_args, result);
652 if (!result.Succeeded())
653 return false;
654 }
Chris Lattner24943d22010-06-08 16:52:24 +0000655
Chris Lattner24943d22010-06-08 16:52:24 +0000656 if (command_obj->WantsRawCommandString())
657 {
658 const char *stripped_command = ::strstr (command_line, command_cstr);
659 if (stripped_command)
660 {
661 stripped_command += strlen(command_cstr);
662 while (isspace(*stripped_command))
663 ++stripped_command;
Greg Clayton63094e02010-06-23 01:19:29 +0000664 command_obj->ExecuteRawCommandString (*this, stripped_command, result);
Chris Lattner24943d22010-06-08 16:52:24 +0000665 }
666 }
667 else
668 {
669 if (add_to_history)
670 m_command_history.push_back (command_line);
671
672 // Remove the command from the args.
673 command_args.Shift();
Greg Clayton63094e02010-06-23 01:19:29 +0000674 command_obj->ExecuteWithOptions (*this, command_args, result);
Chris Lattner24943d22010-06-08 16:52:24 +0000675 }
676 }
677 else
678 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000679 // We didn't find the first command object, so complete the first argument.
Chris Lattner24943d22010-06-08 16:52:24 +0000680 StringList matches;
681 int num_matches;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000682 int cursor_index = 0;
683 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
Jim Ingham802f8b02010-06-30 05:02:46 +0000684 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +0000685 num_matches = HandleCompletionMatches (command_args,
686 cursor_index,
687 cursor_char_position,
688 0,
689 -1,
Jim Ingham802f8b02010-06-30 05:02:46 +0000690 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +0000691 matches);
Chris Lattner24943d22010-06-08 16:52:24 +0000692
693 if (num_matches > 0)
694 {
695 std::string error_msg;
696 error_msg.assign ("ambiguous command '");
697 error_msg.append(command_cstr);
698 error_msg.append ("'.");
699
700 error_msg.append (" Possible completions:");
701 for (int i = 0; i < num_matches; i++)
702 {
703 error_msg.append ("\n\t");
704 error_msg.append (matches.GetStringAtIndex (i));
705 }
706 error_msg.append ("\n");
707 result.AppendRawError (error_msg.c_str(), error_msg.size());
708 }
709 else
710 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_cstr);
711
712 result.SetStatus (eReturnStatusFailed);
713 }
714 }
715 }
716 return result.Succeeded();
717}
718
719int
720CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
721 int &cursor_index,
722 int &cursor_char_position,
723 int match_start_point,
724 int max_return_elements,
Jim Ingham802f8b02010-06-30 05:02:46 +0000725 bool &word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +0000726 StringList &matches)
727{
728 int num_command_matches = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000729 bool look_for_subcommand = false;
Jim Ingham802f8b02010-06-30 05:02:46 +0000730
731 // For any of the command completions a unique match will be a complete word.
732 word_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000733
734 if (cursor_index == -1)
735 {
736 // We got nothing on the command line, so return the list of commands
Jim Inghamd40f8a62010-07-06 22:46:59 +0000737 bool include_aliases = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000738 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
739 }
740 else if (cursor_index == 0)
741 {
742 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Inghamd40f8a62010-07-06 22:46:59 +0000743 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner24943d22010-06-08 16:52:24 +0000744 num_command_matches = matches.GetSize();
745
746 if (num_command_matches == 1
747 && cmd_obj && cmd_obj->IsMultiwordObject()
748 && matches.GetStringAtIndex(0) != NULL
749 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
750 {
751 look_for_subcommand = true;
752 num_command_matches = 0;
753 matches.DeleteStringAtIndex(0);
754 parsed_line.AppendArgument ("");
755 cursor_index++;
756 cursor_char_position = 0;
757 }
758 }
759
760 if (cursor_index > 0 || look_for_subcommand)
761 {
762 // We are completing further on into a commands arguments, so find the command and tell it
763 // to complete the command.
764 // First see if there is a matching initial command:
Jim Inghamd40f8a62010-07-06 22:46:59 +0000765 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner24943d22010-06-08 16:52:24 +0000766 if (command_object == NULL)
767 {
768 return 0;
769 }
770 else
771 {
772 parsed_line.Shift();
773 cursor_index--;
Greg Clayton63094e02010-06-23 01:19:29 +0000774 num_command_matches = command_object->HandleCompletion (*this,
775 parsed_line,
776 cursor_index,
777 cursor_char_position,
778 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +0000779 max_return_elements,
780 word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +0000781 matches);
782 }
783 }
784
785 return num_command_matches;
786
787}
788
789int
790CommandInterpreter::HandleCompletion (const char *current_line,
791 const char *cursor,
792 const char *last_char,
793 int match_start_point,
794 int max_return_elements,
795 StringList &matches)
796{
797 // We parse the argument up to the cursor, so the last argument in parsed_line is
798 // the one containing the cursor, and the cursor is after the last character.
799
800 Args parsed_line(current_line, last_char - current_line);
801 Args partial_parsed_line(current_line, cursor - current_line);
802
803 int num_args = partial_parsed_line.GetArgumentCount();
804 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
805 int cursor_char_position;
806
807 if (cursor_index == -1)
808 cursor_char_position = 0;
809 else
810 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
811
812 int num_command_matches;
813
814 matches.Clear();
815
816 // Only max_return_elements == -1 is supported at present:
817 assert (max_return_elements == -1);
Jim Ingham802f8b02010-06-30 05:02:46 +0000818 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +0000819 num_command_matches = HandleCompletionMatches (parsed_line,
820 cursor_index,
821 cursor_char_position,
822 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +0000823 max_return_elements,
824 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +0000825 matches);
Chris Lattner24943d22010-06-08 16:52:24 +0000826
827 if (num_command_matches <= 0)
828 return num_command_matches;
829
830 if (num_args == 0)
831 {
832 // If we got an empty string, insert nothing.
833 matches.InsertStringAtIndex(0, "");
834 }
835 else
836 {
837 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
838 // put an empty string in element 0.
839 std::string command_partial_str;
840 if (cursor_index >= 0)
841 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index), parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
842
843 std::string common_prefix;
844 matches.LongestCommonPrefix (common_prefix);
845 int partial_name_len = command_partial_str.size();
846
847 // If we matched a unique single command, add a space...
Jim Ingham802f8b02010-06-30 05:02:46 +0000848 // Only do this if the completer told us this was a complete word, however...
849 if (num_command_matches == 1 && word_complete)
Chris Lattner24943d22010-06-08 16:52:24 +0000850 {
851 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
852 if (quote_char != '\0')
853 common_prefix.push_back(quote_char);
854
855 common_prefix.push_back(' ');
856 }
857 common_prefix.erase (0, partial_name_len);
858 matches.InsertStringAtIndex(0, common_prefix.c_str());
859 }
860 return num_command_matches;
861}
862
Chris Lattner24943d22010-06-08 16:52:24 +0000863const Args *
864CommandInterpreter::GetProgramArguments ()
865{
866 if (! HasInterpreterVariables())
867 return NULL;
868
869 VariableMap::const_iterator pos = m_variables.find("run-args");
870 if (pos == m_variables.end())
871 return NULL;
872
873 StateVariable *var = pos->second.get();
874
875 if (var)
876 return &var->GetArgs();
877 return NULL;
878}
879
880const Args *
881CommandInterpreter::GetEnvironmentVariables ()
882{
883 if (! HasInterpreterVariables())
884 return NULL;
885
886 VariableMap::const_iterator pos = m_variables.find("env-vars");
887 if (pos == m_variables.end())
888 return NULL;
889
890 StateVariable *var = pos->second.get();
891 if (var)
892 return &var->GetArgs();
893 return NULL;
894}
895
896
897CommandInterpreter::~CommandInterpreter ()
898{
899}
900
901const char *
902CommandInterpreter::GetPrompt ()
903{
904 VariableMap::iterator pos;
905
906 if (! HasInterpreterVariables())
907 return NULL;
908
909 pos = m_variables.find("prompt");
910 if (pos == m_variables.end())
911 return NULL;
912
913 StateVariable *var = pos->second.get();
914
915 return ((char *) var->GetStringValue());
916}
917
918void
919CommandInterpreter::SetPrompt (const char *new_prompt)
920{
921 VariableMap::iterator pos;
922 CommandReturnObject result;
923
924 if (! HasInterpreterVariables())
925 return;
926
927 pos = m_variables.find ("prompt");
928 if (pos == m_variables.end())
929 return;
930
931 StateVariable *var = pos->second.get();
932
933 if (var->VerifyValue (this, (void *) new_prompt, result))
934 var->SetStringValue (new_prompt);
935}
936
937void
938CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
939{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000940 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner24943d22010-06-08 16:52:24 +0000941
942 if (cmd_obj_sp != NULL)
943 {
944 CommandObject *cmd_obj = cmd_obj_sp.get();
945 if (cmd_obj->IsCrossRefObject ())
946 cmd_obj->AddObject (object_type);
947 }
948}
949
950void
951CommandInterpreter::SetScriptLanguage (ScriptLanguage lang)
952{
953 m_script_language = lang;
954}
955
Chris Lattner24943d22010-06-08 16:52:24 +0000956OptionArgVectorSP
957CommandInterpreter::GetAliasOptions (const char *alias_name)
958{
959 OptionArgMap::iterator pos;
960 OptionArgVectorSP ret_val;
961
962 std::string alias (alias_name);
963
964 if (HasAliasOptions())
965 {
966 pos = m_alias_options.find (alias);
967 if (pos != m_alias_options.end())
968 ret_val = pos->second;
969 }
970
971 return ret_val;
972}
973
974void
975CommandInterpreter::RemoveAliasOptions (const char *alias_name)
976{
977 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
978 if (pos != m_alias_options.end())
979 {
980 m_alias_options.erase (pos);
981 }
982}
983
984void
985CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
986{
987 m_alias_options[alias_name] = option_arg_vector_sp;
988}
989
990bool
991CommandInterpreter::HasCommands ()
992{
993 return (!m_command_dict.empty());
994}
995
996bool
997CommandInterpreter::HasAliases ()
998{
999 return (!m_alias_dict.empty());
1000}
1001
1002bool
1003CommandInterpreter::HasUserCommands ()
1004{
1005 return (!m_user_dict.empty());
1006}
1007
1008bool
1009CommandInterpreter::HasAliasOptions ()
1010{
1011 return (!m_alias_options.empty());
1012}
1013
1014bool
1015CommandInterpreter::HasInterpreterVariables ()
1016{
1017 return (!m_variables.empty());
1018}
1019
1020void
1021CommandInterpreter::BuildAliasCommandArgs
1022(
1023 CommandObject *alias_cmd_obj,
1024 const char *alias_name,
1025 Args &cmd_args,
1026 CommandReturnObject &result
1027)
1028{
1029 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1030
1031 if (option_arg_vector_sp.get())
1032 {
1033 // Make sure that the alias name is the 0th element in cmd_args
1034 std::string alias_name_str = alias_name;
1035 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
1036 cmd_args.Unshift (alias_name);
1037
1038 Args new_args (alias_cmd_obj->GetCommandName());
1039 if (new_args.GetArgumentCount() == 2)
1040 new_args.Shift();
1041
1042 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1043 int old_size = cmd_args.GetArgumentCount();
1044 int *used = (int *) malloc ((old_size + 1) * sizeof (int));
1045
1046 memset (used, 0, (old_size + 1) * sizeof (int));
1047 used[0] = 1;
1048
1049 for (int i = 0; i < option_arg_vector->size(); ++i)
1050 {
1051 OptionArgPair option_pair = (*option_arg_vector)[i];
1052 std::string option = option_pair.first;
1053 std::string value = option_pair.second;
1054 if (option.compare ("<argument>") == 0)
1055 new_args.AppendArgument (value.c_str());
1056 else
1057 {
1058 new_args.AppendArgument (option.c_str());
1059 if (value.compare ("<no-argument>") != 0)
1060 {
1061 int index = GetOptionArgumentPosition (value.c_str());
1062 if (index == 0)
1063 // value was NOT a positional argument; must be a real value
1064 new_args.AppendArgument (value.c_str());
1065 else if (index >= cmd_args.GetArgumentCount())
1066 {
1067 result.AppendErrorWithFormat
1068 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1069 index);
1070 result.SetStatus (eReturnStatusFailed);
1071 return;
1072 }
1073 else
1074 {
1075 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
1076 used[index] = 1;
1077 }
1078 }
1079 }
1080 }
1081
1082 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
1083 {
1084 if (!used[j])
1085 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
1086 }
1087
1088 cmd_args.Clear();
1089 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1090 }
1091 else
1092 {
1093 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1094 // This alias was not created with any options; nothing further needs to be done.
1095 return;
1096 }
1097
1098 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1099 return;
1100}
1101
1102
1103int
1104CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
1105{
1106 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
1107 // of zero.
1108
1109 char *cptr = (char *) in_string;
1110
1111 // Does it start with '%'
1112 if (cptr[0] == '%')
1113 {
1114 ++cptr;
1115
1116 // Is the rest of it entirely digits?
1117 if (isdigit (cptr[0]))
1118 {
1119 const char *start = cptr;
1120 while (isdigit (cptr[0]))
1121 ++cptr;
1122
1123 // We've gotten to the end of the digits; are we at the end of the string?
1124 if (cptr[0] == '\0')
1125 position = atoi (start);
1126 }
1127 }
1128
1129 return position;
1130}
1131
1132void
1133CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
1134{
1135 const char *init_file_path = in_cwd ? "./.lldbinit" : "~/.lldbinit";
1136 FileSpec init_file (init_file_path);
1137 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
1138 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
1139
1140 if (init_file.Exists())
1141 {
1142 char path[PATH_MAX];
1143 init_file.GetPath(path, sizeof(path));
1144 StreamString source_command;
1145 source_command.Printf ("source '%s'", path);
1146 HandleCommand (source_command.GetData(), false, result);
1147 }
1148 else
1149 {
1150 // nothing to be done if the file doesn't exist
1151 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1152 }
1153}
1154
1155ScriptInterpreter *
1156CommandInterpreter::GetScriptInterpreter ()
1157{
Greg Clayton63094e02010-06-23 01:19:29 +00001158 CommandObject::CommandMap::iterator pos;
1159
1160 pos = m_command_dict.find ("script");
1161 if (pos != m_command_dict.end())
Chris Lattner24943d22010-06-08 16:52:24 +00001162 {
Greg Clayton63094e02010-06-23 01:19:29 +00001163 CommandObject *script_cmd_obj = pos->second.get();
1164 return ((CommandObjectScript *) script_cmd_obj)->GetInterpreter (*this);
Chris Lattner24943d22010-06-08 16:52:24 +00001165 }
Greg Clayton63094e02010-06-23 01:19:29 +00001166 return NULL;
Chris Lattner24943d22010-06-08 16:52:24 +00001167}
1168
1169
1170
1171bool
1172CommandInterpreter::GetSynchronous ()
1173{
1174 return m_synchronous_execution;
1175}
1176
1177void
1178CommandInterpreter::SetSynchronous (bool value)
1179{
1180 static bool value_set_once = false;
1181 if (!value_set_once)
1182 {
1183 value_set_once = true;
1184 m_synchronous_execution = value;
1185 }
1186}
1187
1188void
1189CommandInterpreter::OutputFormattedHelpText (Stream &strm,
1190 const char *word_text,
1191 const char *separator,
1192 const char *help_text,
1193 uint32_t max_word_len)
1194{
1195 StateVariable *var = GetStateVariable ("term-width");
1196 int max_columns = var->GetIntValue();
1197 // Sanity check max_columns, to cope with emacs shell mode with TERM=dumb
1198 // (0 rows; 0 columns;).
1199 if (max_columns <= 0) max_columns = 80;
1200
1201 int indent_size = max_word_len + strlen (separator) + 2;
1202
1203 strm.IndentMore (indent_size);
1204
1205 int len = indent_size + strlen (help_text) + 1;
1206 char *text = (char *) malloc (len);
1207 sprintf (text, "%-*s %s %s", max_word_len, word_text, separator, help_text);
1208 if (text[len - 1] == '\n')
1209 text[--len] = '\0';
1210
1211 if (len < max_columns)
1212 {
1213 // Output it as a single line.
1214 strm.Printf ("%s", text);
1215 }
1216 else
1217 {
1218 // We need to break it up into multiple lines.
1219 bool first_line = true;
1220 int text_width;
1221 int start = 0;
1222 int end = start;
1223 int final_end = strlen (text);
1224 int sub_len;
1225
1226 while (end < final_end)
1227 {
1228 if (first_line)
1229 text_width = max_columns - 1;
1230 else
1231 text_width = max_columns - indent_size - 1;
1232
1233 // Don't start the 'text' on a space, since we're already outputting the indentation.
1234 if (!first_line)
1235 {
1236 while ((start < final_end) && (text[start] == ' '))
1237 start++;
1238 }
1239
1240 end = start + text_width;
1241 if (end > final_end)
1242 end = final_end;
1243 else
1244 {
1245 // If we're not at the end of the text, make sure we break the line on white space.
1246 while (end > start
1247 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
1248 end--;
1249 }
1250
1251 sub_len = end - start;
1252 if (start != 0)
1253 strm.EOL();
1254 if (!first_line)
1255 strm.Indent();
1256 else
1257 first_line = false;
1258 assert (start <= final_end);
1259 assert (start + sub_len <= final_end);
1260 if (sub_len > 0)
1261 strm.Write (text + start, sub_len);
1262 start = end + 1;
1263 }
1264 }
1265 strm.EOL();
1266 strm.IndentLess(indent_size);
1267 free (text);
1268}
1269
1270void
1271CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word,
1272 StringList &commands_found, StringList &commands_help)
1273{
1274 CommandObject::CommandMap::const_iterator pos;
1275 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict;
1276 CommandObject *sub_cmd_obj;
1277
1278 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos)
1279 {
1280 const char * command_name = pos->first.c_str();
1281 sub_cmd_obj = pos->second.get();
1282 StreamString complete_command_name;
1283
1284 complete_command_name.Printf ("%s %s", prefix, command_name);
1285
1286 if (sub_cmd_obj->HelpTextContainsWord (search_word))
1287 {
1288 commands_found.AppendString (complete_command_name.GetData());
1289 commands_help.AppendString (sub_cmd_obj->GetHelp());
1290 }
1291
1292 if (sub_cmd_obj->IsMultiwordObject())
1293 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found,
1294 commands_help);
1295 }
1296
1297}
1298
1299void
1300CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
1301 StringList &commands_help)
1302{
1303 CommandObject::CommandMap::const_iterator pos;
1304
1305 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
1306 {
1307 const char *command_name = pos->first.c_str();
1308 CommandObject *cmd_obj = pos->second.get();
1309
1310 if (cmd_obj->HelpTextContainsWord (search_word))
1311 {
1312 commands_found.AppendString (command_name);
1313 commands_help.AppendString (cmd_obj->GetHelp());
1314 }
1315
1316 if (cmd_obj->IsMultiwordObject())
1317 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help);
1318
1319 }
1320}