* completer.c (command_completer): New function.
[platform/upstream/binutils.git] / gdb / completer.c
1 /* Line completion stuff for GDB, the GNU debugger.
2    Copyright 2000, 2001 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 2 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, write to the Free Software
18    Foundation, Inc., 59 Temple Place - Suite 330,
19    Boston, MA 02111-1307, USA.  */
20
21 #include "defs.h"
22 #include "symtab.h"
23 #include "gdbtypes.h"
24 #include "expression.h"
25 #include "filenames.h"          /* for DOSish file names */
26
27 /* FIXME: This is needed because of lookup_cmd_1().
28    We should be calling a hook instead so we eliminate the CLI dependency. */
29 #include "gdbcmd.h"
30
31 /* Needed for rl_completer_word_break_characters() and for
32    filename_completion_function.  */
33 #include <readline/readline.h>
34
35 /* readline defines this.  */
36 #undef savestring
37
38 #include "completer.h"
39
40 /* Prototypes for local functions */
41 char *line_completion_function (char *text, int matches, char *line_buffer,
42                                 int point);
43
44 /* readline uses the word breaks for two things:
45    (1) In figuring out where to point the TEXT parameter to the
46    rl_completion_entry_function.  Since we don't use TEXT for much,
47    it doesn't matter a lot what the word breaks are for this purpose, but
48    it does affect how much stuff M-? lists.
49    (2) If one of the matches contains a word break character, readline
50    will quote it.  That's why we switch between
51    gdb_completer_word_break_characters and
52    gdb_completer_command_word_break_characters.  I'm not sure when
53    we need this behavior (perhaps for funky characters in C++ symbols?).  */
54
55 /* Variables which are necessary for fancy command line editing.  */
56 static char *gdb_completer_word_break_characters =
57 " \t\n!@#$%^&*()+=|~`}{[]\"';:?/>.<,-";
58
59 /* When completing on command names, we remove '-' from the list of
60    word break characters, since we use it in command names.  If the
61    readline library sees one in any of the current completion strings,
62    it thinks that the string needs to be quoted and automatically supplies
63    a leading quote. */
64 static char *gdb_completer_command_word_break_characters =
65 " \t\n!@#$%^&*()+=|~`}{[]\"';:?/>.<,";
66
67 /* When completing on file names, we remove from the list of word
68    break characters any characters that are commonly used in file
69    names, such as '-', '+', '~', etc.  Otherwise, readline displays
70    incorrect completion candidates.  */
71 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
72 /* MS-DOS and MS-Windows use colon as part of the drive spec, and most
73    programs support @foo style response files.  */
74 static char *gdb_completer_file_name_break_characters = " \t\n*|\"';?><@";
75 #else
76 static char *gdb_completer_file_name_break_characters = " \t\n*|\"';:?><";
77 #endif
78
79 /* These are used when completing on locations, which can mix file
80    names and symbol names separated by a colon.  */
81 static char *gdb_completer_loc_break_characters = " \t\n*|\"';:?><,";
82
83 /* Characters that can be used to quote completion strings.  Note that we
84    can't include '"' because the gdb C parser treats such quoted sequences
85    as strings. */
86 static char *gdb_completer_quote_characters = "'";
87 \f
88 /* Accessor for some completer data that may interest other files. */
89
90 char *
91 get_gdb_completer_word_break_characters (void)
92 {
93   return gdb_completer_word_break_characters;
94 }
95
96 char *
97 get_gdb_completer_quote_characters (void)
98 {
99   return gdb_completer_quote_characters;
100 }
101
102 /* Line completion interface function for readline.  */
103
104 char *
105 readline_line_completion_function (char *text, int matches)
106 {
107   return line_completion_function (text, matches, rl_line_buffer, rl_point);
108 }
109
110 /* This can be used for functions which don't want to complete on symbols
111    but don't want to complete on anything else either.  */
112 char **
113 noop_completer (char *text, char *prefix)
114 {
115   return NULL;
116 }
117
118 /* Complete on filenames.  */
119 char **
120 filename_completer (char *text, char *word)
121 {
122   int subsequent_name;
123   char **return_val;
124   int return_val_used;
125   int return_val_alloced;
126
127   return_val_used = 0;
128   /* Small for testing.  */
129   return_val_alloced = 1;
130   return_val = (char **) xmalloc (return_val_alloced * sizeof (char *));
131
132   subsequent_name = 0;
133   while (1)
134     {
135       char *p;
136       p = filename_completion_function (text, subsequent_name);
137       if (return_val_used >= return_val_alloced)
138         {
139           return_val_alloced *= 2;
140           return_val =
141             (char **) xrealloc (return_val,
142                                 return_val_alloced * sizeof (char *));
143         }
144       if (p == NULL)
145         {
146           return_val[return_val_used++] = p;
147           break;
148         }
149       /* We need to set subsequent_name to a non-zero value before the
150          continue line below, because otherwise, if the first file seen
151          by GDB is a backup file whose name ends in a `~', we will loop
152          indefinitely.  */
153       subsequent_name = 1;
154       /* Like emacs, don't complete on old versions.  Especially useful
155          in the "source" command.  */
156       if (p[strlen (p) - 1] == '~')
157         continue;
158
159       {
160         char *q;
161         if (word == text)
162           /* Return exactly p.  */
163           return_val[return_val_used++] = p;
164         else if (word > text)
165           {
166             /* Return some portion of p.  */
167             q = xmalloc (strlen (p) + 5);
168             strcpy (q, p + (word - text));
169             return_val[return_val_used++] = q;
170             xfree (p);
171           }
172         else
173           {
174             /* Return some of TEXT plus p.  */
175             q = xmalloc (strlen (p) + (text - word) + 5);
176             strncpy (q, word, text - word);
177             q[text - word] = '\0';
178             strcat (q, p);
179             return_val[return_val_used++] = q;
180             xfree (p);
181           }
182       }
183     }
184 #if 0
185   /* There is no way to do this just long enough to affect quote inserting
186      without also affecting the next completion.  This should be fixed in
187      readline.  FIXME.  */
188   /* Insure that readline does the right thing
189      with respect to inserting quotes.  */
190   rl_completer_word_break_characters = "";
191 #endif
192   return return_val;
193 }
194
195 /* Complete on locations, which might be of two possible forms:
196
197        file:line
198    or
199        symbol+offset
200
201    This is intended to be used in commands that set breakpoints etc.  */
202 char **
203 location_completer (char *text, char *word)
204 {
205   int n_syms = 0, n_files = 0;
206   char ** fn_list = NULL;
207   char ** list = NULL;
208   char *p;
209   int quote_found = 0;
210   int quoted = *text == '\'' || *text == '"';
211   int quote_char = '\0';
212   char *colon = NULL;
213   char *file_to_match = NULL;
214   char *symbol_start = text;
215   char *orig_text = text;
216   size_t text_len;
217
218   /* Do we have an unquoted colon, as in "break foo.c::bar"?  */
219   for (p = text; *p != '\0'; ++p)
220     {
221       if (*p == '\\' && p[1] == '\'')
222         p++;
223       else if (*p == '\'' || *p == '"')
224         {
225           quote_found = *p;
226           quote_char = *p++;
227           while (*p != '\0' && *p != quote_found)
228             {
229               if (*p == '\\' && p[1] == quote_found)
230                 p++;
231               p++;
232             }
233
234           if (*p == quote_found)
235             quote_found = 0;
236           else
237             break;              /* hit the end of text */
238         }
239 #if HAVE_DOS_BASED_FILE_SYSTEM
240       /* If we have a DOS-style absolute file name at the beginning of
241          TEXT, and the colon after the drive letter is the only colon
242          we found, pretend the colon is not there.  */
243       else if (p < text + 3 && *p == ':' && p == text + 1 + quoted)
244         ;
245 #endif
246       else if (*p == ':' && !colon)
247         {
248           colon = p;
249           symbol_start = p + 1;
250         }
251       else if (strchr (gdb_completer_word_break_characters, *p))
252         symbol_start = p + 1;
253     }
254
255   if (quoted)
256     text++;
257   text_len = strlen (text);
258
259   /* Where is the file name?  */
260   if (colon)
261     {
262       char *s;
263
264       file_to_match = (char *) xmalloc (colon - text + 1);
265       strncpy (file_to_match, text, colon - text + 1);
266       /* Remove trailing colons and quotes from the file name.  */
267       for (s = file_to_match + (colon - text);
268            s > file_to_match;
269            s--)
270         if (*s == ':' || *s == quote_char)
271           *s = '\0';
272     }
273   /* If the text includes a colon, they want completion only on a
274      symbol name after the colon.  Otherwise, we need to complete on
275      symbols as well as on files.  */
276   if (colon)
277     {
278       list = make_file_symbol_completion_list (symbol_start, word,
279                                                file_to_match);
280       xfree (file_to_match);
281     }
282   else
283     {
284       list = make_symbol_completion_list (symbol_start, word);
285       /* If text includes characters which cannot appear in a file
286          name, they cannot be asking for completion on files.  */
287       if (strcspn (text, gdb_completer_file_name_break_characters) == text_len)
288         fn_list = make_source_files_completion_list (text, text);
289     }
290
291   /* How many completions do we have in both lists?  */
292   if (fn_list)
293     for ( ; fn_list[n_files]; n_files++)
294       ;
295   if (list)
296     for ( ; list[n_syms]; n_syms++)
297       ;
298
299   /* Make list[] large enough to hold both lists, then catenate
300      fn_list[] onto the end of list[].  */
301   if (n_syms && n_files)
302     {
303       list = xrealloc (list, (n_syms + n_files + 1) * sizeof (char *));
304       memcpy (list + n_syms, fn_list, (n_files + 1) * sizeof (char *));
305       xfree (fn_list);
306     }
307   else if (n_files)
308     {
309       /* If we only have file names as possible completion, we should
310          bring them in sync with what rl_complete expects.  The
311          problem is that if the user types "break /foo/b TAB", and the
312          possible completions are "/foo/bar" and "/foo/baz"
313          rl_complete expects us to return "bar" and "baz", without the
314          leading directories, as possible completions, because `word'
315          starts at the "b".  But we ignore the value of `word' when we
316          call make_source_files_completion_list above (because that
317          would not DTRT when the completion results in both symbols
318          and file names), so make_source_files_completion_list returns
319          the full "/foo/bar" and "/foo/baz" strings.  This produces
320          wrong results when, e.g., there's only one possible
321          completion, because rl_complete will prepend "/foo/" to each
322          candidate completion.  The loop below removes that leading
323          part.  */
324       for (n_files = 0; fn_list[n_files]; n_files++)
325         {
326           memmove (fn_list[n_files], fn_list[n_files] + (word - text),
327                    strlen (fn_list[n_files]) + 1 - (word - text));
328         }
329       /* Return just the file-name list as the result.  */
330       list = fn_list;
331     }
332   else if (!n_syms)
333     {
334       /* No completions at all.  As the final resort, try completing
335          on the entire text as a symbol.  */
336       list = make_symbol_completion_list (orig_text, word);
337     }
338
339   return list;
340 }
341
342 /* Complete on command names.  Used by "help".  */
343 char **
344 command_completer (char *text, char *word)
345 {
346   return complete_on_cmdlist (cmdlist, text, word);
347 }
348
349
350 /* Here are some useful test cases for completion.  FIXME: These should
351    be put in the test suite.  They should be tested with both M-? and TAB.
352
353    "show output-" "radix"
354    "show output" "-radix"
355    "p" ambiguous (commands starting with p--path, print, printf, etc.)
356    "p "  ambiguous (all symbols)
357    "info t foo" no completions
358    "info t " no completions
359    "info t" ambiguous ("info target", "info terminal", etc.)
360    "info ajksdlfk" no completions
361    "info ajksdlfk " no completions
362    "info" " "
363    "info " ambiguous (all info commands)
364    "p \"a" no completions (string constant)
365    "p 'a" ambiguous (all symbols starting with a)
366    "p b-a" ambiguous (all symbols starting with a)
367    "p b-" ambiguous (all symbols)
368    "file Make" "file" (word break hard to screw up here)
369    "file ../gdb.stabs/we" "ird" (needs to not break word at slash)
370  */
371
372 /* Generate completions one by one for the completer.  Each time we are
373    called return another potential completion to the caller.
374    line_completion just completes on commands or passes the buck to the
375    command's completer function, the stuff specific to symbol completion
376    is in make_symbol_completion_list.
377
378    TEXT is the caller's idea of the "word" we are looking at.
379
380    MATCHES is the number of matches that have currently been collected from
381    calling this completion function.  When zero, then we need to initialize,
382    otherwise the initialization has already taken place and we can just
383    return the next potential completion string.
384
385    LINE_BUFFER is available to be looked at; it contains the entire text
386    of the line.  POINT is the offset in that line of the cursor.  You
387    should pretend that the line ends at POINT.
388
389    Returns NULL if there are no more completions, else a pointer to a string
390    which is a possible completion, it is the caller's responsibility to
391    free the string.  */
392
393 char *
394 line_completion_function (char *text, int matches, char *line_buffer, int point)
395 {
396   static char **list = (char **) NULL;  /* Cache of completions */
397   static int index;             /* Next cached completion */
398   char *output = NULL;
399   char *tmp_command, *p;
400   /* Pointer within tmp_command which corresponds to text.  */
401   char *word;
402   struct cmd_list_element *c, *result_list;
403
404   if (matches == 0)
405     {
406       /* The caller is beginning to accumulate a new set of completions, so
407          we need to find all of them now, and cache them for returning one at
408          a time on future calls. */
409
410       if (list)
411         {
412           /* Free the storage used by LIST, but not by the strings inside.
413              This is because rl_complete_internal () frees the strings. */
414           xfree (list);
415         }
416       list = 0;
417       index = 0;
418
419       /* Choose the default set of word break characters to break completions.
420          If we later find out that we are doing completions on command strings
421          (as opposed to strings supplied by the individual command completer
422          functions, which can be any string) then we will switch to the
423          special word break set for command strings, which leaves out the
424          '-' character used in some commands.  */
425
426       rl_completer_word_break_characters =
427         gdb_completer_word_break_characters;
428
429       /* Decide whether to complete on a list of gdb commands or on symbols. */
430       tmp_command = (char *) alloca (point + 1);
431       p = tmp_command;
432
433       strncpy (tmp_command, line_buffer, point);
434       tmp_command[point] = '\0';
435       /* Since text always contains some number of characters leading up
436          to point, we can find the equivalent position in tmp_command
437          by subtracting that many characters from the end of tmp_command.  */
438       word = tmp_command + point - strlen (text);
439
440       if (point == 0)
441         {
442           /* An empty line we want to consider ambiguous; that is, it
443              could be any command.  */
444           c = (struct cmd_list_element *) -1;
445           result_list = 0;
446         }
447       else
448         {
449           c = lookup_cmd_1 (&p, cmdlist, &result_list, 1);
450         }
451
452       /* Move p up to the next interesting thing.  */
453       while (*p == ' ' || *p == '\t')
454         {
455           p++;
456         }
457
458       if (!c)
459         {
460           /* It is an unrecognized command.  So there are no
461              possible completions.  */
462           list = NULL;
463         }
464       else if (c == (struct cmd_list_element *) -1)
465         {
466           char *q;
467
468           /* lookup_cmd_1 advances p up to the first ambiguous thing, but
469              doesn't advance over that thing itself.  Do so now.  */
470           q = p;
471           while (*q && (isalnum (*q) || *q == '-' || *q == '_'))
472             ++q;
473           if (q != tmp_command + point)
474             {
475               /* There is something beyond the ambiguous
476                  command, so there are no possible completions.  For
477                  example, "info t " or "info t foo" does not complete
478                  to anything, because "info t" can be "info target" or
479                  "info terminal".  */
480               list = NULL;
481             }
482           else
483             {
484               /* We're trying to complete on the command which was ambiguous.
485                  This we can deal with.  */
486               if (result_list)
487                 {
488                   list = complete_on_cmdlist (*result_list->prefixlist, p,
489                                               word);
490                 }
491               else
492                 {
493                   list = complete_on_cmdlist (cmdlist, p, word);
494                 }
495               /* Insure that readline does the right thing with respect to
496                  inserting quotes.  */
497               rl_completer_word_break_characters =
498                 gdb_completer_command_word_break_characters;
499             }
500         }
501       else
502         {
503           /* We've recognized a full command.  */
504
505           if (p == tmp_command + point)
506             {
507               /* There is no non-whitespace in the line beyond the command.  */
508
509               if (p[-1] == ' ' || p[-1] == '\t')
510                 {
511                   /* The command is followed by whitespace; we need to complete
512                      on whatever comes after command.  */
513                   if (c->prefixlist)
514                     {
515                       /* It is a prefix command; what comes after it is
516                          a subcommand (e.g. "info ").  */
517                       list = complete_on_cmdlist (*c->prefixlist, p, word);
518
519                       /* Insure that readline does the right thing
520                          with respect to inserting quotes.  */
521                       rl_completer_word_break_characters =
522                         gdb_completer_command_word_break_characters;
523                     }
524                   else if (c->enums)
525                     {
526                       list = complete_on_enum (c->enums, p, word);
527                       rl_completer_word_break_characters =
528                         gdb_completer_command_word_break_characters;
529                     }
530                   else
531                     {
532                       /* It is a normal command; what comes after it is
533                          completed by the command's completer function.  */
534                       if (c->completer == filename_completer)
535                         {
536                           /* Many commands which want to complete on
537                              file names accept several file names, as
538                              in "run foo bar >>baz".  So we don't want
539                              to complete the entire text after the
540                              command, just the last word.  To this
541                              end, we need to find the beginning of the
542                              file name by starting at `word' and going
543                              backwards.  */
544                           for (p = word;
545                                p > tmp_command
546                                  && strchr (gdb_completer_file_name_break_characters, p[-1]) == NULL;
547                                p--)
548                             ;
549                           rl_completer_word_break_characters =
550                             gdb_completer_file_name_break_characters;
551                         }
552                       else if (c->completer == location_completer)
553                         {
554                           /* Commands which complete on locations want to
555                              see the entire argument.  */
556                           for (p = word;
557                                p > tmp_command
558                                  && p[-1] != ' ' && p[-1] != '\t';
559                                p--)
560                             ;
561                         }
562                       list = (*c->completer) (p, word);
563                     }
564                 }
565               else
566                 {
567                   /* The command is not followed by whitespace; we need to
568                      complete on the command itself.  e.g. "p" which is a
569                      command itself but also can complete to "print", "ptype"
570                      etc.  */
571                   char *q;
572
573                   /* Find the command we are completing on.  */
574                   q = p;
575                   while (q > tmp_command)
576                     {
577                       if (isalnum (q[-1]) || q[-1] == '-' || q[-1] == '_')
578                         --q;
579                       else
580                         break;
581                     }
582
583                   list = complete_on_cmdlist (result_list, q, word);
584
585                   /* Insure that readline does the right thing
586                      with respect to inserting quotes.  */
587                   rl_completer_word_break_characters =
588                     gdb_completer_command_word_break_characters;
589                 }
590             }
591           else
592             {
593               /* There is non-whitespace beyond the command.  */
594
595               if (c->prefixlist && !c->allow_unknown)
596                 {
597                   /* It is an unrecognized subcommand of a prefix command,
598                      e.g. "info adsfkdj".  */
599                   list = NULL;
600                 }
601               else if (c->enums)
602                 {
603                   list = complete_on_enum (c->enums, p, word);
604                 }
605               else
606                 {
607                   /* It is a normal command.  */
608                   if (c->completer == filename_completer)
609                     {
610                       /* See the commentary above about the specifics
611                          of file-name completion.  */
612                       for (p = word;
613                            p > tmp_command
614                              && strchr (gdb_completer_file_name_break_characters, p[-1]) == NULL;
615                            p--)
616                         ;
617                       rl_completer_word_break_characters =
618                         gdb_completer_file_name_break_characters;
619                     }
620                   else if (c->completer == location_completer)
621                     {
622                       for (p = word;
623                            p > tmp_command
624                              && p[-1] != ' ' && p[-1] != '\t';
625                            p--)
626                         ;
627                     }
628                   list = (*c->completer) (p, word);
629                 }
630             }
631         }
632     }
633
634   /* If we found a list of potential completions during initialization then
635      dole them out one at a time.  The vector of completions is NULL
636      terminated, so after returning the last one, return NULL (and continue
637      to do so) each time we are called after that, until a new list is
638      available. */
639
640   if (list)
641     {
642       output = list[index];
643       if (output)
644         {
645           index++;
646         }
647     }
648
649 #if 0
650   /* Can't do this because readline hasn't yet checked the word breaks
651      for figuring out whether to insert a quote.  */
652   if (output == NULL)
653     /* Make sure the word break characters are set back to normal for the
654        next time that readline tries to complete something.  */
655     rl_completer_word_break_characters =
656       gdb_completer_word_break_characters;
657 #endif
658
659   return (output);
660 }
661 /* Skip over a possibly quoted word (as defined by the quote characters
662    and word break characters the completer uses).  Returns pointer to the
663    location after the "word". */
664
665 char *
666 skip_quoted (char *str)
667 {
668   char quote_char = '\0';
669   char *scan;
670
671   for (scan = str; *scan != '\0'; scan++)
672     {
673       if (quote_char != '\0')
674         {
675           /* Ignore everything until the matching close quote char */
676           if (*scan == quote_char)
677             {
678               /* Found matching close quote. */
679               scan++;
680               break;
681             }
682         }
683       else if (strchr (gdb_completer_quote_characters, *scan))
684         {
685           /* Found start of a quoted string. */
686           quote_char = *scan;
687         }
688       else if (strchr (gdb_completer_word_break_characters, *scan))
689         {
690           break;
691         }
692     }
693   return (scan);
694 }
695