1 /* Line completion stuff for GDB, the GNU debugger.
2 Copyright (C) 2000-2019 Free Software Foundation, Inc.
4 This file is part of GDB.
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>. */
22 #include "expression.h"
23 #include "filenames.h" /* For DOSish file names. */
25 #include "common/gdb_signals.h"
27 #include "reggroups.h"
28 #include "user-regs.h"
29 #include "arch-utils.h"
33 #include "cli/cli-decode.h"
35 /* FIXME: This is needed because of lookup_cmd_1 (). We should be
36 calling a hook instead so we eliminate the CLI dependency. */
39 /* Needed for rl_completer_word_break_characters() and for
40 rl_filename_completion_function. */
41 #include "readline/readline.h"
43 /* readline defines this. */
46 #include "completer.h"
48 /* Misc state that needs to be tracked across several different
49 readline completer entry point calls, all related to a single
50 completion invocation. */
52 struct gdb_completer_state
54 /* The current completion's completion tracker. This is a global
55 because a tracker can be shared between the handle_brkchars and
56 handle_completion phases, which involves different readline
58 completion_tracker *tracker = NULL;
60 /* Whether the current completion was aborted. */
64 /* The current completion state. */
65 static gdb_completer_state current_completion;
67 /* An enumeration of the various things a user might attempt to
68 complete for a location. If you change this, remember to update
69 the explicit_options array below too. */
71 enum explicit_location_match_type
73 /* The filename of a source file. */
76 /* The name of a function or method. */
79 /* The fully-qualified name of a function or method. */
85 /* The name of a label. */
89 /* Prototypes for local functions. */
91 /* readline uses the word breaks for two things:
92 (1) In figuring out where to point the TEXT parameter to the
93 rl_completion_entry_function. Since we don't use TEXT for much,
94 it doesn't matter a lot what the word breaks are for this purpose,
95 but it does affect how much stuff M-? lists.
96 (2) If one of the matches contains a word break character, readline
97 will quote it. That's why we switch between
98 current_language->la_word_break_characters() and
99 gdb_completer_command_word_break_characters. I'm not sure when
100 we need this behavior (perhaps for funky characters in C++
103 /* Variables which are necessary for fancy command line editing. */
105 /* When completing on command names, we remove '-' from the list of
106 word break characters, since we use it in command names. If the
107 readline library sees one in any of the current completion strings,
108 it thinks that the string needs to be quoted and automatically
109 supplies a leading quote. */
110 static const char gdb_completer_command_word_break_characters[] =
111 " \t\n!@#$%^&*()+=|~`}{[]\"';:?/>.<,";
113 /* When completing on file names, we remove from the list of word
114 break characters any characters that are commonly used in file
115 names, such as '-', '+', '~', etc. Otherwise, readline displays
116 incorrect completion candidates. */
117 /* MS-DOS and MS-Windows use colon as part of the drive spec, and most
118 programs support @foo style response files. */
119 static const char gdb_completer_file_name_break_characters[] =
120 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
126 /* Characters that can be used to quote completion strings. Note that
127 we can't include '"' because the gdb C parser treats such quoted
128 sequences as strings. */
129 static const char gdb_completer_quote_characters[] = "'";
131 /* Accessor for some completer data that may interest other files. */
134 get_gdb_completer_quote_characters (void)
136 return gdb_completer_quote_characters;
139 /* This can be used for functions which don't want to complete on
140 symbols but don't want to complete on anything else either. */
143 noop_completer (struct cmd_list_element *ignore,
144 completion_tracker &tracker,
145 const char *text, const char *prefix)
149 /* Complete on filenames. */
152 filename_completer (struct cmd_list_element *ignore,
153 completion_tracker &tracker,
154 const char *text, const char *word)
161 gdb::unique_xmalloc_ptr<char> p_rl
162 (rl_filename_completion_function (text, subsequent_name));
165 /* We need to set subsequent_name to a non-zero value before the
166 continue line below, because otherwise, if the first file
167 seen by GDB is a backup file whose name ends in a `~', we
168 will loop indefinitely. */
170 /* Like emacs, don't complete on old versions. Especially
171 useful in the "source" command. */
172 const char *p = p_rl.get ();
173 if (p[strlen (p) - 1] == '~')
176 tracker.add_completion
177 (make_completion_match_str (std::move (p_rl), text, word));
180 /* There is no way to do this just long enough to affect quote
181 inserting without also affecting the next completion. This
182 should be fixed in readline. FIXME. */
183 /* Ensure that readline does the right thing
184 with respect to inserting quotes. */
185 rl_completer_word_break_characters = "";
189 /* The corresponding completer_handle_brkchars
193 filename_completer_handle_brkchars (struct cmd_list_element *ignore,
194 completion_tracker &tracker,
195 const char *text, const char *word)
197 set_rl_completer_word_break_characters
198 (gdb_completer_file_name_break_characters);
201 /* Possible values for the found_quote flags word used by the completion
202 functions. It says what kind of (shell-like) quoting we found anywhere
204 #define RL_QF_SINGLE_QUOTE 0x01
205 #define RL_QF_DOUBLE_QUOTE 0x02
206 #define RL_QF_BACKSLASH 0x04
207 #define RL_QF_OTHER_QUOTE 0x08
209 /* Find the bounds of the current word for completion purposes, and
210 return a pointer to the end of the word. This mimics (and is a
211 modified version of) readline's _rl_find_completion_word internal
214 This function skips quoted substrings (characters between matched
215 pairs of characters in rl_completer_quote_characters). We try to
216 find an unclosed quoted substring on which to do matching. If one
217 is not found, we use the word break characters to find the
218 boundaries of the current word. QC, if non-null, is set to the
219 opening quote character if we found an unclosed quoted substring,
220 '\0' otherwise. DP, if non-null, is set to the value of the
221 delimiter character that caused a word break. */
223 struct gdb_rl_completion_word_info
225 const char *word_break_characters;
226 const char *quote_characters;
227 const char *basic_quote_characters;
231 gdb_rl_find_completion_word (struct gdb_rl_completion_word_info *info,
233 const char *line_buffer)
235 int scan, end, found_quote, delimiter, pass_next, isbrk;
237 const char *brkchars;
238 int point = strlen (line_buffer);
240 /* The algorithm below does '--point'. Avoid buffer underflow with
252 found_quote = delimiter = 0;
255 brkchars = info->word_break_characters;
257 if (info->quote_characters != NULL)
259 /* We have a list of characters which can be used in pairs to
260 quote substrings for the completer. Try to find the start of
261 an unclosed quoted substring. */
262 /* FOUND_QUOTE is set so we know what kind of quotes we
264 for (scan = pass_next = 0;
274 /* Shell-like semantics for single quotes -- don't allow
275 backslash to quote anything in single quotes, especially
276 not the closing quote. If you don't like this, take out
277 the check on the value of quote_char. */
278 if (quote_char != '\'' && line_buffer[scan] == '\\')
281 found_quote |= RL_QF_BACKSLASH;
285 if (quote_char != '\0')
287 /* Ignore everything until the matching close quote
289 if (line_buffer[scan] == quote_char)
291 /* Found matching close. Abandon this
297 else if (strchr (info->quote_characters, line_buffer[scan]))
299 /* Found start of a quoted substring. */
300 quote_char = line_buffer[scan];
302 /* Shell-like quoting conventions. */
303 if (quote_char == '\'')
304 found_quote |= RL_QF_SINGLE_QUOTE;
305 else if (quote_char == '"')
306 found_quote |= RL_QF_DOUBLE_QUOTE;
308 found_quote |= RL_QF_OTHER_QUOTE;
313 if (point == end && quote_char == '\0')
315 /* We didn't find an unclosed quoted substring upon which to do
316 completion, so use the word break characters to find the
317 substring on which to complete. */
320 scan = line_buffer[point];
322 if (strchr (brkchars, scan) != 0)
327 /* If we are at an unquoted word break, then advance past it. */
328 scan = line_buffer[point];
332 isbrk = strchr (brkchars, scan) != 0;
336 /* If the character that caused the word break was a quoting
337 character, then remember it as the delimiter. */
338 if (info->basic_quote_characters
339 && strchr (info->basic_quote_characters, scan)
340 && (end - point) > 1)
352 return line_buffer + point;
355 /* See completer.h. */
358 advance_to_expression_complete_word_point (completion_tracker &tracker,
361 gdb_rl_completion_word_info info;
363 info.word_break_characters
364 = current_language->la_word_break_characters ();
365 info.quote_characters = gdb_completer_quote_characters;
366 info.basic_quote_characters = rl_basic_quote_characters;
370 = gdb_rl_find_completion_word (&info, NULL, &delimiter, text);
372 tracker.advance_custom_word_point_by (start - text);
376 tracker.set_quote_char (delimiter);
377 tracker.set_suppress_append_ws (true);
383 /* See completer.h. */
386 completion_tracker::completes_to_completion_word (const char *word)
388 if (m_lowest_common_denominator_unique)
390 const char *lcd = m_lowest_common_denominator;
392 if (strncmp_iw (word, lcd, strlen (lcd)) == 0)
394 /* Maybe skip the function and complete on keywords. */
395 size_t wordlen = strlen (word);
396 if (word[wordlen - 1] == ' ')
404 /* Complete on linespecs, which might be of two possible forms:
410 This is intended to be used in commands that set breakpoints
414 complete_files_symbols (completion_tracker &tracker,
415 const char *text, const char *word)
417 completion_list fn_list;
420 int quoted = *text == '\'' || *text == '"';
421 int quote_char = '\0';
422 const char *colon = NULL;
423 char *file_to_match = NULL;
424 const char *symbol_start = text;
425 const char *orig_text = text;
427 /* Do we have an unquoted colon, as in "break foo.c:bar"? */
428 for (p = text; *p != '\0'; ++p)
430 if (*p == '\\' && p[1] == '\'')
432 else if (*p == '\'' || *p == '"')
436 while (*p != '\0' && *p != quote_found)
438 if (*p == '\\' && p[1] == quote_found)
443 if (*p == quote_found)
446 break; /* Hit the end of text. */
448 #if HAVE_DOS_BASED_FILE_SYSTEM
449 /* If we have a DOS-style absolute file name at the beginning of
450 TEXT, and the colon after the drive letter is the only colon
451 we found, pretend the colon is not there. */
452 else if (p < text + 3 && *p == ':' && p == text + 1 + quoted)
455 else if (*p == ':' && !colon)
458 symbol_start = p + 1;
460 else if (strchr (current_language->la_word_break_characters(), *p))
461 symbol_start = p + 1;
467 /* Where is the file name? */
472 file_to_match = (char *) xmalloc (colon - text + 1);
473 strncpy (file_to_match, text, colon - text);
474 file_to_match[colon - text] = '\0';
475 /* Remove trailing colons and quotes from the file name. */
476 for (s = file_to_match + (colon - text);
479 if (*s == ':' || *s == quote_char)
482 /* If the text includes a colon, they want completion only on a
483 symbol name after the colon. Otherwise, we need to complete on
484 symbols as well as on files. */
487 collect_file_symbol_completion_matches (tracker,
488 complete_symbol_mode::EXPRESSION,
489 symbol_name_match_type::EXPRESSION,
492 xfree (file_to_match);
496 size_t text_len = strlen (text);
498 collect_symbol_completion_matches (tracker,
499 complete_symbol_mode::EXPRESSION,
500 symbol_name_match_type::EXPRESSION,
502 /* If text includes characters which cannot appear in a file
503 name, they cannot be asking for completion on files. */
505 gdb_completer_file_name_break_characters) == text_len)
506 fn_list = make_source_files_completion_list (text, text);
509 if (!fn_list.empty () && !tracker.have_completions ())
511 /* If we only have file names as possible completion, we should
512 bring them in sync with what rl_complete expects. The
513 problem is that if the user types "break /foo/b TAB", and the
514 possible completions are "/foo/bar" and "/foo/baz"
515 rl_complete expects us to return "bar" and "baz", without the
516 leading directories, as possible completions, because `word'
517 starts at the "b". But we ignore the value of `word' when we
518 call make_source_files_completion_list above (because that
519 would not DTRT when the completion results in both symbols
520 and file names), so make_source_files_completion_list returns
521 the full "/foo/bar" and "/foo/baz" strings. This produces
522 wrong results when, e.g., there's only one possible
523 completion, because rl_complete will prepend "/foo/" to each
524 candidate completion. The loop below removes that leading
526 for (const auto &fn_up: fn_list)
528 char *fn = fn_up.get ();
529 memmove (fn, fn + (word - text), strlen (fn) + 1 - (word - text));
533 tracker.add_completions (std::move (fn_list));
535 if (!tracker.have_completions ())
537 /* No completions at all. As the final resort, try completing
538 on the entire text as a symbol. */
539 collect_symbol_completion_matches (tracker,
540 complete_symbol_mode::EXPRESSION,
541 symbol_name_match_type::EXPRESSION,
546 /* See completer.h. */
549 complete_source_filenames (const char *text)
551 size_t text_len = strlen (text);
553 /* If text includes characters which cannot appear in a file name,
554 the user cannot be asking for completion on files. */
556 gdb_completer_file_name_break_characters)
558 return make_source_files_completion_list (text, text);
563 /* Complete address and linespec locations. */
566 complete_address_and_linespec_locations (completion_tracker &tracker,
568 symbol_name_match_type match_type)
572 tracker.advance_custom_word_point_by (1);
575 = advance_to_expression_complete_word_point (tracker, text);
576 complete_expression (tracker, text, word);
580 linespec_complete (tracker, text, match_type);
584 /* The explicit location options. Note that indexes into this array
585 must match the explicit_location_match_type enumerators. */
587 static const char *const explicit_options[] =
597 /* The probe modifier options. These can appear before a location in
598 breakpoint commands. */
599 static const char *const probe_options[] =
607 /* Returns STRING if not NULL, the empty string otherwise. */
610 string_or_empty (const char *string)
612 return string != NULL ? string : "";
615 /* A helper function to collect explicit location matches for the given
616 LOCATION, which is attempting to match on WORD. */
619 collect_explicit_location_matches (completion_tracker &tracker,
620 struct event_location *location,
621 enum explicit_location_match_type what,
623 const struct language_defn *language)
625 const struct explicit_location *explicit_loc
626 = get_explicit_location (location);
628 /* True if the option expects an argument. */
629 bool needs_arg = true;
631 /* Note, in the various MATCH_* below, we complete on
632 explicit_loc->foo instead of WORD, because only the former will
633 have already skipped past any quote char. */
638 const char *source = string_or_empty (explicit_loc->source_filename);
639 completion_list matches
640 = make_source_files_completion_list (source, source);
641 tracker.add_completions (std::move (matches));
647 const char *function = string_or_empty (explicit_loc->function_name);
648 linespec_complete_function (tracker, function,
649 explicit_loc->func_name_match_type,
650 explicit_loc->source_filename);
654 case MATCH_QUALIFIED:
658 /* Nothing to offer. */
663 const char *label = string_or_empty (explicit_loc->label_name);
664 linespec_complete_label (tracker, language,
665 explicit_loc->source_filename,
666 explicit_loc->function_name,
667 explicit_loc->func_name_match_type,
673 gdb_assert_not_reached ("unhandled explicit_location_match_type");
676 if (!needs_arg || tracker.completes_to_completion_word (word))
678 tracker.discard_completions ();
679 tracker.advance_custom_word_point_by (strlen (word));
680 complete_on_enum (tracker, explicit_options, "", "");
681 complete_on_enum (tracker, linespec_keywords, "", "");
683 else if (!tracker.have_completions ())
685 /* Maybe we have an unterminated linespec keyword at the tail of
686 the string. Try completing on that. */
687 size_t wordlen = strlen (word);
688 const char *keyword = word + wordlen;
690 if (wordlen > 0 && keyword[-1] != ' ')
692 while (keyword > word && *keyword != ' ')
694 /* Don't complete on keywords if we'd be completing on the
695 whole explicit linespec option. E.g., "b -function
696 thr<tab>" should not complete to the "thread"
700 keyword = skip_spaces (keyword);
702 tracker.advance_custom_word_point_by (keyword - word);
703 complete_on_enum (tracker, linespec_keywords, keyword, keyword);
706 else if (wordlen > 0 && keyword[-1] == ' ')
708 /* Assume that we're maybe past the explicit location
709 argument, and we didn't manage to find any match because
710 the user wants to create a pending breakpoint. Offer the
711 keyword and explicit location options as possible
713 tracker.advance_custom_word_point_by (keyword - word);
714 complete_on_enum (tracker, linespec_keywords, keyword, keyword);
715 complete_on_enum (tracker, explicit_options, keyword, keyword);
720 /* If the next word in *TEXT_P is any of the keywords in KEYWORDS,
721 then advance both TEXT_P and the word point in the tracker past the
722 keyword and return the (0-based) index in the KEYWORDS array that
723 matched. Otherwise, return -1. */
726 skip_keyword (completion_tracker &tracker,
727 const char * const *keywords, const char **text_p)
729 const char *text = *text_p;
730 const char *after = skip_to_space (text);
731 size_t len = after - text;
733 if (text[len] != ' ')
737 for (int i = 0; keywords[i] != NULL; i++)
739 if (strncmp (keywords[i], text, len) == 0)
750 tracker.advance_custom_word_point_by (len + 1);
759 /* A completer function for explicit locations. This function
760 completes both options ("-source", "-line", etc) and values. If
761 completing a quoted string, then QUOTED_ARG_START and
762 QUOTED_ARG_END point to the quote characters. LANGUAGE is the
766 complete_explicit_location (completion_tracker &tracker,
767 struct event_location *location,
769 const language_defn *language,
770 const char *quoted_arg_start,
771 const char *quoted_arg_end)
776 int keyword = skip_keyword (tracker, explicit_options, &text);
779 complete_on_enum (tracker, explicit_options, text, text);
782 /* Completing on value. */
783 enum explicit_location_match_type what
784 = (explicit_location_match_type) keyword;
786 if (quoted_arg_start != NULL && quoted_arg_end != NULL)
788 if (quoted_arg_end[1] == '\0')
790 /* If completing a quoted string with the cursor right
791 at the terminating quote char, complete the
792 completion word without interpretation, so that
793 readline advances the cursor one whitespace past the
794 quote, even if there's no match. This makes these
795 cases behave the same:
797 before: "b -function function()"
798 after: "b -function function() "
800 before: "b -function 'function()'"
801 after: "b -function 'function()' "
803 and trusts the user in this case:
805 before: "b -function 'not_loaded_function_yet()'"
806 after: "b -function 'not_loaded_function_yet()' "
808 tracker.add_completion (make_unique_xstrdup (text));
810 else if (quoted_arg_end[1] == ' ')
812 /* We're maybe past the explicit location argument.
813 Skip the argument without interpretion, assuming the
814 user may want to create pending breakpoint. Offer
815 the keyword and explicit location options as possible
817 tracker.advance_custom_word_point_by (strlen (text));
818 complete_on_enum (tracker, linespec_keywords, "", "");
819 complete_on_enum (tracker, explicit_options, "", "");
824 /* Now gather matches */
825 collect_explicit_location_matches (tracker, location, what, text,
830 /* A completer for locations. */
833 location_completer (struct cmd_list_element *ignore,
834 completion_tracker &tracker,
835 const char *text, const char * /* word */)
837 int found_probe_option = -1;
839 /* If we have a probe modifier, skip it. This can only appear as
840 first argument. Until we have a specific completer for probes,
841 falling back to the linespec completer for the remainder of the
842 line is better than nothing. */
843 if (text[0] == '-' && text[1] == 'p')
844 found_probe_option = skip_keyword (tracker, probe_options, &text);
846 const char *option_text = text;
847 int saved_word_point = tracker.custom_word_point ();
849 const char *copy = text;
851 explicit_completion_info completion_info;
852 event_location_up location
853 = string_to_explicit_location (©, current_language,
855 if (completion_info.quoted_arg_start != NULL
856 && completion_info.quoted_arg_end == NULL)
858 /* Found an unbalanced quote. */
859 tracker.set_quote_char (*completion_info.quoted_arg_start);
860 tracker.advance_custom_word_point_by (1);
863 if (completion_info.saw_explicit_location_option)
867 tracker.advance_custom_word_point_by (copy - text);
870 /* We found a terminator at the tail end of the string,
871 which means we're past the explicit location options. We
872 may have a keyword to complete on. If we have a whole
873 keyword, then complete whatever comes after as an
874 expression. This is mainly for the "if" keyword. If the
875 "thread" and "task" keywords gain their own completers,
876 they should be used here. */
877 int keyword = skip_keyword (tracker, linespec_keywords, &text);
881 complete_on_enum (tracker, linespec_keywords, text, text);
886 = advance_to_expression_complete_word_point (tracker, text);
887 complete_expression (tracker, text, word);
892 tracker.advance_custom_word_point_by (completion_info.last_option
894 text = completion_info.last_option;
896 complete_explicit_location (tracker, location.get (), text,
898 completion_info.quoted_arg_start,
899 completion_info.quoted_arg_end);
903 /* This is an address or linespec location. */
904 else if (location != NULL)
906 /* Handle non-explicit location options. */
908 int keyword = skip_keyword (tracker, explicit_options, &text);
910 complete_on_enum (tracker, explicit_options, text, text);
913 tracker.advance_custom_word_point_by (copy - text);
916 symbol_name_match_type match_type
917 = get_explicit_location (location.get ())->func_name_match_type;
918 complete_address_and_linespec_locations (tracker, text, match_type);
924 complete_address_and_linespec_locations (tracker, text,
925 symbol_name_match_type::WILD);
928 /* Add matches for option names, if either:
930 - Some completer above found some matches, but the word point did
931 not advance (e.g., "b <tab>" finds all functions, or "b -<tab>"
932 matches all objc selectors), or;
934 - Some completer above advanced the word point, but found no
937 if ((text[0] == '-' || text[0] == '\0')
938 && (!tracker.have_completions ()
939 || tracker.custom_word_point () == saved_word_point))
941 tracker.set_custom_word_point (saved_word_point);
944 if (found_probe_option == -1)
945 complete_on_enum (tracker, probe_options, text, text);
946 complete_on_enum (tracker, explicit_options, text, text);
950 /* The corresponding completer_handle_brkchars
954 location_completer_handle_brkchars (struct cmd_list_element *ignore,
955 completion_tracker &tracker,
957 const char *word_ignored)
959 tracker.set_use_custom_word_point (true);
961 location_completer (ignore, tracker, text, NULL);
964 /* Helper for expression_completer which recursively adds field and
965 method names from TYPE, a struct or union type, to the OUTPUT
969 add_struct_fields (struct type *type, completion_list &output,
970 const char *fieldname, int namelen)
973 int computed_type_name = 0;
974 const char *type_name = NULL;
976 type = check_typedef (type);
977 for (i = 0; i < TYPE_NFIELDS (type); ++i)
979 if (i < TYPE_N_BASECLASSES (type))
980 add_struct_fields (TYPE_BASECLASS (type, i),
981 output, fieldname, namelen);
982 else if (TYPE_FIELD_NAME (type, i))
984 if (TYPE_FIELD_NAME (type, i)[0] != '\0')
986 if (! strncmp (TYPE_FIELD_NAME (type, i),
988 output.emplace_back (xstrdup (TYPE_FIELD_NAME (type, i)));
990 else if (TYPE_CODE (TYPE_FIELD_TYPE (type, i)) == TYPE_CODE_UNION)
992 /* Recurse into anonymous unions. */
993 add_struct_fields (TYPE_FIELD_TYPE (type, i),
994 output, fieldname, namelen);
999 for (i = TYPE_NFN_FIELDS (type) - 1; i >= 0; --i)
1001 const char *name = TYPE_FN_FIELDLIST_NAME (type, i);
1003 if (name && ! strncmp (name, fieldname, namelen))
1005 if (!computed_type_name)
1007 type_name = TYPE_NAME (type);
1008 computed_type_name = 1;
1010 /* Omit constructors from the completion list. */
1011 if (!type_name || strcmp (type_name, name))
1012 output.emplace_back (xstrdup (name));
1017 /* See completer.h. */
1020 complete_expression (completion_tracker &tracker,
1021 const char *text, const char *word)
1023 struct type *type = NULL;
1024 gdb::unique_xmalloc_ptr<char> fieldname;
1025 enum type_code code = TYPE_CODE_UNDEF;
1027 /* Perform a tentative parse of the expression, to see whether a
1028 field completion is required. */
1031 type = parse_expression_for_completion (text, &fieldname, &code);
1033 catch (const gdb_exception_error &except)
1038 if (fieldname != nullptr && type)
1042 type = check_typedef (type);
1043 if (TYPE_CODE (type) != TYPE_CODE_PTR && !TYPE_IS_REFERENCE (type))
1045 type = TYPE_TARGET_TYPE (type);
1048 if (TYPE_CODE (type) == TYPE_CODE_UNION
1049 || TYPE_CODE (type) == TYPE_CODE_STRUCT)
1051 completion_list result;
1053 add_struct_fields (type, result, fieldname.get (),
1054 strlen (fieldname.get ()));
1055 tracker.add_completions (std::move (result));
1059 else if (fieldname != nullptr && code != TYPE_CODE_UNDEF)
1061 collect_symbol_completion_matches_type (tracker, fieldname.get (),
1062 fieldname.get (), code);
1066 complete_files_symbols (tracker, text, word);
1069 /* Complete on expressions. Often this means completing on symbol
1070 names, but some language parsers also have support for completing
1074 expression_completer (struct cmd_list_element *ignore,
1075 completion_tracker &tracker,
1076 const char *text, const char *word)
1078 complete_expression (tracker, text, word);
1081 /* See definition in completer.h. */
1084 set_rl_completer_word_break_characters (const char *break_chars)
1086 rl_completer_word_break_characters = (char *) break_chars;
1089 /* See definition in completer.h. */
1092 set_gdb_completion_word_break_characters (completer_ftype *fn)
1094 const char *break_chars;
1096 /* So far we are only interested in differentiating filename
1097 completers from everything else. */
1098 if (fn == filename_completer)
1099 break_chars = gdb_completer_file_name_break_characters;
1101 break_chars = gdb_completer_command_word_break_characters;
1103 set_rl_completer_word_break_characters (break_chars);
1106 /* Complete on symbols. */
1109 symbol_completer (struct cmd_list_element *ignore,
1110 completion_tracker &tracker,
1111 const char *text, const char *word)
1113 collect_symbol_completion_matches (tracker, complete_symbol_mode::EXPRESSION,
1114 symbol_name_match_type::EXPRESSION,
1118 /* Here are some useful test cases for completion. FIXME: These
1119 should be put in the test suite. They should be tested with both
1122 "show output-" "radix"
1123 "show output" "-radix"
1124 "p" ambiguous (commands starting with p--path, print, printf, etc.)
1125 "p " ambiguous (all symbols)
1126 "info t foo" no completions
1127 "info t " no completions
1128 "info t" ambiguous ("info target", "info terminal", etc.)
1129 "info ajksdlfk" no completions
1130 "info ajksdlfk " no completions
1132 "info " ambiguous (all info commands)
1133 "p \"a" no completions (string constant)
1134 "p 'a" ambiguous (all symbols starting with a)
1135 "p b-a" ambiguous (all symbols starting with a)
1136 "p b-" ambiguous (all symbols)
1137 "file Make" "file" (word break hard to screw up here)
1138 "file ../gdb.stabs/we" "ird" (needs to not break word at slash)
1141 enum complete_line_internal_reason
1143 /* Preliminary phase, called by gdb_completion_word_break_characters
1144 function, is used to either:
1146 #1 - Determine the set of chars that are word delimiters
1147 depending on the current command in line_buffer.
1149 #2 - Manually advance RL_POINT to the "word break" point instead
1150 of letting readline do it (based on too-simple character
1153 Simpler completers that just pass a brkchars array to readline
1154 (#1 above) must defer generating the completions to the main
1155 phase (below). No completion list should be generated in this
1158 OTOH, completers that manually advance the word point(#2 above)
1159 must set "use_custom_word_point" in the tracker and generate
1160 their completion in this phase. Note that this is the convenient
1161 thing to do since they'll be parsing the input line anyway. */
1164 /* Main phase, called by complete_line function, is used to get the
1165 list of possible completions. */
1168 /* Special case when completing a 'help' command. In this case,
1169 once sub-command completions are exhausted, we simply return
1174 /* Helper for complete_line_internal to simplify it. */
1177 complete_line_internal_normal_command (completion_tracker &tracker,
1178 const char *command, const char *word,
1179 const char *cmd_args,
1180 complete_line_internal_reason reason,
1181 struct cmd_list_element *c)
1183 const char *p = cmd_args;
1185 if (c->completer == filename_completer)
1187 /* Many commands which want to complete on file names accept
1188 several file names, as in "run foo bar >>baz". So we don't
1189 want to complete the entire text after the command, just the
1190 last word. To this end, we need to find the beginning of the
1191 file name by starting at `word' and going backwards. */
1194 && strchr (gdb_completer_file_name_break_characters,
1200 if (reason == handle_brkchars)
1202 completer_handle_brkchars_ftype *brkchars_fn;
1204 if (c->completer_handle_brkchars != NULL)
1205 brkchars_fn = c->completer_handle_brkchars;
1209 = (completer_handle_brkchars_func_for_completer
1213 brkchars_fn (c, tracker, p, word);
1216 if (reason != handle_brkchars && c->completer != NULL)
1217 (*c->completer) (c, tracker, p, word);
1220 /* Internal function used to handle completions.
1223 TEXT is the caller's idea of the "word" we are looking at.
1225 LINE_BUFFER is available to be looked at; it contains the entire
1226 text of the line. POINT is the offset in that line of the cursor.
1227 You should pretend that the line ends at POINT.
1229 See complete_line_internal_reason for description of REASON. */
1232 complete_line_internal_1 (completion_tracker &tracker,
1234 const char *line_buffer, int point,
1235 complete_line_internal_reason reason)
1239 int ignore_help_classes;
1240 /* Pointer within tmp_command which corresponds to text. */
1242 struct cmd_list_element *c, *result_list;
1244 /* Choose the default set of word break characters to break
1245 completions. If we later find out that we are doing completions
1246 on command strings (as opposed to strings supplied by the
1247 individual command completer functions, which can be any string)
1248 then we will switch to the special word break set for command
1249 strings, which leaves out the '-' character used in some
1251 set_rl_completer_word_break_characters
1252 (current_language->la_word_break_characters());
1254 /* Decide whether to complete on a list of gdb commands or on
1256 tmp_command = (char *) alloca (point + 1);
1259 /* The help command should complete help aliases. */
1260 ignore_help_classes = reason != handle_help;
1262 strncpy (tmp_command, line_buffer, point);
1263 tmp_command[point] = '\0';
1264 if (reason == handle_brkchars)
1266 gdb_assert (text == NULL);
1271 /* Since text always contains some number of characters leading up
1272 to point, we can find the equivalent position in tmp_command
1273 by subtracting that many characters from the end of tmp_command. */
1274 word = tmp_command + point - strlen (text);
1277 /* Move P up to the start of the command. */
1278 p = skip_spaces (p);
1282 /* An empty line is ambiguous; that is, it could be any
1284 c = CMD_LIST_AMBIGUOUS;
1289 c = lookup_cmd_1 (&p, cmdlist, &result_list, ignore_help_classes);
1292 /* Move p up to the next interesting thing. */
1293 while (*p == ' ' || *p == '\t')
1298 tracker.advance_custom_word_point_by (p - tmp_command);
1302 /* It is an unrecognized command. So there are no
1303 possible completions. */
1305 else if (c == CMD_LIST_AMBIGUOUS)
1309 /* lookup_cmd_1 advances p up to the first ambiguous thing, but
1310 doesn't advance over that thing itself. Do so now. */
1312 while (*q && (isalnum (*q) || *q == '-' || *q == '_'))
1314 if (q != tmp_command + point)
1316 /* There is something beyond the ambiguous
1317 command, so there are no possible completions. For
1318 example, "info t " or "info t foo" does not complete
1319 to anything, because "info t" can be "info target" or
1324 /* We're trying to complete on the command which was ambiguous.
1325 This we can deal with. */
1328 if (reason != handle_brkchars)
1329 complete_on_cmdlist (*result_list->prefixlist, tracker, p,
1330 word, ignore_help_classes);
1334 if (reason != handle_brkchars)
1335 complete_on_cmdlist (cmdlist, tracker, p, word,
1336 ignore_help_classes);
1338 /* Ensure that readline does the right thing with respect to
1339 inserting quotes. */
1340 set_rl_completer_word_break_characters
1341 (gdb_completer_command_word_break_characters);
1346 /* We've recognized a full command. */
1348 if (p == tmp_command + point)
1350 /* There is no non-whitespace in the line beyond the
1353 if (p[-1] == ' ' || p[-1] == '\t')
1355 /* The command is followed by whitespace; we need to
1356 complete on whatever comes after command. */
1359 /* It is a prefix command; what comes after it is
1360 a subcommand (e.g. "info "). */
1361 if (reason != handle_brkchars)
1362 complete_on_cmdlist (*c->prefixlist, tracker, p, word,
1363 ignore_help_classes);
1365 /* Ensure that readline does the right thing
1366 with respect to inserting quotes. */
1367 set_rl_completer_word_break_characters
1368 (gdb_completer_command_word_break_characters);
1370 else if (reason == handle_help)
1374 if (reason != handle_brkchars)
1375 complete_on_enum (tracker, c->enums, p, word);
1376 set_rl_completer_word_break_characters
1377 (gdb_completer_command_word_break_characters);
1381 /* It is a normal command; what comes after it is
1382 completed by the command's completer function. */
1383 complete_line_internal_normal_command (tracker,
1384 tmp_command, word, p,
1390 /* The command is not followed by whitespace; we need to
1391 complete on the command itself, e.g. "p" which is a
1392 command itself but also can complete to "print", "ptype"
1396 /* Find the command we are completing on. */
1398 while (q > tmp_command)
1400 if (isalnum (q[-1]) || q[-1] == '-' || q[-1] == '_')
1406 /* Move the custom word point back too. */
1407 tracker.advance_custom_word_point_by (q - p);
1409 if (reason != handle_brkchars)
1410 complete_on_cmdlist (result_list, tracker, q, word,
1411 ignore_help_classes);
1413 /* Ensure that readline does the right thing
1414 with respect to inserting quotes. */
1415 set_rl_completer_word_break_characters
1416 (gdb_completer_command_word_break_characters);
1419 else if (reason == handle_help)
1423 /* There is non-whitespace beyond the command. */
1425 if (c->prefixlist && !c->allow_unknown)
1427 /* It is an unrecognized subcommand of a prefix command,
1428 e.g. "info adsfkdj". */
1432 if (reason != handle_brkchars)
1433 complete_on_enum (tracker, c->enums, p, word);
1437 /* It is a normal command. */
1438 complete_line_internal_normal_command (tracker,
1439 tmp_command, word, p,
1446 /* Wrapper around complete_line_internal_1 to handle
1447 MAX_COMPLETIONS_REACHED_ERROR. */
1450 complete_line_internal (completion_tracker &tracker,
1452 const char *line_buffer, int point,
1453 complete_line_internal_reason reason)
1457 complete_line_internal_1 (tracker, text, line_buffer, point, reason);
1459 catch (const gdb_exception_error &except)
1461 if (except.error != MAX_COMPLETIONS_REACHED_ERROR)
1466 /* See completer.h. */
1468 int max_completions = 200;
1470 /* Initial size of the table. It automagically grows from here. */
1471 #define INITIAL_COMPLETION_HTAB_SIZE 200
1473 /* See completer.h. */
1475 completion_tracker::completion_tracker ()
1477 m_entries_hash = htab_create_alloc (INITIAL_COMPLETION_HTAB_SIZE,
1478 htab_hash_string, streq_hash,
1479 NULL, xcalloc, xfree);
1482 /* See completer.h. */
1485 completion_tracker::discard_completions ()
1487 xfree (m_lowest_common_denominator);
1488 m_lowest_common_denominator = NULL;
1490 m_lowest_common_denominator_unique = false;
1492 m_entries_vec.clear ();
1494 htab_delete (m_entries_hash);
1495 m_entries_hash = htab_create_alloc (INITIAL_COMPLETION_HTAB_SIZE,
1496 htab_hash_string, streq_hash,
1497 NULL, xcalloc, xfree);
1500 /* See completer.h. */
1502 completion_tracker::~completion_tracker ()
1504 xfree (m_lowest_common_denominator);
1505 htab_delete (m_entries_hash);
1508 /* See completer.h. */
1511 completion_tracker::maybe_add_completion
1512 (gdb::unique_xmalloc_ptr<char> name,
1513 completion_match_for_lcd *match_for_lcd,
1514 const char *text, const char *word)
1518 if (max_completions == 0)
1521 if (htab_elements (m_entries_hash) >= max_completions)
1524 slot = htab_find_slot (m_entries_hash, name.get (), INSERT);
1525 if (*slot == HTAB_EMPTY_ENTRY)
1527 const char *match_for_lcd_str = NULL;
1529 if (match_for_lcd != NULL)
1530 match_for_lcd_str = match_for_lcd->finish ();
1532 if (match_for_lcd_str == NULL)
1533 match_for_lcd_str = name.get ();
1535 gdb::unique_xmalloc_ptr<char> lcd
1536 = make_completion_match_str (match_for_lcd_str, text, word);
1538 recompute_lowest_common_denominator (std::move (lcd));
1540 *slot = name.get ();
1541 m_entries_vec.push_back (std::move (name));
1547 /* See completer.h. */
1550 completion_tracker::add_completion (gdb::unique_xmalloc_ptr<char> name,
1551 completion_match_for_lcd *match_for_lcd,
1552 const char *text, const char *word)
1554 if (!maybe_add_completion (std::move (name), match_for_lcd, text, word))
1555 throw_error (MAX_COMPLETIONS_REACHED_ERROR, _("Max completions reached."));
1558 /* See completer.h. */
1561 completion_tracker::add_completions (completion_list &&list)
1563 for (auto &candidate : list)
1564 add_completion (std::move (candidate));
1567 /* Helper for the make_completion_match_str overloads. Returns NULL
1568 as an indication that we want MATCH_NAME exactly. It is up to the
1569 caller to xstrdup that string if desired. */
1572 make_completion_match_str_1 (const char *match_name,
1573 const char *text, const char *word)
1579 /* Return NULL as an indication that we want MATCH_NAME
1583 else if (word > text)
1585 /* Return some portion of MATCH_NAME. */
1586 newobj = xstrdup (match_name + (word - text));
1590 /* Return some of WORD plus MATCH_NAME. */
1591 size_t len = strlen (match_name);
1592 newobj = (char *) xmalloc (text - word + len + 1);
1593 memcpy (newobj, word, text - word);
1594 memcpy (newobj + (text - word), match_name, len + 1);
1600 /* See completer.h. */
1602 gdb::unique_xmalloc_ptr<char>
1603 make_completion_match_str (const char *match_name,
1604 const char *text, const char *word)
1606 char *newobj = make_completion_match_str_1 (match_name, text, word);
1608 newobj = xstrdup (match_name);
1609 return gdb::unique_xmalloc_ptr<char> (newobj);
1612 /* See completer.h. */
1614 gdb::unique_xmalloc_ptr<char>
1615 make_completion_match_str (gdb::unique_xmalloc_ptr<char> &&match_name,
1616 const char *text, const char *word)
1618 char *newobj = make_completion_match_str_1 (match_name.get (), text, word);
1620 return std::move (match_name);
1621 return gdb::unique_xmalloc_ptr<char> (newobj);
1624 /* See complete.h. */
1627 complete (const char *line, char const **word, int *quote_char)
1629 completion_tracker tracker_handle_brkchars;
1630 completion_tracker tracker_handle_completions;
1631 completion_tracker *tracker;
1633 /* The WORD should be set to the end of word to complete. We initialize
1634 to the completion point which is assumed to be at the end of LINE.
1635 This leaves WORD to be initialized to a sensible value in cases
1636 completion_find_completion_word() fails i.e., throws an exception.
1638 *word = line + strlen (line);
1642 *word = completion_find_completion_word (tracker_handle_brkchars,
1645 /* Completers that provide a custom word point in the
1646 handle_brkchars phase also compute their completions then.
1647 Completers that leave the completion word handling to readline
1648 must be called twice. */
1649 if (tracker_handle_brkchars.use_custom_word_point ())
1650 tracker = &tracker_handle_brkchars;
1653 complete_line (tracker_handle_completions, *word, line, strlen (line));
1654 tracker = &tracker_handle_completions;
1657 catch (const gdb_exception &ex)
1662 return tracker->build_completion_result (*word, *word - line, strlen (line));
1666 /* Generate completions all at once. Does nothing if max_completions
1667 is 0. If max_completions is non-negative, this will collect at
1668 most max_completions strings.
1670 TEXT is the caller's idea of the "word" we are looking at.
1672 LINE_BUFFER is available to be looked at; it contains the entire
1675 POINT is the offset in that line of the cursor. You
1676 should pretend that the line ends at POINT. */
1679 complete_line (completion_tracker &tracker,
1680 const char *text, const char *line_buffer, int point)
1682 if (max_completions == 0)
1684 complete_line_internal (tracker, text, line_buffer, point,
1685 handle_completions);
1688 /* Complete on command names. Used by "help". */
1691 command_completer (struct cmd_list_element *ignore,
1692 completion_tracker &tracker,
1693 const char *text, const char *word)
1695 complete_line_internal (tracker, word, text,
1696 strlen (text), handle_help);
1699 /* The corresponding completer_handle_brkchars implementation. */
1702 command_completer_handle_brkchars (struct cmd_list_element *ignore,
1703 completion_tracker &tracker,
1704 const char *text, const char *word)
1706 set_rl_completer_word_break_characters
1707 (gdb_completer_command_word_break_characters);
1710 /* Complete on signals. */
1713 signal_completer (struct cmd_list_element *ignore,
1714 completion_tracker &tracker,
1715 const char *text, const char *word)
1717 size_t len = strlen (word);
1719 const char *signame;
1721 for (signum = GDB_SIGNAL_FIRST; signum != GDB_SIGNAL_LAST; ++signum)
1723 /* Can't handle this, so skip it. */
1724 if (signum == GDB_SIGNAL_0)
1727 signame = gdb_signal_to_name ((enum gdb_signal) signum);
1729 /* Ignore the unknown signal case. */
1730 if (!signame || strcmp (signame, "?") == 0)
1733 if (strncasecmp (signame, word, len) == 0)
1734 tracker.add_completion (make_unique_xstrdup (signame));
1738 /* Bit-flags for selecting what the register and/or register-group
1739 completer should complete on. */
1741 enum reg_completer_target
1743 complete_register_names = 0x1,
1744 complete_reggroup_names = 0x2
1746 DEF_ENUM_FLAGS_TYPE (enum reg_completer_target, reg_completer_targets);
1748 /* Complete register names and/or reggroup names based on the value passed
1749 in TARGETS. At least one bit in TARGETS must be set. */
1752 reg_or_group_completer_1 (completion_tracker &tracker,
1753 const char *text, const char *word,
1754 reg_completer_targets targets)
1756 size_t len = strlen (word);
1757 struct gdbarch *gdbarch;
1760 gdb_assert ((targets & (complete_register_names
1761 | complete_reggroup_names)) != 0);
1762 gdbarch = get_current_arch ();
1764 if ((targets & complete_register_names) != 0)
1769 (name = user_reg_map_regnum_to_name (gdbarch, i)) != NULL;
1772 if (*name != '\0' && strncmp (word, name, len) == 0)
1773 tracker.add_completion (make_unique_xstrdup (name));
1777 if ((targets & complete_reggroup_names) != 0)
1779 struct reggroup *group;
1781 for (group = reggroup_next (gdbarch, NULL);
1783 group = reggroup_next (gdbarch, group))
1785 name = reggroup_name (group);
1786 if (strncmp (word, name, len) == 0)
1787 tracker.add_completion (make_unique_xstrdup (name));
1792 /* Perform completion on register and reggroup names. */
1795 reg_or_group_completer (struct cmd_list_element *ignore,
1796 completion_tracker &tracker,
1797 const char *text, const char *word)
1799 reg_or_group_completer_1 (tracker, text, word,
1800 (complete_register_names
1801 | complete_reggroup_names));
1804 /* Perform completion on reggroup names. */
1807 reggroup_completer (struct cmd_list_element *ignore,
1808 completion_tracker &tracker,
1809 const char *text, const char *word)
1811 reg_or_group_completer_1 (tracker, text, word,
1812 complete_reggroup_names);
1815 /* The default completer_handle_brkchars implementation. */
1818 default_completer_handle_brkchars (struct cmd_list_element *ignore,
1819 completion_tracker &tracker,
1820 const char *text, const char *word)
1822 set_rl_completer_word_break_characters
1823 (current_language->la_word_break_characters ());
1826 /* See definition in completer.h. */
1828 completer_handle_brkchars_ftype *
1829 completer_handle_brkchars_func_for_completer (completer_ftype *fn)
1831 if (fn == filename_completer)
1832 return filename_completer_handle_brkchars;
1834 if (fn == location_completer)
1835 return location_completer_handle_brkchars;
1837 if (fn == command_completer)
1838 return command_completer_handle_brkchars;
1840 return default_completer_handle_brkchars;
1843 /* Used as brkchars when we want to tell readline we have a custom
1844 word point. We do that by making our rl_completion_word_break_hook
1845 set RL_POINT to the desired word point, and return the character at
1846 the word break point as the break char. This is two bytes in order
1847 to fit one break character plus the terminating null. */
1848 static char gdb_custom_word_point_brkchars[2];
1850 /* Since rl_basic_quote_characters is not completer-specific, we save
1851 its original value here, in order to be able to restore it in
1852 gdb_rl_attempted_completion_function. */
1853 static const char *gdb_org_rl_basic_quote_characters = rl_basic_quote_characters;
1855 /* Get the list of chars that are considered as word breaks
1856 for the current command. */
1859 gdb_completion_word_break_characters_throw ()
1861 /* New completion starting. Get rid of the previous tracker and
1863 delete current_completion.tracker;
1864 current_completion.tracker = new completion_tracker ();
1866 completion_tracker &tracker = *current_completion.tracker;
1868 complete_line_internal (tracker, NULL, rl_line_buffer,
1869 rl_point, handle_brkchars);
1871 if (tracker.use_custom_word_point ())
1873 gdb_assert (tracker.custom_word_point () > 0);
1874 rl_point = tracker.custom_word_point () - 1;
1875 gdb_custom_word_point_brkchars[0] = rl_line_buffer[rl_point];
1876 rl_completer_word_break_characters = gdb_custom_word_point_brkchars;
1877 rl_completer_quote_characters = NULL;
1879 /* Clear this too, so that if we're completing a quoted string,
1880 readline doesn't consider the quote character a delimiter.
1881 If we didn't do this, readline would auto-complete {b
1882 'fun<tab>} to {'b 'function()'}, i.e., add the terminating
1883 \', but, it wouldn't append the separator space either, which
1884 is not desirable. So instead we take care of appending the
1885 quote character to the LCD ourselves, in
1886 gdb_rl_attempted_completion_function. Since this global is
1887 not just completer-specific, we'll restore it back to the
1888 default in gdb_rl_attempted_completion_function. */
1889 rl_basic_quote_characters = NULL;
1892 return rl_completer_word_break_characters;
1896 gdb_completion_word_break_characters ()
1898 /* New completion starting. */
1899 current_completion.aborted = false;
1903 return gdb_completion_word_break_characters_throw ();
1905 catch (const gdb_exception &ex)
1907 /* Set this to that gdb_rl_attempted_completion_function knows
1909 current_completion.aborted = true;
1915 /* See completer.h. */
1918 completion_find_completion_word (completion_tracker &tracker, const char *text,
1921 size_t point = strlen (text);
1923 complete_line_internal (tracker, NULL, text, point, handle_brkchars);
1925 if (tracker.use_custom_word_point ())
1927 gdb_assert (tracker.custom_word_point () > 0);
1928 *quote_char = tracker.quote_char ();
1929 return text + tracker.custom_word_point ();
1932 gdb_rl_completion_word_info info;
1934 info.word_break_characters = rl_completer_word_break_characters;
1935 info.quote_characters = gdb_completer_quote_characters;
1936 info.basic_quote_characters = rl_basic_quote_characters;
1938 return gdb_rl_find_completion_word (&info, quote_char, NULL, text);
1941 /* See completer.h. */
1944 completion_tracker::recompute_lowest_common_denominator
1945 (gdb::unique_xmalloc_ptr<char> &&new_match_up)
1947 if (m_lowest_common_denominator == NULL)
1949 /* We don't have a lowest common denominator yet, so simply take
1950 the whole NEW_MATCH_UP as being it. */
1951 m_lowest_common_denominator = new_match_up.release ();
1952 m_lowest_common_denominator_unique = true;
1956 /* Find the common denominator between the currently-known
1957 lowest common denominator and NEW_MATCH_UP. That becomes the
1958 new lowest common denominator. */
1960 const char *new_match = new_match_up.get ();
1963 (new_match[i] != '\0'
1964 && new_match[i] == m_lowest_common_denominator[i]);
1967 if (m_lowest_common_denominator[i] != new_match[i])
1969 m_lowest_common_denominator[i] = '\0';
1970 m_lowest_common_denominator_unique = false;
1975 /* See completer.h. */
1978 completion_tracker::advance_custom_word_point_by (int len)
1980 m_custom_word_point += len;
1983 /* Build a new C string that is a copy of LCD with the whitespace of
1984 ORIG/ORIG_LEN preserved.
1986 Say the user is completing a symbol name, with spaces, like:
1990 and the resulting completion match is:
1994 we want to end up with an input line like:
1997 ^^^^^^^ => text from LCD [1], whitespace from ORIG preserved.
1998 ^^ => new text from LCD
2000 [1] - We must take characters from the LCD instead of the original
2001 text, since some completions want to change upper/lowercase. E.g.:
2007 "handle SIG[QUIT|etc.]"
2011 expand_preserving_ws (const char *orig, size_t orig_len,
2014 const char *p_orig = orig;
2015 const char *orig_end = orig + orig_len;
2016 const char *p_lcd = lcd;
2019 while (p_orig < orig_end)
2023 while (p_orig < orig_end && *p_orig == ' ')
2025 p_lcd = skip_spaces (p_lcd);
2029 /* Take characters from the LCD instead of the original
2030 text, since some completions change upper/lowercase.
2034 "handle SIG[QUIT|etc.]"
2042 while (*p_lcd != '\0')
2045 return xstrdup (res.c_str ());
2048 /* See completer.h. */
2051 completion_tracker::build_completion_result (const char *text,
2054 completion_list &list = m_entries_vec; /* The completions. */
2059 /* +1 for the LCD, and +1 for NULL termination. */
2060 char **match_list = XNEWVEC (char *, 1 + list.size () + 1);
2062 /* Build replacement word, based on the LCD. */
2065 = expand_preserving_ws (text, end - start,
2066 m_lowest_common_denominator);
2068 if (m_lowest_common_denominator_unique)
2070 /* We don't rely on readline appending the quote char as
2071 delimiter as then readline wouldn't append the ' ' after the
2073 char buf[2] = { (char) quote_char () };
2075 match_list[0] = reconcat (match_list[0], match_list[0],
2076 buf, (char *) NULL);
2077 match_list[1] = NULL;
2079 /* If the tracker wants to, or we already have a space at the
2080 end of the match, tell readline to skip appending
2082 bool completion_suppress_append
2083 = (suppress_append_ws ()
2084 || match_list[0][strlen (match_list[0]) - 1] == ' ');
2086 return completion_result (match_list, 1, completion_suppress_append);
2092 for (ix = 0; ix < list.size (); ++ix)
2093 match_list[ix + 1] = list[ix].release ();
2094 match_list[ix + 1] = NULL;
2096 return completion_result (match_list, list.size (), false);
2100 /* See completer.h */
2102 completion_result::completion_result ()
2103 : match_list (NULL), number_matches (0),
2104 completion_suppress_append (false)
2107 /* See completer.h */
2109 completion_result::completion_result (char **match_list_,
2110 size_t number_matches_,
2111 bool completion_suppress_append_)
2112 : match_list (match_list_),
2113 number_matches (number_matches_),
2114 completion_suppress_append (completion_suppress_append_)
2117 /* See completer.h */
2119 completion_result::~completion_result ()
2121 reset_match_list ();
2124 /* See completer.h */
2126 completion_result::completion_result (completion_result &&rhs)
2131 reset_match_list ();
2132 match_list = rhs.match_list;
2133 rhs.match_list = NULL;
2134 number_matches = rhs.number_matches;
2135 rhs.number_matches = 0;
2138 /* See completer.h */
2141 completion_result::release_match_list ()
2143 char **ret = match_list;
2148 /* See completer.h */
2151 completion_result::sort_match_list ()
2153 if (number_matches > 1)
2155 /* Element 0 is special (it's the common prefix), leave it
2157 std::sort (&match_list[1],
2158 &match_list[number_matches + 1],
2163 /* See completer.h */
2166 completion_result::reset_match_list ()
2168 if (match_list != NULL)
2170 for (char **p = match_list; *p != NULL; p++)
2177 /* Helper for gdb_rl_attempted_completion_function, which does most of
2178 the work. This is called by readline to build the match list array
2179 and to determine the lowest common denominator. The real matches
2180 list starts at match[1], while match[0] is the slot holding
2181 readline's idea of the lowest common denominator of all matches,
2182 which is what readline replaces the completion "word" with.
2184 TEXT is the caller's idea of the "word" we are looking at, as
2185 computed in the handle_brkchars phase.
2187 START is the offset from RL_LINE_BUFFER where TEXT starts. END is
2188 the offset from RL_LINE_BUFFER where TEXT ends (i.e., where
2191 You should thus pretend that the line ends at END (relative to
2194 RL_LINE_BUFFER contains the entire text of the line. RL_POINT is
2195 the offset in that line of the cursor. You should pretend that the
2198 Returns NULL if there are no completions. */
2201 gdb_rl_attempted_completion_function_throw (const char *text, int start, int end)
2203 /* Completers that provide a custom word point in the
2204 handle_brkchars phase also compute their completions then.
2205 Completers that leave the completion word handling to readline
2206 must be called twice. If rl_point (i.e., END) is at column 0,
2207 then readline skips the handle_brkchars phase, and so we create a
2208 tracker now in that case too. */
2209 if (end == 0 || !current_completion.tracker->use_custom_word_point ())
2211 delete current_completion.tracker;
2212 current_completion.tracker = new completion_tracker ();
2214 complete_line (*current_completion.tracker, text,
2215 rl_line_buffer, rl_point);
2218 completion_tracker &tracker = *current_completion.tracker;
2220 completion_result result
2221 = tracker.build_completion_result (text, start, end);
2223 rl_completion_suppress_append = result.completion_suppress_append;
2224 return result.release_match_list ();
2227 /* Function installed as "rl_attempted_completion_function" readline
2228 hook. Wrapper around gdb_rl_attempted_completion_function_throw
2229 that catches C++ exceptions, which can't cross readline. */
2232 gdb_rl_attempted_completion_function (const char *text, int start, int end)
2234 /* Restore globals that might have been tweaked in
2235 gdb_completion_word_break_characters. */
2236 rl_basic_quote_characters = gdb_org_rl_basic_quote_characters;
2238 /* If we end up returning NULL, either on error, or simple because
2239 there are no matches, inhibit readline's default filename
2241 rl_attempted_completion_over = 1;
2243 /* If the handle_brkchars phase was aborted, don't try
2245 if (current_completion.aborted)
2250 return gdb_rl_attempted_completion_function_throw (text, start, end);
2252 catch (const gdb_exception &ex)
2259 /* Skip over the possibly quoted word STR (as defined by the quote
2260 characters QUOTECHARS and the word break characters BREAKCHARS).
2261 Returns pointer to the location after the "word". If either
2262 QUOTECHARS or BREAKCHARS is NULL, use the same values used by the
2266 skip_quoted_chars (const char *str, const char *quotechars,
2267 const char *breakchars)
2269 char quote_char = '\0';
2272 if (quotechars == NULL)
2273 quotechars = gdb_completer_quote_characters;
2275 if (breakchars == NULL)
2276 breakchars = current_language->la_word_break_characters();
2278 for (scan = str; *scan != '\0'; scan++)
2280 if (quote_char != '\0')
2282 /* Ignore everything until the matching close quote char. */
2283 if (*scan == quote_char)
2285 /* Found matching close quote. */
2290 else if (strchr (quotechars, *scan))
2292 /* Found start of a quoted string. */
2295 else if (strchr (breakchars, *scan))
2304 /* Skip over the possibly quoted word STR (as defined by the quote
2305 characters and word break characters used by the completer).
2306 Returns pointer to the location after the "word". */
2309 skip_quoted (const char *str)
2311 return skip_quoted_chars (str, NULL, NULL);
2314 /* Return a message indicating that the maximum number of completions
2315 has been reached and that there may be more. */
2318 get_max_completions_reached_message (void)
2320 return _("*** List may be truncated, max-completions reached. ***");
2323 /* GDB replacement for rl_display_match_list.
2324 Readline doesn't provide a clean interface for TUI(curses).
2325 A hack previously used was to send readline's rl_outstream through a pipe
2326 and read it from the event loop. Bleah. IWBN if readline abstracted
2327 away all the necessary bits, and this is what this code does. It
2328 replicates the parts of readline we need and then adds an abstraction
2329 layer, currently implemented as struct match_list_displayer, so that both
2330 CLI and TUI can use it. We copy all this readline code to minimize
2331 GDB-specific mods to readline. Once this code performs as desired then
2332 we can submit it to the readline maintainers.
2334 N.B. A lot of the code is the way it is in order to minimize differences
2335 from readline's copy. */
2337 /* Not supported here. */
2338 #undef VISIBLE_STATS
2340 #if defined (HANDLE_MULTIBYTE)
2341 #define MB_INVALIDCH(x) ((x) == (size_t)-1 || (x) == (size_t)-2)
2342 #define MB_NULLWCH(x) ((x) == 0)
2345 #define ELLIPSIS_LEN 3
2347 /* gdb version of readline/complete.c:get_y_or_n.
2348 'y' -> returns 1, and 'n' -> returns 0.
2349 Also supported: space == 'y', RUBOUT == 'n', ctrl-g == start over.
2350 If FOR_PAGER is non-zero, then also supported are:
2351 NEWLINE or RETURN -> returns 2, and 'q' -> returns 0. */
2354 gdb_get_y_or_n (int for_pager, const struct match_list_displayer *displayer)
2360 RL_SETSTATE (RL_STATE_MOREINPUT);
2361 c = displayer->read_key (displayer);
2362 RL_UNSETSTATE (RL_STATE_MOREINPUT);
2364 if (c == 'y' || c == 'Y' || c == ' ')
2366 if (c == 'n' || c == 'N' || c == RUBOUT)
2368 if (c == ABORT_CHAR || c < 0)
2370 /* Readline doesn't erase_entire_line here, but without it the
2371 --More-- prompt isn't erased and neither is the text entered
2372 thus far redisplayed. */
2373 displayer->erase_entire_line (displayer);
2374 /* Note: The arguments to rl_abort are ignored. */
2377 if (for_pager && (c == NEWLINE || c == RETURN))
2379 if (for_pager && (c == 'q' || c == 'Q'))
2381 displayer->beep (displayer);
2385 /* Pager function for tab-completion.
2386 This is based on readline/complete.c:_rl_internal_pager.
2387 LINES is the number of lines of output displayed thus far.
2389 -1 -> user pressed 'n' or equivalent,
2390 0 -> user pressed 'y' or equivalent,
2391 N -> user pressed NEWLINE or equivalent and N is LINES - 1. */
2394 gdb_display_match_list_pager (int lines,
2395 const struct match_list_displayer *displayer)
2399 displayer->puts (displayer, "--More--");
2400 displayer->flush (displayer);
2401 i = gdb_get_y_or_n (1, displayer);
2402 displayer->erase_entire_line (displayer);
2411 /* Return non-zero if FILENAME is a directory.
2412 Based on readline/complete.c:path_isdir. */
2415 gdb_path_isdir (const char *filename)
2419 return (stat (filename, &finfo) == 0 && S_ISDIR (finfo.st_mode));
2422 /* Return the portion of PATHNAME that should be output when listing
2423 possible completions. If we are hacking filename completion, we
2424 are only interested in the basename, the portion following the
2425 final slash. Otherwise, we return what we were passed. Since
2426 printing empty strings is not very informative, if we're doing
2427 filename completion, and the basename is the empty string, we look
2428 for the previous slash and return the portion following that. If
2429 there's no previous slash, we just return what we were passed.
2431 Based on readline/complete.c:printable_part. */
2434 gdb_printable_part (char *pathname)
2438 if (rl_filename_completion_desired == 0) /* don't need to do anything */
2441 temp = strrchr (pathname, '/');
2442 #if defined (__MSDOS__)
2443 if (temp == 0 && ISALPHA ((unsigned char)pathname[0]) && pathname[1] == ':')
2444 temp = pathname + 1;
2447 if (temp == 0 || *temp == '\0')
2449 /* If the basename is NULL, we might have a pathname like '/usr/src/'.
2450 Look for a previous slash and, if one is found, return the portion
2451 following that slash. If there's no previous slash, just return the
2452 pathname we were passed. */
2453 else if (temp[1] == '\0')
2455 for (x = temp - 1; x > pathname; x--)
2458 return ((*x == '/') ? x + 1 : pathname);
2464 /* Compute width of STRING when displayed on screen by print_filename.
2465 Based on readline/complete.c:fnwidth. */
2468 gdb_fnwidth (const char *string)
2471 #if defined (HANDLE_MULTIBYTE)
2477 left = strlen (string) + 1;
2478 memset (&ps, 0, sizeof (mbstate_t));
2484 if (CTRL_CHAR (string[pos]) || string[pos] == RUBOUT)
2491 #if defined (HANDLE_MULTIBYTE)
2492 clen = mbrtowc (&wc, string + pos, left - pos, &ps);
2493 if (MB_INVALIDCH (clen))
2497 memset (&ps, 0, sizeof (mbstate_t));
2499 else if (MB_NULLWCH (clen))
2505 width += (w >= 0) ? w : 1;
2517 /* Print TO_PRINT, one matching completion.
2518 PREFIX_BYTES is number of common prefix bytes.
2519 Based on readline/complete.c:fnprint. */
2522 gdb_fnprint (const char *to_print, int prefix_bytes,
2523 const struct match_list_displayer *displayer)
2527 #if defined (HANDLE_MULTIBYTE)
2534 end = to_print + strlen (to_print) + 1;
2535 memset (&ps, 0, sizeof (mbstate_t));
2540 /* Don't print only the ellipsis if the common prefix is one of the
2541 possible completions */
2542 if (to_print[prefix_bytes] == '\0')
2549 ellipsis = (to_print[prefix_bytes] == '.') ? '_' : '.';
2550 for (w = 0; w < ELLIPSIS_LEN; w++)
2551 displayer->putch (displayer, ellipsis);
2552 printed_len = ELLIPSIS_LEN;
2555 s = to_print + prefix_bytes;
2560 displayer->putch (displayer, '^');
2561 displayer->putch (displayer, UNCTRL (*s));
2564 #if defined (HANDLE_MULTIBYTE)
2565 memset (&ps, 0, sizeof (mbstate_t));
2568 else if (*s == RUBOUT)
2570 displayer->putch (displayer, '^');
2571 displayer->putch (displayer, '?');
2574 #if defined (HANDLE_MULTIBYTE)
2575 memset (&ps, 0, sizeof (mbstate_t));
2580 #if defined (HANDLE_MULTIBYTE)
2581 tlen = mbrtowc (&wc, s, end - s, &ps);
2582 if (MB_INVALIDCH (tlen))
2586 memset (&ps, 0, sizeof (mbstate_t));
2588 else if (MB_NULLWCH (tlen))
2593 width = (w >= 0) ? w : 1;
2595 for (w = 0; w < tlen; ++w)
2596 displayer->putch (displayer, s[w]);
2598 printed_len += width;
2600 displayer->putch (displayer, *s);
2610 /* Output TO_PRINT to rl_outstream. If VISIBLE_STATS is defined and we
2611 are using it, check for and output a single character for `special'
2612 filenames. Return the number of characters we output.
2613 Based on readline/complete.c:print_filename. */
2616 gdb_print_filename (char *to_print, char *full_pathname, int prefix_bytes,
2617 const struct match_list_displayer *displayer)
2619 int printed_len, extension_char, slen, tlen;
2620 char *s, c, *new_full_pathname;
2622 extern int _rl_complete_mark_directories;
2625 printed_len = gdb_fnprint (to_print, prefix_bytes, displayer);
2627 #if defined (VISIBLE_STATS)
2628 if (rl_filename_completion_desired && (rl_visible_stats || _rl_complete_mark_directories))
2630 if (rl_filename_completion_desired && _rl_complete_mark_directories)
2633 /* If to_print != full_pathname, to_print is the basename of the
2634 path passed. In this case, we try to expand the directory
2635 name before checking for the stat character. */
2636 if (to_print != full_pathname)
2638 /* Terminate the directory name. */
2640 to_print[-1] = '\0';
2642 /* If setting the last slash in full_pathname to a NUL results in
2643 full_pathname being the empty string, we are trying to complete
2644 files in the root directory. If we pass a null string to the
2645 bash directory completion hook, for example, it will expand it
2646 to the current directory. We just want the `/'. */
2647 if (full_pathname == 0 || *full_pathname == 0)
2649 else if (full_pathname[0] != '/')
2651 else if (full_pathname[1] == 0)
2652 dn = "//"; /* restore trailing slash to `//' */
2653 else if (full_pathname[1] == '/' && full_pathname[2] == 0)
2654 dn = "/"; /* don't turn /// into // */
2657 s = tilde_expand (dn);
2658 if (rl_directory_completion_hook)
2659 (*rl_directory_completion_hook) (&s);
2662 tlen = strlen (to_print);
2663 new_full_pathname = (char *)xmalloc (slen + tlen + 2);
2664 strcpy (new_full_pathname, s);
2665 if (s[slen - 1] == '/')
2668 new_full_pathname[slen] = '/';
2669 new_full_pathname[slen] = '/';
2670 strcpy (new_full_pathname + slen + 1, to_print);
2672 #if defined (VISIBLE_STATS)
2673 if (rl_visible_stats)
2674 extension_char = stat_char (new_full_pathname);
2677 if (gdb_path_isdir (new_full_pathname))
2678 extension_char = '/';
2680 xfree (new_full_pathname);
2685 s = tilde_expand (full_pathname);
2686 #if defined (VISIBLE_STATS)
2687 if (rl_visible_stats)
2688 extension_char = stat_char (s);
2691 if (gdb_path_isdir (s))
2692 extension_char = '/';
2698 displayer->putch (displayer, extension_char);
2706 /* GDB version of readline/complete.c:complete_get_screenwidth. */
2709 gdb_complete_get_screenwidth (const struct match_list_displayer *displayer)
2711 /* Readline has other stuff here which it's not clear we need. */
2712 return displayer->width;
2715 extern int _rl_completion_prefix_display_length;
2716 extern int _rl_print_completions_horizontally;
2718 EXTERN_C int _rl_qsort_string_compare (const void *, const void *);
2719 typedef int QSFUNC (const void *, const void *);
2721 /* GDB version of readline/complete.c:rl_display_match_list.
2722 See gdb_display_match_list for a description of MATCHES, LEN, MAX.
2723 Returns non-zero if all matches are displayed. */
2726 gdb_display_match_list_1 (char **matches, int len, int max,
2727 const struct match_list_displayer *displayer)
2729 int count, limit, printed_len, lines, cols;
2730 int i, j, k, l, common_length, sind;
2732 int page_completions = displayer->height != INT_MAX && pagination_enabled;
2734 /* Find the length of the prefix common to all items: length as displayed
2735 characters (common_length) and as a byte index into the matches (sind) */
2736 common_length = sind = 0;
2737 if (_rl_completion_prefix_display_length > 0)
2739 t = gdb_printable_part (matches[0]);
2740 temp = strrchr (t, '/');
2741 common_length = temp ? gdb_fnwidth (temp) : gdb_fnwidth (t);
2742 sind = temp ? strlen (temp) : strlen (t);
2744 if (common_length > _rl_completion_prefix_display_length && common_length > ELLIPSIS_LEN)
2745 max -= common_length - ELLIPSIS_LEN;
2747 common_length = sind = 0;
2750 /* How many items of MAX length can we fit in the screen window? */
2751 cols = gdb_complete_get_screenwidth (displayer);
2754 if (limit != 1 && (limit * max == cols))
2757 /* If cols == 0, limit will end up -1 */
2758 if (cols < displayer->width && limit < 0)
2761 /* Avoid a possible floating exception. If max > cols,
2762 limit will be 0 and a divide-by-zero fault will result. */
2766 /* How many iterations of the printing loop? */
2767 count = (len + (limit - 1)) / limit;
2769 /* Watch out for special case. If LEN is less than LIMIT, then
2770 just do the inner printing loop.
2771 0 < len <= limit implies count = 1. */
2773 /* Sort the items if they are not already sorted. */
2774 if (rl_ignore_completion_duplicates == 0 && rl_sort_completion_matches)
2775 qsort (matches + 1, len, sizeof (char *), (QSFUNC *)_rl_qsort_string_compare);
2777 displayer->crlf (displayer);
2780 if (_rl_print_completions_horizontally == 0)
2782 /* Print the sorted items, up-and-down alphabetically, like ls. */
2783 for (i = 1; i <= count; i++)
2785 for (j = 0, l = i; j < limit; j++)
2787 if (l > len || matches[l] == 0)
2791 temp = gdb_printable_part (matches[l]);
2792 printed_len = gdb_print_filename (temp, matches[l], sind,
2796 for (k = 0; k < max - printed_len; k++)
2797 displayer->putch (displayer, ' ');
2801 displayer->crlf (displayer);
2803 if (page_completions && lines >= (displayer->height - 1) && i < count)
2805 lines = gdb_display_match_list_pager (lines, displayer);
2813 /* Print the sorted items, across alphabetically, like ls -x. */
2814 for (i = 1; matches[i]; i++)
2816 temp = gdb_printable_part (matches[i]);
2817 printed_len = gdb_print_filename (temp, matches[i], sind, displayer);
2818 /* Have we reached the end of this line? */
2821 if (i && (limit > 1) && (i % limit) == 0)
2823 displayer->crlf (displayer);
2825 if (page_completions && lines >= displayer->height - 1)
2827 lines = gdb_display_match_list_pager (lines, displayer);
2833 for (k = 0; k < max - printed_len; k++)
2834 displayer->putch (displayer, ' ');
2837 displayer->crlf (displayer);
2843 /* Utility for displaying completion list matches, used by both CLI and TUI.
2845 MATCHES is the list of strings, in argv format, LEN is the number of
2846 strings in MATCHES, and MAX is the length of the longest string in
2850 gdb_display_match_list (char **matches, int len, int max,
2851 const struct match_list_displayer *displayer)
2853 /* Readline will never call this if complete_line returned NULL. */
2854 gdb_assert (max_completions != 0);
2856 /* complete_line will never return more than this. */
2857 if (max_completions > 0)
2858 gdb_assert (len <= max_completions);
2860 if (rl_completion_query_items > 0 && len >= rl_completion_query_items)
2864 /* We can't use *query here because they wait for <RET> which is
2865 wrong here. This follows the readline version as closely as possible
2866 for compatibility's sake. See readline/complete.c. */
2868 displayer->crlf (displayer);
2870 xsnprintf (msg, sizeof (msg),
2871 "Display all %d possibilities? (y or n)", len);
2872 displayer->puts (displayer, msg);
2873 displayer->flush (displayer);
2875 if (gdb_get_y_or_n (0, displayer) == 0)
2877 displayer->crlf (displayer);
2882 if (gdb_display_match_list_1 (matches, len, max, displayer))
2884 /* Note: MAX_COMPLETIONS may be -1 or zero, but LEN is always > 0. */
2885 if (len == max_completions)
2887 /* The maximum number of completions has been reached. Warn the user
2888 that there may be more. */
2889 const char *message = get_max_completions_reached_message ();
2891 displayer->puts (displayer, message);
2892 displayer->crlf (displayer);
2898 _initialize_completer (void)
2900 add_setshow_zuinteger_unlimited_cmd ("max-completions", no_class,
2901 &max_completions, _("\
2902 Set maximum number of completion candidates."), _("\
2903 Show maximum number of completion candidates."), _("\
2904 Use this to limit the number of candidates considered\n\
2905 during completion. Specifying \"unlimited\" or -1\n\
2906 disables limiting. Note that setting either no limit or\n\
2907 a very large limit can make completion slow."),
2908 NULL, NULL, &setlist, &showlist);