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