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