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