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