cbcee28f823867af768e1c70a6c4cc1faaf6dd92
[platform/upstream/bash.git] / lib / readline / complete.c
1 /* complete.c -- filename completion for readline. */
2
3 /* Copyright (C) 1987, 1989, 1992 Free Software Foundation, Inc.
4
5    This file is part of the GNU Readline Library, a library for
6    reading lines of text with interactive input and history editing.
7
8    The GNU Readline Library is free software; you can redistribute it
9    and/or modify it under the terms of the GNU General Public License
10    as published by the Free Software Foundation; either version 2, or
11    (at your option) any later version.
12
13    The GNU Readline Library is distributed in the hope that it will be
14    useful, but WITHOUT ANY WARRANTY; without even the implied warranty
15    of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    The GNU General Public License is often shipped with GNU software, and
19    is generally kept in a file called COPYING or LICENSE.  If you do not
20    have a copy of the license, write to the Free Software Foundation,
21    59 Temple Place, Suite 330, Boston, MA 02111 USA. */
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 #include <pwd.h>
52
53 #include "posixdir.h"
54 #include "posixstat.h"
55
56 /* System-specific feature definitions and include files. */
57 #include "rldefs.h"
58
59 /* Some standard library routines. */
60 #include "readline.h"
61 #include "xmalloc.h"
62 #include "rlprivate.h"
63
64 #ifdef __STDC__
65 typedef int QSFUNC (const void *, const void *);
66 #else
67 typedef int QSFUNC ();
68 #endif
69
70 #ifdef HAVE_LSTAT
71 #  define LSTAT lstat
72 #else
73 #  define LSTAT stat
74 #endif
75
76 /* Unix version of a hidden file.  Could be different on other systems. */
77 #define HIDDEN_FILE(fname)      ((fname)[0] == '.')
78
79 /* Most systems don't declare getpwent in <pwd.h> if _POSIX_SOURCE is
80    defined. */
81 #if !defined (HAVE_GETPW_DECLS) || defined (_POSIX_SOURCE)
82 extern struct passwd *getpwent PARAMS((void));
83 #endif /* !HAVE_GETPW_DECLS || _POSIX_SOURCE */
84
85 /* If non-zero, then this is the address of a function to call when
86    completing a word would normally display the list of possible matches.
87    This function is called instead of actually doing the display.
88    It takes three arguments: (char **matches, int num_matches, int max_length)
89    where MATCHES is the array of strings that matched, NUM_MATCHES is the
90    number of strings in that array, and MAX_LENGTH is the length of the
91    longest string in that array. */
92 rl_compdisp_func_t *rl_completion_display_matches_hook = (rl_compdisp_func_t *)NULL;
93
94 #if defined (VISIBLE_STATS)
95 #  if !defined (X_OK)
96 #    define X_OK 1
97 #  endif
98 static int stat_char PARAMS((char *));
99 #endif
100
101 static char *rl_quote_filename PARAMS((char *, int, char *));
102
103 static int get_y_or_n PARAMS((void));
104 static char *printable_part PARAMS((char *));
105 static int print_filename PARAMS((char *, char *));
106 static char find_completion_word PARAMS((int *, int *));
107
108 static char **gen_completion_matches PARAMS((char *, int, int, rl_compentry_func_t *, int, int));
109
110 static char **remove_duplicate_matches PARAMS((char **));
111 static void insert_match PARAMS((char *, int, int, char *));
112 static int append_to_match PARAMS((char *, int, int, int));
113 static void insert_all_matches PARAMS((char **, int, char *));
114 static void display_matches PARAMS((char **));
115 static int compute_lcd_of_matches PARAMS((char **, int, const char *));
116 static int postprocess_matches PARAMS((char ***, int));
117
118 static char *make_quoted_replacement PARAMS((char *, int, char *));
119 static void free_match_list PARAMS((char **));
120
121 /* **************************************************************** */
122 /*                                                                  */
123 /*      Completion matching, from readline's point of view.         */
124 /*                                                                  */
125 /* **************************************************************** */
126
127 /* Variables known only to the readline library. */
128
129 /* If non-zero, non-unique completions always show the list of matches. */
130 int _rl_complete_show_all = 0;
131
132 /* If non-zero, completed directory names have a slash appended. */
133 int _rl_complete_mark_directories = 1;
134
135 /* If non-zero, completions are printed horizontally in alphabetical order,
136    like `ls -x'. */
137 int _rl_print_completions_horizontally;
138
139 /* Non-zero means that case is not significant in filename completion. */
140 #if defined (__MSDOS__) && !defined (__DJGPP__)
141 int _rl_completion_case_fold = 1;
142 #else
143 int _rl_completion_case_fold;
144 #endif
145
146 /* If non-zero, don't match hidden files (filenames beginning with a `.' on
147    Unix) when doing filename completion. */
148 int _rl_match_hidden_files = 1;
149
150 /* Global variables available to applications using readline. */
151
152 #if defined (VISIBLE_STATS)
153 /* Non-zero means add an additional character to each filename displayed
154    during listing completion iff rl_filename_completion_desired which helps
155    to indicate the type of file being listed. */
156 int rl_visible_stats = 0;
157 #endif /* VISIBLE_STATS */
158
159 /* If non-zero, then this is the address of a function to call when
160    completing on a directory name.  The function is called with
161    the address of a string (the current directory name) as an arg. */
162 rl_icppfunc_t *rl_directory_completion_hook = (rl_icppfunc_t *)NULL;
163
164 rl_icppfunc_t *rl_directory_rewrite_hook = (rl_icppfunc_t *)NULL;
165
166 /* Non-zero means readline completion functions perform tilde expansion. */
167 int rl_complete_with_tilde_expansion = 0;
168
169 /* Pointer to the generator function for completion_matches ().
170    NULL means to use rl_filename_completion_function (), the default filename
171    completer. */
172 rl_compentry_func_t *rl_completion_entry_function = (rl_compentry_func_t *)NULL;
173
174 /* Pointer to alternative function to create matches.
175    Function is called with TEXT, START, and END.
176    START and END are indices in RL_LINE_BUFFER saying what the boundaries
177    of TEXT are.
178    If this function exists and returns NULL then call the value of
179    rl_completion_entry_function to try to match, otherwise use the
180    array of strings returned. */
181 rl_completion_func_t *rl_attempted_completion_function = (rl_completion_func_t *)NULL;
182
183 /* Non-zero means to suppress normal filename completion after the
184    user-specified completion function has been called. */
185 int rl_attempted_completion_over = 0;
186
187 /* Set to a character indicating the type of completion being performed
188    by rl_complete_internal, available for use by application completion
189    functions. */
190 int rl_completion_type = 0;
191
192 /* Up to this many items will be displayed in response to a
193    possible-completions call.  After that, we ask the user if
194    she is sure she wants to see them all. */
195 int rl_completion_query_items = 100;
196
197 /* The basic list of characters that signal a break between words for the
198    completer routine.  The contents of this variable is what breaks words
199    in the shell, i.e. " \t\n\"\\'`@$><=" */
200 const char *rl_basic_word_break_characters = " \t\n\"\\'`@$><=;|&{(";
201
202 /* List of basic quoting characters. */
203 const char *rl_basic_quote_characters = "\"'";
204
205 /* The list of characters that signal a break between words for
206    rl_complete_internal.  The default list is the contents of
207    rl_basic_word_break_characters.  */
208 const char *rl_completer_word_break_characters = (const char *)NULL;
209
210 /* List of characters which can be used to quote a substring of the line.
211    Completion occurs on the entire substring, and within the substring
212    rl_completer_word_break_characters are treated as any other character,
213    unless they also appear within this list. */
214 const char *rl_completer_quote_characters = (const char *)NULL;
215
216 /* List of characters that should be quoted in filenames by the completer. */
217 const char *rl_filename_quote_characters = (const char *)NULL;
218
219 /* List of characters that are word break characters, but should be left
220    in TEXT when it is passed to the completion function.  The shell uses
221    this to help determine what kind of completing to do. */
222 const char *rl_special_prefixes = (const char *)NULL;
223
224 /* If non-zero, then disallow duplicates in the matches. */
225 int rl_ignore_completion_duplicates = 1;
226
227 /* Non-zero means that the results of the matches are to be treated
228    as filenames.  This is ALWAYS zero on entry, and can only be changed
229    within a completion entry finder function. */
230 int rl_filename_completion_desired = 0;
231
232 /* Non-zero means that the results of the matches are to be quoted using
233    double quotes (or an application-specific quoting mechanism) if the
234    filename contains any characters in rl_filename_quote_chars.  This is
235    ALWAYS non-zero on entry, and can only be changed within a completion
236    entry finder function. */
237 int rl_filename_quoting_desired = 1;
238
239 /* This function, if defined, is called by the completer when real
240    filename completion is done, after all the matching names have been
241    generated. It is passed a (char**) known as matches in the code below.
242    It consists of a NULL-terminated array of pointers to potential
243    matching strings.  The 1st element (matches[0]) is the maximal
244    substring that is common to all matches. This function can re-arrange
245    the list of matches as required, but all elements of the array must be
246    free()'d if they are deleted. The main intent of this function is
247    to implement FIGNORE a la SunOS csh. */
248 rl_compignore_func_t *rl_ignore_some_completions_function = (rl_compignore_func_t *)NULL;
249
250 /* Set to a function to quote a filename in an application-specific fashion.
251    Called with the text to quote, the type of match found (single or multiple)
252    and a pointer to the quoting character to be used, which the function can
253    reset if desired. */
254 rl_quote_func_t *rl_filename_quoting_function = rl_quote_filename;
255          
256 /* Function to call to remove quoting characters from a filename.  Called
257    before completion is attempted, so the embedded quotes do not interfere
258    with matching names in the file system.  Readline doesn't do anything
259    with this; it's set only by applications. */
260 rl_dequote_func_t *rl_filename_dequoting_function = (rl_dequote_func_t *)NULL;
261
262 /* Function to call to decide whether or not a word break character is
263    quoted.  If a character is quoted, it does not break words for the
264    completer. */
265 rl_linebuf_func_t *rl_char_is_quoted_p = (rl_linebuf_func_t *)NULL;
266
267 /* Character appended to completed words when at the end of the line.  The
268    default is a space. */
269 int rl_completion_append_character = ' ';
270
271 /* If non-zero, inhibit completion (temporarily). */
272 int rl_inhibit_completion;
273
274 /* Variables local to this file. */
275
276 /* Local variable states what happened during the last completion attempt. */
277 static int completion_changed_buffer;
278
279 /*************************************/
280 /*                                   */
281 /*    Bindable completion functions  */
282 /*                                   */
283 /*************************************/
284
285 /* Complete the word at or before point.  You have supplied the function
286    that does the initial simple matching selection algorithm (see
287    rl_completion_matches ()).  The default is to do filename completion. */
288 int
289 rl_complete (ignore, invoking_key)
290      int ignore, invoking_key;
291 {
292   if (rl_inhibit_completion)
293     return (rl_insert (ignore, invoking_key));
294   else if (rl_last_func == rl_complete && !completion_changed_buffer)
295     return (rl_complete_internal ('?'));
296   else if (_rl_complete_show_all)
297     return (rl_complete_internal ('!'));
298   else
299     return (rl_complete_internal (TAB));
300 }
301
302 /* List the possible completions.  See description of rl_complete (). */
303 int
304 rl_possible_completions (ignore, invoking_key)
305      int ignore, invoking_key;
306 {
307   return (rl_complete_internal ('?'));
308 }
309
310 int
311 rl_insert_completions (ignore, invoking_key)
312      int ignore, invoking_key;
313 {
314   return (rl_complete_internal ('*'));
315 }
316
317 /************************************/
318 /*                                  */
319 /*    Completion utility functions  */
320 /*                                  */
321 /************************************/
322
323 /* The user must press "y" or "n". Non-zero return means "y" pressed. */
324 static int
325 get_y_or_n ()
326 {
327   int c;
328
329   for (;;)
330     {
331       RL_SETSTATE(RL_STATE_MOREINPUT);
332       c = rl_read_key ();
333       RL_UNSETSTATE(RL_STATE_MOREINPUT);
334
335       if (c == 'y' || c == 'Y' || c == ' ')
336         return (1);
337       if (c == 'n' || c == 'N' || c == RUBOUT)
338         return (0);
339       if (c == ABORT_CHAR)
340         _rl_abort_internal ();
341       rl_ding ();
342     }
343 }
344
345 #if defined (VISIBLE_STATS)
346 /* Return the character which best describes FILENAME.
347      `@' for symbolic links
348      `/' for directories
349      `*' for executables
350      `=' for sockets
351      `|' for FIFOs
352      `%' for character special devices
353      `#' for block special devices */
354 static int
355 stat_char (filename)
356      char *filename;
357 {
358   struct stat finfo;
359   int character, r;
360
361 #if defined (HAVE_LSTAT) && defined (S_ISLNK)
362   r = lstat (filename, &finfo);
363 #else
364   r = stat (filename, &finfo);
365 #endif
366
367   if (r == -1)
368     return (0);
369
370   character = 0;
371   if (S_ISDIR (finfo.st_mode))
372     character = '/';
373 #if defined (S_ISCHR)
374   else if (S_ISCHR (finfo.st_mode))
375     character = '%';
376 #endif /* S_ISCHR */
377 #if defined (S_ISBLK)
378   else if (S_ISBLK (finfo.st_mode))
379     character = '#';
380 #endif /* S_ISBLK */
381 #if defined (S_ISLNK)
382   else if (S_ISLNK (finfo.st_mode))
383     character = '@';
384 #endif /* S_ISLNK */
385 #if defined (S_ISSOCK)
386   else if (S_ISSOCK (finfo.st_mode))
387     character = '=';
388 #endif /* S_ISSOCK */
389 #if defined (S_ISFIFO)
390   else if (S_ISFIFO (finfo.st_mode))
391     character = '|';
392 #endif
393   else if (S_ISREG (finfo.st_mode))
394     {
395       if (access (filename, X_OK) == 0)
396         character = '*';
397     }
398   return (character);
399 }
400 #endif /* VISIBLE_STATS */
401
402 /* Return the portion of PATHNAME that should be output when listing
403    possible completions.  If we are hacking filename completion, we
404    are only interested in the basename, the portion following the
405    final slash.  Otherwise, we return what we were passed. */
406 static char *
407 printable_part (pathname)
408       char *pathname;
409 {
410   char *temp;
411
412   temp = rl_filename_completion_desired ? strrchr (pathname, '/') : (char *)NULL;
413 #if defined (__MSDOS__)
414   if (rl_filename_completion_desired && temp == 0 && ISALPHA ((unsigned char)pathname[0]) && pathname[1] == ':')
415     temp = pathname + 1;
416 #endif
417   return (temp ? ++temp : pathname);
418 }
419
420 /* Output TO_PRINT to rl_outstream.  If VISIBLE_STATS is defined and we
421    are using it, check for and output a single character for `special'
422    filenames.  Return the number of characters we output. */
423
424 #define PUTX(c) \
425     do { \
426       if (CTRL_CHAR (c)) \
427         { \
428           putc ('^', rl_outstream); \
429           putc (UNCTRL (c), rl_outstream); \
430           printed_len += 2; \
431         } \
432       else if (c == RUBOUT) \
433         { \
434           putc ('^', rl_outstream); \
435           putc ('?', rl_outstream); \
436           printed_len += 2; \
437         } \
438       else \
439         { \
440           putc (c, rl_outstream); \
441           printed_len++; \
442         } \
443     } while (0)
444
445 static int
446 print_filename (to_print, full_pathname)
447      char *to_print, *full_pathname;
448 {
449   int printed_len = 0;
450 #if !defined (VISIBLE_STATS)
451   char *s;
452
453   for (s = to_print; *s; s++)
454     {
455       PUTX (*s);
456     }
457 #else  
458   char *s, c, *new_full_pathname;
459   int extension_char, slen, tlen;
460
461   for (s = to_print; *s; s++)
462     {
463       PUTX (*s);
464     }
465
466  if (rl_filename_completion_desired && rl_visible_stats)
467     {
468       /* If to_print != full_pathname, to_print is the basename of the
469          path passed.  In this case, we try to expand the directory
470          name before checking for the stat character. */
471       if (to_print != full_pathname)
472         {
473           /* Terminate the directory name. */
474           c = to_print[-1];
475           to_print[-1] = '\0';
476
477           /* If setting the last slash in full_pathname to a NUL results in
478              full_pathname being the empty string, we are trying to complete
479              files in the root directory.  If we pass a null string to the
480              bash directory completion hook, for example, it will expand it
481              to the current directory.  We just want the `/'. */
482           s = tilde_expand (full_pathname && *full_pathname ? full_pathname : "/");
483           if (rl_directory_completion_hook)
484             (*rl_directory_completion_hook) (&s);
485
486           slen = strlen (s);
487           tlen = strlen (to_print);
488           new_full_pathname = (char *)xmalloc (slen + tlen + 2);
489           strcpy (new_full_pathname, s);
490           new_full_pathname[slen] = '/';
491           strcpy (new_full_pathname + slen + 1, to_print);
492
493           extension_char = stat_char (new_full_pathname);
494
495           free (new_full_pathname);
496           to_print[-1] = c;
497         }
498       else
499         {
500           s = tilde_expand (full_pathname);
501           extension_char = stat_char (s);
502         }
503
504       free (s);
505       if (extension_char)
506         {
507           putc (extension_char, rl_outstream);
508           printed_len++;
509         }
510     }
511 #endif /* VISIBLE_STATS */
512   return printed_len;
513 }
514
515 static char *
516 rl_quote_filename (s, rtype, qcp)
517      char *s;
518      int rtype;
519      char *qcp;
520 {
521   char *r;
522
523   r = (char *)xmalloc (strlen (s) + 2);
524   *r = *rl_completer_quote_characters;
525   strcpy (r + 1, s);
526   if (qcp)
527     *qcp = *rl_completer_quote_characters;
528   return r;
529 }
530
531 /* Find the bounds of the current word for completion purposes, and leave
532    rl_point set to the end of the word.  This function skips quoted
533    substrings (characters between matched pairs of characters in
534    rl_completer_quote_characters).  First we try to find an unclosed
535    quoted substring on which to do matching.  If one is not found, we use
536    the word break characters to find the boundaries of the current word.
537    We call an application-specific function to decide whether or not a
538    particular word break character is quoted; if that function returns a
539    non-zero result, the character does not break a word.  This function
540    returns the opening quote character if we found an unclosed quoted
541    substring, '\0' otherwise.  FP, if non-null, is set to a value saying
542    which (shell-like) quote characters we found (single quote, double
543    quote, or backslash) anywhere in the string.  DP, if non-null, is set to
544    the value of the delimiter character that caused a word break. */
545
546 static char
547 find_completion_word (fp, dp)
548      int *fp, *dp;
549 {
550   int scan, end, found_quote, delimiter, pass_next, isbrk;
551   char quote_char;
552
553   end = rl_point;
554   found_quote = delimiter = 0;
555   quote_char = '\0';
556
557   if (rl_completer_quote_characters)
558     {
559       /* We have a list of characters which can be used in pairs to
560          quote substrings for the completer.  Try to find the start
561          of an unclosed quoted substring. */
562       /* FOUND_QUOTE is set so we know what kind of quotes we found. */
563       for (scan = pass_next = 0; scan < end; scan++)
564         {
565           if (pass_next)
566             {
567               pass_next = 0;
568               continue;
569             }
570
571           /* Shell-like semantics for single quotes -- don't allow backslash
572              to quote anything in single quotes, especially not the closing
573              quote.  If you don't like this, take out the check on the value
574              of quote_char. */
575           if (quote_char != '\'' && rl_line_buffer[scan] == '\\')
576             {
577               pass_next = 1;
578               found_quote |= RL_QF_BACKSLASH;
579               continue;
580             }
581
582           if (quote_char != '\0')
583             {
584               /* Ignore everything until the matching close quote char. */
585               if (rl_line_buffer[scan] == quote_char)
586                 {
587                   /* Found matching close.  Abandon this substring. */
588                   quote_char = '\0';
589                   rl_point = end;
590                 }
591             }
592           else if (strchr (rl_completer_quote_characters, rl_line_buffer[scan]))
593             {
594               /* Found start of a quoted substring. */
595               quote_char = rl_line_buffer[scan];
596               rl_point = scan + 1;
597               /* Shell-like quoting conventions. */
598               if (quote_char == '\'')
599                 found_quote |= RL_QF_SINGLE_QUOTE;
600               else if (quote_char == '"')
601                 found_quote |= RL_QF_DOUBLE_QUOTE;
602             }
603         }
604     }
605
606   if (rl_point == end && quote_char == '\0')
607     {
608       /* We didn't find an unclosed quoted substring upon which to do
609          completion, so use the word break characters to find the
610          substring on which to complete. */
611       while (--rl_point)
612         {
613           scan = rl_line_buffer[rl_point];
614
615           if (strchr (rl_completer_word_break_characters, scan) == 0)
616             continue;
617
618           /* Call the application-specific function to tell us whether
619              this word break character is quoted and should be skipped. */
620           if (rl_char_is_quoted_p && found_quote &&
621               (*rl_char_is_quoted_p) (rl_line_buffer, rl_point))
622             continue;
623
624           /* Convoluted code, but it avoids an n^2 algorithm with calls
625              to char_is_quoted. */
626           break;
627         }
628     }
629
630   /* If we are at an unquoted word break, then advance past it. */
631   scan = rl_line_buffer[rl_point];
632
633   /* If there is an application-specific function to say whether or not
634      a character is quoted and we found a quote character, let that
635      function decide whether or not a character is a word break, even
636      if it is found in rl_completer_word_break_characters.  Don't bother
637      if we're at the end of the line, though. */
638   if (scan)
639     {
640       if (rl_char_is_quoted_p)
641         isbrk = (found_quote == 0 ||
642                 (*rl_char_is_quoted_p) (rl_line_buffer, rl_point) == 0) &&
643                 strchr (rl_completer_word_break_characters, scan) != 0;
644       else
645         isbrk = strchr (rl_completer_word_break_characters, scan) != 0;
646
647       if (isbrk)
648         {
649           /* If the character that caused the word break was a quoting
650              character, then remember it as the delimiter. */
651           if (rl_basic_quote_characters &&
652               strchr (rl_basic_quote_characters, scan) &&
653               (end - rl_point) > 1)
654             delimiter = scan;
655
656           /* If the character isn't needed to determine something special
657              about what kind of completion to perform, then advance past it. */
658           if (rl_special_prefixes == 0 || strchr (rl_special_prefixes, scan) == 0)
659             rl_point++;
660         }
661     }
662
663   if (fp)
664     *fp = found_quote;
665   if (dp)
666     *dp = delimiter;
667
668   return (quote_char);
669 }
670
671 static char **
672 gen_completion_matches (text, start, end, our_func, found_quote, quote_char)
673      char *text;
674      int start, end;
675      rl_compentry_func_t *our_func;
676      int found_quote, quote_char;
677 {
678   char **matches, *temp;
679
680   /* If the user wants to TRY to complete, but then wants to give
681      up and use the default completion function, they set the
682      variable rl_attempted_completion_function. */
683   if (rl_attempted_completion_function)
684     {
685       matches = (*rl_attempted_completion_function) (text, start, end);
686
687       if (matches || rl_attempted_completion_over)
688         {
689           rl_attempted_completion_over = 0;
690           return (matches);
691         }
692     }
693
694   /* Beware -- we're stripping the quotes here.  Do this only if we know
695      we are doing filename completion and the application has defined a
696      filename dequoting function. */
697   temp = (char *)NULL;
698
699   if (found_quote && our_func == rl_filename_completion_function &&
700       rl_filename_dequoting_function)
701     {
702       /* delete single and double quotes */
703       temp = (*rl_filename_dequoting_function) (text, quote_char);
704       text = temp;      /* not freeing text is not a memory leak */
705     }
706
707   matches = rl_completion_matches (text, our_func);
708   FREE (temp);
709   return matches;  
710 }
711
712 /* Filter out duplicates in MATCHES.  This frees up the strings in
713    MATCHES. */
714 static char **
715 remove_duplicate_matches (matches)
716      char **matches;
717 {
718   char *lowest_common;
719   int i, j, newlen;
720   char dead_slot;
721   char **temp_array;
722
723   /* Sort the items. */
724   for (i = 0; matches[i]; i++)
725     ;
726
727   /* Sort the array without matches[0], since we need it to
728      stay in place no matter what. */
729   if (i)
730     qsort (matches+1, i-1, sizeof (char *), (QSFUNC *)_rl_qsort_string_compare);
731
732   /* Remember the lowest common denominator for it may be unique. */
733   lowest_common = savestring (matches[0]);
734
735   for (i = newlen = 0; matches[i + 1]; i++)
736     {
737       if (strcmp (matches[i], matches[i + 1]) == 0)
738         {
739           free (matches[i]);
740           matches[i] = (char *)&dead_slot;
741         }
742       else
743         newlen++;
744     }
745
746   /* We have marked all the dead slots with (char *)&dead_slot.
747      Copy all the non-dead entries into a new array. */
748   temp_array = (char **)xmalloc ((3 + newlen) * sizeof (char *));
749   for (i = j = 1; matches[i]; i++)
750     {
751       if (matches[i] != (char *)&dead_slot)
752         temp_array[j++] = matches[i];
753     }
754   temp_array[j] = (char *)NULL;
755
756   if (matches[0] != (char *)&dead_slot)
757     free (matches[0]);
758
759   /* Place the lowest common denominator back in [0]. */
760   temp_array[0] = lowest_common;
761
762   /* If there is one string left, and it is identical to the
763      lowest common denominator, then the LCD is the string to
764      insert. */
765   if (j == 2 && strcmp (temp_array[0], temp_array[1]) == 0)
766     {
767       free (temp_array[1]);
768       temp_array[1] = (char *)NULL;
769     }
770   return (temp_array);
771 }
772
773 /* Find the common prefix of the list of matches, and put it into
774    matches[0]. */
775 static int
776 compute_lcd_of_matches (match_list, matches, text)
777      char **match_list;
778      int matches;
779      const char *text;
780 {
781   register int i, c1, c2, si;
782   int low;              /* Count of max-matched characters. */
783
784   /* If only one match, just use that.  Otherwise, compare each
785      member of the list with the next, finding out where they
786      stop matching. */
787   if (matches == 1)
788     {
789       match_list[0] = match_list[1];
790       match_list[1] = (char *)NULL;
791       return 1;
792     }
793
794   for (i = 1, low = 100000; i < matches; i++)
795     {
796       if (_rl_completion_case_fold)
797         {
798           for (si = 0;
799                (c1 = _rl_to_lower(match_list[i][si])) &&
800                (c2 = _rl_to_lower(match_list[i + 1][si]));
801                si++)
802             if (c1 != c2)
803               break;
804         }
805       else
806         {
807           for (si = 0;
808                (c1 = match_list[i][si]) &&
809                (c2 = match_list[i + 1][si]);
810                si++)
811             if (c1 != c2)
812               break;
813         }
814
815       if (low > si)
816         low = si;
817     }
818
819   /* If there were multiple matches, but none matched up to even the
820      first character, and the user typed something, use that as the
821      value of matches[0]. */
822   if (low == 0 && text && *text)
823     {
824       match_list[0] = (char *)xmalloc (strlen (text) + 1);
825       strcpy (match_list[0], text);
826     }
827   else
828     {
829       match_list[0] = (char *)xmalloc (low + 1);
830
831       /* If we are ignoring case, try to preserve the case of the string
832          the user typed in the face of multiple matches differing in case. */
833       if (_rl_completion_case_fold)
834         {
835           /* sort the list to get consistent answers. */
836           qsort (match_list+1, matches, sizeof(char *), (QSFUNC *)_rl_qsort_string_compare);
837
838           si = strlen (text);
839           if (si <= low)
840             {
841               for (i = 1; i <= matches; i++)
842                 if (strncmp (match_list[i], text, si) == 0)
843                   {
844                     strncpy (match_list[0], match_list[i], low);
845                     break;
846                   }
847               /* no casematch, use first entry */
848               if (i > matches)
849                 strncpy (match_list[0], match_list[1], low);
850             }
851           else
852             /* otherwise, just use the text the user typed. */
853             strncpy (match_list[0], text, low);
854         }
855       else
856         strncpy (match_list[0], match_list[1], low);
857
858       match_list[0][low] = '\0';
859     }
860
861   return matches;
862 }
863
864 static int
865 postprocess_matches (matchesp, matching_filenames)
866      char ***matchesp;
867      int matching_filenames;
868 {
869   char *t, **matches, **temp_matches;
870   int nmatch, i;
871
872   matches = *matchesp;
873
874   /* It seems to me that in all the cases we handle we would like
875      to ignore duplicate possiblilities.  Scan for the text to
876      insert being identical to the other completions. */
877   if (rl_ignore_completion_duplicates)
878     {
879       temp_matches = remove_duplicate_matches (matches);
880       free (matches);
881       matches = temp_matches;
882     }
883
884   /* If we are matching filenames, then here is our chance to
885      do clever processing by re-examining the list.  Call the
886      ignore function with the array as a parameter.  It can
887      munge the array, deleting matches as it desires. */
888   if (rl_ignore_some_completions_function && matching_filenames)
889     {
890       for (nmatch = 1; matches[nmatch]; nmatch++)
891         ;
892       (void)(*rl_ignore_some_completions_function) (matches);
893       if (matches == 0 || matches[0] == 0)
894         {
895           FREE (matches);
896           *matchesp = (char **)0;
897           return 0;
898         }
899       else
900         {
901           /* If we removed some matches, recompute the common prefix. */
902           for (i = 1; matches[i]; i++)
903             ;
904           if (i > 1 && i < nmatch)
905             {
906               t = matches[0];
907               compute_lcd_of_matches (matches, i - 1, t);
908               FREE (t);
909             }
910         }
911     }
912
913   *matchesp = matches;
914   return (1);
915 }
916
917 /* A convenience function for displaying a list of strings in
918    columnar format on readline's output stream.  MATCHES is the list
919    of strings, in argv format, LEN is the number of strings in MATCHES,
920    and MAX is the length of the longest string in MATCHES. */
921 void
922 rl_display_match_list (matches, len, max)
923      char **matches;
924      int len, max;
925 {
926   int count, limit, printed_len;
927   int i, j, k, l;
928   char *temp;
929
930   /* How many items of MAX length can we fit in the screen window? */
931   max += 2;
932   limit = _rl_screenwidth / max;
933   if (limit != 1 && (limit * max == _rl_screenwidth))
934     limit--;
935
936   /* Avoid a possible floating exception.  If max > _rl_screenwidth,
937      limit will be 0 and a divide-by-zero fault will result. */
938   if (limit == 0)
939     limit = 1;
940
941   /* How many iterations of the printing loop? */
942   count = (len + (limit - 1)) / limit;
943
944   /* Watch out for special case.  If LEN is less than LIMIT, then
945      just do the inner printing loop.
946            0 < len <= limit  implies  count = 1. */
947
948   /* Sort the items if they are not already sorted. */
949   if (rl_ignore_completion_duplicates == 0)
950     qsort (matches + 1, len, sizeof (char *), (QSFUNC *)_rl_qsort_string_compare);
951
952   rl_crlf ();
953
954   if (_rl_print_completions_horizontally == 0)
955     {
956       /* Print the sorted items, up-and-down alphabetically, like ls. */
957       for (i = 1; i <= count; i++)
958         {
959           for (j = 0, l = i; j < limit; j++)
960             {
961               if (l > len || matches[l] == 0)
962                 break;
963               else
964                 {
965                   temp = printable_part (matches[l]);
966                   printed_len = print_filename (temp, matches[l]);
967
968                   if (j + 1 < limit)
969                     for (k = 0; k < max - printed_len; k++)
970                       putc (' ', rl_outstream);
971                 }
972               l += count;
973             }
974           rl_crlf ();
975         }
976     }
977   else
978     {
979       /* Print the sorted items, across alphabetically, like ls -x. */
980       for (i = 1; matches[i]; i++)
981         {
982           temp = printable_part (matches[i]);
983           printed_len = print_filename (temp, matches[i]);
984           /* Have we reached the end of this line? */
985           if (matches[i+1])
986             {
987               if (i && (limit > 1) && (i % limit) == 0)
988                 rl_crlf ();
989               else
990                 for (k = 0; k < max - printed_len; k++)
991                   putc (' ', rl_outstream);
992             }
993         }
994       rl_crlf ();
995     }
996 }
997
998 /* Display MATCHES, a list of matching filenames in argv format.  This
999    handles the simple case -- a single match -- first.  If there is more
1000    than one match, we compute the number of strings in the list and the
1001    length of the longest string, which will be needed by the display
1002    function.  If the application wants to handle displaying the list of
1003    matches itself, it sets RL_COMPLETION_DISPLAY_MATCHES_HOOK to the
1004    address of a function, and we just call it.  If we're handling the
1005    display ourselves, we just call rl_display_match_list.  We also check
1006    that the list of matches doesn't exceed the user-settable threshold,
1007    and ask the user if he wants to see the list if there are more matches
1008    than RL_COMPLETION_QUERY_ITEMS. */
1009 static void
1010 display_matches (matches)
1011      char **matches;
1012 {
1013   int len, max, i;
1014   char *temp;
1015
1016   /* Move to the last visible line of a possibly-multiple-line command. */
1017   _rl_move_vert (_rl_vis_botlin);
1018
1019   /* Handle simple case first.  What if there is only one answer? */
1020   if (matches[1] == 0)
1021     {
1022       temp = printable_part (matches[0]);
1023       rl_crlf ();
1024       print_filename (temp, matches[0]);
1025       rl_crlf ();
1026
1027       rl_forced_update_display ();
1028       rl_display_fixed = 1;
1029
1030       return;
1031     }
1032
1033   /* There is more than one answer.  Find out how many there are,
1034      and find the maximum printed length of a single entry. */
1035   for (max = 0, i = 1; matches[i]; i++)
1036     {
1037       temp = printable_part (matches[i]);
1038       len = strlen (temp);
1039
1040       if (len > max)
1041         max = len;
1042     }
1043
1044   len = i - 1;
1045
1046   /* If the caller has defined a display hook, then call that now. */
1047   if (rl_completion_display_matches_hook)
1048     {
1049       (*rl_completion_display_matches_hook) (matches, len, max);
1050       return;
1051     }
1052         
1053   /* If there are many items, then ask the user if she really wants to
1054      see them all. */
1055   if (len >= rl_completion_query_items)
1056     {
1057       rl_crlf ();
1058       fprintf (rl_outstream, "Display all %d possibilities? (y or n)", len);
1059       fflush (rl_outstream);
1060       if (get_y_or_n () == 0)
1061         {
1062           rl_crlf ();
1063
1064           rl_forced_update_display ();
1065           rl_display_fixed = 1;
1066
1067           return;
1068         }
1069     }
1070
1071   rl_display_match_list (matches, len, max);
1072
1073   rl_forced_update_display ();
1074   rl_display_fixed = 1;
1075 }
1076
1077 static char *
1078 make_quoted_replacement (match, mtype, qc)
1079      char *match;
1080      int mtype;
1081      char *qc;  /* Pointer to quoting character, if any */
1082 {
1083   int should_quote, do_replace;
1084   char *replacement;
1085
1086   /* If we are doing completion on quoted substrings, and any matches
1087      contain any of the completer_word_break_characters, then auto-
1088      matically prepend the substring with a quote character (just pick
1089      the first one from the list of such) if it does not already begin
1090      with a quote string.  FIXME: Need to remove any such automatically
1091      inserted quote character when it no longer is necessary, such as
1092      if we change the string we are completing on and the new set of
1093      matches don't require a quoted substring. */
1094   replacement = match;
1095
1096   should_quote = match && rl_completer_quote_characters &&
1097                         rl_filename_completion_desired &&
1098                         rl_filename_quoting_desired;
1099
1100   if (should_quote)
1101     should_quote = should_quote && (!qc || !*qc ||
1102                      (rl_completer_quote_characters && strchr (rl_completer_quote_characters, *qc)));
1103
1104   if (should_quote)
1105     {
1106       /* If there is a single match, see if we need to quote it.
1107          This also checks whether the common prefix of several
1108          matches needs to be quoted. */
1109       should_quote = rl_filename_quote_characters
1110                         ? (_rl_strpbrk (match, rl_filename_quote_characters) != 0)
1111                         : 0;
1112
1113       do_replace = should_quote ? mtype : NO_MATCH;
1114       /* Quote the replacement, since we found an embedded
1115          word break character in a potential match. */
1116       if (do_replace != NO_MATCH && rl_filename_quoting_function)
1117         replacement = (*rl_filename_quoting_function) (match, do_replace, qc);
1118     }
1119   return (replacement);
1120 }
1121
1122 static void
1123 insert_match (match, start, mtype, qc)
1124      char *match;
1125      int start, mtype;
1126      char *qc;
1127 {
1128   char *replacement;
1129   char oqc;
1130
1131   oqc = qc ? *qc : '\0';
1132   replacement = make_quoted_replacement (match, mtype, qc);
1133
1134   /* Now insert the match. */
1135   if (replacement)
1136     {
1137       /* Don't double an opening quote character. */
1138       if (qc && *qc && start && rl_line_buffer[start - 1] == *qc &&
1139             replacement[0] == *qc)
1140         start--;
1141       /* If make_quoted_replacement changed the quoting character, remove
1142          the opening quote and insert the (fully-quoted) replacement. */
1143       else if (qc && (*qc != oqc) && start && rl_line_buffer[start - 1] == oqc &&
1144             replacement[0] != oqc)
1145         start--;
1146       _rl_replace_text (replacement, start, rl_point - 1);
1147       if (replacement != match)
1148         free (replacement);
1149     }
1150 }
1151
1152 /* Append any necessary closing quote and a separator character to the
1153    just-inserted match.  If the user has specified that directories
1154    should be marked by a trailing `/', append one of those instead.  The
1155    default trailing character is a space.  Returns the number of characters
1156    appended.  If NONTRIVIAL_MATCH is set, we test for a symlink (if the OS
1157    has them) and don't add a suffix for a symlink to a directory.  A
1158    nontrivial match is one that actually adds to the word being completed.  */
1159 static int
1160 append_to_match (text, delimiter, quote_char, nontrivial_match)
1161      char *text;
1162      int delimiter, quote_char, nontrivial_match;
1163 {
1164   char temp_string[4], *filename;
1165   int temp_string_index, s;
1166   struct stat finfo;
1167
1168   temp_string_index = 0;
1169   if (quote_char && rl_point && rl_line_buffer[rl_point - 1] != quote_char)
1170     temp_string[temp_string_index++] = quote_char;
1171
1172   if (delimiter)
1173     temp_string[temp_string_index++] = delimiter;
1174   else if (rl_completion_append_character)
1175     temp_string[temp_string_index++] = rl_completion_append_character;
1176
1177   temp_string[temp_string_index++] = '\0';
1178
1179   if (rl_filename_completion_desired)
1180     {
1181       filename = tilde_expand (text);
1182       s = nontrivial_match ? LSTAT (filename, &finfo) : stat (filename, &finfo);
1183       if (s == 0 && S_ISDIR (finfo.st_mode))
1184         {
1185           if (_rl_complete_mark_directories && rl_line_buffer[rl_point] != '/')
1186             rl_insert_text ("/");
1187         }
1188 #ifdef S_ISLNK
1189       /* Don't add anything if the filename is a symlink and resolves to a
1190          directory. */
1191       else if (s == 0 && S_ISLNK (finfo.st_mode) &&
1192                stat (filename, &finfo) == 0 && S_ISDIR (finfo.st_mode))
1193         ;
1194 #endif
1195       else
1196         {
1197           if (rl_point == rl_end)
1198             rl_insert_text (temp_string);
1199         }
1200       free (filename);
1201     }
1202   else
1203     {
1204       if (rl_point == rl_end)
1205         rl_insert_text (temp_string);
1206     }
1207
1208   return (temp_string_index);
1209 }
1210
1211 static void
1212 insert_all_matches (matches, point, qc)
1213      char **matches;
1214      int point;
1215      char *qc;
1216 {
1217   int i;
1218   char *rp;
1219
1220   rl_begin_undo_group ();
1221   /* remove any opening quote character; make_quoted_replacement will add
1222      it back. */
1223   if (qc && *qc && point && rl_line_buffer[point - 1] == *qc)
1224     point--;
1225   rl_delete_text (point, rl_point);
1226   rl_point = point;
1227
1228   if (matches[1])
1229     {
1230       for (i = 1; matches[i]; i++)
1231         {
1232           rp = make_quoted_replacement (matches[i], SINGLE_MATCH, qc);
1233           rl_insert_text (rp);
1234           rl_insert_text (" ");
1235           if (rp != matches[i])
1236             free (rp);
1237         }
1238     }
1239   else
1240     {
1241       rp = make_quoted_replacement (matches[0], SINGLE_MATCH, qc);
1242       rl_insert_text (rp);
1243       rl_insert_text (" ");
1244       if (rp != matches[0])
1245         free (rp);
1246     }
1247   rl_end_undo_group ();
1248 }
1249
1250 static void
1251 free_match_list (matches)
1252      char **matches;
1253 {
1254   register int i;
1255
1256   for (i = 0; matches[i]; i++)
1257     free (matches[i]);
1258   free (matches);
1259 }
1260
1261 /* Complete the word at or before point.
1262    WHAT_TO_DO says what to do with the completion.
1263    `?' means list the possible completions.
1264    TAB means do standard completion.
1265    `*' means insert all of the possible completions.
1266    `!' means to do standard completion, and list all possible completions if
1267    there is more than one. */
1268 int
1269 rl_complete_internal (what_to_do)
1270      int what_to_do;
1271 {
1272   char **matches;
1273   rl_compentry_func_t *our_func;
1274   int start, end, delimiter, found_quote, i, nontrivial_lcd;
1275   char *text, *saved_line_buffer;
1276   char quote_char;
1277
1278   RL_SETSTATE(RL_STATE_COMPLETING);
1279   /* Only the completion entry function can change these. */
1280   rl_filename_completion_desired = 0;
1281   rl_filename_quoting_desired = 1;
1282   rl_completion_type = what_to_do;
1283
1284   saved_line_buffer = rl_line_buffer ? savestring (rl_line_buffer) : (char *)NULL;
1285   our_func = rl_completion_entry_function
1286                 ? rl_completion_entry_function
1287                 : rl_filename_completion_function;
1288
1289   /* We now look backwards for the start of a filename/variable word. */
1290   end = rl_point;
1291   found_quote = delimiter = 0;
1292   quote_char = '\0';
1293
1294   if (rl_point)
1295     /* This (possibly) changes rl_point.  If it returns a non-zero char,
1296        we know we have an open quote. */
1297     quote_char = find_completion_word (&found_quote, &delimiter);
1298
1299   start = rl_point;
1300   rl_point = end;
1301
1302   text = rl_copy_text (start, end);
1303   matches = gen_completion_matches (text, start, end, our_func, found_quote, quote_char);
1304   /* nontrivial_lcd is set if the common prefix adds something to the word
1305      being completed. */
1306   nontrivial_lcd = matches && strcmp (text, matches[0]) != 0;
1307   free (text);
1308
1309   if (matches == 0)
1310     {
1311       rl_ding ();
1312       FREE (saved_line_buffer);
1313       RL_UNSETSTATE(RL_STATE_COMPLETING);
1314       return (0);
1315     }
1316
1317   /* If we are matching filenames, the attempted completion function will
1318      have set rl_filename_completion_desired to a non-zero value.  The basic
1319      rl_filename_completion_function does this. */
1320   i = rl_filename_completion_desired;
1321
1322   if (postprocess_matches (&matches, i) == 0)
1323     {
1324       rl_ding ();
1325       FREE (saved_line_buffer);
1326       completion_changed_buffer = 0;
1327       RL_UNSETSTATE(RL_STATE_COMPLETING);
1328       return (0);
1329     }
1330
1331   switch (what_to_do)
1332     {
1333     case TAB:
1334     case '!':
1335       /* Insert the first match with proper quoting. */
1336       if (*matches[0])
1337         insert_match (matches[0], start, matches[1] ? MULT_MATCH : SINGLE_MATCH, &quote_char);
1338
1339       /* If there are more matches, ring the bell to indicate.
1340          If we are in vi mode, Posix.2 says to not ring the bell.
1341          If the `show-all-if-ambiguous' variable is set, display
1342          all the matches immediately.  Otherwise, if this was the
1343          only match, and we are hacking files, check the file to
1344          see if it was a directory.  If so, and the `mark-directories'
1345          variable is set, add a '/' to the name.  If not, and we
1346          are at the end of the line, then add a space.  */
1347       if (matches[1])
1348         {
1349           if (what_to_do == '!')
1350             {
1351               display_matches (matches);
1352               break;
1353             }
1354           else if (rl_editing_mode != vi_mode)
1355             rl_ding (); /* There are other matches remaining. */
1356         }
1357       else
1358         append_to_match (matches[0], delimiter, quote_char, nontrivial_lcd);
1359
1360       break;
1361
1362     case '*':
1363       insert_all_matches (matches, start, &quote_char);
1364       break;
1365
1366     case '?':
1367       display_matches (matches);
1368       break;
1369
1370     default:
1371       fprintf (stderr, "\r\nreadline: bad value %d for what_to_do in rl_complete\n", what_to_do);
1372       rl_ding ();
1373       FREE (saved_line_buffer);
1374       RL_UNSETSTATE(RL_STATE_COMPLETING);
1375       return 1;
1376     }
1377
1378   free_match_list (matches);
1379
1380   /* Check to see if the line has changed through all of this manipulation. */
1381   if (saved_line_buffer)
1382     {
1383       completion_changed_buffer = strcmp (rl_line_buffer, saved_line_buffer) != 0;
1384       free (saved_line_buffer);
1385     }
1386
1387   RL_UNSETSTATE(RL_STATE_COMPLETING);
1388   return 0;
1389 }
1390
1391 /***************************************************************/
1392 /*                                                             */
1393 /*  Application-callable completion match generator functions  */
1394 /*                                                             */
1395 /***************************************************************/
1396
1397 /* Return an array of (char *) which is a list of completions for TEXT.
1398    If there are no completions, return a NULL pointer.
1399    The first entry in the returned array is the substitution for TEXT.
1400    The remaining entries are the possible completions.
1401    The array is terminated with a NULL pointer.
1402
1403    ENTRY_FUNCTION is a function of two args, and returns a (char *).
1404      The first argument is TEXT.
1405      The second is a state argument; it should be zero on the first call, and
1406      non-zero on subsequent calls.  It returns a NULL pointer to the caller
1407      when there are no more matches.
1408  */
1409 char **
1410 rl_completion_matches (text, entry_function)
1411      const char *text;
1412      rl_compentry_func_t *entry_function;
1413 {
1414   /* Number of slots in match_list. */
1415   int match_list_size;
1416
1417   /* The list of matches. */
1418   char **match_list;
1419
1420   /* Number of matches actually found. */
1421   int matches;
1422
1423   /* Temporary string binder. */
1424   char *string;
1425
1426   matches = 0;
1427   match_list_size = 10;
1428   match_list = (char **)xmalloc ((match_list_size + 1) * sizeof (char *));
1429   match_list[1] = (char *)NULL;
1430
1431   while (string = (*entry_function) (text, matches))
1432     {
1433       if (matches + 1 == match_list_size)
1434         match_list = (char **)xrealloc
1435           (match_list, ((match_list_size += 10) + 1) * sizeof (char *));
1436
1437       match_list[++matches] = string;
1438       match_list[matches + 1] = (char *)NULL;
1439     }
1440
1441   /* If there were any matches, then look through them finding out the
1442      lowest common denominator.  That then becomes match_list[0]. */
1443   if (matches)
1444     compute_lcd_of_matches (match_list, matches, text);
1445   else                          /* There were no matches. */
1446     {
1447       free (match_list);
1448       match_list = (char **)NULL;
1449     }
1450   return (match_list);
1451 }
1452
1453 /* A completion function for usernames.
1454    TEXT contains a partial username preceded by a random
1455    character (usually `~').  */
1456 char *
1457 rl_username_completion_function (text, state)
1458      const char *text;
1459      int state;
1460 {
1461 #if defined (__WIN32__) || defined (__OPENNT)
1462   return (char *)NULL;
1463 #else /* !__WIN32__ && !__OPENNT) */
1464   static char *username = (char *)NULL;
1465   static struct passwd *entry;
1466   static int namelen, first_char, first_char_loc;
1467   char *value;
1468
1469   if (state == 0)
1470     {
1471       FREE (username);
1472
1473       first_char = *text;
1474       first_char_loc = first_char == '~';
1475
1476       username = savestring (&text[first_char_loc]);
1477       namelen = strlen (username);
1478       setpwent ();
1479     }
1480
1481   while (entry = getpwent ())
1482     {
1483       /* Null usernames should result in all users as possible completions. */
1484       if (namelen == 0 || (STREQN (username, entry->pw_name, namelen)))
1485         break;
1486     }
1487
1488   if (entry == 0)
1489     {
1490       endpwent ();
1491       return ((char *)NULL);
1492     }
1493   else
1494     {
1495       value = (char *)xmalloc (2 + strlen (entry->pw_name));
1496
1497       *value = *text;
1498
1499       strcpy (value + first_char_loc, entry->pw_name);
1500
1501       if (first_char == '~')
1502         rl_filename_completion_desired = 1;
1503
1504       return (value);
1505     }
1506 #endif /* !__WIN32__ && !__OPENNT */
1507 }
1508
1509 /* Okay, now we write the entry_function for filename completion.  In the
1510    general case.  Note that completion in the shell is a little different
1511    because of all the pathnames that must be followed when looking up the
1512    completion for a command. */
1513 char *
1514 rl_filename_completion_function (text, state)
1515      const char *text;
1516      int state;
1517 {
1518   static DIR *directory = (DIR *)NULL;
1519   static char *filename = (char *)NULL;
1520   static char *dirname = (char *)NULL;
1521   static char *users_dirname = (char *)NULL;
1522   static int filename_len;
1523   char *temp;
1524   int dirlen;
1525   struct dirent *entry;
1526
1527   /* If we don't have any state, then do some initialization. */
1528   if (state == 0)
1529     {
1530       /* If we were interrupted before closing the directory or reading
1531          all of its contents, close it. */
1532       if (directory)
1533         {
1534           closedir (directory);
1535           directory = (DIR *)NULL;
1536         }
1537       FREE (dirname);
1538       FREE (filename);
1539       FREE (users_dirname);
1540
1541       filename = savestring (text);
1542       if (*text == 0)
1543         text = ".";
1544       dirname = savestring (text);
1545
1546       temp = strrchr (dirname, '/');
1547
1548 #if defined (__MSDOS__)
1549       /* special hack for //X/... */
1550       if (dirname[0] == '/' && dirname[1] == '/' && ISALPHA ((unsigned char)dirname[2]) && dirname[3] == '/')
1551         temp = strrchr (dirname + 3, '/');
1552 #endif
1553
1554       if (temp)
1555         {
1556           strcpy (filename, ++temp);
1557           *temp = '\0';
1558         }
1559 #if defined (__MSDOS__)
1560       /* searches from current directory on the drive */
1561       else if (ISALPHA ((unsigned char)dirname[0]) && dirname[1] == ':')
1562         {
1563           strcpy (filename, dirname + 2);
1564           dirname[2] = '\0';
1565         }
1566 #endif
1567       else
1568         {
1569           dirname[0] = '.';
1570           dirname[1] = '\0';
1571         }
1572
1573       /* We aren't done yet.  We also support the "~user" syntax. */
1574
1575       /* Save the version of the directory that the user typed. */
1576       users_dirname = savestring (dirname);
1577
1578       if (*dirname == '~')
1579         {
1580           temp = tilde_expand (dirname);
1581           free (dirname);
1582           dirname = temp;
1583         }
1584
1585       if (rl_directory_rewrite_hook)
1586         (*rl_directory_rewrite_hook) (&dirname);
1587
1588       if (rl_directory_completion_hook && (*rl_directory_completion_hook) (&dirname))
1589         {
1590           free (users_dirname);
1591           users_dirname = savestring (dirname);
1592         }
1593
1594       directory = opendir (dirname);
1595       filename_len = strlen (filename);
1596
1597       rl_filename_completion_desired = 1;
1598     }
1599
1600   /* At this point we should entertain the possibility of hacking wildcarded
1601      filenames, like /usr/man/man<WILD>/te<TAB>.  If the directory name
1602      contains globbing characters, then build an array of directories, and
1603      then map over that list while completing. */
1604   /* *** UNIMPLEMENTED *** */
1605
1606   /* Now that we have some state, we can read the directory. */
1607
1608   entry = (struct dirent *)NULL;
1609   while (directory && (entry = readdir (directory)))
1610     {
1611       /* Special case for no filename.  If the user has disabled the
1612          `match-hidden-files' variable, skip filenames beginning with `.'.
1613          All other entries except "." and ".." match. */
1614       if (filename_len == 0)
1615         {
1616           if (_rl_match_hidden_files == 0 && HIDDEN_FILE (entry->d_name))
1617             continue;
1618
1619           if (entry->d_name[0] != '.' ||
1620                (entry->d_name[1] &&
1621                  (entry->d_name[1] != '.' || entry->d_name[2])))
1622             break;
1623         }
1624       else
1625         {
1626           /* Otherwise, if these match up to the length of filename, then
1627              it is a match. */
1628           if (_rl_completion_case_fold)
1629             {
1630               if ((_rl_to_lower (entry->d_name[0]) == _rl_to_lower (filename[0])) &&
1631                   (((int)D_NAMLEN (entry)) >= filename_len) &&
1632                   (_rl_strnicmp (filename, entry->d_name, filename_len) == 0))
1633                 break;
1634             }
1635           else
1636             {
1637               if ((entry->d_name[0] == filename[0]) &&
1638                   (((int)D_NAMLEN (entry)) >= filename_len) &&
1639                   (strncmp (filename, entry->d_name, filename_len) == 0))
1640                 break;
1641             }
1642         }
1643     }
1644
1645   if (entry == 0)
1646     {
1647       if (directory)
1648         {
1649           closedir (directory);
1650           directory = (DIR *)NULL;
1651         }
1652       if (dirname)
1653         {
1654           free (dirname);
1655           dirname = (char *)NULL;
1656         }
1657       if (filename)
1658         {
1659           free (filename);
1660           filename = (char *)NULL;
1661         }
1662       if (users_dirname)
1663         {
1664           free (users_dirname);
1665           users_dirname = (char *)NULL;
1666         }
1667
1668       return (char *)NULL;
1669     }
1670   else
1671     {
1672       /* dirname && (strcmp (dirname, ".") != 0) */
1673       if (dirname && (dirname[0] != '.' || dirname[1]))
1674         {
1675           if (rl_complete_with_tilde_expansion && *users_dirname == '~')
1676             {
1677               dirlen = strlen (dirname);
1678               temp = (char *)xmalloc (2 + dirlen + D_NAMLEN (entry));
1679               strcpy (temp, dirname);
1680               /* Canonicalization cuts off any final slash present.  We
1681                  may need to add it back. */
1682               if (dirname[dirlen - 1] != '/')
1683                 {
1684                   temp[dirlen++] = '/';
1685                   temp[dirlen] = '\0';
1686                 }
1687             }
1688           else
1689             {
1690               dirlen = strlen (users_dirname);
1691               temp = (char *)xmalloc (2 + dirlen + D_NAMLEN (entry));
1692               strcpy (temp, users_dirname);
1693               /* Make sure that temp has a trailing slash here. */
1694               if (users_dirname[dirlen - 1] != '/')
1695                 temp[dirlen++] = '/';
1696             }
1697
1698           strcpy (temp + dirlen, entry->d_name);
1699         }
1700       else
1701         temp = savestring (entry->d_name);
1702
1703       return (temp);
1704     }
1705 }
1706
1707 /* An initial implementation of a menu completion function a la tcsh.  The
1708    first time (if the last readline command was not rl_menu_complete), we
1709    generate the list of matches.  This code is very similar to the code in
1710    rl_complete_internal -- there should be a way to combine the two.  Then,
1711    for each item in the list of matches, we insert the match in an undoable
1712    fashion, with the appropriate character appended (this happens on the
1713    second and subsequent consecutive calls to rl_menu_complete).  When we
1714    hit the end of the match list, we restore the original unmatched text,
1715    ring the bell, and reset the counter to zero. */
1716 int
1717 rl_menu_complete (count, ignore)
1718      int count, ignore;
1719 {
1720   rl_compentry_func_t *our_func;
1721   int matching_filenames, found_quote;
1722
1723   static char *orig_text;
1724   static char **matches = (char **)0;
1725   static int match_list_index = 0;
1726   static int match_list_size = 0;
1727   static int orig_start, orig_end;
1728   static char quote_char;
1729   static int delimiter;
1730
1731   /* The first time through, we generate the list of matches and set things
1732      up to insert them. */
1733   if (rl_last_func != rl_menu_complete)
1734     {
1735       /* Clean up from previous call, if any. */
1736       FREE (orig_text);
1737       if (matches)
1738         free_match_list (matches);
1739
1740       match_list_index = match_list_size = 0;
1741       matches = (char **)NULL;
1742
1743       /* Only the completion entry function can change these. */
1744       rl_filename_completion_desired = 0;
1745       rl_filename_quoting_desired = 1;
1746       rl_completion_type = '%';
1747
1748       our_func = rl_completion_entry_function
1749                         ? rl_completion_entry_function
1750                         : rl_filename_completion_function;
1751
1752       /* We now look backwards for the start of a filename/variable word. */
1753       orig_end = rl_point;
1754       found_quote = delimiter = 0;
1755       quote_char = '\0';
1756
1757       if (rl_point)
1758         /* This (possibly) changes rl_point.  If it returns a non-zero char,
1759            we know we have an open quote. */
1760         quote_char = find_completion_word (&found_quote, &delimiter);
1761
1762       orig_start = rl_point;
1763       rl_point = orig_end;
1764
1765       orig_text = rl_copy_text (orig_start, orig_end);
1766       matches = gen_completion_matches (orig_text, orig_start, orig_end,
1767                                         our_func, found_quote, quote_char);
1768
1769       /* If we are matching filenames, the attempted completion function will
1770          have set rl_filename_completion_desired to a non-zero value.  The basic
1771          rl_filename_completion_function does this. */
1772       matching_filenames = rl_filename_completion_desired;
1773
1774       if (matches == 0 || postprocess_matches (&matches, matching_filenames) == 0)
1775         {
1776           rl_ding ();
1777           FREE (matches);
1778           matches = (char **)0;
1779           FREE (orig_text);
1780           orig_text = (char *)0;
1781           completion_changed_buffer = 0;
1782           return (0);
1783         }
1784
1785       for (match_list_size = 0; matches[match_list_size]; match_list_size++)
1786         ;
1787       /* matches[0] is lcd if match_list_size > 1, but the circular buffer
1788          code below should take care of it. */
1789     }
1790
1791   /* Now we have the list of matches.  Replace the text between
1792      rl_line_buffer[orig_start] and rl_line_buffer[rl_point] with
1793      matches[match_list_index], and add any necessary closing char. */
1794
1795   if (matches == 0 || match_list_size == 0) 
1796     {
1797       rl_ding ();
1798       FREE (matches);
1799       matches = (char **)0;
1800       completion_changed_buffer = 0;
1801       return (0);
1802     }
1803
1804   match_list_index = (match_list_index + count) % match_list_size;
1805   if (match_list_index < 0)
1806     match_list_index += match_list_size;
1807
1808   if (match_list_index == 0 && match_list_size > 1)
1809     {
1810       rl_ding ();
1811       insert_match (orig_text, orig_start, MULT_MATCH, &quote_char);
1812     }
1813   else
1814     {
1815       insert_match (matches[match_list_index], orig_start, SINGLE_MATCH, &quote_char);
1816       append_to_match (matches[match_list_index], delimiter, quote_char,
1817                        strcmp (orig_text, matches[match_list_index]));
1818     }
1819
1820   completion_changed_buffer = 1;
1821   return (0);
1822 }