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