]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gdb/completer.c
MI: extract command completion logic from complete_command()
[thirdparty/binutils-gdb.git] / gdb / completer.c
CommitLineData
c5f0f3d0 1/* Line completion stuff for GDB, the GNU debugger.
42a4f53d 2 Copyright (C) 2000-2019 Free Software Foundation, Inc.
c5f0f3d0
FN
3
4 This file is part of GDB.
5
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
a9762ec7 8 the Free Software Foundation; either version 3 of the License, or
c5f0f3d0
FN
9 (at your option) any later version.
10
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.
15
16 You should have received a copy of the GNU General Public License
a9762ec7 17 along with this program. If not, see <http://www.gnu.org/licenses/>. */
c5f0f3d0
FN
18
19#include "defs.h"
4de283e4 20#include "symtab.h"
d55e5aa6 21#include "gdbtypes.h"
4de283e4
TT
22#include "expression.h"
23#include "filenames.h" /* For DOSish file names. */
51065942 24#include "language.h"
4de283e4 25#include "common/gdb_signals.h"
d55e5aa6 26#include "target.h"
4de283e4 27#include "reggroups.h"
71c24708 28#include "user-regs.h"
4de283e4
TT
29#include "arch-utils.h"
30#include "location.h"
31#include <algorithm>
32#include "linespec.h"
33#include "cli/cli-decode.h"
18a642a1 34
03717487
MS
35/* FIXME: This is needed because of lookup_cmd_1 (). We should be
36 calling a hook instead so we eliminate the CLI dependency. */
c5f0f3d0
FN
37#include "gdbcmd.h"
38
c94fdfd0 39/* Needed for rl_completer_word_break_characters() and for
38017ce8 40 rl_filename_completion_function. */
dbda9972 41#include "readline/readline.h"
c5f0f3d0
FN
42
43/* readline defines this. */
44#undef savestring
45
46#include "completer.h"
47
eb3ff9a5
PA
48/* Misc state that needs to be tracked across several different
49 readline completer entry point calls, all related to a single
50 completion invocation. */
51
52struct gdb_completer_state
53{
54 /* The current completion's completion tracker. This is a global
55 because a tracker can be shared between the handle_brkchars and
56 handle_completion phases, which involves different readline
57 callbacks. */
58 completion_tracker *tracker = NULL;
59
60 /* Whether the current completion was aborted. */
61 bool aborted = false;
62};
63
64/* The current completion state. */
65static gdb_completer_state current_completion;
66
c6756f62
PA
67/* An enumeration of the various things a user might attempt to
68 complete for a location. If you change this, remember to update
69 the explicit_options array below too. */
87f0e720
KS
70
71enum explicit_location_match_type
72{
73 /* The filename of a source file. */
74 MATCH_SOURCE,
75
76 /* The name of a function or method. */
77 MATCH_FUNCTION,
78
a20714ff
PA
79 /* The fully-qualified name of a function or method. */
80 MATCH_QUALIFIED,
81
c6756f62
PA
82 /* A line number. */
83 MATCH_LINE,
84
87f0e720
KS
85 /* The name of a label. */
86 MATCH_LABEL
87};
88
9c3f90bd 89/* Prototypes for local functions. */
c5f0f3d0
FN
90
91/* readline uses the word breaks for two things:
92 (1) In figuring out where to point the TEXT parameter to the
93 rl_completion_entry_function. Since we don't use TEXT for much,
aff410f1
MS
94 it doesn't matter a lot what the word breaks are for this purpose,
95 but it does affect how much stuff M-? lists.
c5f0f3d0
FN
96 (2) If one of the matches contains a word break character, readline
97 will quote it. That's why we switch between
51065942 98 current_language->la_word_break_characters() and
c5f0f3d0 99 gdb_completer_command_word_break_characters. I'm not sure when
aff410f1
MS
100 we need this behavior (perhaps for funky characters in C++
101 symbols?). */
c5f0f3d0
FN
102
103/* Variables which are necessary for fancy command line editing. */
c5f0f3d0
FN
104
105/* When completing on command names, we remove '-' from the list of
106 word break characters, since we use it in command names. If the
107 readline library sees one in any of the current completion strings,
aff410f1
MS
108 it thinks that the string needs to be quoted and automatically
109 supplies a leading quote. */
67cb5b2d 110static const char gdb_completer_command_word_break_characters[] =
c5f0f3d0
FN
111" \t\n!@#$%^&*()+=|~`}{[]\"';:?/>.<,";
112
113/* When completing on file names, we remove from the list of word
114 break characters any characters that are commonly used in file
115 names, such as '-', '+', '~', etc. Otherwise, readline displays
116 incorrect completion candidates. */
7830cf6f
EZ
117/* MS-DOS and MS-Windows use colon as part of the drive spec, and most
118 programs support @foo style response files. */
67cb5b2d
PA
119static const char gdb_completer_file_name_break_characters[] =
120#ifdef HAVE_DOS_BASED_FILE_SYSTEM
121 " \t\n*|\"';?><@";
7830cf6f 122#else
67cb5b2d 123 " \t\n*|\"';:?><";
7830cf6f 124#endif
c5f0f3d0 125
aff410f1
MS
126/* Characters that can be used to quote completion strings. Note that
127 we can't include '"' because the gdb C parser treats such quoted
128 sequences as strings. */
67cb5b2d 129static const char gdb_completer_quote_characters[] = "'";
c5f0f3d0 130\f
9c3f90bd 131/* Accessor for some completer data that may interest other files. */
c5f0f3d0 132
67cb5b2d 133const char *
c5f0f3d0
FN
134get_gdb_completer_quote_characters (void)
135{
136 return gdb_completer_quote_characters;
137}
138
aff410f1
MS
139/* This can be used for functions which don't want to complete on
140 symbols but don't want to complete on anything else either. */
eb3ff9a5
PA
141
142void
aff410f1 143noop_completer (struct cmd_list_element *ignore,
eb3ff9a5 144 completion_tracker &tracker,
6f937416 145 const char *text, const char *prefix)
d75b5104 146{
d75b5104
EZ
147}
148
c5f0f3d0 149/* Complete on filenames. */
6e1dbf8c 150
eb3ff9a5
PA
151void
152filename_completer (struct cmd_list_element *ignore,
153 completion_tracker &tracker,
6f937416 154 const char *text, const char *word)
c5f0f3d0 155{
c5f0f3d0 156 int subsequent_name;
c5f0f3d0
FN
157
158 subsequent_name = 0;
159 while (1)
160 {
60a20c19
PA
161 gdb::unique_xmalloc_ptr<char> p_rl
162 (rl_filename_completion_function (text, subsequent_name));
163 if (p_rl == NULL)
49c4e619 164 break;
c5f0f3d0 165 /* We need to set subsequent_name to a non-zero value before the
aff410f1
MS
166 continue line below, because otherwise, if the first file
167 seen by GDB is a backup file whose name ends in a `~', we
168 will loop indefinitely. */
c5f0f3d0 169 subsequent_name = 1;
aff410f1
MS
170 /* Like emacs, don't complete on old versions. Especially
171 useful in the "source" command. */
60a20c19 172 const char *p = p_rl.get ();
c5f0f3d0 173 if (p[strlen (p) - 1] == '~')
60a20c19 174 continue;
c5f0f3d0 175
60a20c19
PA
176 tracker.add_completion
177 (make_completion_match_str (std::move (p_rl), text, word));
c5f0f3d0
FN
178 }
179#if 0
aff410f1
MS
180 /* There is no way to do this just long enough to affect quote
181 inserting without also affecting the next completion. This
182 should be fixed in readline. FIXME. */
489f0516 183 /* Ensure that readline does the right thing
c5f0f3d0
FN
184 with respect to inserting quotes. */
185 rl_completer_word_break_characters = "";
186#endif
c5f0f3d0
FN
187}
188
6e1dbf8c
PA
189/* The corresponding completer_handle_brkchars
190 implementation. */
191
192static void
193filename_completer_handle_brkchars (struct cmd_list_element *ignore,
eb3ff9a5 194 completion_tracker &tracker,
6e1dbf8c
PA
195 const char *text, const char *word)
196{
197 set_rl_completer_word_break_characters
198 (gdb_completer_file_name_break_characters);
199}
200
6a2c1b87
PA
201/* Possible values for the found_quote flags word used by the completion
202 functions. It says what kind of (shell-like) quoting we found anywhere
203 in the line. */
204#define RL_QF_SINGLE_QUOTE 0x01
205#define RL_QF_DOUBLE_QUOTE 0x02
206#define RL_QF_BACKSLASH 0x04
207#define RL_QF_OTHER_QUOTE 0x08
208
209/* Find the bounds of the current word for completion purposes, and
210 return a pointer to the end of the word. This mimics (and is a
211 modified version of) readline's _rl_find_completion_word internal
212 function.
213
214 This function skips quoted substrings (characters between matched
215 pairs of characters in rl_completer_quote_characters). We try to
216 find an unclosed quoted substring on which to do matching. If one
217 is not found, we use the word break characters to find the
218 boundaries of the current word. QC, if non-null, is set to the
219 opening quote character if we found an unclosed quoted substring,
220 '\0' otherwise. DP, if non-null, is set to the value of the
221 delimiter character that caused a word break. */
222
223struct gdb_rl_completion_word_info
224{
225 const char *word_break_characters;
226 const char *quote_characters;
227 const char *basic_quote_characters;
228};
229
230static const char *
231gdb_rl_find_completion_word (struct gdb_rl_completion_word_info *info,
232 int *qc, int *dp,
233 const char *line_buffer)
234{
235 int scan, end, found_quote, delimiter, pass_next, isbrk;
236 char quote_char;
237 const char *brkchars;
238 int point = strlen (line_buffer);
239
240 /* The algorithm below does '--point'. Avoid buffer underflow with
241 the empty string. */
242 if (point == 0)
243 {
244 if (qc != NULL)
245 *qc = '\0';
246 if (dp != NULL)
247 *dp = '\0';
248 return line_buffer;
249 }
250
251 end = point;
252 found_quote = delimiter = 0;
253 quote_char = '\0';
254
255 brkchars = info->word_break_characters;
256
257 if (info->quote_characters != NULL)
258 {
259 /* We have a list of characters which can be used in pairs to
260 quote substrings for the completer. Try to find the start of
261 an unclosed quoted substring. */
262 /* FOUND_QUOTE is set so we know what kind of quotes we
263 found. */
264 for (scan = pass_next = 0;
265 scan < end;
266 scan++)
267 {
268 if (pass_next)
269 {
270 pass_next = 0;
271 continue;
272 }
273
274 /* Shell-like semantics for single quotes -- don't allow
275 backslash to quote anything in single quotes, especially
276 not the closing quote. If you don't like this, take out
277 the check on the value of quote_char. */
278 if (quote_char != '\'' && line_buffer[scan] == '\\')
279 {
280 pass_next = 1;
281 found_quote |= RL_QF_BACKSLASH;
282 continue;
283 }
284
285 if (quote_char != '\0')
286 {
287 /* Ignore everything until the matching close quote
288 char. */
289 if (line_buffer[scan] == quote_char)
290 {
291 /* Found matching close. Abandon this
292 substring. */
293 quote_char = '\0';
294 point = end;
295 }
296 }
297 else if (strchr (info->quote_characters, line_buffer[scan]))
298 {
299 /* Found start of a quoted substring. */
300 quote_char = line_buffer[scan];
301 point = scan + 1;
302 /* Shell-like quoting conventions. */
303 if (quote_char == '\'')
304 found_quote |= RL_QF_SINGLE_QUOTE;
305 else if (quote_char == '"')
306 found_quote |= RL_QF_DOUBLE_QUOTE;
307 else
308 found_quote |= RL_QF_OTHER_QUOTE;
309 }
310 }
311 }
312
313 if (point == end && quote_char == '\0')
314 {
315 /* We didn't find an unclosed quoted substring upon which to do
316 completion, so use the word break characters to find the
317 substring on which to complete. */
318 while (--point)
319 {
320 scan = line_buffer[point];
321
322 if (strchr (brkchars, scan) != 0)
323 break;
324 }
325 }
326
327 /* If we are at an unquoted word break, then advance past it. */
328 scan = line_buffer[point];
329
330 if (scan)
331 {
332 isbrk = strchr (brkchars, scan) != 0;
333
334 if (isbrk)
335 {
336 /* If the character that caused the word break was a quoting
337 character, then remember it as the delimiter. */
338 if (info->basic_quote_characters
339 && strchr (info->basic_quote_characters, scan)
340 && (end - point) > 1)
341 delimiter = scan;
342
343 point++;
344 }
345 }
346
347 if (qc != NULL)
348 *qc = quote_char;
349 if (dp != NULL)
350 *dp = delimiter;
351
352 return line_buffer + point;
353}
354
c6756f62
PA
355/* See completer.h. */
356
357const char *
358advance_to_expression_complete_word_point (completion_tracker &tracker,
359 const char *text)
360{
361 gdb_rl_completion_word_info info;
362
363 info.word_break_characters
364 = current_language->la_word_break_characters ();
365 info.quote_characters = gdb_completer_quote_characters;
366 info.basic_quote_characters = rl_basic_quote_characters;
367
368 const char *start
369 = gdb_rl_find_completion_word (&info, NULL, NULL, text);
370
371 tracker.advance_custom_word_point_by (start - text);
372
373 return start;
374}
375
376/* See completer.h. */
377
378bool
379completion_tracker::completes_to_completion_word (const char *word)
380{
381 if (m_lowest_common_denominator_unique)
382 {
383 const char *lcd = m_lowest_common_denominator;
384
385 if (strncmp_iw (word, lcd, strlen (lcd)) == 0)
386 {
387 /* Maybe skip the function and complete on keywords. */
388 size_t wordlen = strlen (word);
389 if (word[wordlen - 1] == ' ')
390 return true;
391 }
392 }
393
394 return false;
395}
396
87f0e720 397/* Complete on linespecs, which might be of two possible forms:
c94fdfd0
EZ
398
399 file:line
400 or
401 symbol+offset
402
aff410f1
MS
403 This is intended to be used in commands that set breakpoints
404 etc. */
405
eb3ff9a5
PA
406static void
407complete_files_symbols (completion_tracker &tracker,
408 const char *text, const char *word)
c94fdfd0 409{
eb3ff9a5 410 completion_list fn_list;
6f937416 411 const char *p;
c94fdfd0
EZ
412 int quote_found = 0;
413 int quoted = *text == '\'' || *text == '"';
414 int quote_char = '\0';
6f937416 415 const char *colon = NULL;
c94fdfd0 416 char *file_to_match = NULL;
6f937416
PA
417 const char *symbol_start = text;
418 const char *orig_text = text;
c94fdfd0 419
59be2b6a 420 /* Do we have an unquoted colon, as in "break foo.c:bar"? */
c94fdfd0
EZ
421 for (p = text; *p != '\0'; ++p)
422 {
423 if (*p == '\\' && p[1] == '\'')
424 p++;
425 else if (*p == '\'' || *p == '"')
426 {
427 quote_found = *p;
428 quote_char = *p++;
429 while (*p != '\0' && *p != quote_found)
430 {
431 if (*p == '\\' && p[1] == quote_found)
432 p++;
433 p++;
434 }
435
436 if (*p == quote_found)
437 quote_found = 0;
438 else
9c3f90bd 439 break; /* Hit the end of text. */
c94fdfd0
EZ
440 }
441#if HAVE_DOS_BASED_FILE_SYSTEM
442 /* If we have a DOS-style absolute file name at the beginning of
443 TEXT, and the colon after the drive letter is the only colon
444 we found, pretend the colon is not there. */
445 else if (p < text + 3 && *p == ':' && p == text + 1 + quoted)
446 ;
447#endif
448 else if (*p == ':' && !colon)
449 {
450 colon = p;
451 symbol_start = p + 1;
452 }
51065942 453 else if (strchr (current_language->la_word_break_characters(), *p))
c94fdfd0
EZ
454 symbol_start = p + 1;
455 }
456
457 if (quoted)
458 text++;
c94fdfd0
EZ
459
460 /* Where is the file name? */
461 if (colon)
462 {
463 char *s;
464
465 file_to_match = (char *) xmalloc (colon - text + 1);
bbfa2517
YQ
466 strncpy (file_to_match, text, colon - text);
467 file_to_match[colon - text] = '\0';
c94fdfd0
EZ
468 /* Remove trailing colons and quotes from the file name. */
469 for (s = file_to_match + (colon - text);
470 s > file_to_match;
471 s--)
472 if (*s == ':' || *s == quote_char)
473 *s = '\0';
474 }
475 /* If the text includes a colon, they want completion only on a
476 symbol name after the colon. Otherwise, we need to complete on
477 symbols as well as on files. */
478 if (colon)
479 {
c6756f62
PA
480 collect_file_symbol_completion_matches (tracker,
481 complete_symbol_mode::EXPRESSION,
b5ec771e 482 symbol_name_match_type::EXPRESSION,
c6756f62 483 symbol_start, word,
eb3ff9a5 484 file_to_match);
c94fdfd0
EZ
485 xfree (file_to_match);
486 }
487 else
488 {
eb3ff9a5
PA
489 size_t text_len = strlen (text);
490
c6756f62
PA
491 collect_symbol_completion_matches (tracker,
492 complete_symbol_mode::EXPRESSION,
b5ec771e 493 symbol_name_match_type::EXPRESSION,
c6756f62 494 symbol_start, word);
c94fdfd0
EZ
495 /* If text includes characters which cannot appear in a file
496 name, they cannot be asking for completion on files. */
eb3ff9a5 497 if (strcspn (text,
1f20ed91 498 gdb_completer_file_name_break_characters) == text_len)
c94fdfd0
EZ
499 fn_list = make_source_files_completion_list (text, text);
500 }
501
eb3ff9a5 502 if (!fn_list.empty () && !tracker.have_completions ())
c94fdfd0
EZ
503 {
504 /* If we only have file names as possible completion, we should
505 bring them in sync with what rl_complete expects. The
506 problem is that if the user types "break /foo/b TAB", and the
507 possible completions are "/foo/bar" and "/foo/baz"
508 rl_complete expects us to return "bar" and "baz", without the
509 leading directories, as possible completions, because `word'
510 starts at the "b". But we ignore the value of `word' when we
511 call make_source_files_completion_list above (because that
512 would not DTRT when the completion results in both symbols
513 and file names), so make_source_files_completion_list returns
514 the full "/foo/bar" and "/foo/baz" strings. This produces
515 wrong results when, e.g., there's only one possible
516 completion, because rl_complete will prepend "/foo/" to each
517 candidate completion. The loop below removes that leading
518 part. */
eb3ff9a5 519 for (const auto &fn_up: fn_list)
c94fdfd0 520 {
eb3ff9a5
PA
521 char *fn = fn_up.get ();
522 memmove (fn, fn + (word - text), strlen (fn) + 1 - (word - text));
c94fdfd0 523 }
c94fdfd0 524 }
eb3ff9a5
PA
525
526 tracker.add_completions (std::move (fn_list));
527
528 if (!tracker.have_completions ())
c94fdfd0
EZ
529 {
530 /* No completions at all. As the final resort, try completing
531 on the entire text as a symbol. */
eb3ff9a5 532 collect_symbol_completion_matches (tracker,
c6756f62 533 complete_symbol_mode::EXPRESSION,
b5ec771e 534 symbol_name_match_type::EXPRESSION,
eb3ff9a5 535 orig_text, word);
c94fdfd0 536 }
eb3ff9a5
PA
537}
538
c45ec17c
PA
539/* See completer.h. */
540
541completion_list
542complete_source_filenames (const char *text)
543{
544 size_t text_len = strlen (text);
545
546 /* If text includes characters which cannot appear in a file name,
547 the user cannot be asking for completion on files. */
548 if (strcspn (text,
549 gdb_completer_file_name_break_characters)
550 == text_len)
551 return make_source_files_completion_list (text, text);
552
553 return {};
554}
555
556/* Complete address and linespec locations. */
557
558static void
559complete_address_and_linespec_locations (completion_tracker &tracker,
a20714ff
PA
560 const char *text,
561 symbol_name_match_type match_type)
c45ec17c
PA
562{
563 if (*text == '*')
564 {
565 tracker.advance_custom_word_point_by (1);
566 text++;
567 const char *word
568 = advance_to_expression_complete_word_point (tracker, text);
569 complete_expression (tracker, text, word);
570 }
571 else
572 {
a20714ff 573 linespec_complete (tracker, text, match_type);
c45ec17c
PA
574 }
575}
576
c6756f62
PA
577/* The explicit location options. Note that indexes into this array
578 must match the explicit_location_match_type enumerators. */
c45ec17c 579
c6756f62
PA
580static const char *const explicit_options[] =
581 {
582 "-source",
583 "-function",
a20714ff 584 "-qualified",
c6756f62
PA
585 "-line",
586 "-label",
587 NULL
588 };
589
590/* The probe modifier options. These can appear before a location in
591 breakpoint commands. */
592static const char *const probe_options[] =
593 {
594 "-probe",
595 "-probe-stap",
596 "-probe-dtrace",
597 NULL
598 };
599
eb3ff9a5 600/* Returns STRING if not NULL, the empty string otherwise. */
c94fdfd0 601
eb3ff9a5
PA
602static const char *
603string_or_empty (const char *string)
604{
605 return string != NULL ? string : "";
c94fdfd0
EZ
606}
607
87f0e720
KS
608/* A helper function to collect explicit location matches for the given
609 LOCATION, which is attempting to match on WORD. */
610
eb3ff9a5
PA
611static void
612collect_explicit_location_matches (completion_tracker &tracker,
613 struct event_location *location,
87f0e720 614 enum explicit_location_match_type what,
c6756f62
PA
615 const char *word,
616 const struct language_defn *language)
87f0e720 617{
67994074
KS
618 const struct explicit_location *explicit_loc
619 = get_explicit_location (location);
87f0e720 620
a20714ff
PA
621 /* True if the option expects an argument. */
622 bool needs_arg = true;
623
c6756f62
PA
624 /* Note, in the various MATCH_* below, we complete on
625 explicit_loc->foo instead of WORD, because only the former will
626 have already skipped past any quote char. */
87f0e720
KS
627 switch (what)
628 {
629 case MATCH_SOURCE:
630 {
eb3ff9a5
PA
631 const char *source = string_or_empty (explicit_loc->source_filename);
632 completion_list matches
c6756f62 633 = make_source_files_completion_list (source, source);
eb3ff9a5 634 tracker.add_completions (std::move (matches));
87f0e720
KS
635 }
636 break;
637
638 case MATCH_FUNCTION:
639 {
eb3ff9a5 640 const char *function = string_or_empty (explicit_loc->function_name);
c6756f62 641 linespec_complete_function (tracker, function,
a20714ff 642 explicit_loc->func_name_match_type,
c6756f62 643 explicit_loc->source_filename);
87f0e720
KS
644 }
645 break;
646
a20714ff
PA
647 case MATCH_QUALIFIED:
648 needs_arg = false;
649 break;
c6756f62
PA
650 case MATCH_LINE:
651 /* Nothing to offer. */
652 break;
653
87f0e720 654 case MATCH_LABEL:
a2459270
PA
655 {
656 const char *label = string_or_empty (explicit_loc->label_name);
657 linespec_complete_label (tracker, language,
658 explicit_loc->source_filename,
659 explicit_loc->function_name,
a20714ff 660 explicit_loc->func_name_match_type,
a2459270
PA
661 label);
662 }
87f0e720
KS
663 break;
664
665 default:
666 gdb_assert_not_reached ("unhandled explicit_location_match_type");
667 }
c6756f62 668
a20714ff 669 if (!needs_arg || tracker.completes_to_completion_word (word))
c6756f62
PA
670 {
671 tracker.discard_completions ();
672 tracker.advance_custom_word_point_by (strlen (word));
673 complete_on_enum (tracker, explicit_options, "", "");
674 complete_on_enum (tracker, linespec_keywords, "", "");
675 }
676 else if (!tracker.have_completions ())
677 {
678 /* Maybe we have an unterminated linespec keyword at the tail of
679 the string. Try completing on that. */
680 size_t wordlen = strlen (word);
681 const char *keyword = word + wordlen;
682
683 if (wordlen > 0 && keyword[-1] != ' ')
684 {
685 while (keyword > word && *keyword != ' ')
686 keyword--;
687 /* Don't complete on keywords if we'd be completing on the
688 whole explicit linespec option. E.g., "b -function
689 thr<tab>" should not complete to the "thread"
690 keyword. */
691 if (keyword != word)
692 {
f1735a53 693 keyword = skip_spaces (keyword);
c6756f62
PA
694
695 tracker.advance_custom_word_point_by (keyword - word);
696 complete_on_enum (tracker, linespec_keywords, keyword, keyword);
697 }
698 }
699 else if (wordlen > 0 && keyword[-1] == ' ')
700 {
701 /* Assume that we're maybe past the explicit location
702 argument, and we didn't manage to find any match because
703 the user wants to create a pending breakpoint. Offer the
704 keyword and explicit location options as possible
705 completions. */
706 tracker.advance_custom_word_point_by (keyword - word);
707 complete_on_enum (tracker, linespec_keywords, keyword, keyword);
708 complete_on_enum (tracker, explicit_options, keyword, keyword);
709 }
710 }
87f0e720
KS
711}
712
c6756f62
PA
713/* If the next word in *TEXT_P is any of the keywords in KEYWORDS,
714 then advance both TEXT_P and the word point in the tracker past the
715 keyword and return the (0-based) index in the KEYWORDS array that
716 matched. Otherwise, return -1. */
87f0e720 717
c6756f62
PA
718static int
719skip_keyword (completion_tracker &tracker,
720 const char * const *keywords, const char **text_p)
87f0e720 721{
c6756f62 722 const char *text = *text_p;
f1735a53 723 const char *after = skip_to_space (text);
c6756f62 724 size_t len = after - text;
87f0e720 725
c6756f62
PA
726 if (text[len] != ' ')
727 return -1;
728
729 int found = -1;
730 for (int i = 0; keywords[i] != NULL; i++)
731 {
732 if (strncmp (keywords[i], text, len) == 0)
733 {
734 if (found == -1)
735 found = i;
736 else
737 return -1;
738 }
739 }
740
741 if (found != -1)
742 {
743 tracker.advance_custom_word_point_by (len + 1);
744 text += len + 1;
745 *text_p = text;
746 return found;
747 }
748
749 return -1;
87f0e720
KS
750}
751
752/* A completer function for explicit locations. This function
c6756f62
PA
753 completes both options ("-source", "-line", etc) and values. If
754 completing a quoted string, then QUOTED_ARG_START and
755 QUOTED_ARG_END point to the quote characters. LANGUAGE is the
756 current language. */
87f0e720 757
eb3ff9a5
PA
758static void
759complete_explicit_location (completion_tracker &tracker,
760 struct event_location *location,
c6756f62
PA
761 const char *text,
762 const language_defn *language,
763 const char *quoted_arg_start,
764 const char *quoted_arg_end)
87f0e720 765{
c6756f62
PA
766 if (*text != '-')
767 return;
87f0e720 768
c6756f62 769 int keyword = skip_keyword (tracker, explicit_options, &text);
87f0e720 770
c6756f62
PA
771 if (keyword == -1)
772 complete_on_enum (tracker, explicit_options, text, text);
773 else
87f0e720 774 {
c6756f62
PA
775 /* Completing on value. */
776 enum explicit_location_match_type what
777 = (explicit_location_match_type) keyword;
778
779 if (quoted_arg_start != NULL && quoted_arg_end != NULL)
87f0e720 780 {
c6756f62
PA
781 if (quoted_arg_end[1] == '\0')
782 {
783 /* If completing a quoted string with the cursor right
784 at the terminating quote char, complete the
785 completion word without interpretation, so that
786 readline advances the cursor one whitespace past the
787 quote, even if there's no match. This makes these
788 cases behave the same:
789
790 before: "b -function function()"
791 after: "b -function function() "
792
793 before: "b -function 'function()'"
794 after: "b -function 'function()' "
795
796 and trusts the user in this case:
797
798 before: "b -function 'not_loaded_function_yet()'"
799 after: "b -function 'not_loaded_function_yet()' "
800 */
801 gdb::unique_xmalloc_ptr<char> text_copy
802 (xstrdup (text));
803 tracker.add_completion (std::move (text_copy));
804 }
805 else if (quoted_arg_end[1] == ' ')
806 {
807 /* We're maybe past the explicit location argument.
808 Skip the argument without interpretion, assuming the
809 user may want to create pending breakpoint. Offer
810 the keyword and explicit location options as possible
811 completions. */
812 tracker.advance_custom_word_point_by (strlen (text));
813 complete_on_enum (tracker, linespec_keywords, "", "");
814 complete_on_enum (tracker, explicit_options, "", "");
815 }
816 return;
817 }
818
819 /* Now gather matches */
820 collect_explicit_location_matches (tracker, location, what, text,
821 language);
822 }
823}
87f0e720 824
c6756f62 825/* A completer for locations. */
87f0e720 826
c6756f62
PA
827void
828location_completer (struct cmd_list_element *ignore,
829 completion_tracker &tracker,
c45ec17c 830 const char *text, const char * /* word */)
c6756f62
PA
831{
832 int found_probe_option = -1;
833
834 /* If we have a probe modifier, skip it. This can only appear as
835 first argument. Until we have a specific completer for probes,
836 falling back to the linespec completer for the remainder of the
837 line is better than nothing. */
838 if (text[0] == '-' && text[1] == 'p')
839 found_probe_option = skip_keyword (tracker, probe_options, &text);
840
841 const char *option_text = text;
842 int saved_word_point = tracker.custom_word_point ();
843
844 const char *copy = text;
845
846 explicit_completion_info completion_info;
847 event_location_up location
848 = string_to_explicit_location (&copy, current_language,
849 &completion_info);
850 if (completion_info.quoted_arg_start != NULL
851 && completion_info.quoted_arg_end == NULL)
852 {
853 /* Found an unbalanced quote. */
854 tracker.set_quote_char (*completion_info.quoted_arg_start);
855 tracker.advance_custom_word_point_by (1);
87f0e720 856 }
c6756f62 857
a20714ff 858 if (completion_info.saw_explicit_location_option)
87f0e720 859 {
c6756f62 860 if (*copy != '\0')
87f0e720 861 {
c6756f62
PA
862 tracker.advance_custom_word_point_by (copy - text);
863 text = copy;
864
865 /* We found a terminator at the tail end of the string,
866 which means we're past the explicit location options. We
867 may have a keyword to complete on. If we have a whole
868 keyword, then complete whatever comes after as an
869 expression. This is mainly for the "if" keyword. If the
870 "thread" and "task" keywords gain their own completers,
871 they should be used here. */
872 int keyword = skip_keyword (tracker, linespec_keywords, &text);
873
874 if (keyword == -1)
875 {
876 complete_on_enum (tracker, linespec_keywords, text, text);
877 }
878 else
879 {
880 const char *word
881 = advance_to_expression_complete_word_point (tracker, text);
882 complete_expression (tracker, text, word);
883 }
87f0e720 884 }
c6756f62 885 else
87f0e720 886 {
c6756f62
PA
887 tracker.advance_custom_word_point_by (completion_info.last_option
888 - text);
889 text = completion_info.last_option;
890
891 complete_explicit_location (tracker, location.get (), text,
892 current_language,
893 completion_info.quoted_arg_start,
894 completion_info.quoted_arg_end);
895
87f0e720 896 }
c6756f62 897 }
a20714ff
PA
898 /* This is an address or linespec location. */
899 else if (location != NULL)
900 {
901 /* Handle non-explicit location options. */
902
903 int keyword = skip_keyword (tracker, explicit_options, &text);
904 if (keyword == -1)
905 complete_on_enum (tracker, explicit_options, text, text);
906 else
907 {
908 tracker.advance_custom_word_point_by (copy - text);
909 text = copy;
910
911 symbol_name_match_type match_type
912 = get_explicit_location (location.get ())->func_name_match_type;
913 complete_address_and_linespec_locations (tracker, text, match_type);
914 }
915 }
c6756f62
PA
916 else
917 {
a20714ff
PA
918 /* No options. */
919 complete_address_and_linespec_locations (tracker, text,
920 symbol_name_match_type::WILD);
c6756f62 921 }
87f0e720 922
c6756f62 923 /* Add matches for option names, if either:
87f0e720 924
c6756f62
PA
925 - Some completer above found some matches, but the word point did
926 not advance (e.g., "b <tab>" finds all functions, or "b -<tab>"
927 matches all objc selectors), or;
928
929 - Some completer above advanced the word point, but found no
930 matches.
931 */
932 if ((text[0] == '-' || text[0] == '\0')
933 && (!tracker.have_completions ()
934 || tracker.custom_word_point () == saved_word_point))
935 {
936 tracker.set_custom_word_point (saved_word_point);
937 text = option_text;
938
939 if (found_probe_option == -1)
940 complete_on_enum (tracker, probe_options, text, text);
941 complete_on_enum (tracker, explicit_options, text, text);
87f0e720 942 }
87f0e720
KS
943}
944
c6756f62
PA
945/* The corresponding completer_handle_brkchars
946 implementation. */
87f0e720 947
c6756f62
PA
948static void
949location_completer_handle_brkchars (struct cmd_list_element *ignore,
950 completion_tracker &tracker,
951 const char *text,
952 const char *word_ignored)
87f0e720 953{
c6756f62 954 tracker.set_use_custom_word_point (true);
87f0e720 955
c6756f62 956 location_completer (ignore, tracker, text, NULL);
87f0e720
KS
957}
958
1c71341a 959/* Helper for expression_completer which recursively adds field and
eb3ff9a5
PA
960 method names from TYPE, a struct or union type, to the OUTPUT
961 list. */
962
65d12d83 963static void
eb3ff9a5 964add_struct_fields (struct type *type, completion_list &output,
3eac2b65 965 const char *fieldname, int namelen)
65d12d83
TT
966{
967 int i;
b32d97f3 968 int computed_type_name = 0;
0d5cff50 969 const char *type_name = NULL;
65d12d83 970
f168693b 971 type = check_typedef (type);
65d12d83
TT
972 for (i = 0; i < TYPE_NFIELDS (type); ++i)
973 {
974 if (i < TYPE_N_BASECLASSES (type))
49c4e619 975 add_struct_fields (TYPE_BASECLASS (type, i),
aff410f1 976 output, fieldname, namelen);
9ae8282d 977 else if (TYPE_FIELD_NAME (type, i))
65d12d83 978 {
9ae8282d
TT
979 if (TYPE_FIELD_NAME (type, i)[0] != '\0')
980 {
aff410f1
MS
981 if (! strncmp (TYPE_FIELD_NAME (type, i),
982 fieldname, namelen))
eb3ff9a5 983 output.emplace_back (xstrdup (TYPE_FIELD_NAME (type, i)));
9ae8282d
TT
984 }
985 else if (TYPE_CODE (TYPE_FIELD_TYPE (type, i)) == TYPE_CODE_UNION)
986 {
987 /* Recurse into anonymous unions. */
49c4e619 988 add_struct_fields (TYPE_FIELD_TYPE (type, i),
aff410f1 989 output, fieldname, namelen);
9ae8282d 990 }
65d12d83
TT
991 }
992 }
1c71341a
TT
993
994 for (i = TYPE_NFN_FIELDS (type) - 1; i >= 0; --i)
995 {
0d5cff50 996 const char *name = TYPE_FN_FIELDLIST_NAME (type, i);
c5504eaf 997
1c71341a
TT
998 if (name && ! strncmp (name, fieldname, namelen))
999 {
b32d97f3
TT
1000 if (!computed_type_name)
1001 {
a737d952 1002 type_name = TYPE_NAME (type);
b32d97f3
TT
1003 computed_type_name = 1;
1004 }
1c71341a 1005 /* Omit constructors from the completion list. */
907af001 1006 if (!type_name || strcmp (type_name, name))
eb3ff9a5 1007 output.emplace_back (xstrdup (name));
1c71341a
TT
1008 }
1009 }
65d12d83
TT
1010}
1011
c45ec17c 1012/* See completer.h. */
eb3ff9a5 1013
c45ec17c 1014void
eb3ff9a5
PA
1015complete_expression (completion_tracker &tracker,
1016 const char *text, const char *word)
65d12d83 1017{
c92817ce 1018 struct type *type = NULL;
3eac2b65 1019 gdb::unique_xmalloc_ptr<char> fieldname;
2f68a895 1020 enum type_code code = TYPE_CODE_UNDEF;
65d12d83
TT
1021
1022 /* Perform a tentative parse of the expression, to see whether a
1023 field completion is required. */
a70b8144 1024 try
c92817ce 1025 {
2f68a895 1026 type = parse_expression_for_completion (text, &fieldname, &code);
c92817ce 1027 }
230d2906 1028 catch (const gdb_exception_error &except)
492d29ea 1029 {
eb3ff9a5 1030 return;
492d29ea 1031 }
492d29ea 1032
3eac2b65 1033 if (fieldname != nullptr && type)
65d12d83
TT
1034 {
1035 for (;;)
1036 {
f168693b 1037 type = check_typedef (type);
aa006118 1038 if (TYPE_CODE (type) != TYPE_CODE_PTR && !TYPE_IS_REFERENCE (type))
65d12d83
TT
1039 break;
1040 type = TYPE_TARGET_TYPE (type);
1041 }
1042
1043 if (TYPE_CODE (type) == TYPE_CODE_UNION
1044 || TYPE_CODE (type) == TYPE_CODE_STRUCT)
1045 {
eb3ff9a5 1046 completion_list result;
65d12d83 1047
3eac2b65
TT
1048 add_struct_fields (type, result, fieldname.get (),
1049 strlen (fieldname.get ()));
eb3ff9a5
PA
1050 tracker.add_completions (std::move (result));
1051 return;
65d12d83
TT
1052 }
1053 }
3eac2b65 1054 else if (fieldname != nullptr && code != TYPE_CODE_UNDEF)
2f68a895 1055 {
3eac2b65
TT
1056 collect_symbol_completion_matches_type (tracker, fieldname.get (),
1057 fieldname.get (), code);
eb3ff9a5 1058 return;
2f68a895 1059 }
65d12d83 1060
eb3ff9a5
PA
1061 complete_files_symbols (tracker, text, word);
1062}
1063
1064/* Complete on expressions. Often this means completing on symbol
1065 names, but some language parsers also have support for completing
1066 field names. */
1067
1068void
1069expression_completer (struct cmd_list_element *ignore,
1070 completion_tracker &tracker,
1071 const char *text, const char *word)
1072{
1073 complete_expression (tracker, text, word);
65d12d83
TT
1074}
1075
7d793aa9
SDJ
1076/* See definition in completer.h. */
1077
67cb5b2d
PA
1078void
1079set_rl_completer_word_break_characters (const char *break_chars)
1080{
1081 rl_completer_word_break_characters = (char *) break_chars;
1082}
1083
1084/* See definition in completer.h. */
1085
7d793aa9
SDJ
1086void
1087set_gdb_completion_word_break_characters (completer_ftype *fn)
1088{
67cb5b2d
PA
1089 const char *break_chars;
1090
7d793aa9
SDJ
1091 /* So far we are only interested in differentiating filename
1092 completers from everything else. */
1093 if (fn == filename_completer)
67cb5b2d 1094 break_chars = gdb_completer_file_name_break_characters;
7d793aa9 1095 else
67cb5b2d
PA
1096 break_chars = gdb_completer_command_word_break_characters;
1097
1098 set_rl_completer_word_break_characters (break_chars);
7d793aa9
SDJ
1099}
1100
78b13106
PA
1101/* Complete on symbols. */
1102
eb3ff9a5 1103void
78b13106 1104symbol_completer (struct cmd_list_element *ignore,
eb3ff9a5 1105 completion_tracker &tracker,
78b13106
PA
1106 const char *text, const char *word)
1107{
c6756f62 1108 collect_symbol_completion_matches (tracker, complete_symbol_mode::EXPRESSION,
b5ec771e 1109 symbol_name_match_type::EXPRESSION,
c6756f62 1110 text, word);
78b13106
PA
1111}
1112
aff410f1
MS
1113/* Here are some useful test cases for completion. FIXME: These
1114 should be put in the test suite. They should be tested with both
1115 M-? and TAB.
c5f0f3d0
FN
1116
1117 "show output-" "radix"
1118 "show output" "-radix"
1119 "p" ambiguous (commands starting with p--path, print, printf, etc.)
1120 "p " ambiguous (all symbols)
1121 "info t foo" no completions
1122 "info t " no completions
1123 "info t" ambiguous ("info target", "info terminal", etc.)
1124 "info ajksdlfk" no completions
1125 "info ajksdlfk " no completions
1126 "info" " "
1127 "info " ambiguous (all info commands)
1128 "p \"a" no completions (string constant)
1129 "p 'a" ambiguous (all symbols starting with a)
1130 "p b-a" ambiguous (all symbols starting with a)
1131 "p b-" ambiguous (all symbols)
1132 "file Make" "file" (word break hard to screw up here)
1133 "file ../gdb.stabs/we" "ird" (needs to not break word at slash)
1134 */
1135
eb3ff9a5 1136enum complete_line_internal_reason
67c296a2 1137{
eb3ff9a5 1138 /* Preliminary phase, called by gdb_completion_word_break_characters
c6756f62
PA
1139 function, is used to either:
1140
1141 #1 - Determine the set of chars that are word delimiters
1142 depending on the current command in line_buffer.
1143
1144 #2 - Manually advance RL_POINT to the "word break" point instead
1145 of letting readline do it (based on too-simple character
1146 matching).
1147
1148 Simpler completers that just pass a brkchars array to readline
1149 (#1 above) must defer generating the completions to the main
1150 phase (below). No completion list should be generated in this
1151 phase.
1152
1153 OTOH, completers that manually advance the word point(#2 above)
1154 must set "use_custom_word_point" in the tracker and generate
1155 their completion in this phase. Note that this is the convenient
1156 thing to do since they'll be parsing the input line anyway. */
67c296a2 1157 handle_brkchars,
eb3ff9a5
PA
1158
1159 /* Main phase, called by complete_line function, is used to get the
1160 list of possible completions. */
67c296a2 1161 handle_completions,
eb3ff9a5
PA
1162
1163 /* Special case when completing a 'help' command. In this case,
1164 once sub-command completions are exhausted, we simply return
1165 NULL. */
1166 handle_help,
1167};
67c296a2 1168
6e1dbf8c
PA
1169/* Helper for complete_line_internal to simplify it. */
1170
eb3ff9a5
PA
1171static void
1172complete_line_internal_normal_command (completion_tracker &tracker,
1173 const char *command, const char *word,
6e1dbf8c
PA
1174 const char *cmd_args,
1175 complete_line_internal_reason reason,
1176 struct cmd_list_element *c)
1177{
1178 const char *p = cmd_args;
1179
1180 if (c->completer == filename_completer)
1181 {
1182 /* Many commands which want to complete on file names accept
1183 several file names, as in "run foo bar >>baz". So we don't
1184 want to complete the entire text after the command, just the
1185 last word. To this end, we need to find the beginning of the
1186 file name by starting at `word' and going backwards. */
1187 for (p = word;
1188 p > command
1189 && strchr (gdb_completer_file_name_break_characters,
1190 p[-1]) == NULL;
1191 p--)
1192 ;
1193 }
1194
1195 if (reason == handle_brkchars)
1196 {
1197 completer_handle_brkchars_ftype *brkchars_fn;
1198
1199 if (c->completer_handle_brkchars != NULL)
1200 brkchars_fn = c->completer_handle_brkchars;
1201 else
1202 {
1203 brkchars_fn
1204 = (completer_handle_brkchars_func_for_completer
1205 (c->completer));
1206 }
1207
eb3ff9a5 1208 brkchars_fn (c, tracker, p, word);
6e1dbf8c
PA
1209 }
1210
1211 if (reason != handle_brkchars && c->completer != NULL)
eb3ff9a5 1212 (*c->completer) (c, tracker, p, word);
6e1dbf8c 1213}
67c296a2
PM
1214
1215/* Internal function used to handle completions.
1216
c5f0f3d0
FN
1217
1218 TEXT is the caller's idea of the "word" we are looking at.
1219
aff410f1
MS
1220 LINE_BUFFER is available to be looked at; it contains the entire
1221 text of the line. POINT is the offset in that line of the cursor.
1222 You should pretend that the line ends at POINT.
67c296a2 1223
eb3ff9a5 1224 See complete_line_internal_reason for description of REASON. */
14032a66 1225
eb3ff9a5
PA
1226static void
1227complete_line_internal_1 (completion_tracker &tracker,
1228 const char *text,
1229 const char *line_buffer, int point,
1230 complete_line_internal_reason reason)
c5f0f3d0 1231{
6f937416
PA
1232 char *tmp_command;
1233 const char *p;
ace21957 1234 int ignore_help_classes;
c5f0f3d0 1235 /* Pointer within tmp_command which corresponds to text. */
eb3ff9a5 1236 const char *word;
c5f0f3d0
FN
1237 struct cmd_list_element *c, *result_list;
1238
aff410f1
MS
1239 /* Choose the default set of word break characters to break
1240 completions. If we later find out that we are doing completions
1241 on command strings (as opposed to strings supplied by the
1242 individual command completer functions, which can be any string)
1243 then we will switch to the special word break set for command
1244 strings, which leaves out the '-' character used in some
1245 commands. */
67cb5b2d
PA
1246 set_rl_completer_word_break_characters
1247 (current_language->la_word_break_characters());
c5f0f3d0 1248
aff410f1
MS
1249 /* Decide whether to complete on a list of gdb commands or on
1250 symbols. */
83d31a92
TT
1251 tmp_command = (char *) alloca (point + 1);
1252 p = tmp_command;
c5f0f3d0 1253
ace21957
MF
1254 /* The help command should complete help aliases. */
1255 ignore_help_classes = reason != handle_help;
1256
83d31a92
TT
1257 strncpy (tmp_command, line_buffer, point);
1258 tmp_command[point] = '\0';
eb3ff9a5
PA
1259 if (reason == handle_brkchars)
1260 {
1261 gdb_assert (text == NULL);
1262 word = NULL;
1263 }
1264 else
1265 {
1266 /* Since text always contains some number of characters leading up
1267 to point, we can find the equivalent position in tmp_command
1268 by subtracting that many characters from the end of tmp_command. */
1269 word = tmp_command + point - strlen (text);
1270 }
c5f0f3d0 1271
a81aaca0
PA
1272 /* Move P up to the start of the command. */
1273 p = skip_spaces (p);
1274
1275 if (*p == '\0')
83d31a92 1276 {
a81aaca0
PA
1277 /* An empty line is ambiguous; that is, it could be any
1278 command. */
1427fe5e 1279 c = CMD_LIST_AMBIGUOUS;
83d31a92
TT
1280 result_list = 0;
1281 }
1282 else
1283 {
ace21957 1284 c = lookup_cmd_1 (&p, cmdlist, &result_list, ignore_help_classes);
83d31a92 1285 }
c5f0f3d0 1286
83d31a92
TT
1287 /* Move p up to the next interesting thing. */
1288 while (*p == ' ' || *p == '\t')
1289 {
1290 p++;
1291 }
c5f0f3d0 1292
c6756f62
PA
1293 tracker.advance_custom_word_point_by (p - tmp_command);
1294
83d31a92
TT
1295 if (!c)
1296 {
1297 /* It is an unrecognized command. So there are no
1298 possible completions. */
83d31a92 1299 }
1427fe5e 1300 else if (c == CMD_LIST_AMBIGUOUS)
83d31a92 1301 {
6f937416 1302 const char *q;
83d31a92
TT
1303
1304 /* lookup_cmd_1 advances p up to the first ambiguous thing, but
1305 doesn't advance over that thing itself. Do so now. */
1306 q = p;
1307 while (*q && (isalnum (*q) || *q == '-' || *q == '_'))
1308 ++q;
1309 if (q != tmp_command + point)
c5f0f3d0 1310 {
83d31a92
TT
1311 /* There is something beyond the ambiguous
1312 command, so there are no possible completions. For
1313 example, "info t " or "info t foo" does not complete
1314 to anything, because "info t" can be "info target" or
1315 "info terminal". */
c5f0f3d0 1316 }
83d31a92 1317 else
c5f0f3d0 1318 {
83d31a92
TT
1319 /* We're trying to complete on the command which was ambiguous.
1320 This we can deal with. */
1321 if (result_list)
c5f0f3d0 1322 {
67c296a2 1323 if (reason != handle_brkchars)
eb3ff9a5
PA
1324 complete_on_cmdlist (*result_list->prefixlist, tracker, p,
1325 word, ignore_help_classes);
c5f0f3d0
FN
1326 }
1327 else
1328 {
67c296a2 1329 if (reason != handle_brkchars)
eb3ff9a5
PA
1330 complete_on_cmdlist (cmdlist, tracker, p, word,
1331 ignore_help_classes);
c5f0f3d0 1332 }
489f0516 1333 /* Ensure that readline does the right thing with respect to
83d31a92 1334 inserting quotes. */
67cb5b2d
PA
1335 set_rl_completer_word_break_characters
1336 (gdb_completer_command_word_break_characters);
c5f0f3d0 1337 }
83d31a92
TT
1338 }
1339 else
1340 {
1341 /* We've recognized a full command. */
1342
1343 if (p == tmp_command + point)
c5f0f3d0 1344 {
aff410f1
MS
1345 /* There is no non-whitespace in the line beyond the
1346 command. */
c5f0f3d0 1347
83d31a92 1348 if (p[-1] == ' ' || p[-1] == '\t')
c5f0f3d0 1349 {
aff410f1
MS
1350 /* The command is followed by whitespace; we need to
1351 complete on whatever comes after command. */
83d31a92 1352 if (c->prefixlist)
c5f0f3d0 1353 {
83d31a92
TT
1354 /* It is a prefix command; what comes after it is
1355 a subcommand (e.g. "info "). */
67c296a2 1356 if (reason != handle_brkchars)
eb3ff9a5
PA
1357 complete_on_cmdlist (*c->prefixlist, tracker, p, word,
1358 ignore_help_classes);
c5f0f3d0 1359
489f0516 1360 /* Ensure that readline does the right thing
9c3f90bd 1361 with respect to inserting quotes. */
67cb5b2d
PA
1362 set_rl_completer_word_break_characters
1363 (gdb_completer_command_word_break_characters);
c5f0f3d0 1364 }
67c296a2 1365 else if (reason == handle_help)
eb3ff9a5 1366 ;
c5f0f3d0
FN
1367 else if (c->enums)
1368 {
67c296a2 1369 if (reason != handle_brkchars)
eb3ff9a5 1370 complete_on_enum (tracker, c->enums, p, word);
67cb5b2d
PA
1371 set_rl_completer_word_break_characters
1372 (gdb_completer_command_word_break_characters);
c5f0f3d0
FN
1373 }
1374 else
1375 {
83d31a92
TT
1376 /* It is a normal command; what comes after it is
1377 completed by the command's completer function. */
eb3ff9a5
PA
1378 complete_line_internal_normal_command (tracker,
1379 tmp_command, word, p,
1380 reason, c);
c5f0f3d0
FN
1381 }
1382 }
83d31a92
TT
1383 else
1384 {
1385 /* The command is not followed by whitespace; we need to
aff410f1 1386 complete on the command itself, e.g. "p" which is a
83d31a92
TT
1387 command itself but also can complete to "print", "ptype"
1388 etc. */
6f937416 1389 const char *q;
83d31a92
TT
1390
1391 /* Find the command we are completing on. */
1392 q = p;
1393 while (q > tmp_command)
1394 {
1395 if (isalnum (q[-1]) || q[-1] == '-' || q[-1] == '_')
1396 --q;
1397 else
1398 break;
1399 }
1400
67c296a2 1401 if (reason != handle_brkchars)
eb3ff9a5
PA
1402 complete_on_cmdlist (result_list, tracker, q, word,
1403 ignore_help_classes);
83d31a92 1404
489f0516 1405 /* Ensure that readline does the right thing
9c3f90bd 1406 with respect to inserting quotes. */
67cb5b2d
PA
1407 set_rl_completer_word_break_characters
1408 (gdb_completer_command_word_break_characters);
83d31a92
TT
1409 }
1410 }
67c296a2 1411 else if (reason == handle_help)
eb3ff9a5 1412 ;
83d31a92
TT
1413 else
1414 {
1415 /* There is non-whitespace beyond the command. */
1416
1417 if (c->prefixlist && !c->allow_unknown)
1418 {
1419 /* It is an unrecognized subcommand of a prefix command,
1420 e.g. "info adsfkdj". */
83d31a92
TT
1421 }
1422 else if (c->enums)
1423 {
67c296a2 1424 if (reason != handle_brkchars)
eb3ff9a5 1425 complete_on_enum (tracker, c->enums, p, word);
83d31a92
TT
1426 }
1427 else
1428 {
1429 /* It is a normal command. */
eb3ff9a5
PA
1430 complete_line_internal_normal_command (tracker,
1431 tmp_command, word, p,
1432 reason, c);
83d31a92
TT
1433 }
1434 }
1435 }
83d31a92 1436}
ef0b411a 1437
eb3ff9a5
PA
1438/* Wrapper around complete_line_internal_1 to handle
1439 MAX_COMPLETIONS_REACHED_ERROR. */
ef0b411a 1440
eb3ff9a5
PA
1441static void
1442complete_line_internal (completion_tracker &tracker,
1443 const char *text,
1444 const char *line_buffer, int point,
1445 complete_line_internal_reason reason)
1446{
a70b8144 1447 try
eb3ff9a5
PA
1448 {
1449 complete_line_internal_1 (tracker, text, line_buffer, point, reason);
1450 }
230d2906 1451 catch (const gdb_exception_error &except)
eb3ff9a5
PA
1452 {
1453 if (except.error != MAX_COMPLETIONS_REACHED_ERROR)
eedc3f4f 1454 throw;
eb3ff9a5
PA
1455 }
1456}
ef0b411a
GB
1457
1458/* See completer.h. */
1459
eb3ff9a5 1460int max_completions = 200;
ef0b411a 1461
eb3ff9a5
PA
1462/* Initial size of the table. It automagically grows from here. */
1463#define INITIAL_COMPLETION_HTAB_SIZE 200
ef0b411a 1464
eb3ff9a5 1465/* See completer.h. */
ef0b411a 1466
eb3ff9a5 1467completion_tracker::completion_tracker ()
ef0b411a 1468{
eb3ff9a5 1469 m_entries_hash = htab_create_alloc (INITIAL_COMPLETION_HTAB_SIZE,
459a2e4c 1470 htab_hash_string, streq_hash,
eb3ff9a5 1471 NULL, xcalloc, xfree);
ef0b411a
GB
1472}
1473
1474/* See completer.h. */
1475
c6756f62
PA
1476void
1477completion_tracker::discard_completions ()
1478{
1479 xfree (m_lowest_common_denominator);
1480 m_lowest_common_denominator = NULL;
1481
1482 m_lowest_common_denominator_unique = false;
1483
1484 m_entries_vec.clear ();
1485
1486 htab_delete (m_entries_hash);
1487 m_entries_hash = htab_create_alloc (INITIAL_COMPLETION_HTAB_SIZE,
459a2e4c 1488 htab_hash_string, streq_hash,
c6756f62
PA
1489 NULL, xcalloc, xfree);
1490}
1491
1492/* See completer.h. */
1493
eb3ff9a5 1494completion_tracker::~completion_tracker ()
ef0b411a 1495{
eb3ff9a5
PA
1496 xfree (m_lowest_common_denominator);
1497 htab_delete (m_entries_hash);
ef0b411a
GB
1498}
1499
1500/* See completer.h. */
1501
eb3ff9a5 1502bool
a207cff2
PA
1503completion_tracker::maybe_add_completion
1504 (gdb::unique_xmalloc_ptr<char> name,
a22ecf70
PA
1505 completion_match_for_lcd *match_for_lcd,
1506 const char *text, const char *word)
ef0b411a
GB
1507{
1508 void **slot;
1509
ef0b411a 1510 if (max_completions == 0)
eb3ff9a5 1511 return false;
ef0b411a 1512
eb3ff9a5
PA
1513 if (htab_elements (m_entries_hash) >= max_completions)
1514 return false;
ef0b411a 1515
eb3ff9a5
PA
1516 slot = htab_find_slot (m_entries_hash, name.get (), INSERT);
1517 if (*slot == HTAB_EMPTY_ENTRY)
1518 {
a207cff2
PA
1519 const char *match_for_lcd_str = NULL;
1520
1521 if (match_for_lcd != NULL)
1522 match_for_lcd_str = match_for_lcd->finish ();
1523
1524 if (match_for_lcd_str == NULL)
1525 match_for_lcd_str = name.get ();
ef0b411a 1526
a22ecf70
PA
1527 gdb::unique_xmalloc_ptr<char> lcd
1528 = make_completion_match_str (match_for_lcd_str, text, word);
1529
1530 recompute_lowest_common_denominator (std::move (lcd));
ef0b411a 1531
eb3ff9a5
PA
1532 *slot = name.get ();
1533 m_entries_vec.push_back (std::move (name));
1534 }
ef0b411a 1535
eb3ff9a5
PA
1536 return true;
1537}
1538
1539/* See completer.h. */
ef0b411a 1540
eb3ff9a5 1541void
a207cff2 1542completion_tracker::add_completion (gdb::unique_xmalloc_ptr<char> name,
a22ecf70
PA
1543 completion_match_for_lcd *match_for_lcd,
1544 const char *text, const char *word)
eb3ff9a5 1545{
a22ecf70 1546 if (!maybe_add_completion (std::move (name), match_for_lcd, text, word))
eb3ff9a5 1547 throw_error (MAX_COMPLETIONS_REACHED_ERROR, _("Max completions reached."));
ef0b411a
GB
1548}
1549
eb3ff9a5
PA
1550/* See completer.h. */
1551
ef0b411a 1552void
eb3ff9a5 1553completion_tracker::add_completions (completion_list &&list)
ef0b411a 1554{
eb3ff9a5
PA
1555 for (auto &candidate : list)
1556 add_completion (std::move (candidate));
ef0b411a
GB
1557}
1558
60a20c19
PA
1559/* Helper for the make_completion_match_str overloads. Returns NULL
1560 as an indication that we want MATCH_NAME exactly. It is up to the
1561 caller to xstrdup that string if desired. */
1562
1563static char *
1564make_completion_match_str_1 (const char *match_name,
1565 const char *text, const char *word)
1566{
1567 char *newobj;
1568
1569 if (word == text)
1570 {
1571 /* Return NULL as an indication that we want MATCH_NAME
1572 exactly. */
1573 return NULL;
1574 }
1575 else if (word > text)
1576 {
1577 /* Return some portion of MATCH_NAME. */
1578 newobj = xstrdup (match_name + (word - text));
1579 }
1580 else
1581 {
1582 /* Return some of WORD plus MATCH_NAME. */
1583 size_t len = strlen (match_name);
1584 newobj = (char *) xmalloc (text - word + len + 1);
1585 memcpy (newobj, word, text - word);
1586 memcpy (newobj + (text - word), match_name, len + 1);
1587 }
1588
1589 return newobj;
1590}
1591
1592/* See completer.h. */
1593
1594gdb::unique_xmalloc_ptr<char>
1595make_completion_match_str (const char *match_name,
1596 const char *text, const char *word)
1597{
1598 char *newobj = make_completion_match_str_1 (match_name, text, word);
1599 if (newobj == NULL)
1600 newobj = xstrdup (match_name);
1601 return gdb::unique_xmalloc_ptr<char> (newobj);
1602}
1603
1604/* See completer.h. */
1605
1606gdb::unique_xmalloc_ptr<char>
1607make_completion_match_str (gdb::unique_xmalloc_ptr<char> &&match_name,
1608 const char *text, const char *word)
1609{
1610 char *newobj = make_completion_match_str_1 (match_name.get (), text, word);
1611 if (newobj == NULL)
1612 return std::move (match_name);
1613 return gdb::unique_xmalloc_ptr<char> (newobj);
1614}
1615
6e035501
JV
1616/* See complete.h. */
1617
1618completion_result
1619complete (const char *line, char const **word, int *quote_char)
1620{
1621 completion_tracker tracker_handle_brkchars;
1622 completion_tracker tracker_handle_completions;
1623 completion_tracker *tracker;
1624
1625 try
1626 {
1627 *word = completion_find_completion_word (tracker_handle_brkchars,
1628 line, quote_char);
1629
1630 /* Completers that provide a custom word point in the
1631 handle_brkchars phase also compute their completions then.
1632 Completers that leave the completion word handling to readline
1633 must be called twice. */
1634 if (tracker_handle_brkchars.use_custom_word_point ())
1635 tracker = &tracker_handle_brkchars;
1636 else
1637 {
1638 complete_line (tracker_handle_completions, *word, line, strlen (line));
1639 tracker = &tracker_handle_completions;
1640 }
1641 }
1642 catch (const gdb_exception &ex)
1643 {
1644 return {};
1645 }
1646
1647 return tracker->build_completion_result (*word, *word - line, strlen (line));
1648}
1649
1650
eb3ff9a5
PA
1651/* Generate completions all at once. Does nothing if max_completions
1652 is 0. If max_completions is non-negative, this will collect at
1653 most max_completions strings.
83d31a92 1654
67c296a2
PM
1655 TEXT is the caller's idea of the "word" we are looking at.
1656
aff410f1
MS
1657 LINE_BUFFER is available to be looked at; it contains the entire
1658 text of the line.
67c296a2
PM
1659
1660 POINT is the offset in that line of the cursor. You
1661 should pretend that the line ends at POINT. */
14032a66 1662
eb3ff9a5
PA
1663void
1664complete_line (completion_tracker &tracker,
1665 const char *text, const char *line_buffer, int point)
14032a66 1666{
ef0b411a 1667 if (max_completions == 0)
eb3ff9a5
PA
1668 return;
1669 complete_line_internal (tracker, text, line_buffer, point,
1670 handle_completions);
14032a66
TT
1671}
1672
1673/* Complete on command names. Used by "help". */
6e1dbf8c 1674
eb3ff9a5 1675void
aff410f1 1676command_completer (struct cmd_list_element *ignore,
eb3ff9a5 1677 completion_tracker &tracker,
6f937416 1678 const char *text, const char *word)
14032a66 1679{
eb3ff9a5
PA
1680 complete_line_internal (tracker, word, text,
1681 strlen (text), handle_help);
67c296a2
PM
1682}
1683
6e1dbf8c
PA
1684/* The corresponding completer_handle_brkchars implementation. */
1685
1686static void
1687command_completer_handle_brkchars (struct cmd_list_element *ignore,
eb3ff9a5 1688 completion_tracker &tracker,
6e1dbf8c
PA
1689 const char *text, const char *word)
1690{
1691 set_rl_completer_word_break_characters
1692 (gdb_completer_command_word_break_characters);
1693}
1694
de0bea00
MF
1695/* Complete on signals. */
1696
eb3ff9a5 1697void
de0bea00 1698signal_completer (struct cmd_list_element *ignore,
eb3ff9a5 1699 completion_tracker &tracker,
6f937416 1700 const char *text, const char *word)
de0bea00 1701{
de0bea00 1702 size_t len = strlen (word);
570dc176 1703 int signum;
de0bea00
MF
1704 const char *signame;
1705
1706 for (signum = GDB_SIGNAL_FIRST; signum != GDB_SIGNAL_LAST; ++signum)
1707 {
1708 /* Can't handle this, so skip it. */
1709 if (signum == GDB_SIGNAL_0)
1710 continue;
1711
570dc176 1712 signame = gdb_signal_to_name ((enum gdb_signal) signum);
de0bea00
MF
1713
1714 /* Ignore the unknown signal case. */
1715 if (!signame || strcmp (signame, "?") == 0)
1716 continue;
1717
1718 if (strncasecmp (signame, word, len) == 0)
eb3ff9a5
PA
1719 {
1720 gdb::unique_xmalloc_ptr<char> copy (xstrdup (signame));
1721 tracker.add_completion (std::move (copy));
1722 }
de0bea00 1723 }
de0bea00
MF
1724}
1725
51f0e40d
AB
1726/* Bit-flags for selecting what the register and/or register-group
1727 completer should complete on. */
71c24708 1728
8d297bbf 1729enum reg_completer_target
51f0e40d
AB
1730 {
1731 complete_register_names = 0x1,
1732 complete_reggroup_names = 0x2
1733 };
8d297bbf 1734DEF_ENUM_FLAGS_TYPE (enum reg_completer_target, reg_completer_targets);
51f0e40d
AB
1735
1736/* Complete register names and/or reggroup names based on the value passed
1737 in TARGETS. At least one bit in TARGETS must be set. */
1738
eb3ff9a5
PA
1739static void
1740reg_or_group_completer_1 (completion_tracker &tracker,
51f0e40d 1741 const char *text, const char *word,
8d297bbf 1742 reg_completer_targets targets)
71c24708 1743{
71c24708
AA
1744 size_t len = strlen (word);
1745 struct gdbarch *gdbarch;
71c24708 1746 const char *name;
71c24708 1747
51f0e40d
AB
1748 gdb_assert ((targets & (complete_register_names
1749 | complete_reggroup_names)) != 0);
1750 gdbarch = get_current_arch ();
71c24708 1751
51f0e40d 1752 if ((targets & complete_register_names) != 0)
71c24708 1753 {
51f0e40d
AB
1754 int i;
1755
1756 for (i = 0;
1757 (name = user_reg_map_regnum_to_name (gdbarch, i)) != NULL;
1758 i++)
1759 {
1760 if (*name != '\0' && strncmp (word, name, len) == 0)
eb3ff9a5
PA
1761 {
1762 gdb::unique_xmalloc_ptr<char> copy (xstrdup (name));
1763 tracker.add_completion (std::move (copy));
1764 }
51f0e40d 1765 }
71c24708
AA
1766 }
1767
51f0e40d 1768 if ((targets & complete_reggroup_names) != 0)
71c24708 1769 {
51f0e40d
AB
1770 struct reggroup *group;
1771
1772 for (group = reggroup_next (gdbarch, NULL);
1773 group != NULL;
1774 group = reggroup_next (gdbarch, group))
1775 {
1776 name = reggroup_name (group);
1777 if (strncmp (word, name, len) == 0)
eb3ff9a5
PA
1778 {
1779 gdb::unique_xmalloc_ptr<char> copy (xstrdup (name));
1780 tracker.add_completion (std::move (copy));
1781 }
51f0e40d 1782 }
71c24708 1783 }
71c24708
AA
1784}
1785
51f0e40d
AB
1786/* Perform completion on register and reggroup names. */
1787
eb3ff9a5 1788void
51f0e40d 1789reg_or_group_completer (struct cmd_list_element *ignore,
eb3ff9a5 1790 completion_tracker &tracker,
51f0e40d
AB
1791 const char *text, const char *word)
1792{
eb3ff9a5
PA
1793 reg_or_group_completer_1 (tracker, text, word,
1794 (complete_register_names
1795 | complete_reggroup_names));
51f0e40d
AB
1796}
1797
1798/* Perform completion on reggroup names. */
1799
eb3ff9a5 1800void
51f0e40d 1801reggroup_completer (struct cmd_list_element *ignore,
eb3ff9a5 1802 completion_tracker &tracker,
51f0e40d
AB
1803 const char *text, const char *word)
1804{
eb3ff9a5
PA
1805 reg_or_group_completer_1 (tracker, text, word,
1806 complete_reggroup_names);
51f0e40d 1807}
71c24708 1808
6e1dbf8c
PA
1809/* The default completer_handle_brkchars implementation. */
1810
1811static void
1812default_completer_handle_brkchars (struct cmd_list_element *ignore,
eb3ff9a5 1813 completion_tracker &tracker,
6e1dbf8c
PA
1814 const char *text, const char *word)
1815{
1816 set_rl_completer_word_break_characters
1817 (current_language->la_word_break_characters ());
1818}
1819
1820/* See definition in completer.h. */
1821
1822completer_handle_brkchars_ftype *
1823completer_handle_brkchars_func_for_completer (completer_ftype *fn)
1824{
1825 if (fn == filename_completer)
1826 return filename_completer_handle_brkchars;
1827
c6756f62
PA
1828 if (fn == location_completer)
1829 return location_completer_handle_brkchars;
1830
6e1dbf8c
PA
1831 if (fn == command_completer)
1832 return command_completer_handle_brkchars;
1833
1834 return default_completer_handle_brkchars;
1835}
1836
c6756f62
PA
1837/* Used as brkchars when we want to tell readline we have a custom
1838 word point. We do that by making our rl_completion_word_break_hook
1839 set RL_POINT to the desired word point, and return the character at
1840 the word break point as the break char. This is two bytes in order
1841 to fit one break character plus the terminating null. */
1842static char gdb_custom_word_point_brkchars[2];
1843
1844/* Since rl_basic_quote_characters is not completer-specific, we save
1845 its original value here, in order to be able to restore it in
1846 gdb_rl_attempted_completion_function. */
1847static const char *gdb_org_rl_basic_quote_characters = rl_basic_quote_characters;
1848
67c296a2
PM
1849/* Get the list of chars that are considered as word breaks
1850 for the current command. */
1851
eb3ff9a5
PA
1852static char *
1853gdb_completion_word_break_characters_throw ()
67c296a2 1854{
eb3ff9a5
PA
1855 /* New completion starting. Get rid of the previous tracker and
1856 start afresh. */
1857 delete current_completion.tracker;
1858 current_completion.tracker = new completion_tracker ();
1859
1860 completion_tracker &tracker = *current_completion.tracker;
1861
1862 complete_line_internal (tracker, NULL, rl_line_buffer,
1863 rl_point, handle_brkchars);
c5504eaf 1864
c6756f62
PA
1865 if (tracker.use_custom_word_point ())
1866 {
1867 gdb_assert (tracker.custom_word_point () > 0);
1868 rl_point = tracker.custom_word_point () - 1;
1869 gdb_custom_word_point_brkchars[0] = rl_line_buffer[rl_point];
1870 rl_completer_word_break_characters = gdb_custom_word_point_brkchars;
1871 rl_completer_quote_characters = NULL;
1872
1873 /* Clear this too, so that if we're completing a quoted string,
1874 readline doesn't consider the quote character a delimiter.
1875 If we didn't do this, readline would auto-complete {b
1876 'fun<tab>} to {'b 'function()'}, i.e., add the terminating
1877 \', but, it wouldn't append the separator space either, which
1878 is not desirable. So instead we take care of appending the
1879 quote character to the LCD ourselves, in
1880 gdb_rl_attempted_completion_function. Since this global is
1881 not just completer-specific, we'll restore it back to the
1882 default in gdb_rl_attempted_completion_function. */
1883 rl_basic_quote_characters = NULL;
1884 }
1885
67c296a2 1886 return rl_completer_word_break_characters;
14032a66
TT
1887}
1888
eb3ff9a5
PA
1889char *
1890gdb_completion_word_break_characters ()
1891{
1892 /* New completion starting. */
1893 current_completion.aborted = false;
83d31a92 1894
a70b8144 1895 try
eb3ff9a5
PA
1896 {
1897 return gdb_completion_word_break_characters_throw ();
1898 }
230d2906 1899 catch (const gdb_exception &ex)
eb3ff9a5
PA
1900 {
1901 /* Set this to that gdb_rl_attempted_completion_function knows
1902 to abort early. */
1903 current_completion.aborted = true;
1904 }
83d31a92 1905
eb3ff9a5
PA
1906 return NULL;
1907}
83d31a92 1908
eb3ff9a5 1909/* See completer.h. */
83d31a92 1910
6a2c1b87
PA
1911const char *
1912completion_find_completion_word (completion_tracker &tracker, const char *text,
1913 int *quote_char)
1914{
1915 size_t point = strlen (text);
1916
1917 complete_line_internal (tracker, NULL, text, point, handle_brkchars);
1918
c6756f62
PA
1919 if (tracker.use_custom_word_point ())
1920 {
1921 gdb_assert (tracker.custom_word_point () > 0);
1922 *quote_char = tracker.quote_char ();
1923 return text + tracker.custom_word_point ();
1924 }
1925
6a2c1b87
PA
1926 gdb_rl_completion_word_info info;
1927
1928 info.word_break_characters = rl_completer_word_break_characters;
1929 info.quote_characters = gdb_completer_quote_characters;
1930 info.basic_quote_characters = rl_basic_quote_characters;
1931
1932 return gdb_rl_find_completion_word (&info, quote_char, NULL, text);
1933}
1934
1935/* See completer.h. */
1936
eb3ff9a5 1937void
a22ecf70
PA
1938completion_tracker::recompute_lowest_common_denominator
1939 (gdb::unique_xmalloc_ptr<char> &&new_match_up)
83d31a92 1940{
eb3ff9a5
PA
1941 if (m_lowest_common_denominator == NULL)
1942 {
1943 /* We don't have a lowest common denominator yet, so simply take
a22ecf70
PA
1944 the whole NEW_MATCH_UP as being it. */
1945 m_lowest_common_denominator = new_match_up.release ();
eb3ff9a5
PA
1946 m_lowest_common_denominator_unique = true;
1947 }
1948 else
83d31a92 1949 {
eb3ff9a5 1950 /* Find the common denominator between the currently-known
a22ecf70 1951 lowest common denominator and NEW_MATCH_UP. That becomes the
eb3ff9a5
PA
1952 new lowest common denominator. */
1953 size_t i;
a22ecf70 1954 const char *new_match = new_match_up.get ();
83d31a92 1955
eb3ff9a5
PA
1956 for (i = 0;
1957 (new_match[i] != '\0'
1958 && new_match[i] == m_lowest_common_denominator[i]);
1959 i++)
1960 ;
1961 if (m_lowest_common_denominator[i] != new_match[i])
83d31a92 1962 {
eb3ff9a5
PA
1963 m_lowest_common_denominator[i] = '\0';
1964 m_lowest_common_denominator_unique = false;
c5f0f3d0
FN
1965 }
1966 }
eb3ff9a5
PA
1967}
1968
c6756f62
PA
1969/* See completer.h. */
1970
1971void
1972completion_tracker::advance_custom_word_point_by (size_t len)
1973{
1974 m_custom_word_point += len;
1975}
1976
eb3ff9a5
PA
1977/* Build a new C string that is a copy of LCD with the whitespace of
1978 ORIG/ORIG_LEN preserved.
1979
1980 Say the user is completing a symbol name, with spaces, like:
1981
1982 "foo ( i"
1983
1984 and the resulting completion match is:
1985
1986 "foo(int)"
1987
1988 we want to end up with an input line like:
1989
1990 "foo ( int)"
1991 ^^^^^^^ => text from LCD [1], whitespace from ORIG preserved.
1992 ^^ => new text from LCD
1993
1994 [1] - We must take characters from the LCD instead of the original
1995 text, since some completions want to change upper/lowercase. E.g.:
c5f0f3d0 1996
eb3ff9a5 1997 "handle sig<>"
c5f0f3d0 1998
eb3ff9a5
PA
1999 completes to:
2000
2001 "handle SIG[QUIT|etc.]"
2002*/
2003
2004static char *
2005expand_preserving_ws (const char *orig, size_t orig_len,
2006 const char *lcd)
2007{
2008 const char *p_orig = orig;
2009 const char *orig_end = orig + orig_len;
2010 const char *p_lcd = lcd;
2011 std::string res;
2012
2013 while (p_orig < orig_end)
c5f0f3d0 2014 {
eb3ff9a5
PA
2015 if (*p_orig == ' ')
2016 {
2017 while (p_orig < orig_end && *p_orig == ' ')
2018 res += *p_orig++;
f1735a53 2019 p_lcd = skip_spaces (p_lcd);
eb3ff9a5
PA
2020 }
2021 else
c5f0f3d0 2022 {
eb3ff9a5
PA
2023 /* Take characters from the LCD instead of the original
2024 text, since some completions change upper/lowercase.
2025 E.g.:
2026 "handle sig<>"
2027 completes to:
2028 "handle SIG[QUIT|etc.]"
2029 */
2030 res += *p_lcd;
2031 p_orig++;
2032 p_lcd++;
c5f0f3d0
FN
2033 }
2034 }
2035
eb3ff9a5
PA
2036 while (*p_lcd != '\0')
2037 res += *p_lcd++;
2038
2039 return xstrdup (res.c_str ());
2040}
2041
2042/* See completer.h. */
2043
2044completion_result
2045completion_tracker::build_completion_result (const char *text,
2046 int start, int end)
2047{
2048 completion_list &list = m_entries_vec; /* The completions. */
2049
2050 if (list.empty ())
2051 return {};
2052
2053 /* +1 for the LCD, and +1 for NULL termination. */
2054 char **match_list = XNEWVEC (char *, 1 + list.size () + 1);
2055
2056 /* Build replacement word, based on the LCD. */
2057
2058 match_list[0]
2059 = expand_preserving_ws (text, end - start,
2060 m_lowest_common_denominator);
2061
2062 if (m_lowest_common_denominator_unique)
2063 {
c6756f62
PA
2064 /* We don't rely on readline appending the quote char as
2065 delimiter as then readline wouldn't append the ' ' after the
2066 completion. */
896a7aa6 2067 char buf[2] = { (char) quote_char () };
c6756f62
PA
2068
2069 match_list[0] = reconcat (match_list[0], match_list[0],
2070 buf, (char *) NULL);
eb3ff9a5
PA
2071 match_list[1] = NULL;
2072
c45ec17c
PA
2073 /* If the tracker wants to, or we already have a space at the
2074 end of the match, tell readline to skip appending
2075 another. */
eb3ff9a5 2076 bool completion_suppress_append
c45ec17c
PA
2077 = (suppress_append_ws ()
2078 || match_list[0][strlen (match_list[0]) - 1] == ' ');
eb3ff9a5
PA
2079
2080 return completion_result (match_list, 1, completion_suppress_append);
2081 }
2082 else
2083 {
2084 int ix;
2085
2086 for (ix = 0; ix < list.size (); ++ix)
2087 match_list[ix + 1] = list[ix].release ();
2088 match_list[ix + 1] = NULL;
2089
2090 return completion_result (match_list, list.size (), false);
2091 }
2092}
2093
2094/* See completer.h */
2095
2096completion_result::completion_result ()
2097 : match_list (NULL), number_matches (0),
2098 completion_suppress_append (false)
2099{}
2100
2101/* See completer.h */
2102
2103completion_result::completion_result (char **match_list_,
2104 size_t number_matches_,
2105 bool completion_suppress_append_)
2106 : match_list (match_list_),
2107 number_matches (number_matches_),
2108 completion_suppress_append (completion_suppress_append_)
2109{}
2110
2111/* See completer.h */
2112
2113completion_result::~completion_result ()
2114{
2115 reset_match_list ();
2116}
2117
2118/* See completer.h */
2119
2120completion_result::completion_result (completion_result &&rhs)
2121{
2122 if (this == &rhs)
2123 return;
2124
2125 reset_match_list ();
2126 match_list = rhs.match_list;
2127 rhs.match_list = NULL;
2128 number_matches = rhs.number_matches;
2129 rhs.number_matches = 0;
2130}
2131
2132/* See completer.h */
2133
2134char **
2135completion_result::release_match_list ()
2136{
2137 char **ret = match_list;
2138 match_list = NULL;
2139 return ret;
2140}
2141
eb3ff9a5
PA
2142/* See completer.h */
2143
2144void
2145completion_result::sort_match_list ()
2146{
2147 if (number_matches > 1)
2148 {
2149 /* Element 0 is special (it's the common prefix), leave it
2150 be. */
2151 std::sort (&match_list[1],
2152 &match_list[number_matches + 1],
2153 compare_cstrings);
2154 }
2155}
2156
2157/* See completer.h */
2158
2159void
2160completion_result::reset_match_list ()
2161{
2162 if (match_list != NULL)
2163 {
2164 for (char **p = match_list; *p != NULL; p++)
2165 xfree (*p);
2166 xfree (match_list);
2167 match_list = NULL;
2168 }
2169}
2170
2171/* Helper for gdb_rl_attempted_completion_function, which does most of
2172 the work. This is called by readline to build the match list array
2173 and to determine the lowest common denominator. The real matches
2174 list starts at match[1], while match[0] is the slot holding
2175 readline's idea of the lowest common denominator of all matches,
2176 which is what readline replaces the completion "word" with.
2177
2178 TEXT is the caller's idea of the "word" we are looking at, as
2179 computed in the handle_brkchars phase.
2180
2181 START is the offset from RL_LINE_BUFFER where TEXT starts. END is
2182 the offset from RL_LINE_BUFFER where TEXT ends (i.e., where
2183 rl_point is).
2184
2185 You should thus pretend that the line ends at END (relative to
2186 RL_LINE_BUFFER).
2187
2188 RL_LINE_BUFFER contains the entire text of the line. RL_POINT is
2189 the offset in that line of the cursor. You should pretend that the
2190 line ends at POINT.
2191
2192 Returns NULL if there are no completions. */
2193
2194static char **
2195gdb_rl_attempted_completion_function_throw (const char *text, int start, int end)
2196{
c6756f62
PA
2197 /* Completers that provide a custom word point in the
2198 handle_brkchars phase also compute their completions then.
2199 Completers that leave the completion word handling to readline
2200 must be called twice. If rl_point (i.e., END) is at column 0,
2201 then readline skips the handle_brkchars phase, and so we create a
2202 tracker now in that case too. */
2203 if (end == 0 || !current_completion.tracker->use_custom_word_point ())
2204 {
2205 delete current_completion.tracker;
2206 current_completion.tracker = new completion_tracker ();
eb3ff9a5 2207
c6756f62
PA
2208 complete_line (*current_completion.tracker, text,
2209 rl_line_buffer, rl_point);
2210 }
c5f0f3d0 2211
eb3ff9a5
PA
2212 completion_tracker &tracker = *current_completion.tracker;
2213
2214 completion_result result
2215 = tracker.build_completion_result (text, start, end);
2216
2217 rl_completion_suppress_append = result.completion_suppress_append;
2218 return result.release_match_list ();
2219}
2220
2221/* Function installed as "rl_attempted_completion_function" readline
2222 hook. Wrapper around gdb_rl_attempted_completion_function_throw
2223 that catches C++ exceptions, which can't cross readline. */
2224
2225char **
2226gdb_rl_attempted_completion_function (const char *text, int start, int end)
2227{
c6756f62
PA
2228 /* Restore globals that might have been tweaked in
2229 gdb_completion_word_break_characters. */
2230 rl_basic_quote_characters = gdb_org_rl_basic_quote_characters;
2231
eb3ff9a5
PA
2232 /* If we end up returning NULL, either on error, or simple because
2233 there are no matches, inhibit readline's default filename
2234 completer. */
2235 rl_attempted_completion_over = 1;
2236
2237 /* If the handle_brkchars phase was aborted, don't try
2238 completing. */
2239 if (current_completion.aborted)
2240 return NULL;
2241
a70b8144 2242 try
eb3ff9a5
PA
2243 {
2244 return gdb_rl_attempted_completion_function_throw (text, start, end);
2245 }
230d2906 2246 catch (const gdb_exception &ex)
eb3ff9a5
PA
2247 {
2248 }
eb3ff9a5
PA
2249
2250 return NULL;
c5f0f3d0 2251}
4e87b832
KD
2252
2253/* Skip over the possibly quoted word STR (as defined by the quote
b021a221
MS
2254 characters QUOTECHARS and the word break characters BREAKCHARS).
2255 Returns pointer to the location after the "word". If either
2256 QUOTECHARS or BREAKCHARS is NULL, use the same values used by the
2257 completer. */
c5f0f3d0 2258
d7561cbb
KS
2259const char *
2260skip_quoted_chars (const char *str, const char *quotechars,
2261 const char *breakchars)
c5f0f3d0
FN
2262{
2263 char quote_char = '\0';
d7561cbb 2264 const char *scan;
c5f0f3d0 2265
4e87b832
KD
2266 if (quotechars == NULL)
2267 quotechars = gdb_completer_quote_characters;
2268
2269 if (breakchars == NULL)
51065942 2270 breakchars = current_language->la_word_break_characters();
4e87b832 2271
c5f0f3d0
FN
2272 for (scan = str; *scan != '\0'; scan++)
2273 {
2274 if (quote_char != '\0')
2275 {
9c3f90bd 2276 /* Ignore everything until the matching close quote char. */
c5f0f3d0
FN
2277 if (*scan == quote_char)
2278 {
9c3f90bd 2279 /* Found matching close quote. */
c5f0f3d0
FN
2280 scan++;
2281 break;
2282 }
2283 }
4e87b832 2284 else if (strchr (quotechars, *scan))
c5f0f3d0 2285 {
aff410f1 2286 /* Found start of a quoted string. */
c5f0f3d0
FN
2287 quote_char = *scan;
2288 }
4e87b832 2289 else if (strchr (breakchars, *scan))
c5f0f3d0
FN
2290 {
2291 break;
2292 }
2293 }
4e87b832 2294
c5f0f3d0
FN
2295 return (scan);
2296}
2297
4e87b832
KD
2298/* Skip over the possibly quoted word STR (as defined by the quote
2299 characters and word break characters used by the completer).
9c3f90bd 2300 Returns pointer to the location after the "word". */
4e87b832 2301
d7561cbb
KS
2302const char *
2303skip_quoted (const char *str)
4e87b832
KD
2304{
2305 return skip_quoted_chars (str, NULL, NULL);
2306}
ef0b411a
GB
2307
2308/* Return a message indicating that the maximum number of completions
2309 has been reached and that there may be more. */
2310
2311const char *
2312get_max_completions_reached_message (void)
2313{
2314 return _("*** List may be truncated, max-completions reached. ***");
2315}
82083d6d
DE
2316\f
2317/* GDB replacement for rl_display_match_list.
2318 Readline doesn't provide a clean interface for TUI(curses).
2319 A hack previously used was to send readline's rl_outstream through a pipe
2320 and read it from the event loop. Bleah. IWBN if readline abstracted
2321 away all the necessary bits, and this is what this code does. It
2322 replicates the parts of readline we need and then adds an abstraction
2323 layer, currently implemented as struct match_list_displayer, so that both
2324 CLI and TUI can use it. We copy all this readline code to minimize
2325 GDB-specific mods to readline. Once this code performs as desired then
2326 we can submit it to the readline maintainers.
2327
2328 N.B. A lot of the code is the way it is in order to minimize differences
2329 from readline's copy. */
2330
2331/* Not supported here. */
2332#undef VISIBLE_STATS
2333
2334#if defined (HANDLE_MULTIBYTE)
2335#define MB_INVALIDCH(x) ((x) == (size_t)-1 || (x) == (size_t)-2)
2336#define MB_NULLWCH(x) ((x) == 0)
2337#endif
2338
2339#define ELLIPSIS_LEN 3
2340
2341/* gdb version of readline/complete.c:get_y_or_n.
2342 'y' -> returns 1, and 'n' -> returns 0.
2343 Also supported: space == 'y', RUBOUT == 'n', ctrl-g == start over.
2344 If FOR_PAGER is non-zero, then also supported are:
2345 NEWLINE or RETURN -> returns 2, and 'q' -> returns 0. */
2346
2347static int
2348gdb_get_y_or_n (int for_pager, const struct match_list_displayer *displayer)
2349{
2350 int c;
2351
2352 for (;;)
2353 {
2354 RL_SETSTATE (RL_STATE_MOREINPUT);
2355 c = displayer->read_key (displayer);
2356 RL_UNSETSTATE (RL_STATE_MOREINPUT);
2357
2358 if (c == 'y' || c == 'Y' || c == ' ')
2359 return 1;
2360 if (c == 'n' || c == 'N' || c == RUBOUT)
2361 return 0;
2362 if (c == ABORT_CHAR || c < 0)
2363 {
2364 /* Readline doesn't erase_entire_line here, but without it the
2365 --More-- prompt isn't erased and neither is the text entered
2366 thus far redisplayed. */
2367 displayer->erase_entire_line (displayer);
2368 /* Note: The arguments to rl_abort are ignored. */
2369 rl_abort (0, 0);
2370 }
2371 if (for_pager && (c == NEWLINE || c == RETURN))
2372 return 2;
2373 if (for_pager && (c == 'q' || c == 'Q'))
2374 return 0;
2375 displayer->beep (displayer);
2376 }
2377}
2378
2379/* Pager function for tab-completion.
2380 This is based on readline/complete.c:_rl_internal_pager.
2381 LINES is the number of lines of output displayed thus far.
2382 Returns:
2383 -1 -> user pressed 'n' or equivalent,
2384 0 -> user pressed 'y' or equivalent,
2385 N -> user pressed NEWLINE or equivalent and N is LINES - 1. */
2386
2387static int
2388gdb_display_match_list_pager (int lines,
2389 const struct match_list_displayer *displayer)
2390{
2391 int i;
2392
2393 displayer->puts (displayer, "--More--");
2394 displayer->flush (displayer);
2395 i = gdb_get_y_or_n (1, displayer);
2396 displayer->erase_entire_line (displayer);
2397 if (i == 0)
2398 return -1;
2399 else if (i == 2)
2400 return (lines - 1);
2401 else
2402 return 0;
2403}
2404
2405/* Return non-zero if FILENAME is a directory.
2406 Based on readline/complete.c:path_isdir. */
2407
2408static int
2409gdb_path_isdir (const char *filename)
2410{
2411 struct stat finfo;
2412
2413 return (stat (filename, &finfo) == 0 && S_ISDIR (finfo.st_mode));
2414}
2415
2416/* Return the portion of PATHNAME that should be output when listing
2417 possible completions. If we are hacking filename completion, we
2418 are only interested in the basename, the portion following the
2419 final slash. Otherwise, we return what we were passed. Since
2420 printing empty strings is not very informative, if we're doing
2421 filename completion, and the basename is the empty string, we look
2422 for the previous slash and return the portion following that. If
2423 there's no previous slash, we just return what we were passed.
2424
2425 Based on readline/complete.c:printable_part. */
2426
2427static char *
2428gdb_printable_part (char *pathname)
2429{
2430 char *temp, *x;
2431
2432 if (rl_filename_completion_desired == 0) /* don't need to do anything */
2433 return (pathname);
2434
2435 temp = strrchr (pathname, '/');
5836a818 2436#if defined (__MSDOS__)
82083d6d
DE
2437 if (temp == 0 && ISALPHA ((unsigned char)pathname[0]) && pathname[1] == ':')
2438 temp = pathname + 1;
2439#endif
2440
2441 if (temp == 0 || *temp == '\0')
2442 return (pathname);
2443 /* If the basename is NULL, we might have a pathname like '/usr/src/'.
2444 Look for a previous slash and, if one is found, return the portion
2445 following that slash. If there's no previous slash, just return the
2446 pathname we were passed. */
2447 else if (temp[1] == '\0')
2448 {
2449 for (x = temp - 1; x > pathname; x--)
2450 if (*x == '/')
2451 break;
2452 return ((*x == '/') ? x + 1 : pathname);
2453 }
2454 else
2455 return ++temp;
2456}
2457
2458/* Compute width of STRING when displayed on screen by print_filename.
2459 Based on readline/complete.c:fnwidth. */
2460
2461static int
2462gdb_fnwidth (const char *string)
2463{
2464 int width, pos;
2465#if defined (HANDLE_MULTIBYTE)
2466 mbstate_t ps;
2467 int left, w;
2468 size_t clen;
2469 wchar_t wc;
2470
2471 left = strlen (string) + 1;
2472 memset (&ps, 0, sizeof (mbstate_t));
2473#endif
2474
2475 width = pos = 0;
2476 while (string[pos])
2477 {
2478 if (CTRL_CHAR (string[pos]) || string[pos] == RUBOUT)
2479 {
2480 width += 2;
2481 pos++;
2482 }
2483 else
2484 {
2485#if defined (HANDLE_MULTIBYTE)
2486 clen = mbrtowc (&wc, string + pos, left - pos, &ps);
2487 if (MB_INVALIDCH (clen))
2488 {
2489 width++;
2490 pos++;
2491 memset (&ps, 0, sizeof (mbstate_t));
2492 }
2493 else if (MB_NULLWCH (clen))
2494 break;
2495 else
2496 {
2497 pos += clen;
2498 w = wcwidth (wc);
2499 width += (w >= 0) ? w : 1;
2500 }
2501#else
2502 width++;
2503 pos++;
2504#endif
2505 }
2506 }
2507
2508 return width;
2509}
2510
2511/* Print TO_PRINT, one matching completion.
2512 PREFIX_BYTES is number of common prefix bytes.
2513 Based on readline/complete.c:fnprint. */
2514
2515static int
2516gdb_fnprint (const char *to_print, int prefix_bytes,
2517 const struct match_list_displayer *displayer)
2518{
2519 int printed_len, w;
2520 const char *s;
2521#if defined (HANDLE_MULTIBYTE)
2522 mbstate_t ps;
2523 const char *end;
2524 size_t tlen;
2525 int width;
2526 wchar_t wc;
2527
2528 end = to_print + strlen (to_print) + 1;
2529 memset (&ps, 0, sizeof (mbstate_t));
2530#endif
2531
2532 printed_len = 0;
2533
2534 /* Don't print only the ellipsis if the common prefix is one of the
2535 possible completions */
2536 if (to_print[prefix_bytes] == '\0')
2537 prefix_bytes = 0;
2538
2539 if (prefix_bytes)
2540 {
2541 char ellipsis;
2542
2543 ellipsis = (to_print[prefix_bytes] == '.') ? '_' : '.';
2544 for (w = 0; w < ELLIPSIS_LEN; w++)
2545 displayer->putch (displayer, ellipsis);
2546 printed_len = ELLIPSIS_LEN;
2547 }
2548
2549 s = to_print + prefix_bytes;
2550 while (*s)
2551 {
2552 if (CTRL_CHAR (*s))
2553 {
2554 displayer->putch (displayer, '^');
2555 displayer->putch (displayer, UNCTRL (*s));
2556 printed_len += 2;
2557 s++;
2558#if defined (HANDLE_MULTIBYTE)
2559 memset (&ps, 0, sizeof (mbstate_t));
2560#endif
2561 }
2562 else if (*s == RUBOUT)
2563 {
2564 displayer->putch (displayer, '^');
2565 displayer->putch (displayer, '?');
2566 printed_len += 2;
2567 s++;
2568#if defined (HANDLE_MULTIBYTE)
2569 memset (&ps, 0, sizeof (mbstate_t));
2570#endif
2571 }
2572 else
2573 {
2574#if defined (HANDLE_MULTIBYTE)
2575 tlen = mbrtowc (&wc, s, end - s, &ps);
2576 if (MB_INVALIDCH (tlen))
2577 {
2578 tlen = 1;
2579 width = 1;
2580 memset (&ps, 0, sizeof (mbstate_t));
2581 }
2582 else if (MB_NULLWCH (tlen))
2583 break;
2584 else
2585 {
2586 w = wcwidth (wc);
2587 width = (w >= 0) ? w : 1;
2588 }
2589 for (w = 0; w < tlen; ++w)
2590 displayer->putch (displayer, s[w]);
2591 s += tlen;
2592 printed_len += width;
2593#else
2594 displayer->putch (displayer, *s);
2595 s++;
2596 printed_len++;
2597#endif
2598 }
2599 }
2600
2601 return printed_len;
2602}
2603
2604/* Output TO_PRINT to rl_outstream. If VISIBLE_STATS is defined and we
2605 are using it, check for and output a single character for `special'
2606 filenames. Return the number of characters we output.
2607 Based on readline/complete.c:print_filename. */
2608
2609static int
2610gdb_print_filename (char *to_print, char *full_pathname, int prefix_bytes,
2611 const struct match_list_displayer *displayer)
2612{
2613 int printed_len, extension_char, slen, tlen;
a121b7c1
PA
2614 char *s, c, *new_full_pathname;
2615 const char *dn;
82083d6d
DE
2616 extern int _rl_complete_mark_directories;
2617
2618 extension_char = 0;
2619 printed_len = gdb_fnprint (to_print, prefix_bytes, displayer);
2620
2621#if defined (VISIBLE_STATS)
2622 if (rl_filename_completion_desired && (rl_visible_stats || _rl_complete_mark_directories))
2623#else
2624 if (rl_filename_completion_desired && _rl_complete_mark_directories)
2625#endif
2626 {
2627 /* If to_print != full_pathname, to_print is the basename of the
2628 path passed. In this case, we try to expand the directory
2629 name before checking for the stat character. */
2630 if (to_print != full_pathname)
2631 {
2632 /* Terminate the directory name. */
2633 c = to_print[-1];
2634 to_print[-1] = '\0';
2635
2636 /* If setting the last slash in full_pathname to a NUL results in
2637 full_pathname being the empty string, we are trying to complete
2638 files in the root directory. If we pass a null string to the
2639 bash directory completion hook, for example, it will expand it
2640 to the current directory. We just want the `/'. */
2641 if (full_pathname == 0 || *full_pathname == 0)
2642 dn = "/";
2643 else if (full_pathname[0] != '/')
2644 dn = full_pathname;
2645 else if (full_pathname[1] == 0)
2646 dn = "//"; /* restore trailing slash to `//' */
2647 else if (full_pathname[1] == '/' && full_pathname[2] == 0)
2648 dn = "/"; /* don't turn /// into // */
2649 else
2650 dn = full_pathname;
2651 s = tilde_expand (dn);
2652 if (rl_directory_completion_hook)
2653 (*rl_directory_completion_hook) (&s);
2654
2655 slen = strlen (s);
2656 tlen = strlen (to_print);
2657 new_full_pathname = (char *)xmalloc (slen + tlen + 2);
2658 strcpy (new_full_pathname, s);
2659 if (s[slen - 1] == '/')
2660 slen--;
2661 else
2662 new_full_pathname[slen] = '/';
2663 new_full_pathname[slen] = '/';
2664 strcpy (new_full_pathname + slen + 1, to_print);
2665
2666#if defined (VISIBLE_STATS)
2667 if (rl_visible_stats)
2668 extension_char = stat_char (new_full_pathname);
2669 else
2670#endif
2671 if (gdb_path_isdir (new_full_pathname))
2672 extension_char = '/';
2673
2674 xfree (new_full_pathname);
2675 to_print[-1] = c;
2676 }
2677 else
2678 {
2679 s = tilde_expand (full_pathname);
2680#if defined (VISIBLE_STATS)
2681 if (rl_visible_stats)
2682 extension_char = stat_char (s);
2683 else
2684#endif
2685 if (gdb_path_isdir (s))
2686 extension_char = '/';
2687 }
2688
2689 xfree (s);
2690 if (extension_char)
2691 {
2692 displayer->putch (displayer, extension_char);
2693 printed_len++;
2694 }
2695 }
2696
2697 return printed_len;
2698}
2699
2700/* GDB version of readline/complete.c:complete_get_screenwidth. */
2701
2702static int
2703gdb_complete_get_screenwidth (const struct match_list_displayer *displayer)
2704{
2705 /* Readline has other stuff here which it's not clear we need. */
2706 return displayer->width;
2707}
2708
56000a98
PA
2709extern int _rl_completion_prefix_display_length;
2710extern int _rl_print_completions_horizontally;
2711
2712EXTERN_C int _rl_qsort_string_compare (const void *, const void *);
2713typedef int QSFUNC (const void *, const void *);
2714
82083d6d 2715/* GDB version of readline/complete.c:rl_display_match_list.
ef0b411a
GB
2716 See gdb_display_match_list for a description of MATCHES, LEN, MAX.
2717 Returns non-zero if all matches are displayed. */
82083d6d 2718
ef0b411a 2719static int
82083d6d
DE
2720gdb_display_match_list_1 (char **matches, int len, int max,
2721 const struct match_list_displayer *displayer)
2722{
2723 int count, limit, printed_len, lines, cols;
2724 int i, j, k, l, common_length, sind;
2725 char *temp, *t;
2726 int page_completions = displayer->height != INT_MAX && pagination_enabled;
82083d6d
DE
2727
2728 /* Find the length of the prefix common to all items: length as displayed
2729 characters (common_length) and as a byte index into the matches (sind) */
2730 common_length = sind = 0;
2731 if (_rl_completion_prefix_display_length > 0)
2732 {
2733 t = gdb_printable_part (matches[0]);
2734 temp = strrchr (t, '/');
2735 common_length = temp ? gdb_fnwidth (temp) : gdb_fnwidth (t);
2736 sind = temp ? strlen (temp) : strlen (t);
2737
2738 if (common_length > _rl_completion_prefix_display_length && common_length > ELLIPSIS_LEN)
2739 max -= common_length - ELLIPSIS_LEN;
2740 else
2741 common_length = sind = 0;
2742 }
2743
2744 /* How many items of MAX length can we fit in the screen window? */
2745 cols = gdb_complete_get_screenwidth (displayer);
2746 max += 2;
2747 limit = cols / max;
2748 if (limit != 1 && (limit * max == cols))
2749 limit--;
2750
2751 /* If cols == 0, limit will end up -1 */
2752 if (cols < displayer->width && limit < 0)
2753 limit = 1;
2754
2755 /* Avoid a possible floating exception. If max > cols,
2756 limit will be 0 and a divide-by-zero fault will result. */
2757 if (limit == 0)
2758 limit = 1;
2759
2760 /* How many iterations of the printing loop? */
2761 count = (len + (limit - 1)) / limit;
2762
2763 /* Watch out for special case. If LEN is less than LIMIT, then
2764 just do the inner printing loop.
2765 0 < len <= limit implies count = 1. */
2766
2767 /* Sort the items if they are not already sorted. */
2768 if (rl_ignore_completion_duplicates == 0 && rl_sort_completion_matches)
2769 qsort (matches + 1, len, sizeof (char *), (QSFUNC *)_rl_qsort_string_compare);
2770
2771 displayer->crlf (displayer);
2772
2773 lines = 0;
2774 if (_rl_print_completions_horizontally == 0)
2775 {
2776 /* Print the sorted items, up-and-down alphabetically, like ls. */
2777 for (i = 1; i <= count; i++)
2778 {
2779 for (j = 0, l = i; j < limit; j++)
2780 {
2781 if (l > len || matches[l] == 0)
2782 break;
2783 else
2784 {
2785 temp = gdb_printable_part (matches[l]);
2786 printed_len = gdb_print_filename (temp, matches[l], sind,
2787 displayer);
2788
2789 if (j + 1 < limit)
2790 for (k = 0; k < max - printed_len; k++)
2791 displayer->putch (displayer, ' ');
2792 }
2793 l += count;
2794 }
2795 displayer->crlf (displayer);
2796 lines++;
2797 if (page_completions && lines >= (displayer->height - 1) && i < count)
2798 {
2799 lines = gdb_display_match_list_pager (lines, displayer);
2800 if (lines < 0)
ef0b411a 2801 return 0;
82083d6d
DE
2802 }
2803 }
2804 }
2805 else
2806 {
2807 /* Print the sorted items, across alphabetically, like ls -x. */
2808 for (i = 1; matches[i]; i++)
2809 {
2810 temp = gdb_printable_part (matches[i]);
2811 printed_len = gdb_print_filename (temp, matches[i], sind, displayer);
2812 /* Have we reached the end of this line? */
2813 if (matches[i+1])
2814 {
2815 if (i && (limit > 1) && (i % limit) == 0)
2816 {
2817 displayer->crlf (displayer);
2818 lines++;
2819 if (page_completions && lines >= displayer->height - 1)
2820 {
2821 lines = gdb_display_match_list_pager (lines, displayer);
2822 if (lines < 0)
ef0b411a 2823 return 0;
82083d6d
DE
2824 }
2825 }
2826 else
2827 for (k = 0; k < max - printed_len; k++)
2828 displayer->putch (displayer, ' ');
2829 }
2830 }
2831 displayer->crlf (displayer);
2832 }
ef0b411a
GB
2833
2834 return 1;
82083d6d
DE
2835}
2836
2837/* Utility for displaying completion list matches, used by both CLI and TUI.
2838
2839 MATCHES is the list of strings, in argv format, LEN is the number of
05cdcf3d
DE
2840 strings in MATCHES, and MAX is the length of the longest string in
2841 MATCHES. */
82083d6d
DE
2842
2843void
2844gdb_display_match_list (char **matches, int len, int max,
2845 const struct match_list_displayer *displayer)
2846{
ef0b411a
GB
2847 /* Readline will never call this if complete_line returned NULL. */
2848 gdb_assert (max_completions != 0);
2849
2850 /* complete_line will never return more than this. */
2851 if (max_completions > 0)
2852 gdb_assert (len <= max_completions);
2853
82083d6d
DE
2854 if (rl_completion_query_items > 0 && len >= rl_completion_query_items)
2855 {
2856 char msg[100];
2857
2858 /* We can't use *query here because they wait for <RET> which is
2859 wrong here. This follows the readline version as closely as possible
2860 for compatibility's sake. See readline/complete.c. */
2861
2862 displayer->crlf (displayer);
2863
2864 xsnprintf (msg, sizeof (msg),
2865 "Display all %d possibilities? (y or n)", len);
2866 displayer->puts (displayer, msg);
2867 displayer->flush (displayer);
2868
2869 if (gdb_get_y_or_n (0, displayer) == 0)
2870 {
2871 displayer->crlf (displayer);
2872 return;
2873 }
2874 }
2875
ef0b411a
GB
2876 if (gdb_display_match_list_1 (matches, len, max, displayer))
2877 {
2878 /* Note: MAX_COMPLETIONS may be -1 or zero, but LEN is always > 0. */
2879 if (len == max_completions)
2880 {
2881 /* The maximum number of completions has been reached. Warn the user
2882 that there may be more. */
2883 const char *message = get_max_completions_reached_message ();
2884
2885 displayer->puts (displayer, message);
2886 displayer->crlf (displayer);
2887 }
2888 }
2889}
ef0b411a
GB
2890
2891void
2892_initialize_completer (void)
2893{
2894 add_setshow_zuinteger_unlimited_cmd ("max-completions", no_class,
2895 &max_completions, _("\
2896Set maximum number of completion candidates."), _("\
2897Show maximum number of completion candidates."), _("\
2898Use this to limit the number of candidates considered\n\
2899during completion. Specifying \"unlimited\" or -1\n\
2900disables limiting. Note that setting either no limit or\n\
2901a very large limit can make completion slow."),
2902 NULL, NULL, &setlist, &showlist);
82083d6d 2903}