Do not copy old versions of libreadline.a/libhistory.a if they do not exist
[external/binutils.git] / 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 1, 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    675 Mass Ave, Cambridge, MA 02139, USA. */
22
23 #include "sysdep.h"
24 #include <stdio.h>
25 #include <fcntl.h>
26 #if !defined (NO_SYS_FILE)
27 #  include <sys/file.h>
28 #endif /* !NO_SYS_FILE */
29
30 #include <errno.h>
31 /* Not all systems declare ERRNO in errno.h... and some systems #define it! */
32 #if !defined (errno)
33 extern int errno;
34 #endif /* !errno */
35
36 /* These next are for filename completion.  Perhaps this belongs
37    in a different place. */
38 #if !defined(__MSDOS__) && !defined(_MSC_VER)
39 #include <pwd.h>
40 #endif /* __MSDOS__ */
41 #if defined (USG) && !defined (isc386) && !defined (sgi)
42 extern struct passwd *getpwuid (), *getpwent ();
43 #endif
44 #if defined (isc386) && !defined (__STDC__) && defined (_POSIX_SOURCE)
45 extern struct passwd *getpwent ();
46 #endif
47
48 /* Included by <fcntl.h> on some systems, but not SCO, so include it here.  */
49 #include <sys/stat.h>
50
51 /* System-specific feature definitions and include files. */
52 #include "rldefs.h"
53
54 /* Some standard library routines. */
55 #include "readline.h"
56
57 /* Possible values for do_replace in rl_complete_internal. */
58 #define NO_MATCH        0
59 #define SINGLE_MATCH    1
60 #define MULT_MATCH      2
61
62 #if !defined (strchr) && !defined (__STDC__)
63 extern char *strchr (), *strrchr ();
64 #endif /* !strchr && !__STDC__ */
65
66 extern char *tilde_expand ();
67 extern char *rl_copy_text ();
68
69 extern Function *rl_last_func;
70 extern int rl_editing_mode;
71 extern int screenwidth;
72
73 /* Forward declarations for functions defined and used in this file. */
74 char *filename_completion_function ();
75 char **completion_matches ();
76
77 static int compare_strings ();
78 static char *rl_strpbrk ();
79
80 #if defined (STATIC_MALLOC)
81 static char *xmalloc (), *xrealloc ();
82 #else
83 extern char *xmalloc (), *xrealloc ();
84 #endif /* STATIC_MALLOC */
85 \f
86 /* If non-zero, then this is the address of a function to call when
87    completing on a directory name.  The function is called with
88    the address of a string (the current directory name) as an arg. */
89 Function *rl_symbolic_link_hook = (Function *)NULL;
90
91 /* Non-zero means readline completion functions perform tilde expansion. */
92 int rl_complete_with_tilde_expansion = 0;
93
94 #define VISIBLE_STATS
95
96 #if defined (VISIBLE_STATS)
97 #  if !defined (X_OK)
98 #    define X_OK 1
99 #  endif
100
101 static int stat_char ();
102
103 /* Non-zero means add an additional character to each filename displayed
104    during listing completion iff rl_filename_completion_desired which helps
105    to indicate the type of file being listed. */
106 int rl_visible_stats = 0;
107 #endif /* VISIBLE_STATS */
108
109 /* **************************************************************** */
110 /*                                                                  */
111 /*      Completion matching, from readline's point of view.         */
112 /*                                                                  */
113 /* **************************************************************** */
114
115 /* Pointer to the generator function for completion_matches ().
116    NULL means to use filename_entry_function (), the default filename
117    completer. */
118 Function *rl_completion_entry_function = (Function *)NULL;
119
120 /* Pointer to alternative function to create matches.
121    Function is called with TEXT, START, and END.
122    START and END are indices in RL_LINE_BUFFER saying what the boundaries
123    of TEXT are.
124    If this function exists and returns NULL then call the value of
125    rl_completion_entry_function to try to match, otherwise use the
126    array of strings returned. */
127 CPPFunction *rl_attempted_completion_function = (CPPFunction *)NULL;
128
129 /* Local variable states what happened during the last completion attempt. */
130 static int completion_changed_buffer = 0;
131
132 /* Complete the word at or before point.  You have supplied the function
133    that does the initial simple matching selection algorithm (see
134    completion_matches ()).  The default is to do filename completion. */
135
136 rl_complete (ignore, invoking_key)
137      int ignore, invoking_key;
138 {
139   if (rl_last_func == rl_complete && !completion_changed_buffer)
140     rl_complete_internal ('?');
141   else
142     rl_complete_internal (TAB);
143 }
144
145 /* List the possible completions.  See description of rl_complete (). */
146 rl_possible_completions (ignore, invoking_key)
147      int ignore, invoking_key;
148 {
149   rl_complete_internal ('?');
150 }
151
152 rl_insert_completions (ignore, invoking_key)
153      int ignore, invoking_key;
154 {
155   rl_complete_internal ('*');
156 }
157
158 /* The user must press "y" or "n". Non-zero return means "y" pressed. */
159 get_y_or_n ()
160 {
161   int c;
162
163   for (;;)
164     {
165       c = rl_read_key ();
166       if (c == 'y' || c == 'Y')
167         return (1);
168       if (c == 'n' || c == 'N')
169         return (0);
170       if (c == ABORT_CHAR)
171         rl_abort ();
172       ding ();
173     }
174 }
175
176 /* Up to this many items will be displayed in response to a
177    possible-completions call.  After that, we ask the user if
178    she is sure she wants to see them all. */
179 int rl_completion_query_items = 100;
180
181 /* The basic list of characters that signal a break between words for the
182    completer routine.  The contents of this variable is what breaks words
183    in the shell, i.e. " \t\n\"\\'`@$><=" */
184 char *rl_basic_word_break_characters = " \t\n\"\\'`@$><=;|&{(";
185
186 /* The list of characters that signal a break between words for
187    rl_complete_internal.  The default list is the contents of
188    rl_basic_word_break_characters.  */
189 char *rl_completer_word_break_characters = (char *)NULL;
190
191 /* List of characters which can be used to quote a substring of the line.
192    Completion occurs on the entire substring, and within the substring
193    rl_completer_word_break_characters are treated as any other character,
194    unless they also appear within this list. */
195 char *rl_completer_quote_characters = (char *)NULL;
196
197 /* List of characters that are word break characters, but should be left
198    in TEXT when it is passed to the completion function.  The shell uses
199    this to help determine what kind of completing to do. */
200 char *rl_special_prefixes = (char *)NULL;
201
202 /* If non-zero, then disallow duplicates in the matches. */
203 int rl_ignore_completion_duplicates = 1;
204
205 /* Non-zero means that the results of the matches are to be treated
206    as filenames.  This is ALWAYS zero on entry, and can only be changed
207    within a completion entry finder function. */
208 int rl_filename_completion_desired = 0;
209
210 /* This function, if defined, is called by the completer when real
211    filename completion is done, after all the matching names have been
212    generated. It is passed a (char**) known as matches in the code below.
213    It consists of a NULL-terminated array of pointers to potential
214    matching strings.  The 1st element (matches[0]) is the maximal
215    substring that is common to all matches. This function can re-arrange
216    the list of matches as required, but all elements of the array must be
217    free()'d if they are deleted. The main intent of this function is
218    to implement FIGNORE a la SunOS csh. */
219 Function *rl_ignore_some_completions_function = (Function *)NULL;
220
221 #if defined (SHELL)
222 /* A function to strip quotes that are not protected by backquotes.  It
223    allows single quotes to appear within double quotes, and vice versa.
224    It should be smarter.  It's fairly shell-specific, hence the SHELL
225    definition wrapper. */
226 static char *
227 _delete_quotes (text)
228      char *text;
229 {
230   char *ret, *p, *r;
231   int l, quoted;
232
233   l = strlen (text);
234   ret = xmalloc (l + 1);
235   for (quoted = 0, p = text, r = ret; p && *p; p++)
236     {
237       /* Allow backslash-quoted characters to pass through unscathed. */
238       if (*p == '\\')
239         continue;
240       /* Close quote. */
241       if (quoted && *p == quoted)
242         {
243           quoted = 0;
244           continue;
245         }
246       /* Open quote. */
247       if (quoted == 0 && (*p == '\'' || *p == '"'))
248         {
249           quoted = *p;
250           continue;
251         }
252       *r++ = *p;
253     }
254   *r = '\0';
255   return ret;
256 }
257 #endif /* SHELL */
258
259 /* Complete the word at or before point.
260    WHAT_TO_DO says what to do with the completion.
261    `?' means list the possible completions.
262    TAB means do standard completion.
263    `*' means insert all of the possible completions. */
264 rl_complete_internal (what_to_do)
265      int what_to_do;
266 {
267   char **matches;
268   Function *our_func;
269   int start, scan, end, delimiter = 0, pass_next;
270   char *text, *saved_line_buffer;
271   char *replacement;
272   char quote_char = '\0';
273 #if defined (SHELL)
274   int found_quote = 0;
275 #endif
276
277   if (rl_line_buffer)
278     saved_line_buffer = savestring (rl_line_buffer);
279   else
280     saved_line_buffer = (char *)NULL;
281
282   if (rl_completion_entry_function)
283     our_func = rl_completion_entry_function;
284   else
285     our_func = (Function *)filename_completion_function;
286
287   /* Only the completion entry function can change this. */
288   rl_filename_completion_desired = 0;
289
290   /* We now look backwards for the start of a filename/variable word. */
291   end = rl_point;
292
293   if (rl_point)
294     {
295       if (rl_completer_quote_characters)
296         {
297           /* We have a list of characters which can be used in pairs to
298              quote substrings for the completer.  Try to find the start
299              of an unclosed quoted substring. */
300           /* FOUND_QUOTE is set so we know what kind of quotes we found. */
301           for (scan = pass_next = 0; scan < end; scan++)
302             {
303               if (pass_next)
304                 {
305                   pass_next = 0;
306                   continue;
307                 }
308
309               if (rl_line_buffer[scan] == '\\')
310                 {
311                   pass_next = 1;
312                   continue;
313                 }
314
315               if (quote_char != '\0')
316                 {
317                   /* Ignore everything until the matching close quote char. */
318                   if (rl_line_buffer[scan] == quote_char)
319                     {
320                       /* Found matching close.  Abandon this substring. */
321                       quote_char = '\0';
322                       rl_point = end;
323                     }
324                 }
325               else if (strchr (rl_completer_quote_characters, rl_line_buffer[scan]))
326                 {
327                   /* Found start of a quoted substring. */
328                   quote_char = rl_line_buffer[scan];
329                   rl_point = scan + 1;
330 #if defined (SHELL)
331                   if (quote_char == '\'')
332                     found_quote |= 1;
333                   else if (quote_char == '"')
334                     found_quote |= 2;
335 #endif
336                 }
337             }
338         }
339
340       if (rl_point == end)
341         {
342           int quoted = 0;
343           /* We didn't find an unclosed quoted substring up which to do
344              completion, so use the word break characters to find the
345              substring on which to complete. */
346           while (--rl_point)
347             {
348 #if defined (SHELL)
349               /* Don't let word break characters in quoted substrings break
350                  words for the completer. */
351               if (found_quote)
352                 {
353                   if (strchr (rl_completer_quote_characters, rl_line_buffer[rl_point]))
354                     {
355                       quoted = !quoted;
356                       continue;
357                     }
358                   if (quoted)
359                     continue;
360                 }
361 #endif /* SHELL */
362               if (strchr (rl_completer_word_break_characters, rl_line_buffer[rl_point]))
363                 break;
364             }
365         }
366
367       /* If we are at a word break, then advance past it. */
368       if (strchr (rl_completer_word_break_characters, rl_line_buffer[rl_point]))
369         {
370           /* If the character that caused the word break was a quoting
371              character, then remember it as the delimiter. */
372           if (strchr ("\"'", rl_line_buffer[rl_point]) && (end - rl_point) > 1)
373             delimiter = rl_line_buffer[rl_point];
374
375           /* If the character isn't needed to determine something special
376              about what kind of completion to perform, then advance past it. */
377           if (!rl_special_prefixes ||
378               !strchr (rl_special_prefixes, rl_line_buffer[rl_point]))
379             rl_point++;
380         }
381     }
382
383   /* At this point, we know we have an open quote if quote_char != '\0'. */
384   start = rl_point;
385   rl_point = end;
386   text = rl_copy_text (start, end);
387
388   /* If the user wants to TRY to complete, but then wants to give
389      up and use the default completion function, they set the
390      variable rl_attempted_completion_function. */
391   if (rl_attempted_completion_function)
392     {
393       matches = (*rl_attempted_completion_function) (text, start, end);
394
395       if (matches)
396         {
397           /* XXX - This is questionable code. - XXX */
398           if (matches == (char **)-1)
399             matches = (char **)NULL;
400           our_func = (Function *)NULL;
401           goto after_usual_completion;
402         }
403     }
404
405 #if defined (SHELL)
406   /* Beware -- we're stripping the quotes here.  Do this only if we know
407      we are doing filename completion. */
408   if (found_quote && our_func == (Function *)filename_completion_function)
409     {
410       /* delete single and double quotes */
411       replacement = _delete_quotes (text);
412       free (text);
413       text = replacement;
414       replacement = (char *)0;
415     }
416 #endif /* SHELL */
417
418   matches = completion_matches (text, our_func);
419
420  after_usual_completion:
421   free (text);
422
423   if (!matches)
424     ding ();
425   else
426     {
427       register int i;
428
429       /* It seems to me that in all the cases we handle we would like
430          to ignore duplicate possiblilities.  Scan for the text to
431          insert being identical to the other completions. */
432       if (rl_ignore_completion_duplicates)
433         {
434           char *lowest_common;
435           int j, newlen = 0;
436           char dead_slot;
437
438           /* Sort the items. */
439           /* It is safe to sort this array, because the lowest common
440              denominator found in matches[0] will remain in place. */
441           for (i = 0; matches[i]; i++);
442           qsort (matches, i, sizeof (char *), compare_strings);
443
444           /* Remember the lowest common denominator for it may be unique. */
445           lowest_common = savestring (matches[0]);
446
447           for (i = 0; matches[i + 1]; i++)
448             {
449               if (strcmp (matches[i], matches[i + 1]) == 0)
450                 {
451                   free (matches[i]);
452                   matches[i] = (char *)&dead_slot;
453                 }
454               else
455                 newlen++;
456             }
457
458           /* We have marked all the dead slots with (char *)&dead_slot.
459              Copy all the non-dead entries into a new array. */
460           {
461             char **temp_array =
462               (char **)xmalloc ((3 + newlen) * sizeof (char *));
463
464             for (i = 1, j = 1; matches[i]; i++)
465               {
466                 if (matches[i] != (char *)&dead_slot)
467                   temp_array[j++] = matches[i];
468               }
469
470             temp_array[j] = (char *)NULL;
471
472             if (matches[0] != (char *)&dead_slot)
473               free (matches[0]);
474
475             free (matches);
476
477             matches = temp_array;
478           }
479
480           /* Place the lowest common denominator back in [0]. */
481           matches[0] = lowest_common;
482
483           /* If there is one string left, and it is identical to the
484              lowest common denominator, then the LCD is the string to
485              insert. */
486           if (j == 2 && strcmp (matches[0], matches[1]) == 0)
487             {
488               free (matches[1]);
489               matches[1] = (char *)NULL;
490             }
491         }
492
493       switch (what_to_do)
494         {
495         case TAB:
496           /* If we are matching filenames, then here is our chance to
497              do clever processing by re-examining the list.  Call the
498              ignore function with the array as a parameter.  It can
499              munge the array, deleting matches as it desires. */
500           if (rl_ignore_some_completions_function &&
501               our_func == (Function *)filename_completion_function)
502             (void)(*rl_ignore_some_completions_function)(matches);
503
504           /* If we are doing completion on quoted substrings, and any matches
505              contain any of the completer_word_break_characters, then auto-
506              matically prepend the substring with a quote character (just pick
507              the first one from the list of such) if it does not already begin
508              with a quote string.  FIXME: Need to remove any such automatically
509              inserted quote character when it no longer is necessary, such as
510              if we change the string we are completing on and the new set of
511              matches don't require a quoted substring. */
512           replacement = matches[0];
513
514           if (matches[0] && rl_completer_quote_characters && !quote_char &&
515               rl_filename_completion_desired)
516             {
517               int do_replace;
518
519               do_replace = NO_MATCH;
520
521               /* If there is a single match, see if we need to quote it.
522                  This also checks whether the common prefix of several
523                  matches needs to be quoted.  If the common prefix should
524                  not be checked, add !matches[1] to the if clause. */
525               if (rl_strpbrk (matches[0], rl_completer_word_break_characters))
526                 do_replace = matches[1] ? MULT_MATCH : SINGLE_MATCH;
527
528               if (do_replace != NO_MATCH)
529                 {
530 #if defined (SHELL)
531                   /* XXX - experimental */
532                   /* Quote the replacement, since we found an
533                      embedded word break character in a potential
534                      match. */
535                   char *rtext, *mtext;
536                   int rlen;
537                   extern char *double_quote (); /* in builtins/common.c */
538
539                   /* If DO_REPLACE == MULT_MATCH, it means that there is
540                      more than one match.  In this case, we do not add
541                      the closing quote or attempt to perform tilde
542                      expansion.  If DO_REPLACE == SINGLE_MATCH, we try
543                      to perform tilde expansion, because double quotes
544                      inhibit tilde expansion by the shell. */
545
546                   mtext = matches[0];
547                   if (mtext[0] == '~' && do_replace == SINGLE_MATCH)
548                     mtext = tilde_expand (matches[0]);
549                   rtext = double_quote (mtext);
550                   if (mtext != matches[0])
551                     free (mtext);
552
553                   rlen = strlen (rtext);
554                   replacement = (char *)alloca (rlen + 1);
555                   strcpy (replacement, rtext);
556                   if (do_replace == MULT_MATCH)
557                     replacement[rlen - 1] = '\0';
558                   free (rtext);
559 #else /* !SHELL */
560                   /* Found an embedded word break character in a potential
561                      match, so we need to prepend a quote character if we
562                      are replacing the completion string. */
563                   replacement = (char *)alloca (strlen (matches[0]) + 2);
564                   quote_char = *rl_completer_quote_characters;
565                   *replacement = quote_char;
566                   strcpy (replacement + 1, matches[0]);
567 #endif /* SHELL */
568                 }
569             }
570
571           if (replacement)
572             {
573               rl_delete_text (start, rl_point);
574               rl_point = start;
575               rl_insert_text (replacement);
576             }
577
578           /* If there are more matches, ring the bell to indicate.
579              If this was the only match, and we are hacking files,
580              check the file to see if it was a directory.  If so,
581              add a '/' to the name.  If not, and we are at the end
582              of the line, then add a space. */
583           if (matches[1])
584             {
585               if (rl_editing_mode != vi_mode)
586                 ding ();        /* There are other matches remaining. */
587             }
588           else
589             {
590               char temp_string[4];
591               int temp_string_index = 0;
592
593               if (quote_char)
594                 temp_string[temp_string_index++] = quote_char;
595
596               temp_string[temp_string_index++] = delimiter ? delimiter : ' ';
597               temp_string[temp_string_index++] = '\0';
598
599               if (rl_filename_completion_desired)
600                 {
601                   struct stat finfo;
602                   char *filename = tilde_expand (matches[0]);
603
604                   if ((stat (filename, &finfo) == 0) &&
605                       S_ISDIR (finfo.st_mode))
606                     {
607                       if (rl_line_buffer[rl_point] != '/')
608                         rl_insert_text ("/");
609                     }
610                   else
611                     {
612                       if (rl_point == rl_end)
613                         rl_insert_text (temp_string);
614                     }
615                   free (filename);
616                 }
617               else
618                 {
619                   if (rl_point == rl_end)
620                     rl_insert_text (temp_string);
621                 }
622             }
623           break;
624
625         case '*':
626           {
627             int i = 1;
628
629             rl_delete_text (start, rl_point);
630             rl_point = start;
631             rl_begin_undo_group ();
632             if (matches[1])
633               {
634                 while (matches[i])
635                   {
636                     rl_insert_text (matches[i++]);
637                     rl_insert_text (" ");
638                   }
639               }
640             else
641               {
642                 rl_insert_text (matches[0]);
643                 rl_insert_text (" ");
644               }
645             rl_end_undo_group ();
646           }
647           break;
648
649         case '?':
650           {
651             int len, count, limit, max = 0;
652             int j, k, l;
653
654             /* Handle simple case first.  What if there is only one answer? */
655             if (!matches[1])
656               {
657                 char *temp = (char *)NULL;
658
659                 if (rl_filename_completion_desired)
660                   temp = strrchr (matches[0], '/');
661
662                 if (!temp)
663                   temp = matches[0];
664                 else
665                   temp++;
666
667                 crlf ();
668                 fprintf (rl_outstream, "%s", temp);
669 #if defined (VISIBLE_STATS)
670                 if (rl_filename_completion_desired && rl_visible_stats)
671                   {
672                     int extension_char;
673
674                     extension_char = stat_char (matches[0]);
675                     if (extension_char)
676                       putc (extension_char, rl_outstream);
677                   }
678 #endif /* VISIBLE_STATS */
679                 crlf ();
680                 goto restart;
681               }
682
683             /* There is more than one answer.  Find out how many there are,
684                and find out what the maximum printed length of a single entry
685                is. */
686             for (i = 1; matches[i]; i++)
687               {
688                 char *temp;
689                 int name_length;
690
691                 /* If we are hacking filenames, then only count the characters
692                    after the last slash in the pathname. */
693                 if (rl_filename_completion_desired)
694                   temp = strrchr (matches[i], '/');
695                 else
696                   temp = (char *)NULL;
697
698                 if (!temp)
699                   temp = matches[i];
700                 else
701                   temp++;
702
703                 name_length = strlen (temp);
704
705                 if (name_length > max)
706                   max = name_length;
707               }
708
709             len = i - 1;
710
711             /* If there are many items, then ask the user if she
712                really wants to see them all. */
713             if (len >= rl_completion_query_items)
714               {
715                 crlf ();
716                 fprintf (rl_outstream,
717                          "There are %d possibilities.  Do you really", len);
718                 crlf ();
719                 fprintf (rl_outstream, "wish to see them all? (y or n)");
720                 fflush (rl_outstream);
721                 if (!get_y_or_n ())
722                   {
723                     crlf ();
724                     goto restart;
725                   }
726               }
727
728             /* How many items of MAX length can we fit in the screen window? */
729             max += 2;
730             limit = screenwidth / max;
731             if (limit != 1 && (limit * max == screenwidth))
732               limit--;
733
734             /* Avoid a possible floating exception.  If max > screenwidth,
735                limit will be 0 and a divide-by-zero fault will result. */
736             if (limit == 0)
737               limit = 1;
738
739             /* How many iterations of the printing loop? */
740             count = (len + (limit - 1)) / limit;
741
742             /* Watch out for special case.  If LEN is less than LIMIT, then
743                just do the inner printing loop. */
744             if (len < limit)
745               count = 1;
746
747             /* Sort the items if they are not already sorted. */
748             if (!rl_ignore_completion_duplicates)
749               qsort (matches, len, sizeof (char *), compare_strings);
750
751             /* Print the sorted items, up-and-down alphabetically, like
752                ls might. */
753             crlf ();
754
755             for (i = 1; i < count + 1; i++)
756               {
757                 for (j = 0, l = i; j < limit; j++)
758                   {
759                     if (l > len || !matches[l])
760                       {
761                         break;
762                       }
763                     else
764                       {
765                         char *temp = (char *)NULL;
766                         int printed_length;
767
768                         if (rl_filename_completion_desired)
769                           temp = strrchr (matches[l], '/');
770
771                         if (!temp)
772                           temp = matches[l];
773                         else
774                           temp++;
775
776                         printed_length = strlen (temp);
777                         fprintf (rl_outstream, "%s", temp);
778
779 #if defined (VISIBLE_STATS)
780                         if (rl_filename_completion_desired &&
781                             rl_visible_stats)
782                           {
783                             int extension_char;
784
785                             extension_char = stat_char (matches[l]);
786
787                             if (extension_char)
788                               {
789                                 putc (extension_char, rl_outstream);
790                                 printed_length++;
791                               }
792                           }
793 #endif /* VISIBLE_STATS */
794
795                         if (j + 1 < limit)
796                           {
797                             for (k = 0; k < max - printed_length; k++)
798                               putc (' ', rl_outstream);
799                           }
800                       }
801                     l += count;
802                   }
803                 crlf ();
804               }
805           restart:
806
807             rl_on_new_line ();
808           }
809           break;
810
811         default:
812           fprintf (stderr, "\r\nreadline: bad value for what_to_do in rl_complete\n");
813           abort ();
814         }
815
816       for (i = 0; matches[i]; i++)
817         free (matches[i]);
818       free (matches);
819     }
820
821   /* Check to see if the line has changed through all of this manipulation. */
822   if (saved_line_buffer)
823     {
824       if (strcmp (rl_line_buffer, saved_line_buffer) != 0)
825         completion_changed_buffer = 1;
826       else
827         completion_changed_buffer = 0;
828
829       free (saved_line_buffer);
830     }
831 }
832
833 #if defined (VISIBLE_STATS)
834 /* Return the character which best describes FILENAME.
835      `@' for symbolic links
836      `/' for directories
837      `*' for executables
838      `=' for sockets */
839 static int
840 stat_char (filename)
841      char *filename;
842 {
843   struct stat finfo;
844   int character = 0;
845
846   if (stat (filename, &finfo) == -1)
847     return (character);
848
849   if (S_ISDIR (finfo.st_mode))
850     character = '/';
851 #if defined (S_ISLNK)
852   else if (S_ISLNK (finfo.st_mode))
853     character = '@';
854 #endif /* S_ISLNK */
855 #if defined (S_ISSOCK)
856   else if (S_ISSOCK (finfo.st_mode))
857     character = '=';
858 #endif /* S_ISSOCK */
859   else if (S_ISREG (finfo.st_mode))
860     {
861       if (access (filename, X_OK) == 0)
862         character = '*';
863     }
864   return (character);
865 }
866 #endif /* VISIBLE_STATS */
867
868 /* Stupid comparison routine for qsort () ing strings. */
869 static int
870 compare_strings (s1, s2)
871   char **s1, **s2;
872 {
873   return (strcmp (*s1, *s2));
874 }
875
876 /* A completion function for usernames.
877    TEXT contains a partial username preceded by a random
878    character (usually `~').  */
879 char *
880 username_completion_function (text, state)
881      int state;
882      char *text;
883 {
884 #if defined (MINIMAL)
885   return (char *)NULL;
886 #else /* !MINIMAL */
887   static char *username = (char *)NULL;
888   static struct passwd *entry;
889   static int namelen, first_char, first_char_loc;
890
891   if (!state)
892     {
893       if (username)
894         free (username);
895
896       first_char = *text;
897
898       if (first_char == '~')
899         first_char_loc = 1;
900       else
901         first_char_loc = 0;
902
903       username = savestring (&text[first_char_loc]);
904       namelen = strlen (username);
905       setpwent ();
906     }
907
908   while (entry = getpwent ())
909     {
910       if (strncmp (username, entry->pw_name, namelen) == 0)
911         break;
912     }
913
914   if (!entry)
915     {
916       endpwent ();
917       return ((char *)NULL);
918     }
919   else
920     {
921       char *value = (char *)xmalloc (2 + strlen (entry->pw_name));
922
923       *value = *text;
924
925       strcpy (value + first_char_loc, entry->pw_name);
926
927       if (first_char == '~')
928         rl_filename_completion_desired = 1;
929
930       return (value);
931     }
932 #endif /* !MINIMAL */
933 }
934 \f
935 /* **************************************************************** */
936 /*                                                                  */
937 /*                           Completion                             */
938 /*                                                                  */
939 /* **************************************************************** */
940
941 /* Non-zero means that case is not significant in completion. */
942 int completion_case_fold = 0;
943
944 /* Return an array of (char *) which is a list of completions for TEXT.
945    If there are no completions, return a NULL pointer.
946    The first entry in the returned array is the substitution for TEXT.
947    The remaining entries are the possible completions.
948    The array is terminated with a NULL pointer.
949
950    ENTRY_FUNCTION is a function of two args, and returns a (char *).
951      The first argument is TEXT.
952      The second is a state argument; it should be zero on the first call, and
953      non-zero on subsequent calls.  It returns a NULL pointer to the caller
954      when there are no more matches.
955  */
956 char **
957 completion_matches (text, entry_function)
958      char *text;
959      CPFunction *entry_function;
960 {
961   /* Number of slots in match_list. */
962   int match_list_size;
963
964   /* The list of matches. */
965   char **match_list =
966     (char **)xmalloc (((match_list_size = 10) + 1) * sizeof (char *));
967
968   /* Number of matches actually found. */
969   int matches = 0;
970
971   /* Temporary string binder. */
972   char *string;
973
974   match_list[1] = (char *)NULL;
975
976   while (string = (*entry_function) (text, matches))
977     {
978       if (matches + 1 == match_list_size)
979         match_list = (char **)xrealloc
980           (match_list, ((match_list_size += 10) + 1) * sizeof (char *));
981
982       match_list[++matches] = string;
983       match_list[matches + 1] = (char *)NULL;
984     }
985
986   /* If there were any matches, then look through them finding out the
987      lowest common denominator.  That then becomes match_list[0]. */
988   if (matches)
989     {
990       register int i = 1;
991       int low = 100000;         /* Count of max-matched characters. */
992
993       /* If only one match, just use that. */
994       if (matches == 1)
995         {
996           match_list[0] = match_list[1];
997           match_list[1] = (char *)NULL;
998         }
999       else
1000         {
1001           /* Otherwise, compare each member of the list with
1002              the next, finding out where they stop matching. */
1003
1004           while (i < matches)
1005             {
1006               register int c1, c2, si;
1007
1008               if (completion_case_fold)
1009                 {
1010                   for (si = 0;
1011                        (c1 = to_lower(match_list[i][si])) &&
1012                        (c2 = to_lower(match_list[i + 1][si]));
1013                        si++)
1014                     if (c1 != c2) break;
1015                 }
1016               else
1017                 {
1018                   for (si = 0;
1019                        (c1 = match_list[i][si]) &&
1020                        (c2 = match_list[i + 1][si]);
1021                        si++)
1022                     if (c1 != c2) break;
1023                 }
1024
1025               if (low > si) low = si;
1026               i++;
1027             }
1028           match_list[0] = (char *)xmalloc (low + 1);
1029           strncpy (match_list[0], match_list[1], low);
1030           match_list[0][low] = '\0';
1031         }
1032     }
1033   else                          /* There were no matches. */
1034     {
1035       free (match_list);
1036       match_list = (char **)NULL;
1037     }
1038   return (match_list);
1039 }
1040
1041 /* Okay, now we write the entry_function for filename completion.  In the
1042    general case.  Note that completion in the shell is a little different
1043    because of all the pathnames that must be followed when looking up the
1044    completion for a command. */
1045 char *
1046 filename_completion_function (text, state)
1047      int state;
1048      char *text;
1049 {
1050 #ifndef WIN32
1051   static DIR *directory;
1052   static char *filename = (char *)NULL;
1053   static char *dirname = (char *)NULL;
1054   static char *users_dirname = (char *)NULL;
1055   static int filename_len;
1056
1057   dirent *entry = (dirent *)NULL;
1058
1059   /* If we don't have any state, then do some initialization. */
1060   if (!state)
1061     {
1062       char *temp;
1063
1064       if (dirname) free (dirname);
1065       if (filename) free (filename);
1066       if (users_dirname) free (users_dirname);
1067
1068       filename = savestring (text);
1069       if (!*text) text = ".";
1070       dirname = savestring (text);
1071
1072       temp = strrchr (dirname, '/');
1073
1074       if (temp)
1075         {
1076           strcpy (filename, ++temp);
1077           *temp = '\0';
1078         }
1079       else
1080         strcpy (dirname, ".");
1081
1082       /* We aren't done yet.  We also support the "~user" syntax. */
1083
1084       /* Save the version of the directory that the user typed. */
1085       users_dirname = savestring (dirname);
1086       {
1087         char *temp_dirname;
1088
1089         temp_dirname = tilde_expand (dirname);
1090         free (dirname);
1091         dirname = temp_dirname;
1092
1093         if (rl_symbolic_link_hook)
1094           (*rl_symbolic_link_hook) (&dirname);
1095       }
1096       directory = opendir (dirname);
1097       filename_len = strlen (filename);
1098
1099       rl_filename_completion_desired = 1;
1100     }
1101
1102   /* At this point we should entertain the possibility of hacking wildcarded
1103      filenames, like /usr/man/man<WILD>/te<TAB>.  If the directory name
1104      contains globbing characters, then build an array of directories, and
1105      then map over that list while completing. */
1106   /* *** UNIMPLEMENTED *** */
1107
1108   /* Now that we have some state, we can read the directory. */
1109
1110   while (directory && (entry = readdir (directory)))
1111     {
1112       /* Special case for no filename.
1113          All entries except "." and ".." match. */
1114       if (!filename_len)
1115         {
1116           if ((strcmp (entry->d_name, ".") != 0) &&
1117               (strcmp (entry->d_name, "..") != 0))
1118             break;
1119         }
1120       else
1121         {
1122           /* Otherwise, if these match upto the length of filename, then
1123              it is a match. */
1124             if (((int)D_NAMLEN (entry)) >= filename_len &&
1125                 (entry->d_name[0] == filename[0]) &&
1126                 (strncmp (filename, entry->d_name, filename_len) == 0))
1127               {
1128                 break;
1129               }
1130         }
1131     }
1132
1133   if (!entry)
1134     {
1135       if (directory)
1136         {
1137           closedir (directory);
1138           directory = (DIR *)NULL;
1139         }
1140
1141       if (dirname)
1142         {
1143           free (dirname);
1144           dirname = (char *)NULL;
1145         }
1146       if (filename)
1147         {
1148           free (filename);
1149           filename = (char *)NULL;
1150         }
1151       if (users_dirname)
1152         {
1153           free (users_dirname);
1154           users_dirname = (char *)NULL;
1155         }
1156
1157       return (char *)NULL;
1158     }
1159   else
1160     {
1161       char *temp;
1162
1163       if (dirname && (strcmp (dirname, ".") != 0))
1164         {
1165           if (rl_complete_with_tilde_expansion && *users_dirname == '~')
1166             {
1167               int dirlen = strlen (dirname);
1168               temp = (char *)xmalloc (2 + dirlen + D_NAMLEN (entry));
1169               strcpy (temp, dirname);
1170               /* Canonicalization cuts off any final slash present.  We need
1171                  to add it back. */
1172               if (dirname[dirlen - 1] != '/')
1173                 {
1174                   temp[dirlen] = '/';
1175                   temp[dirlen + 1] = '\0';
1176                 }
1177             }
1178           else
1179             {
1180               temp = (char *)
1181                 xmalloc (1 + strlen (users_dirname) + D_NAMLEN (entry));
1182               strcpy (temp, users_dirname);
1183             }
1184
1185           strcat (temp, entry->d_name);
1186         }
1187       else
1188         {
1189           temp = (savestring (entry->d_name));
1190         }
1191       return (temp);
1192     }
1193 #endif
1194 }
1195
1196 /* A function for simple tilde expansion. */
1197 int
1198 rl_tilde_expand (ignore, key)
1199      int ignore, key;
1200 {
1201   register int start, end;
1202   char *homedir;
1203
1204   end = rl_point;
1205   start = end - 1;
1206
1207   if (rl_point == rl_end && rl_line_buffer[rl_point] == '~')
1208     {
1209       homedir = tilde_expand ("~");
1210       goto insert;
1211     }
1212   else if (rl_line_buffer[start] != '~')
1213     {
1214       for (; !whitespace (rl_line_buffer[start]) && start >= 0; start--);
1215       start++;
1216     }
1217
1218   end = start;
1219   do
1220     {
1221       end++;
1222     }
1223   while (!whitespace (rl_line_buffer[end]) && end < rl_end);
1224
1225   if (whitespace (rl_line_buffer[end]) || end >= rl_end)
1226     end--;
1227
1228   /* If the first character of the current word is a tilde, perform
1229      tilde expansion and insert the result.  If not a tilde, do
1230      nothing. */
1231   if (rl_line_buffer[start] == '~')
1232     {
1233       char *temp;
1234       int len;
1235
1236       len = end - start + 1;
1237       temp = (char *)alloca (len + 1);
1238       strncpy (temp, rl_line_buffer + start, len);
1239       temp[len] = '\0';
1240       homedir = tilde_expand (temp);
1241
1242     insert:
1243       rl_begin_undo_group ();
1244       rl_delete_text (start, end + 1);
1245       rl_point = start;
1246       rl_insert_text (homedir);
1247       rl_end_undo_group ();
1248     }
1249
1250   return (0);
1251 }
1252
1253 /* Find the first occurrence in STRING1 of any character from STRING2.
1254    Return a pointer to the character in STRING1. */
1255 static char *
1256 rl_strpbrk (string1, string2)
1257      char *string1, *string2;
1258 {
1259   register char *scan;
1260
1261   for (; *string1; string1++)
1262     {
1263       for (scan = string2; *scan; scan++)
1264         {
1265           if (*string1 == *scan)
1266             {
1267               return (string1);
1268             }
1269         }
1270     }
1271   return ((char *)NULL);
1272 }
1273
1274 #if defined (STATIC_MALLOC)
1275 \f
1276 /* **************************************************************** */
1277 /*                                                                  */
1278 /*                      xmalloc and xrealloc ()                     */
1279 /*                                                                  */
1280 /* **************************************************************** */
1281
1282 static void memory_error_and_abort ();
1283
1284 static char *
1285 xmalloc (bytes)
1286      int bytes;
1287 {
1288   char *temp = (char *)malloc (bytes);
1289
1290   if (!temp)
1291     memory_error_and_abort ();
1292   return (temp);
1293 }
1294
1295 static char *
1296 xrealloc (pointer, bytes)
1297      char *pointer;
1298      int bytes;
1299 {
1300   char *temp;
1301
1302   if (!pointer)
1303     temp = (char *)malloc (bytes);
1304   else
1305     temp = (char *)realloc (pointer, bytes);
1306
1307   if (!temp)
1308     memory_error_and_abort ();
1309
1310   return (temp);
1311 }
1312
1313 static void
1314 memory_error_and_abort ()
1315 {
1316   fprintf (stderr, "readline: Out of virtual memory!\n");
1317   abort ();
1318 }
1319 #endif /* STATIC_MALLOC */