s390: Fix build when using EXEEXT_FOR_BUILD
[binutils-gdb.git] / gdb / completer.c
blobd69ddcceca9ce5940e5fce136f10529228d7917d
1 /* Line completion stuff for GDB, the GNU debugger.
2 Copyright (C) 2000-2023 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/>. */
19 #include "defs.h"
20 #include "symtab.h"
21 #include "gdbtypes.h"
22 #include "expression.h"
23 #include "filenames.h"
24 #include "language.h"
25 #include "gdbsupport/gdb_signals.h"
26 #include "target.h"
27 #include "reggroups.h"
28 #include "user-regs.h"
29 #include "arch-utils.h"
30 #include "location.h"
31 #include <algorithm>
32 #include "linespec.h"
33 #include "cli/cli-decode.h"
35 /* FIXME: This is needed because of lookup_cmd_1 (). We should be
36 calling a hook instead so we eliminate the CLI dependency. */
37 #include "gdbcmd.h"
39 /* Needed for rl_completer_word_break_characters and for
40 rl_filename_completion_function. */
41 #include "readline/readline.h"
43 /* readline defines this. */
44 #undef savestring
46 #include "completer.h"
48 /* See completer.h. */
50 class completion_tracker::completion_hash_entry
52 public:
53 /* Constructor. */
54 completion_hash_entry (gdb::unique_xmalloc_ptr<char> name,
55 gdb::unique_xmalloc_ptr<char> lcd)
56 : m_name (std::move (name)),
57 m_lcd (std::move (lcd))
59 /* Nothing. */
62 /* Returns a pointer to the lowest common denominator string. This
63 string will only be valid while this hash entry is still valid as the
64 string continues to be owned by this hash entry and will be released
65 when this entry is deleted. */
66 char *get_lcd () const
68 return m_lcd.get ();
71 /* Get, and release the name field from this hash entry. This can only
72 be called once, after which the name field is no longer valid. This
73 should be used to pass ownership of the name to someone else. */
74 char *release_name ()
76 return m_name.release ();
79 /* Return true of the name in this hash entry is STR. */
80 bool is_name_eq (const char *str) const
82 return strcmp (m_name.get (), str) == 0;
85 /* Return the hash value based on the name of the entry. */
86 hashval_t hash_name () const
88 return htab_hash_string (m_name.get ());
91 private:
93 /* The symbol name stored in this hash entry. */
94 gdb::unique_xmalloc_ptr<char> m_name;
96 /* The lowest common denominator string computed for this hash entry. */
97 gdb::unique_xmalloc_ptr<char> m_lcd;
100 /* Misc state that needs to be tracked across several different
101 readline completer entry point calls, all related to a single
102 completion invocation. */
104 struct gdb_completer_state
106 /* The current completion's completion tracker. This is a global
107 because a tracker can be shared between the handle_brkchars and
108 handle_completion phases, which involves different readline
109 callbacks. */
110 completion_tracker *tracker = NULL;
112 /* Whether the current completion was aborted. */
113 bool aborted = false;
116 /* The current completion state. */
117 static gdb_completer_state current_completion;
119 /* An enumeration of the various things a user might attempt to
120 complete for a location. If you change this, remember to update
121 the explicit_options array below too. */
123 enum explicit_location_match_type
125 /* The filename of a source file. */
126 MATCH_SOURCE,
128 /* The name of a function or method. */
129 MATCH_FUNCTION,
131 /* The fully-qualified name of a function or method. */
132 MATCH_QUALIFIED,
134 /* A line number. */
135 MATCH_LINE,
137 /* The name of a label. */
138 MATCH_LABEL
141 /* Prototypes for local functions. */
143 /* readline uses the word breaks for two things:
144 (1) In figuring out where to point the TEXT parameter to the
145 rl_completion_entry_function. Since we don't use TEXT for much,
146 it doesn't matter a lot what the word breaks are for this purpose,
147 but it does affect how much stuff M-? lists.
148 (2) If one of the matches contains a word break character, readline
149 will quote it. That's why we switch between
150 current_language->word_break_characters () and
151 gdb_completer_command_word_break_characters. I'm not sure when
152 we need this behavior (perhaps for funky characters in C++
153 symbols?). */
155 /* Variables which are necessary for fancy command line editing. */
157 /* When completing on command names, we remove '-' and '.' from the list of
158 word break characters, since we use it in command names. If the
159 readline library sees one in any of the current completion strings,
160 it thinks that the string needs to be quoted and automatically
161 supplies a leading quote. */
162 static const char gdb_completer_command_word_break_characters[] =
163 " \t\n!@#$%^&*()+=|~`}{[]\"';:?/><,";
165 /* When completing on file names, we remove from the list of word
166 break characters any characters that are commonly used in file
167 names, such as '-', '+', '~', etc. Otherwise, readline displays
168 incorrect completion candidates. */
169 /* MS-DOS and MS-Windows use colon as part of the drive spec, and most
170 programs support @foo style response files. */
171 static const char gdb_completer_file_name_break_characters[] =
172 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
173 " \t\n*|\"';?><@";
174 #else
175 " \t\n*|\"';:?><";
176 #endif
178 /* Characters that can be used to quote completion strings. Note that
179 we can't include '"' because the gdb C parser treats such quoted
180 sequences as strings. */
181 static const char gdb_completer_quote_characters[] = "'";
183 /* Accessor for some completer data that may interest other files. */
185 const char *
186 get_gdb_completer_quote_characters (void)
188 return gdb_completer_quote_characters;
191 /* This can be used for functions which don't want to complete on
192 symbols but don't want to complete on anything else either. */
194 void
195 noop_completer (struct cmd_list_element *ignore,
196 completion_tracker &tracker,
197 const char *text, const char *prefix)
201 /* Complete on filenames. */
203 void
204 filename_completer (struct cmd_list_element *ignore,
205 completion_tracker &tracker,
206 const char *text, const char *word)
208 int subsequent_name;
210 subsequent_name = 0;
211 while (1)
213 gdb::unique_xmalloc_ptr<char> p_rl
214 (rl_filename_completion_function (text, subsequent_name));
215 if (p_rl == NULL)
216 break;
217 /* We need to set subsequent_name to a non-zero value before the
218 continue line below, because otherwise, if the first file
219 seen by GDB is a backup file whose name ends in a `~', we
220 will loop indefinitely. */
221 subsequent_name = 1;
222 /* Like emacs, don't complete on old versions. Especially
223 useful in the "source" command. */
224 const char *p = p_rl.get ();
225 if (p[strlen (p) - 1] == '~')
226 continue;
228 tracker.add_completion
229 (make_completion_match_str (std::move (p_rl), text, word));
231 #if 0
232 /* There is no way to do this just long enough to affect quote
233 inserting without also affecting the next completion. This
234 should be fixed in readline. FIXME. */
235 /* Ensure that readline does the right thing
236 with respect to inserting quotes. */
237 rl_completer_word_break_characters = "";
238 #endif
241 /* The corresponding completer_handle_brkchars
242 implementation. */
244 static void
245 filename_completer_handle_brkchars (struct cmd_list_element *ignore,
246 completion_tracker &tracker,
247 const char *text, const char *word)
249 set_rl_completer_word_break_characters
250 (gdb_completer_file_name_break_characters);
253 /* Find the bounds of the current word for completion purposes, and
254 return a pointer to the end of the word. This mimics (and is a
255 modified version of) readline's _rl_find_completion_word internal
256 function.
258 This function skips quoted substrings (characters between matched
259 pairs of characters in rl_completer_quote_characters). We try to
260 find an unclosed quoted substring on which to do matching. If one
261 is not found, we use the word break characters to find the
262 boundaries of the current word. QC, if non-null, is set to the
263 opening quote character if we found an unclosed quoted substring,
264 '\0' otherwise. DP, if non-null, is set to the value of the
265 delimiter character that caused a word break. */
267 struct gdb_rl_completion_word_info
269 const char *word_break_characters;
270 const char *quote_characters;
271 const char *basic_quote_characters;
274 static const char *
275 gdb_rl_find_completion_word (struct gdb_rl_completion_word_info *info,
276 int *qc, int *dp,
277 const char *line_buffer)
279 int scan, end, delimiter, pass_next, isbrk;
280 char quote_char;
281 const char *brkchars;
282 int point = strlen (line_buffer);
284 /* The algorithm below does '--point'. Avoid buffer underflow with
285 the empty string. */
286 if (point == 0)
288 if (qc != NULL)
289 *qc = '\0';
290 if (dp != NULL)
291 *dp = '\0';
292 return line_buffer;
295 end = point;
296 delimiter = 0;
297 quote_char = '\0';
299 brkchars = info->word_break_characters;
301 if (info->quote_characters != NULL)
303 /* We have a list of characters which can be used in pairs to
304 quote substrings for the completer. Try to find the start of
305 an unclosed quoted substring. */
306 for (scan = pass_next = 0;
307 scan < end;
308 scan++)
310 if (pass_next)
312 pass_next = 0;
313 continue;
316 /* Shell-like semantics for single quotes -- don't allow
317 backslash to quote anything in single quotes, especially
318 not the closing quote. If you don't like this, take out
319 the check on the value of quote_char. */
320 if (quote_char != '\'' && line_buffer[scan] == '\\')
322 pass_next = 1;
323 continue;
326 if (quote_char != '\0')
328 /* Ignore everything until the matching close quote
329 char. */
330 if (line_buffer[scan] == quote_char)
332 /* Found matching close. Abandon this
333 substring. */
334 quote_char = '\0';
335 point = end;
338 else if (strchr (info->quote_characters, line_buffer[scan]))
340 /* Found start of a quoted substring. */
341 quote_char = line_buffer[scan];
342 point = scan + 1;
347 if (point == end && quote_char == '\0')
349 /* We didn't find an unclosed quoted substring upon which to do
350 completion, so use the word break characters to find the
351 substring on which to complete. */
352 while (--point)
354 scan = line_buffer[point];
356 if (strchr (brkchars, scan) != 0)
357 break;
361 /* If we are at an unquoted word break, then advance past it. */
362 scan = line_buffer[point];
364 if (scan)
366 isbrk = strchr (brkchars, scan) != 0;
368 if (isbrk)
370 /* If the character that caused the word break was a quoting
371 character, then remember it as the delimiter. */
372 if (info->basic_quote_characters
373 && strchr (info->basic_quote_characters, scan)
374 && (end - point) > 1)
375 delimiter = scan;
377 point++;
381 if (qc != NULL)
382 *qc = quote_char;
383 if (dp != NULL)
384 *dp = delimiter;
386 return line_buffer + point;
389 /* Find the completion word point for TEXT, emulating the algorithm
390 readline uses to find the word point, using WORD_BREAK_CHARACTERS
391 as word break characters. */
393 static const char *
394 advance_to_completion_word (completion_tracker &tracker,
395 const char *word_break_characters,
396 const char *text)
398 gdb_rl_completion_word_info info;
400 info.word_break_characters = word_break_characters;
401 info.quote_characters = gdb_completer_quote_characters;
402 info.basic_quote_characters = rl_basic_quote_characters;
404 int delimiter;
405 const char *start
406 = gdb_rl_find_completion_word (&info, NULL, &delimiter, text);
408 tracker.advance_custom_word_point_by (start - text);
410 if (delimiter)
412 tracker.set_quote_char (delimiter);
413 tracker.set_suppress_append_ws (true);
416 return start;
419 /* See completer.h. */
421 const char *
422 advance_to_expression_complete_word_point (completion_tracker &tracker,
423 const char *text)
425 const char *brk_chars = current_language->word_break_characters ();
426 return advance_to_completion_word (tracker, brk_chars, text);
429 /* See completer.h. */
431 const char *
432 advance_to_filename_complete_word_point (completion_tracker &tracker,
433 const char *text)
435 const char *brk_chars = gdb_completer_file_name_break_characters;
436 return advance_to_completion_word (tracker, brk_chars, text);
439 /* See completer.h. */
441 bool
442 completion_tracker::completes_to_completion_word (const char *word)
444 recompute_lowest_common_denominator ();
445 if (m_lowest_common_denominator_unique)
447 const char *lcd = m_lowest_common_denominator;
449 if (strncmp_iw (word, lcd, strlen (lcd)) == 0)
451 /* Maybe skip the function and complete on keywords. */
452 size_t wordlen = strlen (word);
453 if (word[wordlen - 1] == ' ')
454 return true;
458 return false;
461 /* See completer.h. */
463 void
464 complete_nested_command_line (completion_tracker &tracker, const char *text)
466 /* Must be called from a custom-word-point completer. */
467 gdb_assert (tracker.use_custom_word_point ());
469 /* Disable the custom word point temporarily, because we want to
470 probe whether the command we're completing itself uses a custom
471 word point. */
472 tracker.set_use_custom_word_point (false);
473 size_t save_custom_word_point = tracker.custom_word_point ();
475 int quote_char = '\0';
476 const char *word = completion_find_completion_word (tracker, text,
477 &quote_char);
479 if (tracker.use_custom_word_point ())
481 /* The command we're completing uses a custom word point, so the
482 tracker already contains the matches. We're done. */
483 return;
486 /* Restore the custom word point settings. */
487 tracker.set_custom_word_point (save_custom_word_point);
488 tracker.set_use_custom_word_point (true);
490 /* Run the handle_completions completer phase. */
491 complete_line (tracker, word, text, strlen (text));
494 /* Complete on linespecs, which might be of two possible forms:
496 file:line
498 symbol+offset
500 This is intended to be used in commands that set breakpoints
501 etc. */
503 static void
504 complete_files_symbols (completion_tracker &tracker,
505 const char *text, const char *word)
507 completion_list fn_list;
508 const char *p;
509 int quote_found = 0;
510 int quoted = *text == '\'' || *text == '"';
511 int quote_char = '\0';
512 const char *colon = NULL;
513 char *file_to_match = NULL;
514 const char *symbol_start = text;
515 const char *orig_text = text;
517 /* Do we have an unquoted colon, as in "break foo.c:bar"? */
518 for (p = text; *p != '\0'; ++p)
520 if (*p == '\\' && p[1] == '\'')
521 p++;
522 else if (*p == '\'' || *p == '"')
524 quote_found = *p;
525 quote_char = *p++;
526 while (*p != '\0' && *p != quote_found)
528 if (*p == '\\' && p[1] == quote_found)
529 p++;
530 p++;
533 if (*p == quote_found)
534 quote_found = 0;
535 else
536 break; /* Hit the end of text. */
538 #if HAVE_DOS_BASED_FILE_SYSTEM
539 /* If we have a DOS-style absolute file name at the beginning of
540 TEXT, and the colon after the drive letter is the only colon
541 we found, pretend the colon is not there. */
542 else if (p < text + 3 && *p == ':' && p == text + 1 + quoted)
544 #endif
545 else if (*p == ':' && !colon)
547 colon = p;
548 symbol_start = p + 1;
550 else if (strchr (current_language->word_break_characters (), *p))
551 symbol_start = p + 1;
554 if (quoted)
555 text++;
557 /* Where is the file name? */
558 if (colon)
560 char *s;
562 file_to_match = (char *) xmalloc (colon - text + 1);
563 strncpy (file_to_match, text, colon - text);
564 file_to_match[colon - text] = '\0';
565 /* Remove trailing colons and quotes from the file name. */
566 for (s = file_to_match + (colon - text);
567 s > file_to_match;
568 s--)
569 if (*s == ':' || *s == quote_char)
570 *s = '\0';
572 /* If the text includes a colon, they want completion only on a
573 symbol name after the colon. Otherwise, we need to complete on
574 symbols as well as on files. */
575 if (colon)
577 collect_file_symbol_completion_matches (tracker,
578 complete_symbol_mode::EXPRESSION,
579 symbol_name_match_type::EXPRESSION,
580 symbol_start, word,
581 file_to_match);
582 xfree (file_to_match);
584 else
586 size_t text_len = strlen (text);
588 collect_symbol_completion_matches (tracker,
589 complete_symbol_mode::EXPRESSION,
590 symbol_name_match_type::EXPRESSION,
591 symbol_start, word);
592 /* If text includes characters which cannot appear in a file
593 name, they cannot be asking for completion on files. */
594 if (strcspn (text,
595 gdb_completer_file_name_break_characters) == text_len)
596 fn_list = make_source_files_completion_list (text, text);
599 if (!fn_list.empty () && !tracker.have_completions ())
601 /* If we only have file names as possible completion, we should
602 bring them in sync with what rl_complete expects. The
603 problem is that if the user types "break /foo/b TAB", and the
604 possible completions are "/foo/bar" and "/foo/baz"
605 rl_complete expects us to return "bar" and "baz", without the
606 leading directories, as possible completions, because `word'
607 starts at the "b". But we ignore the value of `word' when we
608 call make_source_files_completion_list above (because that
609 would not DTRT when the completion results in both symbols
610 and file names), so make_source_files_completion_list returns
611 the full "/foo/bar" and "/foo/baz" strings. This produces
612 wrong results when, e.g., there's only one possible
613 completion, because rl_complete will prepend "/foo/" to each
614 candidate completion. The loop below removes that leading
615 part. */
616 for (const auto &fn_up: fn_list)
618 char *fn = fn_up.get ();
619 memmove (fn, fn + (word - text), strlen (fn) + 1 - (word - text));
623 tracker.add_completions (std::move (fn_list));
625 if (!tracker.have_completions ())
627 /* No completions at all. As the final resort, try completing
628 on the entire text as a symbol. */
629 collect_symbol_completion_matches (tracker,
630 complete_symbol_mode::EXPRESSION,
631 symbol_name_match_type::EXPRESSION,
632 orig_text, word);
636 /* See completer.h. */
638 completion_list
639 complete_source_filenames (const char *text)
641 size_t text_len = strlen (text);
643 /* If text includes characters which cannot appear in a file name,
644 the user cannot be asking for completion on files. */
645 if (strcspn (text,
646 gdb_completer_file_name_break_characters)
647 == text_len)
648 return make_source_files_completion_list (text, text);
650 return {};
653 /* Complete address and linespec locations. */
655 static void
656 complete_address_and_linespec_locations (completion_tracker &tracker,
657 const char *text,
658 symbol_name_match_type match_type)
660 if (*text == '*')
662 tracker.advance_custom_word_point_by (1);
663 text++;
664 const char *word
665 = advance_to_expression_complete_word_point (tracker, text);
666 complete_expression (tracker, text, word);
668 else
670 linespec_complete (tracker, text, match_type);
674 /* The explicit location options. Note that indexes into this array
675 must match the explicit_location_match_type enumerators. */
677 static const char *const explicit_options[] =
679 "-source",
680 "-function",
681 "-qualified",
682 "-line",
683 "-label",
684 NULL
687 /* The probe modifier options. These can appear before a location in
688 breakpoint commands. */
689 static const char *const probe_options[] =
691 "-probe",
692 "-probe-stap",
693 "-probe-dtrace",
694 NULL
697 /* Returns STRING if not NULL, the empty string otherwise. */
699 static const char *
700 string_or_empty (const char *string)
702 return string != NULL ? string : "";
705 /* A helper function to collect explicit location matches for the given
706 LOCATION, which is attempting to match on WORD. */
708 static void
709 collect_explicit_location_matches (completion_tracker &tracker,
710 location_spec *locspec,
711 enum explicit_location_match_type what,
712 const char *word,
713 const struct language_defn *language)
715 const explicit_location_spec *explicit_loc
716 = as_explicit_location_spec (locspec);
718 /* True if the option expects an argument. */
719 bool needs_arg = true;
721 /* Note, in the various MATCH_* below, we complete on
722 explicit_loc->foo instead of WORD, because only the former will
723 have already skipped past any quote char. */
724 switch (what)
726 case MATCH_SOURCE:
728 const char *source
729 = string_or_empty (explicit_loc->source_filename.get ());
730 completion_list matches
731 = make_source_files_completion_list (source, source);
732 tracker.add_completions (std::move (matches));
734 break;
736 case MATCH_FUNCTION:
738 const char *function
739 = string_or_empty (explicit_loc->function_name.get ());
740 linespec_complete_function (tracker, function,
741 explicit_loc->func_name_match_type,
742 explicit_loc->source_filename.get ());
744 break;
746 case MATCH_QUALIFIED:
747 needs_arg = false;
748 break;
749 case MATCH_LINE:
750 /* Nothing to offer. */
751 break;
753 case MATCH_LABEL:
755 const char *label = string_or_empty (explicit_loc->label_name.get ());
756 linespec_complete_label (tracker, language,
757 explicit_loc->source_filename.get (),
758 explicit_loc->function_name.get (),
759 explicit_loc->func_name_match_type,
760 label);
762 break;
764 default:
765 gdb_assert_not_reached ("unhandled explicit_location_match_type");
768 if (!needs_arg || tracker.completes_to_completion_word (word))
770 tracker.discard_completions ();
771 tracker.advance_custom_word_point_by (strlen (word));
772 complete_on_enum (tracker, explicit_options, "", "");
773 complete_on_enum (tracker, linespec_keywords, "", "");
775 else if (!tracker.have_completions ())
777 /* Maybe we have an unterminated linespec keyword at the tail of
778 the string. Try completing on that. */
779 size_t wordlen = strlen (word);
780 const char *keyword = word + wordlen;
782 if (wordlen > 0 && keyword[-1] != ' ')
784 while (keyword > word && *keyword != ' ')
785 keyword--;
786 /* Don't complete on keywords if we'd be completing on the
787 whole explicit linespec option. E.g., "b -function
788 thr<tab>" should not complete to the "thread"
789 keyword. */
790 if (keyword != word)
792 keyword = skip_spaces (keyword);
794 tracker.advance_custom_word_point_by (keyword - word);
795 complete_on_enum (tracker, linespec_keywords, keyword, keyword);
798 else if (wordlen > 0 && keyword[-1] == ' ')
800 /* Assume that we're maybe past the explicit location
801 argument, and we didn't manage to find any match because
802 the user wants to create a pending breakpoint. Offer the
803 keyword and explicit location options as possible
804 completions. */
805 tracker.advance_custom_word_point_by (keyword - word);
806 complete_on_enum (tracker, linespec_keywords, keyword, keyword);
807 complete_on_enum (tracker, explicit_options, keyword, keyword);
812 /* If the next word in *TEXT_P is any of the keywords in KEYWORDS,
813 then advance both TEXT_P and the word point in the tracker past the
814 keyword and return the (0-based) index in the KEYWORDS array that
815 matched. Otherwise, return -1. */
817 static int
818 skip_keyword (completion_tracker &tracker,
819 const char * const *keywords, const char **text_p)
821 const char *text = *text_p;
822 const char *after = skip_to_space (text);
823 size_t len = after - text;
825 if (text[len] != ' ')
826 return -1;
828 int found = -1;
829 for (int i = 0; keywords[i] != NULL; i++)
831 if (strncmp (keywords[i], text, len) == 0)
833 if (found == -1)
834 found = i;
835 else
836 return -1;
840 if (found != -1)
842 tracker.advance_custom_word_point_by (len + 1);
843 text += len + 1;
844 *text_p = text;
845 return found;
848 return -1;
851 /* A completer function for explicit location specs. This function
852 completes both options ("-source", "-line", etc) and values. If
853 completing a quoted string, then QUOTED_ARG_START and
854 QUOTED_ARG_END point to the quote characters. LANGUAGE is the
855 current language. */
857 static void
858 complete_explicit_location_spec (completion_tracker &tracker,
859 location_spec *locspec,
860 const char *text,
861 const language_defn *language,
862 const char *quoted_arg_start,
863 const char *quoted_arg_end)
865 if (*text != '-')
866 return;
868 int keyword = skip_keyword (tracker, explicit_options, &text);
870 if (keyword == -1)
872 complete_on_enum (tracker, explicit_options, text, text);
873 /* There are keywords that start with "-". Include them, too. */
874 complete_on_enum (tracker, linespec_keywords, text, text);
876 else
878 /* Completing on value. */
879 enum explicit_location_match_type what
880 = (explicit_location_match_type) keyword;
882 if (quoted_arg_start != NULL && quoted_arg_end != NULL)
884 if (quoted_arg_end[1] == '\0')
886 /* If completing a quoted string with the cursor right
887 at the terminating quote char, complete the
888 completion word without interpretation, so that
889 readline advances the cursor one whitespace past the
890 quote, even if there's no match. This makes these
891 cases behave the same:
893 before: "b -function function()"
894 after: "b -function function() "
896 before: "b -function 'function()'"
897 after: "b -function 'function()' "
899 and trusts the user in this case:
901 before: "b -function 'not_loaded_function_yet()'"
902 after: "b -function 'not_loaded_function_yet()' "
904 tracker.add_completion (make_unique_xstrdup (text));
906 else if (quoted_arg_end[1] == ' ')
908 /* We're maybe past the explicit location argument.
909 Skip the argument without interpretation, assuming the
910 user may want to create pending breakpoint. Offer
911 the keyword and explicit location options as possible
912 completions. */
913 tracker.advance_custom_word_point_by (strlen (text));
914 complete_on_enum (tracker, linespec_keywords, "", "");
915 complete_on_enum (tracker, explicit_options, "", "");
917 return;
920 /* Now gather matches */
921 collect_explicit_location_matches (tracker, locspec, what, text,
922 language);
926 /* A completer for locations. */
928 void
929 location_completer (struct cmd_list_element *ignore,
930 completion_tracker &tracker,
931 const char *text, const char * /* word */)
933 int found_probe_option = -1;
935 /* If we have a probe modifier, skip it. This can only appear as
936 first argument. Until we have a specific completer for probes,
937 falling back to the linespec completer for the remainder of the
938 line is better than nothing. */
939 if (text[0] == '-' && text[1] == 'p')
940 found_probe_option = skip_keyword (tracker, probe_options, &text);
942 const char *option_text = text;
943 int saved_word_point = tracker.custom_word_point ();
945 const char *copy = text;
947 explicit_completion_info completion_info;
948 location_spec_up locspec
949 = string_to_explicit_location_spec (&copy, current_language,
950 &completion_info);
951 if (completion_info.quoted_arg_start != NULL
952 && completion_info.quoted_arg_end == NULL)
954 /* Found an unbalanced quote. */
955 tracker.set_quote_char (*completion_info.quoted_arg_start);
956 tracker.advance_custom_word_point_by (1);
959 if (completion_info.saw_explicit_location_spec_option)
961 if (*copy != '\0')
963 tracker.advance_custom_word_point_by (copy - text);
964 text = copy;
966 /* We found a terminator at the tail end of the string,
967 which means we're past the explicit location options. We
968 may have a keyword to complete on. If we have a whole
969 keyword, then complete whatever comes after as an
970 expression. This is mainly for the "if" keyword. If the
971 "thread" and "task" keywords gain their own completers,
972 they should be used here. */
973 int keyword = skip_keyword (tracker, linespec_keywords, &text);
975 if (keyword == -1)
977 complete_on_enum (tracker, linespec_keywords, text, text);
979 else
981 const char *word
982 = advance_to_expression_complete_word_point (tracker, text);
983 complete_expression (tracker, text, word);
986 else
988 tracker.advance_custom_word_point_by (completion_info.last_option
989 - text);
990 text = completion_info.last_option;
992 complete_explicit_location_spec (tracker, locspec.get (), text,
993 current_language,
994 completion_info.quoted_arg_start,
995 completion_info.quoted_arg_end);
999 /* This is an address or linespec location. */
1000 else if (locspec != nullptr)
1002 /* Handle non-explicit location options. */
1004 int keyword = skip_keyword (tracker, explicit_options, &text);
1005 if (keyword == -1)
1006 complete_on_enum (tracker, explicit_options, text, text);
1007 else
1009 tracker.advance_custom_word_point_by (copy - text);
1010 text = copy;
1012 symbol_name_match_type match_type
1013 = as_explicit_location_spec (locspec.get ())->func_name_match_type;
1014 complete_address_and_linespec_locations (tracker, text, match_type);
1017 else
1019 /* No options. */
1020 complete_address_and_linespec_locations (tracker, text,
1021 symbol_name_match_type::WILD);
1024 /* Add matches for option names, if either:
1026 - Some completer above found some matches, but the word point did
1027 not advance (e.g., "b <tab>" finds all functions, or "b -<tab>"
1028 matches all objc selectors), or;
1030 - Some completer above advanced the word point, but found no
1031 matches.
1033 if ((text[0] == '-' || text[0] == '\0')
1034 && (!tracker.have_completions ()
1035 || tracker.custom_word_point () == saved_word_point))
1037 tracker.set_custom_word_point (saved_word_point);
1038 text = option_text;
1040 if (found_probe_option == -1)
1041 complete_on_enum (tracker, probe_options, text, text);
1042 complete_on_enum (tracker, explicit_options, text, text);
1046 /* The corresponding completer_handle_brkchars
1047 implementation. */
1049 static void
1050 location_completer_handle_brkchars (struct cmd_list_element *ignore,
1051 completion_tracker &tracker,
1052 const char *text,
1053 const char *word_ignored)
1055 tracker.set_use_custom_word_point (true);
1057 location_completer (ignore, tracker, text, NULL);
1060 /* See completer.h. */
1062 void
1063 complete_expression (completion_tracker &tracker,
1064 const char *text, const char *word)
1066 expression_up exp;
1067 std::unique_ptr<expr_completion_base> expr_completer;
1069 /* Perform a tentative parse of the expression, to see whether a
1070 field completion is required. */
1073 exp = parse_expression_for_completion (text, &expr_completer);
1075 catch (const gdb_exception_error &except)
1077 return;
1080 /* Part of the parse_expression_for_completion contract. */
1081 gdb_assert ((exp == nullptr) == (expr_completer == nullptr));
1082 if (expr_completer != nullptr
1083 && expr_completer->complete (exp.get (), tracker))
1084 return;
1086 complete_files_symbols (tracker, text, word);
1089 /* Complete on expressions. Often this means completing on symbol
1090 names, but some language parsers also have support for completing
1091 field names. */
1093 void
1094 expression_completer (struct cmd_list_element *ignore,
1095 completion_tracker &tracker,
1096 const char *text, const char *word)
1098 complete_expression (tracker, text, word);
1101 /* See definition in completer.h. */
1103 void
1104 set_rl_completer_word_break_characters (const char *break_chars)
1106 rl_completer_word_break_characters = (char *) break_chars;
1109 /* Complete on symbols. */
1111 void
1112 symbol_completer (struct cmd_list_element *ignore,
1113 completion_tracker &tracker,
1114 const char *text, const char *word)
1116 collect_symbol_completion_matches (tracker, complete_symbol_mode::EXPRESSION,
1117 symbol_name_match_type::EXPRESSION,
1118 text, word);
1121 /* Here are some useful test cases for completion. FIXME: These
1122 should be put in the test suite. They should be tested with both
1123 M-? and TAB.
1125 "show output-" "radix"
1126 "show output" "-radix"
1127 "p" ambiguous (commands starting with p--path, print, printf, etc.)
1128 "p " ambiguous (all symbols)
1129 "info t foo" no completions
1130 "info t " no completions
1131 "info t" ambiguous ("info target", "info terminal", etc.)
1132 "info ajksdlfk" no completions
1133 "info ajksdlfk " no completions
1134 "info" " "
1135 "info " ambiguous (all info commands)
1136 "p \"a" no completions (string constant)
1137 "p 'a" ambiguous (all symbols starting with a)
1138 "p b-a" ambiguous (all symbols starting with a)
1139 "p b-" ambiguous (all symbols)
1140 "file Make" "file" (word break hard to screw up here)
1141 "file ../gdb.stabs/we" "ird" (needs to not break word at slash)
1144 enum complete_line_internal_reason
1146 /* Preliminary phase, called by gdb_completion_word_break_characters
1147 function, is used to either:
1149 #1 - Determine the set of chars that are word delimiters
1150 depending on the current command in line_buffer.
1152 #2 - Manually advance RL_POINT to the "word break" point instead
1153 of letting readline do it (based on too-simple character
1154 matching).
1156 Simpler completers that just pass a brkchars array to readline
1157 (#1 above) must defer generating the completions to the main
1158 phase (below). No completion list should be generated in this
1159 phase.
1161 OTOH, completers that manually advance the word point(#2 above)
1162 must set "use_custom_word_point" in the tracker and generate
1163 their completion in this phase. Note that this is the convenient
1164 thing to do since they'll be parsing the input line anyway. */
1165 handle_brkchars,
1167 /* Main phase, called by complete_line function, is used to get the
1168 list of possible completions. */
1169 handle_completions,
1171 /* Special case when completing a 'help' command. In this case,
1172 once sub-command completions are exhausted, we simply return
1173 NULL. */
1174 handle_help,
1177 /* Helper for complete_line_internal to simplify it. */
1179 static void
1180 complete_line_internal_normal_command (completion_tracker &tracker,
1181 const char *command, const char *word,
1182 const char *cmd_args,
1183 complete_line_internal_reason reason,
1184 struct cmd_list_element *c)
1186 const char *p = cmd_args;
1188 if (c->completer == filename_completer)
1190 /* Many commands which want to complete on file names accept
1191 several file names, as in "run foo bar >>baz". So we don't
1192 want to complete the entire text after the command, just the
1193 last word. To this end, we need to find the beginning of the
1194 file name by starting at `word' and going backwards. */
1195 for (p = word;
1196 p > command
1197 && strchr (gdb_completer_file_name_break_characters,
1198 p[-1]) == NULL;
1199 p--)
1203 if (reason == handle_brkchars)
1205 completer_handle_brkchars_ftype *brkchars_fn;
1207 if (c->completer_handle_brkchars != NULL)
1208 brkchars_fn = c->completer_handle_brkchars;
1209 else
1211 brkchars_fn
1212 = (completer_handle_brkchars_func_for_completer
1213 (c->completer));
1216 brkchars_fn (c, tracker, p, word);
1219 if (reason != handle_brkchars && c->completer != NULL)
1220 (*c->completer) (c, tracker, p, word);
1223 /* Internal function used to handle completions.
1226 TEXT is the caller's idea of the "word" we are looking at.
1228 LINE_BUFFER is available to be looked at; it contains the entire
1229 text of the line. POINT is the offset in that line of the cursor.
1230 You should pretend that the line ends at POINT.
1232 See complete_line_internal_reason for description of REASON. */
1234 static void
1235 complete_line_internal_1 (completion_tracker &tracker,
1236 const char *text,
1237 const char *line_buffer, int point,
1238 complete_line_internal_reason reason)
1240 char *tmp_command;
1241 const char *p;
1242 int ignore_help_classes;
1243 /* Pointer within tmp_command which corresponds to text. */
1244 const char *word;
1245 struct cmd_list_element *c, *result_list;
1247 /* Choose the default set of word break characters to break
1248 completions. If we later find out that we are doing completions
1249 on command strings (as opposed to strings supplied by the
1250 individual command completer functions, which can be any string)
1251 then we will switch to the special word break set for command
1252 strings, which leaves out the '-' and '.' character used in some
1253 commands. */
1254 set_rl_completer_word_break_characters
1255 (current_language->word_break_characters ());
1257 /* Decide whether to complete on a list of gdb commands or on
1258 symbols. */
1259 tmp_command = (char *) alloca (point + 1);
1260 p = tmp_command;
1262 /* The help command should complete help aliases. */
1263 ignore_help_classes = reason != handle_help;
1265 strncpy (tmp_command, line_buffer, point);
1266 tmp_command[point] = '\0';
1267 if (reason == handle_brkchars)
1269 gdb_assert (text == NULL);
1270 word = NULL;
1272 else
1274 /* Since text always contains some number of characters leading up
1275 to point, we can find the equivalent position in tmp_command
1276 by subtracting that many characters from the end of tmp_command. */
1277 word = tmp_command + point - strlen (text);
1280 /* Move P up to the start of the command. */
1281 p = skip_spaces (p);
1283 if (*p == '\0')
1285 /* An empty line is ambiguous; that is, it could be any
1286 command. */
1287 c = CMD_LIST_AMBIGUOUS;
1288 result_list = 0;
1290 else
1291 c = lookup_cmd_1 (&p, cmdlist, &result_list, NULL, ignore_help_classes,
1292 true);
1294 /* Move p up to the next interesting thing. */
1295 while (*p == ' ' || *p == '\t')
1297 p++;
1300 tracker.advance_custom_word_point_by (p - tmp_command);
1302 if (!c)
1304 /* It is an unrecognized command. So there are no
1305 possible completions. */
1307 else if (c == CMD_LIST_AMBIGUOUS)
1309 const char *q;
1311 /* lookup_cmd_1 advances p up to the first ambiguous thing, but
1312 doesn't advance over that thing itself. Do so now. */
1313 q = p;
1314 while (valid_cmd_char_p (*q))
1315 ++q;
1316 if (q != tmp_command + point)
1318 /* There is something beyond the ambiguous
1319 command, so there are no possible completions. For
1320 example, "info t " or "info t foo" does not complete
1321 to anything, because "info t" can be "info target" or
1322 "info terminal". */
1324 else
1326 /* We're trying to complete on the command which was ambiguous.
1327 This we can deal with. */
1328 if (result_list)
1330 if (reason != handle_brkchars)
1331 complete_on_cmdlist (*result_list->subcommands, tracker, p,
1332 word, ignore_help_classes);
1334 else
1336 if (reason != handle_brkchars)
1337 complete_on_cmdlist (cmdlist, tracker, p, word,
1338 ignore_help_classes);
1340 /* Ensure that readline does the right thing with respect to
1341 inserting quotes. */
1342 set_rl_completer_word_break_characters
1343 (gdb_completer_command_word_break_characters);
1346 else
1348 /* We've recognized a full command. */
1350 if (p == tmp_command + point)
1352 /* There is no non-whitespace in the line beyond the
1353 command. */
1355 if (p[-1] == ' ' || p[-1] == '\t')
1357 /* The command is followed by whitespace; we need to
1358 complete on whatever comes after command. */
1359 if (c->is_prefix ())
1361 /* It is a prefix command; what comes after it is
1362 a subcommand (e.g. "info "). */
1363 if (reason != handle_brkchars)
1364 complete_on_cmdlist (*c->subcommands, tracker, p, word,
1365 ignore_help_classes);
1367 /* Ensure that readline does the right thing
1368 with respect to inserting quotes. */
1369 set_rl_completer_word_break_characters
1370 (gdb_completer_command_word_break_characters);
1372 else if (reason == handle_help)
1374 else if (c->enums)
1376 if (reason != handle_brkchars)
1377 complete_on_enum (tracker, c->enums, p, word);
1378 set_rl_completer_word_break_characters
1379 (gdb_completer_command_word_break_characters);
1381 else
1383 /* It is a normal command; what comes after it is
1384 completed by the command's completer function. */
1385 complete_line_internal_normal_command (tracker,
1386 tmp_command, word, p,
1387 reason, c);
1390 else
1392 /* The command is not followed by whitespace; we need to
1393 complete on the command itself, e.g. "p" which is a
1394 command itself but also can complete to "print", "ptype"
1395 etc. */
1396 const char *q;
1398 /* Find the command we are completing on. */
1399 q = p;
1400 while (q > tmp_command)
1402 if (valid_cmd_char_p (q[-1]))
1403 --q;
1404 else
1405 break;
1408 /* Move the custom word point back too. */
1409 tracker.advance_custom_word_point_by (q - p);
1411 if (reason != handle_brkchars)
1412 complete_on_cmdlist (result_list, tracker, q, word,
1413 ignore_help_classes);
1415 /* Ensure that readline does the right thing
1416 with respect to inserting quotes. */
1417 set_rl_completer_word_break_characters
1418 (gdb_completer_command_word_break_characters);
1421 else if (reason == handle_help)
1423 else
1425 /* There is non-whitespace beyond the command. */
1427 if (c->is_prefix () && !c->allow_unknown)
1429 /* It is an unrecognized subcommand of a prefix command,
1430 e.g. "info adsfkdj". */
1432 else if (c->enums)
1434 if (reason != handle_brkchars)
1435 complete_on_enum (tracker, c->enums, p, word);
1437 else
1439 /* It is a normal command. */
1440 complete_line_internal_normal_command (tracker,
1441 tmp_command, word, p,
1442 reason, c);
1448 /* Wrapper around complete_line_internal_1 to handle
1449 MAX_COMPLETIONS_REACHED_ERROR. */
1451 static void
1452 complete_line_internal (completion_tracker &tracker,
1453 const char *text,
1454 const char *line_buffer, int point,
1455 complete_line_internal_reason reason)
1459 complete_line_internal_1 (tracker, text, line_buffer, point, reason);
1461 catch (const gdb_exception_error &except)
1463 if (except.error != MAX_COMPLETIONS_REACHED_ERROR)
1464 throw;
1468 /* See completer.h. */
1470 int max_completions = 200;
1472 /* Initial size of the table. It automagically grows from here. */
1473 #define INITIAL_COMPLETION_HTAB_SIZE 200
1475 /* See completer.h. */
1477 completion_tracker::completion_tracker ()
1479 discard_completions ();
1482 /* See completer.h. */
1484 void
1485 completion_tracker::discard_completions ()
1487 xfree (m_lowest_common_denominator);
1488 m_lowest_common_denominator = NULL;
1490 m_lowest_common_denominator_unique = false;
1491 m_lowest_common_denominator_valid = false;
1493 m_entries_hash.reset (nullptr);
1495 /* A callback used by the hash table to compare new entries with existing
1496 entries. We can't use the standard htab_eq_string function here as the
1497 key to our hash is just a single string, while the values we store in
1498 the hash are a struct containing multiple strings. */
1499 static auto entry_eq_func
1500 = [] (const void *first, const void *second) -> int
1502 /* The FIRST argument is the entry already in the hash table, and
1503 the SECOND argument is the new item being inserted. */
1504 const completion_hash_entry *entry
1505 = (const completion_hash_entry *) first;
1506 const char *name_str = (const char *) second;
1508 return entry->is_name_eq (name_str);
1511 /* Callback used by the hash table to compute the hash value for an
1512 existing entry. This is needed when expanding the hash table. */
1513 static auto entry_hash_func
1514 = [] (const void *arg) -> hashval_t
1516 const completion_hash_entry *entry
1517 = (const completion_hash_entry *) arg;
1518 return entry->hash_name ();
1521 m_entries_hash.reset
1522 (htab_create_alloc (INITIAL_COMPLETION_HTAB_SIZE,
1523 entry_hash_func, entry_eq_func,
1524 htab_delete_entry<completion_hash_entry>,
1525 xcalloc, xfree));
1528 /* See completer.h. */
1530 completion_tracker::~completion_tracker ()
1532 xfree (m_lowest_common_denominator);
1535 /* See completer.h. */
1537 bool
1538 completion_tracker::maybe_add_completion
1539 (gdb::unique_xmalloc_ptr<char> name,
1540 completion_match_for_lcd *match_for_lcd,
1541 const char *text, const char *word)
1543 void **slot;
1545 if (max_completions == 0)
1546 return false;
1548 if (htab_elements (m_entries_hash.get ()) >= max_completions)
1549 return false;
1551 hashval_t hash = htab_hash_string (name.get ());
1552 slot = htab_find_slot_with_hash (m_entries_hash.get (), name.get (),
1553 hash, INSERT);
1554 if (*slot == HTAB_EMPTY_ENTRY)
1556 const char *match_for_lcd_str = NULL;
1558 if (match_for_lcd != NULL)
1559 match_for_lcd_str = match_for_lcd->finish ();
1561 if (match_for_lcd_str == NULL)
1562 match_for_lcd_str = name.get ();
1564 gdb::unique_xmalloc_ptr<char> lcd
1565 = make_completion_match_str (match_for_lcd_str, text, word);
1567 size_t lcd_len = strlen (lcd.get ());
1568 *slot = new completion_hash_entry (std::move (name), std::move (lcd));
1570 m_lowest_common_denominator_valid = false;
1571 m_lowest_common_denominator_max_length
1572 = std::max (m_lowest_common_denominator_max_length, lcd_len);
1575 return true;
1578 /* See completer.h. */
1580 void
1581 completion_tracker::add_completion (gdb::unique_xmalloc_ptr<char> name,
1582 completion_match_for_lcd *match_for_lcd,
1583 const char *text, const char *word)
1585 if (!maybe_add_completion (std::move (name), match_for_lcd, text, word))
1586 throw_error (MAX_COMPLETIONS_REACHED_ERROR, _("Max completions reached."));
1589 /* See completer.h. */
1591 void
1592 completion_tracker::add_completions (completion_list &&list)
1594 for (auto &candidate : list)
1595 add_completion (std::move (candidate));
1598 /* See completer.h. */
1600 void
1601 completion_tracker::remove_completion (const char *name)
1603 hashval_t hash = htab_hash_string (name);
1604 if (htab_find_slot_with_hash (m_entries_hash.get (), name, hash, NO_INSERT)
1605 != NULL)
1607 htab_remove_elt_with_hash (m_entries_hash.get (), name, hash);
1608 m_lowest_common_denominator_valid = false;
1612 /* Helper for the make_completion_match_str overloads. Returns NULL
1613 as an indication that we want MATCH_NAME exactly. It is up to the
1614 caller to xstrdup that string if desired. */
1616 static char *
1617 make_completion_match_str_1 (const char *match_name,
1618 const char *text, const char *word)
1620 char *newobj;
1622 if (word == text)
1624 /* Return NULL as an indication that we want MATCH_NAME
1625 exactly. */
1626 return NULL;
1628 else if (word > text)
1630 /* Return some portion of MATCH_NAME. */
1631 newobj = xstrdup (match_name + (word - text));
1633 else
1635 /* Return some of WORD plus MATCH_NAME. */
1636 size_t len = strlen (match_name);
1637 newobj = (char *) xmalloc (text - word + len + 1);
1638 memcpy (newobj, word, text - word);
1639 memcpy (newobj + (text - word), match_name, len + 1);
1642 return newobj;
1645 /* See completer.h. */
1647 gdb::unique_xmalloc_ptr<char>
1648 make_completion_match_str (const char *match_name,
1649 const char *text, const char *word)
1651 char *newobj = make_completion_match_str_1 (match_name, text, word);
1652 if (newobj == NULL)
1653 newobj = xstrdup (match_name);
1654 return gdb::unique_xmalloc_ptr<char> (newobj);
1657 /* See completer.h. */
1659 gdb::unique_xmalloc_ptr<char>
1660 make_completion_match_str (gdb::unique_xmalloc_ptr<char> &&match_name,
1661 const char *text, const char *word)
1663 char *newobj = make_completion_match_str_1 (match_name.get (), text, word);
1664 if (newobj == NULL)
1665 return std::move (match_name);
1666 return gdb::unique_xmalloc_ptr<char> (newobj);
1669 /* See complete.h. */
1671 completion_result
1672 complete (const char *line, char const **word, int *quote_char)
1674 completion_tracker tracker_handle_brkchars;
1675 completion_tracker tracker_handle_completions;
1676 completion_tracker *tracker;
1678 /* The WORD should be set to the end of word to complete. We initialize
1679 to the completion point which is assumed to be at the end of LINE.
1680 This leaves WORD to be initialized to a sensible value in cases
1681 completion_find_completion_word() fails i.e., throws an exception.
1682 See bug 24587. */
1683 *word = line + strlen (line);
1687 *word = completion_find_completion_word (tracker_handle_brkchars,
1688 line, quote_char);
1690 /* Completers that provide a custom word point in the
1691 handle_brkchars phase also compute their completions then.
1692 Completers that leave the completion word handling to readline
1693 must be called twice. */
1694 if (tracker_handle_brkchars.use_custom_word_point ())
1695 tracker = &tracker_handle_brkchars;
1696 else
1698 complete_line (tracker_handle_completions, *word, line, strlen (line));
1699 tracker = &tracker_handle_completions;
1702 catch (const gdb_exception &ex)
1704 return {};
1707 return tracker->build_completion_result (*word, *word - line, strlen (line));
1711 /* Generate completions all at once. Does nothing if max_completions
1712 is 0. If max_completions is non-negative, this will collect at
1713 most max_completions strings.
1715 TEXT is the caller's idea of the "word" we are looking at.
1717 LINE_BUFFER is available to be looked at; it contains the entire
1718 text of the line.
1720 POINT is the offset in that line of the cursor. You
1721 should pretend that the line ends at POINT. */
1723 void
1724 complete_line (completion_tracker &tracker,
1725 const char *text, const char *line_buffer, int point)
1727 if (max_completions == 0)
1728 return;
1729 complete_line_internal (tracker, text, line_buffer, point,
1730 handle_completions);
1733 /* Complete on command names. Used by "help". */
1735 void
1736 command_completer (struct cmd_list_element *ignore,
1737 completion_tracker &tracker,
1738 const char *text, const char *word)
1740 complete_line_internal (tracker, word, text,
1741 strlen (text), handle_help);
1744 /* The corresponding completer_handle_brkchars implementation. */
1746 static void
1747 command_completer_handle_brkchars (struct cmd_list_element *ignore,
1748 completion_tracker &tracker,
1749 const char *text, const char *word)
1751 set_rl_completer_word_break_characters
1752 (gdb_completer_command_word_break_characters);
1755 /* Complete on signals. */
1757 void
1758 signal_completer (struct cmd_list_element *ignore,
1759 completion_tracker &tracker,
1760 const char *text, const char *word)
1762 size_t len = strlen (word);
1763 int signum;
1764 const char *signame;
1766 for (signum = GDB_SIGNAL_FIRST; signum != GDB_SIGNAL_LAST; ++signum)
1768 /* Can't handle this, so skip it. */
1769 if (signum == GDB_SIGNAL_0)
1770 continue;
1772 signame = gdb_signal_to_name ((enum gdb_signal) signum);
1774 /* Ignore the unknown signal case. */
1775 if (!signame || strcmp (signame, "?") == 0)
1776 continue;
1778 if (strncasecmp (signame, word, len) == 0)
1779 tracker.add_completion (make_unique_xstrdup (signame));
1783 /* Bit-flags for selecting what the register and/or register-group
1784 completer should complete on. */
1786 enum reg_completer_target
1788 complete_register_names = 0x1,
1789 complete_reggroup_names = 0x2
1791 DEF_ENUM_FLAGS_TYPE (enum reg_completer_target, reg_completer_targets);
1793 /* Complete register names and/or reggroup names based on the value passed
1794 in TARGETS. At least one bit in TARGETS must be set. */
1796 static void
1797 reg_or_group_completer_1 (completion_tracker &tracker,
1798 const char *text, const char *word,
1799 reg_completer_targets targets)
1801 size_t len = strlen (word);
1802 struct gdbarch *gdbarch;
1803 const char *name;
1805 gdb_assert ((targets & (complete_register_names
1806 | complete_reggroup_names)) != 0);
1807 gdbarch = get_current_arch ();
1809 if ((targets & complete_register_names) != 0)
1811 int i;
1813 for (i = 0;
1814 (name = user_reg_map_regnum_to_name (gdbarch, i)) != NULL;
1815 i++)
1817 if (*name != '\0' && strncmp (word, name, len) == 0)
1818 tracker.add_completion (make_unique_xstrdup (name));
1822 if ((targets & complete_reggroup_names) != 0)
1824 for (const struct reggroup *group : gdbarch_reggroups (gdbarch))
1826 name = group->name ();
1827 if (strncmp (word, name, len) == 0)
1828 tracker.add_completion (make_unique_xstrdup (name));
1833 /* Perform completion on register and reggroup names. */
1835 void
1836 reg_or_group_completer (struct cmd_list_element *ignore,
1837 completion_tracker &tracker,
1838 const char *text, const char *word)
1840 reg_or_group_completer_1 (tracker, text, word,
1841 (complete_register_names
1842 | complete_reggroup_names));
1845 /* Perform completion on reggroup names. */
1847 void
1848 reggroup_completer (struct cmd_list_element *ignore,
1849 completion_tracker &tracker,
1850 const char *text, const char *word)
1852 reg_or_group_completer_1 (tracker, text, word,
1853 complete_reggroup_names);
1856 /* The default completer_handle_brkchars implementation. */
1858 static void
1859 default_completer_handle_brkchars (struct cmd_list_element *ignore,
1860 completion_tracker &tracker,
1861 const char *text, const char *word)
1863 set_rl_completer_word_break_characters
1864 (current_language->word_break_characters ());
1867 /* See definition in completer.h. */
1869 completer_handle_brkchars_ftype *
1870 completer_handle_brkchars_func_for_completer (completer_ftype *fn)
1872 if (fn == filename_completer)
1873 return filename_completer_handle_brkchars;
1875 if (fn == location_completer)
1876 return location_completer_handle_brkchars;
1878 if (fn == command_completer)
1879 return command_completer_handle_brkchars;
1881 return default_completer_handle_brkchars;
1884 /* Used as brkchars when we want to tell readline we have a custom
1885 word point. We do that by making our rl_completion_word_break_hook
1886 set RL_POINT to the desired word point, and return the character at
1887 the word break point as the break char. This is two bytes in order
1888 to fit one break character plus the terminating null. */
1889 static char gdb_custom_word_point_brkchars[2];
1891 /* Since rl_basic_quote_characters is not completer-specific, we save
1892 its original value here, in order to be able to restore it in
1893 gdb_rl_attempted_completion_function. */
1894 static const char *gdb_org_rl_basic_quote_characters = rl_basic_quote_characters;
1896 /* Get the list of chars that are considered as word breaks
1897 for the current command. */
1899 static char *
1900 gdb_completion_word_break_characters_throw ()
1902 /* New completion starting. Get rid of the previous tracker and
1903 start afresh. */
1904 delete current_completion.tracker;
1905 current_completion.tracker = new completion_tracker ();
1907 completion_tracker &tracker = *current_completion.tracker;
1909 complete_line_internal (tracker, NULL, rl_line_buffer,
1910 rl_point, handle_brkchars);
1912 if (tracker.use_custom_word_point ())
1914 gdb_assert (tracker.custom_word_point () > 0);
1915 rl_point = tracker.custom_word_point () - 1;
1917 gdb_assert (rl_point >= 0 && rl_point < strlen (rl_line_buffer));
1919 gdb_custom_word_point_brkchars[0] = rl_line_buffer[rl_point];
1920 rl_completer_word_break_characters = gdb_custom_word_point_brkchars;
1921 rl_completer_quote_characters = NULL;
1923 /* Clear this too, so that if we're completing a quoted string,
1924 readline doesn't consider the quote character a delimiter.
1925 If we didn't do this, readline would auto-complete {b
1926 'fun<tab>} to {'b 'function()'}, i.e., add the terminating
1927 \', but, it wouldn't append the separator space either, which
1928 is not desirable. So instead we take care of appending the
1929 quote character to the LCD ourselves, in
1930 gdb_rl_attempted_completion_function. Since this global is
1931 not just completer-specific, we'll restore it back to the
1932 default in gdb_rl_attempted_completion_function. */
1933 rl_basic_quote_characters = NULL;
1936 return (char *) rl_completer_word_break_characters;
1939 char *
1940 gdb_completion_word_break_characters ()
1942 /* New completion starting. */
1943 current_completion.aborted = false;
1947 return gdb_completion_word_break_characters_throw ();
1949 catch (const gdb_exception &ex)
1951 /* Set this to that gdb_rl_attempted_completion_function knows
1952 to abort early. */
1953 current_completion.aborted = true;
1956 return NULL;
1959 /* See completer.h. */
1961 const char *
1962 completion_find_completion_word (completion_tracker &tracker, const char *text,
1963 int *quote_char)
1965 size_t point = strlen (text);
1967 complete_line_internal (tracker, NULL, text, point, handle_brkchars);
1969 if (tracker.use_custom_word_point ())
1971 gdb_assert (tracker.custom_word_point () > 0);
1972 *quote_char = tracker.quote_char ();
1973 return text + tracker.custom_word_point ();
1976 gdb_rl_completion_word_info info;
1978 info.word_break_characters = rl_completer_word_break_characters;
1979 info.quote_characters = gdb_completer_quote_characters;
1980 info.basic_quote_characters = rl_basic_quote_characters;
1982 return gdb_rl_find_completion_word (&info, quote_char, NULL, text);
1985 /* See completer.h. */
1987 void
1988 completion_tracker::recompute_lcd_visitor (completion_hash_entry *entry)
1990 if (!m_lowest_common_denominator_valid)
1992 /* This is the first lowest common denominator that we are
1993 considering, just copy it in. */
1994 strcpy (m_lowest_common_denominator, entry->get_lcd ());
1995 m_lowest_common_denominator_unique = true;
1996 m_lowest_common_denominator_valid = true;
1998 else
2000 /* Find the common denominator between the currently-known lowest
2001 common denominator and NEW_MATCH_UP. That becomes the new lowest
2002 common denominator. */
2003 size_t i;
2004 const char *new_match = entry->get_lcd ();
2006 for (i = 0;
2007 (new_match[i] != '\0'
2008 && new_match[i] == m_lowest_common_denominator[i]);
2009 i++)
2011 if (m_lowest_common_denominator[i] != new_match[i])
2013 m_lowest_common_denominator[i] = '\0';
2014 m_lowest_common_denominator_unique = false;
2019 /* See completer.h. */
2021 void
2022 completion_tracker::recompute_lowest_common_denominator ()
2024 /* We've already done this. */
2025 if (m_lowest_common_denominator_valid)
2026 return;
2028 /* Resize the storage to ensure we have enough space, the plus one gives
2029 us space for the trailing null terminator we will include. */
2030 m_lowest_common_denominator
2031 = (char *) xrealloc (m_lowest_common_denominator,
2032 m_lowest_common_denominator_max_length + 1);
2034 /* Callback used to visit each entry in the m_entries_hash. */
2035 auto visitor_func
2036 = [] (void **slot, void *info) -> int
2038 completion_tracker *obj = (completion_tracker *) info;
2039 completion_hash_entry *entry = (completion_hash_entry *) *slot;
2040 obj->recompute_lcd_visitor (entry);
2041 return 1;
2044 htab_traverse (m_entries_hash.get (), visitor_func, this);
2045 m_lowest_common_denominator_valid = true;
2048 /* See completer.h. */
2050 void
2051 completion_tracker::advance_custom_word_point_by (int len)
2053 m_custom_word_point += len;
2056 /* Build a new C string that is a copy of LCD with the whitespace of
2057 ORIG/ORIG_LEN preserved.
2059 Say the user is completing a symbol name, with spaces, like:
2061 "foo ( i"
2063 and the resulting completion match is:
2065 "foo(int)"
2067 we want to end up with an input line like:
2069 "foo ( int)"
2070 ^^^^^^^ => text from LCD [1], whitespace from ORIG preserved.
2071 ^^ => new text from LCD
2073 [1] - We must take characters from the LCD instead of the original
2074 text, since some completions want to change upper/lowercase. E.g.:
2076 "handle sig<>"
2078 completes to:
2080 "handle SIG[QUIT|etc.]"
2083 static char *
2084 expand_preserving_ws (const char *orig, size_t orig_len,
2085 const char *lcd)
2087 const char *p_orig = orig;
2088 const char *orig_end = orig + orig_len;
2089 const char *p_lcd = lcd;
2090 std::string res;
2092 while (p_orig < orig_end)
2094 if (*p_orig == ' ')
2096 while (p_orig < orig_end && *p_orig == ' ')
2097 res += *p_orig++;
2098 p_lcd = skip_spaces (p_lcd);
2100 else
2102 /* Take characters from the LCD instead of the original
2103 text, since some completions change upper/lowercase.
2104 E.g.:
2105 "handle sig<>"
2106 completes to:
2107 "handle SIG[QUIT|etc.]"
2109 res += *p_lcd;
2110 p_orig++;
2111 p_lcd++;
2115 while (*p_lcd != '\0')
2116 res += *p_lcd++;
2118 return xstrdup (res.c_str ());
2121 /* See completer.h. */
2123 completion_result
2124 completion_tracker::build_completion_result (const char *text,
2125 int start, int end)
2127 size_t element_count = htab_elements (m_entries_hash.get ());
2129 if (element_count == 0)
2130 return {};
2132 /* +1 for the LCD, and +1 for NULL termination. */
2133 char **match_list = XNEWVEC (char *, 1 + element_count + 1);
2135 /* Build replacement word, based on the LCD. */
2137 recompute_lowest_common_denominator ();
2138 match_list[0]
2139 = expand_preserving_ws (text, end - start,
2140 m_lowest_common_denominator);
2142 if (m_lowest_common_denominator_unique)
2144 /* We don't rely on readline appending the quote char as
2145 delimiter as then readline wouldn't append the ' ' after the
2146 completion. */
2147 char buf[2] = { (char) quote_char () };
2149 match_list[0] = reconcat (match_list[0], match_list[0],
2150 buf, (char *) NULL);
2151 match_list[1] = NULL;
2153 /* If the tracker wants to, or we already have a space at the
2154 end of the match, tell readline to skip appending
2155 another. */
2156 char *match = match_list[0];
2157 bool completion_suppress_append
2158 = (suppress_append_ws ()
2159 || (match[0] != '\0'
2160 && match[strlen (match) - 1] == ' '));
2162 return completion_result (match_list, 1, completion_suppress_append);
2164 else
2166 /* State object used while building the completion list. */
2167 struct list_builder
2169 list_builder (char **ml)
2170 : match_list (ml),
2171 index (1)
2172 { /* Nothing. */ }
2174 /* The list we are filling. */
2175 char **match_list;
2177 /* The next index in the list to write to. */
2178 int index;
2180 list_builder builder (match_list);
2182 /* Visit each entry in m_entries_hash and add it to the completion
2183 list, updating the builder state object. */
2184 auto func
2185 = [] (void **slot, void *info) -> int
2187 completion_hash_entry *entry = (completion_hash_entry *) *slot;
2188 list_builder *state = (list_builder *) info;
2190 state->match_list[state->index] = entry->release_name ();
2191 state->index++;
2192 return 1;
2195 /* Build the completion list and add a null at the end. */
2196 htab_traverse_noresize (m_entries_hash.get (), func, &builder);
2197 match_list[builder.index] = NULL;
2199 return completion_result (match_list, builder.index - 1, false);
2203 /* See completer.h */
2205 completion_result::completion_result ()
2206 : match_list (NULL), number_matches (0),
2207 completion_suppress_append (false)
2210 /* See completer.h */
2212 completion_result::completion_result (char **match_list_,
2213 size_t number_matches_,
2214 bool completion_suppress_append_)
2215 : match_list (match_list_),
2216 number_matches (number_matches_),
2217 completion_suppress_append (completion_suppress_append_)
2220 /* See completer.h */
2222 completion_result::~completion_result ()
2224 reset_match_list ();
2227 /* See completer.h */
2229 completion_result::completion_result (completion_result &&rhs) noexcept
2230 : match_list (rhs.match_list),
2231 number_matches (rhs.number_matches)
2233 rhs.match_list = NULL;
2234 rhs.number_matches = 0;
2237 /* See completer.h */
2239 char **
2240 completion_result::release_match_list ()
2242 char **ret = match_list;
2243 match_list = NULL;
2244 return ret;
2247 /* See completer.h */
2249 void
2250 completion_result::sort_match_list ()
2252 if (number_matches > 1)
2254 /* Element 0 is special (it's the common prefix), leave it
2255 be. */
2256 std::sort (&match_list[1],
2257 &match_list[number_matches + 1],
2258 compare_cstrings);
2262 /* See completer.h */
2264 void
2265 completion_result::reset_match_list ()
2267 if (match_list != NULL)
2269 for (char **p = match_list; *p != NULL; p++)
2270 xfree (*p);
2271 xfree (match_list);
2272 match_list = NULL;
2276 /* Helper for gdb_rl_attempted_completion_function, which does most of
2277 the work. This is called by readline to build the match list array
2278 and to determine the lowest common denominator. The real matches
2279 list starts at match[1], while match[0] is the slot holding
2280 readline's idea of the lowest common denominator of all matches,
2281 which is what readline replaces the completion "word" with.
2283 TEXT is the caller's idea of the "word" we are looking at, as
2284 computed in the handle_brkchars phase.
2286 START is the offset from RL_LINE_BUFFER where TEXT starts. END is
2287 the offset from RL_LINE_BUFFER where TEXT ends (i.e., where
2288 rl_point is).
2290 You should thus pretend that the line ends at END (relative to
2291 RL_LINE_BUFFER).
2293 RL_LINE_BUFFER contains the entire text of the line. RL_POINT is
2294 the offset in that line of the cursor. You should pretend that the
2295 line ends at POINT.
2297 Returns NULL if there are no completions. */
2299 static char **
2300 gdb_rl_attempted_completion_function_throw (const char *text, int start, int end)
2302 /* Completers that provide a custom word point in the
2303 handle_brkchars phase also compute their completions then.
2304 Completers that leave the completion word handling to readline
2305 must be called twice. If rl_point (i.e., END) is at column 0,
2306 then readline skips the handle_brkchars phase, and so we create a
2307 tracker now in that case too. */
2308 if (end == 0 || !current_completion.tracker->use_custom_word_point ())
2310 delete current_completion.tracker;
2311 current_completion.tracker = new completion_tracker ();
2313 complete_line (*current_completion.tracker, text,
2314 rl_line_buffer, rl_point);
2317 completion_tracker &tracker = *current_completion.tracker;
2319 completion_result result
2320 = tracker.build_completion_result (text, start, end);
2322 rl_completion_suppress_append = result.completion_suppress_append;
2323 return result.release_match_list ();
2326 /* Function installed as "rl_attempted_completion_function" readline
2327 hook. Wrapper around gdb_rl_attempted_completion_function_throw
2328 that catches C++ exceptions, which can't cross readline. */
2330 char **
2331 gdb_rl_attempted_completion_function (const char *text, int start, int end)
2333 /* Restore globals that might have been tweaked in
2334 gdb_completion_word_break_characters. */
2335 rl_basic_quote_characters = gdb_org_rl_basic_quote_characters;
2337 /* If we end up returning NULL, either on error, or simple because
2338 there are no matches, inhibit readline's default filename
2339 completer. */
2340 rl_attempted_completion_over = 1;
2342 /* If the handle_brkchars phase was aborted, don't try
2343 completing. */
2344 if (current_completion.aborted)
2345 return NULL;
2349 return gdb_rl_attempted_completion_function_throw (text, start, end);
2351 catch (const gdb_exception &ex)
2355 return NULL;
2358 /* Skip over the possibly quoted word STR (as defined by the quote
2359 characters QUOTECHARS and the word break characters BREAKCHARS).
2360 Returns pointer to the location after the "word". If either
2361 QUOTECHARS or BREAKCHARS is NULL, use the same values used by the
2362 completer. */
2364 const char *
2365 skip_quoted_chars (const char *str, const char *quotechars,
2366 const char *breakchars)
2368 char quote_char = '\0';
2369 const char *scan;
2371 if (quotechars == NULL)
2372 quotechars = gdb_completer_quote_characters;
2374 if (breakchars == NULL)
2375 breakchars = current_language->word_break_characters ();
2377 for (scan = str; *scan != '\0'; scan++)
2379 if (quote_char != '\0')
2381 /* Ignore everything until the matching close quote char. */
2382 if (*scan == quote_char)
2384 /* Found matching close quote. */
2385 scan++;
2386 break;
2389 else if (strchr (quotechars, *scan))
2391 /* Found start of a quoted string. */
2392 quote_char = *scan;
2394 else if (strchr (breakchars, *scan))
2396 break;
2400 return (scan);
2403 /* Skip over the possibly quoted word STR (as defined by the quote
2404 characters and word break characters used by the completer).
2405 Returns pointer to the location after the "word". */
2407 const char *
2408 skip_quoted (const char *str)
2410 return skip_quoted_chars (str, NULL, NULL);
2413 /* Return a message indicating that the maximum number of completions
2414 has been reached and that there may be more. */
2416 const char *
2417 get_max_completions_reached_message (void)
2419 return _("*** List may be truncated, max-completions reached. ***");
2422 /* GDB replacement for rl_display_match_list.
2423 Readline doesn't provide a clean interface for TUI(curses).
2424 A hack previously used was to send readline's rl_outstream through a pipe
2425 and read it from the event loop. Bleah. IWBN if readline abstracted
2426 away all the necessary bits, and this is what this code does. It
2427 replicates the parts of readline we need and then adds an abstraction
2428 layer, currently implemented as struct match_list_displayer, so that both
2429 CLI and TUI can use it. We copy all this readline code to minimize
2430 GDB-specific mods to readline. Once this code performs as desired then
2431 we can submit it to the readline maintainers.
2433 N.B. A lot of the code is the way it is in order to minimize differences
2434 from readline's copy. */
2436 /* Not supported here. */
2437 #undef VISIBLE_STATS
2439 #if defined (HANDLE_MULTIBYTE)
2440 #define MB_INVALIDCH(x) ((x) == (size_t)-1 || (x) == (size_t)-2)
2441 #define MB_NULLWCH(x) ((x) == 0)
2442 #endif
2444 #define ELLIPSIS_LEN 3
2446 /* gdb version of readline/complete.c:get_y_or_n.
2447 'y' -> returns 1, and 'n' -> returns 0.
2448 Also supported: space == 'y', RUBOUT == 'n', ctrl-g == start over.
2449 If FOR_PAGER is non-zero, then also supported are:
2450 NEWLINE or RETURN -> returns 2, and 'q' -> returns 0. */
2452 static int
2453 gdb_get_y_or_n (int for_pager, const struct match_list_displayer *displayer)
2455 int c;
2457 for (;;)
2459 RL_SETSTATE (RL_STATE_MOREINPUT);
2460 c = displayer->read_key (displayer);
2461 RL_UNSETSTATE (RL_STATE_MOREINPUT);
2463 if (c == 'y' || c == 'Y' || c == ' ')
2464 return 1;
2465 if (c == 'n' || c == 'N' || c == RUBOUT)
2466 return 0;
2467 if (c == ABORT_CHAR || c < 0)
2469 /* Readline doesn't erase_entire_line here, but without it the
2470 --More-- prompt isn't erased and neither is the text entered
2471 thus far redisplayed. */
2472 displayer->erase_entire_line (displayer);
2473 /* Note: The arguments to rl_abort are ignored. */
2474 rl_abort (0, 0);
2476 if (for_pager && (c == NEWLINE || c == RETURN))
2477 return 2;
2478 if (for_pager && (c == 'q' || c == 'Q'))
2479 return 0;
2480 displayer->beep (displayer);
2484 /* Pager function for tab-completion.
2485 This is based on readline/complete.c:_rl_internal_pager.
2486 LINES is the number of lines of output displayed thus far.
2487 Returns:
2488 -1 -> user pressed 'n' or equivalent,
2489 0 -> user pressed 'y' or equivalent,
2490 N -> user pressed NEWLINE or equivalent and N is LINES - 1. */
2492 static int
2493 gdb_display_match_list_pager (int lines,
2494 const struct match_list_displayer *displayer)
2496 int i;
2498 displayer->puts (displayer, "--More--");
2499 displayer->flush (displayer);
2500 i = gdb_get_y_or_n (1, displayer);
2501 displayer->erase_entire_line (displayer);
2502 if (i == 0)
2503 return -1;
2504 else if (i == 2)
2505 return (lines - 1);
2506 else
2507 return 0;
2510 /* Return non-zero if FILENAME is a directory.
2511 Based on readline/complete.c:path_isdir. */
2513 static int
2514 gdb_path_isdir (const char *filename)
2516 struct stat finfo;
2518 return (stat (filename, &finfo) == 0 && S_ISDIR (finfo.st_mode));
2521 /* Return the portion of PATHNAME that should be output when listing
2522 possible completions. If we are hacking filename completion, we
2523 are only interested in the basename, the portion following the
2524 final slash. Otherwise, we return what we were passed. Since
2525 printing empty strings is not very informative, if we're doing
2526 filename completion, and the basename is the empty string, we look
2527 for the previous slash and return the portion following that. If
2528 there's no previous slash, we just return what we were passed.
2530 Based on readline/complete.c:printable_part. */
2532 static char *
2533 gdb_printable_part (char *pathname)
2535 char *temp, *x;
2537 if (rl_filename_completion_desired == 0) /* don't need to do anything */
2538 return (pathname);
2540 temp = strrchr (pathname, '/');
2541 #if defined (__MSDOS__)
2542 if (temp == 0 && ISALPHA ((unsigned char)pathname[0]) && pathname[1] == ':')
2543 temp = pathname + 1;
2544 #endif
2546 if (temp == 0 || *temp == '\0')
2547 return (pathname);
2548 /* If the basename is NULL, we might have a pathname like '/usr/src/'.
2549 Look for a previous slash and, if one is found, return the portion
2550 following that slash. If there's no previous slash, just return the
2551 pathname we were passed. */
2552 else if (temp[1] == '\0')
2554 for (x = temp - 1; x > pathname; x--)
2555 if (*x == '/')
2556 break;
2557 return ((*x == '/') ? x + 1 : pathname);
2559 else
2560 return ++temp;
2563 /* Compute width of STRING when displayed on screen by print_filename.
2564 Based on readline/complete.c:fnwidth. */
2566 static int
2567 gdb_fnwidth (const char *string)
2569 int width, pos;
2570 #if defined (HANDLE_MULTIBYTE)
2571 mbstate_t ps;
2572 int left, w;
2573 size_t clen;
2574 wchar_t wc;
2576 left = strlen (string) + 1;
2577 memset (&ps, 0, sizeof (mbstate_t));
2578 #endif
2580 width = pos = 0;
2581 while (string[pos])
2583 if (CTRL_CHAR (string[pos]) || string[pos] == RUBOUT)
2585 width += 2;
2586 pos++;
2588 else
2590 #if defined (HANDLE_MULTIBYTE)
2591 clen = mbrtowc (&wc, string + pos, left - pos, &ps);
2592 if (MB_INVALIDCH (clen))
2594 width++;
2595 pos++;
2596 memset (&ps, 0, sizeof (mbstate_t));
2598 else if (MB_NULLWCH (clen))
2599 break;
2600 else
2602 pos += clen;
2603 w = wcwidth (wc);
2604 width += (w >= 0) ? w : 1;
2606 #else
2607 width++;
2608 pos++;
2609 #endif
2613 return width;
2616 /* Print TO_PRINT, one matching completion.
2617 PREFIX_BYTES is number of common prefix bytes.
2618 Based on readline/complete.c:fnprint. */
2620 static int
2621 gdb_fnprint (const char *to_print, int prefix_bytes,
2622 const struct match_list_displayer *displayer)
2624 int printed_len, w;
2625 const char *s;
2626 #if defined (HANDLE_MULTIBYTE)
2627 mbstate_t ps;
2628 const char *end;
2629 size_t tlen;
2630 int width;
2631 wchar_t wc;
2633 end = to_print + strlen (to_print) + 1;
2634 memset (&ps, 0, sizeof (mbstate_t));
2635 #endif
2637 printed_len = 0;
2639 /* Don't print only the ellipsis if the common prefix is one of the
2640 possible completions */
2641 if (to_print[prefix_bytes] == '\0')
2642 prefix_bytes = 0;
2644 if (prefix_bytes)
2646 char ellipsis;
2648 ellipsis = (to_print[prefix_bytes] == '.') ? '_' : '.';
2649 for (w = 0; w < ELLIPSIS_LEN; w++)
2650 displayer->putch (displayer, ellipsis);
2651 printed_len = ELLIPSIS_LEN;
2654 s = to_print + prefix_bytes;
2655 while (*s)
2657 if (CTRL_CHAR (*s))
2659 displayer->putch (displayer, '^');
2660 displayer->putch (displayer, UNCTRL (*s));
2661 printed_len += 2;
2662 s++;
2663 #if defined (HANDLE_MULTIBYTE)
2664 memset (&ps, 0, sizeof (mbstate_t));
2665 #endif
2667 else if (*s == RUBOUT)
2669 displayer->putch (displayer, '^');
2670 displayer->putch (displayer, '?');
2671 printed_len += 2;
2672 s++;
2673 #if defined (HANDLE_MULTIBYTE)
2674 memset (&ps, 0, sizeof (mbstate_t));
2675 #endif
2677 else
2679 #if defined (HANDLE_MULTIBYTE)
2680 tlen = mbrtowc (&wc, s, end - s, &ps);
2681 if (MB_INVALIDCH (tlen))
2683 tlen = 1;
2684 width = 1;
2685 memset (&ps, 0, sizeof (mbstate_t));
2687 else if (MB_NULLWCH (tlen))
2688 break;
2689 else
2691 w = wcwidth (wc);
2692 width = (w >= 0) ? w : 1;
2694 for (w = 0; w < tlen; ++w)
2695 displayer->putch (displayer, s[w]);
2696 s += tlen;
2697 printed_len += width;
2698 #else
2699 displayer->putch (displayer, *s);
2700 s++;
2701 printed_len++;
2702 #endif
2706 return printed_len;
2709 /* Output TO_PRINT to rl_outstream. If VISIBLE_STATS is defined and we
2710 are using it, check for and output a single character for `special'
2711 filenames. Return the number of characters we output.
2712 Based on readline/complete.c:print_filename. */
2714 static int
2715 gdb_print_filename (char *to_print, char *full_pathname, int prefix_bytes,
2716 const struct match_list_displayer *displayer)
2718 int printed_len, extension_char, slen, tlen;
2719 char *s, c, *new_full_pathname;
2720 const char *dn;
2721 extern int _rl_complete_mark_directories;
2723 extension_char = 0;
2724 printed_len = gdb_fnprint (to_print, prefix_bytes, displayer);
2726 #if defined (VISIBLE_STATS)
2727 if (rl_filename_completion_desired && (rl_visible_stats || _rl_complete_mark_directories))
2728 #else
2729 if (rl_filename_completion_desired && _rl_complete_mark_directories)
2730 #endif
2732 /* If to_print != full_pathname, to_print is the basename of the
2733 path passed. In this case, we try to expand the directory
2734 name before checking for the stat character. */
2735 if (to_print != full_pathname)
2737 /* Terminate the directory name. */
2738 c = to_print[-1];
2739 to_print[-1] = '\0';
2741 /* If setting the last slash in full_pathname to a NUL results in
2742 full_pathname being the empty string, we are trying to complete
2743 files in the root directory. If we pass a null string to the
2744 bash directory completion hook, for example, it will expand it
2745 to the current directory. We just want the `/'. */
2746 if (full_pathname == 0 || *full_pathname == 0)
2747 dn = "/";
2748 else if (full_pathname[0] != '/')
2749 dn = full_pathname;
2750 else if (full_pathname[1] == 0)
2751 dn = "//"; /* restore trailing slash to `//' */
2752 else if (full_pathname[1] == '/' && full_pathname[2] == 0)
2753 dn = "/"; /* don't turn /// into // */
2754 else
2755 dn = full_pathname;
2756 s = tilde_expand (dn);
2757 if (rl_directory_completion_hook)
2758 (*rl_directory_completion_hook) (&s);
2760 slen = strlen (s);
2761 tlen = strlen (to_print);
2762 new_full_pathname = (char *)xmalloc (slen + tlen + 2);
2763 strcpy (new_full_pathname, s);
2764 if (s[slen - 1] == '/')
2765 slen--;
2766 else
2767 new_full_pathname[slen] = '/';
2768 new_full_pathname[slen] = '/';
2769 strcpy (new_full_pathname + slen + 1, to_print);
2771 #if defined (VISIBLE_STATS)
2772 if (rl_visible_stats)
2773 extension_char = stat_char (new_full_pathname);
2774 else
2775 #endif
2776 if (gdb_path_isdir (new_full_pathname))
2777 extension_char = '/';
2779 xfree (new_full_pathname);
2780 to_print[-1] = c;
2782 else
2784 s = tilde_expand (full_pathname);
2785 #if defined (VISIBLE_STATS)
2786 if (rl_visible_stats)
2787 extension_char = stat_char (s);
2788 else
2789 #endif
2790 if (gdb_path_isdir (s))
2791 extension_char = '/';
2794 xfree (s);
2795 if (extension_char)
2797 displayer->putch (displayer, extension_char);
2798 printed_len++;
2802 return printed_len;
2805 /* GDB version of readline/complete.c:complete_get_screenwidth. */
2807 static int
2808 gdb_complete_get_screenwidth (const struct match_list_displayer *displayer)
2810 /* Readline has other stuff here which it's not clear we need. */
2811 return displayer->width;
2814 extern int _rl_completion_prefix_display_length;
2815 extern int _rl_print_completions_horizontally;
2817 extern "C" int _rl_qsort_string_compare (const void *, const void *);
2818 typedef int QSFUNC (const void *, const void *);
2820 /* GDB version of readline/complete.c:rl_display_match_list.
2821 See gdb_display_match_list for a description of MATCHES, LEN, MAX.
2822 Returns non-zero if all matches are displayed. */
2824 static int
2825 gdb_display_match_list_1 (char **matches, int len, int max,
2826 const struct match_list_displayer *displayer)
2828 int count, limit, printed_len, lines, cols;
2829 int i, j, k, l, common_length, sind;
2830 char *temp, *t;
2831 int page_completions = displayer->height != INT_MAX && pagination_enabled;
2833 /* Find the length of the prefix common to all items: length as displayed
2834 characters (common_length) and as a byte index into the matches (sind) */
2835 common_length = sind = 0;
2836 if (_rl_completion_prefix_display_length > 0)
2838 t = gdb_printable_part (matches[0]);
2839 temp = strrchr (t, '/');
2840 common_length = temp ? gdb_fnwidth (temp) : gdb_fnwidth (t);
2841 sind = temp ? strlen (temp) : strlen (t);
2843 if (common_length > _rl_completion_prefix_display_length && common_length > ELLIPSIS_LEN)
2844 max -= common_length - ELLIPSIS_LEN;
2845 else
2846 common_length = sind = 0;
2849 /* How many items of MAX length can we fit in the screen window? */
2850 cols = gdb_complete_get_screenwidth (displayer);
2851 max += 2;
2852 limit = cols / max;
2853 if (limit != 1 && (limit * max == cols))
2854 limit--;
2856 /* If cols == 0, limit will end up -1 */
2857 if (cols < displayer->width && limit < 0)
2858 limit = 1;
2860 /* Avoid a possible floating exception. If max > cols,
2861 limit will be 0 and a divide-by-zero fault will result. */
2862 if (limit == 0)
2863 limit = 1;
2865 /* How many iterations of the printing loop? */
2866 count = (len + (limit - 1)) / limit;
2868 /* Watch out for special case. If LEN is less than LIMIT, then
2869 just do the inner printing loop.
2870 0 < len <= limit implies count = 1. */
2872 /* Sort the items if they are not already sorted. */
2873 if (rl_ignore_completion_duplicates == 0 && rl_sort_completion_matches)
2874 qsort (matches + 1, len, sizeof (char *), (QSFUNC *)_rl_qsort_string_compare);
2876 displayer->crlf (displayer);
2878 lines = 0;
2879 if (_rl_print_completions_horizontally == 0)
2881 /* Print the sorted items, up-and-down alphabetically, like ls. */
2882 for (i = 1; i <= count; i++)
2884 for (j = 0, l = i; j < limit; j++)
2886 if (l > len || matches[l] == 0)
2887 break;
2888 else
2890 temp = gdb_printable_part (matches[l]);
2891 printed_len = gdb_print_filename (temp, matches[l], sind,
2892 displayer);
2894 if (j + 1 < limit)
2895 for (k = 0; k < max - printed_len; k++)
2896 displayer->putch (displayer, ' ');
2898 l += count;
2900 displayer->crlf (displayer);
2901 lines++;
2902 if (page_completions && lines >= (displayer->height - 1) && i < count)
2904 lines = gdb_display_match_list_pager (lines, displayer);
2905 if (lines < 0)
2906 return 0;
2910 else
2912 /* Print the sorted items, across alphabetically, like ls -x. */
2913 for (i = 1; matches[i]; i++)
2915 temp = gdb_printable_part (matches[i]);
2916 printed_len = gdb_print_filename (temp, matches[i], sind, displayer);
2917 /* Have we reached the end of this line? */
2918 if (matches[i+1])
2920 if (i && (limit > 1) && (i % limit) == 0)
2922 displayer->crlf (displayer);
2923 lines++;
2924 if (page_completions && lines >= displayer->height - 1)
2926 lines = gdb_display_match_list_pager (lines, displayer);
2927 if (lines < 0)
2928 return 0;
2931 else
2932 for (k = 0; k < max - printed_len; k++)
2933 displayer->putch (displayer, ' ');
2936 displayer->crlf (displayer);
2939 return 1;
2942 /* Utility for displaying completion list matches, used by both CLI and TUI.
2944 MATCHES is the list of strings, in argv format, LEN is the number of
2945 strings in MATCHES, and MAX is the length of the longest string in
2946 MATCHES. */
2948 void
2949 gdb_display_match_list (char **matches, int len, int max,
2950 const struct match_list_displayer *displayer)
2952 /* Readline will never call this if complete_line returned NULL. */
2953 gdb_assert (max_completions != 0);
2955 /* complete_line will never return more than this. */
2956 if (max_completions > 0)
2957 gdb_assert (len <= max_completions);
2959 if (rl_completion_query_items > 0 && len >= rl_completion_query_items)
2961 char msg[100];
2963 /* We can't use *query here because they wait for <RET> which is
2964 wrong here. This follows the readline version as closely as possible
2965 for compatibility's sake. See readline/complete.c. */
2967 displayer->crlf (displayer);
2969 xsnprintf (msg, sizeof (msg),
2970 "Display all %d possibilities? (y or n)", len);
2971 displayer->puts (displayer, msg);
2972 displayer->flush (displayer);
2974 if (gdb_get_y_or_n (0, displayer) == 0)
2976 displayer->crlf (displayer);
2977 return;
2981 if (gdb_display_match_list_1 (matches, len, max, displayer))
2983 /* Note: MAX_COMPLETIONS may be -1 or zero, but LEN is always > 0. */
2984 if (len == max_completions)
2986 /* The maximum number of completions has been reached. Warn the user
2987 that there may be more. */
2988 const char *message = get_max_completions_reached_message ();
2990 displayer->puts (displayer, message);
2991 displayer->crlf (displayer);
2996 /* See completer.h. */
2998 bool
2999 skip_over_slash_fmt (completion_tracker &tracker, const char **args)
3001 const char *text = *args;
3003 if (text[0] == '/')
3005 bool in_fmt;
3006 tracker.set_use_custom_word_point (true);
3008 if (text[1] == '\0')
3010 /* The user tried to complete after typing just the '/' character
3011 of the /FMT string. Step the completer past the '/', but we
3012 don't offer any completions. */
3013 in_fmt = true;
3014 ++text;
3016 else
3018 /* The user has typed some characters after the '/', we assume
3019 this is a complete /FMT string, first skip over it. */
3020 text = skip_to_space (text);
3022 if (*text == '\0')
3024 /* We're at the end of the input string. The user has typed
3025 '/FMT' and asked for a completion. Push an empty
3026 completion string, this will cause readline to insert a
3027 space so the user now has '/FMT '. */
3028 in_fmt = true;
3029 tracker.add_completion (make_unique_xstrdup (text));
3031 else
3033 /* The user has already typed things after the /FMT, skip the
3034 whitespace and return false. Whoever called this function
3035 should then try to complete what comes next. */
3036 in_fmt = false;
3037 text = skip_spaces (text);
3041 tracker.advance_custom_word_point_by (text - *args);
3042 *args = text;
3043 return in_fmt;
3046 return false;
3049 void _initialize_completer ();
3050 void
3051 _initialize_completer ()
3053 add_setshow_zuinteger_unlimited_cmd ("max-completions", no_class,
3054 &max_completions, _("\
3055 Set maximum number of completion candidates."), _("\
3056 Show maximum number of completion candidates."), _("\
3057 Use this to limit the number of candidates considered\n\
3058 during completion. Specifying \"unlimited\" or -1\n\
3059 disables limiting. Note that setting either no limit or\n\
3060 a very large limit can make completion slow."),
3061 NULL, NULL, &setlist, &showlist);