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