1 /* Line completion stuff for GDB, the GNU debugger.
2 Copyright (C) 2000-2017 Free Software Foundation, Inc.
4 This file is part of GDB.
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>. */
22 #include "expression.h"
23 #include "filenames.h" /* For DOSish file names. */
25 #include "gdb_signals.h"
27 #include "reggroups.h"
28 #include "user-regs.h"
29 #include "arch-utils.h"
32 #include "cli/cli-decode.h"
34 /* FIXME: This is needed because of lookup_cmd_1 (). We should be
35 calling a hook instead so we eliminate the CLI dependency. */
38 /* Needed for rl_completer_word_break_characters() and for
39 rl_filename_completion_function. */
40 #include "readline/readline.h"
42 /* readline defines this. */
45 #include "completer.h"
47 /* Misc state that needs to be tracked across several different
48 readline completer entry point calls, all related to a single
49 completion invocation. */
51 struct gdb_completer_state
53 /* The current completion's completion tracker. This is a global
54 because a tracker can be shared between the handle_brkchars and
55 handle_completion phases, which involves different readline
57 completion_tracker
*tracker
= NULL
;
59 /* Whether the current completion was aborted. */
63 /* The current completion state. */
64 static gdb_completer_state current_completion
;
66 /* An enumeration of the various things a user might
67 attempt to complete for a location. */
69 enum explicit_location_match_type
71 /* The filename of a source file. */
74 /* The name of a function or method. */
77 /* The name of a label. */
81 /* Prototypes for local functions. */
83 /* readline uses the word breaks for two things:
84 (1) In figuring out where to point the TEXT parameter to the
85 rl_completion_entry_function. Since we don't use TEXT for much,
86 it doesn't matter a lot what the word breaks are for this purpose,
87 but it does affect how much stuff M-? lists.
88 (2) If one of the matches contains a word break character, readline
89 will quote it. That's why we switch between
90 current_language->la_word_break_characters() and
91 gdb_completer_command_word_break_characters. I'm not sure when
92 we need this behavior (perhaps for funky characters in C++
95 /* Variables which are necessary for fancy command line editing. */
97 /* When completing on command names, we remove '-' from the list of
98 word break characters, since we use it in command names. If the
99 readline library sees one in any of the current completion strings,
100 it thinks that the string needs to be quoted and automatically
101 supplies a leading quote. */
102 static const char gdb_completer_command_word_break_characters
[] =
103 " \t\n!@#$%^&*()+=|~`}{[]\"';:?/>.<,";
105 /* When completing on file names, we remove from the list of word
106 break characters any characters that are commonly used in file
107 names, such as '-', '+', '~', etc. Otherwise, readline displays
108 incorrect completion candidates. */
109 /* MS-DOS and MS-Windows use colon as part of the drive spec, and most
110 programs support @foo style response files. */
111 static const char gdb_completer_file_name_break_characters
[] =
112 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
118 /* Characters that can be used to quote completion strings. Note that
119 we can't include '"' because the gdb C parser treats such quoted
120 sequences as strings. */
121 static const char gdb_completer_quote_characters
[] = "'";
123 /* Accessor for some completer data that may interest other files. */
126 get_gdb_completer_quote_characters (void)
128 return gdb_completer_quote_characters
;
131 /* This can be used for functions which don't want to complete on
132 symbols but don't want to complete on anything else either. */
135 noop_completer (struct cmd_list_element
*ignore
,
136 completion_tracker
&tracker
,
137 const char *text
, const char *prefix
)
141 /* Complete on filenames. */
144 filename_completer (struct cmd_list_element
*ignore
,
145 completion_tracker
&tracker
,
146 const char *text
, const char *word
)
149 VEC (char_ptr
) *return_val
= NULL
;
156 p
= rl_filename_completion_function (text
, subsequent_name
);
159 /* We need to set subsequent_name to a non-zero value before the
160 continue line below, because otherwise, if the first file
161 seen by GDB is a backup file whose name ends in a `~', we
162 will loop indefinitely. */
164 /* Like emacs, don't complete on old versions. Especially
165 useful in the "source" command. */
166 if (p
[strlen (p
) - 1] == '~')
173 /* Return exactly p. */
175 else if (word
> text
)
177 /* Return some portion of p. */
178 q
= (char *) xmalloc (strlen (p
) + 5);
179 strcpy (q
, p
+ (word
- text
));
184 /* Return some of TEXT plus p. */
185 q
= (char *) xmalloc (strlen (p
) + (text
- word
) + 5);
186 strncpy (q
, word
, text
- word
);
187 q
[text
- word
] = '\0';
191 tracker
.add_completion (gdb::unique_xmalloc_ptr
<char> (q
));
194 /* There is no way to do this just long enough to affect quote
195 inserting without also affecting the next completion. This
196 should be fixed in readline. FIXME. */
197 /* Ensure that readline does the right thing
198 with respect to inserting quotes. */
199 rl_completer_word_break_characters
= "";
203 /* The corresponding completer_handle_brkchars
207 filename_completer_handle_brkchars (struct cmd_list_element
*ignore
,
208 completion_tracker
&tracker
,
209 const char *text
, const char *word
)
211 set_rl_completer_word_break_characters
212 (gdb_completer_file_name_break_characters
);
215 /* Possible values for the found_quote flags word used by the completion
216 functions. It says what kind of (shell-like) quoting we found anywhere
218 #define RL_QF_SINGLE_QUOTE 0x01
219 #define RL_QF_DOUBLE_QUOTE 0x02
220 #define RL_QF_BACKSLASH 0x04
221 #define RL_QF_OTHER_QUOTE 0x08
223 /* Find the bounds of the current word for completion purposes, and
224 return a pointer to the end of the word. This mimics (and is a
225 modified version of) readline's _rl_find_completion_word internal
228 This function skips quoted substrings (characters between matched
229 pairs of characters in rl_completer_quote_characters). We try to
230 find an unclosed quoted substring on which to do matching. If one
231 is not found, we use the word break characters to find the
232 boundaries of the current word. QC, if non-null, is set to the
233 opening quote character if we found an unclosed quoted substring,
234 '\0' otherwise. DP, if non-null, is set to the value of the
235 delimiter character that caused a word break. */
237 struct gdb_rl_completion_word_info
239 const char *word_break_characters
;
240 const char *quote_characters
;
241 const char *basic_quote_characters
;
245 gdb_rl_find_completion_word (struct gdb_rl_completion_word_info
*info
,
247 const char *line_buffer
)
249 int scan
, end
, found_quote
, delimiter
, pass_next
, isbrk
;
251 const char *brkchars
;
252 int point
= strlen (line_buffer
);
254 /* The algorithm below does '--point'. Avoid buffer underflow with
266 found_quote
= delimiter
= 0;
269 brkchars
= info
->word_break_characters
;
271 if (info
->quote_characters
!= NULL
)
273 /* We have a list of characters which can be used in pairs to
274 quote substrings for the completer. Try to find the start of
275 an unclosed quoted substring. */
276 /* FOUND_QUOTE is set so we know what kind of quotes we
278 for (scan
= pass_next
= 0;
288 /* Shell-like semantics for single quotes -- don't allow
289 backslash to quote anything in single quotes, especially
290 not the closing quote. If you don't like this, take out
291 the check on the value of quote_char. */
292 if (quote_char
!= '\'' && line_buffer
[scan
] == '\\')
295 found_quote
|= RL_QF_BACKSLASH
;
299 if (quote_char
!= '\0')
301 /* Ignore everything until the matching close quote
303 if (line_buffer
[scan
] == quote_char
)
305 /* Found matching close. Abandon this
311 else if (strchr (info
->quote_characters
, line_buffer
[scan
]))
313 /* Found start of a quoted substring. */
314 quote_char
= line_buffer
[scan
];
316 /* Shell-like quoting conventions. */
317 if (quote_char
== '\'')
318 found_quote
|= RL_QF_SINGLE_QUOTE
;
319 else if (quote_char
== '"')
320 found_quote
|= RL_QF_DOUBLE_QUOTE
;
322 found_quote
|= RL_QF_OTHER_QUOTE
;
327 if (point
== end
&& quote_char
== '\0')
329 /* We didn't find an unclosed quoted substring upon which to do
330 completion, so use the word break characters to find the
331 substring on which to complete. */
334 scan
= line_buffer
[point
];
336 if (strchr (brkchars
, scan
) != 0)
341 /* If we are at an unquoted word break, then advance past it. */
342 scan
= line_buffer
[point
];
346 isbrk
= strchr (brkchars
, scan
) != 0;
350 /* If the character that caused the word break was a quoting
351 character, then remember it as the delimiter. */
352 if (info
->basic_quote_characters
353 && strchr (info
->basic_quote_characters
, scan
)
354 && (end
- point
) > 1)
366 return line_buffer
+ point
;
369 /* Complete on linespecs, which might be of two possible forms:
375 This is intended to be used in commands that set breakpoints
379 complete_files_symbols (completion_tracker
&tracker
,
380 const char *text
, const char *word
)
383 completion_list fn_list
;
386 int quoted
= *text
== '\'' || *text
== '"';
387 int quote_char
= '\0';
388 const char *colon
= NULL
;
389 char *file_to_match
= NULL
;
390 const char *symbol_start
= text
;
391 const char *orig_text
= text
;
393 /* Do we have an unquoted colon, as in "break foo.c:bar"? */
394 for (p
= text
; *p
!= '\0'; ++p
)
396 if (*p
== '\\' && p
[1] == '\'')
398 else if (*p
== '\'' || *p
== '"')
402 while (*p
!= '\0' && *p
!= quote_found
)
404 if (*p
== '\\' && p
[1] == quote_found
)
409 if (*p
== quote_found
)
412 break; /* Hit the end of text. */
414 #if HAVE_DOS_BASED_FILE_SYSTEM
415 /* If we have a DOS-style absolute file name at the beginning of
416 TEXT, and the colon after the drive letter is the only colon
417 we found, pretend the colon is not there. */
418 else if (p
< text
+ 3 && *p
== ':' && p
== text
+ 1 + quoted
)
421 else if (*p
== ':' && !colon
)
424 symbol_start
= p
+ 1;
426 else if (strchr (current_language
->la_word_break_characters(), *p
))
427 symbol_start
= p
+ 1;
433 /* Where is the file name? */
438 file_to_match
= (char *) xmalloc (colon
- text
+ 1);
439 strncpy (file_to_match
, text
, colon
- text
);
440 file_to_match
[colon
- text
] = '\0';
441 /* Remove trailing colons and quotes from the file name. */
442 for (s
= file_to_match
+ (colon
- text
);
445 if (*s
== ':' || *s
== quote_char
)
448 /* If the text includes a colon, they want completion only on a
449 symbol name after the colon. Otherwise, we need to complete on
450 symbols as well as on files. */
453 collect_file_symbol_completion_matches (tracker
, symbol_start
, word
,
455 xfree (file_to_match
);
459 size_t text_len
= strlen (text
);
461 collect_symbol_completion_matches (tracker
, symbol_start
, word
);
462 /* If text includes characters which cannot appear in a file
463 name, they cannot be asking for completion on files. */
465 gdb_completer_file_name_break_characters
) == text_len
)
466 fn_list
= make_source_files_completion_list (text
, text
);
469 if (!fn_list
.empty () && !tracker
.have_completions ())
473 /* If we only have file names as possible completion, we should
474 bring them in sync with what rl_complete expects. The
475 problem is that if the user types "break /foo/b TAB", and the
476 possible completions are "/foo/bar" and "/foo/baz"
477 rl_complete expects us to return "bar" and "baz", without the
478 leading directories, as possible completions, because `word'
479 starts at the "b". But we ignore the value of `word' when we
480 call make_source_files_completion_list above (because that
481 would not DTRT when the completion results in both symbols
482 and file names), so make_source_files_completion_list returns
483 the full "/foo/bar" and "/foo/baz" strings. This produces
484 wrong results when, e.g., there's only one possible
485 completion, because rl_complete will prepend "/foo/" to each
486 candidate completion. The loop below removes that leading
488 for (const auto &fn_up
: fn_list
)
490 char *fn
= fn_up
.get ();
491 memmove (fn
, fn
+ (word
- text
), strlen (fn
) + 1 - (word
- text
));
495 tracker
.add_completions (std::move (fn_list
));
497 if (!tracker
.have_completions ())
499 /* No completions at all. As the final resort, try completing
500 on the entire text as a symbol. */
501 collect_symbol_completion_matches (tracker
,
506 /* Returns STRING if not NULL, the empty string otherwise. */
509 string_or_empty (const char *string
)
511 return string
!= NULL
? string
: "";
514 /* A helper function to collect explicit location matches for the given
515 LOCATION, which is attempting to match on WORD. */
518 collect_explicit_location_matches (completion_tracker
&tracker
,
519 struct event_location
*location
,
520 enum explicit_location_match_type what
,
523 const struct explicit_location
*explicit_loc
524 = get_explicit_location (location
);
530 const char *source
= string_or_empty (explicit_loc
->source_filename
);
531 completion_list matches
532 = make_source_files_completion_list (source
, word
);
533 tracker
.add_completions (std::move (matches
));
539 const char *function
= string_or_empty (explicit_loc
->function_name
);
540 if (explicit_loc
->source_filename
!= NULL
)
542 const char *filename
= explicit_loc
->source_filename
;
544 collect_file_symbol_completion_matches (tracker
,
545 function
, word
, filename
);
548 collect_symbol_completion_matches (tracker
, function
, word
);
557 gdb_assert_not_reached ("unhandled explicit_location_match_type");
561 /* A convenience macro to (safely) back up P to the previous word. */
564 backup_text_ptr (const char *p
, const char *text
)
566 while (p
> text
&& isspace (*p
))
568 for (; p
> text
&& !isspace (p
[-1]); --p
)
574 /* A completer function for explicit locations. This function
575 completes both options ("-source", "-line", etc) and values. */
578 complete_explicit_location (completion_tracker
&tracker
,
579 struct event_location
*location
,
580 const char *text
, const char *word
)
584 /* Find the beginning of the word. This is necessary because
585 we need to know if we are completing an option name or value. We
586 don't get the leading '-' from the completer. */
587 p
= backup_text_ptr (word
, text
);
591 /* Completing on option name. */
592 static const char *const keywords
[] =
601 /* Skip over the '-'. */
604 complete_on_enum (tracker
, keywords
, p
, p
);
609 /* Completing on value (or unknown). Get the previous word to see what
610 the user is completing on. */
612 const char *new_word
, *end
;
613 enum explicit_location_match_type what
;
614 struct explicit_location
*explicit_loc
615 = get_explicit_location (location
);
617 /* Backup P to the previous word, which should be the option
618 the user is attempting to complete. */
621 p
= backup_text_ptr (p
, text
);
624 if (strncmp (p
, "-source", len
) == 0)
627 new_word
= explicit_loc
->source_filename
+ offset
;
629 else if (strncmp (p
, "-function", len
) == 0)
631 what
= MATCH_FUNCTION
;
632 new_word
= explicit_loc
->function_name
+ offset
;
634 else if (strncmp (p
, "-label", len
) == 0)
637 new_word
= explicit_loc
->label_name
+ offset
;
641 /* The user isn't completing on any valid option name,
642 e.g., "break -source foo.c [tab]". */
646 /* If the user hasn't entered a search expression, e.g.,
647 "break -function <TAB><TAB>", new_word will be NULL, but
648 search routines require non-NULL search words. */
649 if (new_word
== NULL
)
652 /* Now gather matches */
653 collect_explicit_location_matches (tracker
, location
, what
, new_word
);
657 /* A completer for locations. */
660 location_completer (struct cmd_list_element
*ignore
,
661 completion_tracker
&tracker
,
662 const char *text
, const char *word
)
664 const char *copy
= text
;
666 event_location_up location
= string_to_explicit_location (©
,
669 if (location
!= NULL
)
670 complete_explicit_location (tracker
, location
.get (),
674 /* This is an address or linespec location.
675 Right now both of these are handled by the (old) linespec
677 complete_files_symbols (tracker
, text
, word
);
681 /* Helper for expression_completer which recursively adds field and
682 method names from TYPE, a struct or union type, to the OUTPUT
686 add_struct_fields (struct type
*type
, completion_list
&output
,
687 char *fieldname
, int namelen
)
690 int computed_type_name
= 0;
691 const char *type_name
= NULL
;
693 type
= check_typedef (type
);
694 for (i
= 0; i
< TYPE_NFIELDS (type
); ++i
)
696 if (i
< TYPE_N_BASECLASSES (type
))
697 add_struct_fields (TYPE_BASECLASS (type
, i
),
698 output
, fieldname
, namelen
);
699 else if (TYPE_FIELD_NAME (type
, i
))
701 if (TYPE_FIELD_NAME (type
, i
)[0] != '\0')
703 if (! strncmp (TYPE_FIELD_NAME (type
, i
),
705 output
.emplace_back (xstrdup (TYPE_FIELD_NAME (type
, i
)));
707 else if (TYPE_CODE (TYPE_FIELD_TYPE (type
, i
)) == TYPE_CODE_UNION
)
709 /* Recurse into anonymous unions. */
710 add_struct_fields (TYPE_FIELD_TYPE (type
, i
),
711 output
, fieldname
, namelen
);
716 for (i
= TYPE_NFN_FIELDS (type
) - 1; i
>= 0; --i
)
718 const char *name
= TYPE_FN_FIELDLIST_NAME (type
, i
);
720 if (name
&& ! strncmp (name
, fieldname
, namelen
))
722 if (!computed_type_name
)
724 type_name
= type_name_no_tag (type
);
725 computed_type_name
= 1;
727 /* Omit constructors from the completion list. */
728 if (!type_name
|| strcmp (type_name
, name
))
729 output
.emplace_back (xstrdup (name
));
734 /* Complete on expressions. Often this means completing on symbol
735 names, but some language parsers also have support for completing
739 complete_expression (completion_tracker
&tracker
,
740 const char *text
, const char *word
)
742 struct type
*type
= NULL
;
744 enum type_code code
= TYPE_CODE_UNDEF
;
746 /* Perform a tentative parse of the expression, to see whether a
747 field completion is required. */
751 type
= parse_expression_for_completion (text
, &fieldname
, &code
);
753 CATCH (except
, RETURN_MASK_ERROR
)
759 if (fieldname
&& type
)
763 type
= check_typedef (type
);
764 if (TYPE_CODE (type
) != TYPE_CODE_PTR
&& !TYPE_IS_REFERENCE (type
))
766 type
= TYPE_TARGET_TYPE (type
);
769 if (TYPE_CODE (type
) == TYPE_CODE_UNION
770 || TYPE_CODE (type
) == TYPE_CODE_STRUCT
)
772 int flen
= strlen (fieldname
);
773 completion_list result
;
775 add_struct_fields (type
, result
, fieldname
, flen
);
777 tracker
.add_completions (std::move (result
));
781 else if (fieldname
&& code
!= TYPE_CODE_UNDEF
)
783 VEC (char_ptr
) *result
;
784 struct cleanup
*cleanup
= make_cleanup (xfree
, fieldname
);
786 collect_symbol_completion_matches_type (tracker
, fieldname
, fieldname
,
788 do_cleanups (cleanup
);
793 complete_files_symbols (tracker
, text
, word
);
796 /* Complete on expressions. Often this means completing on symbol
797 names, but some language parsers also have support for completing
801 expression_completer (struct cmd_list_element
*ignore
,
802 completion_tracker
&tracker
,
803 const char *text
, const char *word
)
805 complete_expression (tracker
, text
, word
);
808 /* See definition in completer.h. */
811 set_rl_completer_word_break_characters (const char *break_chars
)
813 rl_completer_word_break_characters
= (char *) break_chars
;
816 /* See definition in completer.h. */
819 set_gdb_completion_word_break_characters (completer_ftype
*fn
)
821 const char *break_chars
;
823 /* So far we are only interested in differentiating filename
824 completers from everything else. */
825 if (fn
== filename_completer
)
826 break_chars
= gdb_completer_file_name_break_characters
;
828 break_chars
= gdb_completer_command_word_break_characters
;
830 set_rl_completer_word_break_characters (break_chars
);
833 /* Complete on symbols. */
836 symbol_completer (struct cmd_list_element
*ignore
,
837 completion_tracker
&tracker
,
838 const char *text
, const char *word
)
840 collect_symbol_completion_matches (tracker
, text
, word
);
843 /* Here are some useful test cases for completion. FIXME: These
844 should be put in the test suite. They should be tested with both
847 "show output-" "radix"
848 "show output" "-radix"
849 "p" ambiguous (commands starting with p--path, print, printf, etc.)
850 "p " ambiguous (all symbols)
851 "info t foo" no completions
852 "info t " no completions
853 "info t" ambiguous ("info target", "info terminal", etc.)
854 "info ajksdlfk" no completions
855 "info ajksdlfk " no completions
857 "info " ambiguous (all info commands)
858 "p \"a" no completions (string constant)
859 "p 'a" ambiguous (all symbols starting with a)
860 "p b-a" ambiguous (all symbols starting with a)
861 "p b-" ambiguous (all symbols)
862 "file Make" "file" (word break hard to screw up here)
863 "file ../gdb.stabs/we" "ird" (needs to not break word at slash)
866 enum complete_line_internal_reason
868 /* Preliminary phase, called by gdb_completion_word_break_characters
869 function, is used to determine the correct set of chars that are
870 word delimiters depending on the current command in line_buffer.
871 No completion list should be generated; the return value should
872 be NULL. This is checked by an assertion. */
875 /* Main phase, called by complete_line function, is used to get the
876 list of possible completions. */
879 /* Special case when completing a 'help' command. In this case,
880 once sub-command completions are exhausted, we simply return
885 /* Helper for complete_line_internal to simplify it. */
888 complete_line_internal_normal_command (completion_tracker
&tracker
,
889 const char *command
, const char *word
,
890 const char *cmd_args
,
891 complete_line_internal_reason reason
,
892 struct cmd_list_element
*c
)
894 const char *p
= cmd_args
;
896 if (c
->completer
== filename_completer
)
898 /* Many commands which want to complete on file names accept
899 several file names, as in "run foo bar >>baz". So we don't
900 want to complete the entire text after the command, just the
901 last word. To this end, we need to find the beginning of the
902 file name by starting at `word' and going backwards. */
905 && strchr (gdb_completer_file_name_break_characters
,
911 if (reason
== handle_brkchars
)
913 completer_handle_brkchars_ftype
*brkchars_fn
;
915 if (c
->completer_handle_brkchars
!= NULL
)
916 brkchars_fn
= c
->completer_handle_brkchars
;
920 = (completer_handle_brkchars_func_for_completer
924 brkchars_fn (c
, tracker
, p
, word
);
927 if (reason
!= handle_brkchars
&& c
->completer
!= NULL
)
928 (*c
->completer
) (c
, tracker
, p
, word
);
931 /* Internal function used to handle completions.
934 TEXT is the caller's idea of the "word" we are looking at.
936 LINE_BUFFER is available to be looked at; it contains the entire
937 text of the line. POINT is the offset in that line of the cursor.
938 You should pretend that the line ends at POINT.
940 See complete_line_internal_reason for description of REASON. */
943 complete_line_internal_1 (completion_tracker
&tracker
,
945 const char *line_buffer
, int point
,
946 complete_line_internal_reason reason
)
950 int ignore_help_classes
;
951 /* Pointer within tmp_command which corresponds to text. */
953 struct cmd_list_element
*c
, *result_list
;
955 /* Choose the default set of word break characters to break
956 completions. If we later find out that we are doing completions
957 on command strings (as opposed to strings supplied by the
958 individual command completer functions, which can be any string)
959 then we will switch to the special word break set for command
960 strings, which leaves out the '-' character used in some
962 set_rl_completer_word_break_characters
963 (current_language
->la_word_break_characters());
965 /* Decide whether to complete on a list of gdb commands or on
967 tmp_command
= (char *) alloca (point
+ 1);
970 /* The help command should complete help aliases. */
971 ignore_help_classes
= reason
!= handle_help
;
973 strncpy (tmp_command
, line_buffer
, point
);
974 tmp_command
[point
] = '\0';
975 if (reason
== handle_brkchars
)
977 gdb_assert (text
== NULL
);
982 /* Since text always contains some number of characters leading up
983 to point, we can find the equivalent position in tmp_command
984 by subtracting that many characters from the end of tmp_command. */
985 word
= tmp_command
+ point
- strlen (text
);
990 /* An empty line we want to consider ambiguous; that is, it
991 could be any command. */
992 c
= CMD_LIST_AMBIGUOUS
;
997 c
= lookup_cmd_1 (&p
, cmdlist
, &result_list
, ignore_help_classes
);
1000 /* Move p up to the next interesting thing. */
1001 while (*p
== ' ' || *p
== '\t')
1008 /* It is an unrecognized command. So there are no
1009 possible completions. */
1011 else if (c
== CMD_LIST_AMBIGUOUS
)
1015 /* lookup_cmd_1 advances p up to the first ambiguous thing, but
1016 doesn't advance over that thing itself. Do so now. */
1018 while (*q
&& (isalnum (*q
) || *q
== '-' || *q
== '_'))
1020 if (q
!= tmp_command
+ point
)
1022 /* There is something beyond the ambiguous
1023 command, so there are no possible completions. For
1024 example, "info t " or "info t foo" does not complete
1025 to anything, because "info t" can be "info target" or
1030 /* We're trying to complete on the command which was ambiguous.
1031 This we can deal with. */
1034 if (reason
!= handle_brkchars
)
1035 complete_on_cmdlist (*result_list
->prefixlist
, tracker
, p
,
1036 word
, ignore_help_classes
);
1040 if (reason
!= handle_brkchars
)
1041 complete_on_cmdlist (cmdlist
, tracker
, p
, word
,
1042 ignore_help_classes
);
1044 /* Ensure that readline does the right thing with respect to
1045 inserting quotes. */
1046 set_rl_completer_word_break_characters
1047 (gdb_completer_command_word_break_characters
);
1052 /* We've recognized a full command. */
1054 if (p
== tmp_command
+ point
)
1056 /* There is no non-whitespace in the line beyond the
1059 if (p
[-1] == ' ' || p
[-1] == '\t')
1061 /* The command is followed by whitespace; we need to
1062 complete on whatever comes after command. */
1065 /* It is a prefix command; what comes after it is
1066 a subcommand (e.g. "info "). */
1067 if (reason
!= handle_brkchars
)
1068 complete_on_cmdlist (*c
->prefixlist
, tracker
, p
, word
,
1069 ignore_help_classes
);
1071 /* Ensure that readline does the right thing
1072 with respect to inserting quotes. */
1073 set_rl_completer_word_break_characters
1074 (gdb_completer_command_word_break_characters
);
1076 else if (reason
== handle_help
)
1080 if (reason
!= handle_brkchars
)
1081 complete_on_enum (tracker
, c
->enums
, p
, word
);
1082 set_rl_completer_word_break_characters
1083 (gdb_completer_command_word_break_characters
);
1087 /* It is a normal command; what comes after it is
1088 completed by the command's completer function. */
1089 complete_line_internal_normal_command (tracker
,
1090 tmp_command
, word
, p
,
1096 /* The command is not followed by whitespace; we need to
1097 complete on the command itself, e.g. "p" which is a
1098 command itself but also can complete to "print", "ptype"
1102 /* Find the command we are completing on. */
1104 while (q
> tmp_command
)
1106 if (isalnum (q
[-1]) || q
[-1] == '-' || q
[-1] == '_')
1112 if (reason
!= handle_brkchars
)
1113 complete_on_cmdlist (result_list
, tracker
, q
, word
,
1114 ignore_help_classes
);
1116 /* Ensure that readline does the right thing
1117 with respect to inserting quotes. */
1118 set_rl_completer_word_break_characters
1119 (gdb_completer_command_word_break_characters
);
1122 else if (reason
== handle_help
)
1126 /* There is non-whitespace beyond the command. */
1128 if (c
->prefixlist
&& !c
->allow_unknown
)
1130 /* It is an unrecognized subcommand of a prefix command,
1131 e.g. "info adsfkdj". */
1135 if (reason
!= handle_brkchars
)
1136 complete_on_enum (tracker
, c
->enums
, p
, word
);
1140 /* It is a normal command. */
1141 complete_line_internal_normal_command (tracker
,
1142 tmp_command
, word
, p
,
1149 /* Wrapper around complete_line_internal_1 to handle
1150 MAX_COMPLETIONS_REACHED_ERROR. */
1153 complete_line_internal (completion_tracker
&tracker
,
1155 const char *line_buffer
, int point
,
1156 complete_line_internal_reason reason
)
1160 complete_line_internal_1 (tracker
, text
, line_buffer
, point
, reason
);
1162 CATCH (except
, RETURN_MASK_ERROR
)
1164 if (except
.error
!= MAX_COMPLETIONS_REACHED_ERROR
)
1165 throw_exception (except
);
1169 /* See completer.h. */
1171 int max_completions
= 200;
1173 /* Initial size of the table. It automagically grows from here. */
1174 #define INITIAL_COMPLETION_HTAB_SIZE 200
1176 /* See completer.h. */
1178 completion_tracker::completion_tracker ()
1180 m_entries_hash
= htab_create_alloc (INITIAL_COMPLETION_HTAB_SIZE
,
1181 htab_hash_string
, (htab_eq
) streq
,
1182 NULL
, xcalloc
, xfree
);
1185 /* See completer.h. */
1187 completion_tracker::~completion_tracker ()
1189 xfree (m_lowest_common_denominator
);
1190 htab_delete (m_entries_hash
);
1193 /* See completer.h. */
1196 completion_tracker::maybe_add_completion (gdb::unique_xmalloc_ptr
<char> name
)
1200 if (max_completions
== 0)
1203 if (htab_elements (m_entries_hash
) >= max_completions
)
1206 slot
= htab_find_slot (m_entries_hash
, name
.get (), INSERT
);
1207 if (*slot
== HTAB_EMPTY_ENTRY
)
1209 const char *match_for_lcd_str
= name
.get ();
1211 recompute_lowest_common_denominator (match_for_lcd_str
);
1213 *slot
= name
.get ();
1214 m_entries_vec
.push_back (std::move (name
));
1220 /* See completer.h. */
1223 completion_tracker::add_completion (gdb::unique_xmalloc_ptr
<char> name
)
1225 if (!maybe_add_completion (std::move (name
)))
1226 throw_error (MAX_COMPLETIONS_REACHED_ERROR
, _("Max completions reached."));
1229 /* See completer.h. */
1232 completion_tracker::add_completions (completion_list
&&list
)
1234 for (auto &candidate
: list
)
1235 add_completion (std::move (candidate
));
1238 /* Generate completions all at once. Does nothing if max_completions
1239 is 0. If max_completions is non-negative, this will collect at
1240 most max_completions strings.
1242 TEXT is the caller's idea of the "word" we are looking at.
1244 LINE_BUFFER is available to be looked at; it contains the entire
1247 POINT is the offset in that line of the cursor. You
1248 should pretend that the line ends at POINT. */
1251 complete_line (completion_tracker
&tracker
,
1252 const char *text
, const char *line_buffer
, int point
)
1254 if (max_completions
== 0)
1256 complete_line_internal (tracker
, text
, line_buffer
, point
,
1257 handle_completions
);
1260 /* Complete on command names. Used by "help". */
1263 command_completer (struct cmd_list_element
*ignore
,
1264 completion_tracker
&tracker
,
1265 const char *text
, const char *word
)
1267 complete_line_internal (tracker
, word
, text
,
1268 strlen (text
), handle_help
);
1271 /* The corresponding completer_handle_brkchars implementation. */
1274 command_completer_handle_brkchars (struct cmd_list_element
*ignore
,
1275 completion_tracker
&tracker
,
1276 const char *text
, const char *word
)
1278 set_rl_completer_word_break_characters
1279 (gdb_completer_command_word_break_characters
);
1282 /* Complete on signals. */
1285 signal_completer (struct cmd_list_element
*ignore
,
1286 completion_tracker
&tracker
,
1287 const char *text
, const char *word
)
1289 size_t len
= strlen (word
);
1291 const char *signame
;
1293 for (signum
= GDB_SIGNAL_FIRST
; signum
!= GDB_SIGNAL_LAST
; ++signum
)
1295 /* Can't handle this, so skip it. */
1296 if (signum
== GDB_SIGNAL_0
)
1299 signame
= gdb_signal_to_name ((enum gdb_signal
) signum
);
1301 /* Ignore the unknown signal case. */
1302 if (!signame
|| strcmp (signame
, "?") == 0)
1305 if (strncasecmp (signame
, word
, len
) == 0)
1307 gdb::unique_xmalloc_ptr
<char> copy (xstrdup (signame
));
1308 tracker
.add_completion (std::move (copy
));
1313 /* Bit-flags for selecting what the register and/or register-group
1314 completer should complete on. */
1316 enum reg_completer_target
1318 complete_register_names
= 0x1,
1319 complete_reggroup_names
= 0x2
1321 DEF_ENUM_FLAGS_TYPE (enum reg_completer_target
, reg_completer_targets
);
1323 /* Complete register names and/or reggroup names based on the value passed
1324 in TARGETS. At least one bit in TARGETS must be set. */
1327 reg_or_group_completer_1 (completion_tracker
&tracker
,
1328 const char *text
, const char *word
,
1329 reg_completer_targets targets
)
1331 size_t len
= strlen (word
);
1332 struct gdbarch
*gdbarch
;
1335 gdb_assert ((targets
& (complete_register_names
1336 | complete_reggroup_names
)) != 0);
1337 gdbarch
= get_current_arch ();
1339 if ((targets
& complete_register_names
) != 0)
1344 (name
= user_reg_map_regnum_to_name (gdbarch
, i
)) != NULL
;
1347 if (*name
!= '\0' && strncmp (word
, name
, len
) == 0)
1349 gdb::unique_xmalloc_ptr
<char> copy (xstrdup (name
));
1350 tracker
.add_completion (std::move (copy
));
1355 if ((targets
& complete_reggroup_names
) != 0)
1357 struct reggroup
*group
;
1359 for (group
= reggroup_next (gdbarch
, NULL
);
1361 group
= reggroup_next (gdbarch
, group
))
1363 name
= reggroup_name (group
);
1364 if (strncmp (word
, name
, len
) == 0)
1366 gdb::unique_xmalloc_ptr
<char> copy (xstrdup (name
));
1367 tracker
.add_completion (std::move (copy
));
1373 /* Perform completion on register and reggroup names. */
1376 reg_or_group_completer (struct cmd_list_element
*ignore
,
1377 completion_tracker
&tracker
,
1378 const char *text
, const char *word
)
1380 reg_or_group_completer_1 (tracker
, text
, word
,
1381 (complete_register_names
1382 | complete_reggroup_names
));
1385 /* Perform completion on reggroup names. */
1388 reggroup_completer (struct cmd_list_element
*ignore
,
1389 completion_tracker
&tracker
,
1390 const char *text
, const char *word
)
1392 reg_or_group_completer_1 (tracker
, text
, word
,
1393 complete_reggroup_names
);
1396 /* The default completer_handle_brkchars implementation. */
1399 default_completer_handle_brkchars (struct cmd_list_element
*ignore
,
1400 completion_tracker
&tracker
,
1401 const char *text
, const char *word
)
1403 set_rl_completer_word_break_characters
1404 (current_language
->la_word_break_characters ());
1407 /* See definition in completer.h. */
1409 completer_handle_brkchars_ftype
*
1410 completer_handle_brkchars_func_for_completer (completer_ftype
*fn
)
1412 if (fn
== filename_completer
)
1413 return filename_completer_handle_brkchars
;
1415 if (fn
== command_completer
)
1416 return command_completer_handle_brkchars
;
1418 return default_completer_handle_brkchars
;
1421 /* Get the list of chars that are considered as word breaks
1422 for the current command. */
1425 gdb_completion_word_break_characters_throw ()
1427 /* New completion starting. Get rid of the previous tracker and
1429 delete current_completion
.tracker
;
1430 current_completion
.tracker
= new completion_tracker ();
1432 completion_tracker
&tracker
= *current_completion
.tracker
;
1434 complete_line_internal (tracker
, NULL
, rl_line_buffer
,
1435 rl_point
, handle_brkchars
);
1437 return rl_completer_word_break_characters
;
1441 gdb_completion_word_break_characters ()
1443 /* New completion starting. */
1444 current_completion
.aborted
= false;
1448 return gdb_completion_word_break_characters_throw ();
1450 CATCH (ex
, RETURN_MASK_ALL
)
1452 /* Set this to that gdb_rl_attempted_completion_function knows
1454 current_completion
.aborted
= true;
1461 /* See completer.h. */
1464 completion_find_completion_word (completion_tracker
&tracker
, const char *text
,
1467 size_t point
= strlen (text
);
1469 complete_line_internal (tracker
, NULL
, text
, point
, handle_brkchars
);
1471 gdb_rl_completion_word_info info
;
1473 info
.word_break_characters
= rl_completer_word_break_characters
;
1474 info
.quote_characters
= gdb_completer_quote_characters
;
1475 info
.basic_quote_characters
= rl_basic_quote_characters
;
1477 return gdb_rl_find_completion_word (&info
, quote_char
, NULL
, text
);
1480 /* See completer.h. */
1483 completion_tracker::recompute_lowest_common_denominator (const char *new_match
)
1485 if (m_lowest_common_denominator
== NULL
)
1487 /* We don't have a lowest common denominator yet, so simply take
1488 the whole NEW_MATCH as being it. */
1489 m_lowest_common_denominator
= xstrdup (new_match
);
1490 m_lowest_common_denominator_unique
= true;
1494 /* Find the common denominator between the currently-known
1495 lowest common denominator and NEW_MATCH. That becomes the
1496 new lowest common denominator. */
1500 (new_match
[i
] != '\0'
1501 && new_match
[i
] == m_lowest_common_denominator
[i
]);
1504 if (m_lowest_common_denominator
[i
] != new_match
[i
])
1506 m_lowest_common_denominator
[i
] = '\0';
1507 m_lowest_common_denominator_unique
= false;
1512 /* Build a new C string that is a copy of LCD with the whitespace of
1513 ORIG/ORIG_LEN preserved.
1515 Say the user is completing a symbol name, with spaces, like:
1519 and the resulting completion match is:
1523 we want to end up with an input line like:
1526 ^^^^^^^ => text from LCD [1], whitespace from ORIG preserved.
1527 ^^ => new text from LCD
1529 [1] - We must take characters from the LCD instead of the original
1530 text, since some completions want to change upper/lowercase. E.g.:
1536 "handle SIG[QUIT|etc.]"
1540 expand_preserving_ws (const char *orig
, size_t orig_len
,
1543 const char *p_orig
= orig
;
1544 const char *orig_end
= orig
+ orig_len
;
1545 const char *p_lcd
= lcd
;
1548 while (p_orig
< orig_end
)
1552 while (p_orig
< orig_end
&& *p_orig
== ' ')
1554 p_lcd
= skip_spaces_const (p_lcd
);
1558 /* Take characters from the LCD instead of the original
1559 text, since some completions change upper/lowercase.
1563 "handle SIG[QUIT|etc.]"
1571 while (*p_lcd
!= '\0')
1574 return xstrdup (res
.c_str ());
1577 /* See completer.h. */
1580 completion_tracker::build_completion_result (const char *text
,
1583 completion_list
&list
= m_entries_vec
; /* The completions. */
1588 /* +1 for the LCD, and +1 for NULL termination. */
1589 char **match_list
= XNEWVEC (char *, 1 + list
.size () + 1);
1591 /* Build replacement word, based on the LCD. */
1594 = expand_preserving_ws (text
, end
- start
,
1595 m_lowest_common_denominator
);
1597 if (m_lowest_common_denominator_unique
)
1599 match_list
[1] = NULL
;
1601 /* If we already have a space at the end of the match, tell
1602 readline to skip appending another. */
1603 bool completion_suppress_append
1604 = (match_list
[0][strlen (match_list
[0]) - 1] == ' ');
1606 return completion_result (match_list
, 1, completion_suppress_append
);
1612 for (ix
= 0; ix
< list
.size (); ++ix
)
1613 match_list
[ix
+ 1] = list
[ix
].release ();
1614 match_list
[ix
+ 1] = NULL
;
1616 return completion_result (match_list
, list
.size (), false);
1620 /* See completer.h */
1622 completion_result::completion_result ()
1623 : match_list (NULL
), number_matches (0),
1624 completion_suppress_append (false)
1627 /* See completer.h */
1629 completion_result::completion_result (char **match_list_
,
1630 size_t number_matches_
,
1631 bool completion_suppress_append_
)
1632 : match_list (match_list_
),
1633 number_matches (number_matches_
),
1634 completion_suppress_append (completion_suppress_append_
)
1637 /* See completer.h */
1639 completion_result::~completion_result ()
1641 reset_match_list ();
1644 /* See completer.h */
1646 completion_result::completion_result (completion_result
&&rhs
)
1651 reset_match_list ();
1652 match_list
= rhs
.match_list
;
1653 rhs
.match_list
= NULL
;
1654 number_matches
= rhs
.number_matches
;
1655 rhs
.number_matches
= 0;
1658 /* See completer.h */
1661 completion_result::release_match_list ()
1663 char **ret
= match_list
;
1668 /* Compare C strings for std::sort. */
1671 compare_cstrings (const char *str1
, const char *str2
)
1673 return strcmp (str1
, str2
) < 0;
1676 /* See completer.h */
1679 completion_result::sort_match_list ()
1681 if (number_matches
> 1)
1683 /* Element 0 is special (it's the common prefix), leave it
1685 std::sort (&match_list
[1],
1686 &match_list
[number_matches
+ 1],
1691 /* See completer.h */
1694 completion_result::reset_match_list ()
1696 if (match_list
!= NULL
)
1698 for (char **p
= match_list
; *p
!= NULL
; p
++)
1705 /* Helper for gdb_rl_attempted_completion_function, which does most of
1706 the work. This is called by readline to build the match list array
1707 and to determine the lowest common denominator. The real matches
1708 list starts at match[1], while match[0] is the slot holding
1709 readline's idea of the lowest common denominator of all matches,
1710 which is what readline replaces the completion "word" with.
1712 TEXT is the caller's idea of the "word" we are looking at, as
1713 computed in the handle_brkchars phase.
1715 START is the offset from RL_LINE_BUFFER where TEXT starts. END is
1716 the offset from RL_LINE_BUFFER where TEXT ends (i.e., where
1719 You should thus pretend that the line ends at END (relative to
1722 RL_LINE_BUFFER contains the entire text of the line. RL_POINT is
1723 the offset in that line of the cursor. You should pretend that the
1726 Returns NULL if there are no completions. */
1729 gdb_rl_attempted_completion_function_throw (const char *text
, int start
, int end
)
1731 /* Completers must be called twice. If rl_point (i.e., END) is at
1732 column 0, then readline skips the the handle_brkchars phase, and
1733 so we create a tracker now in that case too. */
1734 delete current_completion
.tracker
;
1735 current_completion
.tracker
= new completion_tracker ();
1737 complete_line (*current_completion
.tracker
, text
,
1738 rl_line_buffer
, rl_point
);
1740 completion_tracker
&tracker
= *current_completion
.tracker
;
1742 completion_result result
1743 = tracker
.build_completion_result (text
, start
, end
);
1745 rl_completion_suppress_append
= result
.completion_suppress_append
;
1746 return result
.release_match_list ();
1749 /* Function installed as "rl_attempted_completion_function" readline
1750 hook. Wrapper around gdb_rl_attempted_completion_function_throw
1751 that catches C++ exceptions, which can't cross readline. */
1754 gdb_rl_attempted_completion_function (const char *text
, int start
, int end
)
1756 /* If we end up returning NULL, either on error, or simple because
1757 there are no matches, inhibit readline's default filename
1759 rl_attempted_completion_over
= 1;
1761 /* If the handle_brkchars phase was aborted, don't try
1763 if (current_completion
.aborted
)
1768 return gdb_rl_attempted_completion_function_throw (text
, start
, end
);
1770 CATCH (ex
, RETURN_MASK_ALL
)
1778 /* Skip over the possibly quoted word STR (as defined by the quote
1779 characters QUOTECHARS and the word break characters BREAKCHARS).
1780 Returns pointer to the location after the "word". If either
1781 QUOTECHARS or BREAKCHARS is NULL, use the same values used by the
1785 skip_quoted_chars (const char *str
, const char *quotechars
,
1786 const char *breakchars
)
1788 char quote_char
= '\0';
1791 if (quotechars
== NULL
)
1792 quotechars
= gdb_completer_quote_characters
;
1794 if (breakchars
== NULL
)
1795 breakchars
= current_language
->la_word_break_characters();
1797 for (scan
= str
; *scan
!= '\0'; scan
++)
1799 if (quote_char
!= '\0')
1801 /* Ignore everything until the matching close quote char. */
1802 if (*scan
== quote_char
)
1804 /* Found matching close quote. */
1809 else if (strchr (quotechars
, *scan
))
1811 /* Found start of a quoted string. */
1814 else if (strchr (breakchars
, *scan
))
1823 /* Skip over the possibly quoted word STR (as defined by the quote
1824 characters and word break characters used by the completer).
1825 Returns pointer to the location after the "word". */
1828 skip_quoted (const char *str
)
1830 return skip_quoted_chars (str
, NULL
, NULL
);
1833 /* Return a message indicating that the maximum number of completions
1834 has been reached and that there may be more. */
1837 get_max_completions_reached_message (void)
1839 return _("*** List may be truncated, max-completions reached. ***");
1842 /* GDB replacement for rl_display_match_list.
1843 Readline doesn't provide a clean interface for TUI(curses).
1844 A hack previously used was to send readline's rl_outstream through a pipe
1845 and read it from the event loop. Bleah. IWBN if readline abstracted
1846 away all the necessary bits, and this is what this code does. It
1847 replicates the parts of readline we need and then adds an abstraction
1848 layer, currently implemented as struct match_list_displayer, so that both
1849 CLI and TUI can use it. We copy all this readline code to minimize
1850 GDB-specific mods to readline. Once this code performs as desired then
1851 we can submit it to the readline maintainers.
1853 N.B. A lot of the code is the way it is in order to minimize differences
1854 from readline's copy. */
1856 /* Not supported here. */
1857 #undef VISIBLE_STATS
1859 #if defined (HANDLE_MULTIBYTE)
1860 #define MB_INVALIDCH(x) ((x) == (size_t)-1 || (x) == (size_t)-2)
1861 #define MB_NULLWCH(x) ((x) == 0)
1864 #define ELLIPSIS_LEN 3
1866 /* gdb version of readline/complete.c:get_y_or_n.
1867 'y' -> returns 1, and 'n' -> returns 0.
1868 Also supported: space == 'y', RUBOUT == 'n', ctrl-g == start over.
1869 If FOR_PAGER is non-zero, then also supported are:
1870 NEWLINE or RETURN -> returns 2, and 'q' -> returns 0. */
1873 gdb_get_y_or_n (int for_pager
, const struct match_list_displayer
*displayer
)
1879 RL_SETSTATE (RL_STATE_MOREINPUT
);
1880 c
= displayer
->read_key (displayer
);
1881 RL_UNSETSTATE (RL_STATE_MOREINPUT
);
1883 if (c
== 'y' || c
== 'Y' || c
== ' ')
1885 if (c
== 'n' || c
== 'N' || c
== RUBOUT
)
1887 if (c
== ABORT_CHAR
|| c
< 0)
1889 /* Readline doesn't erase_entire_line here, but without it the
1890 --More-- prompt isn't erased and neither is the text entered
1891 thus far redisplayed. */
1892 displayer
->erase_entire_line (displayer
);
1893 /* Note: The arguments to rl_abort are ignored. */
1896 if (for_pager
&& (c
== NEWLINE
|| c
== RETURN
))
1898 if (for_pager
&& (c
== 'q' || c
== 'Q'))
1900 displayer
->beep (displayer
);
1904 /* Pager function for tab-completion.
1905 This is based on readline/complete.c:_rl_internal_pager.
1906 LINES is the number of lines of output displayed thus far.
1908 -1 -> user pressed 'n' or equivalent,
1909 0 -> user pressed 'y' or equivalent,
1910 N -> user pressed NEWLINE or equivalent and N is LINES - 1. */
1913 gdb_display_match_list_pager (int lines
,
1914 const struct match_list_displayer
*displayer
)
1918 displayer
->puts (displayer
, "--More--");
1919 displayer
->flush (displayer
);
1920 i
= gdb_get_y_or_n (1, displayer
);
1921 displayer
->erase_entire_line (displayer
);
1930 /* Return non-zero if FILENAME is a directory.
1931 Based on readline/complete.c:path_isdir. */
1934 gdb_path_isdir (const char *filename
)
1938 return (stat (filename
, &finfo
) == 0 && S_ISDIR (finfo
.st_mode
));
1941 /* Return the portion of PATHNAME that should be output when listing
1942 possible completions. If we are hacking filename completion, we
1943 are only interested in the basename, the portion following the
1944 final slash. Otherwise, we return what we were passed. Since
1945 printing empty strings is not very informative, if we're doing
1946 filename completion, and the basename is the empty string, we look
1947 for the previous slash and return the portion following that. If
1948 there's no previous slash, we just return what we were passed.
1950 Based on readline/complete.c:printable_part. */
1953 gdb_printable_part (char *pathname
)
1957 if (rl_filename_completion_desired
== 0) /* don't need to do anything */
1960 temp
= strrchr (pathname
, '/');
1961 #if defined (__MSDOS__)
1962 if (temp
== 0 && ISALPHA ((unsigned char)pathname
[0]) && pathname
[1] == ':')
1963 temp
= pathname
+ 1;
1966 if (temp
== 0 || *temp
== '\0')
1968 /* If the basename is NULL, we might have a pathname like '/usr/src/'.
1969 Look for a previous slash and, if one is found, return the portion
1970 following that slash. If there's no previous slash, just return the
1971 pathname we were passed. */
1972 else if (temp
[1] == '\0')
1974 for (x
= temp
- 1; x
> pathname
; x
--)
1977 return ((*x
== '/') ? x
+ 1 : pathname
);
1983 /* Compute width of STRING when displayed on screen by print_filename.
1984 Based on readline/complete.c:fnwidth. */
1987 gdb_fnwidth (const char *string
)
1990 #if defined (HANDLE_MULTIBYTE)
1996 left
= strlen (string
) + 1;
1997 memset (&ps
, 0, sizeof (mbstate_t));
2003 if (CTRL_CHAR (string
[pos
]) || string
[pos
] == RUBOUT
)
2010 #if defined (HANDLE_MULTIBYTE)
2011 clen
= mbrtowc (&wc
, string
+ pos
, left
- pos
, &ps
);
2012 if (MB_INVALIDCH (clen
))
2016 memset (&ps
, 0, sizeof (mbstate_t));
2018 else if (MB_NULLWCH (clen
))
2024 width
+= (w
>= 0) ? w
: 1;
2036 /* Print TO_PRINT, one matching completion.
2037 PREFIX_BYTES is number of common prefix bytes.
2038 Based on readline/complete.c:fnprint. */
2041 gdb_fnprint (const char *to_print
, int prefix_bytes
,
2042 const struct match_list_displayer
*displayer
)
2046 #if defined (HANDLE_MULTIBYTE)
2053 end
= to_print
+ strlen (to_print
) + 1;
2054 memset (&ps
, 0, sizeof (mbstate_t));
2059 /* Don't print only the ellipsis if the common prefix is one of the
2060 possible completions */
2061 if (to_print
[prefix_bytes
] == '\0')
2068 ellipsis
= (to_print
[prefix_bytes
] == '.') ? '_' : '.';
2069 for (w
= 0; w
< ELLIPSIS_LEN
; w
++)
2070 displayer
->putch (displayer
, ellipsis
);
2071 printed_len
= ELLIPSIS_LEN
;
2074 s
= to_print
+ prefix_bytes
;
2079 displayer
->putch (displayer
, '^');
2080 displayer
->putch (displayer
, UNCTRL (*s
));
2083 #if defined (HANDLE_MULTIBYTE)
2084 memset (&ps
, 0, sizeof (mbstate_t));
2087 else if (*s
== RUBOUT
)
2089 displayer
->putch (displayer
, '^');
2090 displayer
->putch (displayer
, '?');
2093 #if defined (HANDLE_MULTIBYTE)
2094 memset (&ps
, 0, sizeof (mbstate_t));
2099 #if defined (HANDLE_MULTIBYTE)
2100 tlen
= mbrtowc (&wc
, s
, end
- s
, &ps
);
2101 if (MB_INVALIDCH (tlen
))
2105 memset (&ps
, 0, sizeof (mbstate_t));
2107 else if (MB_NULLWCH (tlen
))
2112 width
= (w
>= 0) ? w
: 1;
2114 for (w
= 0; w
< tlen
; ++w
)
2115 displayer
->putch (displayer
, s
[w
]);
2117 printed_len
+= width
;
2119 displayer
->putch (displayer
, *s
);
2129 /* Output TO_PRINT to rl_outstream. If VISIBLE_STATS is defined and we
2130 are using it, check for and output a single character for `special'
2131 filenames. Return the number of characters we output.
2132 Based on readline/complete.c:print_filename. */
2135 gdb_print_filename (char *to_print
, char *full_pathname
, int prefix_bytes
,
2136 const struct match_list_displayer
*displayer
)
2138 int printed_len
, extension_char
, slen
, tlen
;
2139 char *s
, c
, *new_full_pathname
;
2141 extern int _rl_complete_mark_directories
;
2144 printed_len
= gdb_fnprint (to_print
, prefix_bytes
, displayer
);
2146 #if defined (VISIBLE_STATS)
2147 if (rl_filename_completion_desired
&& (rl_visible_stats
|| _rl_complete_mark_directories
))
2149 if (rl_filename_completion_desired
&& _rl_complete_mark_directories
)
2152 /* If to_print != full_pathname, to_print is the basename of the
2153 path passed. In this case, we try to expand the directory
2154 name before checking for the stat character. */
2155 if (to_print
!= full_pathname
)
2157 /* Terminate the directory name. */
2159 to_print
[-1] = '\0';
2161 /* If setting the last slash in full_pathname to a NUL results in
2162 full_pathname being the empty string, we are trying to complete
2163 files in the root directory. If we pass a null string to the
2164 bash directory completion hook, for example, it will expand it
2165 to the current directory. We just want the `/'. */
2166 if (full_pathname
== 0 || *full_pathname
== 0)
2168 else if (full_pathname
[0] != '/')
2170 else if (full_pathname
[1] == 0)
2171 dn
= "//"; /* restore trailing slash to `//' */
2172 else if (full_pathname
[1] == '/' && full_pathname
[2] == 0)
2173 dn
= "/"; /* don't turn /// into // */
2176 s
= tilde_expand (dn
);
2177 if (rl_directory_completion_hook
)
2178 (*rl_directory_completion_hook
) (&s
);
2181 tlen
= strlen (to_print
);
2182 new_full_pathname
= (char *)xmalloc (slen
+ tlen
+ 2);
2183 strcpy (new_full_pathname
, s
);
2184 if (s
[slen
- 1] == '/')
2187 new_full_pathname
[slen
] = '/';
2188 new_full_pathname
[slen
] = '/';
2189 strcpy (new_full_pathname
+ slen
+ 1, to_print
);
2191 #if defined (VISIBLE_STATS)
2192 if (rl_visible_stats
)
2193 extension_char
= stat_char (new_full_pathname
);
2196 if (gdb_path_isdir (new_full_pathname
))
2197 extension_char
= '/';
2199 xfree (new_full_pathname
);
2204 s
= tilde_expand (full_pathname
);
2205 #if defined (VISIBLE_STATS)
2206 if (rl_visible_stats
)
2207 extension_char
= stat_char (s
);
2210 if (gdb_path_isdir (s
))
2211 extension_char
= '/';
2217 displayer
->putch (displayer
, extension_char
);
2225 /* GDB version of readline/complete.c:complete_get_screenwidth. */
2228 gdb_complete_get_screenwidth (const struct match_list_displayer
*displayer
)
2230 /* Readline has other stuff here which it's not clear we need. */
2231 return displayer
->width
;
2234 extern int _rl_completion_prefix_display_length
;
2235 extern int _rl_print_completions_horizontally
;
2237 EXTERN_C
int _rl_qsort_string_compare (const void *, const void *);
2238 typedef int QSFUNC (const void *, const void *);
2240 /* GDB version of readline/complete.c:rl_display_match_list.
2241 See gdb_display_match_list for a description of MATCHES, LEN, MAX.
2242 Returns non-zero if all matches are displayed. */
2245 gdb_display_match_list_1 (char **matches
, int len
, int max
,
2246 const struct match_list_displayer
*displayer
)
2248 int count
, limit
, printed_len
, lines
, cols
;
2249 int i
, j
, k
, l
, common_length
, sind
;
2251 int page_completions
= displayer
->height
!= INT_MAX
&& pagination_enabled
;
2253 /* Find the length of the prefix common to all items: length as displayed
2254 characters (common_length) and as a byte index into the matches (sind) */
2255 common_length
= sind
= 0;
2256 if (_rl_completion_prefix_display_length
> 0)
2258 t
= gdb_printable_part (matches
[0]);
2259 temp
= strrchr (t
, '/');
2260 common_length
= temp
? gdb_fnwidth (temp
) : gdb_fnwidth (t
);
2261 sind
= temp
? strlen (temp
) : strlen (t
);
2263 if (common_length
> _rl_completion_prefix_display_length
&& common_length
> ELLIPSIS_LEN
)
2264 max
-= common_length
- ELLIPSIS_LEN
;
2266 common_length
= sind
= 0;
2269 /* How many items of MAX length can we fit in the screen window? */
2270 cols
= gdb_complete_get_screenwidth (displayer
);
2273 if (limit
!= 1 && (limit
* max
== cols
))
2276 /* If cols == 0, limit will end up -1 */
2277 if (cols
< displayer
->width
&& limit
< 0)
2280 /* Avoid a possible floating exception. If max > cols,
2281 limit will be 0 and a divide-by-zero fault will result. */
2285 /* How many iterations of the printing loop? */
2286 count
= (len
+ (limit
- 1)) / limit
;
2288 /* Watch out for special case. If LEN is less than LIMIT, then
2289 just do the inner printing loop.
2290 0 < len <= limit implies count = 1. */
2292 /* Sort the items if they are not already sorted. */
2293 if (rl_ignore_completion_duplicates
== 0 && rl_sort_completion_matches
)
2294 qsort (matches
+ 1, len
, sizeof (char *), (QSFUNC
*)_rl_qsort_string_compare
);
2296 displayer
->crlf (displayer
);
2299 if (_rl_print_completions_horizontally
== 0)
2301 /* Print the sorted items, up-and-down alphabetically, like ls. */
2302 for (i
= 1; i
<= count
; i
++)
2304 for (j
= 0, l
= i
; j
< limit
; j
++)
2306 if (l
> len
|| matches
[l
] == 0)
2310 temp
= gdb_printable_part (matches
[l
]);
2311 printed_len
= gdb_print_filename (temp
, matches
[l
], sind
,
2315 for (k
= 0; k
< max
- printed_len
; k
++)
2316 displayer
->putch (displayer
, ' ');
2320 displayer
->crlf (displayer
);
2322 if (page_completions
&& lines
>= (displayer
->height
- 1) && i
< count
)
2324 lines
= gdb_display_match_list_pager (lines
, displayer
);
2332 /* Print the sorted items, across alphabetically, like ls -x. */
2333 for (i
= 1; matches
[i
]; i
++)
2335 temp
= gdb_printable_part (matches
[i
]);
2336 printed_len
= gdb_print_filename (temp
, matches
[i
], sind
, displayer
);
2337 /* Have we reached the end of this line? */
2340 if (i
&& (limit
> 1) && (i
% limit
) == 0)
2342 displayer
->crlf (displayer
);
2344 if (page_completions
&& lines
>= displayer
->height
- 1)
2346 lines
= gdb_display_match_list_pager (lines
, displayer
);
2352 for (k
= 0; k
< max
- printed_len
; k
++)
2353 displayer
->putch (displayer
, ' ');
2356 displayer
->crlf (displayer
);
2362 /* Utility for displaying completion list matches, used by both CLI and TUI.
2364 MATCHES is the list of strings, in argv format, LEN is the number of
2365 strings in MATCHES, and MAX is the length of the longest string in
2369 gdb_display_match_list (char **matches
, int len
, int max
,
2370 const struct match_list_displayer
*displayer
)
2372 /* Readline will never call this if complete_line returned NULL. */
2373 gdb_assert (max_completions
!= 0);
2375 /* complete_line will never return more than this. */
2376 if (max_completions
> 0)
2377 gdb_assert (len
<= max_completions
);
2379 if (rl_completion_query_items
> 0 && len
>= rl_completion_query_items
)
2383 /* We can't use *query here because they wait for <RET> which is
2384 wrong here. This follows the readline version as closely as possible
2385 for compatibility's sake. See readline/complete.c. */
2387 displayer
->crlf (displayer
);
2389 xsnprintf (msg
, sizeof (msg
),
2390 "Display all %d possibilities? (y or n)", len
);
2391 displayer
->puts (displayer
, msg
);
2392 displayer
->flush (displayer
);
2394 if (gdb_get_y_or_n (0, displayer
) == 0)
2396 displayer
->crlf (displayer
);
2401 if (gdb_display_match_list_1 (matches
, len
, max
, displayer
))
2403 /* Note: MAX_COMPLETIONS may be -1 or zero, but LEN is always > 0. */
2404 if (len
== max_completions
)
2406 /* The maximum number of completions has been reached. Warn the user
2407 that there may be more. */
2408 const char *message
= get_max_completions_reached_message ();
2410 displayer
->puts (displayer
, message
);
2411 displayer
->crlf (displayer
);
2416 extern initialize_file_ftype _initialize_completer
; /* -Wmissing-prototypes */
2419 _initialize_completer (void)
2421 add_setshow_zuinteger_unlimited_cmd ("max-completions", no_class
,
2422 &max_completions
, _("\
2423 Set maximum number of completion candidates."), _("\
2424 Show maximum number of completion candidates."), _("\
2425 Use this to limit the number of candidates considered\n\
2426 during completion. Specifying \"unlimited\" or -1\n\
2427 disables limiting. Note that setting either no limit or\n\
2428 a very large limit can make completion slow."),
2429 NULL
, NULL
, &setlist
, &showlist
);