Introduce class completion_tracker & rewrite completion<->readline interaction
[deliverable/binutils-gdb.git] / gdb / completer.c
CommitLineData
c5f0f3d0 1/* Line completion stuff for GDB, the GNU debugger.
61baf725 2 Copyright (C) 2000-2017 Free Software Foundation, Inc.
c5f0f3d0
FN
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
a9762ec7 8 the Free Software Foundation; either version 3 of the License, or
c5f0f3d0
FN
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
a9762ec7 17 along with this program. If not, see <http://www.gnu.org/licenses/>. */
c5f0f3d0
FN
18
19#include "defs.h"
20#include "symtab.h"
21#include "gdbtypes.h"
22#include "expression.h"
9c3f90bd 23#include "filenames.h" /* For DOSish file names. */
51065942 24#include "language.h"
de0bea00 25#include "gdb_signals.h"
71c24708
AA
26#include "target.h"
27#include "reggroups.h"
28#include "user-regs.h"
51f0e40d 29#include "arch-utils.h"
87f0e720 30#include "location.h"
eb3ff9a5 31#include <algorithm>
18a642a1
AC
32#include "cli/cli-decode.h"
33
03717487
MS
34/* FIXME: This is needed because of lookup_cmd_1 (). We should be
35 calling a hook instead so we eliminate the CLI dependency. */
c5f0f3d0
FN
36#include "gdbcmd.h"
37
c94fdfd0 38/* Needed for rl_completer_word_break_characters() and for
38017ce8 39 rl_filename_completion_function. */
dbda9972 40#include "readline/readline.h"
c5f0f3d0
FN
41
42/* readline defines this. */
43#undef savestring
44
45#include "completer.h"
46
eb3ff9a5
PA
47/* Misc state that needs to be tracked across several different
48 readline completer entry point calls, all related to a single
49 completion invocation. */
50
51struct gdb_completer_state
52{
53 /* The current completion's completion tracker. This is a global
54 because a tracker can be shared between the handle_brkchars and
55 handle_completion phases, which involves different readline
56 callbacks. */
57 completion_tracker *tracker = NULL;
58
59 /* Whether the current completion was aborted. */
60 bool aborted = false;
61};
62
63/* The current completion state. */
64static gdb_completer_state current_completion;
65
87f0e720
KS
66/* An enumeration of the various things a user might
67 attempt to complete for a location. */
68
69enum explicit_location_match_type
70{
71 /* The filename of a source file. */
72 MATCH_SOURCE,
73
74 /* The name of a function or method. */
75 MATCH_FUNCTION,
76
77 /* The name of a label. */
78 MATCH_LABEL
79};
80
9c3f90bd 81/* Prototypes for local functions. */
c5f0f3d0
FN
82
83/* readline uses the word breaks for two things:
84 (1) In figuring out where to point the TEXT parameter to the
85 rl_completion_entry_function. Since we don't use TEXT for much,
aff410f1
MS
86 it doesn't matter a lot what the word breaks are for this purpose,
87 but it does affect how much stuff M-? lists.
c5f0f3d0
FN
88 (2) If one of the matches contains a word break character, readline
89 will quote it. That's why we switch between
51065942 90 current_language->la_word_break_characters() and
c5f0f3d0 91 gdb_completer_command_word_break_characters. I'm not sure when
aff410f1
MS
92 we need this behavior (perhaps for funky characters in C++
93 symbols?). */
c5f0f3d0
FN
94
95/* Variables which are necessary for fancy command line editing. */
c5f0f3d0
FN
96
97/* When completing on command names, we remove '-' from the list of
98 word break characters, since we use it in command names. If the
99 readline library sees one in any of the current completion strings,
aff410f1
MS
100 it thinks that the string needs to be quoted and automatically
101 supplies a leading quote. */
67cb5b2d 102static const char gdb_completer_command_word_break_characters[] =
c5f0f3d0
FN
103" \t\n!@#$%^&*()+=|~`}{[]\"';:?/>.<,";
104
105/* When completing on file names, we remove from the list of word
106 break characters any characters that are commonly used in file
107 names, such as '-', '+', '~', etc. Otherwise, readline displays
108 incorrect completion candidates. */
7830cf6f
EZ
109/* MS-DOS and MS-Windows use colon as part of the drive spec, and most
110 programs support @foo style response files. */
67cb5b2d
PA
111static const char gdb_completer_file_name_break_characters[] =
112#ifdef HAVE_DOS_BASED_FILE_SYSTEM
113 " \t\n*|\"';?><@";
7830cf6f 114#else
67cb5b2d 115 " \t\n*|\"';:?><";
7830cf6f 116#endif
c5f0f3d0 117
aff410f1
MS
118/* Characters that can be used to quote completion strings. Note that
119 we can't include '"' because the gdb C parser treats such quoted
120 sequences as strings. */
67cb5b2d 121static const char gdb_completer_quote_characters[] = "'";
c5f0f3d0 122\f
9c3f90bd 123/* Accessor for some completer data that may interest other files. */
c5f0f3d0 124
67cb5b2d 125const char *
c5f0f3d0
FN
126get_gdb_completer_quote_characters (void)
127{
128 return gdb_completer_quote_characters;
129}
130
aff410f1
MS
131/* This can be used for functions which don't want to complete on
132 symbols but don't want to complete on anything else either. */
eb3ff9a5
PA
133
134void
aff410f1 135noop_completer (struct cmd_list_element *ignore,
eb3ff9a5 136 completion_tracker &tracker,
6f937416 137 const char *text, const char *prefix)
d75b5104 138{
d75b5104
EZ
139}
140
c5f0f3d0 141/* Complete on filenames. */
6e1dbf8c 142
eb3ff9a5
PA
143void
144filename_completer (struct cmd_list_element *ignore,
145 completion_tracker &tracker,
6f937416 146 const char *text, const char *word)
c5f0f3d0 147{
c5f0f3d0 148 int subsequent_name;
49c4e619 149 VEC (char_ptr) *return_val = NULL;
c5f0f3d0
FN
150
151 subsequent_name = 0;
152 while (1)
153 {
1e8189fb 154 char *p, *q;
c5504eaf 155
38017ce8 156 p = rl_filename_completion_function (text, subsequent_name);
c5f0f3d0 157 if (p == NULL)
49c4e619 158 break;
c5f0f3d0 159 /* We need to set subsequent_name to a non-zero value before the
aff410f1
MS
160 continue line below, because otherwise, if the first file
161 seen by GDB is a backup file whose name ends in a `~', we
162 will loop indefinitely. */
c5f0f3d0 163 subsequent_name = 1;
aff410f1
MS
164 /* Like emacs, don't complete on old versions. Especially
165 useful in the "source" command. */
c5f0f3d0 166 if (p[strlen (p) - 1] == '~')
1e8189fb
MS
167 {
168 xfree (p);
169 continue;
170 }
c5f0f3d0 171
1e8189fb
MS
172 if (word == text)
173 /* Return exactly p. */
49c4e619 174 q = p;
1e8189fb
MS
175 else if (word > text)
176 {
177 /* Return some portion of p. */
224c3ddb 178 q = (char *) xmalloc (strlen (p) + 5);
1e8189fb 179 strcpy (q, p + (word - text));
1e8189fb
MS
180 xfree (p);
181 }
182 else
183 {
184 /* Return some of TEXT plus p. */
224c3ddb 185 q = (char *) xmalloc (strlen (p) + (text - word) + 5);
1e8189fb
MS
186 strncpy (q, word, text - word);
187 q[text - word] = '\0';
188 strcat (q, p);
1e8189fb
MS
189 xfree (p);
190 }
eb3ff9a5 191 tracker.add_completion (gdb::unique_xmalloc_ptr<char> (q));
c5f0f3d0
FN
192 }
193#if 0
aff410f1
MS
194 /* There is no way to do this just long enough to affect quote
195 inserting without also affecting the next completion. This
196 should be fixed in readline. FIXME. */
489f0516 197 /* Ensure that readline does the right thing
c5f0f3d0
FN
198 with respect to inserting quotes. */
199 rl_completer_word_break_characters = "";
200#endif
c5f0f3d0
FN
201}
202
6e1dbf8c
PA
203/* The corresponding completer_handle_brkchars
204 implementation. */
205
206static void
207filename_completer_handle_brkchars (struct cmd_list_element *ignore,
eb3ff9a5 208 completion_tracker &tracker,
6e1dbf8c
PA
209 const char *text, const char *word)
210{
211 set_rl_completer_word_break_characters
212 (gdb_completer_file_name_break_characters);
213}
214
87f0e720 215/* Complete on linespecs, which might be of two possible forms:
c94fdfd0
EZ
216
217 file:line
218 or
219 symbol+offset
220
aff410f1
MS
221 This is intended to be used in commands that set breakpoints
222 etc. */
223
eb3ff9a5
PA
224static void
225complete_files_symbols (completion_tracker &tracker,
226 const char *text, const char *word)
c94fdfd0 227{
eb3ff9a5
PA
228 int ix;
229 completion_list fn_list;
6f937416 230 const char *p;
c94fdfd0
EZ
231 int quote_found = 0;
232 int quoted = *text == '\'' || *text == '"';
233 int quote_char = '\0';
6f937416 234 const char *colon = NULL;
c94fdfd0 235 char *file_to_match = NULL;
6f937416
PA
236 const char *symbol_start = text;
237 const char *orig_text = text;
c94fdfd0 238
59be2b6a 239 /* Do we have an unquoted colon, as in "break foo.c:bar"? */
c94fdfd0
EZ
240 for (p = text; *p != '\0'; ++p)
241 {
242 if (*p == '\\' && p[1] == '\'')
243 p++;
244 else if (*p == '\'' || *p == '"')
245 {
246 quote_found = *p;
247 quote_char = *p++;
248 while (*p != '\0' && *p != quote_found)
249 {
250 if (*p == '\\' && p[1] == quote_found)
251 p++;
252 p++;
253 }
254
255 if (*p == quote_found)
256 quote_found = 0;
257 else
9c3f90bd 258 break; /* Hit the end of text. */
c94fdfd0
EZ
259 }
260#if HAVE_DOS_BASED_FILE_SYSTEM
261 /* If we have a DOS-style absolute file name at the beginning of
262 TEXT, and the colon after the drive letter is the only colon
263 we found, pretend the colon is not there. */
264 else if (p < text + 3 && *p == ':' && p == text + 1 + quoted)
265 ;
266#endif
267 else if (*p == ':' && !colon)
268 {
269 colon = p;
270 symbol_start = p + 1;
271 }
51065942 272 else if (strchr (current_language->la_word_break_characters(), *p))
c94fdfd0
EZ
273 symbol_start = p + 1;
274 }
275
276 if (quoted)
277 text++;
c94fdfd0
EZ
278
279 /* Where is the file name? */
280 if (colon)
281 {
282 char *s;
283
284 file_to_match = (char *) xmalloc (colon - text + 1);
bbfa2517
YQ
285 strncpy (file_to_match, text, colon - text);
286 file_to_match[colon - text] = '\0';
c94fdfd0
EZ
287 /* Remove trailing colons and quotes from the file name. */
288 for (s = file_to_match + (colon - text);
289 s > file_to_match;
290 s--)
291 if (*s == ':' || *s == quote_char)
292 *s = '\0';
293 }
294 /* If the text includes a colon, they want completion only on a
295 symbol name after the colon. Otherwise, we need to complete on
296 symbols as well as on files. */
297 if (colon)
298 {
eb3ff9a5
PA
299 collect_file_symbol_completion_matches (tracker, symbol_start, word,
300 file_to_match);
c94fdfd0
EZ
301 xfree (file_to_match);
302 }
303 else
304 {
eb3ff9a5
PA
305 size_t text_len = strlen (text);
306
307 collect_symbol_completion_matches (tracker, symbol_start, word);
c94fdfd0
EZ
308 /* If text includes characters which cannot appear in a file
309 name, they cannot be asking for completion on files. */
eb3ff9a5 310 if (strcspn (text,
1f20ed91 311 gdb_completer_file_name_break_characters) == text_len)
c94fdfd0
EZ
312 fn_list = make_source_files_completion_list (text, text);
313 }
314
eb3ff9a5 315 if (!fn_list.empty () && !tracker.have_completions ())
c94fdfd0 316 {
6f937416
PA
317 char *fn;
318
c94fdfd0
EZ
319 /* If we only have file names as possible completion, we should
320 bring them in sync with what rl_complete expects. The
321 problem is that if the user types "break /foo/b TAB", and the
322 possible completions are "/foo/bar" and "/foo/baz"
323 rl_complete expects us to return "bar" and "baz", without the
324 leading directories, as possible completions, because `word'
325 starts at the "b". But we ignore the value of `word' when we
326 call make_source_files_completion_list above (because that
327 would not DTRT when the completion results in both symbols
328 and file names), so make_source_files_completion_list returns
329 the full "/foo/bar" and "/foo/baz" strings. This produces
330 wrong results when, e.g., there's only one possible
331 completion, because rl_complete will prepend "/foo/" to each
332 candidate completion. The loop below removes that leading
333 part. */
eb3ff9a5 334 for (const auto &fn_up: fn_list)
c94fdfd0 335 {
eb3ff9a5
PA
336 char *fn = fn_up.get ();
337 memmove (fn, fn + (word - text), strlen (fn) + 1 - (word - text));
c94fdfd0 338 }
c94fdfd0 339 }
eb3ff9a5
PA
340
341 tracker.add_completions (std::move (fn_list));
342
343 if (!tracker.have_completions ())
c94fdfd0
EZ
344 {
345 /* No completions at all. As the final resort, try completing
346 on the entire text as a symbol. */
eb3ff9a5
PA
347 collect_symbol_completion_matches (tracker,
348 orig_text, word);
c94fdfd0 349 }
eb3ff9a5
PA
350}
351
352/* Returns STRING if not NULL, the empty string otherwise. */
c94fdfd0 353
eb3ff9a5
PA
354static const char *
355string_or_empty (const char *string)
356{
357 return string != NULL ? string : "";
c94fdfd0
EZ
358}
359
87f0e720
KS
360/* A helper function to collect explicit location matches for the given
361 LOCATION, which is attempting to match on WORD. */
362
eb3ff9a5
PA
363static void
364collect_explicit_location_matches (completion_tracker &tracker,
365 struct event_location *location,
87f0e720
KS
366 enum explicit_location_match_type what,
367 const char *word)
368{
67994074
KS
369 const struct explicit_location *explicit_loc
370 = get_explicit_location (location);
87f0e720
KS
371
372 switch (what)
373 {
374 case MATCH_SOURCE:
375 {
eb3ff9a5
PA
376 const char *source = string_or_empty (explicit_loc->source_filename);
377 completion_list matches
378 = make_source_files_completion_list (source, word);
379 tracker.add_completions (std::move (matches));
87f0e720
KS
380 }
381 break;
382
383 case MATCH_FUNCTION:
384 {
eb3ff9a5 385 const char *function = string_or_empty (explicit_loc->function_name);
67994074 386 if (explicit_loc->source_filename != NULL)
87f0e720 387 {
67994074
KS
388 const char *filename = explicit_loc->source_filename;
389
eb3ff9a5
PA
390 collect_file_symbol_completion_matches (tracker,
391 function, word, filename);
87f0e720 392 }
eb3ff9a5
PA
393 else
394 collect_symbol_completion_matches (tracker, function, word);
87f0e720
KS
395 }
396 break;
397
398 case MATCH_LABEL:
399 /* Not supported. */
400 break;
401
402 default:
403 gdb_assert_not_reached ("unhandled explicit_location_match_type");
404 }
87f0e720
KS
405}
406
407/* A convenience macro to (safely) back up P to the previous word. */
408
409static const char *
410backup_text_ptr (const char *p, const char *text)
411{
412 while (p > text && isspace (*p))
413 --p;
414 for (; p > text && !isspace (p[-1]); --p)
415 ;
416
417 return p;
418}
419
420/* A completer function for explicit locations. This function
421 completes both options ("-source", "-line", etc) and values. */
422
eb3ff9a5
PA
423static void
424complete_explicit_location (completion_tracker &tracker,
425 struct event_location *location,
426 const char *text, const char *word)
87f0e720
KS
427{
428 const char *p;
87f0e720
KS
429
430 /* Find the beginning of the word. This is necessary because
431 we need to know if we are completing an option name or value. We
432 don't get the leading '-' from the completer. */
433 p = backup_text_ptr (word, text);
434
435 if (*p == '-')
436 {
437 /* Completing on option name. */
438 static const char *const keywords[] =
439 {
440 "source",
441 "function",
442 "line",
443 "label",
444 NULL
445 };
446
447 /* Skip over the '-'. */
448 ++p;
449
eb3ff9a5
PA
450 complete_on_enum (tracker, keywords, p, p);
451 return;
87f0e720
KS
452 }
453 else
454 {
455 /* Completing on value (or unknown). Get the previous word to see what
456 the user is completing on. */
457 size_t len, offset;
458 const char *new_word, *end;
459 enum explicit_location_match_type what;
67994074
KS
460 struct explicit_location *explicit_loc
461 = get_explicit_location (location);
87f0e720
KS
462
463 /* Backup P to the previous word, which should be the option
464 the user is attempting to complete. */
465 offset = word - p;
466 end = --p;
467 p = backup_text_ptr (p, text);
468 len = end - p;
469
470 if (strncmp (p, "-source", len) == 0)
471 {
472 what = MATCH_SOURCE;
67994074 473 new_word = explicit_loc->source_filename + offset;
87f0e720
KS
474 }
475 else if (strncmp (p, "-function", len) == 0)
476 {
477 what = MATCH_FUNCTION;
67994074 478 new_word = explicit_loc->function_name + offset;
87f0e720
KS
479 }
480 else if (strncmp (p, "-label", len) == 0)
481 {
482 what = MATCH_LABEL;
67994074 483 new_word = explicit_loc->label_name + offset;
87f0e720
KS
484 }
485 else
486 {
487 /* The user isn't completing on any valid option name,
488 e.g., "break -source foo.c [tab]". */
eb3ff9a5 489 return;
87f0e720
KS
490 }
491
492 /* If the user hasn't entered a search expression, e.g.,
493 "break -function <TAB><TAB>", new_word will be NULL, but
494 search routines require non-NULL search words. */
495 if (new_word == NULL)
496 new_word = "";
497
498 /* Now gather matches */
eb3ff9a5 499 collect_explicit_location_matches (tracker, location, what, new_word);
87f0e720 500 }
87f0e720
KS
501}
502
503/* A completer for locations. */
504
eb3ff9a5 505void
87f0e720 506location_completer (struct cmd_list_element *ignore,
eb3ff9a5 507 completion_tracker &tracker,
87f0e720
KS
508 const char *text, const char *word)
509{
87f0e720 510 const char *copy = text;
87f0e720 511
ffc2605c
TT
512 event_location_up location = string_to_explicit_location (&copy,
513 current_language,
514 1);
87f0e720 515 if (location != NULL)
eb3ff9a5
PA
516 complete_explicit_location (tracker, location.get (),
517 text, word);
87f0e720
KS
518 else
519 {
520 /* This is an address or linespec location.
521 Right now both of these are handled by the (old) linespec
522 completer. */
eb3ff9a5 523 complete_files_symbols (tracker, text, word);
87f0e720 524 }
87f0e720
KS
525}
526
1c71341a 527/* Helper for expression_completer which recursively adds field and
eb3ff9a5
PA
528 method names from TYPE, a struct or union type, to the OUTPUT
529 list. */
530
65d12d83 531static void
eb3ff9a5 532add_struct_fields (struct type *type, completion_list &output,
65d12d83
TT
533 char *fieldname, int namelen)
534{
535 int i;
b32d97f3 536 int computed_type_name = 0;
0d5cff50 537 const char *type_name = NULL;
65d12d83 538
f168693b 539 type = check_typedef (type);
65d12d83
TT
540 for (i = 0; i < TYPE_NFIELDS (type); ++i)
541 {
542 if (i < TYPE_N_BASECLASSES (type))
49c4e619 543 add_struct_fields (TYPE_BASECLASS (type, i),
aff410f1 544 output, fieldname, namelen);
9ae8282d 545 else if (TYPE_FIELD_NAME (type, i))
65d12d83 546 {
9ae8282d
TT
547 if (TYPE_FIELD_NAME (type, i)[0] != '\0')
548 {
aff410f1
MS
549 if (! strncmp (TYPE_FIELD_NAME (type, i),
550 fieldname, namelen))
eb3ff9a5 551 output.emplace_back (xstrdup (TYPE_FIELD_NAME (type, i)));
9ae8282d
TT
552 }
553 else if (TYPE_CODE (TYPE_FIELD_TYPE (type, i)) == TYPE_CODE_UNION)
554 {
555 /* Recurse into anonymous unions. */
49c4e619 556 add_struct_fields (TYPE_FIELD_TYPE (type, i),
aff410f1 557 output, fieldname, namelen);
9ae8282d 558 }
65d12d83
TT
559 }
560 }
1c71341a
TT
561
562 for (i = TYPE_NFN_FIELDS (type) - 1; i >= 0; --i)
563 {
0d5cff50 564 const char *name = TYPE_FN_FIELDLIST_NAME (type, i);
c5504eaf 565
1c71341a
TT
566 if (name && ! strncmp (name, fieldname, namelen))
567 {
b32d97f3
TT
568 if (!computed_type_name)
569 {
570 type_name = type_name_no_tag (type);
571 computed_type_name = 1;
572 }
1c71341a 573 /* Omit constructors from the completion list. */
907af001 574 if (!type_name || strcmp (type_name, name))
eb3ff9a5 575 output.emplace_back (xstrdup (name));
1c71341a
TT
576 }
577 }
65d12d83
TT
578}
579
580/* Complete on expressions. Often this means completing on symbol
581 names, but some language parsers also have support for completing
582 field names. */
eb3ff9a5
PA
583
584static void
585complete_expression (completion_tracker &tracker,
586 const char *text, const char *word)
65d12d83 587{
c92817ce 588 struct type *type = NULL;
6f937416 589 char *fieldname;
2f68a895 590 enum type_code code = TYPE_CODE_UNDEF;
65d12d83
TT
591
592 /* Perform a tentative parse of the expression, to see whether a
593 field completion is required. */
594 fieldname = NULL;
492d29ea 595 TRY
c92817ce 596 {
2f68a895 597 type = parse_expression_for_completion (text, &fieldname, &code);
c92817ce 598 }
492d29ea
PA
599 CATCH (except, RETURN_MASK_ERROR)
600 {
eb3ff9a5 601 return;
492d29ea
PA
602 }
603 END_CATCH
604
65d12d83
TT
605 if (fieldname && type)
606 {
607 for (;;)
608 {
f168693b 609 type = check_typedef (type);
aa006118 610 if (TYPE_CODE (type) != TYPE_CODE_PTR && !TYPE_IS_REFERENCE (type))
65d12d83
TT
611 break;
612 type = TYPE_TARGET_TYPE (type);
613 }
614
615 if (TYPE_CODE (type) == TYPE_CODE_UNION
616 || TYPE_CODE (type) == TYPE_CODE_STRUCT)
617 {
65d12d83 618 int flen = strlen (fieldname);
eb3ff9a5 619 completion_list result;
65d12d83 620
eb3ff9a5 621 add_struct_fields (type, result, fieldname, flen);
a0b7aece 622 xfree (fieldname);
eb3ff9a5
PA
623 tracker.add_completions (std::move (result));
624 return;
65d12d83
TT
625 }
626 }
2f68a895
TT
627 else if (fieldname && code != TYPE_CODE_UNDEF)
628 {
629 VEC (char_ptr) *result;
630 struct cleanup *cleanup = make_cleanup (xfree, fieldname);
631
eb3ff9a5
PA
632 collect_symbol_completion_matches_type (tracker, fieldname, fieldname,
633 code);
2f68a895 634 do_cleanups (cleanup);
eb3ff9a5 635 return;
2f68a895 636 }
a0b7aece 637 xfree (fieldname);
65d12d83 638
eb3ff9a5
PA
639 complete_files_symbols (tracker, text, word);
640}
641
642/* Complete on expressions. Often this means completing on symbol
643 names, but some language parsers also have support for completing
644 field names. */
645
646void
647expression_completer (struct cmd_list_element *ignore,
648 completion_tracker &tracker,
649 const char *text, const char *word)
650{
651 complete_expression (tracker, text, word);
65d12d83
TT
652}
653
7d793aa9
SDJ
654/* See definition in completer.h. */
655
67cb5b2d
PA
656void
657set_rl_completer_word_break_characters (const char *break_chars)
658{
659 rl_completer_word_break_characters = (char *) break_chars;
660}
661
662/* See definition in completer.h. */
663
7d793aa9
SDJ
664void
665set_gdb_completion_word_break_characters (completer_ftype *fn)
666{
67cb5b2d
PA
667 const char *break_chars;
668
7d793aa9
SDJ
669 /* So far we are only interested in differentiating filename
670 completers from everything else. */
671 if (fn == filename_completer)
67cb5b2d 672 break_chars = gdb_completer_file_name_break_characters;
7d793aa9 673 else
67cb5b2d
PA
674 break_chars = gdb_completer_command_word_break_characters;
675
676 set_rl_completer_word_break_characters (break_chars);
7d793aa9
SDJ
677}
678
78b13106
PA
679/* Complete on symbols. */
680
eb3ff9a5 681void
78b13106 682symbol_completer (struct cmd_list_element *ignore,
eb3ff9a5 683 completion_tracker &tracker,
78b13106
PA
684 const char *text, const char *word)
685{
eb3ff9a5 686 collect_symbol_completion_matches (tracker, text, word);
78b13106
PA
687}
688
aff410f1
MS
689/* Here are some useful test cases for completion. FIXME: These
690 should be put in the test suite. They should be tested with both
691 M-? and TAB.
c5f0f3d0
FN
692
693 "show output-" "radix"
694 "show output" "-radix"
695 "p" ambiguous (commands starting with p--path, print, printf, etc.)
696 "p " ambiguous (all symbols)
697 "info t foo" no completions
698 "info t " no completions
699 "info t" ambiguous ("info target", "info terminal", etc.)
700 "info ajksdlfk" no completions
701 "info ajksdlfk " no completions
702 "info" " "
703 "info " ambiguous (all info commands)
704 "p \"a" no completions (string constant)
705 "p 'a" ambiguous (all symbols starting with a)
706 "p b-a" ambiguous (all symbols starting with a)
707 "p b-" ambiguous (all symbols)
708 "file Make" "file" (word break hard to screw up here)
709 "file ../gdb.stabs/we" "ird" (needs to not break word at slash)
710 */
711
eb3ff9a5 712enum complete_line_internal_reason
67c296a2 713{
eb3ff9a5
PA
714 /* Preliminary phase, called by gdb_completion_word_break_characters
715 function, is used to determine the correct set of chars that are
716 word delimiters depending on the current command in line_buffer.
717 No completion list should be generated; the return value should
718 be NULL. This is checked by an assertion. */
67c296a2 719 handle_brkchars,
eb3ff9a5
PA
720
721 /* Main phase, called by complete_line function, is used to get the
722 list of possible completions. */
67c296a2 723 handle_completions,
eb3ff9a5
PA
724
725 /* Special case when completing a 'help' command. In this case,
726 once sub-command completions are exhausted, we simply return
727 NULL. */
728 handle_help,
729};
67c296a2 730
6e1dbf8c
PA
731/* Helper for complete_line_internal to simplify it. */
732
eb3ff9a5
PA
733static void
734complete_line_internal_normal_command (completion_tracker &tracker,
735 const char *command, const char *word,
6e1dbf8c
PA
736 const char *cmd_args,
737 complete_line_internal_reason reason,
738 struct cmd_list_element *c)
739{
740 const char *p = cmd_args;
741
742 if (c->completer == filename_completer)
743 {
744 /* Many commands which want to complete on file names accept
745 several file names, as in "run foo bar >>baz". So we don't
746 want to complete the entire text after the command, just the
747 last word. To this end, we need to find the beginning of the
748 file name by starting at `word' and going backwards. */
749 for (p = word;
750 p > command
751 && strchr (gdb_completer_file_name_break_characters,
752 p[-1]) == NULL;
753 p--)
754 ;
755 }
756
757 if (reason == handle_brkchars)
758 {
759 completer_handle_brkchars_ftype *brkchars_fn;
760
761 if (c->completer_handle_brkchars != NULL)
762 brkchars_fn = c->completer_handle_brkchars;
763 else
764 {
765 brkchars_fn
766 = (completer_handle_brkchars_func_for_completer
767 (c->completer));
768 }
769
eb3ff9a5 770 brkchars_fn (c, tracker, p, word);
6e1dbf8c
PA
771 }
772
773 if (reason != handle_brkchars && c->completer != NULL)
eb3ff9a5 774 (*c->completer) (c, tracker, p, word);
6e1dbf8c 775}
67c296a2
PM
776
777/* Internal function used to handle completions.
778
c5f0f3d0
FN
779
780 TEXT is the caller's idea of the "word" we are looking at.
781
aff410f1
MS
782 LINE_BUFFER is available to be looked at; it contains the entire
783 text of the line. POINT is the offset in that line of the cursor.
784 You should pretend that the line ends at POINT.
67c296a2 785
eb3ff9a5 786 See complete_line_internal_reason for description of REASON. */
14032a66 787
eb3ff9a5
PA
788static void
789complete_line_internal_1 (completion_tracker &tracker,
790 const char *text,
791 const char *line_buffer, int point,
792 complete_line_internal_reason reason)
c5f0f3d0 793{
6f937416
PA
794 char *tmp_command;
795 const char *p;
ace21957 796 int ignore_help_classes;
c5f0f3d0 797 /* Pointer within tmp_command which corresponds to text. */
eb3ff9a5 798 const char *word;
c5f0f3d0
FN
799 struct cmd_list_element *c, *result_list;
800
aff410f1
MS
801 /* Choose the default set of word break characters to break
802 completions. If we later find out that we are doing completions
803 on command strings (as opposed to strings supplied by the
804 individual command completer functions, which can be any string)
805 then we will switch to the special word break set for command
806 strings, which leaves out the '-' character used in some
807 commands. */
67cb5b2d
PA
808 set_rl_completer_word_break_characters
809 (current_language->la_word_break_characters());
c5f0f3d0 810
aff410f1
MS
811 /* Decide whether to complete on a list of gdb commands or on
812 symbols. */
83d31a92
TT
813 tmp_command = (char *) alloca (point + 1);
814 p = tmp_command;
c5f0f3d0 815
ace21957
MF
816 /* The help command should complete help aliases. */
817 ignore_help_classes = reason != handle_help;
818
83d31a92
TT
819 strncpy (tmp_command, line_buffer, point);
820 tmp_command[point] = '\0';
eb3ff9a5
PA
821 if (reason == handle_brkchars)
822 {
823 gdb_assert (text == NULL);
824 word = NULL;
825 }
826 else
827 {
828 /* Since text always contains some number of characters leading up
829 to point, we can find the equivalent position in tmp_command
830 by subtracting that many characters from the end of tmp_command. */
831 word = tmp_command + point - strlen (text);
832 }
c5f0f3d0 833
83d31a92
TT
834 if (point == 0)
835 {
836 /* An empty line we want to consider ambiguous; that is, it
837 could be any command. */
1427fe5e 838 c = CMD_LIST_AMBIGUOUS;
83d31a92
TT
839 result_list = 0;
840 }
841 else
842 {
ace21957 843 c = lookup_cmd_1 (&p, cmdlist, &result_list, ignore_help_classes);
83d31a92 844 }
c5f0f3d0 845
83d31a92
TT
846 /* Move p up to the next interesting thing. */
847 while (*p == ' ' || *p == '\t')
848 {
849 p++;
850 }
c5f0f3d0 851
83d31a92
TT
852 if (!c)
853 {
854 /* It is an unrecognized command. So there are no
855 possible completions. */
83d31a92 856 }
1427fe5e 857 else if (c == CMD_LIST_AMBIGUOUS)
83d31a92 858 {
6f937416 859 const char *q;
83d31a92
TT
860
861 /* lookup_cmd_1 advances p up to the first ambiguous thing, but
862 doesn't advance over that thing itself. Do so now. */
863 q = p;
864 while (*q && (isalnum (*q) || *q == '-' || *q == '_'))
865 ++q;
866 if (q != tmp_command + point)
c5f0f3d0 867 {
83d31a92
TT
868 /* There is something beyond the ambiguous
869 command, so there are no possible completions. For
870 example, "info t " or "info t foo" does not complete
871 to anything, because "info t" can be "info target" or
872 "info terminal". */
c5f0f3d0 873 }
83d31a92 874 else
c5f0f3d0 875 {
83d31a92
TT
876 /* We're trying to complete on the command which was ambiguous.
877 This we can deal with. */
878 if (result_list)
c5f0f3d0 879 {
67c296a2 880 if (reason != handle_brkchars)
eb3ff9a5
PA
881 complete_on_cmdlist (*result_list->prefixlist, tracker, p,
882 word, ignore_help_classes);
c5f0f3d0
FN
883 }
884 else
885 {
67c296a2 886 if (reason != handle_brkchars)
eb3ff9a5
PA
887 complete_on_cmdlist (cmdlist, tracker, p, word,
888 ignore_help_classes);
c5f0f3d0 889 }
489f0516 890 /* Ensure that readline does the right thing with respect to
83d31a92 891 inserting quotes. */
67cb5b2d
PA
892 set_rl_completer_word_break_characters
893 (gdb_completer_command_word_break_characters);
c5f0f3d0 894 }
83d31a92
TT
895 }
896 else
897 {
898 /* We've recognized a full command. */
899
900 if (p == tmp_command + point)
c5f0f3d0 901 {
aff410f1
MS
902 /* There is no non-whitespace in the line beyond the
903 command. */
c5f0f3d0 904
83d31a92 905 if (p[-1] == ' ' || p[-1] == '\t')
c5f0f3d0 906 {
aff410f1
MS
907 /* The command is followed by whitespace; we need to
908 complete on whatever comes after command. */
83d31a92 909 if (c->prefixlist)
c5f0f3d0 910 {
83d31a92
TT
911 /* It is a prefix command; what comes after it is
912 a subcommand (e.g. "info "). */
67c296a2 913 if (reason != handle_brkchars)
eb3ff9a5
PA
914 complete_on_cmdlist (*c->prefixlist, tracker, p, word,
915 ignore_help_classes);
c5f0f3d0 916
489f0516 917 /* Ensure that readline does the right thing
9c3f90bd 918 with respect to inserting quotes. */
67cb5b2d
PA
919 set_rl_completer_word_break_characters
920 (gdb_completer_command_word_break_characters);
c5f0f3d0 921 }
67c296a2 922 else if (reason == handle_help)
eb3ff9a5 923 ;
c5f0f3d0
FN
924 else if (c->enums)
925 {
67c296a2 926 if (reason != handle_brkchars)
eb3ff9a5 927 complete_on_enum (tracker, c->enums, p, word);
67cb5b2d
PA
928 set_rl_completer_word_break_characters
929 (gdb_completer_command_word_break_characters);
c5f0f3d0
FN
930 }
931 else
932 {
83d31a92
TT
933 /* It is a normal command; what comes after it is
934 completed by the command's completer function. */
eb3ff9a5
PA
935 complete_line_internal_normal_command (tracker,
936 tmp_command, word, p,
937 reason, c);
c5f0f3d0
FN
938 }
939 }
83d31a92
TT
940 else
941 {
942 /* The command is not followed by whitespace; we need to
aff410f1 943 complete on the command itself, e.g. "p" which is a
83d31a92
TT
944 command itself but also can complete to "print", "ptype"
945 etc. */
6f937416 946 const char *q;
83d31a92
TT
947
948 /* Find the command we are completing on. */
949 q = p;
950 while (q > tmp_command)
951 {
952 if (isalnum (q[-1]) || q[-1] == '-' || q[-1] == '_')
953 --q;
954 else
955 break;
956 }
957
67c296a2 958 if (reason != handle_brkchars)
eb3ff9a5
PA
959 complete_on_cmdlist (result_list, tracker, q, word,
960 ignore_help_classes);
83d31a92 961
489f0516 962 /* Ensure that readline does the right thing
9c3f90bd 963 with respect to inserting quotes. */
67cb5b2d
PA
964 set_rl_completer_word_break_characters
965 (gdb_completer_command_word_break_characters);
83d31a92
TT
966 }
967 }
67c296a2 968 else if (reason == handle_help)
eb3ff9a5 969 ;
83d31a92
TT
970 else
971 {
972 /* There is non-whitespace beyond the command. */
973
974 if (c->prefixlist && !c->allow_unknown)
975 {
976 /* It is an unrecognized subcommand of a prefix command,
977 e.g. "info adsfkdj". */
83d31a92
TT
978 }
979 else if (c->enums)
980 {
67c296a2 981 if (reason != handle_brkchars)
eb3ff9a5 982 complete_on_enum (tracker, c->enums, p, word);
83d31a92
TT
983 }
984 else
985 {
986 /* It is a normal command. */
eb3ff9a5
PA
987 complete_line_internal_normal_command (tracker,
988 tmp_command, word, p,
989 reason, c);
83d31a92
TT
990 }
991 }
992 }
83d31a92 993}
ef0b411a 994
eb3ff9a5
PA
995/* Wrapper around complete_line_internal_1 to handle
996 MAX_COMPLETIONS_REACHED_ERROR. */
ef0b411a 997
eb3ff9a5
PA
998static void
999complete_line_internal (completion_tracker &tracker,
1000 const char *text,
1001 const char *line_buffer, int point,
1002 complete_line_internal_reason reason)
1003{
1004 TRY
1005 {
1006 complete_line_internal_1 (tracker, text, line_buffer, point, reason);
1007 }
1008 CATCH (except, RETURN_MASK_ERROR)
1009 {
1010 if (except.error != MAX_COMPLETIONS_REACHED_ERROR)
1011 throw_exception (except);
1012 }
1013}
ef0b411a
GB
1014
1015/* See completer.h. */
1016
eb3ff9a5 1017int max_completions = 200;
ef0b411a 1018
eb3ff9a5
PA
1019/* Initial size of the table. It automagically grows from here. */
1020#define INITIAL_COMPLETION_HTAB_SIZE 200
ef0b411a 1021
eb3ff9a5 1022/* See completer.h. */
ef0b411a 1023
eb3ff9a5 1024completion_tracker::completion_tracker ()
ef0b411a 1025{
eb3ff9a5
PA
1026 m_entries_hash = htab_create_alloc (INITIAL_COMPLETION_HTAB_SIZE,
1027 htab_hash_string, (htab_eq) streq,
1028 NULL, xcalloc, xfree);
ef0b411a
GB
1029}
1030
1031/* See completer.h. */
1032
eb3ff9a5 1033completion_tracker::~completion_tracker ()
ef0b411a 1034{
eb3ff9a5
PA
1035 xfree (m_lowest_common_denominator);
1036 htab_delete (m_entries_hash);
ef0b411a
GB
1037}
1038
1039/* See completer.h. */
1040
eb3ff9a5
PA
1041bool
1042completion_tracker::maybe_add_completion (gdb::unique_xmalloc_ptr<char> name)
ef0b411a
GB
1043{
1044 void **slot;
1045
ef0b411a 1046 if (max_completions == 0)
eb3ff9a5 1047 return false;
ef0b411a 1048
eb3ff9a5
PA
1049 if (htab_elements (m_entries_hash) >= max_completions)
1050 return false;
ef0b411a 1051
eb3ff9a5
PA
1052 slot = htab_find_slot (m_entries_hash, name.get (), INSERT);
1053 if (*slot == HTAB_EMPTY_ENTRY)
1054 {
1055 const char *match_for_lcd_str = name.get ();
ef0b411a 1056
eb3ff9a5 1057 recompute_lowest_common_denominator (match_for_lcd_str);
ef0b411a 1058
eb3ff9a5
PA
1059 *slot = name.get ();
1060 m_entries_vec.push_back (std::move (name));
1061 }
ef0b411a 1062
eb3ff9a5
PA
1063 return true;
1064}
1065
1066/* See completer.h. */
ef0b411a 1067
eb3ff9a5
PA
1068void
1069completion_tracker::add_completion (gdb::unique_xmalloc_ptr<char> name)
1070{
1071 if (!maybe_add_completion (std::move (name)))
1072 throw_error (MAX_COMPLETIONS_REACHED_ERROR, _("Max completions reached."));
ef0b411a
GB
1073}
1074
eb3ff9a5
PA
1075/* See completer.h. */
1076
ef0b411a 1077void
eb3ff9a5 1078completion_tracker::add_completions (completion_list &&list)
ef0b411a 1079{
eb3ff9a5
PA
1080 for (auto &candidate : list)
1081 add_completion (std::move (candidate));
ef0b411a
GB
1082}
1083
eb3ff9a5
PA
1084/* Generate completions all at once. Does nothing if max_completions
1085 is 0. If max_completions is non-negative, this will collect at
1086 most max_completions strings.
83d31a92 1087
67c296a2
PM
1088 TEXT is the caller's idea of the "word" we are looking at.
1089
aff410f1
MS
1090 LINE_BUFFER is available to be looked at; it contains the entire
1091 text of the line.
67c296a2
PM
1092
1093 POINT is the offset in that line of the cursor. You
1094 should pretend that the line ends at POINT. */
14032a66 1095
eb3ff9a5
PA
1096void
1097complete_line (completion_tracker &tracker,
1098 const char *text, const char *line_buffer, int point)
14032a66 1099{
ef0b411a 1100 if (max_completions == 0)
eb3ff9a5
PA
1101 return;
1102 complete_line_internal (tracker, text, line_buffer, point,
1103 handle_completions);
14032a66
TT
1104}
1105
1106/* Complete on command names. Used by "help". */
6e1dbf8c 1107
eb3ff9a5 1108void
aff410f1 1109command_completer (struct cmd_list_element *ignore,
eb3ff9a5 1110 completion_tracker &tracker,
6f937416 1111 const char *text, const char *word)
14032a66 1112{
eb3ff9a5
PA
1113 complete_line_internal (tracker, word, text,
1114 strlen (text), handle_help);
67c296a2
PM
1115}
1116
6e1dbf8c
PA
1117/* The corresponding completer_handle_brkchars implementation. */
1118
1119static void
1120command_completer_handle_brkchars (struct cmd_list_element *ignore,
eb3ff9a5 1121 completion_tracker &tracker,
6e1dbf8c
PA
1122 const char *text, const char *word)
1123{
1124 set_rl_completer_word_break_characters
1125 (gdb_completer_command_word_break_characters);
1126}
1127
de0bea00
MF
1128/* Complete on signals. */
1129
eb3ff9a5 1130void
de0bea00 1131signal_completer (struct cmd_list_element *ignore,
eb3ff9a5 1132 completion_tracker &tracker,
6f937416 1133 const char *text, const char *word)
de0bea00 1134{
de0bea00 1135 size_t len = strlen (word);
570dc176 1136 int signum;
de0bea00
MF
1137 const char *signame;
1138
1139 for (signum = GDB_SIGNAL_FIRST; signum != GDB_SIGNAL_LAST; ++signum)
1140 {
1141 /* Can't handle this, so skip it. */
1142 if (signum == GDB_SIGNAL_0)
1143 continue;
1144
570dc176 1145 signame = gdb_signal_to_name ((enum gdb_signal) signum);
de0bea00
MF
1146
1147 /* Ignore the unknown signal case. */
1148 if (!signame || strcmp (signame, "?") == 0)
1149 continue;
1150
1151 if (strncasecmp (signame, word, len) == 0)
eb3ff9a5
PA
1152 {
1153 gdb::unique_xmalloc_ptr<char> copy (xstrdup (signame));
1154 tracker.add_completion (std::move (copy));
1155 }
de0bea00 1156 }
de0bea00
MF
1157}
1158
51f0e40d
AB
1159/* Bit-flags for selecting what the register and/or register-group
1160 completer should complete on. */
71c24708 1161
8d297bbf 1162enum reg_completer_target
51f0e40d
AB
1163 {
1164 complete_register_names = 0x1,
1165 complete_reggroup_names = 0x2
1166 };
8d297bbf 1167DEF_ENUM_FLAGS_TYPE (enum reg_completer_target, reg_completer_targets);
51f0e40d
AB
1168
1169/* Complete register names and/or reggroup names based on the value passed
1170 in TARGETS. At least one bit in TARGETS must be set. */
1171
eb3ff9a5
PA
1172static void
1173reg_or_group_completer_1 (completion_tracker &tracker,
51f0e40d 1174 const char *text, const char *word,
8d297bbf 1175 reg_completer_targets targets)
71c24708 1176{
71c24708
AA
1177 size_t len = strlen (word);
1178 struct gdbarch *gdbarch;
71c24708 1179 const char *name;
71c24708 1180
51f0e40d
AB
1181 gdb_assert ((targets & (complete_register_names
1182 | complete_reggroup_names)) != 0);
1183 gdbarch = get_current_arch ();
71c24708 1184
51f0e40d 1185 if ((targets & complete_register_names) != 0)
71c24708 1186 {
51f0e40d
AB
1187 int i;
1188
1189 for (i = 0;
1190 (name = user_reg_map_regnum_to_name (gdbarch, i)) != NULL;
1191 i++)
1192 {
1193 if (*name != '\0' && strncmp (word, name, len) == 0)
eb3ff9a5
PA
1194 {
1195 gdb::unique_xmalloc_ptr<char> copy (xstrdup (name));
1196 tracker.add_completion (std::move (copy));
1197 }
51f0e40d 1198 }
71c24708
AA
1199 }
1200
51f0e40d 1201 if ((targets & complete_reggroup_names) != 0)
71c24708 1202 {
51f0e40d
AB
1203 struct reggroup *group;
1204
1205 for (group = reggroup_next (gdbarch, NULL);
1206 group != NULL;
1207 group = reggroup_next (gdbarch, group))
1208 {
1209 name = reggroup_name (group);
1210 if (strncmp (word, name, len) == 0)
eb3ff9a5
PA
1211 {
1212 gdb::unique_xmalloc_ptr<char> copy (xstrdup (name));
1213 tracker.add_completion (std::move (copy));
1214 }
51f0e40d 1215 }
71c24708 1216 }
71c24708
AA
1217}
1218
51f0e40d
AB
1219/* Perform completion on register and reggroup names. */
1220
eb3ff9a5 1221void
51f0e40d 1222reg_or_group_completer (struct cmd_list_element *ignore,
eb3ff9a5 1223 completion_tracker &tracker,
51f0e40d
AB
1224 const char *text, const char *word)
1225{
eb3ff9a5
PA
1226 reg_or_group_completer_1 (tracker, text, word,
1227 (complete_register_names
1228 | complete_reggroup_names));
51f0e40d
AB
1229}
1230
1231/* Perform completion on reggroup names. */
1232
eb3ff9a5 1233void
51f0e40d 1234reggroup_completer (struct cmd_list_element *ignore,
eb3ff9a5 1235 completion_tracker &tracker,
51f0e40d
AB
1236 const char *text, const char *word)
1237{
eb3ff9a5
PA
1238 reg_or_group_completer_1 (tracker, text, word,
1239 complete_reggroup_names);
51f0e40d 1240}
71c24708 1241
6e1dbf8c
PA
1242/* The default completer_handle_brkchars implementation. */
1243
1244static void
1245default_completer_handle_brkchars (struct cmd_list_element *ignore,
eb3ff9a5 1246 completion_tracker &tracker,
6e1dbf8c
PA
1247 const char *text, const char *word)
1248{
1249 set_rl_completer_word_break_characters
1250 (current_language->la_word_break_characters ());
1251}
1252
1253/* See definition in completer.h. */
1254
1255completer_handle_brkchars_ftype *
1256completer_handle_brkchars_func_for_completer (completer_ftype *fn)
1257{
1258 if (fn == filename_completer)
1259 return filename_completer_handle_brkchars;
1260
1261 if (fn == command_completer)
1262 return command_completer_handle_brkchars;
1263
1264 return default_completer_handle_brkchars;
1265}
1266
67c296a2
PM
1267/* Get the list of chars that are considered as word breaks
1268 for the current command. */
1269
eb3ff9a5
PA
1270static char *
1271gdb_completion_word_break_characters_throw ()
67c296a2 1272{
eb3ff9a5
PA
1273 /* New completion starting. Get rid of the previous tracker and
1274 start afresh. */
1275 delete current_completion.tracker;
1276 current_completion.tracker = new completion_tracker ();
1277
1278 completion_tracker &tracker = *current_completion.tracker;
1279
1280 complete_line_internal (tracker, NULL, rl_line_buffer,
1281 rl_point, handle_brkchars);
c5504eaf 1282
67c296a2 1283 return rl_completer_word_break_characters;
14032a66
TT
1284}
1285
eb3ff9a5
PA
1286char *
1287gdb_completion_word_break_characters ()
1288{
1289 /* New completion starting. */
1290 current_completion.aborted = false;
83d31a92 1291
eb3ff9a5
PA
1292 TRY
1293 {
1294 return gdb_completion_word_break_characters_throw ();
1295 }
1296 CATCH (ex, RETURN_MASK_ALL)
1297 {
1298 /* Set this to that gdb_rl_attempted_completion_function knows
1299 to abort early. */
1300 current_completion.aborted = true;
1301 }
1302 END_CATCH
83d31a92 1303
eb3ff9a5
PA
1304 return NULL;
1305}
83d31a92 1306
eb3ff9a5 1307/* See completer.h. */
83d31a92 1308
eb3ff9a5
PA
1309void
1310completion_tracker::recompute_lowest_common_denominator (const char *new_match)
83d31a92 1311{
eb3ff9a5
PA
1312 if (m_lowest_common_denominator == NULL)
1313 {
1314 /* We don't have a lowest common denominator yet, so simply take
1315 the whole NEW_MATCH as being it. */
1316 m_lowest_common_denominator = xstrdup (new_match);
1317 m_lowest_common_denominator_unique = true;
1318 }
1319 else
83d31a92 1320 {
eb3ff9a5
PA
1321 /* Find the common denominator between the currently-known
1322 lowest common denominator and NEW_MATCH. That becomes the
1323 new lowest common denominator. */
1324 size_t i;
83d31a92 1325
eb3ff9a5
PA
1326 for (i = 0;
1327 (new_match[i] != '\0'
1328 && new_match[i] == m_lowest_common_denominator[i]);
1329 i++)
1330 ;
1331 if (m_lowest_common_denominator[i] != new_match[i])
83d31a92 1332 {
eb3ff9a5
PA
1333 m_lowest_common_denominator[i] = '\0';
1334 m_lowest_common_denominator_unique = false;
c5f0f3d0
FN
1335 }
1336 }
eb3ff9a5
PA
1337}
1338
1339/* Build a new C string that is a copy of LCD with the whitespace of
1340 ORIG/ORIG_LEN preserved.
1341
1342 Say the user is completing a symbol name, with spaces, like:
1343
1344 "foo ( i"
1345
1346 and the resulting completion match is:
1347
1348 "foo(int)"
1349
1350 we want to end up with an input line like:
1351
1352 "foo ( int)"
1353 ^^^^^^^ => text from LCD [1], whitespace from ORIG preserved.
1354 ^^ => new text from LCD
1355
1356 [1] - We must take characters from the LCD instead of the original
1357 text, since some completions want to change upper/lowercase. E.g.:
c5f0f3d0 1358
eb3ff9a5 1359 "handle sig<>"
c5f0f3d0 1360
eb3ff9a5
PA
1361 completes to:
1362
1363 "handle SIG[QUIT|etc.]"
1364*/
1365
1366static char *
1367expand_preserving_ws (const char *orig, size_t orig_len,
1368 const char *lcd)
1369{
1370 const char *p_orig = orig;
1371 const char *orig_end = orig + orig_len;
1372 const char *p_lcd = lcd;
1373 std::string res;
1374
1375 while (p_orig < orig_end)
c5f0f3d0 1376 {
eb3ff9a5
PA
1377 if (*p_orig == ' ')
1378 {
1379 while (p_orig < orig_end && *p_orig == ' ')
1380 res += *p_orig++;
1381 p_lcd = skip_spaces_const (p_lcd);
1382 }
1383 else
c5f0f3d0 1384 {
eb3ff9a5
PA
1385 /* Take characters from the LCD instead of the original
1386 text, since some completions change upper/lowercase.
1387 E.g.:
1388 "handle sig<>"
1389 completes to:
1390 "handle SIG[QUIT|etc.]"
1391 */
1392 res += *p_lcd;
1393 p_orig++;
1394 p_lcd++;
c5f0f3d0
FN
1395 }
1396 }
1397
eb3ff9a5
PA
1398 while (*p_lcd != '\0')
1399 res += *p_lcd++;
1400
1401 return xstrdup (res.c_str ());
1402}
1403
1404/* See completer.h. */
1405
1406completion_result
1407completion_tracker::build_completion_result (const char *text,
1408 int start, int end)
1409{
1410 completion_list &list = m_entries_vec; /* The completions. */
1411
1412 if (list.empty ())
1413 return {};
1414
1415 /* +1 for the LCD, and +1 for NULL termination. */
1416 char **match_list = XNEWVEC (char *, 1 + list.size () + 1);
1417
1418 /* Build replacement word, based on the LCD. */
1419
1420 match_list[0]
1421 = expand_preserving_ws (text, end - start,
1422 m_lowest_common_denominator);
1423
1424 if (m_lowest_common_denominator_unique)
1425 {
1426 match_list[1] = NULL;
1427
1428 /* If we already have a space at the end of the match, tell
1429 readline to skip appending another. */
1430 bool completion_suppress_append
1431 = (match_list[0][strlen (match_list[0]) - 1] == ' ');
1432
1433 return completion_result (match_list, 1, completion_suppress_append);
1434 }
1435 else
1436 {
1437 int ix;
1438
1439 for (ix = 0; ix < list.size (); ++ix)
1440 match_list[ix + 1] = list[ix].release ();
1441 match_list[ix + 1] = NULL;
1442
1443 return completion_result (match_list, list.size (), false);
1444 }
1445}
1446
1447/* See completer.h */
1448
1449completion_result::completion_result ()
1450 : match_list (NULL), number_matches (0),
1451 completion_suppress_append (false)
1452{}
1453
1454/* See completer.h */
1455
1456completion_result::completion_result (char **match_list_,
1457 size_t number_matches_,
1458 bool completion_suppress_append_)
1459 : match_list (match_list_),
1460 number_matches (number_matches_),
1461 completion_suppress_append (completion_suppress_append_)
1462{}
1463
1464/* See completer.h */
1465
1466completion_result::~completion_result ()
1467{
1468 reset_match_list ();
1469}
1470
1471/* See completer.h */
1472
1473completion_result::completion_result (completion_result &&rhs)
1474{
1475 if (this == &rhs)
1476 return;
1477
1478 reset_match_list ();
1479 match_list = rhs.match_list;
1480 rhs.match_list = NULL;
1481 number_matches = rhs.number_matches;
1482 rhs.number_matches = 0;
1483}
1484
1485/* See completer.h */
1486
1487char **
1488completion_result::release_match_list ()
1489{
1490 char **ret = match_list;
1491 match_list = NULL;
1492 return ret;
1493}
1494
1495/* Compare C strings for std::sort. */
1496
1497static bool
1498compare_cstrings (const char *str1, const char *str2)
1499{
1500 return strcmp (str1, str2) < 0;
1501}
1502
1503/* See completer.h */
1504
1505void
1506completion_result::sort_match_list ()
1507{
1508 if (number_matches > 1)
1509 {
1510 /* Element 0 is special (it's the common prefix), leave it
1511 be. */
1512 std::sort (&match_list[1],
1513 &match_list[number_matches + 1],
1514 compare_cstrings);
1515 }
1516}
1517
1518/* See completer.h */
1519
1520void
1521completion_result::reset_match_list ()
1522{
1523 if (match_list != NULL)
1524 {
1525 for (char **p = match_list; *p != NULL; p++)
1526 xfree (*p);
1527 xfree (match_list);
1528 match_list = NULL;
1529 }
1530}
1531
1532/* Helper for gdb_rl_attempted_completion_function, which does most of
1533 the work. This is called by readline to build the match list array
1534 and to determine the lowest common denominator. The real matches
1535 list starts at match[1], while match[0] is the slot holding
1536 readline's idea of the lowest common denominator of all matches,
1537 which is what readline replaces the completion "word" with.
1538
1539 TEXT is the caller's idea of the "word" we are looking at, as
1540 computed in the handle_brkchars phase.
1541
1542 START is the offset from RL_LINE_BUFFER where TEXT starts. END is
1543 the offset from RL_LINE_BUFFER where TEXT ends (i.e., where
1544 rl_point is).
1545
1546 You should thus pretend that the line ends at END (relative to
1547 RL_LINE_BUFFER).
1548
1549 RL_LINE_BUFFER contains the entire text of the line. RL_POINT is
1550 the offset in that line of the cursor. You should pretend that the
1551 line ends at POINT.
1552
1553 Returns NULL if there are no completions. */
1554
1555static char **
1556gdb_rl_attempted_completion_function_throw (const char *text, int start, int end)
1557{
1558 /* Completers must be called twice. If rl_point (i.e., END) is at
1559 column 0, then readline skips the the handle_brkchars phase, and
1560 so we create a tracker now in that case too. */
1561 delete current_completion.tracker;
1562 current_completion.tracker = new completion_tracker ();
1563
1564 complete_line (*current_completion.tracker, text,
1565 rl_line_buffer, rl_point);
c5f0f3d0 1566
eb3ff9a5
PA
1567 completion_tracker &tracker = *current_completion.tracker;
1568
1569 completion_result result
1570 = tracker.build_completion_result (text, start, end);
1571
1572 rl_completion_suppress_append = result.completion_suppress_append;
1573 return result.release_match_list ();
1574}
1575
1576/* Function installed as "rl_attempted_completion_function" readline
1577 hook. Wrapper around gdb_rl_attempted_completion_function_throw
1578 that catches C++ exceptions, which can't cross readline. */
1579
1580char **
1581gdb_rl_attempted_completion_function (const char *text, int start, int end)
1582{
1583 /* If we end up returning NULL, either on error, or simple because
1584 there are no matches, inhibit readline's default filename
1585 completer. */
1586 rl_attempted_completion_over = 1;
1587
1588 /* If the handle_brkchars phase was aborted, don't try
1589 completing. */
1590 if (current_completion.aborted)
1591 return NULL;
1592
1593 TRY
1594 {
1595 return gdb_rl_attempted_completion_function_throw (text, start, end);
1596 }
1597 CATCH (ex, RETURN_MASK_ALL)
1598 {
1599 }
1600 END_CATCH
1601
1602 return NULL;
c5f0f3d0 1603}
4e87b832
KD
1604
1605/* Skip over the possibly quoted word STR (as defined by the quote
b021a221
MS
1606 characters QUOTECHARS and the word break characters BREAKCHARS).
1607 Returns pointer to the location after the "word". If either
1608 QUOTECHARS or BREAKCHARS is NULL, use the same values used by the
1609 completer. */
c5f0f3d0 1610
d7561cbb
KS
1611const char *
1612skip_quoted_chars (const char *str, const char *quotechars,
1613 const char *breakchars)
c5f0f3d0
FN
1614{
1615 char quote_char = '\0';
d7561cbb 1616 const char *scan;
c5f0f3d0 1617
4e87b832
KD
1618 if (quotechars == NULL)
1619 quotechars = gdb_completer_quote_characters;
1620
1621 if (breakchars == NULL)
51065942 1622 breakchars = current_language->la_word_break_characters();
4e87b832 1623
c5f0f3d0
FN
1624 for (scan = str; *scan != '\0'; scan++)
1625 {
1626 if (quote_char != '\0')
1627 {
9c3f90bd 1628 /* Ignore everything until the matching close quote char. */
c5f0f3d0
FN
1629 if (*scan == quote_char)
1630 {
9c3f90bd 1631 /* Found matching close quote. */
c5f0f3d0
FN
1632 scan++;
1633 break;
1634 }
1635 }
4e87b832 1636 else if (strchr (quotechars, *scan))
c5f0f3d0 1637 {
aff410f1 1638 /* Found start of a quoted string. */
c5f0f3d0
FN
1639 quote_char = *scan;
1640 }
4e87b832 1641 else if (strchr (breakchars, *scan))
c5f0f3d0
FN
1642 {
1643 break;
1644 }
1645 }
4e87b832 1646
c5f0f3d0
FN
1647 return (scan);
1648}
1649
4e87b832
KD
1650/* Skip over the possibly quoted word STR (as defined by the quote
1651 characters and word break characters used by the completer).
9c3f90bd 1652 Returns pointer to the location after the "word". */
4e87b832 1653
d7561cbb
KS
1654const char *
1655skip_quoted (const char *str)
4e87b832
KD
1656{
1657 return skip_quoted_chars (str, NULL, NULL);
1658}
ef0b411a
GB
1659
1660/* Return a message indicating that the maximum number of completions
1661 has been reached and that there may be more. */
1662
1663const char *
1664get_max_completions_reached_message (void)
1665{
1666 return _("*** List may be truncated, max-completions reached. ***");
1667}
82083d6d
DE
1668\f
1669/* GDB replacement for rl_display_match_list.
1670 Readline doesn't provide a clean interface for TUI(curses).
1671 A hack previously used was to send readline's rl_outstream through a pipe
1672 and read it from the event loop. Bleah. IWBN if readline abstracted
1673 away all the necessary bits, and this is what this code does. It
1674 replicates the parts of readline we need and then adds an abstraction
1675 layer, currently implemented as struct match_list_displayer, so that both
1676 CLI and TUI can use it. We copy all this readline code to minimize
1677 GDB-specific mods to readline. Once this code performs as desired then
1678 we can submit it to the readline maintainers.
1679
1680 N.B. A lot of the code is the way it is in order to minimize differences
1681 from readline's copy. */
1682
1683/* Not supported here. */
1684#undef VISIBLE_STATS
1685
1686#if defined (HANDLE_MULTIBYTE)
1687#define MB_INVALIDCH(x) ((x) == (size_t)-1 || (x) == (size_t)-2)
1688#define MB_NULLWCH(x) ((x) == 0)
1689#endif
1690
1691#define ELLIPSIS_LEN 3
1692
1693/* gdb version of readline/complete.c:get_y_or_n.
1694 'y' -> returns 1, and 'n' -> returns 0.
1695 Also supported: space == 'y', RUBOUT == 'n', ctrl-g == start over.
1696 If FOR_PAGER is non-zero, then also supported are:
1697 NEWLINE or RETURN -> returns 2, and 'q' -> returns 0. */
1698
1699static int
1700gdb_get_y_or_n (int for_pager, const struct match_list_displayer *displayer)
1701{
1702 int c;
1703
1704 for (;;)
1705 {
1706 RL_SETSTATE (RL_STATE_MOREINPUT);
1707 c = displayer->read_key (displayer);
1708 RL_UNSETSTATE (RL_STATE_MOREINPUT);
1709
1710 if (c == 'y' || c == 'Y' || c == ' ')
1711 return 1;
1712 if (c == 'n' || c == 'N' || c == RUBOUT)
1713 return 0;
1714 if (c == ABORT_CHAR || c < 0)
1715 {
1716 /* Readline doesn't erase_entire_line here, but without it the
1717 --More-- prompt isn't erased and neither is the text entered
1718 thus far redisplayed. */
1719 displayer->erase_entire_line (displayer);
1720 /* Note: The arguments to rl_abort are ignored. */
1721 rl_abort (0, 0);
1722 }
1723 if (for_pager && (c == NEWLINE || c == RETURN))
1724 return 2;
1725 if (for_pager && (c == 'q' || c == 'Q'))
1726 return 0;
1727 displayer->beep (displayer);
1728 }
1729}
1730
1731/* Pager function for tab-completion.
1732 This is based on readline/complete.c:_rl_internal_pager.
1733 LINES is the number of lines of output displayed thus far.
1734 Returns:
1735 -1 -> user pressed 'n' or equivalent,
1736 0 -> user pressed 'y' or equivalent,
1737 N -> user pressed NEWLINE or equivalent and N is LINES - 1. */
1738
1739static int
1740gdb_display_match_list_pager (int lines,
1741 const struct match_list_displayer *displayer)
1742{
1743 int i;
1744
1745 displayer->puts (displayer, "--More--");
1746 displayer->flush (displayer);
1747 i = gdb_get_y_or_n (1, displayer);
1748 displayer->erase_entire_line (displayer);
1749 if (i == 0)
1750 return -1;
1751 else if (i == 2)
1752 return (lines - 1);
1753 else
1754 return 0;
1755}
1756
1757/* Return non-zero if FILENAME is a directory.
1758 Based on readline/complete.c:path_isdir. */
1759
1760static int
1761gdb_path_isdir (const char *filename)
1762{
1763 struct stat finfo;
1764
1765 return (stat (filename, &finfo) == 0 && S_ISDIR (finfo.st_mode));
1766}
1767
1768/* Return the portion of PATHNAME that should be output when listing
1769 possible completions. If we are hacking filename completion, we
1770 are only interested in the basename, the portion following the
1771 final slash. Otherwise, we return what we were passed. Since
1772 printing empty strings is not very informative, if we're doing
1773 filename completion, and the basename is the empty string, we look
1774 for the previous slash and return the portion following that. If
1775 there's no previous slash, we just return what we were passed.
1776
1777 Based on readline/complete.c:printable_part. */
1778
1779static char *
1780gdb_printable_part (char *pathname)
1781{
1782 char *temp, *x;
1783
1784 if (rl_filename_completion_desired == 0) /* don't need to do anything */
1785 return (pathname);
1786
1787 temp = strrchr (pathname, '/');
5836a818 1788#if defined (__MSDOS__)
82083d6d
DE
1789 if (temp == 0 && ISALPHA ((unsigned char)pathname[0]) && pathname[1] == ':')
1790 temp = pathname + 1;
1791#endif
1792
1793 if (temp == 0 || *temp == '\0')
1794 return (pathname);
1795 /* If the basename is NULL, we might have a pathname like '/usr/src/'.
1796 Look for a previous slash and, if one is found, return the portion
1797 following that slash. If there's no previous slash, just return the
1798 pathname we were passed. */
1799 else if (temp[1] == '\0')
1800 {
1801 for (x = temp - 1; x > pathname; x--)
1802 if (*x == '/')
1803 break;
1804 return ((*x == '/') ? x + 1 : pathname);
1805 }
1806 else
1807 return ++temp;
1808}
1809
1810/* Compute width of STRING when displayed on screen by print_filename.
1811 Based on readline/complete.c:fnwidth. */
1812
1813static int
1814gdb_fnwidth (const char *string)
1815{
1816 int width, pos;
1817#if defined (HANDLE_MULTIBYTE)
1818 mbstate_t ps;
1819 int left, w;
1820 size_t clen;
1821 wchar_t wc;
1822
1823 left = strlen (string) + 1;
1824 memset (&ps, 0, sizeof (mbstate_t));
1825#endif
1826
1827 width = pos = 0;
1828 while (string[pos])
1829 {
1830 if (CTRL_CHAR (string[pos]) || string[pos] == RUBOUT)
1831 {
1832 width += 2;
1833 pos++;
1834 }
1835 else
1836 {
1837#if defined (HANDLE_MULTIBYTE)
1838 clen = mbrtowc (&wc, string + pos, left - pos, &ps);
1839 if (MB_INVALIDCH (clen))
1840 {
1841 width++;
1842 pos++;
1843 memset (&ps, 0, sizeof (mbstate_t));
1844 }
1845 else if (MB_NULLWCH (clen))
1846 break;
1847 else
1848 {
1849 pos += clen;
1850 w = wcwidth (wc);
1851 width += (w >= 0) ? w : 1;
1852 }
1853#else
1854 width++;
1855 pos++;
1856#endif
1857 }
1858 }
1859
1860 return width;
1861}
1862
1863/* Print TO_PRINT, one matching completion.
1864 PREFIX_BYTES is number of common prefix bytes.
1865 Based on readline/complete.c:fnprint. */
1866
1867static int
1868gdb_fnprint (const char *to_print, int prefix_bytes,
1869 const struct match_list_displayer *displayer)
1870{
1871 int printed_len, w;
1872 const char *s;
1873#if defined (HANDLE_MULTIBYTE)
1874 mbstate_t ps;
1875 const char *end;
1876 size_t tlen;
1877 int width;
1878 wchar_t wc;
1879
1880 end = to_print + strlen (to_print) + 1;
1881 memset (&ps, 0, sizeof (mbstate_t));
1882#endif
1883
1884 printed_len = 0;
1885
1886 /* Don't print only the ellipsis if the common prefix is one of the
1887 possible completions */
1888 if (to_print[prefix_bytes] == '\0')
1889 prefix_bytes = 0;
1890
1891 if (prefix_bytes)
1892 {
1893 char ellipsis;
1894
1895 ellipsis = (to_print[prefix_bytes] == '.') ? '_' : '.';
1896 for (w = 0; w < ELLIPSIS_LEN; w++)
1897 displayer->putch (displayer, ellipsis);
1898 printed_len = ELLIPSIS_LEN;
1899 }
1900
1901 s = to_print + prefix_bytes;
1902 while (*s)
1903 {
1904 if (CTRL_CHAR (*s))
1905 {
1906 displayer->putch (displayer, '^');
1907 displayer->putch (displayer, UNCTRL (*s));
1908 printed_len += 2;
1909 s++;
1910#if defined (HANDLE_MULTIBYTE)
1911 memset (&ps, 0, sizeof (mbstate_t));
1912#endif
1913 }
1914 else if (*s == RUBOUT)
1915 {
1916 displayer->putch (displayer, '^');
1917 displayer->putch (displayer, '?');
1918 printed_len += 2;
1919 s++;
1920#if defined (HANDLE_MULTIBYTE)
1921 memset (&ps, 0, sizeof (mbstate_t));
1922#endif
1923 }
1924 else
1925 {
1926#if defined (HANDLE_MULTIBYTE)
1927 tlen = mbrtowc (&wc, s, end - s, &ps);
1928 if (MB_INVALIDCH (tlen))
1929 {
1930 tlen = 1;
1931 width = 1;
1932 memset (&ps, 0, sizeof (mbstate_t));
1933 }
1934 else if (MB_NULLWCH (tlen))
1935 break;
1936 else
1937 {
1938 w = wcwidth (wc);
1939 width = (w >= 0) ? w : 1;
1940 }
1941 for (w = 0; w < tlen; ++w)
1942 displayer->putch (displayer, s[w]);
1943 s += tlen;
1944 printed_len += width;
1945#else
1946 displayer->putch (displayer, *s);
1947 s++;
1948 printed_len++;
1949#endif
1950 }
1951 }
1952
1953 return printed_len;
1954}
1955
1956/* Output TO_PRINT to rl_outstream. If VISIBLE_STATS is defined and we
1957 are using it, check for and output a single character for `special'
1958 filenames. Return the number of characters we output.
1959 Based on readline/complete.c:print_filename. */
1960
1961static int
1962gdb_print_filename (char *to_print, char *full_pathname, int prefix_bytes,
1963 const struct match_list_displayer *displayer)
1964{
1965 int printed_len, extension_char, slen, tlen;
a121b7c1
PA
1966 char *s, c, *new_full_pathname;
1967 const char *dn;
82083d6d
DE
1968 extern int _rl_complete_mark_directories;
1969
1970 extension_char = 0;
1971 printed_len = gdb_fnprint (to_print, prefix_bytes, displayer);
1972
1973#if defined (VISIBLE_STATS)
1974 if (rl_filename_completion_desired && (rl_visible_stats || _rl_complete_mark_directories))
1975#else
1976 if (rl_filename_completion_desired && _rl_complete_mark_directories)
1977#endif
1978 {
1979 /* If to_print != full_pathname, to_print is the basename of the
1980 path passed. In this case, we try to expand the directory
1981 name before checking for the stat character. */
1982 if (to_print != full_pathname)
1983 {
1984 /* Terminate the directory name. */
1985 c = to_print[-1];
1986 to_print[-1] = '\0';
1987
1988 /* If setting the last slash in full_pathname to a NUL results in
1989 full_pathname being the empty string, we are trying to complete
1990 files in the root directory. If we pass a null string to the
1991 bash directory completion hook, for example, it will expand it
1992 to the current directory. We just want the `/'. */
1993 if (full_pathname == 0 || *full_pathname == 0)
1994 dn = "/";
1995 else if (full_pathname[0] != '/')
1996 dn = full_pathname;
1997 else if (full_pathname[1] == 0)
1998 dn = "//"; /* restore trailing slash to `//' */
1999 else if (full_pathname[1] == '/' && full_pathname[2] == 0)
2000 dn = "/"; /* don't turn /// into // */
2001 else
2002 dn = full_pathname;
2003 s = tilde_expand (dn);
2004 if (rl_directory_completion_hook)
2005 (*rl_directory_completion_hook) (&s);
2006
2007 slen = strlen (s);
2008 tlen = strlen (to_print);
2009 new_full_pathname = (char *)xmalloc (slen + tlen + 2);
2010 strcpy (new_full_pathname, s);
2011 if (s[slen - 1] == '/')
2012 slen--;
2013 else
2014 new_full_pathname[slen] = '/';
2015 new_full_pathname[slen] = '/';
2016 strcpy (new_full_pathname + slen + 1, to_print);
2017
2018#if defined (VISIBLE_STATS)
2019 if (rl_visible_stats)
2020 extension_char = stat_char (new_full_pathname);
2021 else
2022#endif
2023 if (gdb_path_isdir (new_full_pathname))
2024 extension_char = '/';
2025
2026 xfree (new_full_pathname);
2027 to_print[-1] = c;
2028 }
2029 else
2030 {
2031 s = tilde_expand (full_pathname);
2032#if defined (VISIBLE_STATS)
2033 if (rl_visible_stats)
2034 extension_char = stat_char (s);
2035 else
2036#endif
2037 if (gdb_path_isdir (s))
2038 extension_char = '/';
2039 }
2040
2041 xfree (s);
2042 if (extension_char)
2043 {
2044 displayer->putch (displayer, extension_char);
2045 printed_len++;
2046 }
2047 }
2048
2049 return printed_len;
2050}
2051
2052/* GDB version of readline/complete.c:complete_get_screenwidth. */
2053
2054static int
2055gdb_complete_get_screenwidth (const struct match_list_displayer *displayer)
2056{
2057 /* Readline has other stuff here which it's not clear we need. */
2058 return displayer->width;
2059}
2060
56000a98
PA
2061extern int _rl_completion_prefix_display_length;
2062extern int _rl_print_completions_horizontally;
2063
2064EXTERN_C int _rl_qsort_string_compare (const void *, const void *);
2065typedef int QSFUNC (const void *, const void *);
2066
82083d6d 2067/* GDB version of readline/complete.c:rl_display_match_list.
ef0b411a
GB
2068 See gdb_display_match_list for a description of MATCHES, LEN, MAX.
2069 Returns non-zero if all matches are displayed. */
82083d6d 2070
ef0b411a 2071static int
82083d6d
DE
2072gdb_display_match_list_1 (char **matches, int len, int max,
2073 const struct match_list_displayer *displayer)
2074{
2075 int count, limit, printed_len, lines, cols;
2076 int i, j, k, l, common_length, sind;
2077 char *temp, *t;
2078 int page_completions = displayer->height != INT_MAX && pagination_enabled;
82083d6d
DE
2079
2080 /* Find the length of the prefix common to all items: length as displayed
2081 characters (common_length) and as a byte index into the matches (sind) */
2082 common_length = sind = 0;
2083 if (_rl_completion_prefix_display_length > 0)
2084 {
2085 t = gdb_printable_part (matches[0]);
2086 temp = strrchr (t, '/');
2087 common_length = temp ? gdb_fnwidth (temp) : gdb_fnwidth (t);
2088 sind = temp ? strlen (temp) : strlen (t);
2089
2090 if (common_length > _rl_completion_prefix_display_length && common_length > ELLIPSIS_LEN)
2091 max -= common_length - ELLIPSIS_LEN;
2092 else
2093 common_length = sind = 0;
2094 }
2095
2096 /* How many items of MAX length can we fit in the screen window? */
2097 cols = gdb_complete_get_screenwidth (displayer);
2098 max += 2;
2099 limit = cols / max;
2100 if (limit != 1 && (limit * max == cols))
2101 limit--;
2102
2103 /* If cols == 0, limit will end up -1 */
2104 if (cols < displayer->width && limit < 0)
2105 limit = 1;
2106
2107 /* Avoid a possible floating exception. If max > cols,
2108 limit will be 0 and a divide-by-zero fault will result. */
2109 if (limit == 0)
2110 limit = 1;
2111
2112 /* How many iterations of the printing loop? */
2113 count = (len + (limit - 1)) / limit;
2114
2115 /* Watch out for special case. If LEN is less than LIMIT, then
2116 just do the inner printing loop.
2117 0 < len <= limit implies count = 1. */
2118
2119 /* Sort the items if they are not already sorted. */
2120 if (rl_ignore_completion_duplicates == 0 && rl_sort_completion_matches)
2121 qsort (matches + 1, len, sizeof (char *), (QSFUNC *)_rl_qsort_string_compare);
2122
2123 displayer->crlf (displayer);
2124
2125 lines = 0;
2126 if (_rl_print_completions_horizontally == 0)
2127 {
2128 /* Print the sorted items, up-and-down alphabetically, like ls. */
2129 for (i = 1; i <= count; i++)
2130 {
2131 for (j = 0, l = i; j < limit; j++)
2132 {
2133 if (l > len || matches[l] == 0)
2134 break;
2135 else
2136 {
2137 temp = gdb_printable_part (matches[l]);
2138 printed_len = gdb_print_filename (temp, matches[l], sind,
2139 displayer);
2140
2141 if (j + 1 < limit)
2142 for (k = 0; k < max - printed_len; k++)
2143 displayer->putch (displayer, ' ');
2144 }
2145 l += count;
2146 }
2147 displayer->crlf (displayer);
2148 lines++;
2149 if (page_completions && lines >= (displayer->height - 1) && i < count)
2150 {
2151 lines = gdb_display_match_list_pager (lines, displayer);
2152 if (lines < 0)
ef0b411a 2153 return 0;
82083d6d
DE
2154 }
2155 }
2156 }
2157 else
2158 {
2159 /* Print the sorted items, across alphabetically, like ls -x. */
2160 for (i = 1; matches[i]; i++)
2161 {
2162 temp = gdb_printable_part (matches[i]);
2163 printed_len = gdb_print_filename (temp, matches[i], sind, displayer);
2164 /* Have we reached the end of this line? */
2165 if (matches[i+1])
2166 {
2167 if (i && (limit > 1) && (i % limit) == 0)
2168 {
2169 displayer->crlf (displayer);
2170 lines++;
2171 if (page_completions && lines >= displayer->height - 1)
2172 {
2173 lines = gdb_display_match_list_pager (lines, displayer);
2174 if (lines < 0)
ef0b411a 2175 return 0;
82083d6d
DE
2176 }
2177 }
2178 else
2179 for (k = 0; k < max - printed_len; k++)
2180 displayer->putch (displayer, ' ');
2181 }
2182 }
2183 displayer->crlf (displayer);
2184 }
ef0b411a
GB
2185
2186 return 1;
82083d6d
DE
2187}
2188
2189/* Utility for displaying completion list matches, used by both CLI and TUI.
2190
2191 MATCHES is the list of strings, in argv format, LEN is the number of
05cdcf3d
DE
2192 strings in MATCHES, and MAX is the length of the longest string in
2193 MATCHES. */
82083d6d
DE
2194
2195void
2196gdb_display_match_list (char **matches, int len, int max,
2197 const struct match_list_displayer *displayer)
2198{
ef0b411a
GB
2199 /* Readline will never call this if complete_line returned NULL. */
2200 gdb_assert (max_completions != 0);
2201
2202 /* complete_line will never return more than this. */
2203 if (max_completions > 0)
2204 gdb_assert (len <= max_completions);
2205
82083d6d
DE
2206 if (rl_completion_query_items > 0 && len >= rl_completion_query_items)
2207 {
2208 char msg[100];
2209
2210 /* We can't use *query here because they wait for <RET> which is
2211 wrong here. This follows the readline version as closely as possible
2212 for compatibility's sake. See readline/complete.c. */
2213
2214 displayer->crlf (displayer);
2215
2216 xsnprintf (msg, sizeof (msg),
2217 "Display all %d possibilities? (y or n)", len);
2218 displayer->puts (displayer, msg);
2219 displayer->flush (displayer);
2220
2221 if (gdb_get_y_or_n (0, displayer) == 0)
2222 {
2223 displayer->crlf (displayer);
2224 return;
2225 }
2226 }
2227
ef0b411a
GB
2228 if (gdb_display_match_list_1 (matches, len, max, displayer))
2229 {
2230 /* Note: MAX_COMPLETIONS may be -1 or zero, but LEN is always > 0. */
2231 if (len == max_completions)
2232 {
2233 /* The maximum number of completions has been reached. Warn the user
2234 that there may be more. */
2235 const char *message = get_max_completions_reached_message ();
2236
2237 displayer->puts (displayer, message);
2238 displayer->crlf (displayer);
2239 }
2240 }
2241}
2242\f
2243extern initialize_file_ftype _initialize_completer; /* -Wmissing-prototypes */
2244
2245void
2246_initialize_completer (void)
2247{
2248 add_setshow_zuinteger_unlimited_cmd ("max-completions", no_class,
2249 &max_completions, _("\
2250Set maximum number of completion candidates."), _("\
2251Show maximum number of completion candidates."), _("\
2252Use this to limit the number of candidates considered\n\
2253during completion. Specifying \"unlimited\" or -1\n\
2254disables limiting. Note that setting either no limit or\n\
2255a very large limit can make completion slow."),
2256 NULL, NULL, &setlist, &showlist);
82083d6d 2257}
This page took 1.859304 seconds and 4 git commands to generate.