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