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