* cli/cli-cmds.c (compare_strings): 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 all at once.  Returns a NULL-terminated array
373    of strings.  Both the array and each element are allocated with
374    xmalloc.  It can also return NULL if there are no completions.
375
376    TEXT is the caller's idea of the "word" we are looking at.
377
378    LINE_BUFFER is available to be looked at; it contains the entire text
379    of the line.  POINT is the offset in that line of the cursor.  You
380    should pretend that the line ends at POINT.  */
381
382 char **
383 complete_line (char *text, char *line_buffer, int point)
384 {
385   char **list = NULL;
386   char *tmp_command, *p;
387   /* Pointer within tmp_command which corresponds to text.  */
388   char *word;
389   struct cmd_list_element *c, *result_list;
390
391   /* Choose the default set of word break characters to break completions.
392      If we later find out that we are doing completions on command strings
393      (as opposed to strings supplied by the individual command completer
394      functions, which can be any string) then we will switch to the
395      special word break set for command strings, which leaves out the
396      '-' character used in some commands.  */
397
398   rl_completer_word_break_characters =
399     gdb_completer_word_break_characters;
400
401       /* Decide whether to complete on a list of gdb commands or on symbols. */
402   tmp_command = (char *) alloca (point + 1);
403   p = tmp_command;
404
405   strncpy (tmp_command, line_buffer, point);
406   tmp_command[point] = '\0';
407   /* Since text always contains some number of characters leading up
408      to point, we can find the equivalent position in tmp_command
409      by subtracting that many characters from the end of tmp_command.  */
410   word = tmp_command + point - strlen (text);
411
412   if (point == 0)
413     {
414       /* An empty line we want to consider ambiguous; that is, it
415          could be any command.  */
416       c = (struct cmd_list_element *) -1;
417       result_list = 0;
418     }
419   else
420     {
421       c = lookup_cmd_1 (&p, cmdlist, &result_list, 1);
422     }
423
424   /* Move p up to the next interesting thing.  */
425   while (*p == ' ' || *p == '\t')
426     {
427       p++;
428     }
429
430   if (!c)
431     {
432       /* It is an unrecognized command.  So there are no
433          possible completions.  */
434       list = NULL;
435     }
436   else if (c == (struct cmd_list_element *) -1)
437     {
438       char *q;
439
440       /* lookup_cmd_1 advances p up to the first ambiguous thing, but
441          doesn't advance over that thing itself.  Do so now.  */
442       q = p;
443       while (*q && (isalnum (*q) || *q == '-' || *q == '_'))
444         ++q;
445       if (q != tmp_command + point)
446         {
447           /* There is something beyond the ambiguous
448              command, so there are no possible completions.  For
449              example, "info t " or "info t foo" does not complete
450              to anything, because "info t" can be "info target" or
451              "info terminal".  */
452           list = NULL;
453         }
454       else
455         {
456           /* We're trying to complete on the command which was ambiguous.
457              This we can deal with.  */
458           if (result_list)
459             {
460               list = complete_on_cmdlist (*result_list->prefixlist, p,
461                                           word);
462             }
463           else
464             {
465               list = complete_on_cmdlist (cmdlist, p, word);
466             }
467           /* Insure that readline does the right thing with respect to
468              inserting quotes.  */
469           rl_completer_word_break_characters =
470             gdb_completer_command_word_break_characters;
471         }
472     }
473   else
474     {
475       /* We've recognized a full command.  */
476
477       if (p == tmp_command + point)
478         {
479           /* There is no non-whitespace in the line beyond the command.  */
480
481           if (p[-1] == ' ' || p[-1] == '\t')
482             {
483               /* The command is followed by whitespace; we need to complete
484                  on whatever comes after command.  */
485               if (c->prefixlist)
486                 {
487                   /* It is a prefix command; what comes after it is
488                      a subcommand (e.g. "info ").  */
489                   list = complete_on_cmdlist (*c->prefixlist, p, word);
490
491                   /* Insure that readline does the right thing
492                          with respect to inserting quotes.  */
493                   rl_completer_word_break_characters =
494                     gdb_completer_command_word_break_characters;
495                 }
496               else if (c->enums)
497                 {
498                   list = complete_on_enum (c->enums, p, word);
499                   rl_completer_word_break_characters =
500                     gdb_completer_command_word_break_characters;
501                 }
502               else
503                 {
504                   /* It is a normal command; what comes after it is
505                      completed by the command's completer function.  */
506                   if (c->completer == filename_completer)
507                     {
508                       /* Many commands which want to complete on
509                          file names accept several file names, as
510                          in "run foo bar >>baz".  So we don't want
511                          to complete the entire text after the
512                          command, just the last word.  To this
513                          end, we need to find the beginning of the
514                          file name by starting at `word' and going
515                          backwards.  */
516                       for (p = word;
517                            p > tmp_command
518                              && strchr (gdb_completer_file_name_break_characters, p[-1]) == NULL;
519                            p--)
520                         ;
521                       rl_completer_word_break_characters =
522                         gdb_completer_file_name_break_characters;
523                     }
524                   else if (c->completer == location_completer)
525                     {
526                       /* Commands which complete on locations want to
527                          see the entire argument.  */
528                       for (p = word;
529                            p > tmp_command
530                              && p[-1] != ' ' && p[-1] != '\t';
531                            p--)
532                         ;
533                     }
534                   list = (*c->completer) (p, word);
535                 }
536             }
537           else
538             {
539               /* The command is not followed by whitespace; we need to
540                  complete on the command itself.  e.g. "p" which is a
541                  command itself but also can complete to "print", "ptype"
542                  etc.  */
543               char *q;
544
545               /* Find the command we are completing on.  */
546               q = p;
547               while (q > tmp_command)
548                 {
549                   if (isalnum (q[-1]) || q[-1] == '-' || q[-1] == '_')
550                     --q;
551                   else
552                     break;
553                 }
554
555               list = complete_on_cmdlist (result_list, q, word);
556
557                   /* Insure that readline does the right thing
558                      with respect to inserting quotes.  */
559               rl_completer_word_break_characters =
560                 gdb_completer_command_word_break_characters;
561             }
562         }
563       else
564         {
565           /* There is non-whitespace beyond the command.  */
566
567           if (c->prefixlist && !c->allow_unknown)
568             {
569               /* It is an unrecognized subcommand of a prefix command,
570                  e.g. "info adsfkdj".  */
571               list = NULL;
572             }
573           else if (c->enums)
574             {
575               list = complete_on_enum (c->enums, p, word);
576             }
577           else
578             {
579               /* It is a normal command.  */
580               if (c->completer == filename_completer)
581                 {
582                   /* See the commentary above about the specifics
583                      of file-name completion.  */
584                   for (p = word;
585                        p > tmp_command
586                          && strchr (gdb_completer_file_name_break_characters, p[-1]) == NULL;
587                        p--)
588                     ;
589                   rl_completer_word_break_characters =
590                     gdb_completer_file_name_break_characters;
591                 }
592               else if (c->completer == location_completer)
593                 {
594                   for (p = word;
595                        p > tmp_command
596                          && p[-1] != ' ' && p[-1] != '\t';
597                        p--)
598                     ;
599                 }
600               list = (*c->completer) (p, word);
601             }
602         }
603     }
604
605   return list;
606 }
607
608 /* Generate completions one by one for the completer.  Each time we are
609    called return another potential completion to the caller.
610    line_completion just completes on commands or passes the buck to the
611    command's completer function, the stuff specific to symbol completion
612    is in make_symbol_completion_list.
613
614    TEXT is the caller's idea of the "word" we are looking at.
615
616    MATCHES is the number of matches that have currently been collected from
617    calling this completion function.  When zero, then we need to initialize,
618    otherwise the initialization has already taken place and we can just
619    return the next potential completion string.
620
621    LINE_BUFFER is available to be looked at; it contains the entire text
622    of the line.  POINT is the offset in that line of the cursor.  You
623    should pretend that the line ends at POINT.
624
625    Returns NULL if there are no more completions, else a pointer to a string
626    which is a possible completion, it is the caller's responsibility to
627    free the string.  */
628
629 char *
630 line_completion_function (char *text, int matches, char *line_buffer, int point)
631 {
632   static char **list = (char **) NULL;  /* Cache of completions */
633   static int index;             /* Next cached completion */
634   char *output = NULL;
635
636   if (matches == 0)
637     {
638       /* The caller is beginning to accumulate a new set of completions, so
639          we need to find all of them now, and cache them for returning one at
640          a time on future calls. */
641
642       if (list)
643         {
644           /* Free the storage used by LIST, but not by the strings inside.
645              This is because rl_complete_internal () frees the strings. */
646           xfree (list);
647         }
648       index = 0;
649       list = complete_line (text, line_buffer, point);
650     }
651
652   /* If we found a list of potential completions during initialization then
653      dole them out one at a time.  The vector of completions is NULL
654      terminated, so after returning the last one, return NULL (and continue
655      to do so) each time we are called after that, until a new list is
656      available. */
657
658   if (list)
659     {
660       output = list[index];
661       if (output)
662         {
663           index++;
664         }
665     }
666
667 #if 0
668   /* Can't do this because readline hasn't yet checked the word breaks
669      for figuring out whether to insert a quote.  */
670   if (output == NULL)
671     /* Make sure the word break characters are set back to normal for the
672        next time that readline tries to complete something.  */
673     rl_completer_word_break_characters =
674       gdb_completer_word_break_characters;
675 #endif
676
677   return (output);
678 }
679 /* Skip over a possibly quoted word (as defined by the quote characters
680    and word break characters the completer uses).  Returns pointer to the
681    location after the "word". */
682
683 char *
684 skip_quoted (char *str)
685 {
686   char quote_char = '\0';
687   char *scan;
688
689   for (scan = str; *scan != '\0'; scan++)
690     {
691       if (quote_char != '\0')
692         {
693           /* Ignore everything until the matching close quote char */
694           if (*scan == quote_char)
695             {
696               /* Found matching close quote. */
697               scan++;
698               break;
699             }
700         }
701       else if (strchr (gdb_completer_quote_characters, *scan))
702         {
703           /* Found start of a quoted string. */
704           quote_char = *scan;
705         }
706       else if (strchr (gdb_completer_word_break_characters, *scan))
707         {
708           break;
709         }
710     }
711   return (scan);
712 }
713