Automatic date update in version.in
[binutils-gdb.git] / gdb / completer.c
blob4735aa5ed10b88057071311ba0c568567993c688
1 /* Line completion stuff for GDB, the GNU debugger.
2 Copyright (C) 2000-2024 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 "symtab.h"
20 #include "gdbtypes.h"
21 #include "expression.h"
22 #include "filenames.h"
23 #include "language.h"
24 #include "gdbsupport/gdb_signals.h"
25 #include "target.h"
26 #include "reggroups.h"
27 #include "user-regs.h"
28 #include "arch-utils.h"
29 #include "location.h"
30 #include <algorithm>
31 #include "linespec.h"
32 #include "cli/cli-decode.h"
33 #include "gdbsupport/gdb_tilde_expand.h"
34 #include "readline/readline.h"
36 /* FIXME: This is needed because of lookup_cmd_1 (). We should be
37 calling a hook instead so we eliminate the CLI dependency. */
38 #include "cli/cli-cmds.h"
40 /* Needed for rl_completer_word_break_characters and for
41 rl_filename_completion_function. */
42 #include "readline/readline.h"
44 /* readline defines this. */
45 #undef savestring
47 #include "completer.h"
49 /* Forward declarations. */
50 static const char *completion_find_completion_word (completion_tracker &tracker,
51 const char *text,
52 int *quote_char,
53 bool *found_any_quoting);
55 static void set_rl_completer_word_break_characters (const char *break_chars);
57 static bool gdb_path_isdir (const char *filename);
59 /* See completer.h. */
61 class completion_tracker::completion_hash_entry
63 public:
64 /* Constructor. */
65 completion_hash_entry (gdb::unique_xmalloc_ptr<char> name,
66 gdb::unique_xmalloc_ptr<char> lcd)
67 : m_name (std::move (name)),
68 m_lcd (std::move (lcd))
70 /* Nothing. */
73 /* Returns a pointer to the lowest common denominator string. This
74 string will only be valid while this hash entry is still valid as the
75 string continues to be owned by this hash entry and will be released
76 when this entry is deleted. */
77 char *get_lcd () const
79 return m_lcd.get ();
82 /* Get, and release the name field from this hash entry. This can only
83 be called once, after which the name field is no longer valid. This
84 should be used to pass ownership of the name to someone else. */
85 char *release_name ()
87 return m_name.release ();
90 /* Return true of the name in this hash entry is STR. */
91 bool is_name_eq (const char *str) const
93 return strcmp (m_name.get (), str) == 0;
96 /* Return the hash value based on the name of the entry. */
97 hashval_t hash_name () const
99 return htab_hash_string (m_name.get ());
102 private:
104 /* The symbol name stored in this hash entry. */
105 gdb::unique_xmalloc_ptr<char> m_name;
107 /* The lowest common denominator string computed for this hash entry. */
108 gdb::unique_xmalloc_ptr<char> m_lcd;
111 /* Misc state that needs to be tracked across several different
112 readline completer entry point calls, all related to a single
113 completion invocation. */
115 struct gdb_completer_state
117 /* The current completion's completion tracker. This is a global
118 because a tracker can be shared between the handle_brkchars and
119 handle_completion phases, which involves different readline
120 callbacks. */
121 completion_tracker *tracker = NULL;
123 /* Whether the current completion was aborted. */
124 bool aborted = false;
127 /* The current completion state. */
128 static gdb_completer_state current_completion;
130 /* An enumeration of the various things a user might attempt to
131 complete for a location. If you change this, remember to update
132 the explicit_options array below too. */
134 enum explicit_location_match_type
136 /* The filename of a source file. */
137 MATCH_SOURCE,
139 /* The name of a function or method. */
140 MATCH_FUNCTION,
142 /* The fully-qualified name of a function or method. */
143 MATCH_QUALIFIED,
145 /* A line number. */
146 MATCH_LINE,
148 /* The name of a label. */
149 MATCH_LABEL
152 /* Prototypes for local functions. */
154 /* readline uses the word breaks for two things:
155 (1) In figuring out where to point the TEXT parameter to the
156 rl_completion_entry_function. Since we don't use TEXT for much,
157 it doesn't matter a lot what the word breaks are for this purpose,
158 but it does affect how much stuff M-? lists.
159 (2) If one of the matches contains a word break character, readline
160 will quote it. That's why we switch between
161 current_language->word_break_characters () and
162 gdb_completer_command_word_break_characters. I'm not sure when
163 we need this behavior (perhaps for funky characters in C++
164 symbols?). */
166 /* Variables which are necessary for fancy command line editing. */
168 /* When completing on command names, we remove '-' and '.' from the list of
169 word break characters, since we use it in command names. If the
170 readline library sees one in any of the current completion strings,
171 it thinks that the string needs to be quoted and automatically
172 supplies a leading quote. */
173 static const char gdb_completer_command_word_break_characters[] =
174 " \t\n!@#$%^&*()+=|~`}{[]\"';:?/><,";
176 /* When completing on file names, we remove from the list of word
177 break characters any characters that are commonly used in file
178 names, such as '-', '+', '~', etc. Otherwise, readline displays
179 incorrect completion candidates. */
180 /* MS-DOS and MS-Windows use colon as part of the drive spec, and most
181 programs support @foo style response files. */
182 static const char gdb_completer_file_name_break_characters[] =
183 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
184 " \t\n*|\"';?><@";
185 #else
186 " \t\n*|\"';:?><";
187 #endif
189 /* When completing on file names, for commands that don't accept quoted
190 file names, the only character that can be used as a word separator is
191 the path separator. Every other character is treated as a literal
192 character within the filename. */
193 static const char gdb_completer_path_break_characters[] =
194 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
195 ";";
196 #else
197 ":";
198 #endif
200 /* Characters that can be used to quote expressions. Note that we can't
201 include '"' (double quote) because the gdb C parser treats such quoted
202 sequences as strings. */
203 static const char gdb_completer_expression_quote_characters[] = "'";
205 /* Characters that can be used to quote file names. We do allow '"'
206 (double quotes) in this set as file names are not passed through the C
207 expression parser. */
208 static const char gdb_completer_file_name_quote_characters[] = "'\"";
211 /* This can be used for functions which don't want to complete on
212 symbols but don't want to complete on anything else either. */
214 void
215 noop_completer (struct cmd_list_element *ignore,
216 completion_tracker &tracker,
217 const char *text, const char *prefix)
221 /* Return 1 if the character at EINDEX in STRING is quoted (there is an
222 unclosed quoted string), or if the character at EINDEX is quoted by a
223 backslash. */
225 static int
226 gdb_completer_file_name_char_is_quoted (char *string, int eindex)
228 for (int i = 0; i <= eindex && string[i] != '\0'; )
230 char c = string[i];
232 if (c == '\\')
234 /* The backslash itself is not quoted. */
235 if (i >= eindex)
236 return 0;
237 ++i;
238 /* But the next character is. */
239 if (i >= eindex)
240 return 1;
241 if (string[i] == '\0')
242 return 0;
243 ++i;
244 continue;
246 else if (strchr (rl_completer_quote_characters, c) != nullptr)
248 /* This assumes that extract_string_maybe_quoted can handle a
249 string quoted with character C. Currently this is true as the
250 only characters we put in rl_completer_quote_characters are
251 single and/or double quotes, both of which
252 extract_string_maybe_quoted can handle. */
253 gdb_assert (c == '"' || c == '\'');
254 const char *tmp = &string[i];
255 (void) extract_string_maybe_quoted (&tmp);
256 i = tmp - string;
258 /* Consider any character within the string we just skipped over
259 as quoted, though this might not be completely correct; the
260 opening and closing quotes are not themselves quoted. But so
261 far this doesn't seem to have caused any issues. */
262 if (i > eindex)
263 return 1;
265 else
266 ++i;
269 return 0;
272 /* Removing character escaping from FILENAME. QUOTE_CHAR is the quote
273 character around FILENAME or the null-character if there is no quoting
274 around FILENAME. */
276 static char *
277 gdb_completer_file_name_dequote (char *filename, int quote_char)
279 std::string tmp;
281 if (quote_char == '\'')
283 /* There is no backslash escaping within a single quoted string. In
284 this case we can just return the input string. */
285 tmp = filename;
287 else if (quote_char == '"')
289 /* Remove escaping from a double quoted string. */
290 for (const char *input = filename;
291 *input != '\0';
292 ++input)
294 if (input[0] == '\\'
295 && input[1] != '\0'
296 && strchr ("\"\\", input[1]) != nullptr)
297 ++input;
298 tmp += *input;
301 else
303 gdb_assert (quote_char == '\0');
305 /* Remove escaping from an unquoted string. */
306 for (const char *input = filename;
307 *input != '\0';
308 ++input)
310 /* We allow anything to be escaped in an unquoted string. */
311 if (*input == '\\')
313 ++input;
314 if (*input == '\0')
315 break;
318 tmp += *input;
322 return strdup (tmp.c_str ());
325 /* Implement readline's rl_directory_rewrite_hook. Remove any quoting from
326 the string *DIRNAME,update *DIRNAME, and return non-zero. If *DIRNAME
327 doesn't need updating then return zero. See readline docs for more
328 information. */
330 static int
331 gdb_completer_directory_rewrite (char **dirname)
333 if (!rl_completion_found_quote)
334 return 0;
336 int quote_char = rl_completion_quote_character;
337 char *new_dirname
338 = gdb_completer_file_name_dequote (*dirname, quote_char);
339 free (*dirname);
340 *dirname = new_dirname;
342 return 1;
345 /* Apply character escaping to the filename in TEXT and return a newly
346 allocated buffer containing the possibly updated filename.
348 QUOTE_CHAR is the quote character surrounding TEXT, or the
349 null-character if there are no quotes around TEXT. */
351 static char *
352 gdb_completer_file_name_quote_1 (const char *text, char quote_char)
354 std::string str;
356 if (quote_char == '\'')
358 /* There is no backslash escaping permitted within a single quoted
359 string, so in this case we can just return the input sting. */
360 str = text;
362 else if (quote_char == '"')
364 /* Add escaping for a double quoted filename. */
365 for (const char *input = text;
366 *input != '\0';
367 ++input)
369 if (strchr ("\"\\", *input) != nullptr)
370 str += '\\';
371 str += *input;
374 else
376 gdb_assert (quote_char == '\0');
378 /* Add escaping for an unquoted filename. */
379 for (const char *input = text;
380 *input != '\0';
381 ++input)
383 if (strchr (" \t\n\\\"'", *input)
384 != nullptr)
385 str += '\\';
386 str += *input;
390 return strdup (str.c_str ());
393 /* Apply character escaping to the filename in TEXT. QUOTE_PTR points to
394 the quote character surrounding TEXT, or points to the null-character if
395 there are no quotes around TEXT. MATCH_TYPE will be one of the readline
396 constants SINGLE_MATCH or MULTI_MATCH depending on if there is one or
397 many completions.
399 We also add a trailing character, either a '/' of closing quote, if
400 MATCH_TYPE is 'SINGLE_MATCH'. We do this because readline will only
401 add this trailing character when completing at the end of a line. */
403 static char *
404 gdb_completer_file_name_quote (char *text, int match_type, char *quote_ptr)
406 char *result = gdb_completer_file_name_quote_1 (text, *quote_ptr);
408 if (match_type == SINGLE_MATCH)
410 /* Add trailing '/' if TEXT is a directory, otherwise add a closing
411 quote character matching *QUOTE_PTR. */
412 char c = (gdb_path_isdir (gdb_tilde_expand (text).c_str ())
413 ? '/' : *quote_ptr);
415 /* Reallocate RESULT adding C to the end. But only if C is
416 interesting, otherwise we can save the reallocation. */
417 if (c != '\0')
419 char buf[2] = { c, '\0' };
420 result = reconcat (result, result, buf, nullptr);
424 return result;
427 /* The function is used to update the completion word MATCH before
428 displaying it to the user in the 'complete' command output. This
429 function is only used for formatting filename or directory names.
431 This function checks to see if the completion word MATCH is a directory,
432 in which case a trailing "/" (forward-slash) is added, otherwise
433 QUOTE_CHAR is added as a trailing quote.
435 When ADD_ESCAPES is true any special characters (e.g. whitespace,
436 quotes) will be escaped with a backslash. See
437 gdb_completer_file_name_quote_1 for full details on escaping. When
438 ADD_ESCAPES is false then no escaping will be added and MATCH (with the
439 correct trailing character) will be used unmodified.
441 Return the updated completion word as a string. */
443 static std::string
444 filename_match_formatter_1 (const char *match, char quote_char,
445 bool add_escapes)
447 std::string result;
448 if (add_escapes)
450 gdb::unique_xmalloc_ptr<char> quoted_match
451 (gdb_completer_file_name_quote_1 (match, quote_char));
452 result = quoted_match.get ();
454 else
455 result = match;
457 if (gdb_path_isdir (gdb_tilde_expand (match).c_str ()))
458 result += "/";
459 else
460 result += quote_char;
462 return result;
465 /* The formatting function used to format the results of a 'complete'
466 command when the result is a filename, but the filename should not have
467 any escape characters added. Most commands that accept a filename don't
468 expect the filename to be quoted or to contain escape characters.
470 See filename_match_formatter_1 for more argument details. */
472 static std::string
473 filename_unquoted_match_formatter (const char *match, char quote_char)
475 return filename_match_formatter_1 (match, quote_char, false);
478 /* The formatting function used to format the results of a 'complete'
479 command when the result is a filename, and the filename should have any
480 special character (e.g. whitespace, quotes) within it escaped with a
481 backslash. A limited number of commands accept this style of filename
482 argument.
484 See filename_match_formatter_1 for more argument details. */
486 static std::string
487 filename_maybe_quoted_match_formatter (const char *match, char quote_char)
489 return filename_match_formatter_1 (match, quote_char, true);
492 /* Generate filename completions of WORD, storing the completions into
493 TRACKER. This is used for generating completions for commands that
494 only accept unquoted filenames as well as for commands that accept
495 quoted and escaped filenames.
497 When QUOTE_MATCHES is true TRACKER will be given a match formatter
498 function which will add escape characters (if needed) in the results.
499 When QUOTE_MATCHES is false the match formatter provided will not add
500 any escaping to the results. */
502 static void
503 filename_completer_generate_completions (completion_tracker &tracker,
504 const char *word,
505 bool quote_matches)
507 if (quote_matches)
508 tracker.set_match_format_func (filename_maybe_quoted_match_formatter);
509 else
510 tracker.set_match_format_func (filename_unquoted_match_formatter);
512 int subsequent_name = 0;
513 while (1)
515 gdb::unique_xmalloc_ptr<char> p_rl
516 (rl_filename_completion_function (word, subsequent_name));
517 if (p_rl == NULL)
518 break;
519 /* We need to set subsequent_name to a non-zero value before the
520 continue line below, because otherwise, if the first file
521 seen by GDB is a backup file whose name ends in a `~', we
522 will loop indefinitely. */
523 subsequent_name = 1;
524 /* Like emacs, don't complete on old versions. Especially
525 useful in the "source" command. */
526 const char *p = p_rl.get ();
527 if (p[strlen (p) - 1] == '~')
528 continue;
530 tracker.add_completion
531 (make_completion_match_str (std::move (p_rl), word, word));
535 /* The brkchars callback used when completing filenames that can be
536 quoted. */
538 static void
539 filename_maybe_quoted_completer_handle_brkchars
540 (struct cmd_list_element *ignore, completion_tracker &tracker,
541 const char *text, const char *word)
543 set_rl_completer_word_break_characters
544 (gdb_completer_file_name_break_characters);
546 rl_completer_quote_characters = gdb_completer_file_name_quote_characters;
547 rl_char_is_quoted_p = gdb_completer_file_name_char_is_quoted;
550 /* Complete on filenames. This is for commands that accepts possibly
551 quoted filenames. */
553 void
554 filename_maybe_quoted_completer (struct cmd_list_element *ignore,
555 completion_tracker &tracker,
556 const char *text, const char *word)
558 filename_maybe_quoted_completer_handle_brkchars (ignore, tracker,
559 text, word);
560 filename_completer_generate_completions (tracker, word, true);
563 /* The brkchars callback used by commands that don't accept quoted
564 filenames. */
566 static void
567 deprecated_filename_completer_handle_brkchars
568 (struct cmd_list_element *ignore, completion_tracker &tracker,
569 const char *text, const char *word)
571 gdb_assert (word == nullptr);
573 set_rl_completer_word_break_characters (gdb_completer_path_break_characters);
574 rl_completer_quote_characters = nullptr;
575 rl_filename_quoting_desired = 0;
577 tracker.set_use_custom_word_point (true);
578 word = advance_to_deprecated_filename_complete_word_point (tracker, text);
579 deprecated_filename_completer (ignore, tracker, text, word);
582 /* See completer.h. */
584 void
585 deprecated_filename_completer
586 (struct cmd_list_element *ignore, completion_tracker &tracker,
587 const char *text, const char *word)
589 gdb_assert (tracker.use_custom_word_point ());
590 gdb_assert (word != nullptr);
591 filename_completer_generate_completions (tracker, word, false);
594 /* Find the bounds of the current word for completion purposes, and
595 return a pointer to the end of the word. This mimics (and is a
596 modified version of) readline's _rl_find_completion_word internal
597 function.
599 This function skips quoted substrings (characters between matched
600 pairs of characters in rl_completer_quote_characters). We try to
601 find an unclosed quoted substring on which to do matching. If one
602 is not found, we use the word break characters to find the
603 boundaries of the current word. QC, if non-null, is set to the
604 opening quote character if we found an unclosed quoted substring,
605 '\0' otherwise. DP, if non-null, is set to the value of the
606 delimiter character that caused a word break. FOUND_ANY_QUOTING, if
607 non-null, is set to true if we found any quote characters (single or
608 double quotes, or a backslash) while finding the completion word. */
610 struct gdb_rl_completion_word_info
612 const char *word_break_characters;
613 const char *quote_characters;
614 const char *basic_quote_characters;
617 static const char *
618 gdb_rl_find_completion_word (struct gdb_rl_completion_word_info *info,
619 int *qc, int *dp, bool *found_any_quoting,
620 const char *line_buffer)
622 int scan, end, delimiter, pass_next, isbrk;
623 char quote_char;
624 const char *brkchars;
625 int point = strlen (line_buffer);
627 /* The algorithm below does '--point'. Avoid buffer underflow with
628 the empty string. */
629 if (point == 0)
631 if (found_any_quoting != nullptr)
632 *found_any_quoting = false;
633 if (qc != NULL)
634 *qc = '\0';
635 if (dp != NULL)
636 *dp = '\0';
637 return line_buffer;
640 end = point;
641 delimiter = 0;
642 quote_char = '\0';
643 bool found_quote = false;
645 brkchars = info->word_break_characters;
647 if (info->quote_characters != NULL)
649 /* We have a list of characters which can be used in pairs to
650 quote substrings for the completer. Try to find the start of
651 an unclosed quoted substring. */
652 for (scan = pass_next = 0;
653 scan < end;
654 scan++)
656 if (pass_next)
658 pass_next = 0;
659 continue;
662 /* Shell-like semantics for single quotes -- don't allow
663 backslash to quote anything in single quotes, especially
664 not the closing quote. If you don't like this, take out
665 the check on the value of quote_char. */
666 if (quote_char != '\'' && line_buffer[scan] == '\\')
668 pass_next = 1;
669 found_quote = true;
670 continue;
673 if (quote_char != '\0')
675 /* Ignore everything until the matching close quote
676 char. */
677 if (line_buffer[scan] == quote_char)
679 /* Found matching close. Abandon this
680 substring. */
681 quote_char = '\0';
682 point = end;
685 else if (strchr (info->quote_characters, line_buffer[scan]))
687 /* Found start of a quoted substring. */
688 quote_char = line_buffer[scan];
689 point = scan + 1;
690 found_quote = true;
695 if (point == end && quote_char == '\0')
697 /* We didn't find an unclosed quoted substring upon which to do
698 completion, so use the word break characters to find the
699 substring on which to complete. */
700 while (--point)
702 scan = line_buffer[point];
704 if (strchr (brkchars, scan) == 0)
705 continue;
707 /* Call the application-specific function to tell us whether
708 this word break character is quoted and should be skipped.
709 The const_cast is needed here to comply with the readline
710 API. The only function we register for rl_char_is_quoted_p
711 treats the input buffer as 'const', so we're OK. */
712 if (rl_char_is_quoted_p != nullptr && found_quote
713 && (*rl_char_is_quoted_p) (const_cast<char *> (line_buffer),
714 point))
715 continue;
717 /* Convoluted code, but it avoids an n^2 algorithm with calls
718 to char_is_quoted. */
719 break;
723 /* If we are at an unquoted word break, then advance past it. */
724 scan = line_buffer[point];
726 if (scan)
728 isbrk = strchr (brkchars, scan) != 0;
730 if (isbrk)
732 /* If the character that caused the word break was a quoting
733 character, then remember it as the delimiter. */
734 if (info->basic_quote_characters
735 && strchr (info->basic_quote_characters, scan)
736 && (end - point) > 1)
737 delimiter = scan;
739 point++;
743 if (found_any_quoting != nullptr)
744 *found_any_quoting = found_quote;
745 if (qc != NULL)
746 *qc = quote_char;
747 if (dp != NULL)
748 *dp = delimiter;
750 return line_buffer + point;
753 /* Find the completion word point for TEXT, emulating the algorithm
754 readline uses to find the word point, using WORD_BREAK_CHARACTERS
755 as word break characters.
757 The output argument *FOUND_ANY_QUOTING is set to true if the completion
758 word found either has an opening quote, or contains backslash escaping
759 within it. Otherwise *FOUND_ANY_QUOTING is set to false.
761 The output argument *QC is set to the opening quote character for the
762 completion word that is found, or to the null character if there is no
763 opening quote. */
765 static const char *
766 advance_to_completion_word (completion_tracker &tracker,
767 const char *word_break_characters,
768 const char *quote_characters,
769 const char *text,
770 bool *found_any_quoting,
771 int *qc)
773 gdb_rl_completion_word_info info;
775 info.word_break_characters = word_break_characters;
776 info.quote_characters = quote_characters;
777 info.basic_quote_characters = rl_basic_quote_characters;
779 int delimiter;
780 const char *start
781 = gdb_rl_find_completion_word (&info, qc, &delimiter, found_any_quoting,
782 text);
784 tracker.advance_custom_word_point_by (start - text);
786 if (delimiter)
788 tracker.set_quote_char (delimiter);
789 tracker.set_suppress_append_ws (true);
792 return start;
795 /* See completer.h. */
797 const char *
798 advance_to_expression_complete_word_point (completion_tracker &tracker,
799 const char *text)
801 const char *brk_chars = current_language->word_break_characters ();
802 const char *quote_chars = gdb_completer_expression_quote_characters;
803 return advance_to_completion_word (tracker, brk_chars, quote_chars,
804 text, nullptr, nullptr);
807 /* See completer.h. */
809 const char *
810 advance_to_filename_maybe_quoted_complete_word_point
811 (completion_tracker &tracker, const char *text)
813 const char *brk_chars = gdb_completer_file_name_break_characters;
814 const char *quote_chars = gdb_completer_file_name_quote_characters;
815 rl_char_is_quoted_p = gdb_completer_file_name_char_is_quoted;
816 bool found_any_quoting = false;
817 int qc;
818 const char *result
819 = advance_to_completion_word (tracker, brk_chars, quote_chars,
820 text, &found_any_quoting, &qc);
821 rl_completion_found_quote = found_any_quoting ? 1 : 0;
822 if (qc != '\0')
824 tracker.set_quote_char (qc);
825 /* If we're completing for readline (not the 'complete' command) then
826 we want readline to correctly detect the opening quote. The set
827 of quote characters will have been set during the brkchars phase,
828 so now we move the word point back by one (so it's pointing at
829 the quote character) and now readline will correctly spot the
830 opening quote. For the 'complete' command setting the quote
831 character in the tracker is enough, so there's no need to move
832 the word point back here. */
833 if (tracker.from_readline ())
834 tracker.advance_custom_word_point_by (-1);
836 return result;
839 /* See completer.h. */
841 const char *
842 advance_to_deprecated_filename_complete_word_point (completion_tracker &tracker,
843 const char *text)
845 const char *brk_chars = gdb_completer_path_break_characters;
846 const char *quote_chars = nullptr;
847 rl_filename_quoting_desired = 0;
849 return advance_to_completion_word (tracker, brk_chars, quote_chars,
850 text, nullptr, nullptr);
853 /* See completer.h. */
855 bool
856 completion_tracker::completes_to_completion_word (const char *word)
858 recompute_lowest_common_denominator ();
859 if (m_lowest_common_denominator_unique)
861 const char *lcd = m_lowest_common_denominator;
863 if (strncmp_iw (word, lcd, strlen (lcd)) == 0)
865 /* Maybe skip the function and complete on keywords. */
866 size_t wordlen = strlen (word);
867 if (word[wordlen - 1] == ' ')
868 return true;
872 return false;
875 /* See completer.h. */
877 void
878 complete_nested_command_line (completion_tracker &tracker, const char *text)
880 /* Must be called from a custom-word-point completer. */
881 gdb_assert (tracker.use_custom_word_point ());
883 /* Disable the custom word point temporarily, because we want to
884 probe whether the command we're completing itself uses a custom
885 word point. */
886 tracker.set_use_custom_word_point (false);
887 size_t save_custom_word_point = tracker.custom_word_point ();
889 int quote_char = '\0';
890 const char *word = completion_find_completion_word (tracker, text,
891 &quote_char,
892 nullptr);
894 if (tracker.use_custom_word_point ())
896 /* The command we're completing uses a custom word point, so the
897 tracker already contains the matches. We're done. */
898 return;
901 /* Restore the custom word point settings. */
902 tracker.set_custom_word_point (save_custom_word_point);
903 tracker.set_use_custom_word_point (true);
905 /* Run the handle_completions completer phase. */
906 complete_line (tracker, word, text, strlen (text));
909 /* Complete on linespecs, which might be of two possible forms:
911 file:line
913 symbol+offset
915 This is intended to be used in commands that set breakpoints
916 etc. */
918 static void
919 complete_files_symbols (completion_tracker &tracker,
920 const char *text, const char *word)
922 completion_list fn_list;
923 const char *p;
924 int quote_found = 0;
925 int quoted = *text == '\'' || *text == '"';
926 int quote_char = '\0';
927 const char *colon = NULL;
928 char *file_to_match = NULL;
929 const char *symbol_start = text;
930 const char *orig_text = text;
932 /* Do we have an unquoted colon, as in "break foo.c:bar"? */
933 for (p = text; *p != '\0'; ++p)
935 if (*p == '\\' && p[1] == '\'')
936 p++;
937 else if (*p == '\'' || *p == '"')
939 quote_found = *p;
940 quote_char = *p++;
941 while (*p != '\0' && *p != quote_found)
943 if (*p == '\\' && p[1] == quote_found)
944 p++;
945 p++;
948 if (*p == quote_found)
949 quote_found = 0;
950 else
951 break; /* Hit the end of text. */
953 #if HAVE_DOS_BASED_FILE_SYSTEM
954 /* If we have a DOS-style absolute file name at the beginning of
955 TEXT, and the colon after the drive letter is the only colon
956 we found, pretend the colon is not there. */
957 else if (p < text + 3 && *p == ':' && p == text + 1 + quoted)
959 #endif
960 else if (*p == ':' && !colon)
962 colon = p;
963 symbol_start = p + 1;
965 else if (strchr (current_language->word_break_characters (), *p))
966 symbol_start = p + 1;
969 if (quoted)
970 text++;
972 /* Where is the file name? */
973 if (colon)
975 char *s;
977 file_to_match = (char *) xmalloc (colon - text + 1);
978 strncpy (file_to_match, text, colon - text);
979 file_to_match[colon - text] = '\0';
980 /* Remove trailing colons and quotes from the file name. */
981 for (s = file_to_match + (colon - text);
982 s > file_to_match;
983 s--)
984 if (*s == ':' || *s == quote_char)
985 *s = '\0';
987 /* If the text includes a colon, they want completion only on a
988 symbol name after the colon. Otherwise, we need to complete on
989 symbols as well as on files. */
990 if (colon)
992 collect_file_symbol_completion_matches (tracker,
993 complete_symbol_mode::EXPRESSION,
994 symbol_name_match_type::EXPRESSION,
995 symbol_start, word,
996 file_to_match);
997 xfree (file_to_match);
999 else
1001 size_t text_len = strlen (text);
1003 collect_symbol_completion_matches (tracker,
1004 complete_symbol_mode::EXPRESSION,
1005 symbol_name_match_type::EXPRESSION,
1006 symbol_start, word);
1007 /* If text includes characters which cannot appear in a file
1008 name, they cannot be asking for completion on files. */
1009 if (strcspn (text, gdb_completer_file_name_break_characters)
1010 == text_len)
1011 fn_list = make_source_files_completion_list (text, text);
1014 if (!fn_list.empty () && !tracker.have_completions ())
1016 /* If we only have file names as possible completion, we should
1017 bring them in sync with what rl_complete expects. The
1018 problem is that if the user types "break /foo/b TAB", and the
1019 possible completions are "/foo/bar" and "/foo/baz"
1020 rl_complete expects us to return "bar" and "baz", without the
1021 leading directories, as possible completions, because `word'
1022 starts at the "b". But we ignore the value of `word' when we
1023 call make_source_files_completion_list above (because that
1024 would not DTRT when the completion results in both symbols
1025 and file names), so make_source_files_completion_list returns
1026 the full "/foo/bar" and "/foo/baz" strings. This produces
1027 wrong results when, e.g., there's only one possible
1028 completion, because rl_complete will prepend "/foo/" to each
1029 candidate completion. The loop below removes that leading
1030 part. */
1031 for (const auto &fn_up: fn_list)
1033 char *fn = fn_up.get ();
1034 memmove (fn, fn + (word - text), strlen (fn) + 1 - (word - text));
1038 tracker.add_completions (std::move (fn_list));
1040 if (!tracker.have_completions ())
1042 /* No completions at all. As the final resort, try completing
1043 on the entire text as a symbol. */
1044 collect_symbol_completion_matches (tracker,
1045 complete_symbol_mode::EXPRESSION,
1046 symbol_name_match_type::EXPRESSION,
1047 orig_text, word);
1051 /* See completer.h. */
1053 completion_list
1054 complete_source_filenames (const char *text)
1056 size_t text_len = strlen (text);
1058 /* If text includes characters which cannot appear in a file name,
1059 the user cannot be asking for completion on files. */
1060 if (strcspn (text, gdb_completer_file_name_break_characters)
1061 == text_len)
1062 return make_source_files_completion_list (text, text);
1064 return {};
1067 /* Complete address and linespec locations. */
1069 static void
1070 complete_address_and_linespec_locations (completion_tracker &tracker,
1071 const char *text,
1072 symbol_name_match_type match_type)
1074 if (*text == '*')
1076 tracker.advance_custom_word_point_by (1);
1077 text++;
1078 const char *word
1079 = advance_to_expression_complete_word_point (tracker, text);
1080 complete_expression (tracker, text, word);
1082 else
1084 linespec_complete (tracker, text, match_type);
1088 /* The explicit location options. Note that indexes into this array
1089 must match the explicit_location_match_type enumerators. */
1091 static const char *const explicit_options[] =
1093 "-source",
1094 "-function",
1095 "-qualified",
1096 "-line",
1097 "-label",
1098 NULL
1101 /* The probe modifier options. These can appear before a location in
1102 breakpoint commands. */
1103 static const char *const probe_options[] =
1105 "-probe",
1106 "-probe-stap",
1107 "-probe-dtrace",
1108 NULL
1111 /* Returns STRING if not NULL, the empty string otherwise. */
1113 static const char *
1114 string_or_empty (const char *string)
1116 return string != NULL ? string : "";
1119 /* A helper function to collect explicit location matches for the given
1120 LOCATION, which is attempting to match on WORD. */
1122 static void
1123 collect_explicit_location_matches (completion_tracker &tracker,
1124 location_spec *locspec,
1125 enum explicit_location_match_type what,
1126 const char *word,
1127 const struct language_defn *language)
1129 const explicit_location_spec *explicit_loc
1130 = as_explicit_location_spec (locspec);
1132 /* True if the option expects an argument. */
1133 bool needs_arg = true;
1135 /* Note, in the various MATCH_* below, we complete on
1136 explicit_loc->foo instead of WORD, because only the former will
1137 have already skipped past any quote char. */
1138 switch (what)
1140 case MATCH_SOURCE:
1142 const char *source
1143 = string_or_empty (explicit_loc->source_filename.get ());
1144 completion_list matches
1145 = make_source_files_completion_list (source, source);
1146 tracker.add_completions (std::move (matches));
1148 break;
1150 case MATCH_FUNCTION:
1152 const char *function
1153 = string_or_empty (explicit_loc->function_name.get ());
1154 linespec_complete_function (tracker, function,
1155 explicit_loc->func_name_match_type,
1156 explicit_loc->source_filename.get ());
1158 break;
1160 case MATCH_QUALIFIED:
1161 needs_arg = false;
1162 break;
1163 case MATCH_LINE:
1164 /* Nothing to offer. */
1165 break;
1167 case MATCH_LABEL:
1169 const char *label = string_or_empty (explicit_loc->label_name.get ());
1170 linespec_complete_label (tracker, language,
1171 explicit_loc->source_filename.get (),
1172 explicit_loc->function_name.get (),
1173 explicit_loc->func_name_match_type,
1174 label);
1176 break;
1178 default:
1179 gdb_assert_not_reached ("unhandled explicit_location_match_type");
1182 if (!needs_arg || tracker.completes_to_completion_word (word))
1184 tracker.discard_completions ();
1185 tracker.advance_custom_word_point_by (strlen (word));
1186 complete_on_enum (tracker, explicit_options, "", "");
1187 complete_on_enum (tracker, linespec_keywords, "", "");
1189 else if (!tracker.have_completions ())
1191 /* Maybe we have an unterminated linespec keyword at the tail of
1192 the string. Try completing on that. */
1193 size_t wordlen = strlen (word);
1194 const char *keyword = word + wordlen;
1196 if (wordlen > 0 && keyword[-1] != ' ')
1198 while (keyword > word && *keyword != ' ')
1199 keyword--;
1200 /* Don't complete on keywords if we'd be completing on the
1201 whole explicit linespec option. E.g., "b -function
1202 thr<tab>" should not complete to the "thread"
1203 keyword. */
1204 if (keyword != word)
1206 keyword = skip_spaces (keyword);
1208 tracker.advance_custom_word_point_by (keyword - word);
1209 complete_on_enum (tracker, linespec_keywords, keyword, keyword);
1212 else if (wordlen > 0 && keyword[-1] == ' ')
1214 /* Assume that we're maybe past the explicit location
1215 argument, and we didn't manage to find any match because
1216 the user wants to create a pending breakpoint. Offer the
1217 keyword and explicit location options as possible
1218 completions. */
1219 tracker.advance_custom_word_point_by (keyword - word);
1220 complete_on_enum (tracker, linespec_keywords, keyword, keyword);
1221 complete_on_enum (tracker, explicit_options, keyword, keyword);
1226 /* If the next word in *TEXT_P is any of the keywords in KEYWORDS,
1227 then advance both TEXT_P and the word point in the tracker past the
1228 keyword and return the (0-based) index in the KEYWORDS array that
1229 matched. Otherwise, return -1. */
1231 static int
1232 skip_keyword (completion_tracker &tracker,
1233 const char * const *keywords, const char **text_p)
1235 const char *text = *text_p;
1236 const char *after = skip_to_space (text);
1237 size_t len = after - text;
1239 if (text[len] != ' ')
1240 return -1;
1242 int found = -1;
1243 for (int i = 0; keywords[i] != NULL; i++)
1245 if (strncmp (keywords[i], text, len) == 0)
1247 if (found == -1)
1248 found = i;
1249 else
1250 return -1;
1254 if (found != -1)
1256 tracker.advance_custom_word_point_by (len + 1);
1257 text += len + 1;
1258 *text_p = text;
1259 return found;
1262 return -1;
1265 /* A completer function for explicit location specs. This function
1266 completes both options ("-source", "-line", etc) and values. If
1267 completing a quoted string, then QUOTED_ARG_START and
1268 QUOTED_ARG_END point to the quote characters. LANGUAGE is the
1269 current language. */
1271 static void
1272 complete_explicit_location_spec (completion_tracker &tracker,
1273 location_spec *locspec,
1274 const char *text,
1275 const language_defn *language,
1276 const char *quoted_arg_start,
1277 const char *quoted_arg_end)
1279 if (*text != '-')
1280 return;
1282 int keyword = skip_keyword (tracker, explicit_options, &text);
1284 if (keyword == -1)
1286 complete_on_enum (tracker, explicit_options, text, text);
1287 /* There are keywords that start with "-". Include them, too. */
1288 complete_on_enum (tracker, linespec_keywords, text, text);
1290 else
1292 /* Completing on value. */
1293 enum explicit_location_match_type what
1294 = (explicit_location_match_type) keyword;
1296 if (quoted_arg_start != NULL && quoted_arg_end != NULL)
1298 if (quoted_arg_end[1] == '\0')
1300 /* If completing a quoted string with the cursor right
1301 at the terminating quote char, complete the
1302 completion word without interpretation, so that
1303 readline advances the cursor one whitespace past the
1304 quote, even if there's no match. This makes these
1305 cases behave the same:
1307 before: "b -function function()"
1308 after: "b -function function() "
1310 before: "b -function 'function()'"
1311 after: "b -function 'function()' "
1313 and trusts the user in this case:
1315 before: "b -function 'not_loaded_function_yet()'"
1316 after: "b -function 'not_loaded_function_yet()' "
1318 tracker.add_completion (make_unique_xstrdup (text));
1320 else if (quoted_arg_end[1] == ' ')
1322 /* We're maybe past the explicit location argument.
1323 Skip the argument without interpretation, assuming the
1324 user may want to create pending breakpoint. Offer
1325 the keyword and explicit location options as possible
1326 completions. */
1327 tracker.advance_custom_word_point_by (strlen (text));
1328 complete_on_enum (tracker, linespec_keywords, "", "");
1329 complete_on_enum (tracker, explicit_options, "", "");
1331 return;
1334 /* Now gather matches */
1335 collect_explicit_location_matches (tracker, locspec, what, text,
1336 language);
1340 /* A completer for locations. */
1342 void
1343 location_completer (struct cmd_list_element *ignore,
1344 completion_tracker &tracker,
1345 const char *text, const char * /* word */)
1347 int found_probe_option = -1;
1349 /* If we have a probe modifier, skip it. This can only appear as
1350 first argument. Until we have a specific completer for probes,
1351 falling back to the linespec completer for the remainder of the
1352 line is better than nothing. */
1353 if (text[0] == '-' && text[1] == 'p')
1354 found_probe_option = skip_keyword (tracker, probe_options, &text);
1356 const char *option_text = text;
1357 int saved_word_point = tracker.custom_word_point ();
1359 const char *copy = text;
1361 explicit_completion_info completion_info;
1362 location_spec_up locspec
1363 = string_to_explicit_location_spec (&copy, current_language,
1364 &completion_info);
1365 if (completion_info.quoted_arg_start != NULL
1366 && completion_info.quoted_arg_end == NULL)
1368 /* Found an unbalanced quote. */
1369 tracker.set_quote_char (*completion_info.quoted_arg_start);
1370 tracker.advance_custom_word_point_by (1);
1373 if (completion_info.saw_explicit_location_spec_option)
1375 if (*copy != '\0')
1377 tracker.advance_custom_word_point_by (copy - text);
1378 text = copy;
1380 /* We found a terminator at the tail end of the string,
1381 which means we're past the explicit location options. We
1382 may have a keyword to complete on. If we have a whole
1383 keyword, then complete whatever comes after as an
1384 expression. This is mainly for the "if" keyword. If the
1385 "thread" and "task" keywords gain their own completers,
1386 they should be used here. */
1387 int keyword = skip_keyword (tracker, linespec_keywords, &text);
1389 if (keyword == -1)
1391 complete_on_enum (tracker, linespec_keywords, text, text);
1393 else
1395 const char *word
1396 = advance_to_expression_complete_word_point (tracker, text);
1397 complete_expression (tracker, text, word);
1400 else
1402 tracker.advance_custom_word_point_by (completion_info.last_option
1403 - text);
1404 text = completion_info.last_option;
1406 complete_explicit_location_spec (tracker, locspec.get (), text,
1407 current_language,
1408 completion_info.quoted_arg_start,
1409 completion_info.quoted_arg_end);
1413 /* This is an address or linespec location. */
1414 else if (locspec != nullptr)
1416 /* Handle non-explicit location options. */
1418 int keyword = skip_keyword (tracker, explicit_options, &text);
1419 if (keyword == -1)
1420 complete_on_enum (tracker, explicit_options, text, text);
1421 else
1423 tracker.advance_custom_word_point_by (copy - text);
1424 text = copy;
1426 symbol_name_match_type match_type
1427 = as_explicit_location_spec (locspec.get ())->func_name_match_type;
1428 complete_address_and_linespec_locations (tracker, text, match_type);
1431 else
1433 /* No options. */
1434 complete_address_and_linespec_locations (tracker, text,
1435 symbol_name_match_type::WILD);
1438 /* Add matches for option names, if either:
1440 - Some completer above found some matches, but the word point did
1441 not advance (e.g., "b <tab>" finds all functions, or "b -<tab>"
1442 matches all objc selectors), or;
1444 - Some completer above advanced the word point, but found no
1445 matches.
1447 if ((text[0] == '-' || text[0] == '\0')
1448 && (!tracker.have_completions ()
1449 || tracker.custom_word_point () == saved_word_point))
1451 tracker.set_custom_word_point (saved_word_point);
1452 text = option_text;
1454 if (found_probe_option == -1)
1455 complete_on_enum (tracker, probe_options, text, text);
1456 complete_on_enum (tracker, explicit_options, text, text);
1460 /* The corresponding completer_handle_brkchars
1461 implementation. */
1463 static void
1464 location_completer_handle_brkchars (struct cmd_list_element *ignore,
1465 completion_tracker &tracker,
1466 const char *text,
1467 const char *word_ignored)
1469 tracker.set_use_custom_word_point (true);
1471 location_completer (ignore, tracker, text, NULL);
1474 /* See completer.h. */
1476 void
1477 complete_expression (completion_tracker &tracker,
1478 const char *text, const char *word)
1480 expression_up exp;
1481 std::unique_ptr<expr_completion_base> expr_completer;
1483 /* Perform a tentative parse of the expression, to see whether a
1484 field completion is required. */
1487 exp = parse_expression_for_completion (text, &expr_completer);
1489 catch (const gdb_exception_error &except)
1491 return;
1494 /* Part of the parse_expression_for_completion contract. */
1495 gdb_assert ((exp == nullptr) == (expr_completer == nullptr));
1496 if (expr_completer != nullptr
1497 && expr_completer->complete (exp.get (), tracker))
1498 return;
1500 complete_files_symbols (tracker, text, word);
1503 /* Complete on expressions. Often this means completing on symbol
1504 names, but some language parsers also have support for completing
1505 field names. */
1507 void
1508 expression_completer (struct cmd_list_element *ignore,
1509 completion_tracker &tracker,
1510 const char *text, const char *word)
1512 complete_expression (tracker, text, word);
1515 /* Set the word break characters array to BREAK_CHARS. This function is
1516 useful as const-correct alternative to direct assignment to
1517 rl_completer_word_break_characters, which is "char *", not "const
1518 char *". */
1520 static void
1521 set_rl_completer_word_break_characters (const char *break_chars)
1523 rl_completer_word_break_characters = (char *) break_chars;
1526 /* Complete on symbols. */
1528 void
1529 symbol_completer (struct cmd_list_element *ignore,
1530 completion_tracker &tracker,
1531 const char *text, const char *word)
1533 collect_symbol_completion_matches (tracker, complete_symbol_mode::EXPRESSION,
1534 symbol_name_match_type::EXPRESSION,
1535 text, word);
1538 /* Here are some useful test cases for completion. FIXME: These
1539 should be put in the test suite. They should be tested with both
1540 M-? and TAB.
1542 "show output-" "radix"
1543 "show output" "-radix"
1544 "p" ambiguous (commands starting with p--path, print, printf, etc.)
1545 "p " ambiguous (all symbols)
1546 "info t foo" no completions
1547 "info t " no completions
1548 "info t" ambiguous ("info target", "info terminal", etc.)
1549 "info ajksdlfk" no completions
1550 "info ajksdlfk " no completions
1551 "info" " "
1552 "info " ambiguous (all info commands)
1553 "p \"a" no completions (string constant)
1554 "p 'a" ambiguous (all symbols starting with a)
1555 "p b-a" ambiguous (all symbols starting with a)
1556 "p b-" ambiguous (all symbols)
1557 "file Make" "file" (word break hard to screw up here)
1558 "file ../gdb.stabs/we" "ird" (needs to not break word at slash)
1561 enum complete_line_internal_reason
1563 /* Preliminary phase, called by gdb_completion_word_break_characters
1564 function, is used to either:
1566 #1 - Determine the set of chars that are word delimiters
1567 depending on the current command in line_buffer.
1569 #2 - Manually advance RL_POINT to the "word break" point instead
1570 of letting readline do it (based on too-simple character
1571 matching).
1573 Simpler completers that just pass a brkchars array to readline
1574 (#1 above) must defer generating the completions to the main
1575 phase (below). No completion list should be generated in this
1576 phase.
1578 OTOH, completers that manually advance the word point(#2 above)
1579 must set "use_custom_word_point" in the tracker and generate
1580 their completion in this phase. Note that this is the convenient
1581 thing to do since they'll be parsing the input line anyway. */
1582 handle_brkchars,
1584 /* Main phase, called by complete_line function, is used to get the
1585 list of possible completions. */
1586 handle_completions,
1588 /* Special case when completing a 'help' command. In this case,
1589 once sub-command completions are exhausted, we simply return
1590 NULL. */
1591 handle_help,
1594 /* Helper for complete_line_internal to simplify it. */
1596 static void
1597 complete_line_internal_normal_command (completion_tracker &tracker,
1598 const char *command, const char *word,
1599 const char *cmd_args,
1600 complete_line_internal_reason reason,
1601 struct cmd_list_element *c)
1603 if (reason == handle_brkchars)
1605 completer_handle_brkchars_ftype *brkchars_fn;
1607 if (c->completer_handle_brkchars != NULL)
1608 brkchars_fn = c->completer_handle_brkchars;
1609 else
1611 brkchars_fn
1612 = (completer_handle_brkchars_func_for_completer
1613 (c->completer));
1616 brkchars_fn (c, tracker, cmd_args, word);
1619 if (reason != handle_brkchars && c->completer != NULL)
1620 (*c->completer) (c, tracker, cmd_args, word);
1623 /* Internal function used to handle completions.
1626 TEXT is the caller's idea of the "word" we are looking at.
1628 LINE_BUFFER is available to be looked at; it contains the entire
1629 text of the line. POINT is the offset in that line of the cursor.
1630 You should pretend that the line ends at POINT.
1632 See complete_line_internal_reason for description of REASON. */
1634 static void
1635 complete_line_internal_1 (completion_tracker &tracker,
1636 const char *text,
1637 const char *line_buffer, int point,
1638 complete_line_internal_reason reason)
1640 char *tmp_command;
1641 const char *p;
1642 int ignore_help_classes;
1643 /* Pointer within tmp_command which corresponds to text. */
1644 const char *word;
1645 struct cmd_list_element *c, *result_list;
1647 /* Choose the default set of word break characters to break
1648 completions. If we later find out that we are doing completions
1649 on command strings (as opposed to strings supplied by the
1650 individual command completer functions, which can be any string)
1651 then we will switch to the special word break set for command
1652 strings, which leaves out the '-' and '.' character used in some
1653 commands. */
1654 set_rl_completer_word_break_characters
1655 (current_language->word_break_characters ());
1657 /* Likewise for the quote characters. If we later find out that we are
1658 completing file names then we can switch to the file name quote
1659 character set (i.e., both single- and double-quotes). */
1660 rl_completer_quote_characters = gdb_completer_expression_quote_characters;
1661 rl_char_is_quoted_p = nullptr;
1663 /* Decide whether to complete on a list of gdb commands or on
1664 symbols. */
1665 tmp_command = (char *) alloca (point + 1);
1666 p = tmp_command;
1668 /* The help command should complete help aliases. */
1669 ignore_help_classes = reason != handle_help;
1671 strncpy (tmp_command, line_buffer, point);
1672 tmp_command[point] = '\0';
1673 if (reason == handle_brkchars)
1675 gdb_assert (text == NULL);
1676 word = NULL;
1678 else
1680 /* Since text always contains some number of characters leading up
1681 to point, we can find the equivalent position in tmp_command
1682 by subtracting that many characters from the end of tmp_command. */
1683 word = tmp_command + point - strlen (text);
1686 /* Move P up to the start of the command. */
1687 p = skip_spaces (p);
1689 if (*p == '\0')
1691 /* An empty line is ambiguous; that is, it could be any
1692 command. */
1693 c = CMD_LIST_AMBIGUOUS;
1694 result_list = 0;
1696 else
1697 c = lookup_cmd_1 (&p, cmdlist, &result_list, NULL, ignore_help_classes,
1698 true);
1700 /* Move p up to the next interesting thing. */
1701 while (*p == ' ' || *p == '\t')
1703 p++;
1706 tracker.advance_custom_word_point_by (p - tmp_command);
1708 if (!c)
1710 /* It is an unrecognized command. So there are no
1711 possible completions. */
1713 else if (c == CMD_LIST_AMBIGUOUS)
1715 const char *q;
1717 /* lookup_cmd_1 advances p up to the first ambiguous thing, but
1718 doesn't advance over that thing itself. Do so now. */
1719 q = p;
1720 while (valid_cmd_char_p (*q))
1721 ++q;
1722 if (q != tmp_command + point)
1724 /* There is something beyond the ambiguous
1725 command, so there are no possible completions. For
1726 example, "info t " or "info t foo" does not complete
1727 to anything, because "info t" can be "info target" or
1728 "info terminal". */
1730 else
1732 /* We're trying to complete on the command which was ambiguous.
1733 This we can deal with. */
1734 if (result_list)
1736 if (reason != handle_brkchars)
1737 complete_on_cmdlist (*result_list->subcommands, tracker, p,
1738 word, ignore_help_classes);
1740 else
1742 if (reason != handle_brkchars)
1743 complete_on_cmdlist (cmdlist, tracker, p, word,
1744 ignore_help_classes);
1746 /* Ensure that readline does the right thing with respect to
1747 inserting quotes. */
1748 set_rl_completer_word_break_characters
1749 (gdb_completer_command_word_break_characters);
1752 else
1754 /* We've recognized a full command. */
1756 if (p == tmp_command + point)
1758 /* There is no non-whitespace in the line beyond the
1759 command. */
1761 if (p[-1] == ' ' || p[-1] == '\t')
1763 /* The command is followed by whitespace; we need to
1764 complete on whatever comes after command. */
1765 if (c->is_prefix ())
1767 /* It is a prefix command; what comes after it is
1768 a subcommand (e.g. "info "). */
1769 if (reason != handle_brkchars)
1770 complete_on_cmdlist (*c->subcommands, tracker, p, word,
1771 ignore_help_classes);
1773 /* Ensure that readline does the right thing
1774 with respect to inserting quotes. */
1775 set_rl_completer_word_break_characters
1776 (gdb_completer_command_word_break_characters);
1778 else if (reason == handle_help)
1780 else if (c->enums)
1782 if (reason != handle_brkchars)
1783 complete_on_enum (tracker, c->enums, p, word);
1784 set_rl_completer_word_break_characters
1785 (gdb_completer_command_word_break_characters);
1787 else
1789 /* It is a normal command; what comes after it is
1790 completed by the command's completer function. */
1791 complete_line_internal_normal_command (tracker,
1792 tmp_command, word, p,
1793 reason, c);
1796 else
1798 /* The command is not followed by whitespace; we need to
1799 complete on the command itself, e.g. "p" which is a
1800 command itself but also can complete to "print", "ptype"
1801 etc. */
1802 const char *q;
1804 /* Find the command we are completing on. */
1805 q = p;
1806 while (q > tmp_command)
1808 if (valid_cmd_char_p (q[-1]))
1809 --q;
1810 else
1811 break;
1814 /* Move the custom word point back too. */
1815 tracker.advance_custom_word_point_by (q - p);
1817 if (reason != handle_brkchars)
1818 complete_on_cmdlist (result_list, tracker, q, word,
1819 ignore_help_classes);
1821 /* Ensure that readline does the right thing
1822 with respect to inserting quotes. */
1823 set_rl_completer_word_break_characters
1824 (gdb_completer_command_word_break_characters);
1827 else if (reason == handle_help)
1829 else
1831 /* There is non-whitespace beyond the command. */
1833 if (c->is_prefix () && !c->allow_unknown)
1835 /* It is an unrecognized subcommand of a prefix command,
1836 e.g. "info adsfkdj". */
1838 else if (c->enums)
1840 if (reason != handle_brkchars)
1841 complete_on_enum (tracker, c->enums, p, word);
1843 else
1845 /* It is a normal command. */
1846 complete_line_internal_normal_command (tracker,
1847 tmp_command, word, p,
1848 reason, c);
1854 /* Wrapper around complete_line_internal_1 to handle
1855 MAX_COMPLETIONS_REACHED_ERROR. */
1857 static void
1858 complete_line_internal (completion_tracker &tracker,
1859 const char *text,
1860 const char *line_buffer, int point,
1861 complete_line_internal_reason reason)
1865 complete_line_internal_1 (tracker, text, line_buffer, point, reason);
1867 catch (const gdb_exception_error &except)
1869 if (except.error != MAX_COMPLETIONS_REACHED_ERROR)
1870 throw;
1874 /* See completer.h. */
1876 int max_completions = 200;
1878 /* Initial size of the table. It automagically grows from here. */
1879 #define INITIAL_COMPLETION_HTAB_SIZE 200
1881 /* The function is used to update the completion word MATCH before
1882 displaying it to the user in the 'complete' command output. This
1883 default function is used in all cases except those where a completion
1884 function overrides this function by calling set_match_format_func.
1886 This function returns MATCH with QUOTE_CHAR appended. If QUOTE_CHAR is
1887 the null-character then the returned string will just contain MATCH. */
1889 static std::string
1890 default_match_formatter (const char *match, char quote_char)
1892 return std::string (match) + quote_char;
1895 /* See completer.h. */
1897 completion_tracker::completion_tracker (bool from_readline)
1898 : m_from_readline (from_readline),
1899 m_match_format_func (default_match_formatter)
1901 discard_completions ();
1904 /* See completer.h. */
1906 void
1907 completion_tracker::discard_completions ()
1909 xfree (m_lowest_common_denominator);
1910 m_lowest_common_denominator = NULL;
1912 m_lowest_common_denominator_unique = false;
1913 m_lowest_common_denominator_valid = false;
1915 m_entries_hash.reset (nullptr);
1917 /* A callback used by the hash table to compare new entries with existing
1918 entries. We can't use the standard htab_eq_string function here as the
1919 key to our hash is just a single string, while the values we store in
1920 the hash are a struct containing multiple strings. */
1921 static auto entry_eq_func
1922 = [] (const void *first, const void *second) -> int
1924 /* The FIRST argument is the entry already in the hash table, and
1925 the SECOND argument is the new item being inserted. */
1926 const completion_hash_entry *entry
1927 = (const completion_hash_entry *) first;
1928 const char *name_str = (const char *) second;
1930 return entry->is_name_eq (name_str);
1933 /* Callback used by the hash table to compute the hash value for an
1934 existing entry. This is needed when expanding the hash table. */
1935 static auto entry_hash_func
1936 = [] (const void *arg) -> hashval_t
1938 const completion_hash_entry *entry
1939 = (const completion_hash_entry *) arg;
1940 return entry->hash_name ();
1943 m_entries_hash.reset
1944 (htab_create_alloc (INITIAL_COMPLETION_HTAB_SIZE,
1945 entry_hash_func, entry_eq_func,
1946 htab_delete_entry<completion_hash_entry>,
1947 xcalloc, xfree));
1950 /* See completer.h. */
1952 completion_tracker::~completion_tracker ()
1954 xfree (m_lowest_common_denominator);
1957 /* See completer.h. */
1959 bool
1960 completion_tracker::maybe_add_completion
1961 (gdb::unique_xmalloc_ptr<char> name,
1962 completion_match_for_lcd *match_for_lcd,
1963 const char *text, const char *word)
1965 void **slot;
1967 if (max_completions == 0)
1968 return false;
1970 if (htab_elements (m_entries_hash.get ()) >= max_completions)
1971 return false;
1973 hashval_t hash = htab_hash_string (name.get ());
1974 slot = htab_find_slot_with_hash (m_entries_hash.get (), name.get (),
1975 hash, INSERT);
1976 if (*slot == HTAB_EMPTY_ENTRY)
1978 const char *match_for_lcd_str = NULL;
1980 if (match_for_lcd != NULL)
1981 match_for_lcd_str = match_for_lcd->finish ();
1983 if (match_for_lcd_str == NULL)
1984 match_for_lcd_str = name.get ();
1986 gdb::unique_xmalloc_ptr<char> lcd
1987 = make_completion_match_str (match_for_lcd_str, text, word);
1989 size_t lcd_len = strlen (lcd.get ());
1990 *slot = new completion_hash_entry (std::move (name), std::move (lcd));
1992 m_lowest_common_denominator_valid = false;
1993 m_lowest_common_denominator_max_length
1994 = std::max (m_lowest_common_denominator_max_length, lcd_len);
1997 return true;
2000 /* See completer.h. */
2002 void
2003 completion_tracker::add_completion (gdb::unique_xmalloc_ptr<char> name,
2004 completion_match_for_lcd *match_for_lcd,
2005 const char *text, const char *word)
2007 if (!maybe_add_completion (std::move (name), match_for_lcd, text, word))
2008 throw_error (MAX_COMPLETIONS_REACHED_ERROR, _("Max completions reached."));
2011 /* See completer.h. */
2013 void
2014 completion_tracker::add_completions (completion_list &&list)
2016 for (auto &candidate : list)
2017 add_completion (std::move (candidate));
2020 /* See completer.h. */
2022 void
2023 completion_tracker::remove_completion (const char *name)
2025 hashval_t hash = htab_hash_string (name);
2026 if (htab_find_slot_with_hash (m_entries_hash.get (), name, hash, NO_INSERT)
2027 != NULL)
2029 htab_remove_elt_with_hash (m_entries_hash.get (), name, hash);
2030 m_lowest_common_denominator_valid = false;
2034 /* Helper for the make_completion_match_str overloads. Returns NULL
2035 as an indication that we want MATCH_NAME exactly. It is up to the
2036 caller to xstrdup that string if desired. */
2038 static char *
2039 make_completion_match_str_1 (const char *match_name,
2040 const char *text, const char *word)
2042 char *newobj;
2044 if (word == text)
2046 /* Return NULL as an indication that we want MATCH_NAME
2047 exactly. */
2048 return NULL;
2050 else if (word > text)
2052 /* Return some portion of MATCH_NAME. */
2053 newobj = xstrdup (match_name + (word - text));
2055 else
2057 /* Return some of WORD plus MATCH_NAME. */
2058 size_t len = strlen (match_name);
2059 newobj = (char *) xmalloc (text - word + len + 1);
2060 memcpy (newobj, word, text - word);
2061 memcpy (newobj + (text - word), match_name, len + 1);
2064 return newobj;
2067 /* See completer.h. */
2069 gdb::unique_xmalloc_ptr<char>
2070 make_completion_match_str (const char *match_name,
2071 const char *text, const char *word)
2073 char *newobj = make_completion_match_str_1 (match_name, text, word);
2074 if (newobj == NULL)
2075 newobj = xstrdup (match_name);
2076 return gdb::unique_xmalloc_ptr<char> (newobj);
2079 /* See completer.h. */
2081 gdb::unique_xmalloc_ptr<char>
2082 make_completion_match_str (gdb::unique_xmalloc_ptr<char> &&match_name,
2083 const char *text, const char *word)
2085 char *newobj = make_completion_match_str_1 (match_name.get (), text, word);
2086 if (newobj == NULL)
2087 return std::move (match_name);
2088 return gdb::unique_xmalloc_ptr<char> (newobj);
2091 /* See complete.h. */
2093 completion_result
2094 complete (const char *line, char const **word, int *quote_char)
2096 completion_tracker tracker_handle_brkchars (false);
2097 completion_tracker tracker_handle_completions (false);
2098 completion_tracker *tracker;
2100 /* The WORD should be set to the end of word to complete. We initialize
2101 to the completion point which is assumed to be at the end of LINE.
2102 This leaves WORD to be initialized to a sensible value in cases
2103 completion_find_completion_word() fails i.e., throws an exception.
2104 See bug 24587. */
2105 *word = line + strlen (line);
2109 bool found_any_quoting = false;
2111 *word = completion_find_completion_word (tracker_handle_brkchars,
2112 line, quote_char,
2113 &found_any_quoting);
2115 /* Completers that provide a custom word point in the
2116 handle_brkchars phase also compute their completions then.
2117 Completers that leave the completion word handling to readline
2118 must be called twice. */
2119 if (tracker_handle_brkchars.use_custom_word_point ())
2120 tracker = &tracker_handle_brkchars;
2121 else
2123 /* Setting this global matches what readline does within
2124 gen_completion_matches. We need this set correctly in case
2125 our completion function calls back into readline to perform
2126 completion (e.g. filename_completer does this). */
2127 rl_completion_found_quote = found_any_quoting;
2129 complete_line (tracker_handle_completions, *word, line, strlen (line));
2130 tracker = &tracker_handle_completions;
2133 catch (const gdb_exception &ex)
2135 return {};
2138 return tracker->build_completion_result (*word, *word - line, strlen (line));
2142 /* Generate completions all at once. Does nothing if max_completions
2143 is 0. If max_completions is non-negative, this will collect at
2144 most max_completions strings.
2146 TEXT is the caller's idea of the "word" we are looking at.
2148 LINE_BUFFER is available to be looked at; it contains the entire
2149 text of the line.
2151 POINT is the offset in that line of the cursor. You
2152 should pretend that the line ends at POINT. */
2154 void
2155 complete_line (completion_tracker &tracker,
2156 const char *text, const char *line_buffer, int point)
2158 if (max_completions == 0)
2159 return;
2160 complete_line_internal (tracker, text, line_buffer, point,
2161 handle_completions);
2164 /* Complete on command names. Used by "help". */
2166 void
2167 command_completer (struct cmd_list_element *ignore,
2168 completion_tracker &tracker,
2169 const char *text, const char *word)
2171 complete_line_internal (tracker, word, text,
2172 strlen (text), handle_help);
2175 /* The corresponding completer_handle_brkchars implementation. */
2177 static void
2178 command_completer_handle_brkchars (struct cmd_list_element *ignore,
2179 completion_tracker &tracker,
2180 const char *text, const char *word)
2182 set_rl_completer_word_break_characters
2183 (gdb_completer_command_word_break_characters);
2186 /* Complete on signals. */
2188 void
2189 signal_completer (struct cmd_list_element *ignore,
2190 completion_tracker &tracker,
2191 const char *text, const char *word)
2193 size_t len = strlen (word);
2194 int signum;
2195 const char *signame;
2197 for (signum = GDB_SIGNAL_FIRST; signum != GDB_SIGNAL_LAST; ++signum)
2199 /* Can't handle this, so skip it. */
2200 if (signum == GDB_SIGNAL_0)
2201 continue;
2203 signame = gdb_signal_to_name ((enum gdb_signal) signum);
2205 /* Ignore the unknown signal case. */
2206 if (!signame || strcmp (signame, "?") == 0)
2207 continue;
2209 if (strncasecmp (signame, word, len) == 0)
2210 tracker.add_completion (make_unique_xstrdup (signame));
2214 /* Bit-flags for selecting what the register and/or register-group
2215 completer should complete on. */
2217 enum reg_completer_target
2219 complete_register_names = 0x1,
2220 complete_reggroup_names = 0x2
2222 DEF_ENUM_FLAGS_TYPE (enum reg_completer_target, reg_completer_targets);
2224 /* Complete register names and/or reggroup names based on the value passed
2225 in TARGETS. At least one bit in TARGETS must be set. */
2227 static void
2228 reg_or_group_completer_1 (completion_tracker &tracker,
2229 const char *text, const char *word,
2230 reg_completer_targets targets)
2232 size_t len = strlen (word);
2233 struct gdbarch *gdbarch;
2234 const char *name;
2236 gdb_assert ((targets & (complete_register_names
2237 | complete_reggroup_names)) != 0);
2238 gdbarch = get_current_arch ();
2240 if ((targets & complete_register_names) != 0)
2242 int i;
2244 for (i = 0;
2245 (name = user_reg_map_regnum_to_name (gdbarch, i)) != NULL;
2246 i++)
2248 if (*name != '\0' && strncmp (word, name, len) == 0)
2249 tracker.add_completion (make_unique_xstrdup (name));
2253 if ((targets & complete_reggroup_names) != 0)
2255 for (const struct reggroup *group : gdbarch_reggroups (gdbarch))
2257 name = group->name ();
2258 if (strncmp (word, name, len) == 0)
2259 tracker.add_completion (make_unique_xstrdup (name));
2264 /* Perform completion on register and reggroup names. */
2266 void
2267 reg_or_group_completer (struct cmd_list_element *ignore,
2268 completion_tracker &tracker,
2269 const char *text, const char *word)
2271 reg_or_group_completer_1 (tracker, text, word,
2272 (complete_register_names
2273 | complete_reggroup_names));
2276 /* Perform completion on reggroup names. */
2278 void
2279 reggroup_completer (struct cmd_list_element *ignore,
2280 completion_tracker &tracker,
2281 const char *text, const char *word)
2283 reg_or_group_completer_1 (tracker, text, word,
2284 complete_reggroup_names);
2287 /* The default completer_handle_brkchars implementation. */
2289 static void
2290 default_completer_handle_brkchars (struct cmd_list_element *ignore,
2291 completion_tracker &tracker,
2292 const char *text, const char *word)
2294 set_rl_completer_word_break_characters
2295 (current_language->word_break_characters ());
2298 /* See definition in completer.h. */
2300 completer_handle_brkchars_ftype *
2301 completer_handle_brkchars_func_for_completer (completer_ftype *fn)
2303 if (fn == deprecated_filename_completer)
2304 return deprecated_filename_completer_handle_brkchars;
2306 if (fn == filename_maybe_quoted_completer)
2307 return filename_maybe_quoted_completer_handle_brkchars;
2309 if (fn == location_completer)
2310 return location_completer_handle_brkchars;
2312 if (fn == command_completer)
2313 return command_completer_handle_brkchars;
2315 return default_completer_handle_brkchars;
2318 /* Used as brkchars when we want to tell readline we have a custom
2319 word point. We do that by making our rl_completion_word_break_hook
2320 set RL_POINT to the desired word point, and return the character at
2321 the word break point as the break char. This is two bytes in order
2322 to fit one break character plus the terminating null. */
2323 static char gdb_custom_word_point_brkchars[2];
2325 /* Since rl_basic_quote_characters is not completer-specific, we save
2326 its original value here, in order to be able to restore it in
2327 gdb_rl_attempted_completion_function. */
2328 static const char *gdb_org_rl_basic_quote_characters = rl_basic_quote_characters;
2330 /* Get the list of chars that are considered as word breaks
2331 for the current command. */
2333 static char *
2334 gdb_completion_word_break_characters_throw ()
2336 /* New completion starting. Get rid of the previous tracker and
2337 start afresh. */
2338 delete current_completion.tracker;
2339 current_completion.tracker = new completion_tracker (true);
2341 completion_tracker &tracker = *current_completion.tracker;
2343 complete_line_internal (tracker, NULL, rl_line_buffer,
2344 rl_point, handle_brkchars);
2346 if (tracker.use_custom_word_point ())
2348 gdb_assert (tracker.custom_word_point () > 0);
2349 rl_point = tracker.custom_word_point () - 1;
2351 gdb_assert (rl_point >= 0 && rl_point < strlen (rl_line_buffer));
2353 gdb_custom_word_point_brkchars[0] = rl_line_buffer[rl_point];
2354 rl_completer_word_break_characters = gdb_custom_word_point_brkchars;
2356 /* When performing filename completion we have two options, unquoted
2357 filename completion, in which case the quote characters will have
2358 already been set to nullptr, or quoted filename completion in
2359 which case the quote characters will be set to a string of
2360 characters. In this second case we need readline to perform the
2361 check for a quoted string so that it sets its internal notion of
2362 the quote character correctly, this allows readline to correctly
2363 add the trailing quote (if necessary) after completing a
2364 filename.
2366 For non-filename completion we manually add a trailing quote if
2367 needed, so we clear the quote characters set here. */
2368 if (!rl_filename_completion_desired)
2369 rl_completer_quote_characters = NULL;
2371 /* Clear this too, so that if we're completing a quoted string,
2372 readline doesn't consider the quote character a delimiter.
2373 If we didn't do this, readline would auto-complete {b
2374 'fun<tab>} to {'b 'function()'}, i.e., add the terminating
2375 \', but, it wouldn't append the separator space either, which
2376 is not desirable. So instead we take care of appending the
2377 quote character to the LCD ourselves, in
2378 gdb_rl_attempted_completion_function. Since this global is
2379 not just completer-specific, we'll restore it back to the
2380 default in gdb_rl_attempted_completion_function. */
2381 rl_basic_quote_characters = NULL;
2384 return (char *) rl_completer_word_break_characters;
2387 /* Get the list of chars that are considered as word breaks for the current
2388 command. This function does not throw any exceptions and is called from
2389 readline. See gdb_completion_word_break_characters_throw for details. */
2391 static char *
2392 gdb_completion_word_break_characters () noexcept
2394 /* New completion starting. */
2395 current_completion.aborted = false;
2399 return gdb_completion_word_break_characters_throw ();
2401 catch (const gdb_exception &ex)
2403 /* Set this to that gdb_rl_attempted_completion_function knows
2404 to abort early. */
2405 current_completion.aborted = true;
2408 return NULL;
2411 /* Find the bounds of the word in TEXT for completion purposes, and return
2412 a pointer to the end of the word. Calls the completion machinery for a
2413 handle_brkchars phase (using TRACKER) to figure out the right work break
2414 characters for the command in TEXT. QUOTE_CHAR, if non-null, is set to
2415 the opening quote character if we found an unclosed quoted substring,
2416 '\0' otherwise.
2418 The argument *FOUND_ANY_QUOTING is set to true if the completion word is
2419 either surrounded by quotes, or contains any backslash escapes, but is
2420 only set if TRACKER.use_custom_word_point() is false, otherwise
2421 *FOUND_ANY_QUOTING is just set to false. */
2423 static const char *
2424 completion_find_completion_word (completion_tracker &tracker, const char *text,
2425 int *quote_char, bool *found_any_quoting)
2427 size_t point = strlen (text);
2429 complete_line_internal (tracker, NULL, text, point, handle_brkchars);
2431 if (tracker.use_custom_word_point ())
2433 gdb_assert (tracker.custom_word_point () > 0);
2434 *quote_char = tracker.quote_char ();
2435 /* If use_custom_word_point is set then the completions have already
2436 been calculated, in which case we don't need to have this flag
2437 set correctly, which is lucky as we don't currently have any way
2438 to know if the completion word included any backslash escapes. */
2439 if (found_any_quoting != nullptr)
2440 *found_any_quoting = false;
2441 return text + tracker.custom_word_point ();
2444 gdb_rl_completion_word_info info;
2446 info.word_break_characters = rl_completer_word_break_characters;
2447 info.quote_characters = rl_completer_quote_characters;
2448 info.basic_quote_characters = rl_basic_quote_characters;
2450 return gdb_rl_find_completion_word (&info, quote_char, nullptr,
2451 found_any_quoting, text);
2454 /* See completer.h. */
2456 void
2457 completion_tracker::recompute_lcd_visitor (completion_hash_entry *entry)
2459 if (!m_lowest_common_denominator_valid)
2461 /* This is the first lowest common denominator that we are
2462 considering, just copy it in. */
2463 strcpy (m_lowest_common_denominator, entry->get_lcd ());
2464 m_lowest_common_denominator_unique = true;
2465 m_lowest_common_denominator_valid = true;
2467 else
2469 /* Find the common denominator between the currently-known lowest
2470 common denominator and NEW_MATCH_UP. That becomes the new lowest
2471 common denominator. */
2472 size_t i;
2473 const char *new_match = entry->get_lcd ();
2475 for (i = 0;
2476 (new_match[i] != '\0'
2477 && new_match[i] == m_lowest_common_denominator[i]);
2478 i++)
2480 if (m_lowest_common_denominator[i] != new_match[i])
2482 m_lowest_common_denominator[i] = '\0';
2483 m_lowest_common_denominator_unique = false;
2488 /* See completer.h. */
2490 void
2491 completion_tracker::recompute_lowest_common_denominator ()
2493 /* We've already done this. */
2494 if (m_lowest_common_denominator_valid)
2495 return;
2497 /* Resize the storage to ensure we have enough space, the plus one gives
2498 us space for the trailing null terminator we will include. */
2499 m_lowest_common_denominator
2500 = (char *) xrealloc (m_lowest_common_denominator,
2501 m_lowest_common_denominator_max_length + 1);
2503 /* Callback used to visit each entry in the m_entries_hash. */
2504 auto visitor_func
2505 = [] (void **slot, void *info) -> int
2507 completion_tracker *obj = (completion_tracker *) info;
2508 completion_hash_entry *entry = (completion_hash_entry *) *slot;
2509 obj->recompute_lcd_visitor (entry);
2510 return 1;
2513 htab_traverse_noresize (m_entries_hash.get (), visitor_func, this);
2514 m_lowest_common_denominator_valid = true;
2517 /* See completer.h. */
2519 void
2520 completion_tracker::advance_custom_word_point_by (int len)
2522 m_custom_word_point += len;
2525 /* Build a new C string that is a copy of LCD with the whitespace of
2526 ORIG/ORIG_LEN preserved.
2528 Say the user is completing a symbol name, with spaces, like:
2530 "foo ( i"
2532 and the resulting completion match is:
2534 "foo(int)"
2536 we want to end up with an input line like:
2538 "foo ( int)"
2539 ^^^^^^^ => text from LCD [1], whitespace from ORIG preserved.
2540 ^^ => new text from LCD
2542 [1] - We must take characters from the LCD instead of the original
2543 text, since some completions want to change upper/lowercase. E.g.:
2545 "handle sig<>"
2547 completes to:
2549 "handle SIG[QUIT|etc.]"
2552 static char *
2553 expand_preserving_ws (const char *orig, size_t orig_len,
2554 const char *lcd)
2556 const char *p_orig = orig;
2557 const char *orig_end = orig + orig_len;
2558 const char *p_lcd = lcd;
2559 std::string res;
2561 while (p_orig < orig_end)
2563 if (*p_orig == ' ')
2565 while (p_orig < orig_end && *p_orig == ' ')
2566 res += *p_orig++;
2567 p_lcd = skip_spaces (p_lcd);
2569 else
2571 /* Take characters from the LCD instead of the original
2572 text, since some completions change upper/lowercase.
2573 E.g.:
2574 "handle sig<>"
2575 completes to:
2576 "handle SIG[QUIT|etc.]"
2578 res += *p_lcd;
2579 p_orig++;
2580 p_lcd++;
2584 while (*p_lcd != '\0')
2585 res += *p_lcd++;
2587 return xstrdup (res.c_str ());
2590 /* See completer.h. */
2592 completion_result
2593 completion_tracker::build_completion_result (const char *text,
2594 int start, int end)
2596 size_t element_count = htab_elements (m_entries_hash.get ());
2598 if (element_count == 0)
2599 return {};
2601 /* +1 for the LCD, and +1 for NULL termination. */
2602 char **match_list = XNEWVEC (char *, 1 + element_count + 1);
2604 /* Build replacement word, based on the LCD. */
2606 recompute_lowest_common_denominator ();
2607 if (rl_filename_completion_desired)
2608 match_list[0] = xstrdup (m_lowest_common_denominator);
2609 else
2610 match_list[0]
2611 = expand_preserving_ws (text, end - start, m_lowest_common_denominator);
2613 if (m_lowest_common_denominator_unique)
2615 bool completion_suppress_append;
2617 /* For filename completion we rely on readline to append the closing
2618 quote. While for other types of completion we append the closing
2619 quote here. */
2620 if (from_readline () && !rl_filename_completion_desired)
2622 /* We don't rely on readline appending the quote char as
2623 delimiter as then readline wouldn't append the ' ' after the
2624 completion. */
2625 char buf[2] = { (char) quote_char (), '\0' };
2627 match_list[0] = reconcat (match_list[0], match_list[0], buf,
2628 (char *) nullptr);
2630 /* If the tracker wants to, or we already have a space at the end
2631 of the match, tell readline to skip appending another. */
2632 char *match = match_list[0];
2633 completion_suppress_append
2634 = (suppress_append_ws ()
2635 || (match[0] != '\0'
2636 && match[strlen (match) - 1] == ' '));
2638 else
2639 completion_suppress_append = false;
2641 match_list[1] = nullptr;
2643 return completion_result (match_list, 1, completion_suppress_append,
2644 m_match_format_func);
2646 else
2648 /* State object used while building the completion list. */
2649 struct list_builder
2651 list_builder (char **ml)
2652 : match_list (ml),
2653 index (1)
2654 { /* Nothing. */ }
2656 /* The list we are filling. */
2657 char **match_list;
2659 /* The next index in the list to write to. */
2660 int index;
2662 list_builder builder (match_list);
2664 /* Visit each entry in m_entries_hash and add it to the completion
2665 list, updating the builder state object. */
2666 auto func
2667 = [] (void **slot, void *info) -> int
2669 completion_hash_entry *entry = (completion_hash_entry *) *slot;
2670 list_builder *state = (list_builder *) info;
2672 state->match_list[state->index] = entry->release_name ();
2673 state->index++;
2674 return 1;
2677 /* Build the completion list and add a null at the end. */
2678 htab_traverse_noresize (m_entries_hash.get (), func, &builder);
2679 match_list[builder.index] = NULL;
2681 return completion_result (match_list, builder.index - 1, false,
2682 m_match_format_func);
2686 /* See completer.h */
2688 completion_result::completion_result ()
2689 : match_list (NULL), number_matches (0),
2690 completion_suppress_append (false),
2691 m_match_formatter (default_match_formatter)
2694 /* See completer.h */
2696 completion_result::completion_result (char **match_list_,
2697 size_t number_matches_,
2698 bool completion_suppress_append_,
2699 match_format_func_t match_formatter_)
2700 : match_list (match_list_),
2701 number_matches (number_matches_),
2702 completion_suppress_append (completion_suppress_append_),
2703 m_match_formatter (match_formatter_)
2705 gdb_assert (m_match_formatter != nullptr);
2708 /* See completer.h */
2710 completion_result::~completion_result ()
2712 reset_match_list ();
2715 /* See completer.h */
2717 completion_result::completion_result (completion_result &&rhs) noexcept
2718 : match_list (rhs.match_list),
2719 number_matches (rhs.number_matches),
2720 m_match_formatter (rhs.m_match_formatter)
2722 rhs.match_list = NULL;
2723 rhs.number_matches = 0;
2724 rhs.m_match_formatter = default_match_formatter;
2727 /* See completer.h */
2729 char **
2730 completion_result::release_match_list ()
2732 char **ret = match_list;
2733 match_list = NULL;
2734 return ret;
2737 /* See completer.h */
2739 void
2740 completion_result::sort_match_list ()
2742 if (number_matches > 1)
2744 /* Element 0 is special (it's the common prefix), leave it
2745 be. */
2746 std::sort (&match_list[1],
2747 &match_list[number_matches + 1],
2748 compare_cstrings);
2752 /* See completer.h */
2754 void
2755 completion_result::reset_match_list ()
2757 if (match_list != NULL)
2759 for (char **p = match_list; *p != NULL; p++)
2760 xfree (*p);
2761 xfree (match_list);
2762 match_list = NULL;
2766 /* See completer.h */
2768 void
2769 completion_result::print_matches (const std::string &prefix,
2770 const char *word, int quote_char)
2772 this->sort_match_list ();
2774 size_t off = this->number_matches == 1 ? 0 : 1;
2776 for (size_t i = 0; i < this->number_matches; i++)
2778 gdb_assert (this->m_match_formatter != nullptr);
2779 std::string formatted_match
2780 = this->m_match_formatter (this->match_list[i + off],
2781 (char) quote_char);
2783 printf_unfiltered ("%s%s\n", prefix.c_str (),
2784 formatted_match.c_str ());
2787 if (this->number_matches == max_completions)
2789 /* PREFIX and WORD are included in the output so that emacs will
2790 include the message in the output. */
2791 printf_unfiltered (_("%s%s %s\n"),
2792 prefix.c_str (), word,
2793 get_max_completions_reached_message ());
2798 /* Helper for gdb_rl_attempted_completion_function, which does most of
2799 the work. This is called by readline to build the match list array
2800 and to determine the lowest common denominator. The real matches
2801 list starts at match[1], while match[0] is the slot holding
2802 readline's idea of the lowest common denominator of all matches,
2803 which is what readline replaces the completion "word" with.
2805 TEXT is the caller's idea of the "word" we are looking at, as
2806 computed in the handle_brkchars phase.
2808 START is the offset from RL_LINE_BUFFER where TEXT starts. END is
2809 the offset from RL_LINE_BUFFER where TEXT ends (i.e., where
2810 rl_point is).
2812 You should thus pretend that the line ends at END (relative to
2813 RL_LINE_BUFFER).
2815 RL_LINE_BUFFER contains the entire text of the line. RL_POINT is
2816 the offset in that line of the cursor. You should pretend that the
2817 line ends at POINT.
2819 Returns NULL if there are no completions. */
2821 static char **
2822 gdb_rl_attempted_completion_function_throw (const char *text, int start, int end)
2824 /* Completers that provide a custom word point in the
2825 handle_brkchars phase also compute their completions then.
2826 Completers that leave the completion word handling to readline
2827 must be called twice. If rl_point (i.e., END) is at column 0,
2828 then readline skips the handle_brkchars phase, and so we create a
2829 tracker now in that case too. */
2830 if (end == 0 || !current_completion.tracker->use_custom_word_point ())
2832 delete current_completion.tracker;
2833 current_completion.tracker = new completion_tracker (true);
2835 complete_line (*current_completion.tracker, text,
2836 rl_line_buffer, rl_point);
2839 completion_tracker &tracker = *current_completion.tracker;
2841 completion_result result
2842 = tracker.build_completion_result (text, start, end);
2844 rl_completion_suppress_append = result.completion_suppress_append;
2845 return result.release_match_list ();
2848 /* Function installed as "rl_attempted_completion_function" readline
2849 hook. Wrapper around gdb_rl_attempted_completion_function_throw
2850 that catches C++ exceptions, which can't cross readline. */
2852 static char **
2853 gdb_rl_attempted_completion_function (const char *text, int start, int end)
2855 /* Restore globals that might have been tweaked in
2856 gdb_completion_word_break_characters. */
2857 rl_basic_quote_characters = gdb_org_rl_basic_quote_characters;
2859 /* If we end up returning NULL, either on error, or simple because
2860 there are no matches, inhibit readline's default filename
2861 completer. */
2862 rl_attempted_completion_over = 1;
2864 /* If the handle_brkchars phase was aborted, don't try
2865 completing. */
2866 if (current_completion.aborted)
2867 return NULL;
2871 return gdb_rl_attempted_completion_function_throw (text, start, end);
2873 catch (const gdb_exception &ex)
2877 return NULL;
2880 /* Return a message indicating that the maximum number of completions
2881 has been reached and that there may be more. */
2883 const char *
2884 get_max_completions_reached_message (void)
2886 return _("*** List may be truncated, max-completions reached. ***");
2889 /* GDB replacement for rl_display_match_list.
2890 Readline doesn't provide a clean interface for TUI(curses).
2891 A hack previously used was to send readline's rl_outstream through a pipe
2892 and read it from the event loop. Bleah. IWBN if readline abstracted
2893 away all the necessary bits, and this is what this code does. It
2894 replicates the parts of readline we need and then adds an abstraction
2895 layer, currently implemented as struct match_list_displayer, so that both
2896 CLI and TUI can use it. We copy all this readline code to minimize
2897 GDB-specific mods to readline. Once this code performs as desired then
2898 we can submit it to the readline maintainers.
2900 N.B. A lot of the code is the way it is in order to minimize differences
2901 from readline's copy. */
2903 /* Not supported here. */
2904 #undef VISIBLE_STATS
2906 #if defined (HANDLE_MULTIBYTE)
2907 #define MB_INVALIDCH(x) ((x) == (size_t)-1 || (x) == (size_t)-2)
2908 #define MB_NULLWCH(x) ((x) == 0)
2909 #endif
2911 #define ELLIPSIS_LEN 3
2913 /* gdb version of readline/complete.c:get_y_or_n.
2914 'y' -> returns 1, and 'n' -> returns 0.
2915 Also supported: space == 'y', RUBOUT == 'n', ctrl-g == start over.
2916 If FOR_PAGER is non-zero, then also supported are:
2917 NEWLINE or RETURN -> returns 2, and 'q' -> returns 0. */
2919 static int
2920 gdb_get_y_or_n (int for_pager, const struct match_list_displayer *displayer)
2922 int c;
2924 for (;;)
2926 RL_SETSTATE (RL_STATE_MOREINPUT);
2927 c = displayer->read_key (displayer);
2928 RL_UNSETSTATE (RL_STATE_MOREINPUT);
2930 if (c == 'y' || c == 'Y' || c == ' ')
2931 return 1;
2932 if (c == 'n' || c == 'N' || c == RUBOUT)
2933 return 0;
2934 if (c == ABORT_CHAR || c < 0)
2936 /* Readline doesn't erase_entire_line here, but without it the
2937 --More-- prompt isn't erased and neither is the text entered
2938 thus far redisplayed. */
2939 displayer->erase_entire_line (displayer);
2940 /* Note: The arguments to rl_abort are ignored. */
2941 rl_abort (0, 0);
2943 if (for_pager && (c == NEWLINE || c == RETURN))
2944 return 2;
2945 if (for_pager && (c == 'q' || c == 'Q'))
2946 return 0;
2947 displayer->beep (displayer);
2951 /* Pager function for tab-completion.
2952 This is based on readline/complete.c:_rl_internal_pager.
2953 LINES is the number of lines of output displayed thus far.
2954 Returns:
2955 -1 -> user pressed 'n' or equivalent,
2956 0 -> user pressed 'y' or equivalent,
2957 N -> user pressed NEWLINE or equivalent and N is LINES - 1. */
2959 static int
2960 gdb_display_match_list_pager (int lines,
2961 const struct match_list_displayer *displayer)
2963 int i;
2965 displayer->puts (displayer, "--More--");
2966 displayer->flush (displayer);
2967 i = gdb_get_y_or_n (1, displayer);
2968 displayer->erase_entire_line (displayer);
2969 if (i == 0)
2970 return -1;
2971 else if (i == 2)
2972 return (lines - 1);
2973 else
2974 return 0;
2977 /* Return true if FILENAME is a directory.
2978 Based on readline/complete.c:path_isdir. */
2980 static bool
2981 gdb_path_isdir (const char *filename)
2983 struct stat finfo;
2985 return (stat (filename, &finfo) == 0 && S_ISDIR (finfo.st_mode));
2988 /* Return the portion of PATHNAME that should be output when listing
2989 possible completions. If we are hacking filename completion, we
2990 are only interested in the basename, the portion following the
2991 final slash. Otherwise, we return what we were passed. Since
2992 printing empty strings is not very informative, if we're doing
2993 filename completion, and the basename is the empty string, we look
2994 for the previous slash and return the portion following that. If
2995 there's no previous slash, we just return what we were passed.
2997 Based on readline/complete.c:printable_part. */
2999 static char *
3000 gdb_printable_part (char *pathname)
3002 char *temp, *x;
3004 if (rl_filename_completion_desired == 0) /* don't need to do anything */
3005 return (pathname);
3007 temp = strrchr (pathname, '/');
3008 #if defined (__MSDOS__)
3009 if (temp == 0 && ISALPHA ((unsigned char)pathname[0]) && pathname[1] == ':')
3010 temp = pathname + 1;
3011 #endif
3013 if (temp == 0 || *temp == '\0')
3014 return (pathname);
3015 /* If the basename is NULL, we might have a pathname like '/usr/src/'.
3016 Look for a previous slash and, if one is found, return the portion
3017 following that slash. If there's no previous slash, just return the
3018 pathname we were passed. */
3019 else if (temp[1] == '\0')
3021 for (x = temp - 1; x > pathname; x--)
3022 if (*x == '/')
3023 break;
3024 return ((*x == '/') ? x + 1 : pathname);
3026 else
3027 return ++temp;
3030 /* Compute width of STRING when displayed on screen by print_filename.
3031 Based on readline/complete.c:fnwidth. */
3033 static int
3034 gdb_fnwidth (const char *string)
3036 int width, pos;
3037 #if defined (HANDLE_MULTIBYTE)
3038 mbstate_t ps;
3039 int left, w;
3040 size_t clen;
3041 wchar_t wc;
3043 left = strlen (string) + 1;
3044 memset (&ps, 0, sizeof (mbstate_t));
3045 #endif
3047 width = pos = 0;
3048 while (string[pos])
3050 if (CTRL_CHAR (string[pos]) || string[pos] == RUBOUT)
3052 width += 2;
3053 pos++;
3055 else
3057 #if defined (HANDLE_MULTIBYTE)
3058 clen = mbrtowc (&wc, string + pos, left - pos, &ps);
3059 if (MB_INVALIDCH (clen))
3061 width++;
3062 pos++;
3063 memset (&ps, 0, sizeof (mbstate_t));
3065 else if (MB_NULLWCH (clen))
3066 break;
3067 else
3069 pos += clen;
3070 w = wcwidth (wc);
3071 width += (w >= 0) ? w : 1;
3073 #else
3074 width++;
3075 pos++;
3076 #endif
3080 return width;
3083 /* Print TO_PRINT, one matching completion.
3084 PREFIX_BYTES is number of common prefix bytes.
3085 Based on readline/complete.c:fnprint. */
3087 static int
3088 gdb_fnprint (const char *to_print, int prefix_bytes,
3089 const struct match_list_displayer *displayer)
3091 int printed_len, w;
3092 const char *s;
3093 #if defined (HANDLE_MULTIBYTE)
3094 mbstate_t ps;
3095 const char *end;
3096 size_t tlen;
3097 int width;
3098 wchar_t wc;
3100 end = to_print + strlen (to_print) + 1;
3101 memset (&ps, 0, sizeof (mbstate_t));
3102 #endif
3104 printed_len = 0;
3106 /* Don't print only the ellipsis if the common prefix is one of the
3107 possible completions */
3108 if (to_print[prefix_bytes] == '\0')
3109 prefix_bytes = 0;
3111 if (prefix_bytes)
3113 char ellipsis;
3115 ellipsis = (to_print[prefix_bytes] == '.') ? '_' : '.';
3116 for (w = 0; w < ELLIPSIS_LEN; w++)
3117 displayer->putch (displayer, ellipsis);
3118 printed_len = ELLIPSIS_LEN;
3121 s = to_print + prefix_bytes;
3122 while (*s)
3124 if (CTRL_CHAR (*s))
3126 displayer->putch (displayer, '^');
3127 displayer->putch (displayer, UNCTRL (*s));
3128 printed_len += 2;
3129 s++;
3130 #if defined (HANDLE_MULTIBYTE)
3131 memset (&ps, 0, sizeof (mbstate_t));
3132 #endif
3134 else if (*s == RUBOUT)
3136 displayer->putch (displayer, '^');
3137 displayer->putch (displayer, '?');
3138 printed_len += 2;
3139 s++;
3140 #if defined (HANDLE_MULTIBYTE)
3141 memset (&ps, 0, sizeof (mbstate_t));
3142 #endif
3144 else
3146 #if defined (HANDLE_MULTIBYTE)
3147 tlen = mbrtowc (&wc, s, end - s, &ps);
3148 if (MB_INVALIDCH (tlen))
3150 tlen = 1;
3151 width = 1;
3152 memset (&ps, 0, sizeof (mbstate_t));
3154 else if (MB_NULLWCH (tlen))
3155 break;
3156 else
3158 w = wcwidth (wc);
3159 width = (w >= 0) ? w : 1;
3161 for (w = 0; w < tlen; ++w)
3162 displayer->putch (displayer, s[w]);
3163 s += tlen;
3164 printed_len += width;
3165 #else
3166 displayer->putch (displayer, *s);
3167 s++;
3168 printed_len++;
3169 #endif
3173 return printed_len;
3176 /* Output TO_PRINT to rl_outstream. If VISIBLE_STATS is defined and we
3177 are using it, check for and output a single character for `special'
3178 filenames. Return the number of characters we output.
3179 Based on readline/complete.c:print_filename. */
3181 static int
3182 gdb_print_filename (char *to_print, char *full_pathname, int prefix_bytes,
3183 const struct match_list_displayer *displayer)
3185 int printed_len, extension_char, slen, tlen;
3186 char *s, c, *new_full_pathname;
3187 const char *dn;
3188 extern int _rl_complete_mark_directories;
3190 extension_char = 0;
3191 printed_len = gdb_fnprint (to_print, prefix_bytes, displayer);
3193 #if defined (VISIBLE_STATS)
3194 if (rl_filename_completion_desired && (rl_visible_stats || _rl_complete_mark_directories))
3195 #else
3196 if (rl_filename_completion_desired && _rl_complete_mark_directories)
3197 #endif
3199 /* If to_print != full_pathname, to_print is the basename of the
3200 path passed. In this case, we try to expand the directory
3201 name before checking for the stat character. */
3202 if (to_print != full_pathname)
3204 /* Terminate the directory name. */
3205 c = to_print[-1];
3206 to_print[-1] = '\0';
3208 /* If setting the last slash in full_pathname to a NUL results in
3209 full_pathname being the empty string, we are trying to complete
3210 files in the root directory. If we pass a null string to the
3211 bash directory completion hook, for example, it will expand it
3212 to the current directory. We just want the `/'. */
3213 if (full_pathname == 0 || *full_pathname == 0)
3214 dn = "/";
3215 else if (full_pathname[0] != '/')
3216 dn = full_pathname;
3217 else if (full_pathname[1] == 0)
3218 dn = "//"; /* restore trailing slash to `//' */
3219 else if (full_pathname[1] == '/' && full_pathname[2] == 0)
3220 dn = "/"; /* don't turn /// into // */
3221 else
3222 dn = full_pathname;
3223 s = tilde_expand (dn);
3224 if (rl_directory_completion_hook)
3225 (*rl_directory_completion_hook) (&s);
3227 slen = strlen (s);
3228 tlen = strlen (to_print);
3229 new_full_pathname = (char *)xmalloc (slen + tlen + 2);
3230 strcpy (new_full_pathname, s);
3231 if (s[slen - 1] == '/')
3232 slen--;
3233 else
3234 new_full_pathname[slen] = '/';
3235 new_full_pathname[slen] = '/';
3236 strcpy (new_full_pathname + slen + 1, to_print);
3238 #if defined (VISIBLE_STATS)
3239 if (rl_visible_stats)
3240 extension_char = stat_char (new_full_pathname);
3241 else
3242 #endif
3243 if (gdb_path_isdir (new_full_pathname))
3244 extension_char = '/';
3246 xfree (new_full_pathname);
3247 to_print[-1] = c;
3249 else
3251 s = tilde_expand (full_pathname);
3252 #if defined (VISIBLE_STATS)
3253 if (rl_visible_stats)
3254 extension_char = stat_char (s);
3255 else
3256 #endif
3257 if (gdb_path_isdir (s))
3258 extension_char = '/';
3261 xfree (s);
3262 if (extension_char)
3264 displayer->putch (displayer, extension_char);
3265 printed_len++;
3269 return printed_len;
3272 /* GDB version of readline/complete.c:complete_get_screenwidth. */
3274 static int
3275 gdb_complete_get_screenwidth (const struct match_list_displayer *displayer)
3277 /* Readline has other stuff here which it's not clear we need. */
3278 return displayer->width;
3281 extern int _rl_completion_prefix_display_length;
3282 extern int _rl_print_completions_horizontally;
3284 extern "C" int _rl_qsort_string_compare (const void *, const void *);
3285 typedef int QSFUNC (const void *, const void *);
3287 /* GDB version of readline/complete.c:rl_display_match_list.
3288 See gdb_display_match_list for a description of MATCHES, LEN, MAX.
3289 Returns non-zero if all matches are displayed. */
3291 static int
3292 gdb_display_match_list_1 (char **matches, int len, int max,
3293 const struct match_list_displayer *displayer)
3295 int count, limit, printed_len, lines, cols;
3296 int i, j, k, l, common_length, sind;
3297 char *temp, *t;
3298 int page_completions = displayer->height != INT_MAX && pagination_enabled;
3300 /* Find the length of the prefix common to all items: length as displayed
3301 characters (common_length) and as a byte index into the matches (sind) */
3302 common_length = sind = 0;
3303 if (_rl_completion_prefix_display_length > 0)
3305 t = gdb_printable_part (matches[0]);
3306 temp = strrchr (t, '/');
3307 common_length = temp ? gdb_fnwidth (temp) : gdb_fnwidth (t);
3308 sind = temp ? strlen (temp) : strlen (t);
3310 if (common_length > _rl_completion_prefix_display_length && common_length > ELLIPSIS_LEN)
3311 max -= common_length - ELLIPSIS_LEN;
3312 else
3313 common_length = sind = 0;
3316 /* How many items of MAX length can we fit in the screen window? */
3317 cols = gdb_complete_get_screenwidth (displayer);
3318 max += 2;
3319 limit = cols / max;
3320 if (limit != 1 && (limit * max == cols))
3321 limit--;
3323 /* If cols == 0, limit will end up -1 */
3324 if (cols < displayer->width && limit < 0)
3325 limit = 1;
3327 /* Avoid a possible floating exception. If max > cols,
3328 limit will be 0 and a divide-by-zero fault will result. */
3329 if (limit == 0)
3330 limit = 1;
3332 /* How many iterations of the printing loop? */
3333 count = (len + (limit - 1)) / limit;
3335 /* Watch out for special case. If LEN is less than LIMIT, then
3336 just do the inner printing loop.
3337 0 < len <= limit implies count = 1. */
3339 /* Sort the items if they are not already sorted. */
3340 if (rl_ignore_completion_duplicates == 0 && rl_sort_completion_matches)
3341 qsort (matches + 1, len, sizeof (char *), (QSFUNC *)_rl_qsort_string_compare);
3343 displayer->crlf (displayer);
3345 lines = 0;
3346 if (_rl_print_completions_horizontally == 0)
3348 /* Print the sorted items, up-and-down alphabetically, like ls. */
3349 for (i = 1; i <= count; i++)
3351 for (j = 0, l = i; j < limit; j++)
3353 if (l > len || matches[l] == 0)
3354 break;
3355 else
3357 temp = gdb_printable_part (matches[l]);
3358 printed_len = gdb_print_filename (temp, matches[l], sind,
3359 displayer);
3361 if (j + 1 < limit)
3362 for (k = 0; k < max - printed_len; k++)
3363 displayer->putch (displayer, ' ');
3365 l += count;
3367 displayer->crlf (displayer);
3368 lines++;
3369 if (page_completions && lines >= (displayer->height - 1) && i < count)
3371 lines = gdb_display_match_list_pager (lines, displayer);
3372 if (lines < 0)
3373 return 0;
3377 else
3379 /* Print the sorted items, across alphabetically, like ls -x. */
3380 for (i = 1; matches[i]; i++)
3382 temp = gdb_printable_part (matches[i]);
3383 printed_len = gdb_print_filename (temp, matches[i], sind, displayer);
3384 /* Have we reached the end of this line? */
3385 if (matches[i+1])
3387 if (i && (limit > 1) && (i % limit) == 0)
3389 displayer->crlf (displayer);
3390 lines++;
3391 if (page_completions && lines >= displayer->height - 1)
3393 lines = gdb_display_match_list_pager (lines, displayer);
3394 if (lines < 0)
3395 return 0;
3398 else
3399 for (k = 0; k < max - printed_len; k++)
3400 displayer->putch (displayer, ' ');
3403 displayer->crlf (displayer);
3406 return 1;
3409 /* Utility for displaying completion list matches, used by both CLI and TUI.
3411 MATCHES is the list of strings, in argv format, LEN is the number of
3412 strings in MATCHES, and MAX is the length of the longest string in
3413 MATCHES. */
3415 void
3416 gdb_display_match_list (char **matches, int len, int max,
3417 const struct match_list_displayer *displayer)
3419 /* Readline will never call this if complete_line returned NULL. */
3420 gdb_assert (max_completions != 0);
3422 /* complete_line will never return more than this. */
3423 if (max_completions > 0)
3424 gdb_assert (len <= max_completions);
3426 if (rl_completion_query_items > 0 && len >= rl_completion_query_items)
3428 char msg[100];
3430 /* We can't use *query here because they wait for <RET> which is
3431 wrong here. This follows the readline version as closely as possible
3432 for compatibility's sake. See readline/complete.c. */
3434 displayer->crlf (displayer);
3436 xsnprintf (msg, sizeof (msg),
3437 "Display all %d possibilities? (y or n)", len);
3438 displayer->puts (displayer, msg);
3439 displayer->flush (displayer);
3441 if (gdb_get_y_or_n (0, displayer) == 0)
3443 displayer->crlf (displayer);
3444 return;
3448 if (gdb_display_match_list_1 (matches, len, max, displayer))
3450 /* Note: MAX_COMPLETIONS may be -1 or zero, but LEN is always > 0. */
3451 if (len == max_completions)
3453 /* The maximum number of completions has been reached. Warn the user
3454 that there may be more. */
3455 const char *message = get_max_completions_reached_message ();
3457 displayer->puts (displayer, message);
3458 displayer->crlf (displayer);
3463 /* See completer.h. */
3465 bool
3466 skip_over_slash_fmt (completion_tracker &tracker, const char **args)
3468 const char *text = *args;
3470 if (text[0] == '/')
3472 bool in_fmt;
3473 tracker.set_use_custom_word_point (true);
3475 if (text[1] == '\0')
3477 /* The user tried to complete after typing just the '/' character
3478 of the /FMT string. Step the completer past the '/', but we
3479 don't offer any completions. */
3480 in_fmt = true;
3481 ++text;
3483 else
3485 /* The user has typed some characters after the '/', we assume
3486 this is a complete /FMT string, first skip over it. */
3487 text = skip_to_space (text);
3489 if (*text == '\0')
3491 /* We're at the end of the input string. The user has typed
3492 '/FMT' and asked for a completion. Push an empty
3493 completion string, this will cause readline to insert a
3494 space so the user now has '/FMT '. */
3495 in_fmt = true;
3496 tracker.add_completion (make_unique_xstrdup (text));
3498 else
3500 /* The user has already typed things after the /FMT, skip the
3501 whitespace and return false. Whoever called this function
3502 should then try to complete what comes next. */
3503 in_fmt = false;
3504 text = skip_spaces (text);
3508 tracker.advance_custom_word_point_by (text - *args);
3509 *args = text;
3510 return in_fmt;
3513 return false;
3516 void _initialize_completer ();
3517 void
3518 _initialize_completer ()
3520 /* Setup some readline completion globals. */
3521 rl_completion_word_break_hook = gdb_completion_word_break_characters;
3522 rl_attempted_completion_function = gdb_rl_attempted_completion_function;
3523 set_rl_completer_word_break_characters (default_word_break_characters ());
3525 /* Setup readline globals relating to filename completion. */
3526 rl_filename_quote_characters = " \t\n\\\"'";
3527 rl_filename_dequoting_function = gdb_completer_file_name_dequote;
3528 rl_filename_quoting_function = gdb_completer_file_name_quote;
3529 rl_directory_rewrite_hook = gdb_completer_directory_rewrite;
3531 add_setshow_zuinteger_unlimited_cmd ("max-completions", no_class,
3532 &max_completions, _("\
3533 Set maximum number of completion candidates."), _("\
3534 Show maximum number of completion candidates."), _("\
3535 Use this to limit the number of candidates considered\n\
3536 during completion. Specifying \"unlimited\" or -1\n\
3537 disables limiting. Note that setting either no limit or\n\
3538 a very large limit can make completion slow."),
3539 NULL, NULL, &setlist, &showlist);