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