1 /* complete.c -- filename completion for readline. */
3 /* Copyright (C) 1987-2009 Free Software Foundation, Inc.
5 This file is part of the GNU Readline Library (Readline), a library
6 for reading lines of text with interactive input and history editing.
8 Readline is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 Readline is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with Readline. If not, see <http://www.gnu.org/licenses/>.
22 #define READLINE_LIBRARY
24 #if defined (HAVE_CONFIG_H)
28 #include <sys/types.h>
30 #if defined (HAVE_SYS_FILE_H)
31 # include <sys/file.h>
34 #if defined (HAVE_UNISTD_H)
36 #endif /* HAVE_UNISTD_H */
38 #if defined (HAVE_STDLIB_H)
41 # include "ansi_stdlib.h"
42 #endif /* HAVE_STDLIB_H */
51 #if defined (HAVE_PWD_H)
56 #include "posixstat.h"
58 /* System-specific feature definitions and include files. */
62 /* Some standard library routines. */
65 #include "rlprivate.h"
68 typedef int QSFUNC (const void *, const void *);
70 typedef int QSFUNC ();
79 /* Unix version of a hidden file. Could be different on other systems. */
80 #define HIDDEN_FILE(fname) ((fname)[0] == '.')
82 /* Most systems don't declare getpwent in <pwd.h> if _POSIX_SOURCE is
84 #if defined (HAVE_GETPWENT) && (!defined (HAVE_GETPW_DECLS) || defined (_POSIX_SOURCE))
85 extern struct passwd *getpwent PARAMS((void));
86 #endif /* HAVE_GETPWENT && (!HAVE_GETPW_DECLS || _POSIX_SOURCE) */
88 /* If non-zero, then this is the address of a function to call when
89 completing a word would normally display the list of possible matches.
90 This function is called instead of actually doing the display.
91 It takes three arguments: (char **matches, int num_matches, int max_length)
92 where MATCHES is the array of strings that matched, NUM_MATCHES is the
93 number of strings in that array, and MAX_LENGTH is the length of the
94 longest string in that array. */
95 rl_compdisp_func_t *rl_completion_display_matches_hook = (rl_compdisp_func_t *)NULL;
97 #if defined (VISIBLE_STATS)
101 static int stat_char PARAMS((char *));
104 static int path_isdir PARAMS((const char *));
106 static char *rl_quote_filename PARAMS((char *, int, char *));
108 static void set_completion_defaults PARAMS((int));
109 static int get_y_or_n PARAMS((int));
110 static int _rl_internal_pager PARAMS((int));
111 static char *printable_part PARAMS((char *));
112 static int fnwidth PARAMS((const char *));
113 static int fnprint PARAMS((const char *, int));
114 static int print_filename PARAMS((char *, char *, int));
116 static char **gen_completion_matches PARAMS((char *, int, int, rl_compentry_func_t *, int, int));
118 static char **remove_duplicate_matches PARAMS((char **));
119 static void insert_match PARAMS((char *, int, int, char *));
120 static int append_to_match PARAMS((char *, int, int, int));
121 static void insert_all_matches PARAMS((char **, int, char *));
122 static void display_matches PARAMS((char **));
123 static int compute_lcd_of_matches PARAMS((char **, int, const char *));
124 static int postprocess_matches PARAMS((char ***, int));
126 static char *make_quoted_replacement PARAMS((char *, int, char *));
128 /* **************************************************************** */
130 /* Completion matching, from readline's point of view. */
132 /* **************************************************************** */
134 /* Variables known only to the readline library. */
136 /* If non-zero, non-unique completions always show the list of matches. */
137 int _rl_complete_show_all = 0;
139 /* If non-zero, non-unique completions show the list of matches, unless it
140 is not possible to do partial completion and modify the line. */
141 int _rl_complete_show_unmodified = 0;
143 /* If non-zero, completed directory names have a slash appended. */
144 int _rl_complete_mark_directories = 1;
146 /* If non-zero, the symlinked directory completion behavior introduced in
147 readline-4.2a is disabled, and symlinks that point to directories have
148 a slash appended (subject to the value of _rl_complete_mark_directories).
149 This is user-settable via the mark-symlinked-directories variable. */
150 int _rl_complete_mark_symlink_dirs = 0;
152 /* If non-zero, completions are printed horizontally in alphabetical order,
154 int _rl_print_completions_horizontally;
156 /* Non-zero means that case is not significant in filename completion. */
157 #if defined (__MSDOS__) && !defined (__DJGPP__)
158 int _rl_completion_case_fold = 1;
160 int _rl_completion_case_fold;
163 /* If non-zero, don't match hidden files (filenames beginning with a `.' on
164 Unix) when doing filename completion. */
165 int _rl_match_hidden_files = 1;
167 /* Length in characters of a common prefix replaced with an ellipsis (`...')
168 when displaying completion matches. Matches whose printable portion has
169 more than this number of displaying characters in common will have the common
170 display prefix replaced with an ellipsis. */
171 int _rl_completion_prefix_display_length = 0;
173 /* Global variables available to applications using readline. */
175 #if defined (VISIBLE_STATS)
176 /* Non-zero means add an additional character to each filename displayed
177 during listing completion iff rl_filename_completion_desired which helps
178 to indicate the type of file being listed. */
179 int rl_visible_stats = 0;
180 #endif /* VISIBLE_STATS */
182 /* If non-zero, when completing in the middle of a word, don't insert
183 characters from the match that match characters following point in
184 the word. This means, for instance, completing when the cursor is
185 after the `e' in `Makefile' won't result in `Makefilefile'. */
186 int _rl_skip_completed_text = 0;
188 /* If non-zero, then this is the address of a function to call when
189 completing on a directory name. The function is called with
190 the address of a string (the current directory name) as an arg. */
191 rl_icppfunc_t *rl_directory_completion_hook = (rl_icppfunc_t *)NULL;
193 rl_icppfunc_t *rl_directory_rewrite_hook = (rl_icppfunc_t *)NULL;
195 /* If non-zero, this is the address of a function to call when reading
196 directory entries from the filesystem for completion and comparing
197 them to the partial word to be completed. The function should
198 either return its first argument (if no conversion takes place) or
199 newly-allocated memory. This can, for instance, convert filenames
200 between character sets for comparison against what's typed at the
201 keyboard. The returned value is what is added to the list of
202 matches. The second argument is the length of the filename to be
204 rl_dequote_func_t *rl_filename_rewrite_hook = (rl_dequote_func_t *)NULL;
206 /* Non-zero means readline completion functions perform tilde expansion. */
207 int rl_complete_with_tilde_expansion = 0;
209 /* Pointer to the generator function for completion_matches ().
210 NULL means to use rl_filename_completion_function (), the default filename
212 rl_compentry_func_t *rl_completion_entry_function = (rl_compentry_func_t *)NULL;
214 /* Pointer to generator function for rl_menu_complete (). NULL means to use
215 *rl_completion_entry_function (see above). */
216 rl_compentry_func_t *rl_menu_completion_entry_function = (rl_compentry_func_t *)NULL;
218 /* Pointer to alternative function to create matches.
219 Function is called with TEXT, START, and END.
220 START and END are indices in RL_LINE_BUFFER saying what the boundaries
222 If this function exists and returns NULL then call the value of
223 rl_completion_entry_function to try to match, otherwise use the
224 array of strings returned. */
225 rl_completion_func_t *rl_attempted_completion_function = (rl_completion_func_t *)NULL;
227 /* Non-zero means to suppress normal filename completion after the
228 user-specified completion function has been called. */
229 int rl_attempted_completion_over = 0;
231 /* Set to a character indicating the type of completion being performed
232 by rl_complete_internal, available for use by application completion
234 int rl_completion_type = 0;
236 /* Up to this many items will be displayed in response to a
237 possible-completions call. After that, we ask the user if
238 she is sure she wants to see them all. A negative value means
240 int rl_completion_query_items = 100;
242 int _rl_page_completions = 1;
244 /* The basic list of characters that signal a break between words for the
245 completer routine. The contents of this variable is what breaks words
246 in the shell, i.e. " \t\n\"\\'`@$><=" */
247 const char *rl_basic_word_break_characters = " \t\n\"\\'`@$><=;|&{("; /* }) */
249 /* List of basic quoting characters. */
250 const char *rl_basic_quote_characters = "\"'";
252 /* The list of characters that signal a break between words for
253 rl_complete_internal. The default list is the contents of
254 rl_basic_word_break_characters. */
255 /*const*/ char *rl_completer_word_break_characters = (/*const*/ char *)NULL;
257 /* Hook function to allow an application to set the completion word
258 break characters before readline breaks up the line. Allows
259 position-dependent word break characters. */
260 rl_cpvfunc_t *rl_completion_word_break_hook = (rl_cpvfunc_t *)NULL;
262 /* List of characters which can be used to quote a substring of the line.
263 Completion occurs on the entire substring, and within the substring
264 rl_completer_word_break_characters are treated as any other character,
265 unless they also appear within this list. */
266 const char *rl_completer_quote_characters = (const char *)NULL;
268 /* List of characters that should be quoted in filenames by the completer. */
269 const char *rl_filename_quote_characters = (const char *)NULL;
271 /* List of characters that are word break characters, but should be left
272 in TEXT when it is passed to the completion function. The shell uses
273 this to help determine what kind of completing to do. */
274 const char *rl_special_prefixes = (const char *)NULL;
276 /* If non-zero, then disallow duplicates in the matches. */
277 int rl_ignore_completion_duplicates = 1;
279 /* Non-zero means that the results of the matches are to be treated
280 as filenames. This is ALWAYS zero on entry, and can only be changed
281 within a completion entry finder function. */
282 int rl_filename_completion_desired = 0;
284 /* Non-zero means that the results of the matches are to be quoted using
285 double quotes (or an application-specific quoting mechanism) if the
286 filename contains any characters in rl_filename_quote_chars. This is
287 ALWAYS non-zero on entry, and can only be changed within a completion
288 entry finder function. */
289 int rl_filename_quoting_desired = 1;
291 /* This function, if defined, is called by the completer when real
292 filename completion is done, after all the matching names have been
293 generated. It is passed a (char**) known as matches in the code below.
294 It consists of a NULL-terminated array of pointers to potential
295 matching strings. The 1st element (matches[0]) is the maximal
296 substring that is common to all matches. This function can re-arrange
297 the list of matches as required, but all elements of the array must be
298 free()'d if they are deleted. The main intent of this function is
299 to implement FIGNORE a la SunOS csh. */
300 rl_compignore_func_t *rl_ignore_some_completions_function = (rl_compignore_func_t *)NULL;
302 /* Set to a function to quote a filename in an application-specific fashion.
303 Called with the text to quote, the type of match found (single or multiple)
304 and a pointer to the quoting character to be used, which the function can
306 rl_quote_func_t *rl_filename_quoting_function = rl_quote_filename;
308 /* Function to call to remove quoting characters from a filename. Called
309 before completion is attempted, so the embedded quotes do not interfere
310 with matching names in the file system. Readline doesn't do anything
311 with this; it's set only by applications. */
312 rl_dequote_func_t *rl_filename_dequoting_function = (rl_dequote_func_t *)NULL;
314 /* Function to call to decide whether or not a word break character is
315 quoted. If a character is quoted, it does not break words for the
317 rl_linebuf_func_t *rl_char_is_quoted_p = (rl_linebuf_func_t *)NULL;
319 /* If non-zero, the completion functions don't append anything except a
320 possible closing quote. This is set to 0 by rl_complete_internal and
321 may be changed by an application-specific completion function. */
322 int rl_completion_suppress_append = 0;
324 /* Character appended to completed words when at the end of the line. The
325 default is a space. */
326 int rl_completion_append_character = ' ';
328 /* If non-zero, the completion functions don't append any closing quote.
329 This is set to 0 by rl_complete_internal and may be changed by an
330 application-specific completion function. */
331 int rl_completion_suppress_quote = 0;
333 /* Set to any quote character readline thinks it finds before any application
334 completion function is called. */
335 int rl_completion_quote_character;
337 /* Set to a non-zero value if readline found quoting anywhere in the word to
338 be completed; set before any application completion function is called. */
339 int rl_completion_found_quote;
341 /* If non-zero, a slash will be appended to completed filenames that are
342 symbolic links to directory names, subject to the value of the
343 mark-directories variable (which is user-settable). This exists so
344 that application completion functions can override the user's preference
345 (set via the mark-symlinked-directories variable) if appropriate.
346 It's set to the value of _rl_complete_mark_symlink_dirs in
347 rl_complete_internal before any application-specific completion
348 function is called, so without that function doing anything, the user's
349 preferences are honored. */
350 int rl_completion_mark_symlink_dirs;
352 /* If non-zero, inhibit completion (temporarily). */
353 int rl_inhibit_completion;
355 /* Set to the last key used to invoke one of the completion functions */
356 int rl_completion_invoking_key;
358 /* If non-zero, sort the completion matches. On by default. */
359 int rl_sort_completion_matches = 1;
361 /* Variables local to this file. */
363 /* Local variable states what happened during the last completion attempt. */
364 static int completion_changed_buffer;
366 /* The result of the query to the user about displaying completion matches */
367 static int completion_y_or_n;
369 /*************************************/
371 /* Bindable completion functions */
373 /*************************************/
375 /* Complete the word at or before point. You have supplied the function
376 that does the initial simple matching selection algorithm (see
377 rl_completion_matches ()). The default is to do filename completion. */
379 rl_complete (ignore, invoking_key)
380 int ignore, invoking_key;
382 rl_completion_invoking_key = invoking_key;
384 if (rl_inhibit_completion)
385 return (_rl_insert_char (ignore, invoking_key));
386 else if (rl_last_func == rl_complete && !completion_changed_buffer)
387 return (rl_complete_internal ('?'));
388 else if (_rl_complete_show_all)
389 return (rl_complete_internal ('!'));
390 else if (_rl_complete_show_unmodified)
391 return (rl_complete_internal ('@'));
393 return (rl_complete_internal (TAB));
396 /* List the possible completions. See description of rl_complete (). */
398 rl_possible_completions (ignore, invoking_key)
399 int ignore, invoking_key;
401 rl_completion_invoking_key = invoking_key;
402 return (rl_complete_internal ('?'));
406 rl_insert_completions (ignore, invoking_key)
407 int ignore, invoking_key;
409 rl_completion_invoking_key = invoking_key;
410 return (rl_complete_internal ('*'));
413 /* Return the correct value to pass to rl_complete_internal performing
414 the same tests as rl_complete. This allows consecutive calls to an
415 application's completion function to list possible completions and for
416 an application-specific completion function to honor the
417 show-all-if-ambiguous readline variable. */
419 rl_completion_mode (cfunc)
420 rl_command_func_t *cfunc;
422 if (rl_last_func == cfunc && !completion_changed_buffer)
424 else if (_rl_complete_show_all)
426 else if (_rl_complete_show_unmodified)
432 /************************************/
434 /* Completion utility functions */
436 /************************************/
438 /* Reset readline state on a signal or other event. */
440 _rl_reset_completion_state ()
442 rl_completion_found_quote = 0;
443 rl_completion_quote_character = 0;
446 /* Set default values for readline word completion. These are the variables
447 that application completion functions can change or inspect. */
449 set_completion_defaults (what_to_do)
452 /* Only the completion entry function can change these. */
453 rl_filename_completion_desired = 0;
454 rl_filename_quoting_desired = 1;
455 rl_completion_type = what_to_do;
456 rl_completion_suppress_append = rl_completion_suppress_quote = 0;
457 rl_completion_append_character = ' ';
459 /* The completion entry function may optionally change this. */
460 rl_completion_mark_symlink_dirs = _rl_complete_mark_symlink_dirs;
463 /* The user must press "y" or "n". Non-zero return means "y" pressed. */
465 get_y_or_n (for_pager)
472 RL_SETSTATE(RL_STATE_MOREINPUT);
474 RL_UNSETSTATE(RL_STATE_MOREINPUT);
476 if (c == 'y' || c == 'Y' || c == ' ')
478 if (c == 'n' || c == 'N' || c == RUBOUT)
480 if (c == ABORT_CHAR || c < 0)
481 _rl_abort_internal ();
482 if (for_pager && (c == NEWLINE || c == RETURN))
484 if (for_pager && (c == 'q' || c == 'Q'))
491 _rl_internal_pager (lines)
496 fprintf (rl_outstream, "--More--");
497 fflush (rl_outstream);
499 _rl_erase_entire_line ();
509 path_isdir (filename)
510 const char *filename;
514 return (stat (filename, &finfo) == 0 && S_ISDIR (finfo.st_mode));
517 #if defined (VISIBLE_STATS)
518 /* Return the character which best describes FILENAME.
519 `@' for symbolic links
524 `%' for character special devices
525 `#' for block special devices */
533 /* Short-circuit a //server on cygwin, since that will always behave as
536 if (filename[0] == '/' && filename[1] == '/' && strchr (filename+2, '/') == 0)
540 #if defined (HAVE_LSTAT) && defined (S_ISLNK)
541 r = lstat (filename, &finfo);
543 r = stat (filename, &finfo);
550 if (S_ISDIR (finfo.st_mode))
552 #if defined (S_ISCHR)
553 else if (S_ISCHR (finfo.st_mode))
556 #if defined (S_ISBLK)
557 else if (S_ISBLK (finfo.st_mode))
560 #if defined (S_ISLNK)
561 else if (S_ISLNK (finfo.st_mode))
564 #if defined (S_ISSOCK)
565 else if (S_ISSOCK (finfo.st_mode))
567 #endif /* S_ISSOCK */
568 #if defined (S_ISFIFO)
569 else if (S_ISFIFO (finfo.st_mode))
572 else if (S_ISREG (finfo.st_mode))
574 if (access (filename, X_OK) == 0)
579 #endif /* VISIBLE_STATS */
581 /* Return the portion of PATHNAME that should be output when listing
582 possible completions. If we are hacking filename completion, we
583 are only interested in the basename, the portion following the
584 final slash. Otherwise, we return what we were passed. Since
585 printing empty strings is not very informative, if we're doing
586 filename completion, and the basename is the empty string, we look
587 for the previous slash and return the portion following that. If
588 there's no previous slash, we just return what we were passed. */
590 printable_part (pathname)
595 if (rl_filename_completion_desired == 0) /* don't need to do anything */
598 temp = strrchr (pathname, '/');
599 #if defined (__MSDOS__)
600 if (temp == 0 && ISALPHA ((unsigned char)pathname[0]) && pathname[1] == ':')
604 if (temp == 0 || *temp == '\0')
606 /* If the basename is NULL, we might have a pathname like '/usr/src/'.
607 Look for a previous slash and, if one is found, return the portion
608 following that slash. If there's no previous slash, just return the
609 pathname we were passed. */
610 else if (temp[1] == '\0')
612 for (x = temp - 1; x > pathname; x--)
615 return ((*x == '/') ? x + 1 : pathname);
621 /* Compute width of STRING when displayed on screen by print_filename */
627 #if defined (HANDLE_MULTIBYTE)
633 left = strlen (string) + 1;
634 memset (&ps, 0, sizeof (mbstate_t));
640 if (CTRL_CHAR (string[pos]) || string[pos] == RUBOUT)
647 #if defined (HANDLE_MULTIBYTE)
648 clen = mbrtowc (&wc, string + pos, left - pos, &ps);
649 if (MB_INVALIDCH (clen))
653 memset (&ps, 0, sizeof (mbstate_t));
655 else if (MB_NULLWCH (clen))
661 width += (w >= 0) ? w : 1;
673 #define ELLIPSIS_LEN 3
676 fnprint (to_print, prefix_bytes)
677 const char *to_print;
682 #if defined (HANDLE_MULTIBYTE)
689 end = to_print + strlen (to_print) + 1;
690 memset (&ps, 0, sizeof (mbstate_t));
695 /* Don't print only the ellipsis if the common prefix is one of the
696 possible completions */
697 if (to_print[prefix_bytes] == '\0')
704 ellipsis = (to_print[prefix_bytes] == '.') ? '_' : '.';
705 for (w = 0; w < ELLIPSIS_LEN; w++)
706 putc (ellipsis, rl_outstream);
707 printed_len = ELLIPSIS_LEN;
710 s = to_print + prefix_bytes;
715 putc ('^', rl_outstream);
716 putc (UNCTRL (*s), rl_outstream);
719 #if defined (HANDLE_MULTIBYTE)
720 memset (&ps, 0, sizeof (mbstate_t));
723 else if (*s == RUBOUT)
725 putc ('^', rl_outstream);
726 putc ('?', rl_outstream);
729 #if defined (HANDLE_MULTIBYTE)
730 memset (&ps, 0, sizeof (mbstate_t));
735 #if defined (HANDLE_MULTIBYTE)
736 tlen = mbrtowc (&wc, s, end - s, &ps);
737 if (MB_INVALIDCH (tlen))
741 memset (&ps, 0, sizeof (mbstate_t));
743 else if (MB_NULLWCH (tlen))
748 width = (w >= 0) ? w : 1;
750 fwrite (s, 1, tlen, rl_outstream);
752 printed_len += width;
754 putc (*s, rl_outstream);
764 /* Output TO_PRINT to rl_outstream. If VISIBLE_STATS is defined and we
765 are using it, check for and output a single character for `special'
766 filenames. Return the number of characters we output. */
769 print_filename (to_print, full_pathname, prefix_bytes)
770 char *to_print, *full_pathname;
773 int printed_len, extension_char, slen, tlen;
774 char *s, c, *new_full_pathname, *dn;
777 printed_len = fnprint (to_print, prefix_bytes);
779 #if defined (VISIBLE_STATS)
780 if (rl_filename_completion_desired && (rl_visible_stats || _rl_complete_mark_directories))
782 if (rl_filename_completion_desired && _rl_complete_mark_directories)
785 /* If to_print != full_pathname, to_print is the basename of the
786 path passed. In this case, we try to expand the directory
787 name before checking for the stat character. */
788 if (to_print != full_pathname)
790 /* Terminate the directory name. */
794 /* If setting the last slash in full_pathname to a NUL results in
795 full_pathname being the empty string, we are trying to complete
796 files in the root directory. If we pass a null string to the
797 bash directory completion hook, for example, it will expand it
798 to the current directory. We just want the `/'. */
799 if (full_pathname == 0 || *full_pathname == 0)
801 else if (full_pathname[0] != '/')
803 else if (full_pathname[1] == 0)
804 dn = "//"; /* restore trailing slash to `//' */
805 else if (full_pathname[1] == '/' && full_pathname[2] == 0)
806 dn = "/"; /* don't turn /// into // */
809 s = tilde_expand (dn);
810 if (rl_directory_completion_hook)
811 (*rl_directory_completion_hook) (&s);
814 tlen = strlen (to_print);
815 new_full_pathname = (char *)xmalloc (slen + tlen + 2);
816 strcpy (new_full_pathname, s);
817 if (s[slen - 1] == '/')
820 new_full_pathname[slen] = '/';
821 new_full_pathname[slen] = '/';
822 strcpy (new_full_pathname + slen + 1, to_print);
824 #if defined (VISIBLE_STATS)
825 if (rl_visible_stats)
826 extension_char = stat_char (new_full_pathname);
829 if (path_isdir (new_full_pathname))
830 extension_char = '/';
832 free (new_full_pathname);
837 s = tilde_expand (full_pathname);
838 #if defined (VISIBLE_STATS)
839 if (rl_visible_stats)
840 extension_char = stat_char (s);
844 extension_char = '/';
850 putc (extension_char, rl_outstream);
859 rl_quote_filename (s, rtype, qcp)
866 r = (char *)xmalloc (strlen (s) + 2);
867 *r = *rl_completer_quote_characters;
870 *qcp = *rl_completer_quote_characters;
874 /* Find the bounds of the current word for completion purposes, and leave
875 rl_point set to the end of the word. This function skips quoted
876 substrings (characters between matched pairs of characters in
877 rl_completer_quote_characters). First we try to find an unclosed
878 quoted substring on which to do matching. If one is not found, we use
879 the word break characters to find the boundaries of the current word.
880 We call an application-specific function to decide whether or not a
881 particular word break character is quoted; if that function returns a
882 non-zero result, the character does not break a word. This function
883 returns the opening quote character if we found an unclosed quoted
884 substring, '\0' otherwise. FP, if non-null, is set to a value saying
885 which (shell-like) quote characters we found (single quote, double
886 quote, or backslash) anywhere in the string. DP, if non-null, is set to
887 the value of the delimiter character that caused a word break. */
890 _rl_find_completion_word (fp, dp)
893 int scan, end, found_quote, delimiter, pass_next, isbrk;
894 char quote_char, *brkchars;
897 found_quote = delimiter = 0;
901 if (rl_completion_word_break_hook)
902 brkchars = (*rl_completion_word_break_hook) ();
904 brkchars = rl_completer_word_break_characters;
906 if (rl_completer_quote_characters)
908 /* We have a list of characters which can be used in pairs to
909 quote substrings for the completer. Try to find the start
910 of an unclosed quoted substring. */
911 /* FOUND_QUOTE is set so we know what kind of quotes we found. */
912 for (scan = pass_next = 0; scan < end; scan = MB_NEXTCHAR (rl_line_buffer, scan, 1, MB_FIND_ANY))
920 /* Shell-like semantics for single quotes -- don't allow backslash
921 to quote anything in single quotes, especially not the closing
922 quote. If you don't like this, take out the check on the value
924 if (quote_char != '\'' && rl_line_buffer[scan] == '\\')
927 found_quote |= RL_QF_BACKSLASH;
931 if (quote_char != '\0')
933 /* Ignore everything until the matching close quote char. */
934 if (rl_line_buffer[scan] == quote_char)
936 /* Found matching close. Abandon this substring. */
941 else if (strchr (rl_completer_quote_characters, rl_line_buffer[scan]))
943 /* Found start of a quoted substring. */
944 quote_char = rl_line_buffer[scan];
946 /* Shell-like quoting conventions. */
947 if (quote_char == '\'')
948 found_quote |= RL_QF_SINGLE_QUOTE;
949 else if (quote_char == '"')
950 found_quote |= RL_QF_DOUBLE_QUOTE;
952 found_quote |= RL_QF_OTHER_QUOTE;
957 if (rl_point == end && quote_char == '\0')
959 /* We didn't find an unclosed quoted substring upon which to do
960 completion, so use the word break characters to find the
961 substring on which to complete. */
962 while (rl_point = MB_PREVCHAR (rl_line_buffer, rl_point, MB_FIND_ANY))
964 scan = rl_line_buffer[rl_point];
966 if (strchr (brkchars, scan) == 0)
969 /* Call the application-specific function to tell us whether
970 this word break character is quoted and should be skipped. */
971 if (rl_char_is_quoted_p && found_quote &&
972 (*rl_char_is_quoted_p) (rl_line_buffer, rl_point))
975 /* Convoluted code, but it avoids an n^2 algorithm with calls
976 to char_is_quoted. */
981 /* If we are at an unquoted word break, then advance past it. */
982 scan = rl_line_buffer[rl_point];
984 /* If there is an application-specific function to say whether or not
985 a character is quoted and we found a quote character, let that
986 function decide whether or not a character is a word break, even
987 if it is found in rl_completer_word_break_characters. Don't bother
988 if we're at the end of the line, though. */
991 if (rl_char_is_quoted_p)
992 isbrk = (found_quote == 0 ||
993 (*rl_char_is_quoted_p) (rl_line_buffer, rl_point) == 0) &&
994 strchr (brkchars, scan) != 0;
996 isbrk = strchr (brkchars, scan) != 0;
1000 /* If the character that caused the word break was a quoting
1001 character, then remember it as the delimiter. */
1002 if (rl_basic_quote_characters &&
1003 strchr (rl_basic_quote_characters, scan) &&
1004 (end - rl_point) > 1)
1007 /* If the character isn't needed to determine something special
1008 about what kind of completion to perform, then advance past it. */
1009 if (rl_special_prefixes == 0 || strchr (rl_special_prefixes, scan) == 0)
1019 return (quote_char);
1023 gen_completion_matches (text, start, end, our_func, found_quote, quote_char)
1026 rl_compentry_func_t *our_func;
1027 int found_quote, quote_char;
1031 rl_completion_found_quote = found_quote;
1032 rl_completion_quote_character = quote_char;
1034 /* If the user wants to TRY to complete, but then wants to give
1035 up and use the default completion function, they set the
1036 variable rl_attempted_completion_function. */
1037 if (rl_attempted_completion_function)
1039 _rl_interrupt_immediately++;
1040 matches = (*rl_attempted_completion_function) (text, start, end);
1041 if (_rl_interrupt_immediately > 0)
1042 _rl_interrupt_immediately--;
1044 if (matches || rl_attempted_completion_over)
1046 rl_attempted_completion_over = 0;
1051 /* XXX -- filename dequoting moved into rl_filename_completion_function */
1053 matches = rl_completion_matches (text, our_func);
1057 /* Filter out duplicates in MATCHES. This frees up the strings in
1060 remove_duplicate_matches (matches)
1063 char *lowest_common;
1068 /* Sort the items. */
1069 for (i = 0; matches[i]; i++)
1072 /* Sort the array without matches[0], since we need it to
1073 stay in place no matter what. */
1074 if (i && rl_sort_completion_matches)
1075 qsort (matches+1, i-1, sizeof (char *), (QSFUNC *)_rl_qsort_string_compare);
1077 /* Remember the lowest common denominator for it may be unique. */
1078 lowest_common = savestring (matches[0]);
1080 for (i = newlen = 0; matches[i + 1]; i++)
1082 if (strcmp (matches[i], matches[i + 1]) == 0)
1085 matches[i] = (char *)&dead_slot;
1091 /* We have marked all the dead slots with (char *)&dead_slot.
1092 Copy all the non-dead entries into a new array. */
1093 temp_array = (char **)xmalloc ((3 + newlen) * sizeof (char *));
1094 for (i = j = 1; matches[i]; i++)
1096 if (matches[i] != (char *)&dead_slot)
1097 temp_array[j++] = matches[i];
1099 temp_array[j] = (char *)NULL;
1101 if (matches[0] != (char *)&dead_slot)
1104 /* Place the lowest common denominator back in [0]. */
1105 temp_array[0] = lowest_common;
1107 /* If there is one string left, and it is identical to the
1108 lowest common denominator, then the LCD is the string to
1110 if (j == 2 && strcmp (temp_array[0], temp_array[1]) == 0)
1112 free (temp_array[1]);
1113 temp_array[1] = (char *)NULL;
1115 return (temp_array);
1118 /* Find the common prefix of the list of matches, and put it into
1121 compute_lcd_of_matches (match_list, matches, text)
1126 register int i, c1, c2, si;
1127 int low; /* Count of max-matched characters. */
1128 char *dtext; /* dequoted TEXT, if needed */
1129 #if defined (HANDLE_MULTIBYTE)
1135 /* If only one match, just use that. Otherwise, compare each
1136 member of the list with the next, finding out where they
1140 match_list[0] = match_list[1];
1141 match_list[1] = (char *)NULL;
1145 for (i = 1, low = 100000; i < matches; i++)
1147 #if defined (HANDLE_MULTIBYTE)
1148 if (MB_CUR_MAX > 1 && rl_byte_oriented == 0)
1150 memset (&ps1, 0, sizeof (mbstate_t));
1151 memset (&ps2, 0, sizeof (mbstate_t));
1154 if (_rl_completion_case_fold)
1157 (c1 = _rl_to_lower(match_list[i][si])) &&
1158 (c2 = _rl_to_lower(match_list[i + 1][si]));
1160 #if defined (HANDLE_MULTIBYTE)
1161 if (MB_CUR_MAX > 1 && rl_byte_oriented == 0)
1163 v = mbrtowc (&wc1, match_list[i]+si, strlen (match_list[i]+si), &ps1);
1164 mbrtowc (&wc2, match_list[i+1]+si, strlen (match_list[i+1]+si), &ps2);
1165 wc1 = towlower (wc1);
1166 wc2 = towlower (wc2);
1180 (c1 = match_list[i][si]) &&
1181 (c2 = match_list[i + 1][si]);
1183 #if defined (HANDLE_MULTIBYTE)
1184 if (MB_CUR_MAX > 1 && rl_byte_oriented == 0)
1188 if (!_rl_compare_chars (match_list[i], si, &ps1, match_list[i+1], si, &ps2))
1190 else if ((v = _rl_get_char_len (&match_list[i][si], &ps_back)) > 1)
1203 /* If there were multiple matches, but none matched up to even the
1204 first character, and the user typed something, use that as the
1205 value of matches[0]. */
1206 if (low == 0 && text && *text)
1208 match_list[0] = (char *)xmalloc (strlen (text) + 1);
1209 strcpy (match_list[0], text);
1213 match_list[0] = (char *)xmalloc (low + 1);
1215 /* XXX - this might need changes in the presence of multibyte chars */
1217 /* If we are ignoring case, try to preserve the case of the string
1218 the user typed in the face of multiple matches differing in case. */
1219 if (_rl_completion_case_fold)
1221 /* We're making an assumption here:
1222 IF we're completing filenames AND
1223 the application has defined a filename dequoting function AND
1224 we found a quote character AND
1225 the application has requested filename quoting
1227 we assume that TEXT was dequoted before checking against
1228 the file system and needs to be dequoted here before we
1229 check against the list of matches
1231 dtext = (char *)NULL;
1232 if (rl_filename_completion_desired &&
1233 rl_filename_dequoting_function &&
1234 rl_completion_found_quote &&
1235 rl_filename_quoting_desired)
1237 dtext = (*rl_filename_dequoting_function) ((char *)text, rl_completion_quote_character);
1241 /* sort the list to get consistent answers. */
1242 qsort (match_list+1, matches, sizeof(char *), (QSFUNC *)_rl_qsort_string_compare);
1247 for (i = 1; i <= matches; i++)
1248 if (strncmp (match_list[i], text, si) == 0)
1250 strncpy (match_list[0], match_list[i], low);
1253 /* no casematch, use first entry */
1255 strncpy (match_list[0], match_list[1], low);
1258 /* otherwise, just use the text the user typed. */
1259 strncpy (match_list[0], text, low);
1264 strncpy (match_list[0], match_list[1], low);
1266 match_list[0][low] = '\0';
1273 postprocess_matches (matchesp, matching_filenames)
1275 int matching_filenames;
1277 char *t, **matches, **temp_matches;
1280 matches = *matchesp;
1285 /* It seems to me that in all the cases we handle we would like
1286 to ignore duplicate possiblilities. Scan for the text to
1287 insert being identical to the other completions. */
1288 if (rl_ignore_completion_duplicates)
1290 temp_matches = remove_duplicate_matches (matches);
1292 matches = temp_matches;
1295 /* If we are matching filenames, then here is our chance to
1296 do clever processing by re-examining the list. Call the
1297 ignore function with the array as a parameter. It can
1298 munge the array, deleting matches as it desires. */
1299 if (rl_ignore_some_completions_function && matching_filenames)
1301 for (nmatch = 1; matches[nmatch]; nmatch++)
1303 (void)(*rl_ignore_some_completions_function) (matches);
1304 if (matches == 0 || matches[0] == 0)
1307 *matchesp = (char **)0;
1312 /* If we removed some matches, recompute the common prefix. */
1313 for (i = 1; matches[i]; i++)
1315 if (i > 1 && i < nmatch)
1318 compute_lcd_of_matches (matches, i - 1, t);
1324 *matchesp = matches;
1328 /* A convenience function for displaying a list of strings in
1329 columnar format on readline's output stream. MATCHES is the list
1330 of strings, in argv format, LEN is the number of strings in MATCHES,
1331 and MAX is the length of the longest string in MATCHES. */
1333 rl_display_match_list (matches, len, max)
1337 int count, limit, printed_len, lines;
1338 int i, j, k, l, common_length, sind;
1341 /* Find the length of the prefix common to all items: length as displayed
1342 characters (common_length) and as a byte index into the matches (sind) */
1343 common_length = sind = 0;
1344 if (_rl_completion_prefix_display_length > 0)
1346 t = printable_part (matches[0]);
1347 temp = strrchr (t, '/');
1348 common_length = temp ? fnwidth (temp) : fnwidth (t);
1349 sind = temp ? strlen (temp) : strlen (t);
1351 if (common_length > _rl_completion_prefix_display_length && common_length > ELLIPSIS_LEN)
1352 max -= common_length - ELLIPSIS_LEN;
1354 common_length = sind = 0;
1357 /* How many items of MAX length can we fit in the screen window? */
1359 limit = _rl_screenwidth / max;
1360 if (limit != 1 && (limit * max == _rl_screenwidth))
1363 /* Avoid a possible floating exception. If max > _rl_screenwidth,
1364 limit will be 0 and a divide-by-zero fault will result. */
1368 /* How many iterations of the printing loop? */
1369 count = (len + (limit - 1)) / limit;
1371 /* Watch out for special case. If LEN is less than LIMIT, then
1372 just do the inner printing loop.
1373 0 < len <= limit implies count = 1. */
1375 /* Sort the items if they are not already sorted. */
1376 if (rl_ignore_completion_duplicates == 0 && rl_sort_completion_matches)
1377 qsort (matches + 1, len, sizeof (char *), (QSFUNC *)_rl_qsort_string_compare);
1382 if (_rl_print_completions_horizontally == 0)
1384 /* Print the sorted items, up-and-down alphabetically, like ls. */
1385 for (i = 1; i <= count; i++)
1387 for (j = 0, l = i; j < limit; j++)
1389 if (l > len || matches[l] == 0)
1393 temp = printable_part (matches[l]);
1394 printed_len = print_filename (temp, matches[l], sind);
1397 for (k = 0; k < max - printed_len; k++)
1398 putc (' ', rl_outstream);
1404 if (_rl_page_completions && lines >= (_rl_screenheight - 1) && i < count)
1406 lines = _rl_internal_pager (lines);
1414 /* Print the sorted items, across alphabetically, like ls -x. */
1415 for (i = 1; matches[i]; i++)
1417 temp = printable_part (matches[i]);
1418 printed_len = print_filename (temp, matches[i], sind);
1419 /* Have we reached the end of this line? */
1422 if (i && (limit > 1) && (i % limit) == 0)
1426 if (_rl_page_completions && lines >= _rl_screenheight - 1)
1428 lines = _rl_internal_pager (lines);
1434 for (k = 0; k < max - printed_len; k++)
1435 putc (' ', rl_outstream);
1442 /* Display MATCHES, a list of matching filenames in argv format. This
1443 handles the simple case -- a single match -- first. If there is more
1444 than one match, we compute the number of strings in the list and the
1445 length of the longest string, which will be needed by the display
1446 function. If the application wants to handle displaying the list of
1447 matches itself, it sets RL_COMPLETION_DISPLAY_MATCHES_HOOK to the
1448 address of a function, and we just call it. If we're handling the
1449 display ourselves, we just call rl_display_match_list. We also check
1450 that the list of matches doesn't exceed the user-settable threshold,
1451 and ask the user if he wants to see the list if there are more matches
1452 than RL_COMPLETION_QUERY_ITEMS. */
1454 display_matches (matches)
1460 /* Move to the last visible line of a possibly-multiple-line command. */
1461 _rl_move_vert (_rl_vis_botlin);
1463 /* Handle simple case first. What if there is only one answer? */
1464 if (matches[1] == 0)
1466 temp = printable_part (matches[0]);
1468 print_filename (temp, matches[0], 0);
1471 rl_forced_update_display ();
1472 rl_display_fixed = 1;
1477 /* There is more than one answer. Find out how many there are,
1478 and find the maximum printed length of a single entry. */
1479 for (max = 0, i = 1; matches[i]; i++)
1481 temp = printable_part (matches[i]);
1482 len = fnwidth (temp);
1490 /* If the caller has defined a display hook, then call that now. */
1491 if (rl_completion_display_matches_hook)
1493 (*rl_completion_display_matches_hook) (matches, len, max);
1497 /* If there are many items, then ask the user if she really wants to
1499 if (rl_completion_query_items > 0 && len >= rl_completion_query_items)
1502 fprintf (rl_outstream, "Display all %d possibilities? (y or n)", len);
1503 fflush (rl_outstream);
1504 if ((completion_y_or_n = get_y_or_n (0)) == 0)
1508 rl_forced_update_display ();
1509 rl_display_fixed = 1;
1515 rl_display_match_list (matches, len, max);
1517 rl_forced_update_display ();
1518 rl_display_fixed = 1;
1522 make_quoted_replacement (match, mtype, qc)
1525 char *qc; /* Pointer to quoting character, if any */
1527 int should_quote, do_replace;
1530 /* If we are doing completion on quoted substrings, and any matches
1531 contain any of the completer_word_break_characters, then auto-
1532 matically prepend the substring with a quote character (just pick
1533 the first one from the list of such) if it does not already begin
1534 with a quote string. FIXME: Need to remove any such automatically
1535 inserted quote character when it no longer is necessary, such as
1536 if we change the string we are completing on and the new set of
1537 matches don't require a quoted substring. */
1538 replacement = match;
1540 should_quote = match && rl_completer_quote_characters &&
1541 rl_filename_completion_desired &&
1542 rl_filename_quoting_desired;
1545 should_quote = should_quote && (!qc || !*qc ||
1546 (rl_completer_quote_characters && strchr (rl_completer_quote_characters, *qc)));
1550 /* If there is a single match, see if we need to quote it.
1551 This also checks whether the common prefix of several
1552 matches needs to be quoted. */
1553 should_quote = rl_filename_quote_characters
1554 ? (_rl_strpbrk (match, rl_filename_quote_characters) != 0)
1557 do_replace = should_quote ? mtype : NO_MATCH;
1558 /* Quote the replacement, since we found an embedded
1559 word break character in a potential match. */
1560 if (do_replace != NO_MATCH && rl_filename_quoting_function)
1561 replacement = (*rl_filename_quoting_function) (match, do_replace, qc);
1563 return (replacement);
1567 insert_match (match, start, mtype, qc)
1572 char *replacement, *r;
1576 oqc = qc ? *qc : '\0';
1577 replacement = make_quoted_replacement (match, mtype, qc);
1579 /* Now insert the match. */
1582 rlen = strlen (replacement);
1583 /* Don't double an opening quote character. */
1584 if (qc && *qc && start && rl_line_buffer[start - 1] == *qc &&
1585 replacement[0] == *qc)
1587 /* If make_quoted_replacement changed the quoting character, remove
1588 the opening quote and insert the (fully-quoted) replacement. */
1589 else if (qc && (*qc != oqc) && start && rl_line_buffer[start - 1] == oqc &&
1590 replacement[0] != oqc)
1593 /* Don't double a closing quote character */
1594 if (qc && *qc && end && rl_line_buffer[rl_point] == *qc && replacement[rlen - 1] == *qc)
1596 if (_rl_skip_completed_text)
1599 while (start < rl_end && *r && rl_line_buffer[start] == *r)
1604 if (start <= end || *r)
1605 _rl_replace_text (r, start, end);
1606 rl_point = start + strlen (r);
1609 _rl_replace_text (replacement, start, end);
1610 if (replacement != match)
1615 /* Append any necessary closing quote and a separator character to the
1616 just-inserted match. If the user has specified that directories
1617 should be marked by a trailing `/', append one of those instead. The
1618 default trailing character is a space. Returns the number of characters
1619 appended. If NONTRIVIAL_MATCH is set, we test for a symlink (if the OS
1620 has them) and don't add a suffix for a symlink to a directory. A
1621 nontrivial match is one that actually adds to the word being completed.
1622 The variable rl_completion_mark_symlink_dirs controls this behavior
1623 (it's initially set to the what the user has chosen, indicated by the
1624 value of _rl_complete_mark_symlink_dirs, but may be modified by an
1625 application's completion function). */
1627 append_to_match (text, delimiter, quote_char, nontrivial_match)
1629 int delimiter, quote_char, nontrivial_match;
1631 char temp_string[4], *filename;
1632 int temp_string_index, s;
1635 temp_string_index = 0;
1636 if (quote_char && rl_point && rl_completion_suppress_quote == 0 &&
1637 rl_line_buffer[rl_point - 1] != quote_char)
1638 temp_string[temp_string_index++] = quote_char;
1641 temp_string[temp_string_index++] = delimiter;
1642 else if (rl_completion_suppress_append == 0 && rl_completion_append_character)
1643 temp_string[temp_string_index++] = rl_completion_append_character;
1645 temp_string[temp_string_index++] = '\0';
1647 if (rl_filename_completion_desired)
1649 filename = tilde_expand (text);
1650 s = (nontrivial_match && rl_completion_mark_symlink_dirs == 0)
1651 ? LSTAT (filename, &finfo)
1652 : stat (filename, &finfo);
1653 if (s == 0 && S_ISDIR (finfo.st_mode))
1655 if (_rl_complete_mark_directories /* && rl_completion_suppress_append == 0 */)
1657 /* This is clumsy. Avoid putting in a double slash if point
1658 is at the end of the line and the previous character is a
1660 if (rl_point && rl_line_buffer[rl_point] == '\0' && rl_line_buffer[rl_point - 1] == '/')
1662 else if (rl_line_buffer[rl_point] != '/')
1663 rl_insert_text ("/");
1667 /* Don't add anything if the filename is a symlink and resolves to a
1669 else if (s == 0 && S_ISLNK (finfo.st_mode) &&
1670 stat (filename, &finfo) == 0 && S_ISDIR (finfo.st_mode))
1675 if (rl_point == rl_end && temp_string_index)
1676 rl_insert_text (temp_string);
1682 if (rl_point == rl_end && temp_string_index)
1683 rl_insert_text (temp_string);
1686 return (temp_string_index);
1690 insert_all_matches (matches, point, qc)
1698 rl_begin_undo_group ();
1699 /* remove any opening quote character; make_quoted_replacement will add
1701 if (qc && *qc && point && rl_line_buffer[point - 1] == *qc)
1703 rl_delete_text (point, rl_point);
1708 for (i = 1; matches[i]; i++)
1710 rp = make_quoted_replacement (matches[i], SINGLE_MATCH, qc);
1711 rl_insert_text (rp);
1712 rl_insert_text (" ");
1713 if (rp != matches[i])
1719 rp = make_quoted_replacement (matches[0], SINGLE_MATCH, qc);
1720 rl_insert_text (rp);
1721 rl_insert_text (" ");
1722 if (rp != matches[0])
1725 rl_end_undo_group ();
1729 _rl_free_match_list (matches)
1737 for (i = 0; matches[i]; i++)
1742 /* Complete the word at or before point.
1743 WHAT_TO_DO says what to do with the completion.
1744 `?' means list the possible completions.
1745 TAB means do standard completion.
1746 `*' means insert all of the possible completions.
1747 `!' means to do standard completion, and list all possible completions if
1748 there is more than one.
1749 `@' means to do standard completion, and list all possible completions if
1750 there is more than one and partial completion is not possible. */
1752 rl_complete_internal (what_to_do)
1756 rl_compentry_func_t *our_func;
1757 int start, end, delimiter, found_quote, i, nontrivial_lcd;
1758 char *text, *saved_line_buffer;
1761 RL_SETSTATE(RL_STATE_COMPLETING);
1763 set_completion_defaults (what_to_do);
1765 saved_line_buffer = rl_line_buffer ? savestring (rl_line_buffer) : (char *)NULL;
1766 our_func = rl_completion_entry_function
1767 ? rl_completion_entry_function
1768 : rl_filename_completion_function;
1769 /* We now look backwards for the start of a filename/variable word. */
1771 found_quote = delimiter = 0;
1775 /* This (possibly) changes rl_point. If it returns a non-zero char,
1776 we know we have an open quote. */
1777 quote_char = _rl_find_completion_word (&found_quote, &delimiter);
1782 text = rl_copy_text (start, end);
1783 matches = gen_completion_matches (text, start, end, our_func, found_quote, quote_char);
1784 /* nontrivial_lcd is set if the common prefix adds something to the word
1786 nontrivial_lcd = matches && strcmp (text, matches[0]) != 0;
1792 FREE (saved_line_buffer);
1793 completion_changed_buffer = 0;
1794 RL_UNSETSTATE(RL_STATE_COMPLETING);
1795 _rl_reset_completion_state ();
1799 /* If we are matching filenames, the attempted completion function will
1800 have set rl_filename_completion_desired to a non-zero value. The basic
1801 rl_filename_completion_function does this. */
1802 i = rl_filename_completion_desired;
1804 if (postprocess_matches (&matches, i) == 0)
1807 FREE (saved_line_buffer);
1808 completion_changed_buffer = 0;
1809 RL_UNSETSTATE(RL_STATE_COMPLETING);
1810 _rl_reset_completion_state ();
1819 /* Insert the first match with proper quoting. */
1821 insert_match (matches[0], start, matches[1] ? MULT_MATCH : SINGLE_MATCH, "e_char);
1823 /* If there are more matches, ring the bell to indicate.
1824 If we are in vi mode, Posix.2 says to not ring the bell.
1825 If the `show-all-if-ambiguous' variable is set, display
1826 all the matches immediately. Otherwise, if this was the
1827 only match, and we are hacking files, check the file to
1828 see if it was a directory. If so, and the `mark-directories'
1829 variable is set, add a '/' to the name. If not, and we
1830 are at the end of the line, then add a space. */
1833 if (what_to_do == '!')
1835 display_matches (matches);
1838 else if (what_to_do == '@')
1840 if (nontrivial_lcd == 0)
1841 display_matches (matches);
1844 else if (rl_editing_mode != vi_mode)
1845 rl_ding (); /* There are other matches remaining. */
1848 append_to_match (matches[0], delimiter, quote_char, nontrivial_lcd);
1853 insert_all_matches (matches, start, "e_char);
1857 display_matches (matches);
1861 _rl_ttymsg ("bad value %d for what_to_do in rl_complete", what_to_do);
1863 FREE (saved_line_buffer);
1864 RL_UNSETSTATE(RL_STATE_COMPLETING);
1865 _rl_reset_completion_state ();
1869 _rl_free_match_list (matches);
1871 /* Check to see if the line has changed through all of this manipulation. */
1872 if (saved_line_buffer)
1874 completion_changed_buffer = strcmp (rl_line_buffer, saved_line_buffer) != 0;
1875 free (saved_line_buffer);
1878 RL_UNSETSTATE(RL_STATE_COMPLETING);
1879 _rl_reset_completion_state ();
1883 /***************************************************************/
1885 /* Application-callable completion match generator functions */
1887 /***************************************************************/
1889 /* Return an array of (char *) which is a list of completions for TEXT.
1890 If there are no completions, return a NULL pointer.
1891 The first entry in the returned array is the substitution for TEXT.
1892 The remaining entries are the possible completions.
1893 The array is terminated with a NULL pointer.
1895 ENTRY_FUNCTION is a function of two args, and returns a (char *).
1896 The first argument is TEXT.
1897 The second is a state argument; it should be zero on the first call, and
1898 non-zero on subsequent calls. It returns a NULL pointer to the caller
1899 when there are no more matches.
1902 rl_completion_matches (text, entry_function)
1904 rl_compentry_func_t *entry_function;
1906 /* Number of slots in match_list. */
1907 int match_list_size;
1909 /* The list of matches. */
1912 /* Number of matches actually found. */
1915 /* Temporary string binder. */
1919 match_list_size = 10;
1920 match_list = (char **)xmalloc ((match_list_size + 1) * sizeof (char *));
1921 match_list[1] = (char *)NULL;
1923 _rl_interrupt_immediately++;
1924 while (string = (*entry_function) (text, matches))
1926 if (matches + 1 == match_list_size)
1927 match_list = (char **)xrealloc
1928 (match_list, ((match_list_size += 10) + 1) * sizeof (char *));
1930 match_list[++matches] = string;
1931 match_list[matches + 1] = (char *)NULL;
1933 if (_rl_interrupt_immediately > 0)
1934 _rl_interrupt_immediately--;
1936 /* If there were any matches, then look through them finding out the
1937 lowest common denominator. That then becomes match_list[0]. */
1939 compute_lcd_of_matches (match_list, matches, text);
1940 else /* There were no matches. */
1943 match_list = (char **)NULL;
1945 return (match_list);
1948 /* A completion function for usernames.
1949 TEXT contains a partial username preceded by a random
1950 character (usually `~'). */
1952 rl_username_completion_function (text, state)
1956 #if defined (__WIN32__) || defined (__OPENNT)
1957 return (char *)NULL;
1958 #else /* !__WIN32__ && !__OPENNT) */
1959 static char *username = (char *)NULL;
1960 static struct passwd *entry;
1961 static int namelen, first_char, first_char_loc;
1969 first_char_loc = first_char == '~';
1971 username = savestring (&text[first_char_loc]);
1972 namelen = strlen (username);
1976 #if defined (HAVE_GETPWENT)
1977 while (entry = getpwent ())
1979 /* Null usernames should result in all users as possible completions. */
1980 if (namelen == 0 || (STREQN (username, entry->pw_name, namelen)))
1987 #if defined (HAVE_GETPWENT)
1990 return ((char *)NULL);
1994 value = (char *)xmalloc (2 + strlen (entry->pw_name));
1998 strcpy (value + first_char_loc, entry->pw_name);
2000 if (first_char == '~')
2001 rl_filename_completion_desired = 1;
2005 #endif /* !__WIN32__ && !__OPENNT */
2008 /* Okay, now we write the entry_function for filename completion. In the
2009 general case. Note that completion in the shell is a little different
2010 because of all the pathnames that must be followed when looking up the
2011 completion for a command. */
2013 rl_filename_completion_function (text, state)
2017 static DIR *directory = (DIR *)NULL;
2018 static char *filename = (char *)NULL;
2019 static char *dirname = (char *)NULL;
2020 static char *users_dirname = (char *)NULL;
2021 static int filename_len;
2022 char *temp, *dentry, *convfn;
2023 int dirlen, dentlen, convlen;
2024 struct dirent *entry;
2026 /* If we don't have any state, then do some initialization. */
2029 /* If we were interrupted before closing the directory or reading
2030 all of its contents, close it. */
2033 closedir (directory);
2034 directory = (DIR *)NULL;
2038 FREE (users_dirname);
2040 filename = savestring (text);
2043 dirname = savestring (text);
2045 temp = strrchr (dirname, '/');
2047 #if defined (__MSDOS__)
2048 /* special hack for //X/... */
2049 if (dirname[0] == '/' && dirname[1] == '/' && ISALPHA ((unsigned char)dirname[2]) && dirname[3] == '/')
2050 temp = strrchr (dirname + 3, '/');
2055 strcpy (filename, ++temp);
2058 #if defined (__MSDOS__)
2059 /* searches from current directory on the drive */
2060 else if (ISALPHA ((unsigned char)dirname[0]) && dirname[1] == ':')
2062 strcpy (filename, dirname + 2);
2072 /* We aren't done yet. We also support the "~user" syntax. */
2074 /* Save the version of the directory that the user typed. */
2075 users_dirname = savestring (dirname);
2077 if (*dirname == '~')
2079 temp = tilde_expand (dirname);
2084 if (rl_directory_rewrite_hook)
2085 (*rl_directory_rewrite_hook) (&dirname);
2087 /* The directory completion hook should perform any necessary
2089 if (rl_directory_completion_hook && (*rl_directory_completion_hook) (&dirname))
2091 free (users_dirname);
2092 users_dirname = savestring (dirname);
2094 else if (rl_completion_found_quote && rl_filename_dequoting_function)
2096 /* delete single and double quotes */
2097 temp = (*rl_filename_dequoting_function) (users_dirname, rl_completion_quote_character);
2098 free (users_dirname);
2099 users_dirname = temp;
2101 directory = opendir (dirname);
2103 /* Now dequote a non-null filename. */
2104 if (filename && *filename && rl_completion_found_quote && rl_filename_dequoting_function)
2106 /* delete single and double quotes */
2107 temp = (*rl_filename_dequoting_function) (filename, rl_completion_quote_character);
2111 filename_len = strlen (filename);
2113 rl_filename_completion_desired = 1;
2116 /* At this point we should entertain the possibility of hacking wildcarded
2117 filenames, like /usr/man/man<WILD>/te<TAB>. If the directory name
2118 contains globbing characters, then build an array of directories, and
2119 then map over that list while completing. */
2120 /* *** UNIMPLEMENTED *** */
2122 /* Now that we have some state, we can read the directory. */
2124 entry = (struct dirent *)NULL;
2125 while (directory && (entry = readdir (directory)))
2127 convfn = dentry = entry->d_name;
2128 convlen = dentlen = D_NAMLEN (entry);
2130 if (rl_filename_rewrite_hook)
2132 convfn = (*rl_filename_rewrite_hook) (dentry, dentlen);
2133 convlen = (convfn == dentry) ? dentlen : strlen (convfn);
2136 /* Special case for no filename. If the user has disabled the
2137 `match-hidden-files' variable, skip filenames beginning with `.'.
2138 All other entries except "." and ".." match. */
2139 if (filename_len == 0)
2141 if (_rl_match_hidden_files == 0 && HIDDEN_FILE (entry->d_name))
2144 if (convfn[0] != '.' ||
2145 (convfn[1] && (convfn[1] != '.' || convfn[2])))
2150 /* Otherwise, if these match up to the length of filename, then
2152 if (_rl_completion_case_fold)
2154 if ((_rl_to_lower (convfn[0]) == _rl_to_lower (filename[0])) &&
2155 (convlen >= filename_len) &&
2156 (_rl_strnicmp (filename, convfn, filename_len) == 0))
2161 if ((convfn[0] == filename[0]) &&
2162 (convlen >= filename_len) &&
2163 (strncmp (filename, convfn, filename_len) == 0))
2173 closedir (directory);
2174 directory = (DIR *)NULL;
2179 dirname = (char *)NULL;
2184 filename = (char *)NULL;
2188 free (users_dirname);
2189 users_dirname = (char *)NULL;
2192 return (char *)NULL;
2196 /* dirname && (strcmp (dirname, ".") != 0) */
2197 if (dirname && (dirname[0] != '.' || dirname[1]))
2199 if (rl_complete_with_tilde_expansion && *users_dirname == '~')
2201 dirlen = strlen (dirname);
2202 temp = (char *)xmalloc (2 + dirlen + D_NAMLEN (entry));
2203 strcpy (temp, dirname);
2204 /* Canonicalization cuts off any final slash present. We
2205 may need to add it back. */
2206 if (dirname[dirlen - 1] != '/')
2208 temp[dirlen++] = '/';
2209 temp[dirlen] = '\0';
2214 dirlen = strlen (users_dirname);
2215 temp = (char *)xmalloc (2 + dirlen + D_NAMLEN (entry));
2216 strcpy (temp, users_dirname);
2217 /* Make sure that temp has a trailing slash here. */
2218 if (users_dirname[dirlen - 1] != '/')
2219 temp[dirlen++] = '/';
2222 strcpy (temp + dirlen, entry->d_name);
2225 temp = savestring (convfn);
2227 if (convfn != dentry)
2234 /* An initial implementation of a menu completion function a la tcsh. The
2235 first time (if the last readline command was not rl_old_menu_complete), we
2236 generate the list of matches. This code is very similar to the code in
2237 rl_complete_internal -- there should be a way to combine the two. Then,
2238 for each item in the list of matches, we insert the match in an undoable
2239 fashion, with the appropriate character appended (this happens on the
2240 second and subsequent consecutive calls to rl_old_menu_complete). When we
2241 hit the end of the match list, we restore the original unmatched text,
2242 ring the bell, and reset the counter to zero. */
2244 rl_old_menu_complete (count, invoking_key)
2245 int count, invoking_key;
2247 rl_compentry_func_t *our_func;
2248 int matching_filenames, found_quote;
2250 static char *orig_text;
2251 static char **matches = (char **)0;
2252 static int match_list_index = 0;
2253 static int match_list_size = 0;
2254 static int orig_start, orig_end;
2255 static char quote_char;
2256 static int delimiter;
2258 /* The first time through, we generate the list of matches and set things
2259 up to insert them. */
2260 if (rl_last_func != rl_old_menu_complete)
2262 /* Clean up from previous call, if any. */
2265 _rl_free_match_list (matches);
2267 match_list_index = match_list_size = 0;
2268 matches = (char **)NULL;
2270 rl_completion_invoking_key = invoking_key;
2272 RL_SETSTATE(RL_STATE_COMPLETING);
2274 /* Only the completion entry function can change these. */
2275 set_completion_defaults ('%');
2277 our_func = rl_menu_completion_entry_function;
2279 our_func = rl_completion_entry_function
2280 ? rl_completion_entry_function
2281 : rl_filename_completion_function;
2283 /* We now look backwards for the start of a filename/variable word. */
2284 orig_end = rl_point;
2285 found_quote = delimiter = 0;
2289 /* This (possibly) changes rl_point. If it returns a non-zero char,
2290 we know we have an open quote. */
2291 quote_char = _rl_find_completion_word (&found_quote, &delimiter);
2293 orig_start = rl_point;
2294 rl_point = orig_end;
2296 orig_text = rl_copy_text (orig_start, orig_end);
2297 matches = gen_completion_matches (orig_text, orig_start, orig_end,
2298 our_func, found_quote, quote_char);
2300 /* If we are matching filenames, the attempted completion function will
2301 have set rl_filename_completion_desired to a non-zero value. The basic
2302 rl_filename_completion_function does this. */
2303 matching_filenames = rl_filename_completion_desired;
2305 if (matches == 0 || postprocess_matches (&matches, matching_filenames) == 0)
2309 matches = (char **)0;
2311 orig_text = (char *)0;
2312 completion_changed_buffer = 0;
2313 RL_UNSETSTATE(RL_STATE_COMPLETING);
2317 RL_UNSETSTATE(RL_STATE_COMPLETING);
2319 for (match_list_size = 0; matches[match_list_size]; match_list_size++)
2321 /* matches[0] is lcd if match_list_size > 1, but the circular buffer
2322 code below should take care of it. */
2324 if (match_list_size > 1 && _rl_complete_show_all)
2325 display_matches (matches);
2328 /* Now we have the list of matches. Replace the text between
2329 rl_line_buffer[orig_start] and rl_line_buffer[rl_point] with
2330 matches[match_list_index], and add any necessary closing char. */
2332 if (matches == 0 || match_list_size == 0)
2336 matches = (char **)0;
2337 completion_changed_buffer = 0;
2341 match_list_index += count;
2342 if (match_list_index < 0)
2343 match_list_index += match_list_size;
2345 match_list_index %= match_list_size;
2347 if (match_list_index == 0 && match_list_size > 1)
2350 insert_match (orig_text, orig_start, MULT_MATCH, "e_char);
2354 insert_match (matches[match_list_index], orig_start, SINGLE_MATCH, "e_char);
2355 append_to_match (matches[match_list_index], delimiter, quote_char,
2356 strcmp (orig_text, matches[match_list_index]));
2359 completion_changed_buffer = 1;
2364 rl_menu_complete (count, ignore)
2367 rl_compentry_func_t *our_func;
2368 int matching_filenames, found_quote;
2370 static char *orig_text;
2371 static char **matches = (char **)0;
2372 static int match_list_index = 0;
2373 static int match_list_size = 0;
2374 static int nontrivial_lcd = 0;
2375 static int full_completion = 0; /* set to 1 if menu completion should reinitialize on next call */
2376 static int orig_start, orig_end;
2377 static char quote_char;
2378 static int delimiter;
2380 /* The first time through, we generate the list of matches and set things
2381 up to insert them. */
2382 if ((rl_last_func != rl_menu_complete && rl_last_func != rl_backward_menu_complete) || full_completion)
2384 /* Clean up from previous call, if any. */
2387 _rl_free_match_list (matches);
2389 match_list_index = match_list_size = 0;
2390 matches = (char **)NULL;
2392 full_completion = 0;
2394 RL_SETSTATE(RL_STATE_COMPLETING);
2396 /* Only the completion entry function can change these. */
2397 set_completion_defaults ('%');
2399 our_func = rl_menu_completion_entry_function;
2401 our_func = rl_completion_entry_function
2402 ? rl_completion_entry_function
2403 : rl_filename_completion_function;
2405 /* We now look backwards for the start of a filename/variable word. */
2406 orig_end = rl_point;
2407 found_quote = delimiter = 0;
2411 /* This (possibly) changes rl_point. If it returns a non-zero char,
2412 we know we have an open quote. */
2413 quote_char = _rl_find_completion_word (&found_quote, &delimiter);
2415 orig_start = rl_point;
2416 rl_point = orig_end;
2418 orig_text = rl_copy_text (orig_start, orig_end);
2419 matches = gen_completion_matches (orig_text, orig_start, orig_end,
2420 our_func, found_quote, quote_char);
2422 nontrivial_lcd = matches && strcmp (orig_text, matches[0]) != 0;
2424 /* If we are matching filenames, the attempted completion function will
2425 have set rl_filename_completion_desired to a non-zero value. The basic
2426 rl_filename_completion_function does this. */
2427 matching_filenames = rl_filename_completion_desired;
2429 if (matches == 0 || postprocess_matches (&matches, matching_filenames) == 0)
2433 matches = (char **)0;
2435 orig_text = (char *)0;
2436 completion_changed_buffer = 0;
2437 RL_UNSETSTATE(RL_STATE_COMPLETING);
2441 RL_UNSETSTATE(RL_STATE_COMPLETING);
2443 for (match_list_size = 0; matches[match_list_size]; match_list_size++)
2446 if (match_list_size == 0)
2450 matches = (char **)0;
2451 match_list_index = 0;
2452 completion_changed_buffer = 0;
2456 /* matches[0] is lcd if match_list_size > 1, but the circular buffer
2457 code below should take care of it. */
2460 insert_match (matches[0], orig_start, matches[1] ? MULT_MATCH : SINGLE_MATCH, "e_char);
2461 orig_end = orig_start + strlen (matches[0]);
2462 completion_changed_buffer = STREQ (orig_text, matches[0]) == 0;
2465 if (match_list_size > 1 && _rl_complete_show_all)
2467 display_matches (matches);
2468 /* If there are so many matches that the user has to be asked
2469 whether or not he wants to see the matches, menu completion
2471 if (rl_completion_query_items > 0 && match_list_size >= rl_completion_query_items)
2475 matches = (char **)0;
2476 full_completion = 1;
2480 else if (match_list_size <= 1)
2482 append_to_match (matches[0], delimiter, quote_char, nontrivial_lcd);
2483 full_completion = 1;
2488 /* Now we have the list of matches. Replace the text between
2489 rl_line_buffer[orig_start] and rl_line_buffer[rl_point] with
2490 matches[match_list_index], and add any necessary closing char. */
2492 if (matches == 0 || match_list_size == 0)
2496 matches = (char **)0;
2497 completion_changed_buffer = 0;
2501 match_list_index += count;
2502 if (match_list_index < 0)
2503 match_list_index += match_list_size;
2505 match_list_index %= match_list_size;
2507 if (match_list_index == 0 && match_list_size > 1)
2510 insert_match (matches[0], orig_start, MULT_MATCH, "e_char);
2514 insert_match (matches[match_list_index], orig_start, SINGLE_MATCH, "e_char);
2515 append_to_match (matches[match_list_index], delimiter, quote_char,
2516 strcmp (orig_text, matches[match_list_index]));
2519 completion_changed_buffer = 1;
2524 rl_backward_menu_complete (count, key)
2527 /* Positive arguments to backward-menu-complete translate into negative
2528 arguments for menu-complete, and vice versa. */
2529 return (rl_menu_complete (-count, key));