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