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/>. */
21 /* Standard C++ includes. */
24 /* Local non-gdb includes. */
25 #include "arch-utils.h"
26 #include "cli/cli-decode.h"
27 #include "common/gdb_signals.h"
28 #include "expression.h"
29 #include "filenames.h"
34 #include "reggroups.h"
37 #include "user-regs.h"
39 /* FIXME: This is needed because of lookup_cmd_1 (). We should be
40 calling a hook instead so we eliminate the CLI dependency. */
43 /* Needed for rl_completer_word_break_characters() and for
44 rl_filename_completion_function. */
45 #include "readline/readline.h"
47 /* readline defines this. */
50 #include "completer.h"
52 /* Misc state that needs to be tracked across several different
53 readline completer entry point calls, all related to a single
54 completion invocation. */
56 struct gdb_completer_state
58 /* The current completion's completion tracker. This is a global
59 because a tracker can be shared between the handle_brkchars and
60 handle_completion phases, which involves different readline
62 completion_tracker *tracker = NULL;
64 /* Whether the current completion was aborted. */
68 /* The current completion state. */
69 static gdb_completer_state current_completion;
71 /* An enumeration of the various things a user might attempt to
72 complete for a location. If you change this, remember to update
73 the explicit_options array below too. */
75 enum explicit_location_match_type
77 /* The filename of a source file. */
80 /* The name of a function or method. */
83 /* The fully-qualified name of a function or method. */
89 /* The name of a label. */
93 /* Prototypes for local functions. */
95 /* readline uses the word breaks for two things:
96 (1) In figuring out where to point the TEXT parameter to the
97 rl_completion_entry_function. Since we don't use TEXT for much,
98 it doesn't matter a lot what the word breaks are for this purpose,
99 but it does affect how much stuff M-? lists.
100 (2) If one of the matches contains a word break character, readline
101 will quote it. That's why we switch between
102 current_language->la_word_break_characters() and
103 gdb_completer_command_word_break_characters. I'm not sure when
104 we need this behavior (perhaps for funky characters in C++
107 /* Variables which are necessary for fancy command line editing. */
109 /* When completing on command names, we remove '-' from the list of
110 word break characters, since we use it in command names. If the
111 readline library sees one in any of the current completion strings,
112 it thinks that the string needs to be quoted and automatically
113 supplies a leading quote. */
114 static const char gdb_completer_command_word_break_characters[] =
115 " \t\n!@#$%^&*()+=|~`}{[]\"';:?/>.<,";
117 /* When completing on file names, we remove from the list of word
118 break characters any characters that are commonly used in file
119 names, such as '-', '+', '~', etc. Otherwise, readline displays
120 incorrect completion candidates. */
121 /* MS-DOS and MS-Windows use colon as part of the drive spec, and most
122 programs support @foo style response files. */
123 static const char gdb_completer_file_name_break_characters[] =
124 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
130 /* Characters that can be used to quote completion strings. Note that
131 we can't include '"' because the gdb C parser treats such quoted
132 sequences as strings. */
133 static const char gdb_completer_quote_characters[] = "'";
135 /* Accessor for some completer data that may interest other files. */
138 get_gdb_completer_quote_characters (void)
140 return gdb_completer_quote_characters;
143 /* This can be used for functions which don't want to complete on
144 symbols but don't want to complete on anything else either. */
147 noop_completer (struct cmd_list_element *ignore,
148 completion_tracker &tracker,
149 const char *text, const char *prefix)
153 /* Complete on filenames. */
156 filename_completer (struct cmd_list_element *ignore,
157 completion_tracker &tracker,
158 const char *text, const char *word)
165 gdb::unique_xmalloc_ptr<char> p_rl
166 (rl_filename_completion_function (text, subsequent_name));
169 /* We need to set subsequent_name to a non-zero value before the
170 continue line below, because otherwise, if the first file
171 seen by GDB is a backup file whose name ends in a `~', we
172 will loop indefinitely. */
174 /* Like emacs, don't complete on old versions. Especially
175 useful in the "source" command. */
176 const char *p = p_rl.get ();
177 if (p[strlen (p) - 1] == '~')
180 tracker.add_completion
181 (make_completion_match_str (std::move (p_rl), text, word));
184 /* There is no way to do this just long enough to affect quote
185 inserting without also affecting the next completion. This
186 should be fixed in readline. FIXME. */
187 /* Ensure that readline does the right thing
188 with respect to inserting quotes. */
189 rl_completer_word_break_characters = "";
193 /* The corresponding completer_handle_brkchars
197 filename_completer_handle_brkchars (struct cmd_list_element *ignore,
198 completion_tracker &tracker,
199 const char *text, const char *word)
201 set_rl_completer_word_break_characters
202 (gdb_completer_file_name_break_characters);
205 /* Possible values for the found_quote flags word used by the completion
206 functions. It says what kind of (shell-like) quoting we found anywhere
208 #define RL_QF_SINGLE_QUOTE 0x01
209 #define RL_QF_DOUBLE_QUOTE 0x02
210 #define RL_QF_BACKSLASH 0x04
211 #define RL_QF_OTHER_QUOTE 0x08
213 /* Find the bounds of the current word for completion purposes, and
214 return a pointer to the end of the word. This mimics (and is a
215 modified version of) readline's _rl_find_completion_word internal
218 This function skips quoted substrings (characters between matched
219 pairs of characters in rl_completer_quote_characters). We try to
220 find an unclosed quoted substring on which to do matching. If one
221 is not found, we use the word break characters to find the
222 boundaries of the current word. QC, if non-null, is set to the
223 opening quote character if we found an unclosed quoted substring,
224 '\0' otherwise. DP, if non-null, is set to the value of the
225 delimiter character that caused a word break. */
227 struct gdb_rl_completion_word_info
229 const char *word_break_characters;
230 const char *quote_characters;
231 const char *basic_quote_characters;
235 gdb_rl_find_completion_word (struct gdb_rl_completion_word_info *info,
237 const char *line_buffer)
239 int scan, end, found_quote, delimiter, pass_next, isbrk;
241 const char *brkchars;
242 int point = strlen (line_buffer);
244 /* The algorithm below does '--point'. Avoid buffer underflow with
256 found_quote = delimiter = 0;
259 brkchars = info->word_break_characters;
261 if (info->quote_characters != NULL)
263 /* We have a list of characters which can be used in pairs to
264 quote substrings for the completer. Try to find the start of
265 an unclosed quoted substring. */
266 /* FOUND_QUOTE is set so we know what kind of quotes we
268 for (scan = pass_next = 0;
278 /* Shell-like semantics for single quotes -- don't allow
279 backslash to quote anything in single quotes, especially
280 not the closing quote. If you don't like this, take out
281 the check on the value of quote_char. */
282 if (quote_char != '\'' && line_buffer[scan] == '\\')
285 found_quote |= RL_QF_BACKSLASH;
289 if (quote_char != '\0')
291 /* Ignore everything until the matching close quote
293 if (line_buffer[scan] == quote_char)
295 /* Found matching close. Abandon this
301 else if (strchr (info->quote_characters, line_buffer[scan]))
303 /* Found start of a quoted substring. */
304 quote_char = line_buffer[scan];
306 /* Shell-like quoting conventions. */
307 if (quote_char == '\'')
308 found_quote |= RL_QF_SINGLE_QUOTE;
309 else if (quote_char == '"')
310 found_quote |= RL_QF_DOUBLE_QUOTE;
312 found_quote |= RL_QF_OTHER_QUOTE;
317 if (point == end && quote_char == '\0')
319 /* We didn't find an unclosed quoted substring upon which to do
320 completion, so use the word break characters to find the
321 substring on which to complete. */
324 scan = line_buffer[point];
326 if (strchr (brkchars, scan) != 0)
331 /* If we are at an unquoted word break, then advance past it. */
332 scan = line_buffer[point];
336 isbrk = strchr (brkchars, scan) != 0;
340 /* If the character that caused the word break was a quoting
341 character, then remember it as the delimiter. */
342 if (info->basic_quote_characters
343 && strchr (info->basic_quote_characters, scan)
344 && (end - point) > 1)
356 return line_buffer + point;
359 /* See completer.h. */
362 advance_to_expression_complete_word_point (completion_tracker &tracker,
365 gdb_rl_completion_word_info info;
367 info.word_break_characters
368 = current_language->la_word_break_characters ();
369 info.quote_characters = gdb_completer_quote_characters;
370 info.basic_quote_characters = rl_basic_quote_characters;
373 = gdb_rl_find_completion_word (&info, NULL, NULL, text);
375 tracker.advance_custom_word_point_by (start - text);
380 /* See completer.h. */
383 completion_tracker::completes_to_completion_word (const char *word)
385 if (m_lowest_common_denominator_unique)
387 const char *lcd = m_lowest_common_denominator;
389 if (strncmp_iw (word, lcd, strlen (lcd)) == 0)
391 /* Maybe skip the function and complete on keywords. */
392 size_t wordlen = strlen (word);
393 if (word[wordlen - 1] == ' ')
401 /* Complete on linespecs, which might be of two possible forms:
407 This is intended to be used in commands that set breakpoints
411 complete_files_symbols (completion_tracker &tracker,
412 const char *text, const char *word)
414 completion_list fn_list;
417 int quoted = *text == '\'' || *text == '"';
418 int quote_char = '\0';
419 const char *colon = NULL;
420 char *file_to_match = NULL;
421 const char *symbol_start = text;
422 const char *orig_text = text;
424 /* Do we have an unquoted colon, as in "break foo.c:bar"? */
425 for (p = text; *p != '\0'; ++p)
427 if (*p == '\\' && p[1] == '\'')
429 else if (*p == '\'' || *p == '"')
433 while (*p != '\0' && *p != quote_found)
435 if (*p == '\\' && p[1] == quote_found)
440 if (*p == quote_found)
443 break; /* Hit the end of text. */
445 #if HAVE_DOS_BASED_FILE_SYSTEM
446 /* If we have a DOS-style absolute file name at the beginning of
447 TEXT, and the colon after the drive letter is the only colon
448 we found, pretend the colon is not there. */
449 else if (p < text + 3 && *p == ':' && p == text + 1 + quoted)
452 else if (*p == ':' && !colon)
455 symbol_start = p + 1;
457 else if (strchr (current_language->la_word_break_characters(), *p))
458 symbol_start = p + 1;
464 /* Where is the file name? */
469 file_to_match = (char *) xmalloc (colon - text + 1);
470 strncpy (file_to_match, text, colon - text);
471 file_to_match[colon - text] = '\0';
472 /* Remove trailing colons and quotes from the file name. */
473 for (s = file_to_match + (colon - text);
476 if (*s == ':' || *s == quote_char)
479 /* If the text includes a colon, they want completion only on a
480 symbol name after the colon. Otherwise, we need to complete on
481 symbols as well as on files. */
484 collect_file_symbol_completion_matches (tracker,
485 complete_symbol_mode::EXPRESSION,
486 symbol_name_match_type::EXPRESSION,
489 xfree (file_to_match);
493 size_t text_len = strlen (text);
495 collect_symbol_completion_matches (tracker,
496 complete_symbol_mode::EXPRESSION,
497 symbol_name_match_type::EXPRESSION,
499 /* If text includes characters which cannot appear in a file
500 name, they cannot be asking for completion on files. */
502 gdb_completer_file_name_break_characters) == text_len)
503 fn_list = make_source_files_completion_list (text, text);
506 if (!fn_list.empty () && !tracker.have_completions ())
508 /* If we only have file names as possible completion, we should
509 bring them in sync with what rl_complete expects. The
510 problem is that if the user types "break /foo/b TAB", and the
511 possible completions are "/foo/bar" and "/foo/baz"
512 rl_complete expects us to return "bar" and "baz", without the
513 leading directories, as possible completions, because `word'
514 starts at the "b". But we ignore the value of `word' when we
515 call make_source_files_completion_list above (because that
516 would not DTRT when the completion results in both symbols
517 and file names), so make_source_files_completion_list returns
518 the full "/foo/bar" and "/foo/baz" strings. This produces
519 wrong results when, e.g., there's only one possible
520 completion, because rl_complete will prepend "/foo/" to each
521 candidate completion. The loop below removes that leading
523 for (const auto &fn_up: fn_list)
525 char *fn = fn_up.get ();
526 memmove (fn, fn + (word - text), strlen (fn) + 1 - (word - text));
530 tracker.add_completions (std::move (fn_list));
532 if (!tracker.have_completions ())
534 /* No completions at all. As the final resort, try completing
535 on the entire text as a symbol. */
536 collect_symbol_completion_matches (tracker,
537 complete_symbol_mode::EXPRESSION,
538 symbol_name_match_type::EXPRESSION,
543 /* See completer.h. */
546 complete_source_filenames (const char *text)
548 size_t text_len = strlen (text);
550 /* If text includes characters which cannot appear in a file name,
551 the user cannot be asking for completion on files. */
553 gdb_completer_file_name_break_characters)
555 return make_source_files_completion_list (text, text);
560 /* Complete address and linespec locations. */
563 complete_address_and_linespec_locations (completion_tracker &tracker,
565 symbol_name_match_type match_type)
569 tracker.advance_custom_word_point_by (1);
572 = advance_to_expression_complete_word_point (tracker, text);
573 complete_expression (tracker, text, word);
577 linespec_complete (tracker, text, match_type);
581 /* The explicit location options. Note that indexes into this array
582 must match the explicit_location_match_type enumerators. */
584 static const char *const explicit_options[] =
594 /* The probe modifier options. These can appear before a location in
595 breakpoint commands. */
596 static const char *const probe_options[] =
604 /* Returns STRING if not NULL, the empty string otherwise. */
607 string_or_empty (const char *string)
609 return string != NULL ? string : "";
612 /* A helper function to collect explicit location matches for the given
613 LOCATION, which is attempting to match on WORD. */
616 collect_explicit_location_matches (completion_tracker &tracker,
617 struct event_location *location,
618 enum explicit_location_match_type what,
620 const struct language_defn *language)
622 const struct explicit_location *explicit_loc
623 = get_explicit_location (location);
625 /* True if the option expects an argument. */
626 bool needs_arg = true;
628 /* Note, in the various MATCH_* below, we complete on
629 explicit_loc->foo instead of WORD, because only the former will
630 have already skipped past any quote char. */
635 const char *source = string_or_empty (explicit_loc->source_filename);
636 completion_list matches
637 = make_source_files_completion_list (source, source);
638 tracker.add_completions (std::move (matches));
644 const char *function = string_or_empty (explicit_loc->function_name);
645 linespec_complete_function (tracker, function,
646 explicit_loc->func_name_match_type,
647 explicit_loc->source_filename);
651 case MATCH_QUALIFIED:
655 /* Nothing to offer. */
660 const char *label = string_or_empty (explicit_loc->label_name);
661 linespec_complete_label (tracker, language,
662 explicit_loc->source_filename,
663 explicit_loc->function_name,
664 explicit_loc->func_name_match_type,
670 gdb_assert_not_reached ("unhandled explicit_location_match_type");
673 if (!needs_arg || tracker.completes_to_completion_word (word))
675 tracker.discard_completions ();
676 tracker.advance_custom_word_point_by (strlen (word));
677 complete_on_enum (tracker, explicit_options, "", "");
678 complete_on_enum (tracker, linespec_keywords, "", "");
680 else if (!tracker.have_completions ())
682 /* Maybe we have an unterminated linespec keyword at the tail of
683 the string. Try completing on that. */
684 size_t wordlen = strlen (word);
685 const char *keyword = word + wordlen;
687 if (wordlen > 0 && keyword[-1] != ' ')
689 while (keyword > word && *keyword != ' ')
691 /* Don't complete on keywords if we'd be completing on the
692 whole explicit linespec option. E.g., "b -function
693 thr<tab>" should not complete to the "thread"
697 keyword = skip_spaces (keyword);
699 tracker.advance_custom_word_point_by (keyword - word);
700 complete_on_enum (tracker, linespec_keywords, keyword, keyword);
703 else if (wordlen > 0 && keyword[-1] == ' ')
705 /* Assume that we're maybe past the explicit location
706 argument, and we didn't manage to find any match because
707 the user wants to create a pending breakpoint. Offer the
708 keyword and explicit location options as possible
710 tracker.advance_custom_word_point_by (keyword - word);
711 complete_on_enum (tracker, linespec_keywords, keyword, keyword);
712 complete_on_enum (tracker, explicit_options, keyword, keyword);
717 /* If the next word in *TEXT_P is any of the keywords in KEYWORDS,
718 then advance both TEXT_P and the word point in the tracker past the
719 keyword and return the (0-based) index in the KEYWORDS array that
720 matched. Otherwise, return -1. */
723 skip_keyword (completion_tracker &tracker,
724 const char * const *keywords, const char **text_p)
726 const char *text = *text_p;
727 const char *after = skip_to_space (text);
728 size_t len = after - text;
730 if (text[len] != ' ')
734 for (int i = 0; keywords[i] != NULL; i++)
736 if (strncmp (keywords[i], text, len) == 0)
747 tracker.advance_custom_word_point_by (len + 1);
756 /* A completer function for explicit locations. This function
757 completes both options ("-source", "-line", etc) and values. If
758 completing a quoted string, then QUOTED_ARG_START and
759 QUOTED_ARG_END point to the quote characters. LANGUAGE is the
763 complete_explicit_location (completion_tracker &tracker,
764 struct event_location *location,
766 const language_defn *language,
767 const char *quoted_arg_start,
768 const char *quoted_arg_end)
773 int keyword = skip_keyword (tracker, explicit_options, &text);
776 complete_on_enum (tracker, explicit_options, text, text);
779 /* Completing on value. */
780 enum explicit_location_match_type what
781 = (explicit_location_match_type) keyword;
783 if (quoted_arg_start != NULL && quoted_arg_end != NULL)
785 if (quoted_arg_end[1] == '\0')
787 /* If completing a quoted string with the cursor right
788 at the terminating quote char, complete the
789 completion word without interpretation, so that
790 readline advances the cursor one whitespace past the
791 quote, even if there's no match. This makes these
792 cases behave the same:
794 before: "b -function function()"
795 after: "b -function function() "
797 before: "b -function 'function()'"
798 after: "b -function 'function()' "
800 and trusts the user in this case:
802 before: "b -function 'not_loaded_function_yet()'"
803 after: "b -function 'not_loaded_function_yet()' "
805 gdb::unique_xmalloc_ptr<char> text_copy
807 tracker.add_completion (std::move (text_copy));
809 else if (quoted_arg_end[1] == ' ')
811 /* We're maybe past the explicit location argument.
812 Skip the argument without interpretion, assuming the
813 user may want to create pending breakpoint. Offer
814 the keyword and explicit location options as possible
816 tracker.advance_custom_word_point_by (strlen (text));
817 complete_on_enum (tracker, linespec_keywords, "", "");
818 complete_on_enum (tracker, explicit_options, "", "");
823 /* Now gather matches */
824 collect_explicit_location_matches (tracker, location, what, text,
829 /* A completer for locations. */
832 location_completer (struct cmd_list_element *ignore,
833 completion_tracker &tracker,
834 const char *text, const char * /* word */)
836 int found_probe_option = -1;
838 /* If we have a probe modifier, skip it. This can only appear as
839 first argument. Until we have a specific completer for probes,
840 falling back to the linespec completer for the remainder of the
841 line is better than nothing. */
842 if (text[0] == '-' && text[1] == 'p')
843 found_probe_option = skip_keyword (tracker, probe_options, &text);
845 const char *option_text = text;
846 int saved_word_point = tracker.custom_word_point ();
848 const char *copy = text;
850 explicit_completion_info completion_info;
851 event_location_up location
852 = string_to_explicit_location (©, current_language,
854 if (completion_info.quoted_arg_start != NULL
855 && completion_info.quoted_arg_end == NULL)
857 /* Found an unbalanced quote. */
858 tracker.set_quote_char (*completion_info.quoted_arg_start);
859 tracker.advance_custom_word_point_by (1);
862 if (completion_info.saw_explicit_location_option)
866 tracker.advance_custom_word_point_by (copy - text);
869 /* We found a terminator at the tail end of the string,
870 which means we're past the explicit location options. We
871 may have a keyword to complete on. If we have a whole
872 keyword, then complete whatever comes after as an
873 expression. This is mainly for the "if" keyword. If the
874 "thread" and "task" keywords gain their own completers,
875 they should be used here. */
876 int keyword = skip_keyword (tracker, linespec_keywords, &text);
880 complete_on_enum (tracker, linespec_keywords, text, text);
885 = advance_to_expression_complete_word_point (tracker, text);
886 complete_expression (tracker, text, word);
891 tracker.advance_custom_word_point_by (completion_info.last_option
893 text = completion_info.last_option;
895 complete_explicit_location (tracker, location.get (), text,
897 completion_info.quoted_arg_start,
898 completion_info.quoted_arg_end);
902 /* This is an address or linespec location. */
903 else if (location != NULL)
905 /* Handle non-explicit location options. */
907 int keyword = skip_keyword (tracker, explicit_options, &text);
909 complete_on_enum (tracker, explicit_options, text, text);
912 tracker.advance_custom_word_point_by (copy - text);
915 symbol_name_match_type match_type
916 = get_explicit_location (location.get ())->func_name_match_type;
917 complete_address_and_linespec_locations (tracker, text, match_type);
923 complete_address_and_linespec_locations (tracker, text,
924 symbol_name_match_type::WILD);
927 /* Add matches for option names, if either:
929 - Some completer above found some matches, but the word point did
930 not advance (e.g., "b <tab>" finds all functions, or "b -<tab>"
931 matches all objc selectors), or;
933 - Some completer above advanced the word point, but found no
936 if ((text[0] == '-' || text[0] == '\0')
937 && (!tracker.have_completions ()
938 || tracker.custom_word_point () == saved_word_point))
940 tracker.set_custom_word_point (saved_word_point);
943 if (found_probe_option == -1)
944 complete_on_enum (tracker, probe_options, text, text);
945 complete_on_enum (tracker, explicit_options, text, text);
949 /* The corresponding completer_handle_brkchars
953 location_completer_handle_brkchars (struct cmd_list_element *ignore,
954 completion_tracker &tracker,
956 const char *word_ignored)
958 tracker.set_use_custom_word_point (true);
960 location_completer (ignore, tracker, text, NULL);
963 /* Helper for expression_completer which recursively adds field and
964 method names from TYPE, a struct or union type, to the OUTPUT
968 add_struct_fields (struct type *type, completion_list &output,
969 const char *fieldname, int namelen)
972 int computed_type_name = 0;
973 const char *type_name = NULL;
975 type = check_typedef (type);
976 for (i = 0; i < TYPE_NFIELDS (type); ++i)
978 if (i < TYPE_N_BASECLASSES (type))
979 add_struct_fields (TYPE_BASECLASS (type, i),
980 output, fieldname, namelen);
981 else if (TYPE_FIELD_NAME (type, i))
983 if (TYPE_FIELD_NAME (type, i)[0] != '\0')
985 if (! strncmp (TYPE_FIELD_NAME (type, i),
987 output.emplace_back (xstrdup (TYPE_FIELD_NAME (type, i)));
989 else if (TYPE_CODE (TYPE_FIELD_TYPE (type, i)) == TYPE_CODE_UNION)
991 /* Recurse into anonymous unions. */
992 add_struct_fields (TYPE_FIELD_TYPE (type, i),
993 output, fieldname, namelen);
998 for (i = TYPE_NFN_FIELDS (type) - 1; i >= 0; --i)
1000 const char *name = TYPE_FN_FIELDLIST_NAME (type, i);
1002 if (name && ! strncmp (name, fieldname, namelen))
1004 if (!computed_type_name)
1006 type_name = TYPE_NAME (type);
1007 computed_type_name = 1;
1009 /* Omit constructors from the completion list. */
1010 if (!type_name || strcmp (type_name, name))
1011 output.emplace_back (xstrdup (name));
1016 /* See completer.h. */
1019 complete_expression (completion_tracker &tracker,
1020 const char *text, const char *word)
1022 struct type *type = NULL;
1023 gdb::unique_xmalloc_ptr<char> fieldname;
1024 enum type_code code = TYPE_CODE_UNDEF;
1026 /* Perform a tentative parse of the expression, to see whether a
1027 field completion is required. */
1030 type = parse_expression_for_completion (text, &fieldname, &code);
1032 CATCH (except, RETURN_MASK_ERROR)
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 if (reason != handle_brkchars)
1407 complete_on_cmdlist (result_list, tracker, q, word,
1408 ignore_help_classes);
1410 /* Ensure that readline does the right thing
1411 with respect to inserting quotes. */
1412 set_rl_completer_word_break_characters
1413 (gdb_completer_command_word_break_characters);
1416 else if (reason == handle_help)
1420 /* There is non-whitespace beyond the command. */
1422 if (c->prefixlist && !c->allow_unknown)
1424 /* It is an unrecognized subcommand of a prefix command,
1425 e.g. "info adsfkdj". */
1429 if (reason != handle_brkchars)
1430 complete_on_enum (tracker, c->enums, p, word);
1434 /* It is a normal command. */
1435 complete_line_internal_normal_command (tracker,
1436 tmp_command, word, p,
1443 /* Wrapper around complete_line_internal_1 to handle
1444 MAX_COMPLETIONS_REACHED_ERROR. */
1447 complete_line_internal (completion_tracker &tracker,
1449 const char *line_buffer, int point,
1450 complete_line_internal_reason reason)
1454 complete_line_internal_1 (tracker, text, line_buffer, point, reason);
1456 CATCH (except, RETURN_MASK_ERROR)
1458 if (except.error != MAX_COMPLETIONS_REACHED_ERROR)
1459 throw_exception (except);
1464 /* See completer.h. */
1466 int max_completions = 200;
1468 /* Initial size of the table. It automagically grows from here. */
1469 #define INITIAL_COMPLETION_HTAB_SIZE 200
1471 /* See completer.h. */
1473 completion_tracker::completion_tracker ()
1475 m_entries_hash = htab_create_alloc (INITIAL_COMPLETION_HTAB_SIZE,
1476 htab_hash_string, streq_hash,
1477 NULL, xcalloc, xfree);
1480 /* See completer.h. */
1483 completion_tracker::discard_completions ()
1485 xfree (m_lowest_common_denominator);
1486 m_lowest_common_denominator = NULL;
1488 m_lowest_common_denominator_unique = false;
1490 m_entries_vec.clear ();
1492 htab_delete (m_entries_hash);
1493 m_entries_hash = htab_create_alloc (INITIAL_COMPLETION_HTAB_SIZE,
1494 htab_hash_string, streq_hash,
1495 NULL, xcalloc, xfree);
1498 /* See completer.h. */
1500 completion_tracker::~completion_tracker ()
1502 xfree (m_lowest_common_denominator);
1503 htab_delete (m_entries_hash);
1506 /* See completer.h. */
1509 completion_tracker::maybe_add_completion
1510 (gdb::unique_xmalloc_ptr<char> name,
1511 completion_match_for_lcd *match_for_lcd,
1512 const char *text, const char *word)
1516 if (max_completions == 0)
1519 if (htab_elements (m_entries_hash) >= max_completions)
1522 slot = htab_find_slot (m_entries_hash, name.get (), INSERT);
1523 if (*slot == HTAB_EMPTY_ENTRY)
1525 const char *match_for_lcd_str = NULL;
1527 if (match_for_lcd != NULL)
1528 match_for_lcd_str = match_for_lcd->finish ();
1530 if (match_for_lcd_str == NULL)
1531 match_for_lcd_str = name.get ();
1533 gdb::unique_xmalloc_ptr<char> lcd
1534 = make_completion_match_str (match_for_lcd_str, text, word);
1536 recompute_lowest_common_denominator (std::move (lcd));
1538 *slot = name.get ();
1539 m_entries_vec.push_back (std::move (name));
1545 /* See completer.h. */
1548 completion_tracker::add_completion (gdb::unique_xmalloc_ptr<char> name,
1549 completion_match_for_lcd *match_for_lcd,
1550 const char *text, const char *word)
1552 if (!maybe_add_completion (std::move (name), match_for_lcd, text, word))
1553 throw_error (MAX_COMPLETIONS_REACHED_ERROR, _("Max completions reached."));
1556 /* See completer.h. */
1559 completion_tracker::add_completions (completion_list &&list)
1561 for (auto &candidate : list)
1562 add_completion (std::move (candidate));
1565 /* Helper for the make_completion_match_str overloads. Returns NULL
1566 as an indication that we want MATCH_NAME exactly. It is up to the
1567 caller to xstrdup that string if desired. */
1570 make_completion_match_str_1 (const char *match_name,
1571 const char *text, const char *word)
1577 /* Return NULL as an indication that we want MATCH_NAME
1581 else if (word > text)
1583 /* Return some portion of MATCH_NAME. */
1584 newobj = xstrdup (match_name + (word - text));
1588 /* Return some of WORD plus MATCH_NAME. */
1589 size_t len = strlen (match_name);
1590 newobj = (char *) xmalloc (text - word + len + 1);
1591 memcpy (newobj, word, text - word);
1592 memcpy (newobj + (text - word), match_name, len + 1);
1598 /* See completer.h. */
1600 gdb::unique_xmalloc_ptr<char>
1601 make_completion_match_str (const char *match_name,
1602 const char *text, const char *word)
1604 char *newobj = make_completion_match_str_1 (match_name, text, word);
1606 newobj = xstrdup (match_name);
1607 return gdb::unique_xmalloc_ptr<char> (newobj);
1610 /* See completer.h. */
1612 gdb::unique_xmalloc_ptr<char>
1613 make_completion_match_str (gdb::unique_xmalloc_ptr<char> &&match_name,
1614 const char *text, const char *word)
1616 char *newobj = make_completion_match_str_1 (match_name.get (), text, word);
1618 return std::move (match_name);
1619 return gdb::unique_xmalloc_ptr<char> (newobj);
1622 /* Generate completions all at once. Does nothing if max_completions
1623 is 0. If max_completions is non-negative, this will collect at
1624 most max_completions strings.
1626 TEXT is the caller's idea of the "word" we are looking at.
1628 LINE_BUFFER is available to be looked at; it contains the entire
1631 POINT is the offset in that line of the cursor. You
1632 should pretend that the line ends at POINT. */
1635 complete_line (completion_tracker &tracker,
1636 const char *text, const char *line_buffer, int point)
1638 if (max_completions == 0)
1640 complete_line_internal (tracker, text, line_buffer, point,
1641 handle_completions);
1644 /* Complete on command names. Used by "help". */
1647 command_completer (struct cmd_list_element *ignore,
1648 completion_tracker &tracker,
1649 const char *text, const char *word)
1651 complete_line_internal (tracker, word, text,
1652 strlen (text), handle_help);
1655 /* The corresponding completer_handle_brkchars implementation. */
1658 command_completer_handle_brkchars (struct cmd_list_element *ignore,
1659 completion_tracker &tracker,
1660 const char *text, const char *word)
1662 set_rl_completer_word_break_characters
1663 (gdb_completer_command_word_break_characters);
1666 /* Complete on signals. */
1669 signal_completer (struct cmd_list_element *ignore,
1670 completion_tracker &tracker,
1671 const char *text, const char *word)
1673 size_t len = strlen (word);
1675 const char *signame;
1677 for (signum = GDB_SIGNAL_FIRST; signum != GDB_SIGNAL_LAST; ++signum)
1679 /* Can't handle this, so skip it. */
1680 if (signum == GDB_SIGNAL_0)
1683 signame = gdb_signal_to_name ((enum gdb_signal) signum);
1685 /* Ignore the unknown signal case. */
1686 if (!signame || strcmp (signame, "?") == 0)
1689 if (strncasecmp (signame, word, len) == 0)
1691 gdb::unique_xmalloc_ptr<char> copy (xstrdup (signame));
1692 tracker.add_completion (std::move (copy));
1697 /* Bit-flags for selecting what the register and/or register-group
1698 completer should complete on. */
1700 enum reg_completer_target
1702 complete_register_names = 0x1,
1703 complete_reggroup_names = 0x2
1705 DEF_ENUM_FLAGS_TYPE (enum reg_completer_target, reg_completer_targets);
1707 /* Complete register names and/or reggroup names based on the value passed
1708 in TARGETS. At least one bit in TARGETS must be set. */
1711 reg_or_group_completer_1 (completion_tracker &tracker,
1712 const char *text, const char *word,
1713 reg_completer_targets targets)
1715 size_t len = strlen (word);
1716 struct gdbarch *gdbarch;
1719 gdb_assert ((targets & (complete_register_names
1720 | complete_reggroup_names)) != 0);
1721 gdbarch = get_current_arch ();
1723 if ((targets & complete_register_names) != 0)
1728 (name = user_reg_map_regnum_to_name (gdbarch, i)) != NULL;
1731 if (*name != '\0' && strncmp (word, name, len) == 0)
1733 gdb::unique_xmalloc_ptr<char> copy (xstrdup (name));
1734 tracker.add_completion (std::move (copy));
1739 if ((targets & complete_reggroup_names) != 0)
1741 struct reggroup *group;
1743 for (group = reggroup_next (gdbarch, NULL);
1745 group = reggroup_next (gdbarch, group))
1747 name = reggroup_name (group);
1748 if (strncmp (word, name, len) == 0)
1750 gdb::unique_xmalloc_ptr<char> copy (xstrdup (name));
1751 tracker.add_completion (std::move (copy));
1757 /* Perform completion on register and reggroup names. */
1760 reg_or_group_completer (struct cmd_list_element *ignore,
1761 completion_tracker &tracker,
1762 const char *text, const char *word)
1764 reg_or_group_completer_1 (tracker, text, word,
1765 (complete_register_names
1766 | complete_reggroup_names));
1769 /* Perform completion on reggroup names. */
1772 reggroup_completer (struct cmd_list_element *ignore,
1773 completion_tracker &tracker,
1774 const char *text, const char *word)
1776 reg_or_group_completer_1 (tracker, text, word,
1777 complete_reggroup_names);
1780 /* The default completer_handle_brkchars implementation. */
1783 default_completer_handle_brkchars (struct cmd_list_element *ignore,
1784 completion_tracker &tracker,
1785 const char *text, const char *word)
1787 set_rl_completer_word_break_characters
1788 (current_language->la_word_break_characters ());
1791 /* See definition in completer.h. */
1793 completer_handle_brkchars_ftype *
1794 completer_handle_brkchars_func_for_completer (completer_ftype *fn)
1796 if (fn == filename_completer)
1797 return filename_completer_handle_brkchars;
1799 if (fn == location_completer)
1800 return location_completer_handle_brkchars;
1802 if (fn == command_completer)
1803 return command_completer_handle_brkchars;
1805 return default_completer_handle_brkchars;
1808 /* Used as brkchars when we want to tell readline we have a custom
1809 word point. We do that by making our rl_completion_word_break_hook
1810 set RL_POINT to the desired word point, and return the character at
1811 the word break point as the break char. This is two bytes in order
1812 to fit one break character plus the terminating null. */
1813 static char gdb_custom_word_point_brkchars[2];
1815 /* Since rl_basic_quote_characters is not completer-specific, we save
1816 its original value here, in order to be able to restore it in
1817 gdb_rl_attempted_completion_function. */
1818 static const char *gdb_org_rl_basic_quote_characters = rl_basic_quote_characters;
1820 /* Get the list of chars that are considered as word breaks
1821 for the current command. */
1824 gdb_completion_word_break_characters_throw ()
1826 /* New completion starting. Get rid of the previous tracker and
1828 delete current_completion.tracker;
1829 current_completion.tracker = new completion_tracker ();
1831 completion_tracker &tracker = *current_completion.tracker;
1833 complete_line_internal (tracker, NULL, rl_line_buffer,
1834 rl_point, handle_brkchars);
1836 if (tracker.use_custom_word_point ())
1838 gdb_assert (tracker.custom_word_point () > 0);
1839 rl_point = tracker.custom_word_point () - 1;
1840 gdb_custom_word_point_brkchars[0] = rl_line_buffer[rl_point];
1841 rl_completer_word_break_characters = gdb_custom_word_point_brkchars;
1842 rl_completer_quote_characters = NULL;
1844 /* Clear this too, so that if we're completing a quoted string,
1845 readline doesn't consider the quote character a delimiter.
1846 If we didn't do this, readline would auto-complete {b
1847 'fun<tab>} to {'b 'function()'}, i.e., add the terminating
1848 \', but, it wouldn't append the separator space either, which
1849 is not desirable. So instead we take care of appending the
1850 quote character to the LCD ourselves, in
1851 gdb_rl_attempted_completion_function. Since this global is
1852 not just completer-specific, we'll restore it back to the
1853 default in gdb_rl_attempted_completion_function. */
1854 rl_basic_quote_characters = NULL;
1857 return rl_completer_word_break_characters;
1861 gdb_completion_word_break_characters ()
1863 /* New completion starting. */
1864 current_completion.aborted = false;
1868 return gdb_completion_word_break_characters_throw ();
1870 CATCH (ex, RETURN_MASK_ALL)
1872 /* Set this to that gdb_rl_attempted_completion_function knows
1874 current_completion.aborted = true;
1881 /* See completer.h. */
1884 completion_find_completion_word (completion_tracker &tracker, const char *text,
1887 size_t point = strlen (text);
1889 complete_line_internal (tracker, NULL, text, point, handle_brkchars);
1891 if (tracker.use_custom_word_point ())
1893 gdb_assert (tracker.custom_word_point () > 0);
1894 *quote_char = tracker.quote_char ();
1895 return text + tracker.custom_word_point ();
1898 gdb_rl_completion_word_info info;
1900 info.word_break_characters = rl_completer_word_break_characters;
1901 info.quote_characters = gdb_completer_quote_characters;
1902 info.basic_quote_characters = rl_basic_quote_characters;
1904 return gdb_rl_find_completion_word (&info, quote_char, NULL, text);
1907 /* See completer.h. */
1910 completion_tracker::recompute_lowest_common_denominator
1911 (gdb::unique_xmalloc_ptr<char> &&new_match_up)
1913 if (m_lowest_common_denominator == NULL)
1915 /* We don't have a lowest common denominator yet, so simply take
1916 the whole NEW_MATCH_UP as being it. */
1917 m_lowest_common_denominator = new_match_up.release ();
1918 m_lowest_common_denominator_unique = true;
1922 /* Find the common denominator between the currently-known
1923 lowest common denominator and NEW_MATCH_UP. That becomes the
1924 new lowest common denominator. */
1926 const char *new_match = new_match_up.get ();
1929 (new_match[i] != '\0'
1930 && new_match[i] == m_lowest_common_denominator[i]);
1933 if (m_lowest_common_denominator[i] != new_match[i])
1935 m_lowest_common_denominator[i] = '\0';
1936 m_lowest_common_denominator_unique = false;
1941 /* See completer.h. */
1944 completion_tracker::advance_custom_word_point_by (size_t len)
1946 m_custom_word_point += len;
1949 /* Build a new C string that is a copy of LCD with the whitespace of
1950 ORIG/ORIG_LEN preserved.
1952 Say the user is completing a symbol name, with spaces, like:
1956 and the resulting completion match is:
1960 we want to end up with an input line like:
1963 ^^^^^^^ => text from LCD [1], whitespace from ORIG preserved.
1964 ^^ => new text from LCD
1966 [1] - We must take characters from the LCD instead of the original
1967 text, since some completions want to change upper/lowercase. E.g.:
1973 "handle SIG[QUIT|etc.]"
1977 expand_preserving_ws (const char *orig, size_t orig_len,
1980 const char *p_orig = orig;
1981 const char *orig_end = orig + orig_len;
1982 const char *p_lcd = lcd;
1985 while (p_orig < orig_end)
1989 while (p_orig < orig_end && *p_orig == ' ')
1991 p_lcd = skip_spaces (p_lcd);
1995 /* Take characters from the LCD instead of the original
1996 text, since some completions change upper/lowercase.
2000 "handle SIG[QUIT|etc.]"
2008 while (*p_lcd != '\0')
2011 return xstrdup (res.c_str ());
2014 /* See completer.h. */
2017 completion_tracker::build_completion_result (const char *text,
2020 completion_list &list = m_entries_vec; /* The completions. */
2025 /* +1 for the LCD, and +1 for NULL termination. */
2026 char **match_list = XNEWVEC (char *, 1 + list.size () + 1);
2028 /* Build replacement word, based on the LCD. */
2031 = expand_preserving_ws (text, end - start,
2032 m_lowest_common_denominator);
2034 if (m_lowest_common_denominator_unique)
2036 /* We don't rely on readline appending the quote char as
2037 delimiter as then readline wouldn't append the ' ' after the
2039 char buf[2] = { (char) quote_char () };
2041 match_list[0] = reconcat (match_list[0], match_list[0],
2042 buf, (char *) NULL);
2043 match_list[1] = NULL;
2045 /* If the tracker wants to, or we already have a space at the
2046 end of the match, tell readline to skip appending
2048 bool completion_suppress_append
2049 = (suppress_append_ws ()
2050 || match_list[0][strlen (match_list[0]) - 1] == ' ');
2052 return completion_result (match_list, 1, completion_suppress_append);
2058 for (ix = 0; ix < list.size (); ++ix)
2059 match_list[ix + 1] = list[ix].release ();
2060 match_list[ix + 1] = NULL;
2062 return completion_result (match_list, list.size (), false);
2066 /* See completer.h */
2068 completion_result::completion_result ()
2069 : match_list (NULL), number_matches (0),
2070 completion_suppress_append (false)
2073 /* See completer.h */
2075 completion_result::completion_result (char **match_list_,
2076 size_t number_matches_,
2077 bool completion_suppress_append_)
2078 : match_list (match_list_),
2079 number_matches (number_matches_),
2080 completion_suppress_append (completion_suppress_append_)
2083 /* See completer.h */
2085 completion_result::~completion_result ()
2087 reset_match_list ();
2090 /* See completer.h */
2092 completion_result::completion_result (completion_result &&rhs)
2097 reset_match_list ();
2098 match_list = rhs.match_list;
2099 rhs.match_list = NULL;
2100 number_matches = rhs.number_matches;
2101 rhs.number_matches = 0;
2104 /* See completer.h */
2107 completion_result::release_match_list ()
2109 char **ret = match_list;
2114 /* See completer.h */
2117 completion_result::sort_match_list ()
2119 if (number_matches > 1)
2121 /* Element 0 is special (it's the common prefix), leave it
2123 std::sort (&match_list[1],
2124 &match_list[number_matches + 1],
2129 /* See completer.h */
2132 completion_result::reset_match_list ()
2134 if (match_list != NULL)
2136 for (char **p = match_list; *p != NULL; p++)
2143 /* Helper for gdb_rl_attempted_completion_function, which does most of
2144 the work. This is called by readline to build the match list array
2145 and to determine the lowest common denominator. The real matches
2146 list starts at match[1], while match[0] is the slot holding
2147 readline's idea of the lowest common denominator of all matches,
2148 which is what readline replaces the completion "word" with.
2150 TEXT is the caller's idea of the "word" we are looking at, as
2151 computed in the handle_brkchars phase.
2153 START is the offset from RL_LINE_BUFFER where TEXT starts. END is
2154 the offset from RL_LINE_BUFFER where TEXT ends (i.e., where
2157 You should thus pretend that the line ends at END (relative to
2160 RL_LINE_BUFFER contains the entire text of the line. RL_POINT is
2161 the offset in that line of the cursor. You should pretend that the
2164 Returns NULL if there are no completions. */
2167 gdb_rl_attempted_completion_function_throw (const char *text, int start, int end)
2169 /* Completers that provide a custom word point in the
2170 handle_brkchars phase also compute their completions then.
2171 Completers that leave the completion word handling to readline
2172 must be called twice. If rl_point (i.e., END) is at column 0,
2173 then readline skips the handle_brkchars phase, and so we create a
2174 tracker now in that case too. */
2175 if (end == 0 || !current_completion.tracker->use_custom_word_point ())
2177 delete current_completion.tracker;
2178 current_completion.tracker = new completion_tracker ();
2180 complete_line (*current_completion.tracker, text,
2181 rl_line_buffer, rl_point);
2184 completion_tracker &tracker = *current_completion.tracker;
2186 completion_result result
2187 = tracker.build_completion_result (text, start, end);
2189 rl_completion_suppress_append = result.completion_suppress_append;
2190 return result.release_match_list ();
2193 /* Function installed as "rl_attempted_completion_function" readline
2194 hook. Wrapper around gdb_rl_attempted_completion_function_throw
2195 that catches C++ exceptions, which can't cross readline. */
2198 gdb_rl_attempted_completion_function (const char *text, int start, int end)
2200 /* Restore globals that might have been tweaked in
2201 gdb_completion_word_break_characters. */
2202 rl_basic_quote_characters = gdb_org_rl_basic_quote_characters;
2204 /* If we end up returning NULL, either on error, or simple because
2205 there are no matches, inhibit readline's default filename
2207 rl_attempted_completion_over = 1;
2209 /* If the handle_brkchars phase was aborted, don't try
2211 if (current_completion.aborted)
2216 return gdb_rl_attempted_completion_function_throw (text, start, end);
2218 CATCH (ex, RETURN_MASK_ALL)
2226 /* Skip over the possibly quoted word STR (as defined by the quote
2227 characters QUOTECHARS and the word break characters BREAKCHARS).
2228 Returns pointer to the location after the "word". If either
2229 QUOTECHARS or BREAKCHARS is NULL, use the same values used by the
2233 skip_quoted_chars (const char *str, const char *quotechars,
2234 const char *breakchars)
2236 char quote_char = '\0';
2239 if (quotechars == NULL)
2240 quotechars = gdb_completer_quote_characters;
2242 if (breakchars == NULL)
2243 breakchars = current_language->la_word_break_characters();
2245 for (scan = str; *scan != '\0'; scan++)
2247 if (quote_char != '\0')
2249 /* Ignore everything until the matching close quote char. */
2250 if (*scan == quote_char)
2252 /* Found matching close quote. */
2257 else if (strchr (quotechars, *scan))
2259 /* Found start of a quoted string. */
2262 else if (strchr (breakchars, *scan))
2271 /* Skip over the possibly quoted word STR (as defined by the quote
2272 characters and word break characters used by the completer).
2273 Returns pointer to the location after the "word". */
2276 skip_quoted (const char *str)
2278 return skip_quoted_chars (str, NULL, NULL);
2281 /* Return a message indicating that the maximum number of completions
2282 has been reached and that there may be more. */
2285 get_max_completions_reached_message (void)
2287 return _("*** List may be truncated, max-completions reached. ***");
2290 /* GDB replacement for rl_display_match_list.
2291 Readline doesn't provide a clean interface for TUI(curses).
2292 A hack previously used was to send readline's rl_outstream through a pipe
2293 and read it from the event loop. Bleah. IWBN if readline abstracted
2294 away all the necessary bits, and this is what this code does. It
2295 replicates the parts of readline we need and then adds an abstraction
2296 layer, currently implemented as struct match_list_displayer, so that both
2297 CLI and TUI can use it. We copy all this readline code to minimize
2298 GDB-specific mods to readline. Once this code performs as desired then
2299 we can submit it to the readline maintainers.
2301 N.B. A lot of the code is the way it is in order to minimize differences
2302 from readline's copy. */
2304 /* Not supported here. */
2305 #undef VISIBLE_STATS
2307 #if defined (HANDLE_MULTIBYTE)
2308 #define MB_INVALIDCH(x) ((x) == (size_t)-1 || (x) == (size_t)-2)
2309 #define MB_NULLWCH(x) ((x) == 0)
2312 #define ELLIPSIS_LEN 3
2314 /* gdb version of readline/complete.c:get_y_or_n.
2315 'y' -> returns 1, and 'n' -> returns 0.
2316 Also supported: space == 'y', RUBOUT == 'n', ctrl-g == start over.
2317 If FOR_PAGER is non-zero, then also supported are:
2318 NEWLINE or RETURN -> returns 2, and 'q' -> returns 0. */
2321 gdb_get_y_or_n (int for_pager, const struct match_list_displayer *displayer)
2327 RL_SETSTATE (RL_STATE_MOREINPUT);
2328 c = displayer->read_key (displayer);
2329 RL_UNSETSTATE (RL_STATE_MOREINPUT);
2331 if (c == 'y' || c == 'Y' || c == ' ')
2333 if (c == 'n' || c == 'N' || c == RUBOUT)
2335 if (c == ABORT_CHAR || c < 0)
2337 /* Readline doesn't erase_entire_line here, but without it the
2338 --More-- prompt isn't erased and neither is the text entered
2339 thus far redisplayed. */
2340 displayer->erase_entire_line (displayer);
2341 /* Note: The arguments to rl_abort are ignored. */
2344 if (for_pager && (c == NEWLINE || c == RETURN))
2346 if (for_pager && (c == 'q' || c == 'Q'))
2348 displayer->beep (displayer);
2352 /* Pager function for tab-completion.
2353 This is based on readline/complete.c:_rl_internal_pager.
2354 LINES is the number of lines of output displayed thus far.
2356 -1 -> user pressed 'n' or equivalent,
2357 0 -> user pressed 'y' or equivalent,
2358 N -> user pressed NEWLINE or equivalent and N is LINES - 1. */
2361 gdb_display_match_list_pager (int lines,
2362 const struct match_list_displayer *displayer)
2366 displayer->puts (displayer, "--More--");
2367 displayer->flush (displayer);
2368 i = gdb_get_y_or_n (1, displayer);
2369 displayer->erase_entire_line (displayer);
2378 /* Return non-zero if FILENAME is a directory.
2379 Based on readline/complete.c:path_isdir. */
2382 gdb_path_isdir (const char *filename)
2386 return (stat (filename, &finfo) == 0 && S_ISDIR (finfo.st_mode));
2389 /* Return the portion of PATHNAME that should be output when listing
2390 possible completions. If we are hacking filename completion, we
2391 are only interested in the basename, the portion following the
2392 final slash. Otherwise, we return what we were passed. Since
2393 printing empty strings is not very informative, if we're doing
2394 filename completion, and the basename is the empty string, we look
2395 for the previous slash and return the portion following that. If
2396 there's no previous slash, we just return what we were passed.
2398 Based on readline/complete.c:printable_part. */
2401 gdb_printable_part (char *pathname)
2405 if (rl_filename_completion_desired == 0) /* don't need to do anything */
2408 temp = strrchr (pathname, '/');
2409 #if defined (__MSDOS__)
2410 if (temp == 0 && ISALPHA ((unsigned char)pathname[0]) && pathname[1] == ':')
2411 temp = pathname + 1;
2414 if (temp == 0 || *temp == '\0')
2416 /* If the basename is NULL, we might have a pathname like '/usr/src/'.
2417 Look for a previous slash and, if one is found, return the portion
2418 following that slash. If there's no previous slash, just return the
2419 pathname we were passed. */
2420 else if (temp[1] == '\0')
2422 for (x = temp - 1; x > pathname; x--)
2425 return ((*x == '/') ? x + 1 : pathname);
2431 /* Compute width of STRING when displayed on screen by print_filename.
2432 Based on readline/complete.c:fnwidth. */
2435 gdb_fnwidth (const char *string)
2438 #if defined (HANDLE_MULTIBYTE)
2444 left = strlen (string) + 1;
2445 memset (&ps, 0, sizeof (mbstate_t));
2451 if (CTRL_CHAR (string[pos]) || string[pos] == RUBOUT)
2458 #if defined (HANDLE_MULTIBYTE)
2459 clen = mbrtowc (&wc, string + pos, left - pos, &ps);
2460 if (MB_INVALIDCH (clen))
2464 memset (&ps, 0, sizeof (mbstate_t));
2466 else if (MB_NULLWCH (clen))
2472 width += (w >= 0) ? w : 1;
2484 /* Print TO_PRINT, one matching completion.
2485 PREFIX_BYTES is number of common prefix bytes.
2486 Based on readline/complete.c:fnprint. */
2489 gdb_fnprint (const char *to_print, int prefix_bytes,
2490 const struct match_list_displayer *displayer)
2494 #if defined (HANDLE_MULTIBYTE)
2501 end = to_print + strlen (to_print) + 1;
2502 memset (&ps, 0, sizeof (mbstate_t));
2507 /* Don't print only the ellipsis if the common prefix is one of the
2508 possible completions */
2509 if (to_print[prefix_bytes] == '\0')
2516 ellipsis = (to_print[prefix_bytes] == '.') ? '_' : '.';
2517 for (w = 0; w < ELLIPSIS_LEN; w++)
2518 displayer->putch (displayer, ellipsis);
2519 printed_len = ELLIPSIS_LEN;
2522 s = to_print + prefix_bytes;
2527 displayer->putch (displayer, '^');
2528 displayer->putch (displayer, UNCTRL (*s));
2531 #if defined (HANDLE_MULTIBYTE)
2532 memset (&ps, 0, sizeof (mbstate_t));
2535 else if (*s == RUBOUT)
2537 displayer->putch (displayer, '^');
2538 displayer->putch (displayer, '?');
2541 #if defined (HANDLE_MULTIBYTE)
2542 memset (&ps, 0, sizeof (mbstate_t));
2547 #if defined (HANDLE_MULTIBYTE)
2548 tlen = mbrtowc (&wc, s, end - s, &ps);
2549 if (MB_INVALIDCH (tlen))
2553 memset (&ps, 0, sizeof (mbstate_t));
2555 else if (MB_NULLWCH (tlen))
2560 width = (w >= 0) ? w : 1;
2562 for (w = 0; w < tlen; ++w)
2563 displayer->putch (displayer, s[w]);
2565 printed_len += width;
2567 displayer->putch (displayer, *s);
2577 /* Output TO_PRINT to rl_outstream. If VISIBLE_STATS is defined and we
2578 are using it, check for and output a single character for `special'
2579 filenames. Return the number of characters we output.
2580 Based on readline/complete.c:print_filename. */
2583 gdb_print_filename (char *to_print, char *full_pathname, int prefix_bytes,
2584 const struct match_list_displayer *displayer)
2586 int printed_len, extension_char, slen, tlen;
2587 char *s, c, *new_full_pathname;
2589 extern int _rl_complete_mark_directories;
2592 printed_len = gdb_fnprint (to_print, prefix_bytes, displayer);
2594 #if defined (VISIBLE_STATS)
2595 if (rl_filename_completion_desired && (rl_visible_stats || _rl_complete_mark_directories))
2597 if (rl_filename_completion_desired && _rl_complete_mark_directories)
2600 /* If to_print != full_pathname, to_print is the basename of the
2601 path passed. In this case, we try to expand the directory
2602 name before checking for the stat character. */
2603 if (to_print != full_pathname)
2605 /* Terminate the directory name. */
2607 to_print[-1] = '\0';
2609 /* If setting the last slash in full_pathname to a NUL results in
2610 full_pathname being the empty string, we are trying to complete
2611 files in the root directory. If we pass a null string to the
2612 bash directory completion hook, for example, it will expand it
2613 to the current directory. We just want the `/'. */
2614 if (full_pathname == 0 || *full_pathname == 0)
2616 else if (full_pathname[0] != '/')
2618 else if (full_pathname[1] == 0)
2619 dn = "//"; /* restore trailing slash to `//' */
2620 else if (full_pathname[1] == '/' && full_pathname[2] == 0)
2621 dn = "/"; /* don't turn /// into // */
2624 s = tilde_expand (dn);
2625 if (rl_directory_completion_hook)
2626 (*rl_directory_completion_hook) (&s);
2629 tlen = strlen (to_print);
2630 new_full_pathname = (char *)xmalloc (slen + tlen + 2);
2631 strcpy (new_full_pathname, s);
2632 if (s[slen - 1] == '/')
2635 new_full_pathname[slen] = '/';
2636 new_full_pathname[slen] = '/';
2637 strcpy (new_full_pathname + slen + 1, to_print);
2639 #if defined (VISIBLE_STATS)
2640 if (rl_visible_stats)
2641 extension_char = stat_char (new_full_pathname);
2644 if (gdb_path_isdir (new_full_pathname))
2645 extension_char = '/';
2647 xfree (new_full_pathname);
2652 s = tilde_expand (full_pathname);
2653 #if defined (VISIBLE_STATS)
2654 if (rl_visible_stats)
2655 extension_char = stat_char (s);
2658 if (gdb_path_isdir (s))
2659 extension_char = '/';
2665 displayer->putch (displayer, extension_char);
2673 /* GDB version of readline/complete.c:complete_get_screenwidth. */
2676 gdb_complete_get_screenwidth (const struct match_list_displayer *displayer)
2678 /* Readline has other stuff here which it's not clear we need. */
2679 return displayer->width;
2682 extern int _rl_completion_prefix_display_length;
2683 extern int _rl_print_completions_horizontally;
2685 EXTERN_C int _rl_qsort_string_compare (const void *, const void *);
2686 typedef int QSFUNC (const void *, const void *);
2688 /* GDB version of readline/complete.c:rl_display_match_list.
2689 See gdb_display_match_list for a description of MATCHES, LEN, MAX.
2690 Returns non-zero if all matches are displayed. */
2693 gdb_display_match_list_1 (char **matches, int len, int max,
2694 const struct match_list_displayer *displayer)
2696 int count, limit, printed_len, lines, cols;
2697 int i, j, k, l, common_length, sind;
2699 int page_completions = displayer->height != INT_MAX && pagination_enabled;
2701 /* Find the length of the prefix common to all items: length as displayed
2702 characters (common_length) and as a byte index into the matches (sind) */
2703 common_length = sind = 0;
2704 if (_rl_completion_prefix_display_length > 0)
2706 t = gdb_printable_part (matches[0]);
2707 temp = strrchr (t, '/');
2708 common_length = temp ? gdb_fnwidth (temp) : gdb_fnwidth (t);
2709 sind = temp ? strlen (temp) : strlen (t);
2711 if (common_length > _rl_completion_prefix_display_length && common_length > ELLIPSIS_LEN)
2712 max -= common_length - ELLIPSIS_LEN;
2714 common_length = sind = 0;
2717 /* How many items of MAX length can we fit in the screen window? */
2718 cols = gdb_complete_get_screenwidth (displayer);
2721 if (limit != 1 && (limit * max == cols))
2724 /* If cols == 0, limit will end up -1 */
2725 if (cols < displayer->width && limit < 0)
2728 /* Avoid a possible floating exception. If max > cols,
2729 limit will be 0 and a divide-by-zero fault will result. */
2733 /* How many iterations of the printing loop? */
2734 count = (len + (limit - 1)) / limit;
2736 /* Watch out for special case. If LEN is less than LIMIT, then
2737 just do the inner printing loop.
2738 0 < len <= limit implies count = 1. */
2740 /* Sort the items if they are not already sorted. */
2741 if (rl_ignore_completion_duplicates == 0 && rl_sort_completion_matches)
2742 qsort (matches + 1, len, sizeof (char *), (QSFUNC *)_rl_qsort_string_compare);
2744 displayer->crlf (displayer);
2747 if (_rl_print_completions_horizontally == 0)
2749 /* Print the sorted items, up-and-down alphabetically, like ls. */
2750 for (i = 1; i <= count; i++)
2752 for (j = 0, l = i; j < limit; j++)
2754 if (l > len || matches[l] == 0)
2758 temp = gdb_printable_part (matches[l]);
2759 printed_len = gdb_print_filename (temp, matches[l], sind,
2763 for (k = 0; k < max - printed_len; k++)
2764 displayer->putch (displayer, ' ');
2768 displayer->crlf (displayer);
2770 if (page_completions && lines >= (displayer->height - 1) && i < count)
2772 lines = gdb_display_match_list_pager (lines, displayer);
2780 /* Print the sorted items, across alphabetically, like ls -x. */
2781 for (i = 1; matches[i]; i++)
2783 temp = gdb_printable_part (matches[i]);
2784 printed_len = gdb_print_filename (temp, matches[i], sind, displayer);
2785 /* Have we reached the end of this line? */
2788 if (i && (limit > 1) && (i % limit) == 0)
2790 displayer->crlf (displayer);
2792 if (page_completions && lines >= displayer->height - 1)
2794 lines = gdb_display_match_list_pager (lines, displayer);
2800 for (k = 0; k < max - printed_len; k++)
2801 displayer->putch (displayer, ' ');
2804 displayer->crlf (displayer);
2810 /* Utility for displaying completion list matches, used by both CLI and TUI.
2812 MATCHES is the list of strings, in argv format, LEN is the number of
2813 strings in MATCHES, and MAX is the length of the longest string in
2817 gdb_display_match_list (char **matches, int len, int max,
2818 const struct match_list_displayer *displayer)
2820 /* Readline will never call this if complete_line returned NULL. */
2821 gdb_assert (max_completions != 0);
2823 /* complete_line will never return more than this. */
2824 if (max_completions > 0)
2825 gdb_assert (len <= max_completions);
2827 if (rl_completion_query_items > 0 && len >= rl_completion_query_items)
2831 /* We can't use *query here because they wait for <RET> which is
2832 wrong here. This follows the readline version as closely as possible
2833 for compatibility's sake. See readline/complete.c. */
2835 displayer->crlf (displayer);
2837 xsnprintf (msg, sizeof (msg),
2838 "Display all %d possibilities? (y or n)", len);
2839 displayer->puts (displayer, msg);
2840 displayer->flush (displayer);
2842 if (gdb_get_y_or_n (0, displayer) == 0)
2844 displayer->crlf (displayer);
2849 if (gdb_display_match_list_1 (matches, len, max, displayer))
2851 /* Note: MAX_COMPLETIONS may be -1 or zero, but LEN is always > 0. */
2852 if (len == max_completions)
2854 /* The maximum number of completions has been reached. Warn the user
2855 that there may be more. */
2856 const char *message = get_max_completions_reached_message ();
2858 displayer->puts (displayer, message);
2859 displayer->crlf (displayer);
2865 _initialize_completer (void)
2867 add_setshow_zuinteger_unlimited_cmd ("max-completions", no_class,
2868 &max_completions, _("\
2869 Set maximum number of completion candidates."), _("\
2870 Show maximum number of completion candidates."), _("\
2871 Use this to limit the number of candidates considered\n\
2872 during completion. Specifying \"unlimited\" or -1\n\
2873 disables limiting. Note that setting either no limit or\n\
2874 a very large limit can make completion slow."),
2875 NULL, NULL, &setlist, &showlist);