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