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