2 /* complete.c -- filename completion for readline. */
4 /* Copyright (C) 1987, 1989, 1992 Free Software Foundation, Inc.
6 This file is part of the GNU Readline Library, a library for
7 reading lines of text with interactive input and history editing.
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.
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.
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
25 #if defined (HAVE_CONFIG_H)
29 #include <sys/types.h>
31 #if defined (HAVE_SYS_FILE_H)
35 #if defined (HAVE_UNISTD_H)
37 #endif /* HAVE_UNISTD_H */
39 #if defined (HAVE_STDLIB_H)
42 # include "ansi_stdlib.h"
43 #endif /* HAVE_STDLIB_H */
55 #include "posixstat.h"
57 /* System-specific feature definitions and include files. */
60 /* Some standard library routines. */
63 #include "rlprivate.h"
66 typedef int QSFUNC (const void *, const void *);
68 typedef int QSFUNC ();
71 /* Most systems don't declare getpwent in <pwd.h> if _POSIX_SOURCE is
73 #if !defined (HAVE_GETPW_DECLS) || defined (_POSIX_SOURCE)
74 extern struct passwd *getpwent __P((void));
75 #endif /* !HAVE_GETPW_DECLS || _POSIX_SOURCE */
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. */
84 rl_compdisp_func_t *rl_completion_display_matches_hook = (rl_compdisp_func_t *)NULL;
86 #if defined (VISIBLE_STATS)
90 static int stat_char __P((char *));
93 static char *rl_quote_filename __P((char *, int, char *));
95 static char **remove_duplicate_matches __P((char **));
96 static void insert_match __P((char *, int, int, char *));
97 static int append_to_match __P((char *, int, int));
98 static void insert_all_matches __P((char **, int, char *));
99 static void display_matches __P((char **));
100 static int compute_lcd_of_matches __P((char **, int, const char *));
102 /* **************************************************************** */
104 /* Completion matching, from readline's point of view. */
106 /* **************************************************************** */
108 /* Variables known only to the readline library. */
110 /* If non-zero, non-unique completions always show the list of matches. */
111 int _rl_complete_show_all = 0;
113 /* If non-zero, completed directory names have a slash appended. */
114 int _rl_complete_mark_directories = 1;
116 /* If non-zero, completions are printed horizontally in alphabetical order,
118 int _rl_print_completions_horizontally;
120 /* Non-zero means that case is not significant in filename completion. */
121 #if defined (__MSDOS__) && !defined (__DJGPP__)
122 int _rl_completion_case_fold = 1;
124 int _rl_completion_case_fold;
127 /* Global variables available to applications using readline. */
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. */
133 int rl_visible_stats = 0;
134 #endif /* VISIBLE_STATS */
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. */
139 rl_icppfunc_t *rl_directory_completion_hook = (rl_icppfunc_t *)NULL;
141 rl_icppfunc_t *rl_directory_rewrite_hook = (rl_icppfunc_t *)NULL;
143 /* Non-zero means readline completion functions perform tilde expansion. */
144 int rl_complete_with_tilde_expansion = 0;
146 /* Pointer to the generator function for completion_matches ().
147 NULL means to use rl_filename_completion_function (), the default filename
149 rl_compentry_func_t *rl_completion_entry_function = (rl_compentry_func_t *)NULL;
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
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. */
158 rl_completion_func_t *rl_attempted_completion_function = (rl_completion_func_t *)NULL;
160 /* Non-zero means to suppress normal filename completion after the
161 user-specified completion function has been called. */
162 int rl_attempted_completion_over = 0;
164 /* Set to a character indicating the type of completion being performed
165 by rl_complete_internal, available for use by application completion
167 int rl_completion_type = 0;
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. */
172 int rl_completion_query_items = 100;
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\"\\'`@$><=" */
177 const char *rl_basic_word_break_characters = " \t\n\"\\'`@$><=;|&{(";
179 /* List of basic quoting characters. */
180 const char *rl_basic_quote_characters = "\"'";
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. */
185 const char *rl_completer_word_break_characters = (const char *)NULL;
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. */
191 const char *rl_completer_quote_characters = (const char *)NULL;
193 /* List of characters that should be quoted in filenames by the completer. */
194 const char *rl_filename_quote_characters = (const char *)NULL;
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. */
199 const char *rl_special_prefixes = (const char *)NULL;
201 /* If non-zero, then disallow duplicates in the matches. */
202 int rl_ignore_completion_duplicates = 1;
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. */
207 int rl_filename_completion_desired = 0;
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. */
214 int rl_filename_quoting_desired = 1;
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. */
225 rl_compignore_func_t *rl_ignore_some_completions_function = (rl_compignore_func_t *)NULL;
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
231 rl_quote_func_t *rl_filename_quoting_function = rl_quote_filename;
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. */
237 rl_dequote_func_t *rl_filename_dequoting_function = (rl_dequote_func_t *)NULL;
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
242 rl_linebuf_func_t *rl_char_is_quoted_p = (rl_linebuf_func_t *)NULL;
244 /* Character appended to completed words when at the end of the line. The
245 default is a space. */
246 int rl_completion_append_character = ' ';
248 /* If non-zero, inhibit completion (temporarily). */
249 int rl_inhibit_completion;
251 /* Variables local to this file. */
253 /* Local variable states what happened during the last completion attempt. */
254 static int completion_changed_buffer;
256 /*************************************/
258 /* Bindable completion functions */
260 /*************************************/
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. */
266 rl_complete (ignore, invoking_key)
267 int ignore, invoking_key;
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 ('!'));
276 return (rl_complete_internal (TAB));
279 /* List the possible completions. See description of rl_complete (). */
281 rl_possible_completions (ignore, invoking_key)
282 int ignore, invoking_key;
284 return (rl_complete_internal ('?'));
288 rl_insert_completions (ignore, invoking_key)
289 int ignore, invoking_key;
291 return (rl_complete_internal ('*'));
294 /************************************/
296 /* Completion utility functions */
298 /************************************/
300 /* The user must press "y" or "n". Non-zero return means "y" pressed. */
308 RL_SETSTATE(RL_STATE_MOREINPUT);
310 RL_UNSETSTATE(RL_STATE_MOREINPUT);
312 if (c == 'y' || c == 'Y' || c == ' ')
314 if (c == 'n' || c == 'N' || c == RUBOUT)
317 _rl_abort_internal ();
322 #if defined (VISIBLE_STATS)
323 /* Return the character which best describes FILENAME.
324 `@' for symbolic links
329 `%' for character special devices
330 `#' for block special devices */
338 #if defined (HAVE_LSTAT) && defined (S_ISLNK)
339 r = lstat (filename, &finfo);
341 r = stat (filename, &finfo);
348 if (S_ISDIR (finfo.st_mode))
350 #if defined (S_ISCHR)
351 else if (S_ISCHR (finfo.st_mode))
354 #if defined (S_ISBLK)
355 else if (S_ISBLK (finfo.st_mode))
358 #if defined (S_ISLNK)
359 else if (S_ISLNK (finfo.st_mode))
362 #if defined (S_ISSOCK)
363 else if (S_ISSOCK (finfo.st_mode))
365 #endif /* S_ISSOCK */
366 #if defined (S_ISFIFO)
367 else if (S_ISFIFO (finfo.st_mode))
370 else if (S_ISREG (finfo.st_mode))
372 if (access (filename, X_OK) == 0)
377 #endif /* VISIBLE_STATS */
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. */
384 printable_part (pathname)
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] == ':')
394 return (temp ? ++temp : pathname);
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. */
405 putc ('^', rl_outstream); \
406 putc (UNCTRL (c), rl_outstream); \
409 else if (c == RUBOUT) \
411 putc ('^', rl_outstream); \
412 putc ('?', rl_outstream); \
417 putc (c, rl_outstream); \
423 print_filename (to_print, full_pathname)
424 char *to_print, *full_pathname;
427 #if !defined (VISIBLE_STATS)
430 for (s = to_print; *s; s++)
435 char *s, c, *new_full_pathname;
436 int extension_char, slen, tlen;
438 for (s = to_print; *s; s++)
443 if (rl_filename_completion_desired && rl_visible_stats)
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)
450 /* Terminate the directory name. */
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);
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);
470 extension_char = stat_char (new_full_pathname);
472 free (new_full_pathname);
477 s = tilde_expand (full_pathname);
478 extension_char = stat_char (s);
484 putc (extension_char, rl_outstream);
488 #endif /* VISIBLE_STATS */
493 rl_quote_filename (s, rtype, qcp)
500 r = xmalloc (strlen (s) + 2);
501 *r = *rl_completer_quote_characters;
504 *qcp = *rl_completer_quote_characters;
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. */
524 find_completion_word (fp, dp)
527 int scan, end, found_quote, delimiter, pass_next, isbrk;
531 found_quote = delimiter = 0;
534 if (rl_completer_quote_characters)
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++)
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
552 if (quote_char != '\'' && rl_line_buffer[scan] == '\\')
555 found_quote |= RL_QF_BACKSLASH;
559 if (quote_char != '\0')
561 /* Ignore everything until the matching close quote char. */
562 if (rl_line_buffer[scan] == quote_char)
564 /* Found matching close. Abandon this substring. */
569 else if (strchr (rl_completer_quote_characters, rl_line_buffer[scan]))
571 /* Found start of a quoted substring. */
572 quote_char = rl_line_buffer[scan];
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;
583 if (rl_point == end && quote_char == '\0')
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. */
590 scan = rl_line_buffer[rl_point];
592 if (strchr (rl_completer_word_break_characters, scan) == 0)
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))
601 /* Convoluted code, but it avoids an n^2 algorithm with calls
602 to char_is_quoted. */
607 /* If we are at an unquoted word break, then advance past it. */
608 scan = rl_line_buffer[rl_point];
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. */
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;
622 isbrk = strchr (rl_completer_word_break_characters, scan) != 0;
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)
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)
649 gen_completion_matches (text, start, end, our_func, found_quote, quote_char)
652 rl_compentry_func_t *our_func;
653 int found_quote, quote_char;
655 char **matches, *temp;
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)
662 matches = (*rl_attempted_completion_function) (text, start, end);
664 if (matches || rl_attempted_completion_over)
666 rl_attempted_completion_over = 0;
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. */
676 if (found_quote && our_func == rl_filename_completion_function &&
677 rl_filename_dequoting_function)
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 */
684 matches = rl_completion_matches (text, our_func);
689 /* Filter out duplicates in MATCHES. This frees up the strings in
692 remove_duplicate_matches (matches)
700 /* Sort the items. */
701 for (i = 0; matches[i]; i++)
704 /* Sort the array without matches[0], since we need it to
705 stay in place no matter what. */
707 qsort (matches+1, i-1, sizeof (char *), (QSFUNC *)_rl_qsort_string_compare);
709 /* Remember the lowest common denominator for it may be unique. */
710 lowest_common = savestring (matches[0]);
712 for (i = newlen = 0; matches[i + 1]; i++)
714 if (strcmp (matches[i], matches[i + 1]) == 0)
717 matches[i] = (char *)&dead_slot;
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++)
728 if (matches[i] != (char *)&dead_slot)
729 temp_array[j++] = matches[i];
731 temp_array[j] = (char *)NULL;
733 if (matches[0] != (char *)&dead_slot)
736 /* Place the lowest common denominator back in [0]. */
737 temp_array[0] = lowest_common;
739 /* If there is one string left, and it is identical to the
740 lowest common denominator, then the LCD is the string to
742 if (j == 2 && strcmp (temp_array[0], temp_array[1]) == 0)
744 free (temp_array[1]);
745 temp_array[1] = (char *)NULL;
750 /* Find the common prefix of the list of matches, and put it into
753 compute_lcd_of_matches (match_list, matches, text)
758 register int i, c1, c2, si;
759 int low; /* Count of max-matched characters. */
761 /* If only one match, just use that. Otherwise, compare each
762 member of the list with the next, finding out where they
766 match_list[0] = match_list[1];
767 match_list[1] = (char *)NULL;
771 for (i = 1, low = 100000; i < matches; i++)
773 if (_rl_completion_case_fold)
776 (c1 = _rl_to_lower(match_list[i][si])) &&
777 (c2 = _rl_to_lower(match_list[i + 1][si]));
785 (c1 = match_list[i][si]) &&
786 (c2 = match_list[i + 1][si]);
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)
801 match_list[0] = xmalloc (strlen (text) + 1);
802 strcpy (match_list[0], text);
806 match_list[0] = xmalloc (low + 1);
807 strncpy (match_list[0], match_list[1], low);
808 match_list[0][low] = '\0';
815 postprocess_matches (matchesp, matching_filenames)
817 int matching_filenames;
819 char *t, **matches, **temp_matches;
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)
829 temp_matches = remove_duplicate_matches (matches);
831 matches = temp_matches;
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)
840 for (nmatch = 1; matches[nmatch]; nmatch++)
842 (void)(*rl_ignore_some_completions_function) (matches);
843 if (matches == 0 || matches[0] == 0)
846 *matchesp = (char **)0;
851 /* If we removed some matches, recompute the common prefix. */
852 for (i = 1; matches[i]; i++)
854 if (i > 1 && i < nmatch)
857 compute_lcd_of_matches (matches, i - 1, t);
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. */
872 rl_display_match_list (matches, len, max)
876 int count, limit, printed_len;
880 /* How many items of MAX length can we fit in the screen window? */
882 limit = _rl_screenwidth / max;
883 if (limit != 1 && (limit * max == _rl_screenwidth))
886 /* Avoid a possible floating exception. If max > _rl_screenwidth,
887 limit will be 0 and a divide-by-zero fault will result. */
891 /* How many iterations of the printing loop? */
892 count = (len + (limit - 1)) / limit;
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. */
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);
904 if (_rl_print_completions_horizontally == 0)
906 /* Print the sorted items, up-and-down alphabetically, like ls. */
907 for (i = 1; i <= count; i++)
909 for (j = 0, l = i; j < limit; j++)
911 if (l > len || matches[l] == 0)
915 temp = printable_part (matches[l]);
916 printed_len = print_filename (temp, matches[l]);
919 for (k = 0; k < max - printed_len; k++)
920 putc (' ', rl_outstream);
929 /* Print the sorted items, across alphabetically, like ls -x. */
930 for (i = 1; matches[i]; i++)
932 temp = printable_part (matches[i]);
933 printed_len = print_filename (temp, matches[i]);
934 /* Have we reached the end of this line? */
937 if (i && (limit > 1) && (i % limit) == 0)
940 for (k = 0; k < max - printed_len; k++)
941 putc (' ', rl_outstream);
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. */
960 display_matches (matches)
966 /* Move to the last visible line of a possibly-multiple-line command. */
967 _rl_move_vert (_rl_vis_botlin);
969 /* Handle simple case first. What if there is only one answer? */
972 temp = printable_part (matches[0]);
974 print_filename (temp, matches[0]);
977 rl_forced_update_display ();
978 rl_display_fixed = 1;
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++)
987 temp = printable_part (matches[i]);
996 /* If the caller has defined a display hook, then call that now. */
997 if (rl_completion_display_matches_hook)
999 (*rl_completion_display_matches_hook) (matches, len, max);
1003 /* If there are many items, then ask the user if she really wants to
1005 if (len >= rl_completion_query_items)
1008 fprintf (rl_outstream, "Display all %d possibilities? (y or n)", len);
1009 fflush (rl_outstream);
1010 if (get_y_or_n () == 0)
1014 rl_forced_update_display ();
1015 rl_display_fixed = 1;
1021 rl_display_match_list (matches, len, max);
1023 rl_forced_update_display ();
1024 rl_display_fixed = 1;
1028 make_quoted_replacement (match, mtype, qc)
1031 char *qc; /* Pointer to quoting character, if any */
1033 int should_quote, do_replace;
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;
1046 should_quote = match && rl_completer_quote_characters &&
1047 rl_filename_completion_desired &&
1048 rl_filename_quoting_desired;
1051 should_quote = should_quote && (!qc || !*qc ||
1052 (rl_completer_quote_characters && strchr (rl_completer_quote_characters, *qc)));
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)
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);
1069 return (replacement);
1073 insert_match (match, start, mtype, qc)
1081 oqc = qc ? *qc : '\0';
1082 replacement = make_quoted_replacement (match, mtype, qc);
1084 /* Now insert the match. */
1087 /* Don't double an opening quote character. */
1088 if (qc && *qc && start && rl_line_buffer[start - 1] == *qc &&
1089 replacement[0] == *qc)
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)
1096 _rl_replace_text (replacement, start, rl_point - 1);
1097 if (replacement != match)
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
1108 append_to_match (text, delimiter, quote_char)
1110 int delimiter, quote_char;
1112 char temp_string[4], *filename;
1113 int temp_string_index;
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;
1121 temp_string[temp_string_index++] = delimiter;
1122 else if (rl_completion_append_character)
1123 temp_string[temp_string_index++] = rl_completion_append_character;
1125 temp_string[temp_string_index++] = '\0';
1127 if (rl_filename_completion_desired)
1129 filename = tilde_expand (text);
1130 if (stat (filename, &finfo) == 0 && S_ISDIR (finfo.st_mode))
1132 if (_rl_complete_mark_directories && rl_line_buffer[rl_point] != '/')
1133 rl_insert_text ("/");
1137 if (rl_point == rl_end)
1138 rl_insert_text (temp_string);
1144 if (rl_point == rl_end)
1145 rl_insert_text (temp_string);
1148 return (temp_string_index);
1152 insert_all_matches (matches, point, qc)
1160 rl_begin_undo_group ();
1161 /* remove any opening quote character; make_quoted_replacement will add
1163 if (qc && *qc && point && rl_line_buffer[point - 1] == *qc)
1165 rl_delete_text (point, rl_point);
1170 for (i = 1; matches[i]; i++)
1172 rp = make_quoted_replacement (matches[i], SINGLE_MATCH, qc);
1173 rl_insert_text (rp);
1174 rl_insert_text (" ");
1175 if (rp != matches[i])
1181 rp = make_quoted_replacement (matches[0], SINGLE_MATCH, qc);
1182 rl_insert_text (rp);
1183 rl_insert_text (" ");
1184 if (rp != matches[0])
1187 rl_end_undo_group ();
1191 free_match_list (matches)
1196 for (i = 0; matches[i]; i++)
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. */
1209 rl_complete_internal (what_to_do)
1213 rl_compentry_func_t *our_func;
1214 int start, end, delimiter, found_quote, i;
1215 char *text, *saved_line_buffer;
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;
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;
1229 /* We now look backwards for the start of a filename/variable word. */
1231 found_quote = delimiter = 0;
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);
1242 text = rl_copy_text (start, end);
1243 matches = gen_completion_matches (text, start, end, our_func, found_quote, quote_char);
1249 FREE (saved_line_buffer);
1250 RL_UNSETSTATE(RL_STATE_COMPLETING);
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;
1259 if (postprocess_matches (&matches, i) == 0)
1262 FREE (saved_line_buffer);
1263 completion_changed_buffer = 0;
1264 RL_UNSETSTATE(RL_STATE_COMPLETING);
1272 /* Insert the first match with proper quoting. */
1274 insert_match (matches[0], start, matches[1] ? MULT_MATCH : SINGLE_MATCH, "e_char);
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. */
1286 if (what_to_do == '!')
1288 display_matches (matches);
1291 else if (rl_editing_mode != vi_mode)
1292 rl_ding (); /* There are other matches remaining. */
1295 append_to_match (matches[0], delimiter, quote_char);
1300 insert_all_matches (matches, start, "e_char);
1304 display_matches (matches);
1308 fprintf (stderr, "\r\nreadline: bad value %d for what_to_do in rl_complete\n", what_to_do);
1310 FREE (saved_line_buffer);
1311 RL_UNSETSTATE(RL_STATE_COMPLETING);
1315 free_match_list (matches);
1317 /* Check to see if the line has changed through all of this manipulation. */
1318 if (saved_line_buffer)
1320 completion_changed_buffer = strcmp (rl_line_buffer, saved_line_buffer) != 0;
1321 free (saved_line_buffer);
1324 RL_UNSETSTATE(RL_STATE_COMPLETING);
1328 /***************************************************************/
1330 /* Application-callable completion match generator functions */
1332 /***************************************************************/
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.
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.
1347 rl_completion_matches (text, entry_function)
1349 rl_compentry_func_t *entry_function;
1351 /* Number of slots in match_list. */
1352 int match_list_size;
1354 /* The list of matches. */
1357 /* Number of matches actually found. */
1360 /* Temporary string binder. */
1364 match_list_size = 10;
1365 match_list = (char **)xmalloc ((match_list_size + 1) * sizeof (char *));
1366 match_list[1] = (char *)NULL;
1368 while (string = (*entry_function) (text, matches))
1370 if (matches + 1 == match_list_size)
1371 match_list = (char **)xrealloc
1372 (match_list, ((match_list_size += 10) + 1) * sizeof (char *));
1374 match_list[++matches] = string;
1375 match_list[matches + 1] = (char *)NULL;
1378 /* If there were any matches, then look through them finding out the
1379 lowest common denominator. That then becomes match_list[0]. */
1381 compute_lcd_of_matches (match_list, matches, text);
1382 else /* There were no matches. */
1385 match_list = (char **)NULL;
1387 return (match_list);
1390 /* A completion function for usernames.
1391 TEXT contains a partial username preceded by a random
1392 character (usually `~'). */
1394 rl_username_completion_function (text, state)
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;
1411 first_char_loc = first_char == '~';
1413 username = savestring (&text[first_char_loc]);
1414 namelen = strlen (username);
1418 while (entry = getpwent ())
1420 /* Null usernames should result in all users as possible completions. */
1421 if (namelen == 0 || (STREQN (username, entry->pw_name, namelen)))
1428 return ((char *)NULL);
1432 value = xmalloc (2 + strlen (entry->pw_name));
1436 strcpy (value + first_char_loc, entry->pw_name);
1438 if (first_char == '~')
1439 rl_filename_completion_desired = 1;
1443 #endif /* !__WIN32__ && !__OPENNT */
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. */
1451 rl_filename_completion_function (text, state)
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;
1462 struct dirent *entry;
1464 /* If we don't have any state, then do some initialization. */
1467 /* If we were interrupted before closing the directory or reading
1468 all of its contents, close it. */
1471 closedir (directory);
1472 directory = (DIR *)NULL;
1476 FREE (users_dirname);
1478 filename = savestring (text);
1481 dirname = savestring (text);
1483 temp = strrchr (dirname, '/');
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, '/');
1493 strcpy (filename, ++temp);
1496 #if defined (__MSDOS__)
1497 /* searches from current directory on the drive */
1498 else if (isalpha (dirname[0]) && dirname[1] == ':')
1500 strcpy (filename, dirname + 2);
1510 /* We aren't done yet. We also support the "~user" syntax. */
1512 /* Save the version of the directory that the user typed. */
1513 users_dirname = savestring (dirname);
1515 if (*dirname == '~')
1517 temp = tilde_expand (dirname);
1522 if (rl_directory_rewrite_hook)
1523 (*rl_directory_rewrite_hook) (&dirname);
1525 if (rl_directory_completion_hook && (*rl_directory_completion_hook) (&dirname))
1527 free (users_dirname);
1528 users_dirname = savestring (dirname);
1531 directory = opendir (dirname);
1532 filename_len = strlen (filename);
1534 rl_filename_completion_desired = 1;
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 *** */
1543 /* Now that we have some state, we can read the directory. */
1545 entry = (struct dirent *)NULL;
1546 while (directory && (entry = readdir (directory)))
1548 /* Special case for no filename.
1549 All entries except "." and ".." match. */
1550 if (filename_len == 0)
1552 if (entry->d_name[0] != '.' ||
1553 (entry->d_name[1] &&
1554 (entry->d_name[1] != '.' || entry->d_name[2])))
1559 /* Otherwise, if these match up to the length of filename, then
1561 if (_rl_completion_case_fold)
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))
1570 if ((entry->d_name[0] == filename[0]) &&
1571 (((int)D_NAMLEN (entry)) >= filename_len) &&
1572 (strncmp (filename, entry->d_name, filename_len) == 0))
1582 closedir (directory);
1583 directory = (DIR *)NULL;
1588 dirname = (char *)NULL;
1593 filename = (char *)NULL;
1597 free (users_dirname);
1598 users_dirname = (char *)NULL;
1601 return (char *)NULL;
1605 /* dirname && (strcmp (dirname, ".") != 0) */
1606 if (dirname && (dirname[0] != '.' || dirname[1]))
1608 if (rl_complete_with_tilde_expansion && *users_dirname == '~')
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] != '/')
1617 temp[dirlen++] = '/';
1618 temp[dirlen] = '\0';
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++] = '/';
1631 strcpy (temp + dirlen, entry->d_name);
1634 temp = savestring (entry->d_name);
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. */
1650 rl_menu_complete (count, ignore)
1653 rl_compentry_func_t *our_func;
1654 int matching_filenames, found_quote;
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;
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)
1668 /* Clean up from previous call, if any. */
1671 free_match_list (matches);
1673 match_list_index = match_list_size = 0;
1674 matches = (char **)NULL;
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 = '%';
1681 our_func = rl_completion_entry_function
1682 ? rl_completion_entry_function
1683 : rl_filename_completion_function;
1685 /* We now look backwards for the start of a filename/variable word. */
1686 orig_end = rl_point;
1687 found_quote = delimiter = 0;
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);
1695 orig_start = rl_point;
1696 rl_point = orig_end;
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);
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;
1707 if (matches == 0 || postprocess_matches (&matches, matching_filenames) == 0)
1711 matches = (char **)0;
1713 orig_text = (char *)0;
1714 completion_changed_buffer = 0;
1718 for (match_list_size = 0; matches[match_list_size]; match_list_size++)
1720 /* matches[0] is lcd if match_list_size > 1, but the circular buffer
1721 code below should take care of it. */
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. */
1728 if (matches == 0 || match_list_size == 0)
1732 matches = (char **)0;
1733 completion_changed_buffer = 0;
1737 match_list_index = (match_list_index + count) % match_list_size;
1738 if (match_list_index < 0)
1739 match_list_index += match_list_size;
1741 if (match_list_index == 0 && match_list_size > 1)
1744 insert_match (orig_text, orig_start, MULT_MATCH, "e_char);
1748 insert_match (matches[match_list_index], orig_start, SINGLE_MATCH, "e_char);
1749 append_to_match (matches[match_list_index], delimiter, quote_char);
1752 completion_changed_buffer = 1;