1 /* Line completion stuff for GDB, the GNU debugger.
2 Copyright (C) 2000-2017 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 "gdb_signals.h"
27 #include "reggroups.h"
28 #include "user-regs.h"
29 #include "arch-utils.h"
32 #include "cli/cli-decode.h"
34 /* FIXME: This is needed because of lookup_cmd_1 (). We should be
35 calling a hook instead so we eliminate the CLI dependency. */
38 /* Needed for rl_completer_word_break_characters() and for
39 rl_filename_completion_function. */
40 #include "readline/readline.h"
42 /* readline defines this. */
45 #include "completer.h"
47 /* Misc state that needs to be tracked across several different
48 readline completer entry point calls, all related to a single
49 completion invocation. */
51 struct gdb_completer_state
53 /* The current completion's completion tracker. This is a global
54 because a tracker can be shared between the handle_brkchars and
55 handle_completion phases, which involves different readline
57 completion_tracker *tracker = NULL;
59 /* Whether the current completion was aborted. */
63 /* The current completion state. */
64 static gdb_completer_state current_completion;
66 /* An enumeration of the various things a user might
67 attempt to complete for a location. */
69 enum explicit_location_match_type
71 /* The filename of a source file. */
74 /* The name of a function or method. */
77 /* The name of a label. */
81 /* Prototypes for local functions. */
83 /* readline uses the word breaks for two things:
84 (1) In figuring out where to point the TEXT parameter to the
85 rl_completion_entry_function. Since we don't use TEXT for much,
86 it doesn't matter a lot what the word breaks are for this purpose,
87 but it does affect how much stuff M-? lists.
88 (2) If one of the matches contains a word break character, readline
89 will quote it. That's why we switch between
90 current_language->la_word_break_characters() and
91 gdb_completer_command_word_break_characters. I'm not sure when
92 we need this behavior (perhaps for funky characters in C++
95 /* Variables which are necessary for fancy command line editing. */
97 /* When completing on command names, we remove '-' from the list of
98 word break characters, since we use it in command names. If the
99 readline library sees one in any of the current completion strings,
100 it thinks that the string needs to be quoted and automatically
101 supplies a leading quote. */
102 static const char gdb_completer_command_word_break_characters[] =
103 " \t\n!@#$%^&*()+=|~`}{[]\"';:?/>.<,";
105 /* When completing on file names, we remove from the list of word
106 break characters any characters that are commonly used in file
107 names, such as '-', '+', '~', etc. Otherwise, readline displays
108 incorrect completion candidates. */
109 /* MS-DOS and MS-Windows use colon as part of the drive spec, and most
110 programs support @foo style response files. */
111 static const char gdb_completer_file_name_break_characters[] =
112 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
118 /* Characters that can be used to quote completion strings. Note that
119 we can't include '"' because the gdb C parser treats such quoted
120 sequences as strings. */
121 static const char gdb_completer_quote_characters[] = "'";
123 /* Accessor for some completer data that may interest other files. */
126 get_gdb_completer_quote_characters (void)
128 return gdb_completer_quote_characters;
131 /* This can be used for functions which don't want to complete on
132 symbols but don't want to complete on anything else either. */
135 noop_completer (struct cmd_list_element *ignore,
136 completion_tracker &tracker,
137 const char *text, const char *prefix)
141 /* Complete on filenames. */
144 filename_completer (struct cmd_list_element *ignore,
145 completion_tracker &tracker,
146 const char *text, const char *word)
149 VEC (char_ptr) *return_val = NULL;
156 p = rl_filename_completion_function (text, subsequent_name);
159 /* We need to set subsequent_name to a non-zero value before the
160 continue line below, because otherwise, if the first file
161 seen by GDB is a backup file whose name ends in a `~', we
162 will loop indefinitely. */
164 /* Like emacs, don't complete on old versions. Especially
165 useful in the "source" command. */
166 if (p[strlen (p) - 1] == '~')
173 /* Return exactly p. */
175 else if (word > text)
177 /* Return some portion of p. */
178 q = (char *) xmalloc (strlen (p) + 5);
179 strcpy (q, p + (word - text));
184 /* Return some of TEXT plus p. */
185 q = (char *) xmalloc (strlen (p) + (text - word) + 5);
186 strncpy (q, word, text - word);
187 q[text - word] = '\0';
191 tracker.add_completion (gdb::unique_xmalloc_ptr<char> (q));
194 /* There is no way to do this just long enough to affect quote
195 inserting without also affecting the next completion. This
196 should be fixed in readline. FIXME. */
197 /* Ensure that readline does the right thing
198 with respect to inserting quotes. */
199 rl_completer_word_break_characters = "";
203 /* The corresponding completer_handle_brkchars
207 filename_completer_handle_brkchars (struct cmd_list_element *ignore,
208 completion_tracker &tracker,
209 const char *text, const char *word)
211 set_rl_completer_word_break_characters
212 (gdb_completer_file_name_break_characters);
215 /* Complete on linespecs, which might be of two possible forms:
221 This is intended to be used in commands that set breakpoints
225 complete_files_symbols (completion_tracker &tracker,
226 const char *text, const char *word)
229 completion_list fn_list;
232 int quoted = *text == '\'' || *text == '"';
233 int quote_char = '\0';
234 const char *colon = NULL;
235 char *file_to_match = NULL;
236 const char *symbol_start = text;
237 const char *orig_text = text;
239 /* Do we have an unquoted colon, as in "break foo.c:bar"? */
240 for (p = text; *p != '\0'; ++p)
242 if (*p == '\\' && p[1] == '\'')
244 else if (*p == '\'' || *p == '"')
248 while (*p != '\0' && *p != quote_found)
250 if (*p == '\\' && p[1] == quote_found)
255 if (*p == quote_found)
258 break; /* Hit the end of text. */
260 #if HAVE_DOS_BASED_FILE_SYSTEM
261 /* If we have a DOS-style absolute file name at the beginning of
262 TEXT, and the colon after the drive letter is the only colon
263 we found, pretend the colon is not there. */
264 else if (p < text + 3 && *p == ':' && p == text + 1 + quoted)
267 else if (*p == ':' && !colon)
270 symbol_start = p + 1;
272 else if (strchr (current_language->la_word_break_characters(), *p))
273 symbol_start = p + 1;
279 /* Where is the file name? */
284 file_to_match = (char *) xmalloc (colon - text + 1);
285 strncpy (file_to_match, text, colon - text);
286 file_to_match[colon - text] = '\0';
287 /* Remove trailing colons and quotes from the file name. */
288 for (s = file_to_match + (colon - text);
291 if (*s == ':' || *s == quote_char)
294 /* If the text includes a colon, they want completion only on a
295 symbol name after the colon. Otherwise, we need to complete on
296 symbols as well as on files. */
299 collect_file_symbol_completion_matches (tracker, symbol_start, word,
301 xfree (file_to_match);
305 size_t text_len = strlen (text);
307 collect_symbol_completion_matches (tracker, symbol_start, word);
308 /* If text includes characters which cannot appear in a file
309 name, they cannot be asking for completion on files. */
311 gdb_completer_file_name_break_characters) == text_len)
312 fn_list = make_source_files_completion_list (text, text);
315 if (!fn_list.empty () && !tracker.have_completions ())
319 /* If we only have file names as possible completion, we should
320 bring them in sync with what rl_complete expects. The
321 problem is that if the user types "break /foo/b TAB", and the
322 possible completions are "/foo/bar" and "/foo/baz"
323 rl_complete expects us to return "bar" and "baz", without the
324 leading directories, as possible completions, because `word'
325 starts at the "b". But we ignore the value of `word' when we
326 call make_source_files_completion_list above (because that
327 would not DTRT when the completion results in both symbols
328 and file names), so make_source_files_completion_list returns
329 the full "/foo/bar" and "/foo/baz" strings. This produces
330 wrong results when, e.g., there's only one possible
331 completion, because rl_complete will prepend "/foo/" to each
332 candidate completion. The loop below removes that leading
334 for (const auto &fn_up: fn_list)
336 char *fn = fn_up.get ();
337 memmove (fn, fn + (word - text), strlen (fn) + 1 - (word - text));
341 tracker.add_completions (std::move (fn_list));
343 if (!tracker.have_completions ())
345 /* No completions at all. As the final resort, try completing
346 on the entire text as a symbol. */
347 collect_symbol_completion_matches (tracker,
352 /* Returns STRING if not NULL, the empty string otherwise. */
355 string_or_empty (const char *string)
357 return string != NULL ? string : "";
360 /* A helper function to collect explicit location matches for the given
361 LOCATION, which is attempting to match on WORD. */
364 collect_explicit_location_matches (completion_tracker &tracker,
365 struct event_location *location,
366 enum explicit_location_match_type what,
369 const struct explicit_location *explicit_loc
370 = get_explicit_location (location);
376 const char *source = string_or_empty (explicit_loc->source_filename);
377 completion_list matches
378 = make_source_files_completion_list (source, word);
379 tracker.add_completions (std::move (matches));
385 const char *function = string_or_empty (explicit_loc->function_name);
386 if (explicit_loc->source_filename != NULL)
388 const char *filename = explicit_loc->source_filename;
390 collect_file_symbol_completion_matches (tracker,
391 function, word, filename);
394 collect_symbol_completion_matches (tracker, function, word);
403 gdb_assert_not_reached ("unhandled explicit_location_match_type");
407 /* A convenience macro to (safely) back up P to the previous word. */
410 backup_text_ptr (const char *p, const char *text)
412 while (p > text && isspace (*p))
414 for (; p > text && !isspace (p[-1]); --p)
420 /* A completer function for explicit locations. This function
421 completes both options ("-source", "-line", etc) and values. */
424 complete_explicit_location (completion_tracker &tracker,
425 struct event_location *location,
426 const char *text, const char *word)
430 /* Find the beginning of the word. This is necessary because
431 we need to know if we are completing an option name or value. We
432 don't get the leading '-' from the completer. */
433 p = backup_text_ptr (word, text);
437 /* Completing on option name. */
438 static const char *const keywords[] =
447 /* Skip over the '-'. */
450 complete_on_enum (tracker, keywords, p, p);
455 /* Completing on value (or unknown). Get the previous word to see what
456 the user is completing on. */
458 const char *new_word, *end;
459 enum explicit_location_match_type what;
460 struct explicit_location *explicit_loc
461 = get_explicit_location (location);
463 /* Backup P to the previous word, which should be the option
464 the user is attempting to complete. */
467 p = backup_text_ptr (p, text);
470 if (strncmp (p, "-source", len) == 0)
473 new_word = explicit_loc->source_filename + offset;
475 else if (strncmp (p, "-function", len) == 0)
477 what = MATCH_FUNCTION;
478 new_word = explicit_loc->function_name + offset;
480 else if (strncmp (p, "-label", len) == 0)
483 new_word = explicit_loc->label_name + offset;
487 /* The user isn't completing on any valid option name,
488 e.g., "break -source foo.c [tab]". */
492 /* If the user hasn't entered a search expression, e.g.,
493 "break -function <TAB><TAB>", new_word will be NULL, but
494 search routines require non-NULL search words. */
495 if (new_word == NULL)
498 /* Now gather matches */
499 collect_explicit_location_matches (tracker, location, what, new_word);
503 /* A completer for locations. */
506 location_completer (struct cmd_list_element *ignore,
507 completion_tracker &tracker,
508 const char *text, const char *word)
510 const char *copy = text;
512 event_location_up location = string_to_explicit_location (©,
515 if (location != NULL)
516 complete_explicit_location (tracker, location.get (),
520 /* This is an address or linespec location.
521 Right now both of these are handled by the (old) linespec
523 complete_files_symbols (tracker, text, word);
527 /* Helper for expression_completer which recursively adds field and
528 method names from TYPE, a struct or union type, to the OUTPUT
532 add_struct_fields (struct type *type, completion_list &output,
533 char *fieldname, int namelen)
536 int computed_type_name = 0;
537 const char *type_name = NULL;
539 type = check_typedef (type);
540 for (i = 0; i < TYPE_NFIELDS (type); ++i)
542 if (i < TYPE_N_BASECLASSES (type))
543 add_struct_fields (TYPE_BASECLASS (type, i),
544 output, fieldname, namelen);
545 else if (TYPE_FIELD_NAME (type, i))
547 if (TYPE_FIELD_NAME (type, i)[0] != '\0')
549 if (! strncmp (TYPE_FIELD_NAME (type, i),
551 output.emplace_back (xstrdup (TYPE_FIELD_NAME (type, i)));
553 else if (TYPE_CODE (TYPE_FIELD_TYPE (type, i)) == TYPE_CODE_UNION)
555 /* Recurse into anonymous unions. */
556 add_struct_fields (TYPE_FIELD_TYPE (type, i),
557 output, fieldname, namelen);
562 for (i = TYPE_NFN_FIELDS (type) - 1; i >= 0; --i)
564 const char *name = TYPE_FN_FIELDLIST_NAME (type, i);
566 if (name && ! strncmp (name, fieldname, namelen))
568 if (!computed_type_name)
570 type_name = type_name_no_tag (type);
571 computed_type_name = 1;
573 /* Omit constructors from the completion list. */
574 if (!type_name || strcmp (type_name, name))
575 output.emplace_back (xstrdup (name));
580 /* Complete on expressions. Often this means completing on symbol
581 names, but some language parsers also have support for completing
585 complete_expression (completion_tracker &tracker,
586 const char *text, const char *word)
588 struct type *type = NULL;
590 enum type_code code = TYPE_CODE_UNDEF;
592 /* Perform a tentative parse of the expression, to see whether a
593 field completion is required. */
597 type = parse_expression_for_completion (text, &fieldname, &code);
599 CATCH (except, RETURN_MASK_ERROR)
605 if (fieldname && type)
609 type = check_typedef (type);
610 if (TYPE_CODE (type) != TYPE_CODE_PTR && !TYPE_IS_REFERENCE (type))
612 type = TYPE_TARGET_TYPE (type);
615 if (TYPE_CODE (type) == TYPE_CODE_UNION
616 || TYPE_CODE (type) == TYPE_CODE_STRUCT)
618 int flen = strlen (fieldname);
619 completion_list result;
621 add_struct_fields (type, result, fieldname, flen);
623 tracker.add_completions (std::move (result));
627 else if (fieldname && code != TYPE_CODE_UNDEF)
629 VEC (char_ptr) *result;
630 struct cleanup *cleanup = make_cleanup (xfree, fieldname);
632 collect_symbol_completion_matches_type (tracker, fieldname, fieldname,
634 do_cleanups (cleanup);
639 complete_files_symbols (tracker, text, word);
642 /* Complete on expressions. Often this means completing on symbol
643 names, but some language parsers also have support for completing
647 expression_completer (struct cmd_list_element *ignore,
648 completion_tracker &tracker,
649 const char *text, const char *word)
651 complete_expression (tracker, text, word);
654 /* See definition in completer.h. */
657 set_rl_completer_word_break_characters (const char *break_chars)
659 rl_completer_word_break_characters = (char *) break_chars;
662 /* See definition in completer.h. */
665 set_gdb_completion_word_break_characters (completer_ftype *fn)
667 const char *break_chars;
669 /* So far we are only interested in differentiating filename
670 completers from everything else. */
671 if (fn == filename_completer)
672 break_chars = gdb_completer_file_name_break_characters;
674 break_chars = gdb_completer_command_word_break_characters;
676 set_rl_completer_word_break_characters (break_chars);
679 /* Complete on symbols. */
682 symbol_completer (struct cmd_list_element *ignore,
683 completion_tracker &tracker,
684 const char *text, const char *word)
686 collect_symbol_completion_matches (tracker, text, word);
689 /* Here are some useful test cases for completion. FIXME: These
690 should be put in the test suite. They should be tested with both
693 "show output-" "radix"
694 "show output" "-radix"
695 "p" ambiguous (commands starting with p--path, print, printf, etc.)
696 "p " ambiguous (all symbols)
697 "info t foo" no completions
698 "info t " no completions
699 "info t" ambiguous ("info target", "info terminal", etc.)
700 "info ajksdlfk" no completions
701 "info ajksdlfk " no completions
703 "info " ambiguous (all info commands)
704 "p \"a" no completions (string constant)
705 "p 'a" ambiguous (all symbols starting with a)
706 "p b-a" ambiguous (all symbols starting with a)
707 "p b-" ambiguous (all symbols)
708 "file Make" "file" (word break hard to screw up here)
709 "file ../gdb.stabs/we" "ird" (needs to not break word at slash)
712 enum complete_line_internal_reason
714 /* Preliminary phase, called by gdb_completion_word_break_characters
715 function, is used to determine the correct set of chars that are
716 word delimiters depending on the current command in line_buffer.
717 No completion list should be generated; the return value should
718 be NULL. This is checked by an assertion. */
721 /* Main phase, called by complete_line function, is used to get the
722 list of possible completions. */
725 /* Special case when completing a 'help' command. In this case,
726 once sub-command completions are exhausted, we simply return
731 /* Helper for complete_line_internal to simplify it. */
734 complete_line_internal_normal_command (completion_tracker &tracker,
735 const char *command, const char *word,
736 const char *cmd_args,
737 complete_line_internal_reason reason,
738 struct cmd_list_element *c)
740 const char *p = cmd_args;
742 if (c->completer == filename_completer)
744 /* Many commands which want to complete on file names accept
745 several file names, as in "run foo bar >>baz". So we don't
746 want to complete the entire text after the command, just the
747 last word. To this end, we need to find the beginning of the
748 file name by starting at `word' and going backwards. */
751 && strchr (gdb_completer_file_name_break_characters,
757 if (reason == handle_brkchars)
759 completer_handle_brkchars_ftype *brkchars_fn;
761 if (c->completer_handle_brkchars != NULL)
762 brkchars_fn = c->completer_handle_brkchars;
766 = (completer_handle_brkchars_func_for_completer
770 brkchars_fn (c, tracker, p, word);
773 if (reason != handle_brkchars && c->completer != NULL)
774 (*c->completer) (c, tracker, p, word);
777 /* Internal function used to handle completions.
780 TEXT is the caller's idea of the "word" we are looking at.
782 LINE_BUFFER is available to be looked at; it contains the entire
783 text of the line. POINT is the offset in that line of the cursor.
784 You should pretend that the line ends at POINT.
786 See complete_line_internal_reason for description of REASON. */
789 complete_line_internal_1 (completion_tracker &tracker,
791 const char *line_buffer, int point,
792 complete_line_internal_reason reason)
796 int ignore_help_classes;
797 /* Pointer within tmp_command which corresponds to text. */
799 struct cmd_list_element *c, *result_list;
801 /* Choose the default set of word break characters to break
802 completions. If we later find out that we are doing completions
803 on command strings (as opposed to strings supplied by the
804 individual command completer functions, which can be any string)
805 then we will switch to the special word break set for command
806 strings, which leaves out the '-' character used in some
808 set_rl_completer_word_break_characters
809 (current_language->la_word_break_characters());
811 /* Decide whether to complete on a list of gdb commands or on
813 tmp_command = (char *) alloca (point + 1);
816 /* The help command should complete help aliases. */
817 ignore_help_classes = reason != handle_help;
819 strncpy (tmp_command, line_buffer, point);
820 tmp_command[point] = '\0';
821 if (reason == handle_brkchars)
823 gdb_assert (text == NULL);
828 /* Since text always contains some number of characters leading up
829 to point, we can find the equivalent position in tmp_command
830 by subtracting that many characters from the end of tmp_command. */
831 word = tmp_command + point - strlen (text);
836 /* An empty line we want to consider ambiguous; that is, it
837 could be any command. */
838 c = CMD_LIST_AMBIGUOUS;
843 c = lookup_cmd_1 (&p, cmdlist, &result_list, ignore_help_classes);
846 /* Move p up to the next interesting thing. */
847 while (*p == ' ' || *p == '\t')
854 /* It is an unrecognized command. So there are no
855 possible completions. */
857 else if (c == CMD_LIST_AMBIGUOUS)
861 /* lookup_cmd_1 advances p up to the first ambiguous thing, but
862 doesn't advance over that thing itself. Do so now. */
864 while (*q && (isalnum (*q) || *q == '-' || *q == '_'))
866 if (q != tmp_command + point)
868 /* There is something beyond the ambiguous
869 command, so there are no possible completions. For
870 example, "info t " or "info t foo" does not complete
871 to anything, because "info t" can be "info target" or
876 /* We're trying to complete on the command which was ambiguous.
877 This we can deal with. */
880 if (reason != handle_brkchars)
881 complete_on_cmdlist (*result_list->prefixlist, tracker, p,
882 word, ignore_help_classes);
886 if (reason != handle_brkchars)
887 complete_on_cmdlist (cmdlist, tracker, p, word,
888 ignore_help_classes);
890 /* Ensure that readline does the right thing with respect to
892 set_rl_completer_word_break_characters
893 (gdb_completer_command_word_break_characters);
898 /* We've recognized a full command. */
900 if (p == tmp_command + point)
902 /* There is no non-whitespace in the line beyond the
905 if (p[-1] == ' ' || p[-1] == '\t')
907 /* The command is followed by whitespace; we need to
908 complete on whatever comes after command. */
911 /* It is a prefix command; what comes after it is
912 a subcommand (e.g. "info "). */
913 if (reason != handle_brkchars)
914 complete_on_cmdlist (*c->prefixlist, tracker, p, word,
915 ignore_help_classes);
917 /* Ensure that readline does the right thing
918 with respect to inserting quotes. */
919 set_rl_completer_word_break_characters
920 (gdb_completer_command_word_break_characters);
922 else if (reason == handle_help)
926 if (reason != handle_brkchars)
927 complete_on_enum (tracker, c->enums, p, word);
928 set_rl_completer_word_break_characters
929 (gdb_completer_command_word_break_characters);
933 /* It is a normal command; what comes after it is
934 completed by the command's completer function. */
935 complete_line_internal_normal_command (tracker,
936 tmp_command, word, p,
942 /* The command is not followed by whitespace; we need to
943 complete on the command itself, e.g. "p" which is a
944 command itself but also can complete to "print", "ptype"
948 /* Find the command we are completing on. */
950 while (q > tmp_command)
952 if (isalnum (q[-1]) || q[-1] == '-' || q[-1] == '_')
958 if (reason != handle_brkchars)
959 complete_on_cmdlist (result_list, tracker, q, word,
960 ignore_help_classes);
962 /* Ensure that readline does the right thing
963 with respect to inserting quotes. */
964 set_rl_completer_word_break_characters
965 (gdb_completer_command_word_break_characters);
968 else if (reason == handle_help)
972 /* There is non-whitespace beyond the command. */
974 if (c->prefixlist && !c->allow_unknown)
976 /* It is an unrecognized subcommand of a prefix command,
977 e.g. "info adsfkdj". */
981 if (reason != handle_brkchars)
982 complete_on_enum (tracker, c->enums, p, word);
986 /* It is a normal command. */
987 complete_line_internal_normal_command (tracker,
988 tmp_command, word, p,
995 /* Wrapper around complete_line_internal_1 to handle
996 MAX_COMPLETIONS_REACHED_ERROR. */
999 complete_line_internal (completion_tracker &tracker,
1001 const char *line_buffer, int point,
1002 complete_line_internal_reason reason)
1006 complete_line_internal_1 (tracker, text, line_buffer, point, reason);
1008 CATCH (except, RETURN_MASK_ERROR)
1010 if (except.error != MAX_COMPLETIONS_REACHED_ERROR)
1011 throw_exception (except);
1015 /* See completer.h. */
1017 int max_completions = 200;
1019 /* Initial size of the table. It automagically grows from here. */
1020 #define INITIAL_COMPLETION_HTAB_SIZE 200
1022 /* See completer.h. */
1024 completion_tracker::completion_tracker ()
1026 m_entries_hash = htab_create_alloc (INITIAL_COMPLETION_HTAB_SIZE,
1027 htab_hash_string, (htab_eq) streq,
1028 NULL, xcalloc, xfree);
1031 /* See completer.h. */
1033 completion_tracker::~completion_tracker ()
1035 xfree (m_lowest_common_denominator);
1036 htab_delete (m_entries_hash);
1039 /* See completer.h. */
1042 completion_tracker::maybe_add_completion (gdb::unique_xmalloc_ptr<char> name)
1046 if (max_completions == 0)
1049 if (htab_elements (m_entries_hash) >= max_completions)
1052 slot = htab_find_slot (m_entries_hash, name.get (), INSERT);
1053 if (*slot == HTAB_EMPTY_ENTRY)
1055 const char *match_for_lcd_str = name.get ();
1057 recompute_lowest_common_denominator (match_for_lcd_str);
1059 *slot = name.get ();
1060 m_entries_vec.push_back (std::move (name));
1066 /* See completer.h. */
1069 completion_tracker::add_completion (gdb::unique_xmalloc_ptr<char> name)
1071 if (!maybe_add_completion (std::move (name)))
1072 throw_error (MAX_COMPLETIONS_REACHED_ERROR, _("Max completions reached."));
1075 /* See completer.h. */
1078 completion_tracker::add_completions (completion_list &&list)
1080 for (auto &candidate : list)
1081 add_completion (std::move (candidate));
1084 /* Generate completions all at once. Does nothing if max_completions
1085 is 0. If max_completions is non-negative, this will collect at
1086 most max_completions strings.
1088 TEXT is the caller's idea of the "word" we are looking at.
1090 LINE_BUFFER is available to be looked at; it contains the entire
1093 POINT is the offset in that line of the cursor. You
1094 should pretend that the line ends at POINT. */
1097 complete_line (completion_tracker &tracker,
1098 const char *text, const char *line_buffer, int point)
1100 if (max_completions == 0)
1102 complete_line_internal (tracker, text, line_buffer, point,
1103 handle_completions);
1106 /* Complete on command names. Used by "help". */
1109 command_completer (struct cmd_list_element *ignore,
1110 completion_tracker &tracker,
1111 const char *text, const char *word)
1113 complete_line_internal (tracker, word, text,
1114 strlen (text), handle_help);
1117 /* The corresponding completer_handle_brkchars implementation. */
1120 command_completer_handle_brkchars (struct cmd_list_element *ignore,
1121 completion_tracker &tracker,
1122 const char *text, const char *word)
1124 set_rl_completer_word_break_characters
1125 (gdb_completer_command_word_break_characters);
1128 /* Complete on signals. */
1131 signal_completer (struct cmd_list_element *ignore,
1132 completion_tracker &tracker,
1133 const char *text, const char *word)
1135 size_t len = strlen (word);
1137 const char *signame;
1139 for (signum = GDB_SIGNAL_FIRST; signum != GDB_SIGNAL_LAST; ++signum)
1141 /* Can't handle this, so skip it. */
1142 if (signum == GDB_SIGNAL_0)
1145 signame = gdb_signal_to_name ((enum gdb_signal) signum);
1147 /* Ignore the unknown signal case. */
1148 if (!signame || strcmp (signame, "?") == 0)
1151 if (strncasecmp (signame, word, len) == 0)
1153 gdb::unique_xmalloc_ptr<char> copy (xstrdup (signame));
1154 tracker.add_completion (std::move (copy));
1159 /* Bit-flags for selecting what the register and/or register-group
1160 completer should complete on. */
1162 enum reg_completer_target
1164 complete_register_names = 0x1,
1165 complete_reggroup_names = 0x2
1167 DEF_ENUM_FLAGS_TYPE (enum reg_completer_target, reg_completer_targets);
1169 /* Complete register names and/or reggroup names based on the value passed
1170 in TARGETS. At least one bit in TARGETS must be set. */
1173 reg_or_group_completer_1 (completion_tracker &tracker,
1174 const char *text, const char *word,
1175 reg_completer_targets targets)
1177 size_t len = strlen (word);
1178 struct gdbarch *gdbarch;
1181 gdb_assert ((targets & (complete_register_names
1182 | complete_reggroup_names)) != 0);
1183 gdbarch = get_current_arch ();
1185 if ((targets & complete_register_names) != 0)
1190 (name = user_reg_map_regnum_to_name (gdbarch, i)) != NULL;
1193 if (*name != '\0' && strncmp (word, name, len) == 0)
1195 gdb::unique_xmalloc_ptr<char> copy (xstrdup (name));
1196 tracker.add_completion (std::move (copy));
1201 if ((targets & complete_reggroup_names) != 0)
1203 struct reggroup *group;
1205 for (group = reggroup_next (gdbarch, NULL);
1207 group = reggroup_next (gdbarch, group))
1209 name = reggroup_name (group);
1210 if (strncmp (word, name, len) == 0)
1212 gdb::unique_xmalloc_ptr<char> copy (xstrdup (name));
1213 tracker.add_completion (std::move (copy));
1219 /* Perform completion on register and reggroup names. */
1222 reg_or_group_completer (struct cmd_list_element *ignore,
1223 completion_tracker &tracker,
1224 const char *text, const char *word)
1226 reg_or_group_completer_1 (tracker, text, word,
1227 (complete_register_names
1228 | complete_reggroup_names));
1231 /* Perform completion on reggroup names. */
1234 reggroup_completer (struct cmd_list_element *ignore,
1235 completion_tracker &tracker,
1236 const char *text, const char *word)
1238 reg_or_group_completer_1 (tracker, text, word,
1239 complete_reggroup_names);
1242 /* The default completer_handle_brkchars implementation. */
1245 default_completer_handle_brkchars (struct cmd_list_element *ignore,
1246 completion_tracker &tracker,
1247 const char *text, const char *word)
1249 set_rl_completer_word_break_characters
1250 (current_language->la_word_break_characters ());
1253 /* See definition in completer.h. */
1255 completer_handle_brkchars_ftype *
1256 completer_handle_brkchars_func_for_completer (completer_ftype *fn)
1258 if (fn == filename_completer)
1259 return filename_completer_handle_brkchars;
1261 if (fn == command_completer)
1262 return command_completer_handle_brkchars;
1264 return default_completer_handle_brkchars;
1267 /* Get the list of chars that are considered as word breaks
1268 for the current command. */
1271 gdb_completion_word_break_characters_throw ()
1273 /* New completion starting. Get rid of the previous tracker and
1275 delete current_completion.tracker;
1276 current_completion.tracker = new completion_tracker ();
1278 completion_tracker &tracker = *current_completion.tracker;
1280 complete_line_internal (tracker, NULL, rl_line_buffer,
1281 rl_point, handle_brkchars);
1283 return rl_completer_word_break_characters;
1287 gdb_completion_word_break_characters ()
1289 /* New completion starting. */
1290 current_completion.aborted = false;
1294 return gdb_completion_word_break_characters_throw ();
1296 CATCH (ex, RETURN_MASK_ALL)
1298 /* Set this to that gdb_rl_attempted_completion_function knows
1300 current_completion.aborted = true;
1307 /* See completer.h. */
1310 completion_tracker::recompute_lowest_common_denominator (const char *new_match)
1312 if (m_lowest_common_denominator == NULL)
1314 /* We don't have a lowest common denominator yet, so simply take
1315 the whole NEW_MATCH as being it. */
1316 m_lowest_common_denominator = xstrdup (new_match);
1317 m_lowest_common_denominator_unique = true;
1321 /* Find the common denominator between the currently-known
1322 lowest common denominator and NEW_MATCH. That becomes the
1323 new lowest common denominator. */
1327 (new_match[i] != '\0'
1328 && new_match[i] == m_lowest_common_denominator[i]);
1331 if (m_lowest_common_denominator[i] != new_match[i])
1333 m_lowest_common_denominator[i] = '\0';
1334 m_lowest_common_denominator_unique = false;
1339 /* Build a new C string that is a copy of LCD with the whitespace of
1340 ORIG/ORIG_LEN preserved.
1342 Say the user is completing a symbol name, with spaces, like:
1346 and the resulting completion match is:
1350 we want to end up with an input line like:
1353 ^^^^^^^ => text from LCD [1], whitespace from ORIG preserved.
1354 ^^ => new text from LCD
1356 [1] - We must take characters from the LCD instead of the original
1357 text, since some completions want to change upper/lowercase. E.g.:
1363 "handle SIG[QUIT|etc.]"
1367 expand_preserving_ws (const char *orig, size_t orig_len,
1370 const char *p_orig = orig;
1371 const char *orig_end = orig + orig_len;
1372 const char *p_lcd = lcd;
1375 while (p_orig < orig_end)
1379 while (p_orig < orig_end && *p_orig == ' ')
1381 p_lcd = skip_spaces_const (p_lcd);
1385 /* Take characters from the LCD instead of the original
1386 text, since some completions change upper/lowercase.
1390 "handle SIG[QUIT|etc.]"
1398 while (*p_lcd != '\0')
1401 return xstrdup (res.c_str ());
1404 /* See completer.h. */
1407 completion_tracker::build_completion_result (const char *text,
1410 completion_list &list = m_entries_vec; /* The completions. */
1415 /* +1 for the LCD, and +1 for NULL termination. */
1416 char **match_list = XNEWVEC (char *, 1 + list.size () + 1);
1418 /* Build replacement word, based on the LCD. */
1421 = expand_preserving_ws (text, end - start,
1422 m_lowest_common_denominator);
1424 if (m_lowest_common_denominator_unique)
1426 match_list[1] = NULL;
1428 /* If we already have a space at the end of the match, tell
1429 readline to skip appending another. */
1430 bool completion_suppress_append
1431 = (match_list[0][strlen (match_list[0]) - 1] == ' ');
1433 return completion_result (match_list, 1, completion_suppress_append);
1439 for (ix = 0; ix < list.size (); ++ix)
1440 match_list[ix + 1] = list[ix].release ();
1441 match_list[ix + 1] = NULL;
1443 return completion_result (match_list, list.size (), false);
1447 /* See completer.h */
1449 completion_result::completion_result ()
1450 : match_list (NULL), number_matches (0),
1451 completion_suppress_append (false)
1454 /* See completer.h */
1456 completion_result::completion_result (char **match_list_,
1457 size_t number_matches_,
1458 bool completion_suppress_append_)
1459 : match_list (match_list_),
1460 number_matches (number_matches_),
1461 completion_suppress_append (completion_suppress_append_)
1464 /* See completer.h */
1466 completion_result::~completion_result ()
1468 reset_match_list ();
1471 /* See completer.h */
1473 completion_result::completion_result (completion_result &&rhs)
1478 reset_match_list ();
1479 match_list = rhs.match_list;
1480 rhs.match_list = NULL;
1481 number_matches = rhs.number_matches;
1482 rhs.number_matches = 0;
1485 /* See completer.h */
1488 completion_result::release_match_list ()
1490 char **ret = match_list;
1495 /* Compare C strings for std::sort. */
1498 compare_cstrings (const char *str1, const char *str2)
1500 return strcmp (str1, str2) < 0;
1503 /* See completer.h */
1506 completion_result::sort_match_list ()
1508 if (number_matches > 1)
1510 /* Element 0 is special (it's the common prefix), leave it
1512 std::sort (&match_list[1],
1513 &match_list[number_matches + 1],
1518 /* See completer.h */
1521 completion_result::reset_match_list ()
1523 if (match_list != NULL)
1525 for (char **p = match_list; *p != NULL; p++)
1532 /* Helper for gdb_rl_attempted_completion_function, which does most of
1533 the work. This is called by readline to build the match list array
1534 and to determine the lowest common denominator. The real matches
1535 list starts at match[1], while match[0] is the slot holding
1536 readline's idea of the lowest common denominator of all matches,
1537 which is what readline replaces the completion "word" with.
1539 TEXT is the caller's idea of the "word" we are looking at, as
1540 computed in the handle_brkchars phase.
1542 START is the offset from RL_LINE_BUFFER where TEXT starts. END is
1543 the offset from RL_LINE_BUFFER where TEXT ends (i.e., where
1546 You should thus pretend that the line ends at END (relative to
1549 RL_LINE_BUFFER contains the entire text of the line. RL_POINT is
1550 the offset in that line of the cursor. You should pretend that the
1553 Returns NULL if there are no completions. */
1556 gdb_rl_attempted_completion_function_throw (const char *text, int start, int end)
1558 /* Completers must be called twice. If rl_point (i.e., END) is at
1559 column 0, then readline skips the the handle_brkchars phase, and
1560 so we create a tracker now in that case too. */
1561 delete current_completion.tracker;
1562 current_completion.tracker = new completion_tracker ();
1564 complete_line (*current_completion.tracker, text,
1565 rl_line_buffer, rl_point);
1567 completion_tracker &tracker = *current_completion.tracker;
1569 completion_result result
1570 = tracker.build_completion_result (text, start, end);
1572 rl_completion_suppress_append = result.completion_suppress_append;
1573 return result.release_match_list ();
1576 /* Function installed as "rl_attempted_completion_function" readline
1577 hook. Wrapper around gdb_rl_attempted_completion_function_throw
1578 that catches C++ exceptions, which can't cross readline. */
1581 gdb_rl_attempted_completion_function (const char *text, int start, int end)
1583 /* If we end up returning NULL, either on error, or simple because
1584 there are no matches, inhibit readline's default filename
1586 rl_attempted_completion_over = 1;
1588 /* If the handle_brkchars phase was aborted, don't try
1590 if (current_completion.aborted)
1595 return gdb_rl_attempted_completion_function_throw (text, start, end);
1597 CATCH (ex, RETURN_MASK_ALL)
1605 /* Skip over the possibly quoted word STR (as defined by the quote
1606 characters QUOTECHARS and the word break characters BREAKCHARS).
1607 Returns pointer to the location after the "word". If either
1608 QUOTECHARS or BREAKCHARS is NULL, use the same values used by the
1612 skip_quoted_chars (const char *str, const char *quotechars,
1613 const char *breakchars)
1615 char quote_char = '\0';
1618 if (quotechars == NULL)
1619 quotechars = gdb_completer_quote_characters;
1621 if (breakchars == NULL)
1622 breakchars = current_language->la_word_break_characters();
1624 for (scan = str; *scan != '\0'; scan++)
1626 if (quote_char != '\0')
1628 /* Ignore everything until the matching close quote char. */
1629 if (*scan == quote_char)
1631 /* Found matching close quote. */
1636 else if (strchr (quotechars, *scan))
1638 /* Found start of a quoted string. */
1641 else if (strchr (breakchars, *scan))
1650 /* Skip over the possibly quoted word STR (as defined by the quote
1651 characters and word break characters used by the completer).
1652 Returns pointer to the location after the "word". */
1655 skip_quoted (const char *str)
1657 return skip_quoted_chars (str, NULL, NULL);
1660 /* Return a message indicating that the maximum number of completions
1661 has been reached and that there may be more. */
1664 get_max_completions_reached_message (void)
1666 return _("*** List may be truncated, max-completions reached. ***");
1669 /* GDB replacement for rl_display_match_list.
1670 Readline doesn't provide a clean interface for TUI(curses).
1671 A hack previously used was to send readline's rl_outstream through a pipe
1672 and read it from the event loop. Bleah. IWBN if readline abstracted
1673 away all the necessary bits, and this is what this code does. It
1674 replicates the parts of readline we need and then adds an abstraction
1675 layer, currently implemented as struct match_list_displayer, so that both
1676 CLI and TUI can use it. We copy all this readline code to minimize
1677 GDB-specific mods to readline. Once this code performs as desired then
1678 we can submit it to the readline maintainers.
1680 N.B. A lot of the code is the way it is in order to minimize differences
1681 from readline's copy. */
1683 /* Not supported here. */
1684 #undef VISIBLE_STATS
1686 #if defined (HANDLE_MULTIBYTE)
1687 #define MB_INVALIDCH(x) ((x) == (size_t)-1 || (x) == (size_t)-2)
1688 #define MB_NULLWCH(x) ((x) == 0)
1691 #define ELLIPSIS_LEN 3
1693 /* gdb version of readline/complete.c:get_y_or_n.
1694 'y' -> returns 1, and 'n' -> returns 0.
1695 Also supported: space == 'y', RUBOUT == 'n', ctrl-g == start over.
1696 If FOR_PAGER is non-zero, then also supported are:
1697 NEWLINE or RETURN -> returns 2, and 'q' -> returns 0. */
1700 gdb_get_y_or_n (int for_pager, const struct match_list_displayer *displayer)
1706 RL_SETSTATE (RL_STATE_MOREINPUT);
1707 c = displayer->read_key (displayer);
1708 RL_UNSETSTATE (RL_STATE_MOREINPUT);
1710 if (c == 'y' || c == 'Y' || c == ' ')
1712 if (c == 'n' || c == 'N' || c == RUBOUT)
1714 if (c == ABORT_CHAR || c < 0)
1716 /* Readline doesn't erase_entire_line here, but without it the
1717 --More-- prompt isn't erased and neither is the text entered
1718 thus far redisplayed. */
1719 displayer->erase_entire_line (displayer);
1720 /* Note: The arguments to rl_abort are ignored. */
1723 if (for_pager && (c == NEWLINE || c == RETURN))
1725 if (for_pager && (c == 'q' || c == 'Q'))
1727 displayer->beep (displayer);
1731 /* Pager function for tab-completion.
1732 This is based on readline/complete.c:_rl_internal_pager.
1733 LINES is the number of lines of output displayed thus far.
1735 -1 -> user pressed 'n' or equivalent,
1736 0 -> user pressed 'y' or equivalent,
1737 N -> user pressed NEWLINE or equivalent and N is LINES - 1. */
1740 gdb_display_match_list_pager (int lines,
1741 const struct match_list_displayer *displayer)
1745 displayer->puts (displayer, "--More--");
1746 displayer->flush (displayer);
1747 i = gdb_get_y_or_n (1, displayer);
1748 displayer->erase_entire_line (displayer);
1757 /* Return non-zero if FILENAME is a directory.
1758 Based on readline/complete.c:path_isdir. */
1761 gdb_path_isdir (const char *filename)
1765 return (stat (filename, &finfo) == 0 && S_ISDIR (finfo.st_mode));
1768 /* Return the portion of PATHNAME that should be output when listing
1769 possible completions. If we are hacking filename completion, we
1770 are only interested in the basename, the portion following the
1771 final slash. Otherwise, we return what we were passed. Since
1772 printing empty strings is not very informative, if we're doing
1773 filename completion, and the basename is the empty string, we look
1774 for the previous slash and return the portion following that. If
1775 there's no previous slash, we just return what we were passed.
1777 Based on readline/complete.c:printable_part. */
1780 gdb_printable_part (char *pathname)
1784 if (rl_filename_completion_desired == 0) /* don't need to do anything */
1787 temp = strrchr (pathname, '/');
1788 #if defined (__MSDOS__)
1789 if (temp == 0 && ISALPHA ((unsigned char)pathname[0]) && pathname[1] == ':')
1790 temp = pathname + 1;
1793 if (temp == 0 || *temp == '\0')
1795 /* If the basename is NULL, we might have a pathname like '/usr/src/'.
1796 Look for a previous slash and, if one is found, return the portion
1797 following that slash. If there's no previous slash, just return the
1798 pathname we were passed. */
1799 else if (temp[1] == '\0')
1801 for (x = temp - 1; x > pathname; x--)
1804 return ((*x == '/') ? x + 1 : pathname);
1810 /* Compute width of STRING when displayed on screen by print_filename.
1811 Based on readline/complete.c:fnwidth. */
1814 gdb_fnwidth (const char *string)
1817 #if defined (HANDLE_MULTIBYTE)
1823 left = strlen (string) + 1;
1824 memset (&ps, 0, sizeof (mbstate_t));
1830 if (CTRL_CHAR (string[pos]) || string[pos] == RUBOUT)
1837 #if defined (HANDLE_MULTIBYTE)
1838 clen = mbrtowc (&wc, string + pos, left - pos, &ps);
1839 if (MB_INVALIDCH (clen))
1843 memset (&ps, 0, sizeof (mbstate_t));
1845 else if (MB_NULLWCH (clen))
1851 width += (w >= 0) ? w : 1;
1863 /* Print TO_PRINT, one matching completion.
1864 PREFIX_BYTES is number of common prefix bytes.
1865 Based on readline/complete.c:fnprint. */
1868 gdb_fnprint (const char *to_print, int prefix_bytes,
1869 const struct match_list_displayer *displayer)
1873 #if defined (HANDLE_MULTIBYTE)
1880 end = to_print + strlen (to_print) + 1;
1881 memset (&ps, 0, sizeof (mbstate_t));
1886 /* Don't print only the ellipsis if the common prefix is one of the
1887 possible completions */
1888 if (to_print[prefix_bytes] == '\0')
1895 ellipsis = (to_print[prefix_bytes] == '.') ? '_' : '.';
1896 for (w = 0; w < ELLIPSIS_LEN; w++)
1897 displayer->putch (displayer, ellipsis);
1898 printed_len = ELLIPSIS_LEN;
1901 s = to_print + prefix_bytes;
1906 displayer->putch (displayer, '^');
1907 displayer->putch (displayer, UNCTRL (*s));
1910 #if defined (HANDLE_MULTIBYTE)
1911 memset (&ps, 0, sizeof (mbstate_t));
1914 else if (*s == RUBOUT)
1916 displayer->putch (displayer, '^');
1917 displayer->putch (displayer, '?');
1920 #if defined (HANDLE_MULTIBYTE)
1921 memset (&ps, 0, sizeof (mbstate_t));
1926 #if defined (HANDLE_MULTIBYTE)
1927 tlen = mbrtowc (&wc, s, end - s, &ps);
1928 if (MB_INVALIDCH (tlen))
1932 memset (&ps, 0, sizeof (mbstate_t));
1934 else if (MB_NULLWCH (tlen))
1939 width = (w >= 0) ? w : 1;
1941 for (w = 0; w < tlen; ++w)
1942 displayer->putch (displayer, s[w]);
1944 printed_len += width;
1946 displayer->putch (displayer, *s);
1956 /* Output TO_PRINT to rl_outstream. If VISIBLE_STATS is defined and we
1957 are using it, check for and output a single character for `special'
1958 filenames. Return the number of characters we output.
1959 Based on readline/complete.c:print_filename. */
1962 gdb_print_filename (char *to_print, char *full_pathname, int prefix_bytes,
1963 const struct match_list_displayer *displayer)
1965 int printed_len, extension_char, slen, tlen;
1966 char *s, c, *new_full_pathname;
1968 extern int _rl_complete_mark_directories;
1971 printed_len = gdb_fnprint (to_print, prefix_bytes, displayer);
1973 #if defined (VISIBLE_STATS)
1974 if (rl_filename_completion_desired && (rl_visible_stats || _rl_complete_mark_directories))
1976 if (rl_filename_completion_desired && _rl_complete_mark_directories)
1979 /* If to_print != full_pathname, to_print is the basename of the
1980 path passed. In this case, we try to expand the directory
1981 name before checking for the stat character. */
1982 if (to_print != full_pathname)
1984 /* Terminate the directory name. */
1986 to_print[-1] = '\0';
1988 /* If setting the last slash in full_pathname to a NUL results in
1989 full_pathname being the empty string, we are trying to complete
1990 files in the root directory. If we pass a null string to the
1991 bash directory completion hook, for example, it will expand it
1992 to the current directory. We just want the `/'. */
1993 if (full_pathname == 0 || *full_pathname == 0)
1995 else if (full_pathname[0] != '/')
1997 else if (full_pathname[1] == 0)
1998 dn = "//"; /* restore trailing slash to `//' */
1999 else if (full_pathname[1] == '/' && full_pathname[2] == 0)
2000 dn = "/"; /* don't turn /// into // */
2003 s = tilde_expand (dn);
2004 if (rl_directory_completion_hook)
2005 (*rl_directory_completion_hook) (&s);
2008 tlen = strlen (to_print);
2009 new_full_pathname = (char *)xmalloc (slen + tlen + 2);
2010 strcpy (new_full_pathname, s);
2011 if (s[slen - 1] == '/')
2014 new_full_pathname[slen] = '/';
2015 new_full_pathname[slen] = '/';
2016 strcpy (new_full_pathname + slen + 1, to_print);
2018 #if defined (VISIBLE_STATS)
2019 if (rl_visible_stats)
2020 extension_char = stat_char (new_full_pathname);
2023 if (gdb_path_isdir (new_full_pathname))
2024 extension_char = '/';
2026 xfree (new_full_pathname);
2031 s = tilde_expand (full_pathname);
2032 #if defined (VISIBLE_STATS)
2033 if (rl_visible_stats)
2034 extension_char = stat_char (s);
2037 if (gdb_path_isdir (s))
2038 extension_char = '/';
2044 displayer->putch (displayer, extension_char);
2052 /* GDB version of readline/complete.c:complete_get_screenwidth. */
2055 gdb_complete_get_screenwidth (const struct match_list_displayer *displayer)
2057 /* Readline has other stuff here which it's not clear we need. */
2058 return displayer->width;
2061 extern int _rl_completion_prefix_display_length;
2062 extern int _rl_print_completions_horizontally;
2064 EXTERN_C int _rl_qsort_string_compare (const void *, const void *);
2065 typedef int QSFUNC (const void *, const void *);
2067 /* GDB version of readline/complete.c:rl_display_match_list.
2068 See gdb_display_match_list for a description of MATCHES, LEN, MAX.
2069 Returns non-zero if all matches are displayed. */
2072 gdb_display_match_list_1 (char **matches, int len, int max,
2073 const struct match_list_displayer *displayer)
2075 int count, limit, printed_len, lines, cols;
2076 int i, j, k, l, common_length, sind;
2078 int page_completions = displayer->height != INT_MAX && pagination_enabled;
2080 /* Find the length of the prefix common to all items: length as displayed
2081 characters (common_length) and as a byte index into the matches (sind) */
2082 common_length = sind = 0;
2083 if (_rl_completion_prefix_display_length > 0)
2085 t = gdb_printable_part (matches[0]);
2086 temp = strrchr (t, '/');
2087 common_length = temp ? gdb_fnwidth (temp) : gdb_fnwidth (t);
2088 sind = temp ? strlen (temp) : strlen (t);
2090 if (common_length > _rl_completion_prefix_display_length && common_length > ELLIPSIS_LEN)
2091 max -= common_length - ELLIPSIS_LEN;
2093 common_length = sind = 0;
2096 /* How many items of MAX length can we fit in the screen window? */
2097 cols = gdb_complete_get_screenwidth (displayer);
2100 if (limit != 1 && (limit * max == cols))
2103 /* If cols == 0, limit will end up -1 */
2104 if (cols < displayer->width && limit < 0)
2107 /* Avoid a possible floating exception. If max > cols,
2108 limit will be 0 and a divide-by-zero fault will result. */
2112 /* How many iterations of the printing loop? */
2113 count = (len + (limit - 1)) / limit;
2115 /* Watch out for special case. If LEN is less than LIMIT, then
2116 just do the inner printing loop.
2117 0 < len <= limit implies count = 1. */
2119 /* Sort the items if they are not already sorted. */
2120 if (rl_ignore_completion_duplicates == 0 && rl_sort_completion_matches)
2121 qsort (matches + 1, len, sizeof (char *), (QSFUNC *)_rl_qsort_string_compare);
2123 displayer->crlf (displayer);
2126 if (_rl_print_completions_horizontally == 0)
2128 /* Print the sorted items, up-and-down alphabetically, like ls. */
2129 for (i = 1; i <= count; i++)
2131 for (j = 0, l = i; j < limit; j++)
2133 if (l > len || matches[l] == 0)
2137 temp = gdb_printable_part (matches[l]);
2138 printed_len = gdb_print_filename (temp, matches[l], sind,
2142 for (k = 0; k < max - printed_len; k++)
2143 displayer->putch (displayer, ' ');
2147 displayer->crlf (displayer);
2149 if (page_completions && lines >= (displayer->height - 1) && i < count)
2151 lines = gdb_display_match_list_pager (lines, displayer);
2159 /* Print the sorted items, across alphabetically, like ls -x. */
2160 for (i = 1; matches[i]; i++)
2162 temp = gdb_printable_part (matches[i]);
2163 printed_len = gdb_print_filename (temp, matches[i], sind, displayer);
2164 /* Have we reached the end of this line? */
2167 if (i && (limit > 1) && (i % limit) == 0)
2169 displayer->crlf (displayer);
2171 if (page_completions && lines >= displayer->height - 1)
2173 lines = gdb_display_match_list_pager (lines, displayer);
2179 for (k = 0; k < max - printed_len; k++)
2180 displayer->putch (displayer, ' ');
2183 displayer->crlf (displayer);
2189 /* Utility for displaying completion list matches, used by both CLI and TUI.
2191 MATCHES is the list of strings, in argv format, LEN is the number of
2192 strings in MATCHES, and MAX is the length of the longest string in
2196 gdb_display_match_list (char **matches, int len, int max,
2197 const struct match_list_displayer *displayer)
2199 /* Readline will never call this if complete_line returned NULL. */
2200 gdb_assert (max_completions != 0);
2202 /* complete_line will never return more than this. */
2203 if (max_completions > 0)
2204 gdb_assert (len <= max_completions);
2206 if (rl_completion_query_items > 0 && len >= rl_completion_query_items)
2210 /* We can't use *query here because they wait for <RET> which is
2211 wrong here. This follows the readline version as closely as possible
2212 for compatibility's sake. See readline/complete.c. */
2214 displayer->crlf (displayer);
2216 xsnprintf (msg, sizeof (msg),
2217 "Display all %d possibilities? (y or n)", len);
2218 displayer->puts (displayer, msg);
2219 displayer->flush (displayer);
2221 if (gdb_get_y_or_n (0, displayer) == 0)
2223 displayer->crlf (displayer);
2228 if (gdb_display_match_list_1 (matches, len, max, displayer))
2230 /* Note: MAX_COMPLETIONS may be -1 or zero, but LEN is always > 0. */
2231 if (len == max_completions)
2233 /* The maximum number of completions has been reached. Warn the user
2234 that there may be more. */
2235 const char *message = get_max_completions_reached_message ();
2237 displayer->puts (displayer, message);
2238 displayer->crlf (displayer);
2243 extern initialize_file_ftype _initialize_completer; /* -Wmissing-prototypes */
2246 _initialize_completer (void)
2248 add_setshow_zuinteger_unlimited_cmd ("max-completions", no_class,
2249 &max_completions, _("\
2250 Set maximum number of completion candidates."), _("\
2251 Show maximum number of completion candidates."), _("\
2252 Use this to limit the number of candidates considered\n\
2253 during completion. Specifying \"unlimited\" or -1\n\
2254 disables limiting. Note that setting either no limit or\n\
2255 a very large limit can make completion slow."),
2256 NULL, NULL, &setlist, &showlist);