1 /* Line completion stuff for GDB, the GNU debugger.
2 Copyright (C) 2000-2021 Free Software Foundation, Inc.
4 This file is part of GDB.
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>. */
22 #include "expression.h"
23 #include "filenames.h" /* For DOSish file names. */
25 #include "gdbsupport/gdb_signals.h"
27 #include "reggroups.h"
28 #include "user-regs.h"
29 #include "arch-utils.h"
33 #include "cli/cli-decode.h"
35 /* FIXME: This is needed because of lookup_cmd_1 (). We should be
36 calling a hook instead so we eliminate the CLI dependency. */
39 /* Needed for rl_completer_word_break_characters() and for
40 rl_filename_completion_function. */
41 #include "readline/readline.h"
43 /* readline defines this. */
46 #include "completer.h"
48 /* See completer.h. */
50 class completion_tracker::completion_hash_entry
54 completion_hash_entry (gdb::unique_xmalloc_ptr
<char> name
,
55 gdb::unique_xmalloc_ptr
<char> lcd
)
56 : m_name (std::move (name
)),
57 m_lcd (std::move (lcd
))
62 /* Returns a pointer to the lowest common denominator string. This
63 string will only be valid while this hash entry is still valid as the
64 string continues to be owned by this hash entry and will be released
65 when this entry is deleted. */
66 char *get_lcd () const
71 /* Get, and release the name field from this hash entry. This can only
72 be called once, after which the name field is no longer valid. This
73 should be used to pass ownership of the name to someone else. */
76 return m_name
.release ();
79 /* Return true of the name in this hash entry is STR. */
80 bool is_name_eq (const char *str
) const
82 return strcmp (m_name
.get (), str
) == 0;
85 /* Return the hash value based on the name of the entry. */
86 hashval_t
hash_name () const
88 return htab_hash_string (m_name
.get ());
93 /* The symbol name stored in this hash entry. */
94 gdb::unique_xmalloc_ptr
<char> m_name
;
96 /* The lowest common denominator string computed for this hash entry. */
97 gdb::unique_xmalloc_ptr
<char> m_lcd
;
100 /* Misc state that needs to be tracked across several different
101 readline completer entry point calls, all related to a single
102 completion invocation. */
104 struct gdb_completer_state
106 /* The current completion's completion tracker. This is a global
107 because a tracker can be shared between the handle_brkchars and
108 handle_completion phases, which involves different readline
110 completion_tracker
*tracker
= NULL
;
112 /* Whether the current completion was aborted. */
113 bool aborted
= false;
116 /* The current completion state. */
117 static gdb_completer_state current_completion
;
119 /* An enumeration of the various things a user might attempt to
120 complete for a location. If you change this, remember to update
121 the explicit_options array below too. */
123 enum explicit_location_match_type
125 /* The filename of a source file. */
128 /* The name of a function or method. */
131 /* The fully-qualified name of a function or method. */
137 /* The name of a label. */
141 /* Prototypes for local functions. */
143 /* readline uses the word breaks for two things:
144 (1) In figuring out where to point the TEXT parameter to the
145 rl_completion_entry_function. Since we don't use TEXT for much,
146 it doesn't matter a lot what the word breaks are for this purpose,
147 but it does affect how much stuff M-? lists.
148 (2) If one of the matches contains a word break character, readline
149 will quote it. That's why we switch between
150 current_language->word_break_characters () and
151 gdb_completer_command_word_break_characters. I'm not sure when
152 we need this behavior (perhaps for funky characters in C++
155 /* Variables which are necessary for fancy command line editing. */
157 /* When completing on command names, we remove '-' and '.' from the list of
158 word break characters, since we use it in command names. If the
159 readline library sees one in any of the current completion strings,
160 it thinks that the string needs to be quoted and automatically
161 supplies a leading quote. */
162 static const char gdb_completer_command_word_break_characters
[] =
163 " \t\n!@#$%^&*()+=|~`}{[]\"';:?/><,";
165 /* When completing on file names, we remove from the list of word
166 break characters any characters that are commonly used in file
167 names, such as '-', '+', '~', etc. Otherwise, readline displays
168 incorrect completion candidates. */
169 /* MS-DOS and MS-Windows use colon as part of the drive spec, and most
170 programs support @foo style response files. */
171 static const char gdb_completer_file_name_break_characters
[] =
172 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
178 /* Characters that can be used to quote completion strings. Note that
179 we can't include '"' because the gdb C parser treats such quoted
180 sequences as strings. */
181 static const char gdb_completer_quote_characters
[] = "'";
183 /* Accessor for some completer data that may interest other files. */
186 get_gdb_completer_quote_characters (void)
188 return gdb_completer_quote_characters
;
191 /* This can be used for functions which don't want to complete on
192 symbols but don't want to complete on anything else either. */
195 noop_completer (struct cmd_list_element
*ignore
,
196 completion_tracker
&tracker
,
197 const char *text
, const char *prefix
)
201 /* Complete on filenames. */
204 filename_completer (struct cmd_list_element
*ignore
,
205 completion_tracker
&tracker
,
206 const char *text
, const char *word
)
213 gdb::unique_xmalloc_ptr
<char> p_rl
214 (rl_filename_completion_function (text
, subsequent_name
));
217 /* We need to set subsequent_name to a non-zero value before the
218 continue line below, because otherwise, if the first file
219 seen by GDB is a backup file whose name ends in a `~', we
220 will loop indefinitely. */
222 /* Like emacs, don't complete on old versions. Especially
223 useful in the "source" command. */
224 const char *p
= p_rl
.get ();
225 if (p
[strlen (p
) - 1] == '~')
228 tracker
.add_completion
229 (make_completion_match_str (std::move (p_rl
), text
, word
));
232 /* There is no way to do this just long enough to affect quote
233 inserting without also affecting the next completion. This
234 should be fixed in readline. FIXME. */
235 /* Ensure that readline does the right thing
236 with respect to inserting quotes. */
237 rl_completer_word_break_characters
= "";
241 /* The corresponding completer_handle_brkchars
245 filename_completer_handle_brkchars (struct cmd_list_element
*ignore
,
246 completion_tracker
&tracker
,
247 const char *text
, const char *word
)
249 set_rl_completer_word_break_characters
250 (gdb_completer_file_name_break_characters
);
253 /* Possible values for the found_quote flags word used by the completion
254 functions. It says what kind of (shell-like) quoting we found anywhere
256 #define RL_QF_SINGLE_QUOTE 0x01
257 #define RL_QF_DOUBLE_QUOTE 0x02
258 #define RL_QF_BACKSLASH 0x04
259 #define RL_QF_OTHER_QUOTE 0x08
261 /* Find the bounds of the current word for completion purposes, and
262 return a pointer to the end of the word. This mimics (and is a
263 modified version of) readline's _rl_find_completion_word internal
266 This function skips quoted substrings (characters between matched
267 pairs of characters in rl_completer_quote_characters). We try to
268 find an unclosed quoted substring on which to do matching. If one
269 is not found, we use the word break characters to find the
270 boundaries of the current word. QC, if non-null, is set to the
271 opening quote character if we found an unclosed quoted substring,
272 '\0' otherwise. DP, if non-null, is set to the value of the
273 delimiter character that caused a word break. */
275 struct gdb_rl_completion_word_info
277 const char *word_break_characters
;
278 const char *quote_characters
;
279 const char *basic_quote_characters
;
283 gdb_rl_find_completion_word (struct gdb_rl_completion_word_info
*info
,
285 const char *line_buffer
)
287 int scan
, end
, found_quote
, delimiter
, pass_next
, isbrk
;
289 const char *brkchars
;
290 int point
= strlen (line_buffer
);
292 /* The algorithm below does '--point'. Avoid buffer underflow with
304 found_quote
= delimiter
= 0;
307 brkchars
= info
->word_break_characters
;
309 if (info
->quote_characters
!= NULL
)
311 /* We have a list of characters which can be used in pairs to
312 quote substrings for the completer. Try to find the start of
313 an unclosed quoted substring. */
314 /* FOUND_QUOTE is set so we know what kind of quotes we
316 for (scan
= pass_next
= 0;
326 /* Shell-like semantics for single quotes -- don't allow
327 backslash to quote anything in single quotes, especially
328 not the closing quote. If you don't like this, take out
329 the check on the value of quote_char. */
330 if (quote_char
!= '\'' && line_buffer
[scan
] == '\\')
333 found_quote
|= RL_QF_BACKSLASH
;
337 if (quote_char
!= '\0')
339 /* Ignore everything until the matching close quote
341 if (line_buffer
[scan
] == quote_char
)
343 /* Found matching close. Abandon this
349 else if (strchr (info
->quote_characters
, line_buffer
[scan
]))
351 /* Found start of a quoted substring. */
352 quote_char
= line_buffer
[scan
];
354 /* Shell-like quoting conventions. */
355 if (quote_char
== '\'')
356 found_quote
|= RL_QF_SINGLE_QUOTE
;
357 else if (quote_char
== '"')
358 found_quote
|= RL_QF_DOUBLE_QUOTE
;
360 found_quote
|= RL_QF_OTHER_QUOTE
;
365 if (point
== end
&& quote_char
== '\0')
367 /* We didn't find an unclosed quoted substring upon which to do
368 completion, so use the word break characters to find the
369 substring on which to complete. */
372 scan
= line_buffer
[point
];
374 if (strchr (brkchars
, scan
) != 0)
379 /* If we are at an unquoted word break, then advance past it. */
380 scan
= line_buffer
[point
];
384 isbrk
= strchr (brkchars
, scan
) != 0;
388 /* If the character that caused the word break was a quoting
389 character, then remember it as the delimiter. */
390 if (info
->basic_quote_characters
391 && strchr (info
->basic_quote_characters
, scan
)
392 && (end
- point
) > 1)
404 return line_buffer
+ point
;
407 /* Find the completion word point for TEXT, emulating the algorithm
408 readline uses to find the word point, using WORD_BREAK_CHARACTERS
409 as word break characters. */
412 advance_to_completion_word (completion_tracker
&tracker
,
413 const char *word_break_characters
,
416 gdb_rl_completion_word_info info
;
418 info
.word_break_characters
= word_break_characters
;
419 info
.quote_characters
= gdb_completer_quote_characters
;
420 info
.basic_quote_characters
= rl_basic_quote_characters
;
424 = gdb_rl_find_completion_word (&info
, NULL
, &delimiter
, text
);
426 tracker
.advance_custom_word_point_by (start
- text
);
430 tracker
.set_quote_char (delimiter
);
431 tracker
.set_suppress_append_ws (true);
437 /* See completer.h. */
440 advance_to_expression_complete_word_point (completion_tracker
&tracker
,
443 const char *brk_chars
= current_language
->word_break_characters ();
444 return advance_to_completion_word (tracker
, brk_chars
, text
);
447 /* See completer.h. */
450 advance_to_filename_complete_word_point (completion_tracker
&tracker
,
453 const char *brk_chars
= gdb_completer_file_name_break_characters
;
454 return advance_to_completion_word (tracker
, brk_chars
, text
);
457 /* See completer.h. */
460 completion_tracker::completes_to_completion_word (const char *word
)
462 recompute_lowest_common_denominator ();
463 if (m_lowest_common_denominator_unique
)
465 const char *lcd
= m_lowest_common_denominator
;
467 if (strncmp_iw (word
, lcd
, strlen (lcd
)) == 0)
469 /* Maybe skip the function and complete on keywords. */
470 size_t wordlen
= strlen (word
);
471 if (word
[wordlen
- 1] == ' ')
479 /* See completer.h. */
482 complete_nested_command_line (completion_tracker
&tracker
, const char *text
)
484 /* Must be called from a custom-word-point completer. */
485 gdb_assert (tracker
.use_custom_word_point ());
487 /* Disable the custom word point temporarily, because we want to
488 probe whether the command we're completing itself uses a custom
490 tracker
.set_use_custom_word_point (false);
491 size_t save_custom_word_point
= tracker
.custom_word_point ();
493 int quote_char
= '\0';
494 const char *word
= completion_find_completion_word (tracker
, text
,
497 if (tracker
.use_custom_word_point ())
499 /* The command we're completing uses a custom word point, so the
500 tracker already contains the matches. We're done. */
504 /* Restore the custom word point settings. */
505 tracker
.set_custom_word_point (save_custom_word_point
);
506 tracker
.set_use_custom_word_point (true);
508 /* Run the handle_completions completer phase. */
509 complete_line (tracker
, word
, text
, strlen (text
));
512 /* Complete on linespecs, which might be of two possible forms:
518 This is intended to be used in commands that set breakpoints
522 complete_files_symbols (completion_tracker
&tracker
,
523 const char *text
, const char *word
)
525 completion_list fn_list
;
528 int quoted
= *text
== '\'' || *text
== '"';
529 int quote_char
= '\0';
530 const char *colon
= NULL
;
531 char *file_to_match
= NULL
;
532 const char *symbol_start
= text
;
533 const char *orig_text
= text
;
535 /* Do we have an unquoted colon, as in "break foo.c:bar"? */
536 for (p
= text
; *p
!= '\0'; ++p
)
538 if (*p
== '\\' && p
[1] == '\'')
540 else if (*p
== '\'' || *p
== '"')
544 while (*p
!= '\0' && *p
!= quote_found
)
546 if (*p
== '\\' && p
[1] == quote_found
)
551 if (*p
== quote_found
)
554 break; /* Hit the end of text. */
556 #if HAVE_DOS_BASED_FILE_SYSTEM
557 /* If we have a DOS-style absolute file name at the beginning of
558 TEXT, and the colon after the drive letter is the only colon
559 we found, pretend the colon is not there. */
560 else if (p
< text
+ 3 && *p
== ':' && p
== text
+ 1 + quoted
)
563 else if (*p
== ':' && !colon
)
566 symbol_start
= p
+ 1;
568 else if (strchr (current_language
->word_break_characters (), *p
))
569 symbol_start
= p
+ 1;
575 /* Where is the file name? */
580 file_to_match
= (char *) xmalloc (colon
- text
+ 1);
581 strncpy (file_to_match
, text
, colon
- text
);
582 file_to_match
[colon
- text
] = '\0';
583 /* Remove trailing colons and quotes from the file name. */
584 for (s
= file_to_match
+ (colon
- text
);
587 if (*s
== ':' || *s
== quote_char
)
590 /* If the text includes a colon, they want completion only on a
591 symbol name after the colon. Otherwise, we need to complete on
592 symbols as well as on files. */
595 collect_file_symbol_completion_matches (tracker
,
596 complete_symbol_mode::EXPRESSION
,
597 symbol_name_match_type::EXPRESSION
,
600 xfree (file_to_match
);
604 size_t text_len
= strlen (text
);
606 collect_symbol_completion_matches (tracker
,
607 complete_symbol_mode::EXPRESSION
,
608 symbol_name_match_type::EXPRESSION
,
610 /* If text includes characters which cannot appear in a file
611 name, they cannot be asking for completion on files. */
613 gdb_completer_file_name_break_characters
) == text_len
)
614 fn_list
= make_source_files_completion_list (text
, text
);
617 if (!fn_list
.empty () && !tracker
.have_completions ())
619 /* If we only have file names as possible completion, we should
620 bring them in sync with what rl_complete expects. The
621 problem is that if the user types "break /foo/b TAB", and the
622 possible completions are "/foo/bar" and "/foo/baz"
623 rl_complete expects us to return "bar" and "baz", without the
624 leading directories, as possible completions, because `word'
625 starts at the "b". But we ignore the value of `word' when we
626 call make_source_files_completion_list above (because that
627 would not DTRT when the completion results in both symbols
628 and file names), so make_source_files_completion_list returns
629 the full "/foo/bar" and "/foo/baz" strings. This produces
630 wrong results when, e.g., there's only one possible
631 completion, because rl_complete will prepend "/foo/" to each
632 candidate completion. The loop below removes that leading
634 for (const auto &fn_up
: fn_list
)
636 char *fn
= fn_up
.get ();
637 memmove (fn
, fn
+ (word
- text
), strlen (fn
) + 1 - (word
- text
));
641 tracker
.add_completions (std::move (fn_list
));
643 if (!tracker
.have_completions ())
645 /* No completions at all. As the final resort, try completing
646 on the entire text as a symbol. */
647 collect_symbol_completion_matches (tracker
,
648 complete_symbol_mode::EXPRESSION
,
649 symbol_name_match_type::EXPRESSION
,
654 /* See completer.h. */
657 complete_source_filenames (const char *text
)
659 size_t text_len
= strlen (text
);
661 /* If text includes characters which cannot appear in a file name,
662 the user cannot be asking for completion on files. */
664 gdb_completer_file_name_break_characters
)
666 return make_source_files_completion_list (text
, text
);
671 /* Complete address and linespec locations. */
674 complete_address_and_linespec_locations (completion_tracker
&tracker
,
676 symbol_name_match_type match_type
)
680 tracker
.advance_custom_word_point_by (1);
683 = advance_to_expression_complete_word_point (tracker
, text
);
684 complete_expression (tracker
, text
, word
);
688 linespec_complete (tracker
, text
, match_type
);
692 /* The explicit location options. Note that indexes into this array
693 must match the explicit_location_match_type enumerators. */
695 static const char *const explicit_options
[] =
705 /* The probe modifier options. These can appear before a location in
706 breakpoint commands. */
707 static const char *const probe_options
[] =
715 /* Returns STRING if not NULL, the empty string otherwise. */
718 string_or_empty (const char *string
)
720 return string
!= NULL
? string
: "";
723 /* A helper function to collect explicit location matches for the given
724 LOCATION, which is attempting to match on WORD. */
727 collect_explicit_location_matches (completion_tracker
&tracker
,
728 struct event_location
*location
,
729 enum explicit_location_match_type what
,
731 const struct language_defn
*language
)
733 const struct explicit_location
*explicit_loc
734 = get_explicit_location (location
);
736 /* True if the option expects an argument. */
737 bool needs_arg
= true;
739 /* Note, in the various MATCH_* below, we complete on
740 explicit_loc->foo instead of WORD, because only the former will
741 have already skipped past any quote char. */
746 const char *source
= string_or_empty (explicit_loc
->source_filename
);
747 completion_list matches
748 = make_source_files_completion_list (source
, source
);
749 tracker
.add_completions (std::move (matches
));
755 const char *function
= string_or_empty (explicit_loc
->function_name
);
756 linespec_complete_function (tracker
, function
,
757 explicit_loc
->func_name_match_type
,
758 explicit_loc
->source_filename
);
762 case MATCH_QUALIFIED
:
766 /* Nothing to offer. */
771 const char *label
= string_or_empty (explicit_loc
->label_name
);
772 linespec_complete_label (tracker
, language
,
773 explicit_loc
->source_filename
,
774 explicit_loc
->function_name
,
775 explicit_loc
->func_name_match_type
,
781 gdb_assert_not_reached ("unhandled explicit_location_match_type");
784 if (!needs_arg
|| tracker
.completes_to_completion_word (word
))
786 tracker
.discard_completions ();
787 tracker
.advance_custom_word_point_by (strlen (word
));
788 complete_on_enum (tracker
, explicit_options
, "", "");
789 complete_on_enum (tracker
, linespec_keywords
, "", "");
791 else if (!tracker
.have_completions ())
793 /* Maybe we have an unterminated linespec keyword at the tail of
794 the string. Try completing on that. */
795 size_t wordlen
= strlen (word
);
796 const char *keyword
= word
+ wordlen
;
798 if (wordlen
> 0 && keyword
[-1] != ' ')
800 while (keyword
> word
&& *keyword
!= ' ')
802 /* Don't complete on keywords if we'd be completing on the
803 whole explicit linespec option. E.g., "b -function
804 thr<tab>" should not complete to the "thread"
808 keyword
= skip_spaces (keyword
);
810 tracker
.advance_custom_word_point_by (keyword
- word
);
811 complete_on_enum (tracker
, linespec_keywords
, keyword
, keyword
);
814 else if (wordlen
> 0 && keyword
[-1] == ' ')
816 /* Assume that we're maybe past the explicit location
817 argument, and we didn't manage to find any match because
818 the user wants to create a pending breakpoint. Offer the
819 keyword and explicit location options as possible
821 tracker
.advance_custom_word_point_by (keyword
- word
);
822 complete_on_enum (tracker
, linespec_keywords
, keyword
, keyword
);
823 complete_on_enum (tracker
, explicit_options
, keyword
, keyword
);
828 /* If the next word in *TEXT_P is any of the keywords in KEYWORDS,
829 then advance both TEXT_P and the word point in the tracker past the
830 keyword and return the (0-based) index in the KEYWORDS array that
831 matched. Otherwise, return -1. */
834 skip_keyword (completion_tracker
&tracker
,
835 const char * const *keywords
, const char **text_p
)
837 const char *text
= *text_p
;
838 const char *after
= skip_to_space (text
);
839 size_t len
= after
- text
;
841 if (text
[len
] != ' ')
845 for (int i
= 0; keywords
[i
] != NULL
; i
++)
847 if (strncmp (keywords
[i
], text
, len
) == 0)
858 tracker
.advance_custom_word_point_by (len
+ 1);
867 /* A completer function for explicit locations. This function
868 completes both options ("-source", "-line", etc) and values. If
869 completing a quoted string, then QUOTED_ARG_START and
870 QUOTED_ARG_END point to the quote characters. LANGUAGE is the
874 complete_explicit_location (completion_tracker
&tracker
,
875 struct event_location
*location
,
877 const language_defn
*language
,
878 const char *quoted_arg_start
,
879 const char *quoted_arg_end
)
884 int keyword
= skip_keyword (tracker
, explicit_options
, &text
);
888 complete_on_enum (tracker
, explicit_options
, text
, text
);
889 /* There are keywords that start with "-". Include them, too. */
890 complete_on_enum (tracker
, linespec_keywords
, text
, text
);
894 /* Completing on value. */
895 enum explicit_location_match_type what
896 = (explicit_location_match_type
) keyword
;
898 if (quoted_arg_start
!= NULL
&& quoted_arg_end
!= NULL
)
900 if (quoted_arg_end
[1] == '\0')
902 /* If completing a quoted string with the cursor right
903 at the terminating quote char, complete the
904 completion word without interpretation, so that
905 readline advances the cursor one whitespace past the
906 quote, even if there's no match. This makes these
907 cases behave the same:
909 before: "b -function function()"
910 after: "b -function function() "
912 before: "b -function 'function()'"
913 after: "b -function 'function()' "
915 and trusts the user in this case:
917 before: "b -function 'not_loaded_function_yet()'"
918 after: "b -function 'not_loaded_function_yet()' "
920 tracker
.add_completion (make_unique_xstrdup (text
));
922 else if (quoted_arg_end
[1] == ' ')
924 /* We're maybe past the explicit location argument.
925 Skip the argument without interpretation, assuming the
926 user may want to create pending breakpoint. Offer
927 the keyword and explicit location options as possible
929 tracker
.advance_custom_word_point_by (strlen (text
));
930 complete_on_enum (tracker
, linespec_keywords
, "", "");
931 complete_on_enum (tracker
, explicit_options
, "", "");
936 /* Now gather matches */
937 collect_explicit_location_matches (tracker
, location
, what
, text
,
942 /* A completer for locations. */
945 location_completer (struct cmd_list_element
*ignore
,
946 completion_tracker
&tracker
,
947 const char *text
, const char * /* word */)
949 int found_probe_option
= -1;
951 /* If we have a probe modifier, skip it. This can only appear as
952 first argument. Until we have a specific completer for probes,
953 falling back to the linespec completer for the remainder of the
954 line is better than nothing. */
955 if (text
[0] == '-' && text
[1] == 'p')
956 found_probe_option
= skip_keyword (tracker
, probe_options
, &text
);
958 const char *option_text
= text
;
959 int saved_word_point
= tracker
.custom_word_point ();
961 const char *copy
= text
;
963 explicit_completion_info completion_info
;
964 event_location_up location
965 = string_to_explicit_location (©
, current_language
,
967 if (completion_info
.quoted_arg_start
!= NULL
968 && completion_info
.quoted_arg_end
== NULL
)
970 /* Found an unbalanced quote. */
971 tracker
.set_quote_char (*completion_info
.quoted_arg_start
);
972 tracker
.advance_custom_word_point_by (1);
975 if (completion_info
.saw_explicit_location_option
)
979 tracker
.advance_custom_word_point_by (copy
- text
);
982 /* We found a terminator at the tail end of the string,
983 which means we're past the explicit location options. We
984 may have a keyword to complete on. If we have a whole
985 keyword, then complete whatever comes after as an
986 expression. This is mainly for the "if" keyword. If the
987 "thread" and "task" keywords gain their own completers,
988 they should be used here. */
989 int keyword
= skip_keyword (tracker
, linespec_keywords
, &text
);
993 complete_on_enum (tracker
, linespec_keywords
, text
, text
);
998 = advance_to_expression_complete_word_point (tracker
, text
);
999 complete_expression (tracker
, text
, word
);
1004 tracker
.advance_custom_word_point_by (completion_info
.last_option
1006 text
= completion_info
.last_option
;
1008 complete_explicit_location (tracker
, location
.get (), text
,
1010 completion_info
.quoted_arg_start
,
1011 completion_info
.quoted_arg_end
);
1015 /* This is an address or linespec location. */
1016 else if (location
!= NULL
)
1018 /* Handle non-explicit location options. */
1020 int keyword
= skip_keyword (tracker
, explicit_options
, &text
);
1022 complete_on_enum (tracker
, explicit_options
, text
, text
);
1025 tracker
.advance_custom_word_point_by (copy
- text
);
1028 symbol_name_match_type match_type
1029 = get_explicit_location (location
.get ())->func_name_match_type
;
1030 complete_address_and_linespec_locations (tracker
, text
, match_type
);
1036 complete_address_and_linespec_locations (tracker
, text
,
1037 symbol_name_match_type::WILD
);
1040 /* Add matches for option names, if either:
1042 - Some completer above found some matches, but the word point did
1043 not advance (e.g., "b <tab>" finds all functions, or "b -<tab>"
1044 matches all objc selectors), or;
1046 - Some completer above advanced the word point, but found no
1049 if ((text
[0] == '-' || text
[0] == '\0')
1050 && (!tracker
.have_completions ()
1051 || tracker
.custom_word_point () == saved_word_point
))
1053 tracker
.set_custom_word_point (saved_word_point
);
1056 if (found_probe_option
== -1)
1057 complete_on_enum (tracker
, probe_options
, text
, text
);
1058 complete_on_enum (tracker
, explicit_options
, text
, text
);
1062 /* The corresponding completer_handle_brkchars
1066 location_completer_handle_brkchars (struct cmd_list_element
*ignore
,
1067 completion_tracker
&tracker
,
1069 const char *word_ignored
)
1071 tracker
.set_use_custom_word_point (true);
1073 location_completer (ignore
, tracker
, text
, NULL
);
1076 /* Helper for expression_completer which recursively adds field and
1077 method names from TYPE, a struct or union type, to the OUTPUT
1081 add_struct_fields (struct type
*type
, completion_list
&output
,
1082 const char *fieldname
, int namelen
)
1085 int computed_type_name
= 0;
1086 const char *type_name
= NULL
;
1088 type
= check_typedef (type
);
1089 for (i
= 0; i
< type
->num_fields (); ++i
)
1091 if (i
< TYPE_N_BASECLASSES (type
))
1092 add_struct_fields (TYPE_BASECLASS (type
, i
),
1093 output
, fieldname
, namelen
);
1094 else if (TYPE_FIELD_NAME (type
, i
))
1096 if (TYPE_FIELD_NAME (type
, i
)[0] != '\0')
1098 if (! strncmp (TYPE_FIELD_NAME (type
, i
),
1099 fieldname
, namelen
))
1100 output
.emplace_back (xstrdup (TYPE_FIELD_NAME (type
, i
)));
1102 else if (type
->field (i
).type ()->code () == TYPE_CODE_UNION
)
1104 /* Recurse into anonymous unions. */
1105 add_struct_fields (type
->field (i
).type (),
1106 output
, fieldname
, namelen
);
1111 for (i
= TYPE_NFN_FIELDS (type
) - 1; i
>= 0; --i
)
1113 const char *name
= TYPE_FN_FIELDLIST_NAME (type
, i
);
1115 if (name
&& ! strncmp (name
, fieldname
, namelen
))
1117 if (!computed_type_name
)
1119 type_name
= type
->name ();
1120 computed_type_name
= 1;
1122 /* Omit constructors from the completion list. */
1123 if (!type_name
|| strcmp (type_name
, name
))
1124 output
.emplace_back (xstrdup (name
));
1129 /* See completer.h. */
1132 complete_expression (completion_tracker
&tracker
,
1133 const char *text
, const char *word
)
1135 struct type
*type
= NULL
;
1136 gdb::unique_xmalloc_ptr
<char> fieldname
;
1137 enum type_code code
= TYPE_CODE_UNDEF
;
1139 /* Perform a tentative parse of the expression, to see whether a
1140 field completion is required. */
1143 type
= parse_expression_for_completion (text
, &fieldname
, &code
);
1145 catch (const gdb_exception_error
&except
)
1150 if (fieldname
!= nullptr && type
)
1154 type
= check_typedef (type
);
1155 if (type
->code () != TYPE_CODE_PTR
&& !TYPE_IS_REFERENCE (type
))
1157 type
= TYPE_TARGET_TYPE (type
);
1160 if (type
->code () == TYPE_CODE_UNION
1161 || type
->code () == TYPE_CODE_STRUCT
)
1163 completion_list result
;
1165 add_struct_fields (type
, result
, fieldname
.get (),
1166 strlen (fieldname
.get ()));
1167 tracker
.add_completions (std::move (result
));
1171 else if (fieldname
!= nullptr && code
!= TYPE_CODE_UNDEF
)
1173 collect_symbol_completion_matches_type (tracker
, fieldname
.get (),
1174 fieldname
.get (), code
);
1178 complete_files_symbols (tracker
, text
, word
);
1181 /* Complete on expressions. Often this means completing on symbol
1182 names, but some language parsers also have support for completing
1186 expression_completer (struct cmd_list_element
*ignore
,
1187 completion_tracker
&tracker
,
1188 const char *text
, const char *word
)
1190 complete_expression (tracker
, text
, word
);
1193 /* See definition in completer.h. */
1196 set_rl_completer_word_break_characters (const char *break_chars
)
1198 rl_completer_word_break_characters
= (char *) break_chars
;
1201 /* Complete on symbols. */
1204 symbol_completer (struct cmd_list_element
*ignore
,
1205 completion_tracker
&tracker
,
1206 const char *text
, const char *word
)
1208 collect_symbol_completion_matches (tracker
, complete_symbol_mode::EXPRESSION
,
1209 symbol_name_match_type::EXPRESSION
,
1213 /* Here are some useful test cases for completion. FIXME: These
1214 should be put in the test suite. They should be tested with both
1217 "show output-" "radix"
1218 "show output" "-radix"
1219 "p" ambiguous (commands starting with p--path, print, printf, etc.)
1220 "p " ambiguous (all symbols)
1221 "info t foo" no completions
1222 "info t " no completions
1223 "info t" ambiguous ("info target", "info terminal", etc.)
1224 "info ajksdlfk" no completions
1225 "info ajksdlfk " no completions
1227 "info " ambiguous (all info commands)
1228 "p \"a" no completions (string constant)
1229 "p 'a" ambiguous (all symbols starting with a)
1230 "p b-a" ambiguous (all symbols starting with a)
1231 "p b-" ambiguous (all symbols)
1232 "file Make" "file" (word break hard to screw up here)
1233 "file ../gdb.stabs/we" "ird" (needs to not break word at slash)
1236 enum complete_line_internal_reason
1238 /* Preliminary phase, called by gdb_completion_word_break_characters
1239 function, is used to either:
1241 #1 - Determine the set of chars that are word delimiters
1242 depending on the current command in line_buffer.
1244 #2 - Manually advance RL_POINT to the "word break" point instead
1245 of letting readline do it (based on too-simple character
1248 Simpler completers that just pass a brkchars array to readline
1249 (#1 above) must defer generating the completions to the main
1250 phase (below). No completion list should be generated in this
1253 OTOH, completers that manually advance the word point(#2 above)
1254 must set "use_custom_word_point" in the tracker and generate
1255 their completion in this phase. Note that this is the convenient
1256 thing to do since they'll be parsing the input line anyway. */
1259 /* Main phase, called by complete_line function, is used to get the
1260 list of possible completions. */
1263 /* Special case when completing a 'help' command. In this case,
1264 once sub-command completions are exhausted, we simply return
1269 /* Helper for complete_line_internal to simplify it. */
1272 complete_line_internal_normal_command (completion_tracker
&tracker
,
1273 const char *command
, const char *word
,
1274 const char *cmd_args
,
1275 complete_line_internal_reason reason
,
1276 struct cmd_list_element
*c
)
1278 const char *p
= cmd_args
;
1280 if (c
->completer
== filename_completer
)
1282 /* Many commands which want to complete on file names accept
1283 several file names, as in "run foo bar >>baz". So we don't
1284 want to complete the entire text after the command, just the
1285 last word. To this end, we need to find the beginning of the
1286 file name by starting at `word' and going backwards. */
1289 && strchr (gdb_completer_file_name_break_characters
,
1295 if (reason
== handle_brkchars
)
1297 completer_handle_brkchars_ftype
*brkchars_fn
;
1299 if (c
->completer_handle_brkchars
!= NULL
)
1300 brkchars_fn
= c
->completer_handle_brkchars
;
1304 = (completer_handle_brkchars_func_for_completer
1308 brkchars_fn (c
, tracker
, p
, word
);
1311 if (reason
!= handle_brkchars
&& c
->completer
!= NULL
)
1312 (*c
->completer
) (c
, tracker
, p
, word
);
1315 /* Internal function used to handle completions.
1318 TEXT is the caller's idea of the "word" we are looking at.
1320 LINE_BUFFER is available to be looked at; it contains the entire
1321 text of the line. POINT is the offset in that line of the cursor.
1322 You should pretend that the line ends at POINT.
1324 See complete_line_internal_reason for description of REASON. */
1327 complete_line_internal_1 (completion_tracker
&tracker
,
1329 const char *line_buffer
, int point
,
1330 complete_line_internal_reason reason
)
1334 int ignore_help_classes
;
1335 /* Pointer within tmp_command which corresponds to text. */
1337 struct cmd_list_element
*c
, *result_list
;
1339 /* Choose the default set of word break characters to break
1340 completions. If we later find out that we are doing completions
1341 on command strings (as opposed to strings supplied by the
1342 individual command completer functions, which can be any string)
1343 then we will switch to the special word break set for command
1344 strings, which leaves out the '-' and '.' character used in some
1346 set_rl_completer_word_break_characters
1347 (current_language
->word_break_characters ());
1349 /* Decide whether to complete on a list of gdb commands or on
1351 tmp_command
= (char *) alloca (point
+ 1);
1354 /* The help command should complete help aliases. */
1355 ignore_help_classes
= reason
!= handle_help
;
1357 strncpy (tmp_command
, line_buffer
, point
);
1358 tmp_command
[point
] = '\0';
1359 if (reason
== handle_brkchars
)
1361 gdb_assert (text
== NULL
);
1366 /* Since text always contains some number of characters leading up
1367 to point, we can find the equivalent position in tmp_command
1368 by subtracting that many characters from the end of tmp_command. */
1369 word
= tmp_command
+ point
- strlen (text
);
1372 /* Move P up to the start of the command. */
1373 p
= skip_spaces (p
);
1377 /* An empty line is ambiguous; that is, it could be any
1379 c
= CMD_LIST_AMBIGUOUS
;
1383 c
= lookup_cmd_1 (&p
, cmdlist
, &result_list
, NULL
, ignore_help_classes
,
1386 /* Move p up to the next interesting thing. */
1387 while (*p
== ' ' || *p
== '\t')
1392 tracker
.advance_custom_word_point_by (p
- tmp_command
);
1396 /* It is an unrecognized command. So there are no
1397 possible completions. */
1399 else if (c
== CMD_LIST_AMBIGUOUS
)
1403 /* lookup_cmd_1 advances p up to the first ambiguous thing, but
1404 doesn't advance over that thing itself. Do so now. */
1406 while (valid_cmd_char_p (*q
))
1408 if (q
!= tmp_command
+ point
)
1410 /* There is something beyond the ambiguous
1411 command, so there are no possible completions. For
1412 example, "info t " or "info t foo" does not complete
1413 to anything, because "info t" can be "info target" or
1418 /* We're trying to complete on the command which was ambiguous.
1419 This we can deal with. */
1422 if (reason
!= handle_brkchars
)
1423 complete_on_cmdlist (*result_list
->subcommands
, tracker
, p
,
1424 word
, ignore_help_classes
);
1428 if (reason
!= handle_brkchars
)
1429 complete_on_cmdlist (cmdlist
, tracker
, p
, word
,
1430 ignore_help_classes
);
1432 /* Ensure that readline does the right thing with respect to
1433 inserting quotes. */
1434 set_rl_completer_word_break_characters
1435 (gdb_completer_command_word_break_characters
);
1440 /* We've recognized a full command. */
1442 if (p
== tmp_command
+ point
)
1444 /* There is no non-whitespace in the line beyond the
1447 if (p
[-1] == ' ' || p
[-1] == '\t')
1449 /* The command is followed by whitespace; we need to
1450 complete on whatever comes after command. */
1451 if (c
->is_prefix ())
1453 /* It is a prefix command; what comes after it is
1454 a subcommand (e.g. "info "). */
1455 if (reason
!= handle_brkchars
)
1456 complete_on_cmdlist (*c
->subcommands
, tracker
, p
, word
,
1457 ignore_help_classes
);
1459 /* Ensure that readline does the right thing
1460 with respect to inserting quotes. */
1461 set_rl_completer_word_break_characters
1462 (gdb_completer_command_word_break_characters
);
1464 else if (reason
== handle_help
)
1468 if (reason
!= handle_brkchars
)
1469 complete_on_enum (tracker
, c
->enums
, p
, word
);
1470 set_rl_completer_word_break_characters
1471 (gdb_completer_command_word_break_characters
);
1475 /* It is a normal command; what comes after it is
1476 completed by the command's completer function. */
1477 complete_line_internal_normal_command (tracker
,
1478 tmp_command
, word
, p
,
1484 /* The command is not followed by whitespace; we need to
1485 complete on the command itself, e.g. "p" which is a
1486 command itself but also can complete to "print", "ptype"
1490 /* Find the command we are completing on. */
1492 while (q
> tmp_command
)
1494 if (valid_cmd_char_p (q
[-1]))
1500 /* Move the custom word point back too. */
1501 tracker
.advance_custom_word_point_by (q
- p
);
1503 if (reason
!= handle_brkchars
)
1504 complete_on_cmdlist (result_list
, tracker
, q
, word
,
1505 ignore_help_classes
);
1507 /* Ensure that readline does the right thing
1508 with respect to inserting quotes. */
1509 set_rl_completer_word_break_characters
1510 (gdb_completer_command_word_break_characters
);
1513 else if (reason
== handle_help
)
1517 /* There is non-whitespace beyond the command. */
1519 if (c
->is_prefix () && !c
->allow_unknown
)
1521 /* It is an unrecognized subcommand of a prefix command,
1522 e.g. "info adsfkdj". */
1526 if (reason
!= handle_brkchars
)
1527 complete_on_enum (tracker
, c
->enums
, p
, word
);
1531 /* It is a normal command. */
1532 complete_line_internal_normal_command (tracker
,
1533 tmp_command
, word
, p
,
1540 /* Wrapper around complete_line_internal_1 to handle
1541 MAX_COMPLETIONS_REACHED_ERROR. */
1544 complete_line_internal (completion_tracker
&tracker
,
1546 const char *line_buffer
, int point
,
1547 complete_line_internal_reason reason
)
1551 complete_line_internal_1 (tracker
, text
, line_buffer
, point
, reason
);
1553 catch (const gdb_exception_error
&except
)
1555 if (except
.error
!= MAX_COMPLETIONS_REACHED_ERROR
)
1560 /* See completer.h. */
1562 int max_completions
= 200;
1564 /* Initial size of the table. It automagically grows from here. */
1565 #define INITIAL_COMPLETION_HTAB_SIZE 200
1567 /* See completer.h. */
1569 completion_tracker::completion_tracker ()
1571 discard_completions ();
1574 /* See completer.h. */
1577 completion_tracker::discard_completions ()
1579 xfree (m_lowest_common_denominator
);
1580 m_lowest_common_denominator
= NULL
;
1582 m_lowest_common_denominator_unique
= false;
1583 m_lowest_common_denominator_valid
= false;
1585 m_entries_hash
.reset (nullptr);
1587 /* A callback used by the hash table to compare new entries with existing
1588 entries. We can't use the standard htab_eq_string function here as the
1589 key to our hash is just a single string, while the values we store in
1590 the hash are a struct containing multiple strings. */
1591 static auto entry_eq_func
1592 = [] (const void *first
, const void *second
) -> int
1594 /* The FIRST argument is the entry already in the hash table, and
1595 the SECOND argument is the new item being inserted. */
1596 const completion_hash_entry
*entry
1597 = (const completion_hash_entry
*) first
;
1598 const char *name_str
= (const char *) second
;
1600 return entry
->is_name_eq (name_str
);
1603 /* Callback used by the hash table to compute the hash value for an
1604 existing entry. This is needed when expanding the hash table. */
1605 static auto entry_hash_func
1606 = [] (const void *arg
) -> hashval_t
1608 const completion_hash_entry
*entry
1609 = (const completion_hash_entry
*) arg
;
1610 return entry
->hash_name ();
1613 m_entries_hash
.reset
1614 (htab_create_alloc (INITIAL_COMPLETION_HTAB_SIZE
,
1615 entry_hash_func
, entry_eq_func
,
1616 htab_delete_entry
<completion_hash_entry
>,
1620 /* See completer.h. */
1622 completion_tracker::~completion_tracker ()
1624 xfree (m_lowest_common_denominator
);
1627 /* See completer.h. */
1630 completion_tracker::maybe_add_completion
1631 (gdb::unique_xmalloc_ptr
<char> name
,
1632 completion_match_for_lcd
*match_for_lcd
,
1633 const char *text
, const char *word
)
1637 if (max_completions
== 0)
1640 if (htab_elements (m_entries_hash
.get ()) >= max_completions
)
1643 hashval_t hash
= htab_hash_string (name
.get ());
1644 slot
= htab_find_slot_with_hash (m_entries_hash
.get (), name
.get (),
1646 if (*slot
== HTAB_EMPTY_ENTRY
)
1648 const char *match_for_lcd_str
= NULL
;
1650 if (match_for_lcd
!= NULL
)
1651 match_for_lcd_str
= match_for_lcd
->finish ();
1653 if (match_for_lcd_str
== NULL
)
1654 match_for_lcd_str
= name
.get ();
1656 gdb::unique_xmalloc_ptr
<char> lcd
1657 = make_completion_match_str (match_for_lcd_str
, text
, word
);
1659 size_t lcd_len
= strlen (lcd
.get ());
1660 *slot
= new completion_hash_entry (std::move (name
), std::move (lcd
));
1662 m_lowest_common_denominator_valid
= false;
1663 m_lowest_common_denominator_max_length
1664 = std::max (m_lowest_common_denominator_max_length
, lcd_len
);
1670 /* See completer.h. */
1673 completion_tracker::add_completion (gdb::unique_xmalloc_ptr
<char> name
,
1674 completion_match_for_lcd
*match_for_lcd
,
1675 const char *text
, const char *word
)
1677 if (!maybe_add_completion (std::move (name
), match_for_lcd
, text
, word
))
1678 throw_error (MAX_COMPLETIONS_REACHED_ERROR
, _("Max completions reached."));
1681 /* See completer.h. */
1684 completion_tracker::add_completions (completion_list
&&list
)
1686 for (auto &candidate
: list
)
1687 add_completion (std::move (candidate
));
1690 /* See completer.h. */
1693 completion_tracker::remove_completion (const char *name
)
1695 hashval_t hash
= htab_hash_string (name
);
1696 if (htab_find_slot_with_hash (m_entries_hash
.get (), name
, hash
, NO_INSERT
)
1699 htab_remove_elt_with_hash (m_entries_hash
.get (), name
, hash
);
1700 m_lowest_common_denominator_valid
= false;
1704 /* Helper for the make_completion_match_str overloads. Returns NULL
1705 as an indication that we want MATCH_NAME exactly. It is up to the
1706 caller to xstrdup that string if desired. */
1709 make_completion_match_str_1 (const char *match_name
,
1710 const char *text
, const char *word
)
1716 /* Return NULL as an indication that we want MATCH_NAME
1720 else if (word
> text
)
1722 /* Return some portion of MATCH_NAME. */
1723 newobj
= xstrdup (match_name
+ (word
- text
));
1727 /* Return some of WORD plus MATCH_NAME. */
1728 size_t len
= strlen (match_name
);
1729 newobj
= (char *) xmalloc (text
- word
+ len
+ 1);
1730 memcpy (newobj
, word
, text
- word
);
1731 memcpy (newobj
+ (text
- word
), match_name
, len
+ 1);
1737 /* See completer.h. */
1739 gdb::unique_xmalloc_ptr
<char>
1740 make_completion_match_str (const char *match_name
,
1741 const char *text
, const char *word
)
1743 char *newobj
= make_completion_match_str_1 (match_name
, text
, word
);
1745 newobj
= xstrdup (match_name
);
1746 return gdb::unique_xmalloc_ptr
<char> (newobj
);
1749 /* See completer.h. */
1751 gdb::unique_xmalloc_ptr
<char>
1752 make_completion_match_str (gdb::unique_xmalloc_ptr
<char> &&match_name
,
1753 const char *text
, const char *word
)
1755 char *newobj
= make_completion_match_str_1 (match_name
.get (), text
, word
);
1757 return std::move (match_name
);
1758 return gdb::unique_xmalloc_ptr
<char> (newobj
);
1761 /* See complete.h. */
1764 complete (const char *line
, char const **word
, int *quote_char
)
1766 completion_tracker tracker_handle_brkchars
;
1767 completion_tracker tracker_handle_completions
;
1768 completion_tracker
*tracker
;
1770 /* The WORD should be set to the end of word to complete. We initialize
1771 to the completion point which is assumed to be at the end of LINE.
1772 This leaves WORD to be initialized to a sensible value in cases
1773 completion_find_completion_word() fails i.e., throws an exception.
1775 *word
= line
+ strlen (line
);
1779 *word
= completion_find_completion_word (tracker_handle_brkchars
,
1782 /* Completers that provide a custom word point in the
1783 handle_brkchars phase also compute their completions then.
1784 Completers that leave the completion word handling to readline
1785 must be called twice. */
1786 if (tracker_handle_brkchars
.use_custom_word_point ())
1787 tracker
= &tracker_handle_brkchars
;
1790 complete_line (tracker_handle_completions
, *word
, line
, strlen (line
));
1791 tracker
= &tracker_handle_completions
;
1794 catch (const gdb_exception
&ex
)
1799 return tracker
->build_completion_result (*word
, *word
- line
, strlen (line
));
1803 /* Generate completions all at once. Does nothing if max_completions
1804 is 0. If max_completions is non-negative, this will collect at
1805 most max_completions strings.
1807 TEXT is the caller's idea of the "word" we are looking at.
1809 LINE_BUFFER is available to be looked at; it contains the entire
1812 POINT is the offset in that line of the cursor. You
1813 should pretend that the line ends at POINT. */
1816 complete_line (completion_tracker
&tracker
,
1817 const char *text
, const char *line_buffer
, int point
)
1819 if (max_completions
== 0)
1821 complete_line_internal (tracker
, text
, line_buffer
, point
,
1822 handle_completions
);
1825 /* Complete on command names. Used by "help". */
1828 command_completer (struct cmd_list_element
*ignore
,
1829 completion_tracker
&tracker
,
1830 const char *text
, const char *word
)
1832 complete_line_internal (tracker
, word
, text
,
1833 strlen (text
), handle_help
);
1836 /* The corresponding completer_handle_brkchars implementation. */
1839 command_completer_handle_brkchars (struct cmd_list_element
*ignore
,
1840 completion_tracker
&tracker
,
1841 const char *text
, const char *word
)
1843 set_rl_completer_word_break_characters
1844 (gdb_completer_command_word_break_characters
);
1847 /* Complete on signals. */
1850 signal_completer (struct cmd_list_element
*ignore
,
1851 completion_tracker
&tracker
,
1852 const char *text
, const char *word
)
1854 size_t len
= strlen (word
);
1856 const char *signame
;
1858 for (signum
= GDB_SIGNAL_FIRST
; signum
!= GDB_SIGNAL_LAST
; ++signum
)
1860 /* Can't handle this, so skip it. */
1861 if (signum
== GDB_SIGNAL_0
)
1864 signame
= gdb_signal_to_name ((enum gdb_signal
) signum
);
1866 /* Ignore the unknown signal case. */
1867 if (!signame
|| strcmp (signame
, "?") == 0)
1870 if (strncasecmp (signame
, word
, len
) == 0)
1871 tracker
.add_completion (make_unique_xstrdup (signame
));
1875 /* Bit-flags for selecting what the register and/or register-group
1876 completer should complete on. */
1878 enum reg_completer_target
1880 complete_register_names
= 0x1,
1881 complete_reggroup_names
= 0x2
1883 DEF_ENUM_FLAGS_TYPE (enum reg_completer_target
, reg_completer_targets
);
1885 /* Complete register names and/or reggroup names based on the value passed
1886 in TARGETS. At least one bit in TARGETS must be set. */
1889 reg_or_group_completer_1 (completion_tracker
&tracker
,
1890 const char *text
, const char *word
,
1891 reg_completer_targets targets
)
1893 size_t len
= strlen (word
);
1894 struct gdbarch
*gdbarch
;
1897 gdb_assert ((targets
& (complete_register_names
1898 | complete_reggroup_names
)) != 0);
1899 gdbarch
= get_current_arch ();
1901 if ((targets
& complete_register_names
) != 0)
1906 (name
= user_reg_map_regnum_to_name (gdbarch
, i
)) != NULL
;
1909 if (*name
!= '\0' && strncmp (word
, name
, len
) == 0)
1910 tracker
.add_completion (make_unique_xstrdup (name
));
1914 if ((targets
& complete_reggroup_names
) != 0)
1916 struct reggroup
*group
;
1918 for (group
= reggroup_next (gdbarch
, NULL
);
1920 group
= reggroup_next (gdbarch
, group
))
1922 name
= reggroup_name (group
);
1923 if (strncmp (word
, name
, len
) == 0)
1924 tracker
.add_completion (make_unique_xstrdup (name
));
1929 /* Perform completion on register and reggroup names. */
1932 reg_or_group_completer (struct cmd_list_element
*ignore
,
1933 completion_tracker
&tracker
,
1934 const char *text
, const char *word
)
1936 reg_or_group_completer_1 (tracker
, text
, word
,
1937 (complete_register_names
1938 | complete_reggroup_names
));
1941 /* Perform completion on reggroup names. */
1944 reggroup_completer (struct cmd_list_element
*ignore
,
1945 completion_tracker
&tracker
,
1946 const char *text
, const char *word
)
1948 reg_or_group_completer_1 (tracker
, text
, word
,
1949 complete_reggroup_names
);
1952 /* The default completer_handle_brkchars implementation. */
1955 default_completer_handle_brkchars (struct cmd_list_element
*ignore
,
1956 completion_tracker
&tracker
,
1957 const char *text
, const char *word
)
1959 set_rl_completer_word_break_characters
1960 (current_language
->word_break_characters ());
1963 /* See definition in completer.h. */
1965 completer_handle_brkchars_ftype
*
1966 completer_handle_brkchars_func_for_completer (completer_ftype
*fn
)
1968 if (fn
== filename_completer
)
1969 return filename_completer_handle_brkchars
;
1971 if (fn
== location_completer
)
1972 return location_completer_handle_brkchars
;
1974 if (fn
== command_completer
)
1975 return command_completer_handle_brkchars
;
1977 return default_completer_handle_brkchars
;
1980 /* Used as brkchars when we want to tell readline we have a custom
1981 word point. We do that by making our rl_completion_word_break_hook
1982 set RL_POINT to the desired word point, and return the character at
1983 the word break point as the break char. This is two bytes in order
1984 to fit one break character plus the terminating null. */
1985 static char gdb_custom_word_point_brkchars
[2];
1987 /* Since rl_basic_quote_characters is not completer-specific, we save
1988 its original value here, in order to be able to restore it in
1989 gdb_rl_attempted_completion_function. */
1990 static const char *gdb_org_rl_basic_quote_characters
= rl_basic_quote_characters
;
1992 /* Get the list of chars that are considered as word breaks
1993 for the current command. */
1996 gdb_completion_word_break_characters_throw ()
1998 /* New completion starting. Get rid of the previous tracker and
2000 delete current_completion
.tracker
;
2001 current_completion
.tracker
= new completion_tracker ();
2003 completion_tracker
&tracker
= *current_completion
.tracker
;
2005 complete_line_internal (tracker
, NULL
, rl_line_buffer
,
2006 rl_point
, handle_brkchars
);
2008 if (tracker
.use_custom_word_point ())
2010 gdb_assert (tracker
.custom_word_point () > 0);
2011 rl_point
= tracker
.custom_word_point () - 1;
2013 gdb_assert (rl_point
>= 0 && rl_point
< strlen (rl_line_buffer
));
2015 gdb_custom_word_point_brkchars
[0] = rl_line_buffer
[rl_point
];
2016 rl_completer_word_break_characters
= gdb_custom_word_point_brkchars
;
2017 rl_completer_quote_characters
= NULL
;
2019 /* Clear this too, so that if we're completing a quoted string,
2020 readline doesn't consider the quote character a delimiter.
2021 If we didn't do this, readline would auto-complete {b
2022 'fun<tab>} to {'b 'function()'}, i.e., add the terminating
2023 \', but, it wouldn't append the separator space either, which
2024 is not desirable. So instead we take care of appending the
2025 quote character to the LCD ourselves, in
2026 gdb_rl_attempted_completion_function. Since this global is
2027 not just completer-specific, we'll restore it back to the
2028 default in gdb_rl_attempted_completion_function. */
2029 rl_basic_quote_characters
= NULL
;
2032 return rl_completer_word_break_characters
;
2036 gdb_completion_word_break_characters ()
2038 /* New completion starting. */
2039 current_completion
.aborted
= false;
2043 return gdb_completion_word_break_characters_throw ();
2045 catch (const gdb_exception
&ex
)
2047 /* Set this to that gdb_rl_attempted_completion_function knows
2049 current_completion
.aborted
= true;
2055 /* See completer.h. */
2058 completion_find_completion_word (completion_tracker
&tracker
, const char *text
,
2061 size_t point
= strlen (text
);
2063 complete_line_internal (tracker
, NULL
, text
, point
, handle_brkchars
);
2065 if (tracker
.use_custom_word_point ())
2067 gdb_assert (tracker
.custom_word_point () > 0);
2068 *quote_char
= tracker
.quote_char ();
2069 return text
+ tracker
.custom_word_point ();
2072 gdb_rl_completion_word_info info
;
2074 info
.word_break_characters
= rl_completer_word_break_characters
;
2075 info
.quote_characters
= gdb_completer_quote_characters
;
2076 info
.basic_quote_characters
= rl_basic_quote_characters
;
2078 return gdb_rl_find_completion_word (&info
, quote_char
, NULL
, text
);
2081 /* See completer.h. */
2084 completion_tracker::recompute_lcd_visitor (completion_hash_entry
*entry
)
2086 if (!m_lowest_common_denominator_valid
)
2088 /* This is the first lowest common denominator that we are
2089 considering, just copy it in. */
2090 strcpy (m_lowest_common_denominator
, entry
->get_lcd ());
2091 m_lowest_common_denominator_unique
= true;
2092 m_lowest_common_denominator_valid
= true;
2096 /* Find the common denominator between the currently-known lowest
2097 common denominator and NEW_MATCH_UP. That becomes the new lowest
2098 common denominator. */
2100 const char *new_match
= entry
->get_lcd ();
2103 (new_match
[i
] != '\0'
2104 && new_match
[i
] == m_lowest_common_denominator
[i
]);
2107 if (m_lowest_common_denominator
[i
] != new_match
[i
])
2109 m_lowest_common_denominator
[i
] = '\0';
2110 m_lowest_common_denominator_unique
= false;
2115 /* See completer.h. */
2118 completion_tracker::recompute_lowest_common_denominator ()
2120 /* We've already done this. */
2121 if (m_lowest_common_denominator_valid
)
2124 /* Resize the storage to ensure we have enough space, the plus one gives
2125 us space for the trailing null terminator we will include. */
2126 m_lowest_common_denominator
2127 = (char *) xrealloc (m_lowest_common_denominator
,
2128 m_lowest_common_denominator_max_length
+ 1);
2130 /* Callback used to visit each entry in the m_entries_hash. */
2132 = [] (void **slot
, void *info
) -> int
2134 completion_tracker
*obj
= (completion_tracker
*) info
;
2135 completion_hash_entry
*entry
= (completion_hash_entry
*) *slot
;
2136 obj
->recompute_lcd_visitor (entry
);
2140 htab_traverse (m_entries_hash
.get (), visitor_func
, this);
2141 m_lowest_common_denominator_valid
= true;
2144 /* See completer.h. */
2147 completion_tracker::advance_custom_word_point_by (int len
)
2149 m_custom_word_point
+= len
;
2152 /* Build a new C string that is a copy of LCD with the whitespace of
2153 ORIG/ORIG_LEN preserved.
2155 Say the user is completing a symbol name, with spaces, like:
2159 and the resulting completion match is:
2163 we want to end up with an input line like:
2166 ^^^^^^^ => text from LCD [1], whitespace from ORIG preserved.
2167 ^^ => new text from LCD
2169 [1] - We must take characters from the LCD instead of the original
2170 text, since some completions want to change upper/lowercase. E.g.:
2176 "handle SIG[QUIT|etc.]"
2180 expand_preserving_ws (const char *orig
, size_t orig_len
,
2183 const char *p_orig
= orig
;
2184 const char *orig_end
= orig
+ orig_len
;
2185 const char *p_lcd
= lcd
;
2188 while (p_orig
< orig_end
)
2192 while (p_orig
< orig_end
&& *p_orig
== ' ')
2194 p_lcd
= skip_spaces (p_lcd
);
2198 /* Take characters from the LCD instead of the original
2199 text, since some completions change upper/lowercase.
2203 "handle SIG[QUIT|etc.]"
2211 while (*p_lcd
!= '\0')
2214 return xstrdup (res
.c_str ());
2217 /* See completer.h. */
2220 completion_tracker::build_completion_result (const char *text
,
2223 size_t element_count
= htab_elements (m_entries_hash
.get ());
2225 if (element_count
== 0)
2228 /* +1 for the LCD, and +1 for NULL termination. */
2229 char **match_list
= XNEWVEC (char *, 1 + element_count
+ 1);
2231 /* Build replacement word, based on the LCD. */
2233 recompute_lowest_common_denominator ();
2235 = expand_preserving_ws (text
, end
- start
,
2236 m_lowest_common_denominator
);
2238 if (m_lowest_common_denominator_unique
)
2240 /* We don't rely on readline appending the quote char as
2241 delimiter as then readline wouldn't append the ' ' after the
2243 char buf
[2] = { (char) quote_char () };
2245 match_list
[0] = reconcat (match_list
[0], match_list
[0],
2246 buf
, (char *) NULL
);
2247 match_list
[1] = NULL
;
2249 /* If the tracker wants to, or we already have a space at the
2250 end of the match, tell readline to skip appending
2252 char *match
= match_list
[0];
2253 bool completion_suppress_append
2254 = (suppress_append_ws ()
2255 || (match
[0] != '\0'
2256 && match
[strlen (match
) - 1] == ' '));
2258 return completion_result (match_list
, 1, completion_suppress_append
);
2262 /* State object used while building the completion list. */
2265 list_builder (char **ml
)
2270 /* The list we are filling. */
2273 /* The next index in the list to write to. */
2276 list_builder
builder (match_list
);
2278 /* Visit each entry in m_entries_hash and add it to the completion
2279 list, updating the builder state object. */
2281 = [] (void **slot
, void *info
) -> int
2283 completion_hash_entry
*entry
= (completion_hash_entry
*) *slot
;
2284 list_builder
*state
= (list_builder
*) info
;
2286 state
->match_list
[state
->index
] = entry
->release_name ();
2291 /* Build the completion list and add a null at the end. */
2292 htab_traverse_noresize (m_entries_hash
.get (), func
, &builder
);
2293 match_list
[builder
.index
] = NULL
;
2295 return completion_result (match_list
, builder
.index
- 1, false);
2299 /* See completer.h */
2301 completion_result::completion_result ()
2302 : match_list (NULL
), number_matches (0),
2303 completion_suppress_append (false)
2306 /* See completer.h */
2308 completion_result::completion_result (char **match_list_
,
2309 size_t number_matches_
,
2310 bool completion_suppress_append_
)
2311 : match_list (match_list_
),
2312 number_matches (number_matches_
),
2313 completion_suppress_append (completion_suppress_append_
)
2316 /* See completer.h */
2318 completion_result::~completion_result ()
2320 reset_match_list ();
2323 /* See completer.h */
2325 completion_result::completion_result (completion_result
&&rhs
) noexcept
2326 : match_list (rhs
.match_list
),
2327 number_matches (rhs
.number_matches
)
2329 rhs
.match_list
= NULL
;
2330 rhs
.number_matches
= 0;
2333 /* See completer.h */
2336 completion_result::release_match_list ()
2338 char **ret
= match_list
;
2343 /* See completer.h */
2346 completion_result::sort_match_list ()
2348 if (number_matches
> 1)
2350 /* Element 0 is special (it's the common prefix), leave it
2352 std::sort (&match_list
[1],
2353 &match_list
[number_matches
+ 1],
2358 /* See completer.h */
2361 completion_result::reset_match_list ()
2363 if (match_list
!= NULL
)
2365 for (char **p
= match_list
; *p
!= NULL
; p
++)
2372 /* Helper for gdb_rl_attempted_completion_function, which does most of
2373 the work. This is called by readline to build the match list array
2374 and to determine the lowest common denominator. The real matches
2375 list starts at match[1], while match[0] is the slot holding
2376 readline's idea of the lowest common denominator of all matches,
2377 which is what readline replaces the completion "word" with.
2379 TEXT is the caller's idea of the "word" we are looking at, as
2380 computed in the handle_brkchars phase.
2382 START is the offset from RL_LINE_BUFFER where TEXT starts. END is
2383 the offset from RL_LINE_BUFFER where TEXT ends (i.e., where
2386 You should thus pretend that the line ends at END (relative to
2389 RL_LINE_BUFFER contains the entire text of the line. RL_POINT is
2390 the offset in that line of the cursor. You should pretend that the
2393 Returns NULL if there are no completions. */
2396 gdb_rl_attempted_completion_function_throw (const char *text
, int start
, int end
)
2398 /* Completers that provide a custom word point in the
2399 handle_brkchars phase also compute their completions then.
2400 Completers that leave the completion word handling to readline
2401 must be called twice. If rl_point (i.e., END) is at column 0,
2402 then readline skips the handle_brkchars phase, and so we create a
2403 tracker now in that case too. */
2404 if (end
== 0 || !current_completion
.tracker
->use_custom_word_point ())
2406 delete current_completion
.tracker
;
2407 current_completion
.tracker
= new completion_tracker ();
2409 complete_line (*current_completion
.tracker
, text
,
2410 rl_line_buffer
, rl_point
);
2413 completion_tracker
&tracker
= *current_completion
.tracker
;
2415 completion_result result
2416 = tracker
.build_completion_result (text
, start
, end
);
2418 rl_completion_suppress_append
= result
.completion_suppress_append
;
2419 return result
.release_match_list ();
2422 /* Function installed as "rl_attempted_completion_function" readline
2423 hook. Wrapper around gdb_rl_attempted_completion_function_throw
2424 that catches C++ exceptions, which can't cross readline. */
2427 gdb_rl_attempted_completion_function (const char *text
, int start
, int end
)
2429 /* Restore globals that might have been tweaked in
2430 gdb_completion_word_break_characters. */
2431 rl_basic_quote_characters
= gdb_org_rl_basic_quote_characters
;
2433 /* If we end up returning NULL, either on error, or simple because
2434 there are no matches, inhibit readline's default filename
2436 rl_attempted_completion_over
= 1;
2438 /* If the handle_brkchars phase was aborted, don't try
2440 if (current_completion
.aborted
)
2445 return gdb_rl_attempted_completion_function_throw (text
, start
, end
);
2447 catch (const gdb_exception
&ex
)
2454 /* Skip over the possibly quoted word STR (as defined by the quote
2455 characters QUOTECHARS and the word break characters BREAKCHARS).
2456 Returns pointer to the location after the "word". If either
2457 QUOTECHARS or BREAKCHARS is NULL, use the same values used by the
2461 skip_quoted_chars (const char *str
, const char *quotechars
,
2462 const char *breakchars
)
2464 char quote_char
= '\0';
2467 if (quotechars
== NULL
)
2468 quotechars
= gdb_completer_quote_characters
;
2470 if (breakchars
== NULL
)
2471 breakchars
= current_language
->word_break_characters ();
2473 for (scan
= str
; *scan
!= '\0'; scan
++)
2475 if (quote_char
!= '\0')
2477 /* Ignore everything until the matching close quote char. */
2478 if (*scan
== quote_char
)
2480 /* Found matching close quote. */
2485 else if (strchr (quotechars
, *scan
))
2487 /* Found start of a quoted string. */
2490 else if (strchr (breakchars
, *scan
))
2499 /* Skip over the possibly quoted word STR (as defined by the quote
2500 characters and word break characters used by the completer).
2501 Returns pointer to the location after the "word". */
2504 skip_quoted (const char *str
)
2506 return skip_quoted_chars (str
, NULL
, NULL
);
2509 /* Return a message indicating that the maximum number of completions
2510 has been reached and that there may be more. */
2513 get_max_completions_reached_message (void)
2515 return _("*** List may be truncated, max-completions reached. ***");
2518 /* GDB replacement for rl_display_match_list.
2519 Readline doesn't provide a clean interface for TUI(curses).
2520 A hack previously used was to send readline's rl_outstream through a pipe
2521 and read it from the event loop. Bleah. IWBN if readline abstracted
2522 away all the necessary bits, and this is what this code does. It
2523 replicates the parts of readline we need and then adds an abstraction
2524 layer, currently implemented as struct match_list_displayer, so that both
2525 CLI and TUI can use it. We copy all this readline code to minimize
2526 GDB-specific mods to readline. Once this code performs as desired then
2527 we can submit it to the readline maintainers.
2529 N.B. A lot of the code is the way it is in order to minimize differences
2530 from readline's copy. */
2532 /* Not supported here. */
2533 #undef VISIBLE_STATS
2535 #if defined (HANDLE_MULTIBYTE)
2536 #define MB_INVALIDCH(x) ((x) == (size_t)-1 || (x) == (size_t)-2)
2537 #define MB_NULLWCH(x) ((x) == 0)
2540 #define ELLIPSIS_LEN 3
2542 /* gdb version of readline/complete.c:get_y_or_n.
2543 'y' -> returns 1, and 'n' -> returns 0.
2544 Also supported: space == 'y', RUBOUT == 'n', ctrl-g == start over.
2545 If FOR_PAGER is non-zero, then also supported are:
2546 NEWLINE or RETURN -> returns 2, and 'q' -> returns 0. */
2549 gdb_get_y_or_n (int for_pager
, const struct match_list_displayer
*displayer
)
2555 RL_SETSTATE (RL_STATE_MOREINPUT
);
2556 c
= displayer
->read_key (displayer
);
2557 RL_UNSETSTATE (RL_STATE_MOREINPUT
);
2559 if (c
== 'y' || c
== 'Y' || c
== ' ')
2561 if (c
== 'n' || c
== 'N' || c
== RUBOUT
)
2563 if (c
== ABORT_CHAR
|| c
< 0)
2565 /* Readline doesn't erase_entire_line here, but without it the
2566 --More-- prompt isn't erased and neither is the text entered
2567 thus far redisplayed. */
2568 displayer
->erase_entire_line (displayer
);
2569 /* Note: The arguments to rl_abort are ignored. */
2572 if (for_pager
&& (c
== NEWLINE
|| c
== RETURN
))
2574 if (for_pager
&& (c
== 'q' || c
== 'Q'))
2576 displayer
->beep (displayer
);
2580 /* Pager function for tab-completion.
2581 This is based on readline/complete.c:_rl_internal_pager.
2582 LINES is the number of lines of output displayed thus far.
2584 -1 -> user pressed 'n' or equivalent,
2585 0 -> user pressed 'y' or equivalent,
2586 N -> user pressed NEWLINE or equivalent and N is LINES - 1. */
2589 gdb_display_match_list_pager (int lines
,
2590 const struct match_list_displayer
*displayer
)
2594 displayer
->puts (displayer
, "--More--");
2595 displayer
->flush (displayer
);
2596 i
= gdb_get_y_or_n (1, displayer
);
2597 displayer
->erase_entire_line (displayer
);
2606 /* Return non-zero if FILENAME is a directory.
2607 Based on readline/complete.c:path_isdir. */
2610 gdb_path_isdir (const char *filename
)
2614 return (stat (filename
, &finfo
) == 0 && S_ISDIR (finfo
.st_mode
));
2617 /* Return the portion of PATHNAME that should be output when listing
2618 possible completions. If we are hacking filename completion, we
2619 are only interested in the basename, the portion following the
2620 final slash. Otherwise, we return what we were passed. Since
2621 printing empty strings is not very informative, if we're doing
2622 filename completion, and the basename is the empty string, we look
2623 for the previous slash and return the portion following that. If
2624 there's no previous slash, we just return what we were passed.
2626 Based on readline/complete.c:printable_part. */
2629 gdb_printable_part (char *pathname
)
2633 if (rl_filename_completion_desired
== 0) /* don't need to do anything */
2636 temp
= strrchr (pathname
, '/');
2637 #if defined (__MSDOS__)
2638 if (temp
== 0 && ISALPHA ((unsigned char)pathname
[0]) && pathname
[1] == ':')
2639 temp
= pathname
+ 1;
2642 if (temp
== 0 || *temp
== '\0')
2644 /* If the basename is NULL, we might have a pathname like '/usr/src/'.
2645 Look for a previous slash and, if one is found, return the portion
2646 following that slash. If there's no previous slash, just return the
2647 pathname we were passed. */
2648 else if (temp
[1] == '\0')
2650 for (x
= temp
- 1; x
> pathname
; x
--)
2653 return ((*x
== '/') ? x
+ 1 : pathname
);
2659 /* Compute width of STRING when displayed on screen by print_filename.
2660 Based on readline/complete.c:fnwidth. */
2663 gdb_fnwidth (const char *string
)
2666 #if defined (HANDLE_MULTIBYTE)
2672 left
= strlen (string
) + 1;
2673 memset (&ps
, 0, sizeof (mbstate_t));
2679 if (CTRL_CHAR (string
[pos
]) || string
[pos
] == RUBOUT
)
2686 #if defined (HANDLE_MULTIBYTE)
2687 clen
= mbrtowc (&wc
, string
+ pos
, left
- pos
, &ps
);
2688 if (MB_INVALIDCH (clen
))
2692 memset (&ps
, 0, sizeof (mbstate_t));
2694 else if (MB_NULLWCH (clen
))
2700 width
+= (w
>= 0) ? w
: 1;
2712 /* Print TO_PRINT, one matching completion.
2713 PREFIX_BYTES is number of common prefix bytes.
2714 Based on readline/complete.c:fnprint. */
2717 gdb_fnprint (const char *to_print
, int prefix_bytes
,
2718 const struct match_list_displayer
*displayer
)
2722 #if defined (HANDLE_MULTIBYTE)
2729 end
= to_print
+ strlen (to_print
) + 1;
2730 memset (&ps
, 0, sizeof (mbstate_t));
2735 /* Don't print only the ellipsis if the common prefix is one of the
2736 possible completions */
2737 if (to_print
[prefix_bytes
] == '\0')
2744 ellipsis
= (to_print
[prefix_bytes
] == '.') ? '_' : '.';
2745 for (w
= 0; w
< ELLIPSIS_LEN
; w
++)
2746 displayer
->putch (displayer
, ellipsis
);
2747 printed_len
= ELLIPSIS_LEN
;
2750 s
= to_print
+ prefix_bytes
;
2755 displayer
->putch (displayer
, '^');
2756 displayer
->putch (displayer
, UNCTRL (*s
));
2759 #if defined (HANDLE_MULTIBYTE)
2760 memset (&ps
, 0, sizeof (mbstate_t));
2763 else if (*s
== RUBOUT
)
2765 displayer
->putch (displayer
, '^');
2766 displayer
->putch (displayer
, '?');
2769 #if defined (HANDLE_MULTIBYTE)
2770 memset (&ps
, 0, sizeof (mbstate_t));
2775 #if defined (HANDLE_MULTIBYTE)
2776 tlen
= mbrtowc (&wc
, s
, end
- s
, &ps
);
2777 if (MB_INVALIDCH (tlen
))
2781 memset (&ps
, 0, sizeof (mbstate_t));
2783 else if (MB_NULLWCH (tlen
))
2788 width
= (w
>= 0) ? w
: 1;
2790 for (w
= 0; w
< tlen
; ++w
)
2791 displayer
->putch (displayer
, s
[w
]);
2793 printed_len
+= width
;
2795 displayer
->putch (displayer
, *s
);
2805 /* Output TO_PRINT to rl_outstream. If VISIBLE_STATS is defined and we
2806 are using it, check for and output a single character for `special'
2807 filenames. Return the number of characters we output.
2808 Based on readline/complete.c:print_filename. */
2811 gdb_print_filename (char *to_print
, char *full_pathname
, int prefix_bytes
,
2812 const struct match_list_displayer
*displayer
)
2814 int printed_len
, extension_char
, slen
, tlen
;
2815 char *s
, c
, *new_full_pathname
;
2817 extern int _rl_complete_mark_directories
;
2820 printed_len
= gdb_fnprint (to_print
, prefix_bytes
, displayer
);
2822 #if defined (VISIBLE_STATS)
2823 if (rl_filename_completion_desired
&& (rl_visible_stats
|| _rl_complete_mark_directories
))
2825 if (rl_filename_completion_desired
&& _rl_complete_mark_directories
)
2828 /* If to_print != full_pathname, to_print is the basename of the
2829 path passed. In this case, we try to expand the directory
2830 name before checking for the stat character. */
2831 if (to_print
!= full_pathname
)
2833 /* Terminate the directory name. */
2835 to_print
[-1] = '\0';
2837 /* If setting the last slash in full_pathname to a NUL results in
2838 full_pathname being the empty string, we are trying to complete
2839 files in the root directory. If we pass a null string to the
2840 bash directory completion hook, for example, it will expand it
2841 to the current directory. We just want the `/'. */
2842 if (full_pathname
== 0 || *full_pathname
== 0)
2844 else if (full_pathname
[0] != '/')
2846 else if (full_pathname
[1] == 0)
2847 dn
= "//"; /* restore trailing slash to `//' */
2848 else if (full_pathname
[1] == '/' && full_pathname
[2] == 0)
2849 dn
= "/"; /* don't turn /// into // */
2852 s
= tilde_expand (dn
);
2853 if (rl_directory_completion_hook
)
2854 (*rl_directory_completion_hook
) (&s
);
2857 tlen
= strlen (to_print
);
2858 new_full_pathname
= (char *)xmalloc (slen
+ tlen
+ 2);
2859 strcpy (new_full_pathname
, s
);
2860 if (s
[slen
- 1] == '/')
2863 new_full_pathname
[slen
] = '/';
2864 new_full_pathname
[slen
] = '/';
2865 strcpy (new_full_pathname
+ slen
+ 1, to_print
);
2867 #if defined (VISIBLE_STATS)
2868 if (rl_visible_stats
)
2869 extension_char
= stat_char (new_full_pathname
);
2872 if (gdb_path_isdir (new_full_pathname
))
2873 extension_char
= '/';
2875 xfree (new_full_pathname
);
2880 s
= tilde_expand (full_pathname
);
2881 #if defined (VISIBLE_STATS)
2882 if (rl_visible_stats
)
2883 extension_char
= stat_char (s
);
2886 if (gdb_path_isdir (s
))
2887 extension_char
= '/';
2893 displayer
->putch (displayer
, extension_char
);
2901 /* GDB version of readline/complete.c:complete_get_screenwidth. */
2904 gdb_complete_get_screenwidth (const struct match_list_displayer
*displayer
)
2906 /* Readline has other stuff here which it's not clear we need. */
2907 return displayer
->width
;
2910 extern int _rl_completion_prefix_display_length
;
2911 extern int _rl_print_completions_horizontally
;
2913 EXTERN_C
int _rl_qsort_string_compare (const void *, const void *);
2914 typedef int QSFUNC (const void *, const void *);
2916 /* GDB version of readline/complete.c:rl_display_match_list.
2917 See gdb_display_match_list for a description of MATCHES, LEN, MAX.
2918 Returns non-zero if all matches are displayed. */
2921 gdb_display_match_list_1 (char **matches
, int len
, int max
,
2922 const struct match_list_displayer
*displayer
)
2924 int count
, limit
, printed_len
, lines
, cols
;
2925 int i
, j
, k
, l
, common_length
, sind
;
2927 int page_completions
= displayer
->height
!= INT_MAX
&& pagination_enabled
;
2929 /* Find the length of the prefix common to all items: length as displayed
2930 characters (common_length) and as a byte index into the matches (sind) */
2931 common_length
= sind
= 0;
2932 if (_rl_completion_prefix_display_length
> 0)
2934 t
= gdb_printable_part (matches
[0]);
2935 temp
= strrchr (t
, '/');
2936 common_length
= temp
? gdb_fnwidth (temp
) : gdb_fnwidth (t
);
2937 sind
= temp
? strlen (temp
) : strlen (t
);
2939 if (common_length
> _rl_completion_prefix_display_length
&& common_length
> ELLIPSIS_LEN
)
2940 max
-= common_length
- ELLIPSIS_LEN
;
2942 common_length
= sind
= 0;
2945 /* How many items of MAX length can we fit in the screen window? */
2946 cols
= gdb_complete_get_screenwidth (displayer
);
2949 if (limit
!= 1 && (limit
* max
== cols
))
2952 /* If cols == 0, limit will end up -1 */
2953 if (cols
< displayer
->width
&& limit
< 0)
2956 /* Avoid a possible floating exception. If max > cols,
2957 limit will be 0 and a divide-by-zero fault will result. */
2961 /* How many iterations of the printing loop? */
2962 count
= (len
+ (limit
- 1)) / limit
;
2964 /* Watch out for special case. If LEN is less than LIMIT, then
2965 just do the inner printing loop.
2966 0 < len <= limit implies count = 1. */
2968 /* Sort the items if they are not already sorted. */
2969 if (rl_ignore_completion_duplicates
== 0 && rl_sort_completion_matches
)
2970 qsort (matches
+ 1, len
, sizeof (char *), (QSFUNC
*)_rl_qsort_string_compare
);
2972 displayer
->crlf (displayer
);
2975 if (_rl_print_completions_horizontally
== 0)
2977 /* Print the sorted items, up-and-down alphabetically, like ls. */
2978 for (i
= 1; i
<= count
; i
++)
2980 for (j
= 0, l
= i
; j
< limit
; j
++)
2982 if (l
> len
|| matches
[l
] == 0)
2986 temp
= gdb_printable_part (matches
[l
]);
2987 printed_len
= gdb_print_filename (temp
, matches
[l
], sind
,
2991 for (k
= 0; k
< max
- printed_len
; k
++)
2992 displayer
->putch (displayer
, ' ');
2996 displayer
->crlf (displayer
);
2998 if (page_completions
&& lines
>= (displayer
->height
- 1) && i
< count
)
3000 lines
= gdb_display_match_list_pager (lines
, displayer
);
3008 /* Print the sorted items, across alphabetically, like ls -x. */
3009 for (i
= 1; matches
[i
]; i
++)
3011 temp
= gdb_printable_part (matches
[i
]);
3012 printed_len
= gdb_print_filename (temp
, matches
[i
], sind
, displayer
);
3013 /* Have we reached the end of this line? */
3016 if (i
&& (limit
> 1) && (i
% limit
) == 0)
3018 displayer
->crlf (displayer
);
3020 if (page_completions
&& lines
>= displayer
->height
- 1)
3022 lines
= gdb_display_match_list_pager (lines
, displayer
);
3028 for (k
= 0; k
< max
- printed_len
; k
++)
3029 displayer
->putch (displayer
, ' ');
3032 displayer
->crlf (displayer
);
3038 /* Utility for displaying completion list matches, used by both CLI and TUI.
3040 MATCHES is the list of strings, in argv format, LEN is the number of
3041 strings in MATCHES, and MAX is the length of the longest string in
3045 gdb_display_match_list (char **matches
, int len
, int max
,
3046 const struct match_list_displayer
*displayer
)
3048 /* Readline will never call this if complete_line returned NULL. */
3049 gdb_assert (max_completions
!= 0);
3051 /* complete_line will never return more than this. */
3052 if (max_completions
> 0)
3053 gdb_assert (len
<= max_completions
);
3055 if (rl_completion_query_items
> 0 && len
>= rl_completion_query_items
)
3059 /* We can't use *query here because they wait for <RET> which is
3060 wrong here. This follows the readline version as closely as possible
3061 for compatibility's sake. See readline/complete.c. */
3063 displayer
->crlf (displayer
);
3065 xsnprintf (msg
, sizeof (msg
),
3066 "Display all %d possibilities? (y or n)", len
);
3067 displayer
->puts (displayer
, msg
);
3068 displayer
->flush (displayer
);
3070 if (gdb_get_y_or_n (0, displayer
) == 0)
3072 displayer
->crlf (displayer
);
3077 if (gdb_display_match_list_1 (matches
, len
, max
, displayer
))
3079 /* Note: MAX_COMPLETIONS may be -1 or zero, but LEN is always > 0. */
3080 if (len
== max_completions
)
3082 /* The maximum number of completions has been reached. Warn the user
3083 that there may be more. */
3084 const char *message
= get_max_completions_reached_message ();
3086 displayer
->puts (displayer
, message
);
3087 displayer
->crlf (displayer
);
3092 void _initialize_completer ();
3094 _initialize_completer ()
3096 add_setshow_zuinteger_unlimited_cmd ("max-completions", no_class
,
3097 &max_completions
, _("\
3098 Set maximum number of completion candidates."), _("\
3099 Show maximum number of completion candidates."), _("\
3100 Use this to limit the number of candidates considered\n\
3101 during completion. Specifying \"unlimited\" or -1\n\
3102 disables limiting. Note that setting either no limit or\n\
3103 a very large limit can make completion slow."),
3104 NULL
, NULL
, &setlist
, &showlist
);