blob: ea7fde2d2ce2a9ac4ed99d89962df7bfaeec1805 [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 {
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000630 command_line = m_repeat_command.c_str();
631 if (m_repeat_command.empty())
632 {
633 result.AppendError("");
634 result.SetStatus (eReturnStatusFailed);
635 return false;
636 }
Chris Lattner24943d22010-06-08 16:52:24 +0000637 }
638 add_to_history = false;
639 }
640
641 Args command_args(command_line);
642
643 if (command_args.GetArgumentCount() > 0)
644 {
645 const char *command_cstr = command_args.GetArgumentAtIndex(0);
646 if (command_cstr)
647 {
648
649 // We're looking up the command object here. So first find an exact match to the
650 // command in the commands.
Jim Inghamd40f8a62010-07-06 22:46:59 +0000651 CommandObject *command_obj = GetCommandObject(command_cstr);
652
653 if (command_obj != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000654 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000655 if (command_obj->IsAlias())
Chris Lattner24943d22010-06-08 16:52:24 +0000656 {
657 BuildAliasCommandArgs (command_obj, command_cstr, command_args, result);
658 if (!result.Succeeded())
659 return false;
660 }
Chris Lattner24943d22010-06-08 16:52:24 +0000661
Jim Ingham5d9cbd42010-07-06 23:48:33 +0000662 if (add_to_history)
663 {
664 const char *repeat_command = command_obj->GetRepeatCommand(command_line);
665 if (repeat_command)
666 m_repeat_command.assign(repeat_command);
667 else
668 m_repeat_command.clear();
669
670 m_command_history.push_back (command_line);
671 }
672
673
Chris Lattner24943d22010-06-08 16:52:24 +0000674 if (command_obj->WantsRawCommandString())
675 {
676 const char *stripped_command = ::strstr (command_line, command_cstr);
677 if (stripped_command)
678 {
679 stripped_command += strlen(command_cstr);
680 while (isspace(*stripped_command))
681 ++stripped_command;
Greg Clayton63094e02010-06-23 01:19:29 +0000682 command_obj->ExecuteRawCommandString (*this, stripped_command, result);
Chris Lattner24943d22010-06-08 16:52:24 +0000683 }
684 }
685 else
686 {
Chris Lattner24943d22010-06-08 16:52:24 +0000687 // Remove the command from the args.
688 command_args.Shift();
Greg Clayton63094e02010-06-23 01:19:29 +0000689 command_obj->ExecuteWithOptions (*this, command_args, result);
Chris Lattner24943d22010-06-08 16:52:24 +0000690 }
691 }
692 else
693 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000694 // We didn't find the first command object, so complete the first argument.
Chris Lattner24943d22010-06-08 16:52:24 +0000695 StringList matches;
696 int num_matches;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000697 int cursor_index = 0;
698 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
Jim Ingham802f8b02010-06-30 05:02:46 +0000699 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +0000700 num_matches = HandleCompletionMatches (command_args,
701 cursor_index,
702 cursor_char_position,
703 0,
704 -1,
Jim Ingham802f8b02010-06-30 05:02:46 +0000705 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +0000706 matches);
Chris Lattner24943d22010-06-08 16:52:24 +0000707
708 if (num_matches > 0)
709 {
710 std::string error_msg;
711 error_msg.assign ("ambiguous command '");
712 error_msg.append(command_cstr);
713 error_msg.append ("'.");
714
715 error_msg.append (" Possible completions:");
716 for (int i = 0; i < num_matches; i++)
717 {
718 error_msg.append ("\n\t");
719 error_msg.append (matches.GetStringAtIndex (i));
720 }
721 error_msg.append ("\n");
722 result.AppendRawError (error_msg.c_str(), error_msg.size());
723 }
724 else
725 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_cstr);
726
727 result.SetStatus (eReturnStatusFailed);
728 }
729 }
730 }
731 return result.Succeeded();
732}
733
734int
735CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
736 int &cursor_index,
737 int &cursor_char_position,
738 int match_start_point,
739 int max_return_elements,
Jim Ingham802f8b02010-06-30 05:02:46 +0000740 bool &word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +0000741 StringList &matches)
742{
743 int num_command_matches = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000744 bool look_for_subcommand = false;
Jim Ingham802f8b02010-06-30 05:02:46 +0000745
746 // For any of the command completions a unique match will be a complete word.
747 word_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000748
749 if (cursor_index == -1)
750 {
751 // We got nothing on the command line, so return the list of commands
Jim Inghamd40f8a62010-07-06 22:46:59 +0000752 bool include_aliases = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000753 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
754 }
755 else if (cursor_index == 0)
756 {
757 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Inghamd40f8a62010-07-06 22:46:59 +0000758 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner24943d22010-06-08 16:52:24 +0000759 num_command_matches = matches.GetSize();
760
761 if (num_command_matches == 1
762 && cmd_obj && cmd_obj->IsMultiwordObject()
763 && matches.GetStringAtIndex(0) != NULL
764 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
765 {
766 look_for_subcommand = true;
767 num_command_matches = 0;
768 matches.DeleteStringAtIndex(0);
769 parsed_line.AppendArgument ("");
770 cursor_index++;
771 cursor_char_position = 0;
772 }
773 }
774
775 if (cursor_index > 0 || look_for_subcommand)
776 {
777 // We are completing further on into a commands arguments, so find the command and tell it
778 // to complete the command.
779 // First see if there is a matching initial command:
Jim Inghamd40f8a62010-07-06 22:46:59 +0000780 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner24943d22010-06-08 16:52:24 +0000781 if (command_object == NULL)
782 {
783 return 0;
784 }
785 else
786 {
787 parsed_line.Shift();
788 cursor_index--;
Greg Clayton63094e02010-06-23 01:19:29 +0000789 num_command_matches = command_object->HandleCompletion (*this,
790 parsed_line,
791 cursor_index,
792 cursor_char_position,
793 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +0000794 max_return_elements,
795 word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +0000796 matches);
797 }
798 }
799
800 return num_command_matches;
801
802}
803
804int
805CommandInterpreter::HandleCompletion (const char *current_line,
806 const char *cursor,
807 const char *last_char,
808 int match_start_point,
809 int max_return_elements,
810 StringList &matches)
811{
812 // We parse the argument up to the cursor, so the last argument in parsed_line is
813 // the one containing the cursor, and the cursor is after the last character.
814
815 Args parsed_line(current_line, last_char - current_line);
816 Args partial_parsed_line(current_line, cursor - current_line);
817
818 int num_args = partial_parsed_line.GetArgumentCount();
819 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
820 int cursor_char_position;
821
822 if (cursor_index == -1)
823 cursor_char_position = 0;
824 else
825 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
826
827 int num_command_matches;
828
829 matches.Clear();
830
831 // Only max_return_elements == -1 is supported at present:
832 assert (max_return_elements == -1);
Jim Ingham802f8b02010-06-30 05:02:46 +0000833 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +0000834 num_command_matches = HandleCompletionMatches (parsed_line,
835 cursor_index,
836 cursor_char_position,
837 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +0000838 max_return_elements,
839 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +0000840 matches);
Chris Lattner24943d22010-06-08 16:52:24 +0000841
842 if (num_command_matches <= 0)
843 return num_command_matches;
844
845 if (num_args == 0)
846 {
847 // If we got an empty string, insert nothing.
848 matches.InsertStringAtIndex(0, "");
849 }
850 else
851 {
852 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
853 // put an empty string in element 0.
854 std::string command_partial_str;
855 if (cursor_index >= 0)
856 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index), parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
857
858 std::string common_prefix;
859 matches.LongestCommonPrefix (common_prefix);
860 int partial_name_len = command_partial_str.size();
861
862 // If we matched a unique single command, add a space...
Jim Ingham802f8b02010-06-30 05:02:46 +0000863 // Only do this if the completer told us this was a complete word, however...
864 if (num_command_matches == 1 && word_complete)
Chris Lattner24943d22010-06-08 16:52:24 +0000865 {
866 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
867 if (quote_char != '\0')
868 common_prefix.push_back(quote_char);
869
870 common_prefix.push_back(' ');
871 }
872 common_prefix.erase (0, partial_name_len);
873 matches.InsertStringAtIndex(0, common_prefix.c_str());
874 }
875 return num_command_matches;
876}
877
Chris Lattner24943d22010-06-08 16:52:24 +0000878const Args *
879CommandInterpreter::GetProgramArguments ()
880{
881 if (! HasInterpreterVariables())
882 return NULL;
883
884 VariableMap::const_iterator pos = m_variables.find("run-args");
885 if (pos == m_variables.end())
886 return NULL;
887
888 StateVariable *var = pos->second.get();
889
890 if (var)
891 return &var->GetArgs();
892 return NULL;
893}
894
895const Args *
896CommandInterpreter::GetEnvironmentVariables ()
897{
898 if (! HasInterpreterVariables())
899 return NULL;
900
901 VariableMap::const_iterator pos = m_variables.find("env-vars");
902 if (pos == m_variables.end())
903 return NULL;
904
905 StateVariable *var = pos->second.get();
906 if (var)
907 return &var->GetArgs();
908 return NULL;
909}
910
911
912CommandInterpreter::~CommandInterpreter ()
913{
914}
915
916const char *
917CommandInterpreter::GetPrompt ()
918{
919 VariableMap::iterator pos;
920
921 if (! HasInterpreterVariables())
922 return NULL;
923
924 pos = m_variables.find("prompt");
925 if (pos == m_variables.end())
926 return NULL;
927
928 StateVariable *var = pos->second.get();
929
930 return ((char *) var->GetStringValue());
931}
932
933void
934CommandInterpreter::SetPrompt (const char *new_prompt)
935{
936 VariableMap::iterator pos;
937 CommandReturnObject result;
938
939 if (! HasInterpreterVariables())
940 return;
941
942 pos = m_variables.find ("prompt");
943 if (pos == m_variables.end())
944 return;
945
946 StateVariable *var = pos->second.get();
947
948 if (var->VerifyValue (this, (void *) new_prompt, result))
949 var->SetStringValue (new_prompt);
950}
951
952void
953CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
954{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000955 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner24943d22010-06-08 16:52:24 +0000956
957 if (cmd_obj_sp != NULL)
958 {
959 CommandObject *cmd_obj = cmd_obj_sp.get();
960 if (cmd_obj->IsCrossRefObject ())
961 cmd_obj->AddObject (object_type);
962 }
963}
964
965void
966CommandInterpreter::SetScriptLanguage (ScriptLanguage lang)
967{
968 m_script_language = lang;
969}
970
Chris Lattner24943d22010-06-08 16:52:24 +0000971OptionArgVectorSP
972CommandInterpreter::GetAliasOptions (const char *alias_name)
973{
974 OptionArgMap::iterator pos;
975 OptionArgVectorSP ret_val;
976
977 std::string alias (alias_name);
978
979 if (HasAliasOptions())
980 {
981 pos = m_alias_options.find (alias);
982 if (pos != m_alias_options.end())
983 ret_val = pos->second;
984 }
985
986 return ret_val;
987}
988
989void
990CommandInterpreter::RemoveAliasOptions (const char *alias_name)
991{
992 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
993 if (pos != m_alias_options.end())
994 {
995 m_alias_options.erase (pos);
996 }
997}
998
999void
1000CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
1001{
1002 m_alias_options[alias_name] = option_arg_vector_sp;
1003}
1004
1005bool
1006CommandInterpreter::HasCommands ()
1007{
1008 return (!m_command_dict.empty());
1009}
1010
1011bool
1012CommandInterpreter::HasAliases ()
1013{
1014 return (!m_alias_dict.empty());
1015}
1016
1017bool
1018CommandInterpreter::HasUserCommands ()
1019{
1020 return (!m_user_dict.empty());
1021}
1022
1023bool
1024CommandInterpreter::HasAliasOptions ()
1025{
1026 return (!m_alias_options.empty());
1027}
1028
1029bool
1030CommandInterpreter::HasInterpreterVariables ()
1031{
1032 return (!m_variables.empty());
1033}
1034
1035void
1036CommandInterpreter::BuildAliasCommandArgs
1037(
1038 CommandObject *alias_cmd_obj,
1039 const char *alias_name,
1040 Args &cmd_args,
1041 CommandReturnObject &result
1042)
1043{
1044 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1045
1046 if (option_arg_vector_sp.get())
1047 {
1048 // Make sure that the alias name is the 0th element in cmd_args
1049 std::string alias_name_str = alias_name;
1050 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
1051 cmd_args.Unshift (alias_name);
1052
1053 Args new_args (alias_cmd_obj->GetCommandName());
1054 if (new_args.GetArgumentCount() == 2)
1055 new_args.Shift();
1056
1057 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1058 int old_size = cmd_args.GetArgumentCount();
1059 int *used = (int *) malloc ((old_size + 1) * sizeof (int));
1060
1061 memset (used, 0, (old_size + 1) * sizeof (int));
1062 used[0] = 1;
1063
1064 for (int i = 0; i < option_arg_vector->size(); ++i)
1065 {
1066 OptionArgPair option_pair = (*option_arg_vector)[i];
1067 std::string option = option_pair.first;
1068 std::string value = option_pair.second;
1069 if (option.compare ("<argument>") == 0)
1070 new_args.AppendArgument (value.c_str());
1071 else
1072 {
1073 new_args.AppendArgument (option.c_str());
1074 if (value.compare ("<no-argument>") != 0)
1075 {
1076 int index = GetOptionArgumentPosition (value.c_str());
1077 if (index == 0)
1078 // value was NOT a positional argument; must be a real value
1079 new_args.AppendArgument (value.c_str());
1080 else if (index >= cmd_args.GetArgumentCount())
1081 {
1082 result.AppendErrorWithFormat
1083 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1084 index);
1085 result.SetStatus (eReturnStatusFailed);
1086 return;
1087 }
1088 else
1089 {
1090 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
1091 used[index] = 1;
1092 }
1093 }
1094 }
1095 }
1096
1097 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
1098 {
1099 if (!used[j])
1100 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
1101 }
1102
1103 cmd_args.Clear();
1104 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1105 }
1106 else
1107 {
1108 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1109 // This alias was not created with any options; nothing further needs to be done.
1110 return;
1111 }
1112
1113 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1114 return;
1115}
1116
1117
1118int
1119CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
1120{
1121 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
1122 // of zero.
1123
1124 char *cptr = (char *) in_string;
1125
1126 // Does it start with '%'
1127 if (cptr[0] == '%')
1128 {
1129 ++cptr;
1130
1131 // Is the rest of it entirely digits?
1132 if (isdigit (cptr[0]))
1133 {
1134 const char *start = cptr;
1135 while (isdigit (cptr[0]))
1136 ++cptr;
1137
1138 // We've gotten to the end of the digits; are we at the end of the string?
1139 if (cptr[0] == '\0')
1140 position = atoi (start);
1141 }
1142 }
1143
1144 return position;
1145}
1146
1147void
1148CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
1149{
1150 const char *init_file_path = in_cwd ? "./.lldbinit" : "~/.lldbinit";
1151 FileSpec init_file (init_file_path);
1152 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
1153 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
1154
1155 if (init_file.Exists())
1156 {
1157 char path[PATH_MAX];
1158 init_file.GetPath(path, sizeof(path));
1159 StreamString source_command;
1160 source_command.Printf ("source '%s'", path);
1161 HandleCommand (source_command.GetData(), false, result);
1162 }
1163 else
1164 {
1165 // nothing to be done if the file doesn't exist
1166 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1167 }
1168}
1169
1170ScriptInterpreter *
1171CommandInterpreter::GetScriptInterpreter ()
1172{
Greg Clayton63094e02010-06-23 01:19:29 +00001173 CommandObject::CommandMap::iterator pos;
1174
1175 pos = m_command_dict.find ("script");
1176 if (pos != m_command_dict.end())
Chris Lattner24943d22010-06-08 16:52:24 +00001177 {
Greg Clayton63094e02010-06-23 01:19:29 +00001178 CommandObject *script_cmd_obj = pos->second.get();
1179 return ((CommandObjectScript *) script_cmd_obj)->GetInterpreter (*this);
Chris Lattner24943d22010-06-08 16:52:24 +00001180 }
Greg Clayton63094e02010-06-23 01:19:29 +00001181 return NULL;
Chris Lattner24943d22010-06-08 16:52:24 +00001182}
1183
1184
1185
1186bool
1187CommandInterpreter::GetSynchronous ()
1188{
1189 return m_synchronous_execution;
1190}
1191
1192void
1193CommandInterpreter::SetSynchronous (bool value)
1194{
1195 static bool value_set_once = false;
1196 if (!value_set_once)
1197 {
1198 value_set_once = true;
1199 m_synchronous_execution = value;
1200 }
1201}
1202
1203void
1204CommandInterpreter::OutputFormattedHelpText (Stream &strm,
1205 const char *word_text,
1206 const char *separator,
1207 const char *help_text,
1208 uint32_t max_word_len)
1209{
1210 StateVariable *var = GetStateVariable ("term-width");
1211 int max_columns = var->GetIntValue();
1212 // Sanity check max_columns, to cope with emacs shell mode with TERM=dumb
1213 // (0 rows; 0 columns;).
1214 if (max_columns <= 0) max_columns = 80;
1215
1216 int indent_size = max_word_len + strlen (separator) + 2;
1217
1218 strm.IndentMore (indent_size);
1219
1220 int len = indent_size + strlen (help_text) + 1;
1221 char *text = (char *) malloc (len);
1222 sprintf (text, "%-*s %s %s", max_word_len, word_text, separator, help_text);
1223 if (text[len - 1] == '\n')
1224 text[--len] = '\0';
1225
1226 if (len < max_columns)
1227 {
1228 // Output it as a single line.
1229 strm.Printf ("%s", text);
1230 }
1231 else
1232 {
1233 // We need to break it up into multiple lines.
1234 bool first_line = true;
1235 int text_width;
1236 int start = 0;
1237 int end = start;
1238 int final_end = strlen (text);
1239 int sub_len;
1240
1241 while (end < final_end)
1242 {
1243 if (first_line)
1244 text_width = max_columns - 1;
1245 else
1246 text_width = max_columns - indent_size - 1;
1247
1248 // Don't start the 'text' on a space, since we're already outputting the indentation.
1249 if (!first_line)
1250 {
1251 while ((start < final_end) && (text[start] == ' '))
1252 start++;
1253 }
1254
1255 end = start + text_width;
1256 if (end > final_end)
1257 end = final_end;
1258 else
1259 {
1260 // If we're not at the end of the text, make sure we break the line on white space.
1261 while (end > start
1262 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
1263 end--;
1264 }
1265
1266 sub_len = end - start;
1267 if (start != 0)
1268 strm.EOL();
1269 if (!first_line)
1270 strm.Indent();
1271 else
1272 first_line = false;
1273 assert (start <= final_end);
1274 assert (start + sub_len <= final_end);
1275 if (sub_len > 0)
1276 strm.Write (text + start, sub_len);
1277 start = end + 1;
1278 }
1279 }
1280 strm.EOL();
1281 strm.IndentLess(indent_size);
1282 free (text);
1283}
1284
1285void
1286CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word,
1287 StringList &commands_found, StringList &commands_help)
1288{
1289 CommandObject::CommandMap::const_iterator pos;
1290 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict;
1291 CommandObject *sub_cmd_obj;
1292
1293 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos)
1294 {
1295 const char * command_name = pos->first.c_str();
1296 sub_cmd_obj = pos->second.get();
1297 StreamString complete_command_name;
1298
1299 complete_command_name.Printf ("%s %s", prefix, command_name);
1300
1301 if (sub_cmd_obj->HelpTextContainsWord (search_word))
1302 {
1303 commands_found.AppendString (complete_command_name.GetData());
1304 commands_help.AppendString (sub_cmd_obj->GetHelp());
1305 }
1306
1307 if (sub_cmd_obj->IsMultiwordObject())
1308 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found,
1309 commands_help);
1310 }
1311
1312}
1313
1314void
1315CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
1316 StringList &commands_help)
1317{
1318 CommandObject::CommandMap::const_iterator pos;
1319
1320 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
1321 {
1322 const char *command_name = pos->first.c_str();
1323 CommandObject *cmd_obj = pos->second.get();
1324
1325 if (cmd_obj->HelpTextContainsWord (search_word))
1326 {
1327 commands_found.AppendString (command_name);
1328 commands_help.AppendString (cmd_obj->GetHelp());
1329 }
1330
1331 if (cmd_obj->IsMultiwordObject())
1332 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help);
1333
1334 }
1335}