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