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