Release 2.33.1
[external/binutils.git] / readline / complete.c
1 /* complete.c -- filename completion for readline. */
2
3 /* Copyright (C) 1987-2017 Free Software Foundation, Inc.
4
5    This file is part of the GNU Readline Library (Readline), a library
6    for reading lines of text with interactive input and history editing.
7
8    Readline is free software: you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation, either version 3 of the License, or
11    (at your option) any later version.
12
13    Readline is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with Readline.  If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 #define READLINE_LIBRARY
23
24 #if defined (HAVE_CONFIG_H)
25 #  include <config.h>
26 #endif
27
28 #include <sys/types.h>
29 #include <fcntl.h>
30 #if defined (HAVE_SYS_FILE_H)
31 #  include <sys/file.h>
32 #endif
33
34 #include <signal.h>
35
36 #if defined (HAVE_UNISTD_H)
37 #  include <unistd.h>
38 #endif /* HAVE_UNISTD_H */
39
40 #if defined (HAVE_STDLIB_H)
41 #  include <stdlib.h>
42 #else
43 #  include "ansi_stdlib.h"
44 #endif /* HAVE_STDLIB_H */
45
46 #include <stdio.h>
47
48 #include <errno.h>
49 #if !defined (errno)
50 extern int errno;
51 #endif /* !errno */
52
53 #if defined (HAVE_PWD_H)
54 #include <pwd.h>
55 #endif
56
57 #include "posixdir.h"
58 #include "posixstat.h"
59
60 /* System-specific feature definitions and include files. */
61 #include "rldefs.h"
62 #include "rlmbutil.h"
63
64 /* Some standard library routines. */
65 #include "readline.h"
66 #include "xmalloc.h"
67 #include "rlprivate.h"
68
69 #if defined (COLOR_SUPPORT)
70 #  include "colors.h"
71 #endif
72
73 #ifdef __STDC__
74 typedef int QSFUNC (const void *, const void *);
75 #else
76 typedef int QSFUNC ();
77 #endif
78
79 #ifdef HAVE_LSTAT
80 #  define LSTAT lstat
81 #else
82 #  define LSTAT stat
83 #endif
84
85 /* Unix version of a hidden file.  Could be different on other systems. */
86 #define HIDDEN_FILE(fname)      ((fname)[0] == '.')
87
88 /* Most systems don't declare getpwent in <pwd.h> if _POSIX_SOURCE is
89    defined. */
90 #if defined (HAVE_GETPWENT) && (!defined (HAVE_GETPW_DECLS) || defined (_POSIX_SOURCE))
91 extern struct passwd *getpwent PARAMS((void));
92 #endif /* HAVE_GETPWENT && (!HAVE_GETPW_DECLS || _POSIX_SOURCE) */
93
94 /* If non-zero, then this is the address of a function to call when
95    completing a word would normally display the list of possible matches.
96    This function is called instead of actually doing the display.
97    It takes three arguments: (char **matches, int num_matches, int max_length)
98    where MATCHES is the array of strings that matched, NUM_MATCHES is the
99    number of strings in that array, and MAX_LENGTH is the length of the
100    longest string in that array. */
101 rl_compdisp_func_t *rl_completion_display_matches_hook = (rl_compdisp_func_t *)NULL;
102
103 #if defined (VISIBLE_STATS) || defined (COLOR_SUPPORT)
104 #  if !defined (X_OK)
105 #    define X_OK 1
106 #  endif
107 #endif
108
109 #if defined (VISIBLE_STATS)
110 static int stat_char PARAMS((char *));
111 #endif
112
113 #if defined (COLOR_SUPPORT)
114 static int colored_stat_start PARAMS((const char *));
115 static void colored_stat_end PARAMS((void));
116 static int colored_prefix_start PARAMS((void));
117 static void colored_prefix_end PARAMS((void));
118 #endif
119
120 static int path_isdir PARAMS((const char *));
121
122 static char *rl_quote_filename PARAMS((char *, int, char *));
123
124 static void _rl_complete_sigcleanup PARAMS((int, void *));
125
126 static void set_completion_defaults PARAMS((int));
127 static int get_y_or_n PARAMS((int));
128 static int _rl_internal_pager PARAMS((int));
129 static char *printable_part PARAMS((char *));
130 static int fnwidth PARAMS((const char *));
131 static int fnprint PARAMS((const char *, int, const char *));
132 static int print_filename PARAMS((char *, char *, int));
133
134 static char **gen_completion_matches PARAMS((char *, int, int, rl_compentry_func_t *, int, int));
135
136 static char **remove_duplicate_matches PARAMS((char **));
137 static void insert_match PARAMS((char *, int, int, char *));
138 static int append_to_match PARAMS((char *, int, int, int));
139 static void insert_all_matches PARAMS((char **, int, char *));
140 static int complete_fncmp PARAMS((const char *, int, const char *, int));
141 static void display_matches PARAMS((char **));
142 static int compute_lcd_of_matches PARAMS((char **, int, const char *));
143 static int postprocess_matches PARAMS((char ***, int));
144 static int complete_get_screenwidth PARAMS((void));
145
146 static char *make_quoted_replacement PARAMS((char *, int, char *));
147
148 /* **************************************************************** */
149 /*                                                                  */
150 /*      Completion matching, from readline's point of view.         */
151 /*                                                                  */
152 /* **************************************************************** */
153
154 /* Variables known only to the readline library. */
155
156 /* If non-zero, non-unique completions always show the list of matches. */
157 int _rl_complete_show_all = 0;
158
159 /* If non-zero, non-unique completions show the list of matches, unless it
160    is not possible to do partial completion and modify the line. */
161 int _rl_complete_show_unmodified = 0;
162
163 /* If non-zero, completed directory names have a slash appended. */
164 int _rl_complete_mark_directories = 1;
165
166 /* If non-zero, the symlinked directory completion behavior introduced in
167    readline-4.2a is disabled, and symlinks that point to directories have
168    a slash appended (subject to the value of _rl_complete_mark_directories).
169    This is user-settable via the mark-symlinked-directories variable. */
170 int _rl_complete_mark_symlink_dirs = 0;
171
172 /* If non-zero, completions are printed horizontally in alphabetical order,
173    like `ls -x'. */
174 int _rl_print_completions_horizontally;
175
176 /* Non-zero means that case is not significant in filename completion. */
177 #if (defined (__MSDOS__) && !defined (__DJGPP__)) || (defined (_WIN32) && !defined (__CYGWIN__))
178 int _rl_completion_case_fold = 1;
179 #else
180 int _rl_completion_case_fold = 0;
181 #endif
182
183 /* Non-zero means that `-' and `_' are equivalent when comparing filenames
184   for completion. */
185 int _rl_completion_case_map = 0;
186
187 /* If zero, don't match hidden files (filenames beginning with a `.' on
188    Unix) when doing filename completion. */
189 int _rl_match_hidden_files = 1;
190
191 /* Length in characters of a common prefix replaced with an ellipsis (`...')
192    when displaying completion matches.  Matches whose printable portion has
193    more than this number of displaying characters in common will have the common
194    display prefix replaced with an ellipsis. */
195 int _rl_completion_prefix_display_length = 0;
196
197 /* The readline-private number of screen columns to use when displaying
198    matches.  If < 0 or > _rl_screenwidth, it is ignored. */
199 int _rl_completion_columns = -1;
200
201 #if defined (COLOR_SUPPORT)
202 /* Non-zero means to use colors to indicate file type when listing possible
203    completions.  The colors used are taken from $LS_COLORS, if set. */
204 int _rl_colored_stats = 0;
205
206 /* Non-zero means to use a color (currently magenta) to indicate the common
207    prefix of a set of possible word completions. */
208 int _rl_colored_completion_prefix = 0;
209 #endif
210
211 /* If non-zero, when completing in the middle of a word, don't insert
212    characters from the match that match characters following point in
213    the word.  This means, for instance, completing when the cursor is
214    after the `e' in `Makefile' won't result in `Makefilefile'. */
215 int _rl_skip_completed_text = 0;
216
217 /* If non-zero, menu completion displays the common prefix first in the
218    cycle of possible completions instead of the last. */
219 int _rl_menu_complete_prefix_first = 0;
220
221 /* Global variables available to applications using readline. */
222
223 #if defined (VISIBLE_STATS)
224 /* Non-zero means add an additional character to each filename displayed
225    during listing completion iff rl_filename_completion_desired which helps
226    to indicate the type of file being listed. */
227 int rl_visible_stats = 0;
228 #endif /* VISIBLE_STATS */
229
230 /* If non-zero, then this is the address of a function to call when
231    completing on a directory name.  The function is called with
232    the address of a string (the current directory name) as an arg. */
233 rl_icppfunc_t *rl_directory_completion_hook = (rl_icppfunc_t *)NULL;
234
235 rl_icppfunc_t *rl_directory_rewrite_hook = (rl_icppfunc_t *)NULL;
236
237 rl_icppfunc_t *rl_filename_stat_hook = (rl_icppfunc_t *)NULL;
238
239 /* If non-zero, this is the address of a function to call when reading
240    directory entries from the filesystem for completion and comparing
241    them to the partial word to be completed.  The function should
242    either return its first argument (if no conversion takes place) or
243    newly-allocated memory.  This can, for instance, convert filenames
244    between character sets for comparison against what's typed at the
245    keyboard.  The returned value is what is added to the list of
246    matches.  The second argument is the length of the filename to be
247    converted. */
248 rl_dequote_func_t *rl_filename_rewrite_hook = (rl_dequote_func_t *)NULL;
249
250 /* Non-zero means readline completion functions perform tilde expansion. */
251 int rl_complete_with_tilde_expansion = 0;
252
253 /* Pointer to the generator function for completion_matches ().
254    NULL means to use rl_filename_completion_function (), the default filename
255    completer. */
256 rl_compentry_func_t *rl_completion_entry_function = (rl_compentry_func_t *)NULL;
257
258 /* Pointer to generator function for rl_menu_complete ().  NULL means to use
259    *rl_completion_entry_function (see above). */
260 rl_compentry_func_t *rl_menu_completion_entry_function = (rl_compentry_func_t *)NULL;
261
262 /* Pointer to alternative function to create matches.
263    Function is called with TEXT, START, and END.
264    START and END are indices in RL_LINE_BUFFER saying what the boundaries
265    of TEXT are.
266    If this function exists and returns NULL then call the value of
267    rl_completion_entry_function to try to match, otherwise use the
268    array of strings returned. */
269 rl_completion_func_t *rl_attempted_completion_function = (rl_completion_func_t *)NULL;
270
271 /* Non-zero means to suppress normal filename completion after the
272    user-specified completion function has been called. */
273 int rl_attempted_completion_over = 0;
274
275 /* Set to a character indicating the type of completion being performed
276    by rl_complete_internal, available for use by application completion
277    functions. */
278 int rl_completion_type = 0;
279
280 /* Up to this many items will be displayed in response to a
281    possible-completions call.  After that, we ask the user if
282    she is sure she wants to see them all.  A negative value means
283    don't ask. */
284 int rl_completion_query_items = 100;
285
286 int _rl_page_completions = 1;
287
288 /* The basic list of characters that signal a break between words for the
289    completer routine.  The contents of this variable is what breaks words
290    in the shell, i.e. " \t\n\"\\'`@$><=" */
291 const char *rl_basic_word_break_characters = " \t\n\"\\'`@$><=;|&{("; /* }) */
292
293 /* List of basic quoting characters. */
294 const char *rl_basic_quote_characters = "\"'";
295
296 /* The list of characters that signal a break between words for
297    rl_complete_internal.  The default list is the contents of
298    rl_basic_word_break_characters.  */
299 /*const*/ char *rl_completer_word_break_characters = (/*const*/ char *)NULL;
300
301 /* Hook function to allow an application to set the completion word
302    break characters before readline breaks up the line.  Allows
303    position-dependent word break characters. */
304 rl_cpvfunc_t *rl_completion_word_break_hook = (rl_cpvfunc_t *)NULL;
305
306 /* List of characters which can be used to quote a substring of the line.
307    Completion occurs on the entire substring, and within the substring
308    rl_completer_word_break_characters are treated as any other character,
309    unless they also appear within this list. */
310 const char *rl_completer_quote_characters = (const char *)NULL;
311
312 /* List of characters that should be quoted in filenames by the completer. */
313 const char *rl_filename_quote_characters = (const char *)NULL;
314
315 /* List of characters that are word break characters, but should be left
316    in TEXT when it is passed to the completion function.  The shell uses
317    this to help determine what kind of completing to do. */
318 const char *rl_special_prefixes = (const char *)NULL;
319
320 /* If non-zero, then disallow duplicates in the matches. */
321 int rl_ignore_completion_duplicates = 1;
322
323 /* Non-zero means that the results of the matches are to be treated
324    as filenames.  This is ALWAYS zero on entry, and can only be changed
325    within a completion entry finder function. */
326 int rl_filename_completion_desired = 0;
327
328 /* Non-zero means that the results of the matches are to be quoted using
329    double quotes (or an application-specific quoting mechanism) if the
330    filename contains any characters in rl_filename_quote_chars.  This is
331    ALWAYS non-zero on entry, and can only be changed within a completion
332    entry finder function. */
333 int rl_filename_quoting_desired = 1;
334
335 /* This function, if defined, is called by the completer when real
336    filename completion is done, after all the matching names have been
337    generated. It is passed a (char**) known as matches in the code below.
338    It consists of a NULL-terminated array of pointers to potential
339    matching strings.  The 1st element (matches[0]) is the maximal
340    substring that is common to all matches. This function can re-arrange
341    the list of matches as required, but all elements of the array must be
342    free()'d if they are deleted. The main intent of this function is
343    to implement FIGNORE a la SunOS csh. */
344 rl_compignore_func_t *rl_ignore_some_completions_function = (rl_compignore_func_t *)NULL;
345
346 /* Set to a function to quote a filename in an application-specific fashion.
347    Called with the text to quote, the type of match found (single or multiple)
348    and a pointer to the quoting character to be used, which the function can
349    reset if desired. */
350 rl_quote_func_t *rl_filename_quoting_function = rl_quote_filename;
351          
352 /* Function to call to remove quoting characters from a filename.  Called
353    before completion is attempted, so the embedded quotes do not interfere
354    with matching names in the file system.  Readline doesn't do anything
355    with this; it's set only by applications. */
356 rl_dequote_func_t *rl_filename_dequoting_function = (rl_dequote_func_t *)NULL;
357
358 /* Function to call to decide whether or not a word break character is
359    quoted.  If a character is quoted, it does not break words for the
360    completer. */
361 rl_linebuf_func_t *rl_char_is_quoted_p = (rl_linebuf_func_t *)NULL;
362
363 /* If non-zero, the completion functions don't append anything except a
364    possible closing quote.  This is set to 0 by rl_complete_internal and
365    may be changed by an application-specific completion function. */
366 int rl_completion_suppress_append = 0;
367
368 /* Character appended to completed words when at the end of the line.  The
369    default is a space. */
370 int rl_completion_append_character = ' ';
371
372 /* If non-zero, the completion functions don't append any closing quote.
373    This is set to 0 by rl_complete_internal and may be changed by an
374    application-specific completion function. */
375 int rl_completion_suppress_quote = 0;
376
377 /* Set to any quote character readline thinks it finds before any application
378    completion function is called. */
379 int rl_completion_quote_character;
380
381 /* Set to a non-zero value if readline found quoting anywhere in the word to
382    be completed; set before any application completion function is called. */
383 int rl_completion_found_quote;
384
385 /* If non-zero, a slash will be appended to completed filenames that are
386    symbolic links to directory names, subject to the value of the
387    mark-directories variable (which is user-settable).  This exists so
388    that application completion functions can override the user's preference
389    (set via the mark-symlinked-directories variable) if appropriate.
390    It's set to the value of _rl_complete_mark_symlink_dirs in
391    rl_complete_internal before any application-specific completion
392    function is called, so without that function doing anything, the user's
393    preferences are honored. */
394 int rl_completion_mark_symlink_dirs;
395
396 /* If non-zero, inhibit completion (temporarily). */
397 int rl_inhibit_completion;
398
399 /* Set to the last key used to invoke one of the completion functions */
400 int rl_completion_invoking_key;
401
402 /* If non-zero, sort the completion matches.  On by default. */
403 int rl_sort_completion_matches = 1;
404
405 /* Variables local to this file. */
406
407 /* Local variable states what happened during the last completion attempt. */
408 static int completion_changed_buffer;
409
410 /* The result of the query to the user about displaying completion matches */
411 static int completion_y_or_n;
412
413 static int _rl_complete_display_matches_interrupt = 0;
414
415 /*************************************/
416 /*                                   */
417 /*    Bindable completion functions  */
418 /*                                   */
419 /*************************************/
420
421 /* Complete the word at or before point.  You have supplied the function
422    that does the initial simple matching selection algorithm (see
423    rl_completion_matches ()).  The default is to do filename completion. */
424 int
425 rl_complete (int ignore, int invoking_key)
426 {
427   rl_completion_invoking_key = invoking_key;
428
429   if (rl_inhibit_completion)
430     return (_rl_insert_char (ignore, invoking_key));
431   else if (rl_last_func == rl_complete && !completion_changed_buffer)
432     return (rl_complete_internal ('?'));
433   else if (_rl_complete_show_all)
434     return (rl_complete_internal ('!'));
435   else if (_rl_complete_show_unmodified)
436     return (rl_complete_internal ('@'));
437   else
438     return (rl_complete_internal (TAB));
439 }
440
441 /* List the possible completions.  See description of rl_complete (). */
442 int
443 rl_possible_completions (int ignore, int invoking_key)
444 {
445   rl_completion_invoking_key = invoking_key;
446   return (rl_complete_internal ('?'));
447 }
448
449 int
450 rl_insert_completions (int ignore, int invoking_key)
451 {
452   rl_completion_invoking_key = invoking_key;
453   return (rl_complete_internal ('*'));
454 }
455
456 /* Return the correct value to pass to rl_complete_internal performing
457    the same tests as rl_complete.  This allows consecutive calls to an
458    application's completion function to list possible completions and for
459    an application-specific completion function to honor the
460    show-all-if-ambiguous readline variable. */
461 int
462 rl_completion_mode (rl_command_func_t *cfunc)
463 {
464   if (rl_last_func == cfunc && !completion_changed_buffer)
465     return '?';
466   else if (_rl_complete_show_all)
467     return '!';
468   else if (_rl_complete_show_unmodified)
469     return '@';
470   else
471     return TAB;
472 }
473
474 /************************************/
475 /*                                  */
476 /*    Completion utility functions  */
477 /*                                  */
478 /************************************/
479
480 /* Reset readline state on a signal or other event. */
481 void
482 _rl_reset_completion_state (void)
483 {
484   rl_completion_found_quote = 0;
485   rl_completion_quote_character = 0;
486 }
487
488 static void
489 _rl_complete_sigcleanup (int sig, void *ptr)
490 {
491   if (sig == SIGINT)    /* XXX - for now */
492     {
493       _rl_free_match_list ((char **)ptr);
494       _rl_complete_display_matches_interrupt = 1;
495     }
496 }
497
498 /* Set default values for readline word completion.  These are the variables
499    that application completion functions can change or inspect. */
500 static void
501 set_completion_defaults (int what_to_do)
502 {
503   /* Only the completion entry function can change these. */
504   rl_filename_completion_desired = 0;
505   rl_filename_quoting_desired = 1;
506   rl_completion_type = what_to_do;
507   rl_completion_suppress_append = rl_completion_suppress_quote = 0;
508   rl_completion_append_character = ' ';
509
510   /* The completion entry function may optionally change this. */
511   rl_completion_mark_symlink_dirs = _rl_complete_mark_symlink_dirs;
512
513   /* Reset private state. */
514   _rl_complete_display_matches_interrupt = 0;
515 }
516
517 /* The user must press "y" or "n". Non-zero return means "y" pressed. */
518 static int
519 get_y_or_n (int for_pager)
520 {
521   int c;
522
523   /* For now, disable pager in callback mode, until we later convert to state
524      driven functions.  Have to wait until next major version to add new
525      state definition, since it will change value of RL_STATE_DONE. */
526 #if defined (READLINE_CALLBACKS)
527   if (RL_ISSTATE (RL_STATE_CALLBACK))
528     return 1;
529 #endif
530
531   for (;;)
532     {
533       RL_SETSTATE(RL_STATE_MOREINPUT);
534       c = rl_read_key ();
535       RL_UNSETSTATE(RL_STATE_MOREINPUT);
536
537       if (c == 'y' || c == 'Y' || c == ' ')
538         return (1);
539       if (c == 'n' || c == 'N' || c == RUBOUT)
540         return (0);
541       if (c == ABORT_CHAR || c < 0)
542         _rl_abort_internal ();
543       if (for_pager && (c == NEWLINE || c == RETURN))
544         return (2);
545       if (for_pager && (c == 'q' || c == 'Q'))
546         return (0);
547       rl_ding ();
548     }
549 }
550
551 static int
552 _rl_internal_pager (int lines)
553 {
554   int i;
555
556   fprintf (rl_outstream, "--More--");
557   fflush (rl_outstream);
558   i = get_y_or_n (1);
559   _rl_erase_entire_line ();
560   if (i == 0)
561     return -1;
562   else if (i == 2)
563     return (lines - 1);
564   else
565     return 0;
566 }
567
568 static int
569 path_isdir (const char *filename)
570 {
571   struct stat finfo;
572
573   return (stat (filename, &finfo) == 0 && S_ISDIR (finfo.st_mode));
574 }
575
576 #if defined (VISIBLE_STATS)
577 /* Return the character which best describes FILENAME.
578      `@' for symbolic links
579      `/' for directories
580      `*' for executables
581      `=' for sockets
582      `|' for FIFOs
583      `%' for character special devices
584      `#' for block special devices */
585 static int
586 stat_char (char *filename)
587 {
588   struct stat finfo;
589   int character, r;
590   char *f;
591   const char *fn;
592
593   /* Short-circuit a //server on cygwin, since that will always behave as
594      a directory. */
595 #if __CYGWIN__
596   if (filename[0] == '/' && filename[1] == '/' && strchr (filename+2, '/') == 0)
597     return '/';
598 #endif
599
600   f = 0;
601   if (rl_filename_stat_hook)
602     {
603       f = savestring (filename);
604       (*rl_filename_stat_hook) (&f);
605       fn = f;
606     }
607   else
608     fn = filename;
609     
610 #if defined (HAVE_LSTAT) && defined (S_ISLNK)
611   r = lstat (fn, &finfo);
612 #else
613   r = stat (fn, &finfo);
614 #endif
615
616   if (r == -1)
617     {
618       xfree (f);
619       return (0);
620     }
621
622   character = 0;
623   if (S_ISDIR (finfo.st_mode))
624     character = '/';
625 #if defined (S_ISCHR)
626   else if (S_ISCHR (finfo.st_mode))
627     character = '%';
628 #endif /* S_ISCHR */
629 #if defined (S_ISBLK)
630   else if (S_ISBLK (finfo.st_mode))
631     character = '#';
632 #endif /* S_ISBLK */
633 #if defined (S_ISLNK)
634   else if (S_ISLNK (finfo.st_mode))
635     character = '@';
636 #endif /* S_ISLNK */
637 #if defined (S_ISSOCK)
638   else if (S_ISSOCK (finfo.st_mode))
639     character = '=';
640 #endif /* S_ISSOCK */
641 #if defined (S_ISFIFO)
642   else if (S_ISFIFO (finfo.st_mode))
643     character = '|';
644 #endif
645   else if (S_ISREG (finfo.st_mode))
646     {
647 #if defined (_WIN32) && !defined (__CYGWIN__)
648       char *ext;
649
650       /* Windows doesn't do access and X_OK; check file extension instead */
651       ext = strrchr (fn, '.');
652       if (ext && (_rl_stricmp (ext, ".exe") == 0 ||
653                   _rl_stricmp (ext, ".cmd") == 0 ||
654                   _rl_stricmp (ext, ".bat") == 0 ||
655                   _rl_stricmp (ext, ".com") == 0))
656         character = '*';
657 #else
658       if (access (filename, X_OK) == 0)
659         character = '*';
660 #endif
661     }
662
663   xfree (f);
664   return (character);
665 }
666 #endif /* VISIBLE_STATS */
667
668 #if defined (COLOR_SUPPORT)
669 static int
670 colored_stat_start (const char *filename)
671 {
672   _rl_set_normal_color ();
673   return (_rl_print_color_indicator (filename));
674 }
675
676 static void
677 colored_stat_end (void)
678 {
679   _rl_prep_non_filename_text ();
680   _rl_put_indicator (&_rl_color_indicator[C_CLR_TO_EOL]);
681 }
682
683 static int
684 colored_prefix_start (void)
685 {
686   _rl_set_normal_color ();
687   return (_rl_print_prefix_color ());
688 }
689
690 static void
691 colored_prefix_end (void)
692 {
693   colored_stat_end ();          /* for now */
694 }
695 #endif
696
697 /* Return the portion of PATHNAME that should be output when listing
698    possible completions.  If we are hacking filename completion, we
699    are only interested in the basename, the portion following the
700    final slash.  Otherwise, we return what we were passed.  Since
701    printing empty strings is not very informative, if we're doing
702    filename completion, and the basename is the empty string, we look
703    for the previous slash and return the portion following that.  If
704    there's no previous slash, we just return what we were passed. */
705 static char *
706 printable_part (char *pathname)
707 {
708   char *temp, *x;
709
710   if (rl_filename_completion_desired == 0)      /* don't need to do anything */
711     return (pathname);
712
713   temp = strrchr (pathname, '/');
714 #if defined (__MSDOS__) || defined (_WIN32)
715   if (temp == 0 && ISALPHA ((unsigned char)pathname[0]) && pathname[1] == ':')
716     temp = pathname + 1;
717 #endif
718
719   if (temp == 0 || *temp == '\0')
720     return (pathname);
721   else if (temp[1] == 0 && temp == pathname)
722     return (pathname);
723   /* If the basename is NULL, we might have a pathname like '/usr/src/'.
724      Look for a previous slash and, if one is found, return the portion
725      following that slash.  If there's no previous slash, just return the
726      pathname we were passed. */
727   else if (temp[1] == '\0')
728     {
729       for (x = temp - 1; x > pathname; x--)
730         if (*x == '/')
731           break;
732       return ((*x == '/') ? x + 1 : pathname);
733     }
734   else
735     return ++temp;
736 }
737
738 /* Compute width of STRING when displayed on screen by print_filename */
739 static int
740 fnwidth (const char *string)
741 {
742   int width, pos;
743 #if defined (HANDLE_MULTIBYTE)
744   mbstate_t ps;
745   int left, w;
746   size_t clen;
747   wchar_t wc;
748
749   left = strlen (string) + 1;
750   memset (&ps, 0, sizeof (mbstate_t));
751 #endif
752
753   width = pos = 0;
754   while (string[pos])
755     {
756       if (CTRL_CHAR (string[pos]) || string[pos] == RUBOUT)
757         {
758           width += 2;
759           pos++;
760         }
761       else
762         {
763 #if defined (HANDLE_MULTIBYTE)
764           clen = mbrtowc (&wc, string + pos, left - pos, &ps);
765           if (MB_INVALIDCH (clen))
766             {
767               width++;
768               pos++;
769               memset (&ps, 0, sizeof (mbstate_t));
770             }
771           else if (MB_NULLWCH (clen))
772             break;
773           else
774             {
775               pos += clen;
776               w = WCWIDTH (wc);
777               width += (w >= 0) ? w : 1;
778             }
779 #else
780           width++;
781           pos++;
782 #endif
783         }
784     }
785
786   return width;
787 }
788
789 #define ELLIPSIS_LEN    3
790
791 static int
792 fnprint (const char *to_print, int prefix_bytes, const char *real_pathname)
793 {
794   int printed_len, w;
795   const char *s;
796   int common_prefix_len, print_len;
797 #if defined (HANDLE_MULTIBYTE)
798   mbstate_t ps;
799   const char *end;
800   size_t tlen;
801   int width;
802   wchar_t wc;
803
804   print_len = strlen (to_print);
805   end = to_print + print_len + 1;
806   memset (&ps, 0, sizeof (mbstate_t));
807 #else
808   print_len = strlen (to_print);
809 #endif
810
811   printed_len = common_prefix_len = 0;
812
813   /* Don't print only the ellipsis if the common prefix is one of the
814      possible completions.  Only cut off prefix_bytes if we're going to be
815      printing the ellipsis, which takes precedence over coloring the
816      completion prefix (see print_filename() below). */
817   if (_rl_completion_prefix_display_length > 0 && prefix_bytes >= print_len)
818     prefix_bytes = 0;
819
820 #if defined (COLOR_SUPPORT)
821   if (_rl_colored_stats && (prefix_bytes == 0 || _rl_colored_completion_prefix <= 0))
822     colored_stat_start (real_pathname);
823 #endif
824
825   if (prefix_bytes && _rl_completion_prefix_display_length > 0)
826     {
827       char ellipsis;
828
829       ellipsis = (to_print[prefix_bytes] == '.') ? '_' : '.';
830       for (w = 0; w < ELLIPSIS_LEN; w++)
831         putc (ellipsis, rl_outstream);
832       printed_len = ELLIPSIS_LEN;
833     }
834 #if defined (COLOR_SUPPORT)
835   else if (prefix_bytes && _rl_colored_completion_prefix > 0)
836     {
837       common_prefix_len = prefix_bytes;
838       prefix_bytes = 0;
839       /* XXX - print color indicator start here */
840       colored_prefix_start ();
841     }
842 #endif
843
844   s = to_print + prefix_bytes;
845   while (*s)
846     {
847       if (CTRL_CHAR (*s))
848         {
849           putc ('^', rl_outstream);
850           putc (UNCTRL (*s), rl_outstream);
851           printed_len += 2;
852           s++;
853 #if defined (HANDLE_MULTIBYTE)
854           memset (&ps, 0, sizeof (mbstate_t));
855 #endif
856         }
857       else if (*s == RUBOUT)
858         {
859           putc ('^', rl_outstream);
860           putc ('?', rl_outstream);
861           printed_len += 2;
862           s++;
863 #if defined (HANDLE_MULTIBYTE)
864           memset (&ps, 0, sizeof (mbstate_t));
865 #endif
866         }
867       else
868         {
869 #if defined (HANDLE_MULTIBYTE)
870           tlen = mbrtowc (&wc, s, end - s, &ps);
871           if (MB_INVALIDCH (tlen))
872             {
873               tlen = 1;
874               width = 1;
875               memset (&ps, 0, sizeof (mbstate_t));
876             }
877           else if (MB_NULLWCH (tlen))
878             break;
879           else
880             {
881               w = WCWIDTH (wc);
882               width = (w >= 0) ? w : 1;
883             }
884           fwrite (s, 1, tlen, rl_outstream);
885           s += tlen;
886           printed_len += width;
887 #else
888           putc (*s, rl_outstream);
889           s++;
890           printed_len++;
891 #endif
892         }
893       if (common_prefix_len > 0 && (s - to_print) >= common_prefix_len)
894         {
895 #if defined (COLOR_SUPPORT)
896           /* printed bytes = s - to_print */
897           /* printed bytes should never be > but check for paranoia's sake */
898           colored_prefix_end ();
899           if (_rl_colored_stats)
900             colored_stat_start (real_pathname);         /* XXX - experiment */
901 #endif
902           common_prefix_len = 0;
903         }
904     }
905
906 #if defined (COLOR_SUPPORT)
907   /* XXX - unconditional for now */
908   if (_rl_colored_stats)
909     colored_stat_end ();
910 #endif
911
912   return printed_len;
913 }
914
915 /* Output TO_PRINT to rl_outstream.  If VISIBLE_STATS is defined and we
916    are using it, check for and output a single character for `special'
917    filenames.  Return the number of characters we output. */
918
919 static int
920 print_filename (char *to_print, char *full_pathname, int prefix_bytes)
921 {
922   int printed_len, extension_char, slen, tlen;
923   char *s, c, *new_full_pathname, *dn;
924
925   extension_char = 0;
926 #if defined (COLOR_SUPPORT)
927   /* Defer printing if we want to prefix with a color indicator */
928   if (_rl_colored_stats == 0 || rl_filename_completion_desired == 0)
929 #endif
930     printed_len = fnprint (to_print, prefix_bytes, to_print);
931
932   if (rl_filename_completion_desired && (
933 #if defined (VISIBLE_STATS)
934      rl_visible_stats ||
935 #endif
936 #if defined (COLOR_SUPPORT)
937      _rl_colored_stats ||
938 #endif
939      _rl_complete_mark_directories))
940     {
941       /* If to_print != full_pathname, to_print is the basename of the
942          path passed.  In this case, we try to expand the directory
943          name before checking for the stat character. */
944       if (to_print != full_pathname)
945         {
946           /* Terminate the directory name. */
947           c = to_print[-1];
948           to_print[-1] = '\0';
949
950           /* If setting the last slash in full_pathname to a NUL results in
951              full_pathname being the empty string, we are trying to complete
952              files in the root directory.  If we pass a null string to the
953              bash directory completion hook, for example, it will expand it
954              to the current directory.  We just want the `/'. */
955           if (full_pathname == 0 || *full_pathname == 0)
956             dn = "/";
957           else if (full_pathname[0] != '/')
958             dn = full_pathname;
959           else if (full_pathname[1] == 0)
960             dn = "//";          /* restore trailing slash to `//' */
961           else if (full_pathname[1] == '/' && full_pathname[2] == 0)
962             dn = "/";           /* don't turn /// into // */
963           else
964             dn = full_pathname;
965           s = tilde_expand (dn);
966           if (rl_directory_completion_hook)
967             (*rl_directory_completion_hook) (&s);
968
969           slen = strlen (s);
970           tlen = strlen (to_print);
971           new_full_pathname = (char *)xmalloc (slen + tlen + 2);
972           strcpy (new_full_pathname, s);
973           if (s[slen - 1] == '/')
974             slen--;
975           else
976             new_full_pathname[slen] = '/';
977           strcpy (new_full_pathname + slen + 1, to_print);
978
979 #if defined (VISIBLE_STATS)
980           if (rl_visible_stats)
981             extension_char = stat_char (new_full_pathname);
982           else
983 #endif
984           if (_rl_complete_mark_directories)
985             {
986               dn = 0;
987               if (rl_directory_completion_hook == 0 && rl_filename_stat_hook)
988                 {
989                   dn = savestring (new_full_pathname);
990                   (*rl_filename_stat_hook) (&dn);
991                   xfree (new_full_pathname);
992                   new_full_pathname = dn;
993                 }
994               if (path_isdir (new_full_pathname))
995                 extension_char = '/';
996             }
997
998           /* Move colored-stats code inside fnprint() */
999 #if defined (COLOR_SUPPORT)
1000           if (_rl_colored_stats)
1001             printed_len = fnprint (to_print, prefix_bytes, new_full_pathname);
1002 #endif
1003
1004           xfree (new_full_pathname);
1005           to_print[-1] = c;
1006         }
1007       else
1008         {
1009           s = tilde_expand (full_pathname);
1010 #if defined (VISIBLE_STATS)
1011           if (rl_visible_stats)
1012             extension_char = stat_char (s);
1013           else
1014 #endif
1015             if (_rl_complete_mark_directories && path_isdir (s))
1016               extension_char = '/';
1017
1018           /* Move colored-stats code inside fnprint() */
1019 #if defined (COLOR_SUPPORT)
1020           if (_rl_colored_stats)
1021             printed_len = fnprint (to_print, prefix_bytes, s);
1022 #endif
1023         }
1024
1025       xfree (s);
1026       if (extension_char)
1027         {
1028           putc (extension_char, rl_outstream);
1029           printed_len++;
1030         }
1031     }
1032
1033   return printed_len;
1034 }
1035
1036 static char *
1037 rl_quote_filename (char *s, int rtype, char *qcp)
1038 {
1039   char *r;
1040
1041   r = (char *)xmalloc (strlen (s) + 2);
1042   *r = *rl_completer_quote_characters;
1043   strcpy (r + 1, s);
1044   if (qcp)
1045     *qcp = *rl_completer_quote_characters;
1046   return r;
1047 }
1048
1049 /* Find the bounds of the current word for completion purposes, and leave
1050    rl_point set to the end of the word.  This function skips quoted
1051    substrings (characters between matched pairs of characters in
1052    rl_completer_quote_characters).  First we try to find an unclosed
1053    quoted substring on which to do matching.  If one is not found, we use
1054    the word break characters to find the boundaries of the current word.
1055    We call an application-specific function to decide whether or not a
1056    particular word break character is quoted; if that function returns a
1057    non-zero result, the character does not break a word.  This function
1058    returns the opening quote character if we found an unclosed quoted
1059    substring, '\0' otherwise.  FP, if non-null, is set to a value saying
1060    which (shell-like) quote characters we found (single quote, double
1061    quote, or backslash) anywhere in the string.  DP, if non-null, is set to
1062    the value of the delimiter character that caused a word break. */
1063
1064 char
1065 _rl_find_completion_word (int *fp, int *dp)
1066 {
1067   int scan, end, found_quote, delimiter, pass_next, isbrk;
1068   char quote_char, *brkchars;
1069
1070   end = rl_point;
1071   found_quote = delimiter = 0;
1072   quote_char = '\0';
1073
1074   brkchars = 0;
1075   if (rl_completion_word_break_hook)
1076     brkchars = (*rl_completion_word_break_hook) ();
1077   if (brkchars == 0)
1078     brkchars = rl_completer_word_break_characters;
1079
1080   if (rl_completer_quote_characters)
1081     {
1082       /* We have a list of characters which can be used in pairs to
1083          quote substrings for the completer.  Try to find the start
1084          of an unclosed quoted substring. */
1085       /* FOUND_QUOTE is set so we know what kind of quotes we found. */
1086       for (scan = pass_next = 0; scan < end; scan = MB_NEXTCHAR (rl_line_buffer, scan, 1, MB_FIND_ANY))
1087         {
1088           if (pass_next)
1089             {
1090               pass_next = 0;
1091               continue;
1092             }
1093
1094           /* Shell-like semantics for single quotes -- don't allow backslash
1095              to quote anything in single quotes, especially not the closing
1096              quote.  If you don't like this, take out the check on the value
1097              of quote_char. */
1098           if (quote_char != '\'' && rl_line_buffer[scan] == '\\')
1099             {
1100               pass_next = 1;
1101               found_quote |= RL_QF_BACKSLASH;
1102               continue;
1103             }
1104
1105           if (quote_char != '\0')
1106             {
1107               /* Ignore everything until the matching close quote char. */
1108               if (rl_line_buffer[scan] == quote_char)
1109                 {
1110                   /* Found matching close.  Abandon this substring. */
1111                   quote_char = '\0';
1112                   rl_point = end;
1113                 }
1114             }
1115           else if (strchr (rl_completer_quote_characters, rl_line_buffer[scan]))
1116             {
1117               /* Found start of a quoted substring. */
1118               quote_char = rl_line_buffer[scan];
1119               rl_point = scan + 1;
1120               /* Shell-like quoting conventions. */
1121               if (quote_char == '\'')
1122                 found_quote |= RL_QF_SINGLE_QUOTE;
1123               else if (quote_char == '"')
1124                 found_quote |= RL_QF_DOUBLE_QUOTE;
1125               else
1126                 found_quote |= RL_QF_OTHER_QUOTE;      
1127             }
1128         }
1129     }
1130
1131   if (rl_point == end && quote_char == '\0')
1132     {
1133       /* We didn't find an unclosed quoted substring upon which to do
1134          completion, so use the word break characters to find the
1135          substring on which to complete. */
1136       while (rl_point = MB_PREVCHAR (rl_line_buffer, rl_point, MB_FIND_ANY))
1137         {
1138           scan = rl_line_buffer[rl_point];
1139
1140           if (strchr (brkchars, scan) == 0)
1141             continue;
1142
1143           /* Call the application-specific function to tell us whether
1144              this word break character is quoted and should be skipped. */
1145           if (rl_char_is_quoted_p && found_quote &&
1146               (*rl_char_is_quoted_p) (rl_line_buffer, rl_point))
1147             continue;
1148
1149           /* Convoluted code, but it avoids an n^2 algorithm with calls
1150              to char_is_quoted. */
1151           break;
1152         }
1153     }
1154
1155   /* If we are at an unquoted word break, then advance past it. */
1156   scan = rl_line_buffer[rl_point];
1157
1158   /* If there is an application-specific function to say whether or not
1159      a character is quoted and we found a quote character, let that
1160      function decide whether or not a character is a word break, even
1161      if it is found in rl_completer_word_break_characters.  Don't bother
1162      if we're at the end of the line, though. */
1163   if (scan)
1164     {
1165       if (rl_char_is_quoted_p)
1166         isbrk = (found_quote == 0 ||
1167                 (*rl_char_is_quoted_p) (rl_line_buffer, rl_point) == 0) &&
1168                 strchr (brkchars, scan) != 0;
1169       else
1170         isbrk = strchr (brkchars, scan) != 0;
1171
1172       if (isbrk)
1173         {
1174           /* If the character that caused the word break was a quoting
1175              character, then remember it as the delimiter. */
1176           if (rl_basic_quote_characters &&
1177               strchr (rl_basic_quote_characters, scan) &&
1178               (end - rl_point) > 1)
1179             delimiter = scan;
1180
1181           /* If the character isn't needed to determine something special
1182              about what kind of completion to perform, then advance past it. */
1183           if (rl_special_prefixes == 0 || strchr (rl_special_prefixes, scan) == 0)
1184             rl_point++;
1185         }
1186     }
1187
1188   if (fp)
1189     *fp = found_quote;
1190   if (dp)
1191     *dp = delimiter;
1192
1193   return (quote_char);
1194 }
1195
1196 static char **
1197 gen_completion_matches (char *text, int start, int end, rl_compentry_func_t *our_func, int found_quote, int quote_char)
1198 {
1199   char **matches;
1200
1201   rl_completion_found_quote = found_quote;
1202   rl_completion_quote_character = quote_char;
1203
1204   /* If the user wants to TRY to complete, but then wants to give
1205      up and use the default completion function, they set the
1206      variable rl_attempted_completion_function. */
1207   if (rl_attempted_completion_function)
1208     {
1209       matches = (*rl_attempted_completion_function) (text, start, end);
1210       if (RL_SIG_RECEIVED())
1211         {
1212           _rl_free_match_list (matches);
1213           matches = 0;
1214           RL_CHECK_SIGNALS ();
1215         }
1216
1217       if (matches || rl_attempted_completion_over)
1218         {
1219           rl_attempted_completion_over = 0;
1220           return (matches);
1221         }
1222     }
1223
1224   /* XXX -- filename dequoting moved into rl_filename_completion_function */
1225
1226   /* rl_completion_matches will check for signals as well to avoid a long
1227      delay while reading a directory. */
1228   matches = rl_completion_matches (text, our_func);
1229   if (RL_SIG_RECEIVED())
1230     {
1231       _rl_free_match_list (matches);
1232       matches = 0;
1233       RL_CHECK_SIGNALS ();
1234     }
1235   return matches;  
1236 }
1237
1238 /* Filter out duplicates in MATCHES.  This frees up the strings in
1239    MATCHES. */
1240 static char **
1241 remove_duplicate_matches (char **matches)
1242 {
1243   char *lowest_common;
1244   int i, j, newlen;
1245   char dead_slot;
1246   char **temp_array;
1247
1248   /* Sort the items. */
1249   for (i = 0; matches[i]; i++)
1250     ;
1251
1252   /* Sort the array without matches[0], since we need it to
1253      stay in place no matter what. */
1254   if (i && rl_sort_completion_matches)
1255     qsort (matches+1, i-1, sizeof (char *), (QSFUNC *)_rl_qsort_string_compare);
1256
1257   /* Remember the lowest common denominator for it may be unique. */
1258   lowest_common = savestring (matches[0]);
1259
1260   for (i = newlen = 0; matches[i + 1]; i++)
1261     {
1262       if (strcmp (matches[i], matches[i + 1]) == 0)
1263         {
1264           xfree (matches[i]);
1265           matches[i] = (char *)&dead_slot;
1266         }
1267       else
1268         newlen++;
1269     }
1270
1271   /* We have marked all the dead slots with (char *)&dead_slot.
1272      Copy all the non-dead entries into a new array. */
1273   temp_array = (char **)xmalloc ((3 + newlen) * sizeof (char *));
1274   for (i = j = 1; matches[i]; i++)
1275     {
1276       if (matches[i] != (char *)&dead_slot)
1277         temp_array[j++] = matches[i];
1278     }
1279   temp_array[j] = (char *)NULL;
1280
1281   if (matches[0] != (char *)&dead_slot)
1282     xfree (matches[0]);
1283
1284   /* Place the lowest common denominator back in [0]. */
1285   temp_array[0] = lowest_common;
1286
1287   /* If there is one string left, and it is identical to the
1288      lowest common denominator, then the LCD is the string to
1289      insert. */
1290   if (j == 2 && strcmp (temp_array[0], temp_array[1]) == 0)
1291     {
1292       xfree (temp_array[1]);
1293       temp_array[1] = (char *)NULL;
1294     }
1295   return (temp_array);
1296 }
1297
1298 /* Find the common prefix of the list of matches, and put it into
1299    matches[0]. */
1300 static int
1301 compute_lcd_of_matches (char **match_list, int matches, const char *text)
1302 {
1303   register int i, c1, c2, si;
1304   int low;              /* Count of max-matched characters. */
1305   int lx;
1306   char *dtext;          /* dequoted TEXT, if needed */
1307 #if defined (HANDLE_MULTIBYTE)
1308   int v;
1309   size_t v1, v2;
1310   mbstate_t ps1, ps2;
1311   wchar_t wc1, wc2;
1312 #endif
1313
1314   /* If only one match, just use that.  Otherwise, compare each
1315      member of the list with the next, finding out where they
1316      stop matching. */
1317   if (matches == 1)
1318     {
1319       match_list[0] = match_list[1];
1320       match_list[1] = (char *)NULL;
1321       return 1;
1322     }
1323
1324   for (i = 1, low = 100000; i < matches; i++)
1325     {
1326 #if defined (HANDLE_MULTIBYTE)
1327       if (MB_CUR_MAX > 1 && rl_byte_oriented == 0)
1328         {
1329           memset (&ps1, 0, sizeof (mbstate_t));
1330           memset (&ps2, 0, sizeof (mbstate_t));
1331         }
1332 #endif
1333       if (_rl_completion_case_fold)
1334         {
1335           for (si = 0;
1336                (c1 = _rl_to_lower(match_list[i][si])) &&
1337                (c2 = _rl_to_lower(match_list[i + 1][si]));
1338                si++)
1339 #if defined (HANDLE_MULTIBYTE)
1340             if (MB_CUR_MAX > 1 && rl_byte_oriented == 0)
1341               {
1342                 v1 = mbrtowc(&wc1, match_list[i]+si, strlen (match_list[i]+si), &ps1);
1343                 v2 = mbrtowc (&wc2, match_list[i+1]+si, strlen (match_list[i+1]+si), &ps2);
1344                 if (MB_INVALIDCH (v1) || MB_INVALIDCH (v2))
1345                   {
1346                     if (c1 != c2)       /* do byte comparison */
1347                       break;
1348                     continue;
1349                   }
1350                 wc1 = towlower (wc1);
1351                 wc2 = towlower (wc2);
1352                 if (wc1 != wc2)
1353                   break;
1354                 else if (v1 > 1)
1355                   si += v1 - 1;
1356               }
1357             else
1358 #endif
1359             if (c1 != c2)
1360               break;
1361         }
1362       else
1363         {
1364           for (si = 0;
1365                (c1 = match_list[i][si]) &&
1366                (c2 = match_list[i + 1][si]);
1367                si++)
1368 #if defined (HANDLE_MULTIBYTE)
1369             if (MB_CUR_MAX > 1 && rl_byte_oriented == 0)
1370               {
1371                 mbstate_t ps_back;
1372                 ps_back = ps1;
1373                 if (!_rl_compare_chars (match_list[i], si, &ps1, match_list[i+1], si, &ps2))
1374                   break;
1375                 else if ((v = _rl_get_char_len (&match_list[i][si], &ps_back)) > 1)
1376                   si += v - 1;
1377               }
1378             else
1379 #endif
1380             if (c1 != c2)
1381               break;
1382         }
1383
1384       if (low > si)
1385         low = si;
1386     }
1387
1388   /* If there were multiple matches, but none matched up to even the
1389      first character, and the user typed something, use that as the
1390      value of matches[0]. */
1391   if (low == 0 && text && *text)
1392     {
1393       match_list[0] = (char *)xmalloc (strlen (text) + 1);
1394       strcpy (match_list[0], text);
1395     }
1396   else
1397     {
1398       match_list[0] = (char *)xmalloc (low + 1);
1399
1400       /* XXX - this might need changes in the presence of multibyte chars */
1401
1402       /* If we are ignoring case, try to preserve the case of the string
1403          the user typed in the face of multiple matches differing in case. */
1404       if (_rl_completion_case_fold)
1405         {
1406           /* We're making an assumption here:
1407                 IF we're completing filenames AND
1408                    the application has defined a filename dequoting function AND
1409                    we found a quote character AND
1410                    the application has requested filename quoting
1411                 THEN
1412                    we assume that TEXT was dequoted before checking against
1413                    the file system and needs to be dequoted here before we
1414                    check against the list of matches
1415                 FI */
1416           dtext = (char *)NULL;
1417           if (rl_filename_completion_desired &&
1418               rl_filename_dequoting_function &&
1419               rl_completion_found_quote &&
1420               rl_filename_quoting_desired)
1421             {
1422               dtext = (*rl_filename_dequoting_function) ((char *)text, rl_completion_quote_character);
1423               text = dtext;
1424             }
1425
1426           /* sort the list to get consistent answers. */
1427           if (rl_sort_completion_matches)
1428             qsort (match_list+1, matches, sizeof(char *), (QSFUNC *)_rl_qsort_string_compare);
1429
1430           si = strlen (text);
1431           lx = (si <= low) ? si : low;  /* check shorter of text and matches */
1432           /* Try to preserve the case of what the user typed in the presence of
1433              multiple matches: check each match for something that matches
1434              what the user typed taking case into account; use it up to common
1435              length of matches if one is found.  If not, just use first match. */
1436           for (i = 1; i <= matches; i++)
1437             if (strncmp (match_list[i], text, lx) == 0)
1438               {
1439                 strncpy (match_list[0], match_list[i], low);
1440                 break;
1441               }
1442           /* no casematch, use first entry */
1443           if (i > matches)
1444             strncpy (match_list[0], match_list[1], low);
1445
1446           FREE (dtext);
1447         }
1448       else
1449         strncpy (match_list[0], match_list[1], low);
1450
1451       match_list[0][low] = '\0';
1452     }
1453
1454   return matches;
1455 }
1456
1457 static int
1458 postprocess_matches (char ***matchesp, int matching_filenames)
1459 {
1460   char *t, **matches, **temp_matches;
1461   int nmatch, i;
1462
1463   matches = *matchesp;
1464
1465   if (matches == 0)
1466     return 0;
1467
1468   /* It seems to me that in all the cases we handle we would like
1469      to ignore duplicate possibilities.  Scan for the text to
1470      insert being identical to the other completions. */
1471   if (rl_ignore_completion_duplicates)
1472     {
1473       temp_matches = remove_duplicate_matches (matches);
1474       xfree (matches);
1475       matches = temp_matches;
1476     }
1477
1478   /* If we are matching filenames, then here is our chance to
1479      do clever processing by re-examining the list.  Call the
1480      ignore function with the array as a parameter.  It can
1481      munge the array, deleting matches as it desires. */
1482   if (rl_ignore_some_completions_function && matching_filenames)
1483     {
1484       for (nmatch = 1; matches[nmatch]; nmatch++)
1485         ;
1486       (void)(*rl_ignore_some_completions_function) (matches);
1487       if (matches == 0 || matches[0] == 0)
1488         {
1489           FREE (matches);
1490           *matchesp = (char **)0;
1491           return 0;
1492         }
1493       else
1494         {
1495           /* If we removed some matches, recompute the common prefix. */
1496           for (i = 1; matches[i]; i++)
1497             ;
1498           if (i > 1 && i < nmatch)
1499             {
1500               t = matches[0];
1501               compute_lcd_of_matches (matches, i - 1, t);
1502               FREE (t);
1503             }
1504         }
1505     }
1506
1507   *matchesp = matches;
1508   return (1);
1509 }
1510
1511 static int
1512 complete_get_screenwidth (void)
1513 {
1514   int cols;
1515   char *envcols;
1516
1517   cols = _rl_completion_columns;
1518   if (cols >= 0 && cols <= _rl_screenwidth)
1519     return cols;
1520   envcols = getenv ("COLUMNS");
1521   if (envcols && *envcols)
1522     cols = atoi (envcols);
1523   if (cols >= 0 && cols <= _rl_screenwidth)
1524     return cols;
1525   return _rl_screenwidth;
1526 }
1527
1528 /* A convenience function for displaying a list of strings in
1529    columnar format on readline's output stream.  MATCHES is the list
1530    of strings, in argv format, LEN is the number of strings in MATCHES,
1531    and MAX is the length of the longest string in MATCHES. */
1532 void
1533 rl_display_match_list (char **matches, int len, int max)
1534 {
1535   int count, limit, printed_len, lines, cols;
1536   int i, j, k, l, common_length, sind;
1537   char *temp, *t;
1538
1539   /* Find the length of the prefix common to all items: length as displayed
1540      characters (common_length) and as a byte index into the matches (sind) */
1541   common_length = sind = 0;
1542   if (_rl_completion_prefix_display_length > 0)
1543     {
1544       t = printable_part (matches[0]);
1545       /* check again in case of /usr/src/ */
1546       temp = rl_filename_completion_desired ? strrchr (t, '/') : 0;
1547       common_length = temp ? fnwidth (temp) : fnwidth (t);
1548       sind = temp ? strlen (temp) : strlen (t);
1549       if (common_length > max || sind > max)
1550         common_length = sind = 0;
1551
1552       if (common_length > _rl_completion_prefix_display_length && common_length > ELLIPSIS_LEN)
1553         max -= common_length - ELLIPSIS_LEN;
1554       else
1555         common_length = sind = 0;
1556     }
1557 #if defined (COLOR_SUPPORT)
1558   else if (_rl_colored_completion_prefix > 0)
1559     {
1560       t = printable_part (matches[0]);
1561       temp = rl_filename_completion_desired ? strrchr (t, '/') : 0;
1562       common_length = temp ? fnwidth (temp) : fnwidth (t);
1563       sind = temp ? RL_STRLEN (temp+1) : RL_STRLEN (t);         /* want portion after final slash */
1564       if (common_length > max || sind > max)
1565         common_length = sind = 0;
1566     }
1567 #endif
1568
1569   /* How many items of MAX length can we fit in the screen window? */
1570   cols = complete_get_screenwidth ();
1571   max += 2;
1572   limit = cols / max;
1573   if (limit != 1 && (limit * max == cols))
1574     limit--;
1575
1576   /* If cols == 0, limit will end up -1 */
1577   if (cols < _rl_screenwidth && limit < 0)
1578     limit = 1;
1579
1580   /* Avoid a possible floating exception.  If max > cols,
1581      limit will be 0 and a divide-by-zero fault will result. */
1582   if (limit == 0)
1583     limit = 1;
1584
1585   /* How many iterations of the printing loop? */
1586   count = (len + (limit - 1)) / limit;
1587
1588   /* Watch out for special case.  If LEN is less than LIMIT, then
1589      just do the inner printing loop.
1590            0 < len <= limit  implies  count = 1. */
1591
1592   /* Sort the items if they are not already sorted. */
1593   if (rl_ignore_completion_duplicates == 0 && rl_sort_completion_matches)
1594     qsort (matches + 1, len, sizeof (char *), (QSFUNC *)_rl_qsort_string_compare);
1595
1596   rl_crlf ();
1597
1598   lines = 0;
1599   if (_rl_print_completions_horizontally == 0)
1600     {
1601       /* Print the sorted items, up-and-down alphabetically, like ls. */
1602       for (i = 1; i <= count; i++)
1603         {
1604           for (j = 0, l = i; j < limit; j++)
1605             {
1606               if (l > len || matches[l] == 0)
1607                 break;
1608               else
1609                 {
1610                   temp = printable_part (matches[l]);
1611                   printed_len = print_filename (temp, matches[l], sind);
1612
1613                   if (j + 1 < limit)
1614                     {
1615                       if (max <= printed_len)
1616                         putc (' ', rl_outstream);
1617                       else
1618                         for (k = 0; k < max - printed_len; k++)
1619                           putc (' ', rl_outstream);
1620                     }
1621                 }
1622               l += count;
1623             }
1624           rl_crlf ();
1625 #if defined (SIGWINCH)
1626           if (RL_SIG_RECEIVED () && RL_SIGWINCH_RECEIVED() == 0)
1627 #else
1628           if (RL_SIG_RECEIVED ())
1629 #endif
1630             return;
1631           lines++;
1632           if (_rl_page_completions && lines >= (_rl_screenheight - 1) && i < count)
1633             {
1634               lines = _rl_internal_pager (lines);
1635               if (lines < 0)
1636                 return;
1637             }
1638         }
1639     }
1640   else
1641     {
1642       /* Print the sorted items, across alphabetically, like ls -x. */
1643       for (i = 1; matches[i]; i++)
1644         {
1645           temp = printable_part (matches[i]);
1646           printed_len = print_filename (temp, matches[i], sind);
1647           /* Have we reached the end of this line? */
1648 #if defined (SIGWINCH)
1649           if (RL_SIG_RECEIVED () && RL_SIGWINCH_RECEIVED() == 0)
1650 #else
1651           if (RL_SIG_RECEIVED ())
1652 #endif
1653             return;
1654           if (matches[i+1])
1655             {
1656               if (limit == 1 || (i && (limit > 1) && (i % limit) == 0))
1657                 {
1658                   rl_crlf ();
1659                   lines++;
1660                   if (_rl_page_completions && lines >= _rl_screenheight - 1)
1661                     {
1662                       lines = _rl_internal_pager (lines);
1663                       if (lines < 0)
1664                         return;
1665                     }
1666                 }
1667               else if (max <= printed_len)
1668                 putc (' ', rl_outstream);
1669               else
1670                 for (k = 0; k < max - printed_len; k++)
1671                   putc (' ', rl_outstream);
1672             }
1673         }
1674       rl_crlf ();
1675     }
1676 }
1677
1678 /* Display MATCHES, a list of matching filenames in argv format.  This
1679    handles the simple case -- a single match -- first.  If there is more
1680    than one match, we compute the number of strings in the list and the
1681    length of the longest string, which will be needed by the display
1682    function.  If the application wants to handle displaying the list of
1683    matches itself, it sets RL_COMPLETION_DISPLAY_MATCHES_HOOK to the
1684    address of a function, and we just call it.  If we're handling the
1685    display ourselves, we just call rl_display_match_list.  We also check
1686    that the list of matches doesn't exceed the user-settable threshold,
1687    and ask the user if he wants to see the list if there are more matches
1688    than RL_COMPLETION_QUERY_ITEMS. */
1689 static void
1690 display_matches (char **matches)
1691 {
1692   int len, max, i;
1693   char *temp;
1694
1695   /* Move to the last visible line of a possibly-multiple-line command. */
1696   _rl_move_vert (_rl_vis_botlin);
1697
1698   /* Handle simple case first.  What if there is only one answer? */
1699   if (matches[1] == 0)
1700     {
1701       temp = printable_part (matches[0]);
1702       rl_crlf ();
1703       print_filename (temp, matches[0], 0);
1704       rl_crlf ();
1705
1706       rl_forced_update_display ();
1707       rl_display_fixed = 1;
1708
1709       return;
1710     }
1711
1712   /* There is more than one answer.  Find out how many there are,
1713      and find the maximum printed length of a single entry. */
1714   for (max = 0, i = 1; matches[i]; i++)
1715     {
1716       temp = printable_part (matches[i]);
1717       len = fnwidth (temp);
1718
1719       if (len > max)
1720         max = len;
1721     }
1722
1723   len = i - 1;
1724
1725   /* If the caller has defined a display hook, then call that now. */
1726   if (rl_completion_display_matches_hook)
1727     {
1728       (*rl_completion_display_matches_hook) (matches, len, max);
1729       return;
1730     }
1731         
1732   /* If there are many items, then ask the user if she really wants to
1733      see them all. */
1734   if (rl_completion_query_items > 0 && len >= rl_completion_query_items)
1735     {
1736       rl_crlf ();
1737       fprintf (rl_outstream, "Display all %d possibilities? (y or n)", len);
1738       fflush (rl_outstream);
1739       if ((completion_y_or_n = get_y_or_n (0)) == 0)
1740         {
1741           rl_crlf ();
1742
1743           rl_forced_update_display ();
1744           rl_display_fixed = 1;
1745
1746           return;
1747         }
1748     }
1749
1750   rl_display_match_list (matches, len, max);
1751
1752   rl_forced_update_display ();
1753   rl_display_fixed = 1;
1754 }
1755
1756 /* qc == pointer to quoting character, if any */
1757 static char *
1758 make_quoted_replacement (char *match, int mtype, char *qc)
1759 {
1760   int should_quote, do_replace;
1761   char *replacement;
1762
1763   /* If we are doing completion on quoted substrings, and any matches
1764      contain any of the completer_word_break_characters, then auto-
1765      matically prepend the substring with a quote character (just pick
1766      the first one from the list of such) if it does not already begin
1767      with a quote string.  FIXME: Need to remove any such automatically
1768      inserted quote character when it no longer is necessary, such as
1769      if we change the string we are completing on and the new set of
1770      matches don't require a quoted substring. */
1771   replacement = match;
1772
1773   should_quote = match && rl_completer_quote_characters &&
1774                         rl_filename_completion_desired &&
1775                         rl_filename_quoting_desired;
1776
1777   if (should_quote)
1778     should_quote = should_quote && (!qc || !*qc ||
1779                      (rl_completer_quote_characters && strchr (rl_completer_quote_characters, *qc)));
1780
1781   if (should_quote)
1782     {
1783       /* If there is a single match, see if we need to quote it.
1784          This also checks whether the common prefix of several
1785          matches needs to be quoted. */
1786       should_quote = rl_filename_quote_characters
1787                         ? (_rl_strpbrk (match, rl_filename_quote_characters) != 0)
1788                         : 0;
1789
1790       do_replace = should_quote ? mtype : NO_MATCH;
1791       /* Quote the replacement, since we found an embedded
1792          word break character in a potential match. */
1793       if (do_replace != NO_MATCH && rl_filename_quoting_function)
1794         replacement = (*rl_filename_quoting_function) (match, do_replace, qc);
1795     }
1796   return (replacement);
1797 }
1798
1799 static void
1800 insert_match (char *match, int start, int mtype, char *qc)
1801 {
1802   char *replacement, *r;
1803   char oqc;
1804   int end, rlen;
1805
1806   oqc = qc ? *qc : '\0';
1807   replacement = make_quoted_replacement (match, mtype, qc);
1808
1809   /* Now insert the match. */
1810   if (replacement)
1811     {
1812       rlen = strlen (replacement);
1813       /* Don't double an opening quote character. */
1814       if (qc && *qc && start && rl_line_buffer[start - 1] == *qc &&
1815             replacement[0] == *qc)
1816         start--;
1817       /* If make_quoted_replacement changed the quoting character, remove
1818          the opening quote and insert the (fully-quoted) replacement. */
1819       else if (qc && (*qc != oqc) && start && rl_line_buffer[start - 1] == oqc &&
1820             replacement[0] != oqc)
1821         start--;
1822       end = rl_point - 1;
1823       /* Don't double a closing quote character */
1824       if (qc && *qc && end && rl_line_buffer[rl_point] == *qc && replacement[rlen - 1] == *qc)
1825         end++;
1826       if (_rl_skip_completed_text)
1827         {
1828           r = replacement;
1829           while (start < rl_end && *r && rl_line_buffer[start] == *r)
1830             {
1831               start++;
1832               r++;
1833             }
1834           if (start <= end || *r)
1835             _rl_replace_text (r, start, end);
1836           rl_point = start + strlen (r);
1837         }
1838       else
1839         _rl_replace_text (replacement, start, end);
1840       if (replacement != match)
1841         xfree (replacement);
1842     }
1843 }
1844
1845 /* Append any necessary closing quote and a separator character to the
1846    just-inserted match.  If the user has specified that directories
1847    should be marked by a trailing `/', append one of those instead.  The
1848    default trailing character is a space.  Returns the number of characters
1849    appended.  If NONTRIVIAL_MATCH is set, we test for a symlink (if the OS
1850    has them) and don't add a suffix for a symlink to a directory.  A
1851    nontrivial match is one that actually adds to the word being completed.
1852    The variable rl_completion_mark_symlink_dirs controls this behavior
1853    (it's initially set to the what the user has chosen, indicated by the
1854    value of _rl_complete_mark_symlink_dirs, but may be modified by an
1855    application's completion function). */
1856 static int
1857 append_to_match (char *text, int delimiter, int quote_char, int nontrivial_match)
1858 {
1859   char temp_string[4], *filename, *fn;
1860   int temp_string_index, s;
1861   struct stat finfo;
1862
1863   temp_string_index = 0;
1864   if (quote_char && rl_point && rl_completion_suppress_quote == 0 &&
1865       rl_line_buffer[rl_point - 1] != quote_char)
1866     temp_string[temp_string_index++] = quote_char;
1867
1868   if (delimiter)
1869     temp_string[temp_string_index++] = delimiter;
1870   else if (rl_completion_suppress_append == 0 && rl_completion_append_character)
1871     temp_string[temp_string_index++] = rl_completion_append_character;
1872
1873   temp_string[temp_string_index++] = '\0';
1874
1875   if (rl_filename_completion_desired)
1876     {
1877       filename = tilde_expand (text);
1878       if (rl_filename_stat_hook)
1879         {
1880           fn = savestring (filename);
1881           (*rl_filename_stat_hook) (&fn);
1882           xfree (filename);
1883           filename = fn;
1884         }
1885       s = (nontrivial_match && rl_completion_mark_symlink_dirs == 0)
1886                 ? LSTAT (filename, &finfo)
1887                 : stat (filename, &finfo);
1888       if (s == 0 && S_ISDIR (finfo.st_mode))
1889         {
1890           if (_rl_complete_mark_directories /* && rl_completion_suppress_append == 0 */)
1891             {
1892               /* This is clumsy.  Avoid putting in a double slash if point
1893                  is at the end of the line and the previous character is a
1894                  slash. */
1895               if (rl_point && rl_line_buffer[rl_point] == '\0' && rl_line_buffer[rl_point - 1] == '/')
1896                 ;
1897               else if (rl_line_buffer[rl_point] != '/')
1898                 rl_insert_text ("/");
1899             }
1900         }
1901 #ifdef S_ISLNK
1902       /* Don't add anything if the filename is a symlink and resolves to a
1903          directory. */
1904       else if (s == 0 && S_ISLNK (finfo.st_mode) && path_isdir (filename))
1905         ;
1906 #endif
1907       else
1908         {
1909           if (rl_point == rl_end && temp_string_index)
1910             rl_insert_text (temp_string);
1911         }
1912       xfree (filename);
1913     }
1914   else
1915     {
1916       if (rl_point == rl_end && temp_string_index)
1917         rl_insert_text (temp_string);
1918     }
1919
1920   return (temp_string_index);
1921 }
1922
1923 static void
1924 insert_all_matches (char **matches, int point, char *qc)
1925 {
1926   int i;
1927   char *rp;
1928
1929   rl_begin_undo_group ();
1930   /* remove any opening quote character; make_quoted_replacement will add
1931      it back. */
1932   if (qc && *qc && point && rl_line_buffer[point - 1] == *qc)
1933     point--;
1934   rl_delete_text (point, rl_point);
1935   rl_point = point;
1936
1937   if (matches[1])
1938     {
1939       for (i = 1; matches[i]; i++)
1940         {
1941           rp = make_quoted_replacement (matches[i], SINGLE_MATCH, qc);
1942           rl_insert_text (rp);
1943           rl_insert_text (" ");
1944           if (rp != matches[i])
1945             xfree (rp);
1946         }
1947     }
1948   else
1949     {
1950       rp = make_quoted_replacement (matches[0], SINGLE_MATCH, qc);
1951       rl_insert_text (rp);
1952       rl_insert_text (" ");
1953       if (rp != matches[0])
1954         xfree (rp);
1955     }
1956   rl_end_undo_group ();
1957 }
1958
1959 void
1960 _rl_free_match_list (char **matches)
1961 {
1962   register int i;
1963
1964   if (matches == 0)
1965     return;
1966
1967   for (i = 0; matches[i]; i++)
1968     xfree (matches[i]);
1969   xfree (matches);
1970 }
1971
1972 /* Complete the word at or before point.
1973    WHAT_TO_DO says what to do with the completion.
1974    `?' means list the possible completions.
1975    TAB means do standard completion.
1976    `*' means insert all of the possible completions.
1977    `!' means to do standard completion, and list all possible completions if
1978    there is more than one.
1979    `@' means to do standard completion, and list all possible completions if
1980    there is more than one and partial completion is not possible. */
1981 int
1982 rl_complete_internal (int what_to_do)
1983 {
1984   char **matches;
1985   rl_compentry_func_t *our_func;
1986   int start, end, delimiter, found_quote, i, nontrivial_lcd;
1987   char *text, *saved_line_buffer;
1988   char quote_char;
1989   int tlen, mlen;
1990
1991   RL_SETSTATE(RL_STATE_COMPLETING);
1992
1993   set_completion_defaults (what_to_do);
1994
1995   saved_line_buffer = rl_line_buffer ? savestring (rl_line_buffer) : (char *)NULL;
1996   our_func = rl_completion_entry_function
1997                 ? rl_completion_entry_function
1998                 : rl_filename_completion_function;
1999   /* We now look backwards for the start of a filename/variable word. */
2000   end = rl_point;
2001   found_quote = delimiter = 0;
2002   quote_char = '\0';
2003
2004   if (rl_point)
2005     /* This (possibly) changes rl_point.  If it returns a non-zero char,
2006        we know we have an open quote. */
2007     quote_char = _rl_find_completion_word (&found_quote, &delimiter);
2008
2009   start = rl_point;
2010   rl_point = end;
2011
2012   text = rl_copy_text (start, end);
2013   matches = gen_completion_matches (text, start, end, our_func, found_quote, quote_char);
2014   /* nontrivial_lcd is set if the common prefix adds something to the word
2015      being completed. */
2016   nontrivial_lcd = matches && strcmp (text, matches[0]) != 0;
2017   if (what_to_do == '!' || what_to_do == '@')
2018     tlen = strlen (text);
2019   xfree (text);
2020
2021   if (matches == 0)
2022     {
2023       rl_ding ();
2024       FREE (saved_line_buffer);
2025       completion_changed_buffer = 0;
2026       RL_UNSETSTATE(RL_STATE_COMPLETING);
2027       _rl_reset_completion_state ();
2028       return (0);
2029     }
2030
2031   /* If we are matching filenames, the attempted completion function will
2032      have set rl_filename_completion_desired to a non-zero value.  The basic
2033      rl_filename_completion_function does this. */
2034   i = rl_filename_completion_desired;
2035
2036   if (postprocess_matches (&matches, i) == 0)
2037     {
2038       rl_ding ();
2039       FREE (saved_line_buffer);
2040       completion_changed_buffer = 0;
2041       RL_UNSETSTATE(RL_STATE_COMPLETING);
2042       _rl_reset_completion_state ();
2043       return (0);
2044     }
2045
2046   switch (what_to_do)
2047     {
2048     case TAB:
2049     case '!':
2050     case '@':
2051       /* Insert the first match with proper quoting. */
2052       if (what_to_do == TAB)
2053         {
2054           if (*matches[0])
2055             insert_match (matches[0], start, matches[1] ? MULT_MATCH : SINGLE_MATCH, &quote_char);
2056         }
2057       else if (*matches[0] && matches[1] == 0)
2058         /* should we perform the check only if there are multiple matches? */
2059         insert_match (matches[0], start, matches[1] ? MULT_MATCH : SINGLE_MATCH, &quote_char);
2060       else if (*matches[0])     /* what_to_do != TAB && multiple matches */
2061         {
2062           mlen = *matches[0] ? strlen (matches[0]) : 0;
2063           if (mlen >= tlen)
2064             insert_match (matches[0], start, matches[1] ? MULT_MATCH : SINGLE_MATCH, &quote_char);
2065         }
2066
2067       /* If there are more matches, ring the bell to indicate.
2068          If we are in vi mode, Posix.2 says to not ring the bell.
2069          If the `show-all-if-ambiguous' variable is set, display
2070          all the matches immediately.  Otherwise, if this was the
2071          only match, and we are hacking files, check the file to
2072          see if it was a directory.  If so, and the `mark-directories'
2073          variable is set, add a '/' to the name.  If not, and we
2074          are at the end of the line, then add a space.  */
2075       if (matches[1])
2076         {
2077           if (what_to_do == '!')
2078             {
2079               display_matches (matches);
2080               break;
2081             }
2082           else if (what_to_do == '@')
2083             {
2084               if (nontrivial_lcd == 0)
2085                 display_matches (matches);
2086               break;
2087             }
2088           else if (rl_editing_mode != vi_mode)
2089             rl_ding (); /* There are other matches remaining. */
2090         }
2091       else
2092         append_to_match (matches[0], delimiter, quote_char, nontrivial_lcd);
2093
2094       break;
2095
2096     case '*':
2097       insert_all_matches (matches, start, &quote_char);
2098       break;
2099
2100     case '?':
2101       if (rl_completion_display_matches_hook == 0)
2102         {
2103           _rl_sigcleanup = _rl_complete_sigcleanup;
2104           _rl_sigcleanarg = matches;
2105           _rl_complete_display_matches_interrupt = 0;
2106         }
2107       display_matches (matches);
2108       if (_rl_complete_display_matches_interrupt)
2109         {
2110           matches = 0;          /* already freed by rl_complete_sigcleanup */
2111           _rl_complete_display_matches_interrupt = 0;
2112           if (rl_signal_event_hook)
2113             (*rl_signal_event_hook) ();         /* XXX */
2114         }
2115       _rl_sigcleanup = 0;
2116       _rl_sigcleanarg = 0;
2117       break;
2118
2119     default:
2120       _rl_ttymsg ("bad value %d for what_to_do in rl_complete", what_to_do);
2121       rl_ding ();
2122       FREE (saved_line_buffer);
2123       RL_UNSETSTATE(RL_STATE_COMPLETING);
2124       _rl_free_match_list (matches);
2125       _rl_reset_completion_state ();
2126       return 1;
2127     }
2128
2129   _rl_free_match_list (matches);
2130
2131   /* Check to see if the line has changed through all of this manipulation. */
2132   if (saved_line_buffer)
2133     {
2134       completion_changed_buffer = strcmp (rl_line_buffer, saved_line_buffer) != 0;
2135       xfree (saved_line_buffer);
2136     }
2137
2138   RL_UNSETSTATE(RL_STATE_COMPLETING);
2139   _rl_reset_completion_state ();
2140
2141   RL_CHECK_SIGNALS ();
2142   return 0;
2143 }
2144
2145 /***************************************************************/
2146 /*                                                             */
2147 /*  Application-callable completion match generator functions  */
2148 /*                                                             */
2149 /***************************************************************/
2150
2151 /* Return an array of (char *) which is a list of completions for TEXT.
2152    If there are no completions, return a NULL pointer.
2153    The first entry in the returned array is the substitution for TEXT.
2154    The remaining entries are the possible completions.
2155    The array is terminated with a NULL pointer.
2156
2157    ENTRY_FUNCTION is a function of two args, and returns a (char *).
2158      The first argument is TEXT.
2159      The second is a state argument; it should be zero on the first call, and
2160      non-zero on subsequent calls.  It returns a NULL pointer to the caller
2161      when there are no more matches.
2162  */
2163 char **
2164 rl_completion_matches (const char *text, rl_compentry_func_t *entry_function)
2165 {
2166   register int i;
2167
2168   /* Number of slots in match_list. */
2169   int match_list_size;
2170
2171   /* The list of matches. */
2172   char **match_list;
2173
2174   /* Number of matches actually found. */
2175   int matches;
2176
2177   /* Temporary string binder. */
2178   char *string;
2179
2180   matches = 0;
2181   match_list_size = 10;
2182   match_list = (char **)xmalloc ((match_list_size + 1) * sizeof (char *));
2183   match_list[1] = (char *)NULL;
2184
2185   while (string = (*entry_function) (text, matches))
2186     {
2187       if (RL_SIG_RECEIVED ())
2188         {
2189           /* Start at 1 because we don't set matches[0] in this function.
2190              Only free the list members if we're building match list from
2191              rl_filename_completion_function, since we know that doesn't
2192              free the strings it returns. */
2193           if (entry_function == rl_filename_completion_function)
2194             {
2195               for (i = 1; match_list[i]; i++)
2196                 xfree (match_list[i]);
2197             }
2198           xfree (match_list);
2199           match_list = 0;
2200           match_list_size = 0;
2201           matches = 0;
2202           RL_CHECK_SIGNALS ();
2203         }
2204
2205       if (matches + 1 >= match_list_size)
2206         match_list = (char **)xrealloc
2207           (match_list, ((match_list_size += 10) + 1) * sizeof (char *));
2208
2209       if (match_list == 0)
2210         return (match_list);
2211
2212       match_list[++matches] = string;
2213       match_list[matches + 1] = (char *)NULL;
2214     }
2215
2216   /* If there were any matches, then look through them finding out the
2217      lowest common denominator.  That then becomes match_list[0]. */
2218   if (matches)
2219     compute_lcd_of_matches (match_list, matches, text);
2220   else                          /* There were no matches. */
2221     {
2222       xfree (match_list);
2223       match_list = (char **)NULL;
2224     }
2225   return (match_list);
2226 }
2227
2228 /* A completion function for usernames.
2229    TEXT contains a partial username preceded by a random
2230    character (usually `~').  */
2231 char *
2232 rl_username_completion_function (const char *text, int state)
2233 {
2234 #if defined (__WIN32__) || defined (__OPENNT)
2235   return (char *)NULL;
2236 #else /* !__WIN32__ && !__OPENNT) */
2237   static char *username = (char *)NULL;
2238   static struct passwd *entry;
2239   static int namelen, first_char, first_char_loc;
2240   char *value;
2241
2242   if (state == 0)
2243     {
2244       FREE (username);
2245
2246       first_char = *text;
2247       first_char_loc = first_char == '~';
2248
2249       username = savestring (&text[first_char_loc]);
2250       namelen = strlen (username);
2251 #if defined (HAVE_GETPWENT)
2252       setpwent ();
2253 #endif
2254     }
2255
2256 #if defined (HAVE_GETPWENT)
2257   while (entry = getpwent ())
2258     {
2259       /* Null usernames should result in all users as possible completions. */
2260       if (namelen == 0 || (STREQN (username, entry->pw_name, namelen)))
2261         break;
2262     }
2263 #endif
2264
2265   if (entry == 0)
2266     {
2267 #if defined (HAVE_GETPWENT)
2268       endpwent ();
2269 #endif
2270       return ((char *)NULL);
2271     }
2272   else
2273     {
2274       value = (char *)xmalloc (2 + strlen (entry->pw_name));
2275
2276       *value = *text;
2277
2278       strcpy (value + first_char_loc, entry->pw_name);
2279
2280       if (first_char == '~')
2281         rl_filename_completion_desired = 1;
2282
2283       return (value);
2284     }
2285 #endif /* !__WIN32__ && !__OPENNT */
2286 }
2287
2288 /* Return non-zero if CONVFN matches FILENAME up to the length of FILENAME
2289    (FILENAME_LEN).  If _rl_completion_case_fold is set, compare without
2290    regard to the alphabetic case of characters.  If
2291    _rl_completion_case_map is set, make `-' and `_' equivalent.  CONVFN is
2292    the possibly-converted directory entry; FILENAME is what the user typed. */
2293 static int
2294 complete_fncmp (const char *convfn, int convlen, const char *filename, int filename_len)
2295 {
2296   register char *s1, *s2;
2297   int d, len;
2298 #if defined (HANDLE_MULTIBYTE)
2299   size_t v1, v2;
2300   mbstate_t ps1, ps2;
2301   wchar_t wc1, wc2;
2302 #endif
2303
2304 #if defined (HANDLE_MULTIBYTE)
2305   memset (&ps1, 0, sizeof (mbstate_t));
2306   memset (&ps2, 0, sizeof (mbstate_t));
2307 #endif
2308
2309   if (filename_len == 0)
2310     return 1;
2311   if (convlen < filename_len)
2312     return 0;
2313
2314   len = filename_len;
2315   s1 = (char *)convfn;
2316   s2 = (char *)filename;
2317
2318   /* Otherwise, if these match up to the length of filename, then
2319      it is a match. */
2320   if (_rl_completion_case_fold && _rl_completion_case_map)
2321     {
2322       /* Case-insensitive comparison treating _ and - as equivalent */
2323 #if defined (HANDLE_MULTIBYTE)
2324       if (MB_CUR_MAX > 1 && rl_byte_oriented == 0)
2325         {
2326           do
2327             {
2328               v1 = mbrtowc (&wc1, s1, convlen, &ps1);
2329               v2 = mbrtowc (&wc2, s2, filename_len, &ps2);
2330               if (v1 == 0 && v2 == 0)
2331                 return 1;
2332               else if (MB_INVALIDCH (v1) || MB_INVALIDCH (v2))
2333                 {
2334                   if (*s1 != *s2)               /* do byte comparison */
2335                     return 0;
2336                   else if ((*s1 == '-' || *s1 == '_') && (*s2 == '-' || *s2 == '_'))
2337                     return 0;
2338                   s1++; s2++; len--;
2339                   continue;
2340                 }
2341               wc1 = towlower (wc1);
2342               wc2 = towlower (wc2);
2343               s1 += v1;
2344               s2 += v1;
2345               len -= v1;
2346               if ((wc1 == L'-' || wc1 == L'_') && (wc2 == L'-' || wc2 == L'_'))
2347                 continue;
2348               if (wc1 != wc2)
2349                 return 0;
2350             }
2351           while (len != 0);
2352         }
2353       else
2354 #endif
2355         {
2356         do
2357           {
2358             d = _rl_to_lower (*s1) - _rl_to_lower (*s2);
2359             /* *s1 == [-_] && *s2 == [-_] */
2360             if ((*s1 == '-' || *s1 == '_') && (*s2 == '-' || *s2 == '_'))
2361               d = 0;
2362             if (d != 0)
2363               return 0;
2364             s1++; s2++; /* already checked convlen >= filename_len */
2365           }
2366         while (--len != 0);
2367         }
2368
2369       return 1;
2370     }
2371   else if (_rl_completion_case_fold)
2372     {
2373 #if defined (HANDLE_MULTIBYTE)
2374       if (MB_CUR_MAX > 1 && rl_byte_oriented == 0)
2375         {
2376           do
2377             {
2378               v1 = mbrtowc (&wc1, s1, convlen, &ps1);
2379               v2 = mbrtowc (&wc2, s2, filename_len, &ps2);
2380               if (v1 == 0 && v2 == 0)
2381                 return 1;
2382               else if (MB_INVALIDCH (v1) || MB_INVALIDCH (v2))
2383                 {
2384                   if (*s1 != *s2)               /* do byte comparison */
2385                     return 0;
2386                   s1++; s2++; len--;
2387                   continue;
2388                 }
2389               wc1 = towlower (wc1);
2390               wc2 = towlower (wc2);
2391               if (wc1 != wc2)
2392                 return 0;
2393               s1 += v1;
2394               s2 += v1;
2395               len -= v1;
2396             }
2397           while (len != 0);
2398           return 1;
2399         }
2400       else
2401 #endif
2402       if ((_rl_to_lower (convfn[0]) == _rl_to_lower (filename[0])) &&
2403           (convlen >= filename_len) &&
2404           (_rl_strnicmp (filename, convfn, filename_len) == 0))
2405         return 1;
2406     }
2407   else
2408     {
2409       if ((convfn[0] == filename[0]) &&
2410           (convlen >= filename_len) &&
2411           (strncmp (filename, convfn, filename_len) == 0))
2412         return 1;
2413     }
2414   return 0;
2415 }
2416
2417 /* Okay, now we write the entry_function for filename completion.  In the
2418    general case.  Note that completion in the shell is a little different
2419    because of all the pathnames that must be followed when looking up the
2420    completion for a command. */
2421 char *
2422 rl_filename_completion_function (const char *text, int state)
2423 {
2424   static DIR *directory = (DIR *)NULL;
2425   static char *filename = (char *)NULL;
2426   static char *dirname = (char *)NULL;
2427   static char *users_dirname = (char *)NULL;
2428   static int filename_len;
2429   char *temp, *dentry, *convfn;
2430   int dirlen, dentlen, convlen;
2431   int tilde_dirname;
2432   struct dirent *entry;
2433
2434   /* If we don't have any state, then do some initialization. */
2435   if (state == 0)
2436     {
2437       /* If we were interrupted before closing the directory or reading
2438          all of its contents, close it. */
2439       if (directory)
2440         {
2441           closedir (directory);
2442           directory = (DIR *)NULL;
2443         }
2444       FREE (dirname);
2445       FREE (filename);
2446       FREE (users_dirname);
2447
2448       filename = savestring (text);
2449       if (*text == 0)
2450         text = ".";
2451       dirname = savestring (text);
2452
2453       temp = strrchr (dirname, '/');
2454
2455 #if defined (__MSDOS__) || defined (_WIN32)
2456       /* special hack for //X/... */
2457       if (dirname[0] == '/' && dirname[1] == '/' && ISALPHA ((unsigned char)dirname[2]) && dirname[3] == '/')
2458         temp = strrchr (dirname + 3, '/');
2459 #endif
2460
2461       if (temp)
2462         {
2463           strcpy (filename, ++temp);
2464           *temp = '\0';
2465         }
2466 #if defined (__MSDOS__) || (defined (_WIN32) && !defined (__CYGWIN__))
2467       /* searches from current directory on the drive */
2468       else if (ISALPHA ((unsigned char)dirname[0]) && dirname[1] == ':')
2469         {
2470           strcpy (filename, dirname + 2);
2471           dirname[2] = '\0';
2472         }
2473 #endif
2474       else
2475         {
2476           dirname[0] = '.';
2477           dirname[1] = '\0';
2478         }
2479
2480       /* We aren't done yet.  We also support the "~user" syntax. */
2481
2482       /* Save the version of the directory that the user typed, dequoting
2483          it if necessary. */
2484       if (rl_completion_found_quote && rl_filename_dequoting_function)
2485         users_dirname = (*rl_filename_dequoting_function) (dirname, rl_completion_quote_character);
2486       else
2487         users_dirname = savestring (dirname);
2488
2489       tilde_dirname = 0;
2490       if (*dirname == '~')
2491         {
2492           temp = tilde_expand (dirname);
2493           xfree (dirname);
2494           dirname = temp;
2495           tilde_dirname = 1;
2496         }
2497
2498       /* We have saved the possibly-dequoted version of the directory name
2499          the user typed.  Now transform the directory name we're going to
2500          pass to opendir(2).  The directory rewrite hook modifies only the
2501          directory name; the directory completion hook modifies both the
2502          directory name passed to opendir(2) and the version the user
2503          typed.  Both the directory completion and rewrite hooks should perform
2504          any necessary dequoting.  The hook functions return 1 if they modify
2505          the directory name argument.  If either hook returns 0, it should
2506          not modify the directory name pointer passed as an argument. */
2507       if (rl_directory_rewrite_hook)
2508         (*rl_directory_rewrite_hook) (&dirname);
2509       else if (rl_directory_completion_hook && (*rl_directory_completion_hook) (&dirname))
2510         {
2511           xfree (users_dirname);
2512           users_dirname = savestring (dirname);
2513         }
2514       else if (tilde_dirname == 0 && rl_completion_found_quote && rl_filename_dequoting_function)
2515         {
2516           /* delete single and double quotes */
2517           xfree (dirname);
2518           dirname = savestring (users_dirname);
2519         }
2520       directory = opendir (dirname);
2521
2522       /* Now dequote a non-null filename.  FILENAME will not be NULL, but may
2523          be empty. */
2524       if (*filename && rl_completion_found_quote && rl_filename_dequoting_function)
2525         {
2526           /* delete single and double quotes */
2527           temp = (*rl_filename_dequoting_function) (filename, rl_completion_quote_character);
2528           xfree (filename);
2529           filename = temp;
2530         }
2531       filename_len = strlen (filename);
2532
2533       rl_filename_completion_desired = 1;
2534     }
2535
2536   /* At this point we should entertain the possibility of hacking wildcarded
2537      filenames, like /usr/man/man<WILD>/te<TAB>.  If the directory name
2538      contains globbing characters, then build an array of directories, and
2539      then map over that list while completing. */
2540   /* *** UNIMPLEMENTED *** */
2541
2542   /* Now that we have some state, we can read the directory. */
2543
2544   entry = (struct dirent *)NULL;
2545   while (directory && (entry = readdir (directory)))
2546     {
2547       convfn = dentry = entry->d_name;
2548       convlen = dentlen = D_NAMLEN (entry);
2549
2550       if (rl_filename_rewrite_hook)
2551         {
2552           convfn = (*rl_filename_rewrite_hook) (dentry, dentlen);
2553           convlen = (convfn == dentry) ? dentlen : strlen (convfn);
2554         }
2555
2556       /* Special case for no filename.  If the user has disabled the
2557          `match-hidden-files' variable, skip filenames beginning with `.'.
2558          All other entries except "." and ".." match. */
2559       if (filename_len == 0)
2560         {
2561           if (_rl_match_hidden_files == 0 && HIDDEN_FILE (convfn))
2562             continue;
2563
2564           if (convfn[0] != '.' ||
2565                (convfn[1] && (convfn[1] != '.' || convfn[2])))
2566             break;
2567         }
2568       else
2569         {
2570           if (complete_fncmp (convfn, convlen, filename, filename_len))
2571             break;
2572         }
2573     }
2574
2575   if (entry == 0)
2576     {
2577       if (directory)
2578         {
2579           closedir (directory);
2580           directory = (DIR *)NULL;
2581         }
2582       if (dirname)
2583         {
2584           xfree (dirname);
2585           dirname = (char *)NULL;
2586         }
2587       if (filename)
2588         {
2589           xfree (filename);
2590           filename = (char *)NULL;
2591         }
2592       if (users_dirname)
2593         {
2594           xfree (users_dirname);
2595           users_dirname = (char *)NULL;
2596         }
2597
2598       return (char *)NULL;
2599     }
2600   else
2601     {
2602       /* dirname && (strcmp (dirname, ".") != 0) */
2603       if (dirname && (dirname[0] != '.' || dirname[1]))
2604         {
2605           if (rl_complete_with_tilde_expansion && *users_dirname == '~')
2606             {
2607               dirlen = strlen (dirname);
2608               temp = (char *)xmalloc (2 + dirlen + D_NAMLEN (entry));
2609               strcpy (temp, dirname);
2610               /* Canonicalization cuts off any final slash present.  We
2611                  may need to add it back. */
2612               if (dirname[dirlen - 1] != '/')
2613                 {
2614                   temp[dirlen++] = '/';
2615                   temp[dirlen] = '\0';
2616                 }
2617             }
2618           else
2619             {
2620               dirlen = strlen (users_dirname);
2621               temp = (char *)xmalloc (2 + dirlen + D_NAMLEN (entry));
2622               strcpy (temp, users_dirname);
2623               /* Make sure that temp has a trailing slash here. */
2624               if (users_dirname[dirlen - 1] != '/')
2625                 temp[dirlen++] = '/';
2626             }
2627
2628           strcpy (temp + dirlen, convfn);
2629         }
2630       else
2631         temp = savestring (convfn);
2632
2633       if (convfn != dentry)
2634         xfree (convfn);
2635
2636       return (temp);
2637     }
2638 }
2639
2640 /* An initial implementation of a menu completion function a la tcsh.  The
2641    first time (if the last readline command was not rl_old_menu_complete), we
2642    generate the list of matches.  This code is very similar to the code in
2643    rl_complete_internal -- there should be a way to combine the two.  Then,
2644    for each item in the list of matches, we insert the match in an undoable
2645    fashion, with the appropriate character appended (this happens on the
2646    second and subsequent consecutive calls to rl_old_menu_complete).  When we
2647    hit the end of the match list, we restore the original unmatched text,
2648    ring the bell, and reset the counter to zero. */
2649 int
2650 rl_old_menu_complete (int count, int invoking_key)
2651 {
2652   rl_compentry_func_t *our_func;
2653   int matching_filenames, found_quote;
2654
2655   static char *orig_text;
2656   static char **matches = (char **)0;
2657   static int match_list_index = 0;
2658   static int match_list_size = 0;
2659   static int orig_start, orig_end;
2660   static char quote_char;
2661   static int delimiter;
2662
2663   /* The first time through, we generate the list of matches and set things
2664      up to insert them. */
2665   if (rl_last_func != rl_old_menu_complete)
2666     {
2667       /* Clean up from previous call, if any. */
2668       FREE (orig_text);
2669       if (matches)
2670         _rl_free_match_list (matches);
2671
2672       match_list_index = match_list_size = 0;
2673       matches = (char **)NULL;
2674
2675       rl_completion_invoking_key = invoking_key;
2676
2677       RL_SETSTATE(RL_STATE_COMPLETING);
2678
2679       /* Only the completion entry function can change these. */
2680       set_completion_defaults ('%');
2681
2682       our_func = rl_menu_completion_entry_function;
2683       if (our_func == 0)
2684         our_func = rl_completion_entry_function
2685                         ? rl_completion_entry_function
2686                         : rl_filename_completion_function;
2687
2688       /* We now look backwards for the start of a filename/variable word. */
2689       orig_end = rl_point;
2690       found_quote = delimiter = 0;
2691       quote_char = '\0';
2692
2693       if (rl_point)
2694         /* This (possibly) changes rl_point.  If it returns a non-zero char,
2695            we know we have an open quote. */
2696         quote_char = _rl_find_completion_word (&found_quote, &delimiter);
2697
2698       orig_start = rl_point;
2699       rl_point = orig_end;
2700
2701       orig_text = rl_copy_text (orig_start, orig_end);
2702       matches = gen_completion_matches (orig_text, orig_start, orig_end,
2703                                         our_func, found_quote, quote_char);
2704
2705       /* If we are matching filenames, the attempted completion function will
2706          have set rl_filename_completion_desired to a non-zero value.  The basic
2707          rl_filename_completion_function does this. */
2708       matching_filenames = rl_filename_completion_desired;
2709
2710       if (matches == 0 || postprocess_matches (&matches, matching_filenames) == 0)
2711         {
2712           rl_ding ();
2713           FREE (matches);
2714           matches = (char **)0;
2715           FREE (orig_text);
2716           orig_text = (char *)0;
2717           completion_changed_buffer = 0;
2718           RL_UNSETSTATE(RL_STATE_COMPLETING);
2719           return (0);
2720         }
2721
2722       RL_UNSETSTATE(RL_STATE_COMPLETING);
2723
2724       for (match_list_size = 0; matches[match_list_size]; match_list_size++)
2725         ;
2726       /* matches[0] is lcd if match_list_size > 1, but the circular buffer
2727          code below should take care of it. */
2728
2729       if (match_list_size > 1 && _rl_complete_show_all)
2730         display_matches (matches);
2731     }
2732
2733   /* Now we have the list of matches.  Replace the text between
2734      rl_line_buffer[orig_start] and rl_line_buffer[rl_point] with
2735      matches[match_list_index], and add any necessary closing char. */
2736
2737   if (matches == 0 || match_list_size == 0) 
2738     {
2739       rl_ding ();
2740       FREE (matches);
2741       matches = (char **)0;
2742       completion_changed_buffer = 0;
2743       return (0);
2744     }
2745
2746   match_list_index += count;
2747   if (match_list_index < 0)
2748     {
2749       while (match_list_index < 0)
2750         match_list_index += match_list_size;
2751     }
2752   else
2753     match_list_index %= match_list_size;
2754
2755   if (match_list_index == 0 && match_list_size > 1)
2756     {
2757       rl_ding ();
2758       insert_match (orig_text, orig_start, MULT_MATCH, &quote_char);
2759     }
2760   else
2761     {
2762       insert_match (matches[match_list_index], orig_start, SINGLE_MATCH, &quote_char);
2763       append_to_match (matches[match_list_index], delimiter, quote_char,
2764                        strcmp (orig_text, matches[match_list_index]));
2765     }
2766
2767   completion_changed_buffer = 1;
2768   return (0);
2769 }
2770
2771 /* The current version of menu completion.
2772    The differences between this function and the original are:
2773
2774 1. It honors the maximum number of completions variable (completion-query-items)
2775 2. It appends to the word as usual if there is only one match
2776 3. It displays the common prefix if there is one, and makes it the first menu
2777    choice if the menu-complete-display-prefix option is enabled
2778 */
2779  
2780 int
2781 rl_menu_complete (int count, int ignore)
2782 {
2783   rl_compentry_func_t *our_func;
2784   int matching_filenames, found_quote;
2785
2786   static char *orig_text;
2787   static char **matches = (char **)0;
2788   static int match_list_index = 0;
2789   static int match_list_size = 0;
2790   static int nontrivial_lcd = 0;
2791   static int full_completion = 0;       /* set to 1 if menu completion should reinitialize on next call */
2792   static int orig_start, orig_end;
2793   static char quote_char;
2794   static int delimiter, cstate;
2795
2796   /* The first time through, we generate the list of matches and set things
2797      up to insert them. */
2798   if ((rl_last_func != rl_menu_complete && rl_last_func != rl_backward_menu_complete) || full_completion)
2799     {
2800       /* Clean up from previous call, if any. */
2801       FREE (orig_text);
2802       if (matches)
2803         _rl_free_match_list (matches);
2804
2805       match_list_index = match_list_size = 0;
2806       matches = (char **)NULL;
2807
2808       full_completion = 0;
2809
2810       RL_SETSTATE(RL_STATE_COMPLETING);
2811
2812       /* Only the completion entry function can change these. */
2813       set_completion_defaults ('%');
2814
2815       our_func = rl_menu_completion_entry_function;
2816       if (our_func == 0)
2817         our_func = rl_completion_entry_function
2818                         ? rl_completion_entry_function
2819                         : rl_filename_completion_function;
2820
2821       /* We now look backwards for the start of a filename/variable word. */
2822       orig_end = rl_point;
2823       found_quote = delimiter = 0;
2824       quote_char = '\0';
2825
2826       if (rl_point)
2827         /* This (possibly) changes rl_point.  If it returns a non-zero char,
2828            we know we have an open quote. */
2829         quote_char = _rl_find_completion_word (&found_quote, &delimiter);
2830
2831       orig_start = rl_point;
2832       rl_point = orig_end;
2833
2834       orig_text = rl_copy_text (orig_start, orig_end);
2835       matches = gen_completion_matches (orig_text, orig_start, orig_end,
2836                                         our_func, found_quote, quote_char);
2837
2838       nontrivial_lcd = matches && strcmp (orig_text, matches[0]) != 0;
2839
2840       /* If we are matching filenames, the attempted completion function will
2841          have set rl_filename_completion_desired to a non-zero value.  The basic
2842          rl_filename_completion_function does this. */
2843       matching_filenames = rl_filename_completion_desired;
2844
2845       if (matches == 0 || postprocess_matches (&matches, matching_filenames) == 0)
2846         {
2847           rl_ding ();
2848           FREE (matches);
2849           matches = (char **)0;
2850           FREE (orig_text);
2851           orig_text = (char *)0;
2852           completion_changed_buffer = 0;
2853           RL_UNSETSTATE(RL_STATE_COMPLETING);
2854           return (0);
2855         }
2856
2857       RL_UNSETSTATE(RL_STATE_COMPLETING);
2858
2859       for (match_list_size = 0; matches[match_list_size]; match_list_size++)
2860         ;
2861
2862       if (match_list_size == 0) 
2863         {
2864           rl_ding ();
2865           FREE (matches);
2866           matches = (char **)0;
2867           match_list_index = 0;
2868           completion_changed_buffer = 0;
2869           return (0);
2870         }
2871
2872       /* matches[0] is lcd if match_list_size > 1, but the circular buffer
2873          code below should take care of it. */
2874       if (*matches[0])
2875         {
2876           insert_match (matches[0], orig_start, matches[1] ? MULT_MATCH : SINGLE_MATCH, &quote_char);
2877           orig_end = orig_start + strlen (matches[0]);
2878           completion_changed_buffer = STREQ (orig_text, matches[0]) == 0;
2879         }
2880
2881       if (match_list_size > 1 && _rl_complete_show_all)
2882         {
2883           display_matches (matches);
2884           /* If there are so many matches that the user has to be asked
2885              whether or not he wants to see the matches, menu completion
2886              is unwieldy. */
2887           if (rl_completion_query_items > 0 && match_list_size >= rl_completion_query_items)
2888             {
2889               rl_ding ();
2890               FREE (matches);
2891               matches = (char **)0;
2892               full_completion = 1;
2893               return (0);
2894             }
2895           else if (_rl_menu_complete_prefix_first)
2896             {
2897               rl_ding ();
2898               return (0);
2899             }
2900         }
2901       else if (match_list_size <= 1)
2902         {
2903           append_to_match (matches[0], delimiter, quote_char, nontrivial_lcd);
2904           full_completion = 1;
2905           return (0);
2906         }
2907       else if (_rl_menu_complete_prefix_first && match_list_size > 1)
2908         {
2909           rl_ding ();
2910           return (0);
2911         }
2912     }
2913
2914   /* Now we have the list of matches.  Replace the text between
2915      rl_line_buffer[orig_start] and rl_line_buffer[rl_point] with
2916      matches[match_list_index], and add any necessary closing char. */
2917
2918   if (matches == 0 || match_list_size == 0) 
2919     {
2920       rl_ding ();
2921       FREE (matches);
2922       matches = (char **)0;
2923       completion_changed_buffer = 0;
2924       return (0);
2925     }
2926
2927   match_list_index += count;
2928   if (match_list_index < 0)
2929     {
2930       while (match_list_index < 0)
2931         match_list_index += match_list_size;
2932     }
2933   else
2934     match_list_index %= match_list_size;
2935
2936   if (match_list_index == 0 && match_list_size > 1)
2937     {
2938       rl_ding ();
2939       insert_match (matches[0], orig_start, MULT_MATCH, &quote_char);
2940     }
2941   else
2942     {
2943       insert_match (matches[match_list_index], orig_start, SINGLE_MATCH, &quote_char);
2944       append_to_match (matches[match_list_index], delimiter, quote_char,
2945                        strcmp (orig_text, matches[match_list_index]));
2946     }
2947
2948   completion_changed_buffer = 1;
2949   return (0);
2950 }
2951
2952 int
2953 rl_backward_menu_complete (int count, int key)
2954 {
2955   /* Positive arguments to backward-menu-complete translate into negative
2956      arguments for menu-complete, and vice versa. */
2957   return (rl_menu_complete (-count, key));
2958 }