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