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/>. */
21 #include "expression.h"
22 #include "filenames.h"
24 #include "gdbsupport/gdb_signals.h"
26 #include "reggroups.h"
27 #include "user-regs.h"
28 #include "arch-utils.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. */
47 #include "completer.h"
49 /* Forward declarations. */
50 static const char *completion_find_completion_word (completion_tracker
&tracker
,
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
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
))
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
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. */
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 ());
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
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. */
139 /* The name of a function or method. */
142 /* The fully-qualified name of a function or method. */
148 /* The name of a 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++
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
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
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. */
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
226 gdb_completer_file_name_char_is_quoted (char *string
, int eindex
)
228 for (int i
= 0; i
<= eindex
&& string
[i
] != '\0'; )
234 /* The backslash itself is not quoted. */
238 /* But the next character is. */
241 if (string
[i
] == '\0')
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
);
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. */
272 /* Removing character escaping from FILENAME. QUOTE_CHAR is the quote
273 character around FILENAME or the null-character if there is no quoting
277 gdb_completer_file_name_dequote (char *filename
, int quote_char
)
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. */
287 else if (quote_char
== '"')
289 /* Remove escaping from a double quoted string. */
290 for (const char *input
= filename
;
296 && strchr ("\"\\", input
[1]) != nullptr)
303 gdb_assert (quote_char
== '\0');
305 /* Remove escaping from an unquoted string. */
306 for (const char *input
= filename
;
310 /* We allow anything to be escaped in an unquoted string. */
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
331 gdb_completer_directory_rewrite (char **dirname
)
333 if (!rl_completion_found_quote
)
336 int quote_char
= rl_completion_quote_character
;
338 = gdb_completer_file_name_dequote (*dirname
, quote_char
);
340 *dirname
= new_dirname
;
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. */
352 gdb_completer_file_name_quote_1 (const char *text
, char quote_char
)
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. */
362 else if (quote_char
== '"')
364 /* Add escaping for a double quoted filename. */
365 for (const char *input
= text
;
369 if (strchr ("\"\\", *input
) != nullptr)
376 gdb_assert (quote_char
== '\0');
378 /* Add escaping for an unquoted filename. */
379 for (const char *input
= text
;
383 if (strchr (" \t\n\\\"'", *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
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. */
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 ())
415 /* Reallocate RESULT adding C to the end. But only if C is
416 interesting, otherwise we can save the reallocation. */
419 char buf
[2] = { c
, '\0' };
420 result
= reconcat (result
, result
, buf
, nullptr);
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. */
444 filename_match_formatter_1 (const char *match
, char quote_char
,
450 gdb::unique_xmalloc_ptr
<char> quoted_match
451 (gdb_completer_file_name_quote_1 (match
, quote_char
));
452 result
= quoted_match
.get ();
457 if (gdb_path_isdir (gdb_tilde_expand (match
).c_str ()))
460 result
+= quote_char
;
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. */
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
484 See filename_match_formatter_1 for more argument details. */
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. */
503 filename_completer_generate_completions (completion_tracker
&tracker
,
508 tracker
.set_match_format_func (filename_maybe_quoted_match_formatter
);
510 tracker
.set_match_format_func (filename_unquoted_match_formatter
);
512 int subsequent_name
= 0;
515 gdb::unique_xmalloc_ptr
<char> p_rl
516 (rl_filename_completion_function (word
, subsequent_name
));
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. */
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] == '~')
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
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
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
,
560 filename_completer_generate_completions (tracker
, word
, true);
563 /* The brkchars callback used by commands that don't accept quoted
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. */
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
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
;
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
;
624 const char *brkchars
;
625 int point
= strlen (line_buffer
);
627 /* The algorithm below does '--point'. Avoid buffer underflow with
631 if (found_any_quoting
!= nullptr)
632 *found_any_quoting
= false;
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;
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
] == '\\')
673 if (quote_char
!= '\0')
675 /* Ignore everything until the matching close quote
677 if (line_buffer
[scan
] == quote_char
)
679 /* Found matching close. Abandon this
685 else if (strchr (info
->quote_characters
, line_buffer
[scan
]))
687 /* Found start of a quoted substring. */
688 quote_char
= line_buffer
[scan
];
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. */
702 scan
= line_buffer
[point
];
704 if (strchr (brkchars
, scan
) == 0)
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
),
717 /* Convoluted code, but it avoids an n^2 algorithm with calls
718 to char_is_quoted. */
723 /* If we are at an unquoted word break, then advance past it. */
724 scan
= line_buffer
[point
];
728 isbrk
= strchr (brkchars
, scan
) != 0;
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)
743 if (found_any_quoting
!= nullptr)
744 *found_any_quoting
= found_quote
;
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
766 advance_to_completion_word (completion_tracker
&tracker
,
767 const char *word_break_characters
,
768 const char *quote_characters
,
770 bool *found_any_quoting
,
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
;
781 = gdb_rl_find_completion_word (&info
, qc
, &delimiter
, found_any_quoting
,
784 tracker
.advance_custom_word_point_by (start
- text
);
788 tracker
.set_quote_char (delimiter
);
789 tracker
.set_suppress_append_ws (true);
795 /* See completer.h. */
798 advance_to_expression_complete_word_point (completion_tracker
&tracker
,
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. */
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;
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;
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);
839 /* See completer.h. */
842 advance_to_deprecated_filename_complete_word_point (completion_tracker
&tracker
,
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. */
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] == ' ')
875 /* See completer.h. */
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
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
,
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. */
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:
915 This is intended to be used in commands that set breakpoints
919 complete_files_symbols (completion_tracker
&tracker
,
920 const char *text
, const char *word
)
922 completion_list fn_list
;
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] == '\'')
937 else if (*p
== '\'' || *p
== '"')
941 while (*p
!= '\0' && *p
!= quote_found
)
943 if (*p
== '\\' && p
[1] == quote_found
)
948 if (*p
== quote_found
)
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
)
960 else if (*p
== ':' && !colon
)
963 symbol_start
= p
+ 1;
965 else if (strchr (current_language
->word_break_characters (), *p
))
966 symbol_start
= p
+ 1;
972 /* Where is the file name? */
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
);
984 if (*s
== ':' || *s
== quote_char
)
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. */
992 collect_file_symbol_completion_matches (tracker
,
993 complete_symbol_mode::EXPRESSION
,
994 symbol_name_match_type::EXPRESSION
,
997 xfree (file_to_match
);
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
)
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
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
,
1051 /* See completer.h. */
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
)
1062 return make_source_files_completion_list (text
, text
);
1067 /* Complete address and linespec locations. */
1070 complete_address_and_linespec_locations (completion_tracker
&tracker
,
1072 symbol_name_match_type match_type
)
1076 tracker
.advance_custom_word_point_by (1);
1079 = advance_to_expression_complete_word_point (tracker
, text
);
1080 complete_expression (tracker
, text
, word
);
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
[] =
1101 /* The probe modifier options. These can appear before a location in
1102 breakpoint commands. */
1103 static const char *const probe_options
[] =
1111 /* Returns STRING if not NULL, the empty string otherwise. */
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. */
1123 collect_explicit_location_matches (completion_tracker
&tracker
,
1124 location_spec
*locspec
,
1125 enum explicit_location_match_type what
,
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. */
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
));
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 ());
1160 case MATCH_QUALIFIED
:
1164 /* Nothing to offer. */
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
,
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
!= ' ')
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"
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
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. */
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
] != ' ')
1243 for (int i
= 0; keywords
[i
] != NULL
; i
++)
1245 if (strncmp (keywords
[i
], text
, len
) == 0)
1256 tracker
.advance_custom_word_point_by (len
+ 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. */
1272 complete_explicit_location_spec (completion_tracker
&tracker
,
1273 location_spec
*locspec
,
1275 const language_defn
*language
,
1276 const char *quoted_arg_start
,
1277 const char *quoted_arg_end
)
1282 int keyword
= skip_keyword (tracker
, explicit_options
, &text
);
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
);
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
1327 tracker
.advance_custom_word_point_by (strlen (text
));
1328 complete_on_enum (tracker
, linespec_keywords
, "", "");
1329 complete_on_enum (tracker
, explicit_options
, "", "");
1334 /* Now gather matches */
1335 collect_explicit_location_matches (tracker
, locspec
, what
, text
,
1340 /* A completer for locations. */
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 (©
, current_language
,
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
)
1377 tracker
.advance_custom_word_point_by (copy
- text
);
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
);
1391 complete_on_enum (tracker
, linespec_keywords
, text
, text
);
1396 = advance_to_expression_complete_word_point (tracker
, text
);
1397 complete_expression (tracker
, text
, word
);
1402 tracker
.advance_custom_word_point_by (completion_info
.last_option
1404 text
= completion_info
.last_option
;
1406 complete_explicit_location_spec (tracker
, locspec
.get (), text
,
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
);
1420 complete_on_enum (tracker
, explicit_options
, text
, text
);
1423 tracker
.advance_custom_word_point_by (copy
- text
);
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
);
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
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
);
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
1464 location_completer_handle_brkchars (struct cmd_list_element
*ignore
,
1465 completion_tracker
&tracker
,
1467 const char *word_ignored
)
1469 tracker
.set_use_custom_word_point (true);
1471 location_completer (ignore
, tracker
, text
, NULL
);
1474 /* See completer.h. */
1477 complete_expression (completion_tracker
&tracker
,
1478 const char *text
, const char *word
)
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
)
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
))
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
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
1521 set_rl_completer_word_break_characters (const char *break_chars
)
1523 rl_completer_word_break_characters
= (char *) break_chars
;
1526 /* Complete on symbols. */
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
,
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
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
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
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
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. */
1584 /* Main phase, called by complete_line function, is used to get the
1585 list of possible completions. */
1588 /* Special case when completing a 'help' command. In this case,
1589 once sub-command completions are exhausted, we simply return
1594 /* Helper for complete_line_internal to simplify it. */
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
;
1612 = (completer_handle_brkchars_func_for_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. */
1635 complete_line_internal_1 (completion_tracker
&tracker
,
1637 const char *line_buffer
, int point
,
1638 complete_line_internal_reason reason
)
1642 int ignore_help_classes
;
1643 /* Pointer within tmp_command which corresponds to text. */
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
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
1665 tmp_command
= (char *) alloca (point
+ 1);
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
);
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
);
1691 /* An empty line is ambiguous; that is, it could be any
1693 c
= CMD_LIST_AMBIGUOUS
;
1697 c
= lookup_cmd_1 (&p
, cmdlist
, &result_list
, NULL
, ignore_help_classes
,
1700 /* Move p up to the next interesting thing. */
1701 while (*p
== ' ' || *p
== '\t')
1706 tracker
.advance_custom_word_point_by (p
- tmp_command
);
1710 /* It is an unrecognized command. So there are no
1711 possible completions. */
1713 else if (c
== CMD_LIST_AMBIGUOUS
)
1717 /* lookup_cmd_1 advances p up to the first ambiguous thing, but
1718 doesn't advance over that thing itself. Do so now. */
1720 while (valid_cmd_char_p (*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
1732 /* We're trying to complete on the command which was ambiguous.
1733 This we can deal with. */
1736 if (reason
!= handle_brkchars
)
1737 complete_on_cmdlist (*result_list
->subcommands
, tracker
, p
,
1738 word
, ignore_help_classes
);
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
);
1754 /* We've recognized a full command. */
1756 if (p
== tmp_command
+ point
)
1758 /* There is no non-whitespace in the line beyond the
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
)
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
);
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
,
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"
1804 /* Find the command we are completing on. */
1806 while (q
> tmp_command
)
1808 if (valid_cmd_char_p (q
[-1]))
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
)
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". */
1840 if (reason
!= handle_brkchars
)
1841 complete_on_enum (tracker
, c
->enums
, p
, word
);
1845 /* It is a normal command. */
1846 complete_line_internal_normal_command (tracker
,
1847 tmp_command
, word
, p
,
1854 /* Wrapper around complete_line_internal_1 to handle
1855 MAX_COMPLETIONS_REACHED_ERROR. */
1858 complete_line_internal (completion_tracker
&tracker
,
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
)
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. */
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. */
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
>,
1950 /* See completer.h. */
1952 completion_tracker::~completion_tracker ()
1954 xfree (m_lowest_common_denominator
);
1957 /* See completer.h. */
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
)
1967 if (max_completions
== 0)
1970 if (htab_elements (m_entries_hash
.get ()) >= max_completions
)
1973 hashval_t hash
= htab_hash_string (name
.get ());
1974 slot
= htab_find_slot_with_hash (m_entries_hash
.get (), name
.get (),
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
);
2000 /* See completer.h. */
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. */
2014 completion_tracker::add_completions (completion_list
&&list
)
2016 for (auto &candidate
: list
)
2017 add_completion (std::move (candidate
));
2020 /* See completer.h. */
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
)
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. */
2039 make_completion_match_str_1 (const char *match_name
,
2040 const char *text
, const char *word
)
2046 /* Return NULL as an indication that we want MATCH_NAME
2050 else if (word
> text
)
2052 /* Return some portion of MATCH_NAME. */
2053 newobj
= xstrdup (match_name
+ (word
- text
));
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);
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
);
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
);
2087 return std::move (match_name
);
2088 return gdb::unique_xmalloc_ptr
<char> (newobj
);
2091 /* See complete.h. */
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.
2105 *word
= line
+ strlen (line
);
2109 bool found_any_quoting
= false;
2111 *word
= completion_find_completion_word (tracker_handle_brkchars
,
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
;
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
)
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
2151 POINT is the offset in that line of the cursor. You
2152 should pretend that the line ends at POINT. */
2155 complete_line (completion_tracker
&tracker
,
2156 const char *text
, const char *line_buffer
, int point
)
2158 if (max_completions
== 0)
2160 complete_line_internal (tracker
, text
, line_buffer
, point
,
2161 handle_completions
);
2164 /* Complete on command names. Used by "help". */
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. */
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. */
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
);
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
)
2203 signame
= gdb_signal_to_name ((enum gdb_signal
) signum
);
2205 /* Ignore the unknown signal case. */
2206 if (!signame
|| strcmp (signame
, "?") == 0)
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. */
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
;
2236 gdb_assert ((targets
& (complete_register_names
2237 | complete_reggroup_names
)) != 0);
2238 gdbarch
= get_current_arch ();
2240 if ((targets
& complete_register_names
) != 0)
2245 (name
= user_reg_map_regnum_to_name (gdbarch
, i
)) != NULL
;
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. */
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. */
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. */
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. */
2334 gdb_completion_word_break_characters_throw ()
2336 /* New completion starting. Get rid of the previous tracker and
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
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. */
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
2405 current_completion
.aborted
= true;
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,
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. */
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. */
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;
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. */
2473 const char *new_match
= entry
->get_lcd ();
2476 (new_match
[i
] != '\0'
2477 && new_match
[i
] == m_lowest_common_denominator
[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. */
2491 completion_tracker::recompute_lowest_common_denominator ()
2493 /* We've already done this. */
2494 if (m_lowest_common_denominator_valid
)
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. */
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
);
2513 htab_traverse_noresize (m_entries_hash
.get (), visitor_func
, this);
2514 m_lowest_common_denominator_valid
= true;
2517 /* See completer.h. */
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:
2532 and the resulting completion match is:
2536 we want to end up with an input line like:
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.:
2549 "handle SIG[QUIT|etc.]"
2553 expand_preserving_ws (const char *orig
, size_t orig_len
,
2556 const char *p_orig
= orig
;
2557 const char *orig_end
= orig
+ orig_len
;
2558 const char *p_lcd
= lcd
;
2561 while (p_orig
< orig_end
)
2565 while (p_orig
< orig_end
&& *p_orig
== ' ')
2567 p_lcd
= skip_spaces (p_lcd
);
2571 /* Take characters from the LCD instead of the original
2572 text, since some completions change upper/lowercase.
2576 "handle SIG[QUIT|etc.]"
2584 while (*p_lcd
!= '\0')
2587 return xstrdup (res
.c_str ());
2590 /* See completer.h. */
2593 completion_tracker::build_completion_result (const char *text
,
2596 size_t element_count
= htab_elements (m_entries_hash
.get ());
2598 if (element_count
== 0)
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
);
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
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
2625 char buf
[2] = { (char) quote_char (), '\0' };
2627 match_list
[0] = reconcat (match_list
[0], match_list
[0], buf
,
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] == ' '));
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
);
2648 /* State object used while building the completion list. */
2651 list_builder (char **ml
)
2656 /* The list we are filling. */
2659 /* The next index in the list to write to. */
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. */
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 ();
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 */
2730 completion_result::release_match_list ()
2732 char **ret
= match_list
;
2737 /* See completer.h */
2740 completion_result::sort_match_list ()
2742 if (number_matches
> 1)
2744 /* Element 0 is special (it's the common prefix), leave it
2746 std::sort (&match_list
[1],
2747 &match_list
[number_matches
+ 1],
2752 /* See completer.h */
2755 completion_result::reset_match_list ()
2757 if (match_list
!= NULL
)
2759 for (char **p
= match_list
; *p
!= NULL
; p
++)
2766 /* See completer.h */
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
],
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
2812 You should thus pretend that the line ends at END (relative to
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
2819 Returns NULL if there are no completions. */
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. */
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
2862 rl_attempted_completion_over
= 1;
2864 /* If the handle_brkchars phase was aborted, don't try
2866 if (current_completion
.aborted
)
2871 return gdb_rl_attempted_completion_function_throw (text
, start
, end
);
2873 catch (const gdb_exception
&ex
)
2880 /* Return a message indicating that the maximum number of completions
2881 has been reached and that there may be more. */
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)
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. */
2920 gdb_get_y_or_n (int for_pager
, const struct match_list_displayer
*displayer
)
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
== ' ')
2932 if (c
== 'n' || c
== 'N' || c
== RUBOUT
)
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. */
2943 if (for_pager
&& (c
== NEWLINE
|| c
== RETURN
))
2945 if (for_pager
&& (c
== 'q' || c
== 'Q'))
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.
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. */
2960 gdb_display_match_list_pager (int lines
,
2961 const struct match_list_displayer
*displayer
)
2965 displayer
->puts (displayer
, "--More--");
2966 displayer
->flush (displayer
);
2967 i
= gdb_get_y_or_n (1, displayer
);
2968 displayer
->erase_entire_line (displayer
);
2977 /* Return true if FILENAME is a directory.
2978 Based on readline/complete.c:path_isdir. */
2981 gdb_path_isdir (const char *filename
)
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. */
3000 gdb_printable_part (char *pathname
)
3004 if (rl_filename_completion_desired
== 0) /* don't need to do anything */
3007 temp
= strrchr (pathname
, '/');
3008 #if defined (__MSDOS__)
3009 if (temp
== 0 && ISALPHA ((unsigned char)pathname
[0]) && pathname
[1] == ':')
3010 temp
= pathname
+ 1;
3013 if (temp
== 0 || *temp
== '\0')
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
--)
3024 return ((*x
== '/') ? x
+ 1 : pathname
);
3030 /* Compute width of STRING when displayed on screen by print_filename.
3031 Based on readline/complete.c:fnwidth. */
3034 gdb_fnwidth (const char *string
)
3037 #if defined (HANDLE_MULTIBYTE)
3043 left
= strlen (string
) + 1;
3044 memset (&ps
, 0, sizeof (mbstate_t));
3050 if (CTRL_CHAR (string
[pos
]) || string
[pos
] == RUBOUT
)
3057 #if defined (HANDLE_MULTIBYTE)
3058 clen
= mbrtowc (&wc
, string
+ pos
, left
- pos
, &ps
);
3059 if (MB_INVALIDCH (clen
))
3063 memset (&ps
, 0, sizeof (mbstate_t));
3065 else if (MB_NULLWCH (clen
))
3071 width
+= (w
>= 0) ? w
: 1;
3083 /* Print TO_PRINT, one matching completion.
3084 PREFIX_BYTES is number of common prefix bytes.
3085 Based on readline/complete.c:fnprint. */
3088 gdb_fnprint (const char *to_print
, int prefix_bytes
,
3089 const struct match_list_displayer
*displayer
)
3093 #if defined (HANDLE_MULTIBYTE)
3100 end
= to_print
+ strlen (to_print
) + 1;
3101 memset (&ps
, 0, sizeof (mbstate_t));
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')
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
;
3126 displayer
->putch (displayer
, '^');
3127 displayer
->putch (displayer
, UNCTRL (*s
));
3130 #if defined (HANDLE_MULTIBYTE)
3131 memset (&ps
, 0, sizeof (mbstate_t));
3134 else if (*s
== RUBOUT
)
3136 displayer
->putch (displayer
, '^');
3137 displayer
->putch (displayer
, '?');
3140 #if defined (HANDLE_MULTIBYTE)
3141 memset (&ps
, 0, sizeof (mbstate_t));
3146 #if defined (HANDLE_MULTIBYTE)
3147 tlen
= mbrtowc (&wc
, s
, end
- s
, &ps
);
3148 if (MB_INVALIDCH (tlen
))
3152 memset (&ps
, 0, sizeof (mbstate_t));
3154 else if (MB_NULLWCH (tlen
))
3159 width
= (w
>= 0) ? w
: 1;
3161 for (w
= 0; w
< tlen
; ++w
)
3162 displayer
->putch (displayer
, s
[w
]);
3164 printed_len
+= width
;
3166 displayer
->putch (displayer
, *s
);
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. */
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
;
3188 extern int _rl_complete_mark_directories
;
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
))
3196 if (rl_filename_completion_desired
&& _rl_complete_mark_directories
)
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. */
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)
3215 else if (full_pathname
[0] != '/')
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 // */
3223 s
= tilde_expand (dn
);
3224 if (rl_directory_completion_hook
)
3225 (*rl_directory_completion_hook
) (&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] == '/')
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
);
3243 if (gdb_path_isdir (new_full_pathname
))
3244 extension_char
= '/';
3246 xfree (new_full_pathname
);
3251 s
= tilde_expand (full_pathname
);
3252 #if defined (VISIBLE_STATS)
3253 if (rl_visible_stats
)
3254 extension_char
= stat_char (s
);
3257 if (gdb_path_isdir (s
))
3258 extension_char
= '/';
3264 displayer
->putch (displayer
, extension_char
);
3272 /* GDB version of readline/complete.c:complete_get_screenwidth. */
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. */
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
;
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
;
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
);
3320 if (limit
!= 1 && (limit
* max
== cols
))
3323 /* If cols == 0, limit will end up -1 */
3324 if (cols
< displayer
->width
&& limit
< 0)
3327 /* Avoid a possible floating exception. If max > cols,
3328 limit will be 0 and a divide-by-zero fault will result. */
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
);
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)
3357 temp
= gdb_printable_part (matches
[l
]);
3358 printed_len
= gdb_print_filename (temp
, matches
[l
], sind
,
3362 for (k
= 0; k
< max
- printed_len
; k
++)
3363 displayer
->putch (displayer
, ' ');
3367 displayer
->crlf (displayer
);
3369 if (page_completions
&& lines
>= (displayer
->height
- 1) && i
< count
)
3371 lines
= gdb_display_match_list_pager (lines
, displayer
);
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? */
3387 if (i
&& (limit
> 1) && (i
% limit
) == 0)
3389 displayer
->crlf (displayer
);
3391 if (page_completions
&& lines
>= displayer
->height
- 1)
3393 lines
= gdb_display_match_list_pager (lines
, displayer
);
3399 for (k
= 0; k
< max
- printed_len
; k
++)
3400 displayer
->putch (displayer
, ' ');
3403 displayer
->crlf (displayer
);
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
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
)
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
);
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. */
3466 skip_over_slash_fmt (completion_tracker
&tracker
, const char **args
)
3468 const char *text
= *args
;
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. */
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
);
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 '. */
3496 tracker
.add_completion (make_unique_xstrdup (text
));
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. */
3504 text
= skip_spaces (text
);
3508 tracker
.advance_custom_word_point_by (text
- *args
);
3516 void _initialize_completer ();
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
);