1 /* complete.c -- filename completion for readline. */
3 /* Copyright (C) 1987-2011 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 int complete_fncmp PARAMS((const char *, int, const char *, int));
123 static void display_matches PARAMS((char **));
124 static int compute_lcd_of_matches PARAMS((char **, int, const char *));
125 static int postprocess_matches PARAMS((char ***, int));
126 static int complete_get_screenwidth PARAMS((void));
128 static char *make_quoted_replacement PARAMS((char *, int, char *));
130 /* **************************************************************** */
132 /* Completion matching, from readline's point of view. */
134 /* **************************************************************** */
136 /* Variables known only to the readline library. */
138 /* If non-zero, non-unique completions always show the list of matches. */
139 int _rl_complete_show_all = 0;
141 /* If non-zero, non-unique completions show the list of matches, unless it
142 is not possible to do partial completion and modify the line. */
143 int _rl_complete_show_unmodified = 0;
145 /* If non-zero, completed directory names have a slash appended. */
146 int _rl_complete_mark_directories = 1;
148 /* If non-zero, the symlinked directory completion behavior introduced in
149 readline-4.2a is disabled, and symlinks that point to directories have
150 a slash appended (subject to the value of _rl_complete_mark_directories).
151 This is user-settable via the mark-symlinked-directories variable. */
152 int _rl_complete_mark_symlink_dirs = 0;
154 /* If non-zero, completions are printed horizontally in alphabetical order,
156 int _rl_print_completions_horizontally;
158 /* Non-zero means that case is not significant in filename completion. */
159 #if defined (__MSDOS__) && !defined (__DJGPP__)
160 int _rl_completion_case_fold = 1;
162 int _rl_completion_case_fold = 0;
165 /* Non-zero means that `-' and `_' are equivalent when comparing filenames
167 int _rl_completion_case_map = 0;
169 /* If zero, don't match hidden files (filenames beginning with a `.' on
170 Unix) when doing filename completion. */
171 int _rl_match_hidden_files = 1;
173 /* Length in characters of a common prefix replaced with an ellipsis (`...')
174 when displaying completion matches. Matches whose printable portion has
175 more than this number of displaying characters in common will have the common
176 display prefix replaced with an ellipsis. */
177 int _rl_completion_prefix_display_length = 0;
179 /* The readline-private number of screen columns to use when displaying
180 matches. If < 0 or > _rl_screenwidth, it is ignored. */
181 int _rl_completion_columns = -1;
183 /* Global variables available to applications using readline. */
185 #if defined (VISIBLE_STATS)
186 /* Non-zero means add an additional character to each filename displayed
187 during listing completion iff rl_filename_completion_desired which helps
188 to indicate the type of file being listed. */
189 int rl_visible_stats = 0;
190 #endif /* VISIBLE_STATS */
192 /* If non-zero, when completing in the middle of a word, don't insert
193 characters from the match that match characters following point in
194 the word. This means, for instance, completing when the cursor is
195 after the `e' in `Makefile' won't result in `Makefilefile'. */
196 int _rl_skip_completed_text = 0;
198 /* If non-zero, menu completion displays the common prefix first in the
199 cycle of possible completions instead of the last. */
200 int _rl_menu_complete_prefix_first = 0;
202 /* If non-zero, then this is the address of a function to call when
203 completing on a directory name. The function is called with
204 the address of a string (the current directory name) as an arg. */
205 rl_icppfunc_t *rl_directory_completion_hook = (rl_icppfunc_t *)NULL;
207 rl_icppfunc_t *rl_directory_rewrite_hook = (rl_icppfunc_t *)NULL;
209 /* If non-zero, this is the address of a function to call when reading
210 directory entries from the filesystem for completion and comparing
211 them to the partial word to be completed. The function should
212 either return its first argument (if no conversion takes place) or
213 newly-allocated memory. This can, for instance, convert filenames
214 between character sets for comparison against what's typed at the
215 keyboard. The returned value is what is added to the list of
216 matches. The second argument is the length of the filename to be
218 rl_dequote_func_t *rl_filename_rewrite_hook = (rl_dequote_func_t *)NULL;
220 /* Non-zero means readline completion functions perform tilde expansion. */
221 int rl_complete_with_tilde_expansion = 0;
223 /* Pointer to the generator function for completion_matches ().
224 NULL means to use rl_filename_completion_function (), the default filename
226 rl_compentry_func_t *rl_completion_entry_function = (rl_compentry_func_t *)NULL;
228 /* Pointer to generator function for rl_menu_complete (). NULL means to use
229 *rl_completion_entry_function (see above). */
230 rl_compentry_func_t *rl_menu_completion_entry_function = (rl_compentry_func_t *)NULL;
232 /* Pointer to alternative function to create matches.
233 Function is called with TEXT, START, and END.
234 START and END are indices in RL_LINE_BUFFER saying what the boundaries
236 If this function exists and returns NULL then call the value of
237 rl_completion_entry_function to try to match, otherwise use the
238 array of strings returned. */
239 rl_completion_func_t *rl_attempted_completion_function = (rl_completion_func_t *)NULL;
241 /* Non-zero means to suppress normal filename completion after the
242 user-specified completion function has been called. */
243 int rl_attempted_completion_over = 0;
245 /* Set to a character indicating the type of completion being performed
246 by rl_complete_internal, available for use by application completion
248 int rl_completion_type = 0;
250 /* Up to this many items will be displayed in response to a
251 possible-completions call. After that, we ask the user if
252 she is sure she wants to see them all. A negative value means
254 int rl_completion_query_items = 100;
256 int _rl_page_completions = 1;
258 /* The basic list of characters that signal a break between words for the
259 completer routine. The contents of this variable is what breaks words
260 in the shell, i.e. " \t\n\"\\'`@$><=" */
261 const char *rl_basic_word_break_characters = " \t\n\"\\'`@$><=;|&{("; /* }) */
263 /* List of basic quoting characters. */
264 const char *rl_basic_quote_characters = "\"'";
266 /* The list of characters that signal a break between words for
267 rl_complete_internal. The default list is the contents of
268 rl_basic_word_break_characters. */
269 /*const*/ char *rl_completer_word_break_characters = (/*const*/ char *)NULL;
271 /* Hook function to allow an application to set the completion word
272 break characters before readline breaks up the line. Allows
273 position-dependent word break characters. */
274 rl_cpvfunc_t *rl_completion_word_break_hook = (rl_cpvfunc_t *)NULL;
276 /* List of characters which can be used to quote a substring of the line.
277 Completion occurs on the entire substring, and within the substring
278 rl_completer_word_break_characters are treated as any other character,
279 unless they also appear within this list. */
280 const char *rl_completer_quote_characters = (const char *)NULL;
282 /* List of characters that should be quoted in filenames by the completer. */
283 const char *rl_filename_quote_characters = (const char *)NULL;
285 /* List of characters that are word break characters, but should be left
286 in TEXT when it is passed to the completion function. The shell uses
287 this to help determine what kind of completing to do. */
288 const char *rl_special_prefixes = (const char *)NULL;
290 /* If non-zero, then disallow duplicates in the matches. */
291 int rl_ignore_completion_duplicates = 1;
293 /* Non-zero means that the results of the matches are to be treated
294 as filenames. This is ALWAYS zero on entry, and can only be changed
295 within a completion entry finder function. */
296 int rl_filename_completion_desired = 0;
298 /* Non-zero means that the results of the matches are to be quoted using
299 double quotes (or an application-specific quoting mechanism) if the
300 filename contains any characters in rl_filename_quote_chars. This is
301 ALWAYS non-zero on entry, and can only be changed within a completion
302 entry finder function. */
303 int rl_filename_quoting_desired = 1;
305 /* This function, if defined, is called by the completer when real
306 filename completion is done, after all the matching names have been
307 generated. It is passed a (char**) known as matches in the code below.
308 It consists of a NULL-terminated array of pointers to potential
309 matching strings. The 1st element (matches[0]) is the maximal
310 substring that is common to all matches. This function can re-arrange
311 the list of matches as required, but all elements of the array must be
312 free()'d if they are deleted. The main intent of this function is
313 to implement FIGNORE a la SunOS csh. */
314 rl_compignore_func_t *rl_ignore_some_completions_function = (rl_compignore_func_t *)NULL;
316 /* Set to a function to quote a filename in an application-specific fashion.
317 Called with the text to quote, the type of match found (single or multiple)
318 and a pointer to the quoting character to be used, which the function can
320 rl_quote_func_t *rl_filename_quoting_function = rl_quote_filename;
322 /* Function to call to remove quoting characters from a filename. Called
323 before completion is attempted, so the embedded quotes do not interfere
324 with matching names in the file system. Readline doesn't do anything
325 with this; it's set only by applications. */
326 rl_dequote_func_t *rl_filename_dequoting_function = (rl_dequote_func_t *)NULL;
328 /* Function to call to decide whether or not a word break character is
329 quoted. If a character is quoted, it does not break words for the
331 rl_linebuf_func_t *rl_char_is_quoted_p = (rl_linebuf_func_t *)NULL;
333 /* If non-zero, the completion functions don't append anything except a
334 possible closing quote. This is set to 0 by rl_complete_internal and
335 may be changed by an application-specific completion function. */
336 int rl_completion_suppress_append = 0;
338 /* Character appended to completed words when at the end of the line. The
339 default is a space. */
340 int rl_completion_append_character = ' ';
342 /* If non-zero, the completion functions don't append any closing quote.
343 This is set to 0 by rl_complete_internal and may be changed by an
344 application-specific completion function. */
345 int rl_completion_suppress_quote = 0;
347 /* Set to any quote character readline thinks it finds before any application
348 completion function is called. */
349 int rl_completion_quote_character;
351 /* Set to a non-zero value if readline found quoting anywhere in the word to
352 be completed; set before any application completion function is called. */
353 int rl_completion_found_quote;
355 /* If non-zero, a slash will be appended to completed filenames that are
356 symbolic links to directory names, subject to the value of the
357 mark-directories variable (which is user-settable). This exists so
358 that application completion functions can override the user's preference
359 (set via the mark-symlinked-directories variable) if appropriate.
360 It's set to the value of _rl_complete_mark_symlink_dirs in
361 rl_complete_internal before any application-specific completion
362 function is called, so without that function doing anything, the user's
363 preferences are honored. */
364 int rl_completion_mark_symlink_dirs;
366 /* If non-zero, inhibit completion (temporarily). */
367 int rl_inhibit_completion;
369 /* Set to the last key used to invoke one of the completion functions */
370 int rl_completion_invoking_key;
372 /* If non-zero, sort the completion matches. On by default. */
373 int rl_sort_completion_matches = 1;
375 /* Variables local to this file. */
377 /* Local variable states what happened during the last completion attempt. */
378 static int completion_changed_buffer;
380 /* The result of the query to the user about displaying completion matches */
381 static int completion_y_or_n;
383 /*************************************/
385 /* Bindable completion functions */
387 /*************************************/
389 /* Complete the word at or before point. You have supplied the function
390 that does the initial simple matching selection algorithm (see
391 rl_completion_matches ()). The default is to do filename completion. */
393 rl_complete (ignore, invoking_key)
394 int ignore, invoking_key;
396 rl_completion_invoking_key = invoking_key;
398 if (rl_inhibit_completion)
399 return (_rl_insert_char (ignore, invoking_key));
400 else if (rl_last_func == rl_complete && !completion_changed_buffer)
401 return (rl_complete_internal ('?'));
402 else if (_rl_complete_show_all)
403 return (rl_complete_internal ('!'));
404 else if (_rl_complete_show_unmodified)
405 return (rl_complete_internal ('@'));
407 return (rl_complete_internal (TAB));
410 /* List the possible completions. See description of rl_complete (). */
412 rl_possible_completions (ignore, invoking_key)
413 int ignore, invoking_key;
415 rl_completion_invoking_key = invoking_key;
416 return (rl_complete_internal ('?'));
420 rl_insert_completions (ignore, invoking_key)
421 int ignore, invoking_key;
423 rl_completion_invoking_key = invoking_key;
424 return (rl_complete_internal ('*'));
427 /* Return the correct value to pass to rl_complete_internal performing
428 the same tests as rl_complete. This allows consecutive calls to an
429 application's completion function to list possible completions and for
430 an application-specific completion function to honor the
431 show-all-if-ambiguous readline variable. */
433 rl_completion_mode (cfunc)
434 rl_command_func_t *cfunc;
436 if (rl_last_func == cfunc && !completion_changed_buffer)
438 else if (_rl_complete_show_all)
440 else if (_rl_complete_show_unmodified)
446 /************************************/
448 /* Completion utility functions */
450 /************************************/
452 /* Reset readline state on a signal or other event. */
454 _rl_reset_completion_state ()
456 rl_completion_found_quote = 0;
457 rl_completion_quote_character = 0;
460 /* Set default values for readline word completion. These are the variables
461 that application completion functions can change or inspect. */
463 set_completion_defaults (what_to_do)
466 /* Only the completion entry function can change these. */
467 rl_filename_completion_desired = 0;
468 rl_filename_quoting_desired = 1;
469 rl_completion_type = what_to_do;
470 rl_completion_suppress_append = rl_completion_suppress_quote = 0;
471 rl_completion_append_character = ' ';
473 /* The completion entry function may optionally change this. */
474 rl_completion_mark_symlink_dirs = _rl_complete_mark_symlink_dirs;
477 /* The user must press "y" or "n". Non-zero return means "y" pressed. */
479 get_y_or_n (for_pager)
484 /* Disabled for GDB due to the gdb.base/readline-ask.exp regression.
485 [patch] testsuite: Test readline-6.2 "ask" regression
486 http://sourceware.org/ml/gdb-patches/2011-05/msg00002.html */
488 /* For now, disable pager in callback mode, until we later convert to state
489 driven functions. Have to wait until next major version to add new
490 state definition, since it will change value of RL_STATE_DONE. */
491 #if defined (READLINE_CALLBACKS)
492 if (RL_ISSTATE (RL_STATE_CALLBACK))
499 RL_SETSTATE(RL_STATE_MOREINPUT);
501 RL_UNSETSTATE(RL_STATE_MOREINPUT);
503 if (c == 'y' || c == 'Y' || c == ' ')
505 if (c == 'n' || c == 'N' || c == RUBOUT)
507 if (c == ABORT_CHAR || c < 0)
508 _rl_abort_internal ();
509 if (for_pager && (c == NEWLINE || c == RETURN))
511 if (for_pager && (c == 'q' || c == 'Q'))
518 _rl_internal_pager (lines)
523 fprintf (rl_outstream, "--More--");
524 fflush (rl_outstream);
526 _rl_erase_entire_line ();
536 path_isdir (filename)
537 const char *filename;
541 return (stat (filename, &finfo) == 0 && S_ISDIR (finfo.st_mode));
544 #if defined (VISIBLE_STATS)
545 /* Return the character which best describes FILENAME.
546 `@' for symbolic links
551 `%' for character special devices
552 `#' for block special devices */
560 /* Short-circuit a //server on cygwin, since that will always behave as
563 if (filename[0] == '/' && filename[1] == '/' && strchr (filename+2, '/') == 0)
567 #if defined (HAVE_LSTAT) && defined (S_ISLNK)
568 r = lstat (filename, &finfo);
570 r = stat (filename, &finfo);
577 if (S_ISDIR (finfo.st_mode))
579 #if defined (S_ISCHR)
580 else if (S_ISCHR (finfo.st_mode))
583 #if defined (S_ISBLK)
584 else if (S_ISBLK (finfo.st_mode))
587 #if defined (S_ISLNK)
588 else if (S_ISLNK (finfo.st_mode))
591 #if defined (S_ISSOCK)
592 else if (S_ISSOCK (finfo.st_mode))
594 #endif /* S_ISSOCK */
595 #if defined (S_ISFIFO)
596 else if (S_ISFIFO (finfo.st_mode))
599 else if (S_ISREG (finfo.st_mode))
601 if (access (filename, X_OK) == 0)
606 #endif /* VISIBLE_STATS */
608 /* Return the portion of PATHNAME that should be output when listing
609 possible completions. If we are hacking filename completion, we
610 are only interested in the basename, the portion following the
611 final slash. Otherwise, we return what we were passed. Since
612 printing empty strings is not very informative, if we're doing
613 filename completion, and the basename is the empty string, we look
614 for the previous slash and return the portion following that. If
615 there's no previous slash, we just return what we were passed. */
617 printable_part (pathname)
622 if (rl_filename_completion_desired == 0) /* don't need to do anything */
625 temp = strrchr (pathname, '/');
626 #if defined (__MSDOS__)
627 if (temp == 0 && ISALPHA ((unsigned char)pathname[0]) && pathname[1] == ':')
631 if (temp == 0 || *temp == '\0')
633 /* If the basename is NULL, we might have a pathname like '/usr/src/'.
634 Look for a previous slash and, if one is found, return the portion
635 following that slash. If there's no previous slash, just return the
636 pathname we were passed. */
637 else if (temp[1] == '\0')
639 for (x = temp - 1; x > pathname; x--)
642 return ((*x == '/') ? x + 1 : pathname);
648 /* Compute width of STRING when displayed on screen by print_filename */
654 #if defined (HANDLE_MULTIBYTE)
660 left = strlen (string) + 1;
661 memset (&ps, 0, sizeof (mbstate_t));
667 if (CTRL_CHAR (string[pos]) || string[pos] == RUBOUT)
674 #if defined (HANDLE_MULTIBYTE)
675 clen = mbrtowc (&wc, string + pos, left - pos, &ps);
676 if (MB_INVALIDCH (clen))
680 memset (&ps, 0, sizeof (mbstate_t));
682 else if (MB_NULLWCH (clen))
688 width += (w >= 0) ? w : 1;
700 #define ELLIPSIS_LEN 3
703 fnprint (to_print, prefix_bytes)
704 const char *to_print;
709 #if defined (HANDLE_MULTIBYTE)
716 end = to_print + strlen (to_print) + 1;
717 memset (&ps, 0, sizeof (mbstate_t));
722 /* Don't print only the ellipsis if the common prefix is one of the
723 possible completions */
724 if (to_print[prefix_bytes] == '\0')
731 ellipsis = (to_print[prefix_bytes] == '.') ? '_' : '.';
732 for (w = 0; w < ELLIPSIS_LEN; w++)
733 putc (ellipsis, rl_outstream);
734 printed_len = ELLIPSIS_LEN;
737 s = to_print + prefix_bytes;
742 putc ('^', rl_outstream);
743 putc (UNCTRL (*s), rl_outstream);
746 #if defined (HANDLE_MULTIBYTE)
747 memset (&ps, 0, sizeof (mbstate_t));
750 else if (*s == RUBOUT)
752 putc ('^', rl_outstream);
753 putc ('?', rl_outstream);
756 #if defined (HANDLE_MULTIBYTE)
757 memset (&ps, 0, sizeof (mbstate_t));
762 #if defined (HANDLE_MULTIBYTE)
763 tlen = mbrtowc (&wc, s, end - s, &ps);
764 if (MB_INVALIDCH (tlen))
768 memset (&ps, 0, sizeof (mbstate_t));
770 else if (MB_NULLWCH (tlen))
775 width = (w >= 0) ? w : 1;
777 fwrite (s, 1, tlen, rl_outstream);
779 printed_len += width;
781 putc (*s, rl_outstream);
791 /* Output TO_PRINT to rl_outstream. If VISIBLE_STATS is defined and we
792 are using it, check for and output a single character for `special'
793 filenames. Return the number of characters we output. */
796 print_filename (to_print, full_pathname, prefix_bytes)
797 char *to_print, *full_pathname;
800 int printed_len, extension_char, slen, tlen;
801 char *s, c, *new_full_pathname, *dn;
804 printed_len = fnprint (to_print, prefix_bytes);
806 #if defined (VISIBLE_STATS)
807 if (rl_filename_completion_desired && (rl_visible_stats || _rl_complete_mark_directories))
809 if (rl_filename_completion_desired && _rl_complete_mark_directories)
812 /* If to_print != full_pathname, to_print is the basename of the
813 path passed. In this case, we try to expand the directory
814 name before checking for the stat character. */
815 if (to_print != full_pathname)
817 /* Terminate the directory name. */
821 /* If setting the last slash in full_pathname to a NUL results in
822 full_pathname being the empty string, we are trying to complete
823 files in the root directory. If we pass a null string to the
824 bash directory completion hook, for example, it will expand it
825 to the current directory. We just want the `/'. */
826 if (full_pathname == 0 || *full_pathname == 0)
828 else if (full_pathname[0] != '/')
830 else if (full_pathname[1] == 0)
831 dn = "//"; /* restore trailing slash to `//' */
832 else if (full_pathname[1] == '/' && full_pathname[2] == 0)
833 dn = "/"; /* don't turn /// into // */
836 s = tilde_expand (dn);
837 if (rl_directory_completion_hook)
838 (*rl_directory_completion_hook) (&s);
841 tlen = strlen (to_print);
842 new_full_pathname = (char *)xmalloc (slen + tlen + 2);
843 strcpy (new_full_pathname, s);
844 if (s[slen - 1] == '/')
847 new_full_pathname[slen] = '/';
848 new_full_pathname[slen] = '/';
849 strcpy (new_full_pathname + slen + 1, to_print);
851 #if defined (VISIBLE_STATS)
852 if (rl_visible_stats)
853 extension_char = stat_char (new_full_pathname);
856 if (path_isdir (new_full_pathname))
857 extension_char = '/';
859 xfree (new_full_pathname);
864 s = tilde_expand (full_pathname);
865 #if defined (VISIBLE_STATS)
866 if (rl_visible_stats)
867 extension_char = stat_char (s);
871 extension_char = '/';
877 putc (extension_char, rl_outstream);
886 rl_quote_filename (s, rtype, qcp)
893 r = (char *)xmalloc (strlen (s) + 2);
894 *r = *rl_completer_quote_characters;
897 *qcp = *rl_completer_quote_characters;
901 /* Find the bounds of the current word for completion purposes, and leave
902 rl_point set to the end of the word. This function skips quoted
903 substrings (characters between matched pairs of characters in
904 rl_completer_quote_characters). First we try to find an unclosed
905 quoted substring on which to do matching. If one is not found, we use
906 the word break characters to find the boundaries of the current word.
907 We call an application-specific function to decide whether or not a
908 particular word break character is quoted; if that function returns a
909 non-zero result, the character does not break a word. This function
910 returns the opening quote character if we found an unclosed quoted
911 substring, '\0' otherwise. FP, if non-null, is set to a value saying
912 which (shell-like) quote characters we found (single quote, double
913 quote, or backslash) anywhere in the string. DP, if non-null, is set to
914 the value of the delimiter character that caused a word break. */
917 _rl_find_completion_word (fp, dp)
920 int scan, end, found_quote, delimiter, pass_next, isbrk;
921 char quote_char, *brkchars;
924 found_quote = delimiter = 0;
928 if (rl_completion_word_break_hook)
929 brkchars = (*rl_completion_word_break_hook) ();
931 brkchars = rl_completer_word_break_characters;
933 if (rl_completer_quote_characters)
935 /* We have a list of characters which can be used in pairs to
936 quote substrings for the completer. Try to find the start
937 of an unclosed quoted substring. */
938 /* FOUND_QUOTE is set so we know what kind of quotes we found. */
939 for (scan = pass_next = 0; scan < end; scan = MB_NEXTCHAR (rl_line_buffer, scan, 1, MB_FIND_ANY))
947 /* Shell-like semantics for single quotes -- don't allow backslash
948 to quote anything in single quotes, especially not the closing
949 quote. If you don't like this, take out the check on the value
951 if (quote_char != '\'' && rl_line_buffer[scan] == '\\')
954 found_quote |= RL_QF_BACKSLASH;
958 if (quote_char != '\0')
960 /* Ignore everything until the matching close quote char. */
961 if (rl_line_buffer[scan] == quote_char)
963 /* Found matching close. Abandon this substring. */
968 else if (strchr (rl_completer_quote_characters, rl_line_buffer[scan]))
970 /* Found start of a quoted substring. */
971 quote_char = rl_line_buffer[scan];
973 /* Shell-like quoting conventions. */
974 if (quote_char == '\'')
975 found_quote |= RL_QF_SINGLE_QUOTE;
976 else if (quote_char == '"')
977 found_quote |= RL_QF_DOUBLE_QUOTE;
979 found_quote |= RL_QF_OTHER_QUOTE;
984 if (rl_point == end && quote_char == '\0')
986 /* We didn't find an unclosed quoted substring upon which to do
987 completion, so use the word break characters to find the
988 substring on which to complete. */
989 while (rl_point = MB_PREVCHAR (rl_line_buffer, rl_point, MB_FIND_ANY))
991 scan = rl_line_buffer[rl_point];
993 if (strchr (brkchars, scan) == 0)
996 /* Call the application-specific function to tell us whether
997 this word break character is quoted and should be skipped. */
998 if (rl_char_is_quoted_p && found_quote &&
999 (*rl_char_is_quoted_p) (rl_line_buffer, rl_point))
1002 /* Convoluted code, but it avoids an n^2 algorithm with calls
1003 to char_is_quoted. */
1008 /* If we are at an unquoted word break, then advance past it. */
1009 scan = rl_line_buffer[rl_point];
1011 /* If there is an application-specific function to say whether or not
1012 a character is quoted and we found a quote character, let that
1013 function decide whether or not a character is a word break, even
1014 if it is found in rl_completer_word_break_characters. Don't bother
1015 if we're at the end of the line, though. */
1018 if (rl_char_is_quoted_p)
1019 isbrk = (found_quote == 0 ||
1020 (*rl_char_is_quoted_p) (rl_line_buffer, rl_point) == 0) &&
1021 strchr (brkchars, scan) != 0;
1023 isbrk = strchr (brkchars, scan) != 0;
1027 /* If the character that caused the word break was a quoting
1028 character, then remember it as the delimiter. */
1029 if (rl_basic_quote_characters &&
1030 strchr (rl_basic_quote_characters, scan) &&
1031 (end - rl_point) > 1)
1034 /* If the character isn't needed to determine something special
1035 about what kind of completion to perform, then advance past it. */
1036 if (rl_special_prefixes == 0 || strchr (rl_special_prefixes, scan) == 0)
1046 return (quote_char);
1050 gen_completion_matches (text, start, end, our_func, found_quote, quote_char)
1053 rl_compentry_func_t *our_func;
1054 int found_quote, quote_char;
1058 rl_completion_found_quote = found_quote;
1059 rl_completion_quote_character = quote_char;
1061 /* If the user wants to TRY to complete, but then wants to give
1062 up and use the default completion function, they set the
1063 variable rl_attempted_completion_function. */
1064 if (rl_attempted_completion_function)
1066 _rl_interrupt_immediately++;
1067 matches = (*rl_attempted_completion_function) (text, start, end);
1068 if (_rl_interrupt_immediately > 0)
1069 _rl_interrupt_immediately--;
1071 if (matches || rl_attempted_completion_over)
1073 rl_attempted_completion_over = 0;
1078 /* XXX -- filename dequoting moved into rl_filename_completion_function */
1080 matches = rl_completion_matches (text, our_func);
1084 /* Filter out duplicates in MATCHES. This frees up the strings in
1087 remove_duplicate_matches (matches)
1090 char *lowest_common;
1095 /* Sort the items. */
1096 for (i = 0; matches[i]; i++)
1099 /* Sort the array without matches[0], since we need it to
1100 stay in place no matter what. */
1101 if (i && rl_sort_completion_matches)
1102 qsort (matches+1, i-1, sizeof (char *), (QSFUNC *)_rl_qsort_string_compare);
1104 /* Remember the lowest common denominator for it may be unique. */
1105 lowest_common = savestring (matches[0]);
1107 for (i = newlen = 0; matches[i + 1]; i++)
1109 if (strcmp (matches[i], matches[i + 1]) == 0)
1112 matches[i] = (char *)&dead_slot;
1118 /* We have marked all the dead slots with (char *)&dead_slot.
1119 Copy all the non-dead entries into a new array. */
1120 temp_array = (char **)xmalloc ((3 + newlen) * sizeof (char *));
1121 for (i = j = 1; matches[i]; i++)
1123 if (matches[i] != (char *)&dead_slot)
1124 temp_array[j++] = matches[i];
1126 temp_array[j] = (char *)NULL;
1128 if (matches[0] != (char *)&dead_slot)
1131 /* Place the lowest common denominator back in [0]. */
1132 temp_array[0] = lowest_common;
1134 /* If there is one string left, and it is identical to the
1135 lowest common denominator, then the LCD is the string to
1137 if (j == 2 && strcmp (temp_array[0], temp_array[1]) == 0)
1139 xfree (temp_array[1]);
1140 temp_array[1] = (char *)NULL;
1142 return (temp_array);
1145 /* Find the common prefix of the list of matches, and put it into
1148 compute_lcd_of_matches (match_list, matches, text)
1153 register int i, c1, c2, si;
1154 int low; /* Count of max-matched characters. */
1155 char *dtext; /* dequoted TEXT, if needed */
1156 #if defined (HANDLE_MULTIBYTE)
1162 /* If only one match, just use that. Otherwise, compare each
1163 member of the list with the next, finding out where they
1167 match_list[0] = match_list[1];
1168 match_list[1] = (char *)NULL;
1172 for (i = 1, low = 100000; i < matches; i++)
1174 #if defined (HANDLE_MULTIBYTE)
1175 if (MB_CUR_MAX > 1 && rl_byte_oriented == 0)
1177 memset (&ps1, 0, sizeof (mbstate_t));
1178 memset (&ps2, 0, sizeof (mbstate_t));
1181 if (_rl_completion_case_fold)
1184 (c1 = _rl_to_lower(match_list[i][si])) &&
1185 (c2 = _rl_to_lower(match_list[i + 1][si]));
1187 #if defined (HANDLE_MULTIBYTE)
1188 if (MB_CUR_MAX > 1 && rl_byte_oriented == 0)
1190 v = mbrtowc (&wc1, match_list[i]+si, strlen (match_list[i]+si), &ps1);
1191 mbrtowc (&wc2, match_list[i+1]+si, strlen (match_list[i+1]+si), &ps2);
1192 wc1 = towlower (wc1);
1193 wc2 = towlower (wc2);
1207 (c1 = match_list[i][si]) &&
1208 (c2 = match_list[i + 1][si]);
1210 #if defined (HANDLE_MULTIBYTE)
1211 if (MB_CUR_MAX > 1 && rl_byte_oriented == 0)
1215 if (!_rl_compare_chars (match_list[i], si, &ps1, match_list[i+1], si, &ps2))
1217 else if ((v = _rl_get_char_len (&match_list[i][si], &ps_back)) > 1)
1230 /* If there were multiple matches, but none matched up to even the
1231 first character, and the user typed something, use that as the
1232 value of matches[0]. */
1233 if (low == 0 && text && *text)
1235 match_list[0] = (char *)xmalloc (strlen (text) + 1);
1236 strcpy (match_list[0], text);
1240 match_list[0] = (char *)xmalloc (low + 1);
1242 /* XXX - this might need changes in the presence of multibyte chars */
1244 /* If we are ignoring case, try to preserve the case of the string
1245 the user typed in the face of multiple matches differing in case. */
1246 if (_rl_completion_case_fold)
1248 /* We're making an assumption here:
1249 IF we're completing filenames AND
1250 the application has defined a filename dequoting function AND
1251 we found a quote character AND
1252 the application has requested filename quoting
1254 we assume that TEXT was dequoted before checking against
1255 the file system and needs to be dequoted here before we
1256 check against the list of matches
1258 dtext = (char *)NULL;
1259 if (rl_filename_completion_desired &&
1260 rl_filename_dequoting_function &&
1261 rl_completion_found_quote &&
1262 rl_filename_quoting_desired)
1264 dtext = (*rl_filename_dequoting_function) ((char *)text, rl_completion_quote_character);
1268 /* sort the list to get consistent answers. */
1269 qsort (match_list+1, matches, sizeof(char *), (QSFUNC *)_rl_qsort_string_compare);
1274 for (i = 1; i <= matches; i++)
1275 if (strncmp (match_list[i], text, si) == 0)
1277 strncpy (match_list[0], match_list[i], low);
1280 /* no casematch, use first entry */
1282 strncpy (match_list[0], match_list[1], low);
1285 /* otherwise, just use the text the user typed. */
1286 strncpy (match_list[0], text, low);
1291 strncpy (match_list[0], match_list[1], low);
1293 match_list[0][low] = '\0';
1300 postprocess_matches (matchesp, matching_filenames)
1302 int matching_filenames;
1304 char *t, **matches, **temp_matches;
1307 matches = *matchesp;
1312 /* It seems to me that in all the cases we handle we would like
1313 to ignore duplicate possiblilities. Scan for the text to
1314 insert being identical to the other completions. */
1315 if (rl_ignore_completion_duplicates)
1317 temp_matches = remove_duplicate_matches (matches);
1319 matches = temp_matches;
1322 /* If we are matching filenames, then here is our chance to
1323 do clever processing by re-examining the list. Call the
1324 ignore function with the array as a parameter. It can
1325 munge the array, deleting matches as it desires. */
1326 if (rl_ignore_some_completions_function && matching_filenames)
1328 for (nmatch = 1; matches[nmatch]; nmatch++)
1330 (void)(*rl_ignore_some_completions_function) (matches);
1331 if (matches == 0 || matches[0] == 0)
1334 *matchesp = (char **)0;
1339 /* If we removed some matches, recompute the common prefix. */
1340 for (i = 1; matches[i]; i++)
1342 if (i > 1 && i < nmatch)
1345 compute_lcd_of_matches (matches, i - 1, t);
1351 *matchesp = matches;
1356 complete_get_screenwidth ()
1361 cols = _rl_completion_columns;
1362 if (cols >= 0 && cols <= _rl_screenwidth)
1364 envcols = getenv ("COLUMNS");
1365 if (envcols && *envcols)
1366 cols = atoi (envcols);
1367 if (cols >= 0 && cols <= _rl_screenwidth)
1369 return _rl_screenwidth;
1372 /* A convenience function for displaying a list of strings in
1373 columnar format on readline's output stream. MATCHES is the list
1374 of strings, in argv format, LEN is the number of strings in MATCHES,
1375 and MAX is the length of the longest string in MATCHES. */
1377 rl_display_match_list (matches, len, max)
1381 int count, limit, printed_len, lines, cols;
1382 int i, j, k, l, common_length, sind;
1385 /* Find the length of the prefix common to all items: length as displayed
1386 characters (common_length) and as a byte index into the matches (sind) */
1387 common_length = sind = 0;
1388 if (_rl_completion_prefix_display_length > 0)
1390 t = printable_part (matches[0]);
1391 temp = strrchr (t, '/');
1392 common_length = temp ? fnwidth (temp) : fnwidth (t);
1393 sind = temp ? strlen (temp) : strlen (t);
1395 if (common_length > _rl_completion_prefix_display_length && common_length > ELLIPSIS_LEN)
1396 max -= common_length - ELLIPSIS_LEN;
1398 common_length = sind = 0;
1401 /* How many items of MAX length can we fit in the screen window? */
1402 cols = complete_get_screenwidth ();
1405 if (limit != 1 && (limit * max == cols))
1408 /* If cols == 0, limit will end up -1 */
1409 if (cols < _rl_screenwidth && limit < 0)
1412 /* Avoid a possible floating exception. If max > cols,
1413 limit will be 0 and a divide-by-zero fault will result. */
1417 /* How many iterations of the printing loop? */
1418 count = (len + (limit - 1)) / limit;
1420 /* Watch out for special case. If LEN is less than LIMIT, then
1421 just do the inner printing loop.
1422 0 < len <= limit implies count = 1. */
1424 /* Sort the items if they are not already sorted. */
1425 if (rl_ignore_completion_duplicates == 0 && rl_sort_completion_matches)
1426 qsort (matches + 1, len, sizeof (char *), (QSFUNC *)_rl_qsort_string_compare);
1431 if (_rl_print_completions_horizontally == 0)
1433 /* Print the sorted items, up-and-down alphabetically, like ls. */
1434 for (i = 1; i <= count; i++)
1436 for (j = 0, l = i; j < limit; j++)
1438 if (l > len || matches[l] == 0)
1442 temp = printable_part (matches[l]);
1443 printed_len = print_filename (temp, matches[l], sind);
1446 for (k = 0; k < max - printed_len; k++)
1447 putc (' ', rl_outstream);
1453 if (_rl_page_completions && lines >= (_rl_screenheight - 1) && i < count)
1455 lines = _rl_internal_pager (lines);
1463 /* Print the sorted items, across alphabetically, like ls -x. */
1464 for (i = 1; matches[i]; i++)
1466 temp = printable_part (matches[i]);
1467 printed_len = print_filename (temp, matches[i], sind);
1468 /* Have we reached the end of this line? */
1471 if (i && (limit > 1) && (i % limit) == 0)
1475 if (_rl_page_completions && lines >= _rl_screenheight - 1)
1477 lines = _rl_internal_pager (lines);
1483 for (k = 0; k < max - printed_len; k++)
1484 putc (' ', rl_outstream);
1491 /* Display MATCHES, a list of matching filenames in argv format. This
1492 handles the simple case -- a single match -- first. If there is more
1493 than one match, we compute the number of strings in the list and the
1494 length of the longest string, which will be needed by the display
1495 function. If the application wants to handle displaying the list of
1496 matches itself, it sets RL_COMPLETION_DISPLAY_MATCHES_HOOK to the
1497 address of a function, and we just call it. If we're handling the
1498 display ourselves, we just call rl_display_match_list. We also check
1499 that the list of matches doesn't exceed the user-settable threshold,
1500 and ask the user if he wants to see the list if there are more matches
1501 than RL_COMPLETION_QUERY_ITEMS. */
1503 display_matches (matches)
1509 /* Move to the last visible line of a possibly-multiple-line command. */
1510 _rl_move_vert (_rl_vis_botlin);
1512 /* Handle simple case first. What if there is only one answer? */
1513 if (matches[1] == 0)
1515 temp = printable_part (matches[0]);
1517 print_filename (temp, matches[0], 0);
1520 rl_forced_update_display ();
1521 rl_display_fixed = 1;
1526 /* There is more than one answer. Find out how many there are,
1527 and find the maximum printed length of a single entry. */
1528 for (max = 0, i = 1; matches[i]; i++)
1530 temp = printable_part (matches[i]);
1531 len = fnwidth (temp);
1539 /* If the caller has defined a display hook, then call that now. */
1540 if (rl_completion_display_matches_hook)
1542 (*rl_completion_display_matches_hook) (matches, len, max);
1546 /* If there are many items, then ask the user if she really wants to
1548 if (rl_completion_query_items > 0 && len >= rl_completion_query_items)
1551 fprintf (rl_outstream, "Display all %d possibilities? (y or n)", len);
1552 fflush (rl_outstream);
1553 if ((completion_y_or_n = get_y_or_n (0)) == 0)
1557 rl_forced_update_display ();
1558 rl_display_fixed = 1;
1564 rl_display_match_list (matches, len, max);
1566 rl_forced_update_display ();
1567 rl_display_fixed = 1;
1571 make_quoted_replacement (match, mtype, qc)
1574 char *qc; /* Pointer to quoting character, if any */
1576 int should_quote, do_replace;
1579 /* If we are doing completion on quoted substrings, and any matches
1580 contain any of the completer_word_break_characters, then auto-
1581 matically prepend the substring with a quote character (just pick
1582 the first one from the list of such) if it does not already begin
1583 with a quote string. FIXME: Need to remove any such automatically
1584 inserted quote character when it no longer is necessary, such as
1585 if we change the string we are completing on and the new set of
1586 matches don't require a quoted substring. */
1587 replacement = match;
1589 should_quote = match && rl_completer_quote_characters &&
1590 rl_filename_completion_desired &&
1591 rl_filename_quoting_desired;
1594 should_quote = should_quote && (!qc || !*qc ||
1595 (rl_completer_quote_characters && strchr (rl_completer_quote_characters, *qc)));
1599 /* If there is a single match, see if we need to quote it.
1600 This also checks whether the common prefix of several
1601 matches needs to be quoted. */
1602 should_quote = rl_filename_quote_characters
1603 ? (_rl_strpbrk (match, rl_filename_quote_characters) != 0)
1606 do_replace = should_quote ? mtype : NO_MATCH;
1607 /* Quote the replacement, since we found an embedded
1608 word break character in a potential match. */
1609 if (do_replace != NO_MATCH && rl_filename_quoting_function)
1610 replacement = (*rl_filename_quoting_function) (match, do_replace, qc);
1612 return (replacement);
1616 insert_match (match, start, mtype, qc)
1621 char *replacement, *r;
1625 oqc = qc ? *qc : '\0';
1626 replacement = make_quoted_replacement (match, mtype, qc);
1628 /* Now insert the match. */
1631 rlen = strlen (replacement);
1632 /* Don't double an opening quote character. */
1633 if (qc && *qc && start && rl_line_buffer[start - 1] == *qc &&
1634 replacement[0] == *qc)
1636 /* If make_quoted_replacement changed the quoting character, remove
1637 the opening quote and insert the (fully-quoted) replacement. */
1638 else if (qc && (*qc != oqc) && start && rl_line_buffer[start - 1] == oqc &&
1639 replacement[0] != oqc)
1642 /* Don't double a closing quote character */
1643 if (qc && *qc && end && rl_line_buffer[rl_point] == *qc && replacement[rlen - 1] == *qc)
1645 if (_rl_skip_completed_text)
1648 while (start < rl_end && *r && rl_line_buffer[start] == *r)
1653 if (start <= end || *r)
1654 _rl_replace_text (r, start, end);
1655 rl_point = start + strlen (r);
1658 _rl_replace_text (replacement, start, end);
1659 if (replacement != match)
1660 xfree (replacement);
1664 /* Append any necessary closing quote and a separator character to the
1665 just-inserted match. If the user has specified that directories
1666 should be marked by a trailing `/', append one of those instead. The
1667 default trailing character is a space. Returns the number of characters
1668 appended. If NONTRIVIAL_MATCH is set, we test for a symlink (if the OS
1669 has them) and don't add a suffix for a symlink to a directory. A
1670 nontrivial match is one that actually adds to the word being completed.
1671 The variable rl_completion_mark_symlink_dirs controls this behavior
1672 (it's initially set to the what the user has chosen, indicated by the
1673 value of _rl_complete_mark_symlink_dirs, but may be modified by an
1674 application's completion function). */
1676 append_to_match (text, delimiter, quote_char, nontrivial_match)
1678 int delimiter, quote_char, nontrivial_match;
1680 char temp_string[4], *filename;
1681 int temp_string_index, s;
1684 temp_string_index = 0;
1685 if (quote_char && rl_point && rl_completion_suppress_quote == 0 &&
1686 rl_line_buffer[rl_point - 1] != quote_char)
1687 temp_string[temp_string_index++] = quote_char;
1690 temp_string[temp_string_index++] = delimiter;
1691 else if (rl_completion_suppress_append == 0 && rl_completion_append_character)
1692 temp_string[temp_string_index++] = rl_completion_append_character;
1694 temp_string[temp_string_index++] = '\0';
1696 if (rl_filename_completion_desired)
1698 filename = tilde_expand (text);
1699 s = (nontrivial_match && rl_completion_mark_symlink_dirs == 0)
1700 ? LSTAT (filename, &finfo)
1701 : stat (filename, &finfo);
1702 if (s == 0 && S_ISDIR (finfo.st_mode))
1704 if (_rl_complete_mark_directories /* && rl_completion_suppress_append == 0 */)
1706 /* This is clumsy. Avoid putting in a double slash if point
1707 is at the end of the line and the previous character is a
1709 if (rl_point && rl_line_buffer[rl_point] == '\0' && rl_line_buffer[rl_point - 1] == '/')
1711 else if (rl_line_buffer[rl_point] != '/')
1712 rl_insert_text ("/");
1716 /* Don't add anything if the filename is a symlink and resolves to a
1718 else if (s == 0 && S_ISLNK (finfo.st_mode) &&
1719 stat (filename, &finfo) == 0 && S_ISDIR (finfo.st_mode))
1724 if (rl_point == rl_end && temp_string_index)
1725 rl_insert_text (temp_string);
1731 if (rl_point == rl_end && temp_string_index)
1732 rl_insert_text (temp_string);
1735 return (temp_string_index);
1739 insert_all_matches (matches, point, qc)
1747 rl_begin_undo_group ();
1748 /* remove any opening quote character; make_quoted_replacement will add
1750 if (qc && *qc && point && rl_line_buffer[point - 1] == *qc)
1752 rl_delete_text (point, rl_point);
1757 for (i = 1; matches[i]; i++)
1759 rp = make_quoted_replacement (matches[i], SINGLE_MATCH, qc);
1760 rl_insert_text (rp);
1761 rl_insert_text (" ");
1762 if (rp != matches[i])
1768 rp = make_quoted_replacement (matches[0], SINGLE_MATCH, qc);
1769 rl_insert_text (rp);
1770 rl_insert_text (" ");
1771 if (rp != matches[0])
1774 rl_end_undo_group ();
1778 _rl_free_match_list (matches)
1786 for (i = 0; matches[i]; i++)
1791 /* Complete the word at or before point.
1792 WHAT_TO_DO says what to do with the completion.
1793 `?' means list the possible completions.
1794 TAB means do standard completion.
1795 `*' means insert all of the possible completions.
1796 `!' means to do standard completion, and list all possible completions if
1797 there is more than one.
1798 `@' means to do standard completion, and list all possible completions if
1799 there is more than one and partial completion is not possible. */
1801 rl_complete_internal (what_to_do)
1805 rl_compentry_func_t *our_func;
1806 int start, end, delimiter, found_quote, i, nontrivial_lcd;
1807 char *text, *saved_line_buffer;
1813 RL_SETSTATE(RL_STATE_COMPLETING);
1815 set_completion_defaults (what_to_do);
1817 saved_line_buffer = rl_line_buffer ? savestring (rl_line_buffer) : (char *)NULL;
1818 our_func = rl_completion_entry_function
1819 ? rl_completion_entry_function
1820 : rl_filename_completion_function;
1821 /* We now look backwards for the start of a filename/variable word. */
1823 found_quote = delimiter = 0;
1827 /* This (possibly) changes rl_point. If it returns a non-zero char,
1828 we know we have an open quote. */
1829 quote_char = _rl_find_completion_word (&found_quote, &delimiter);
1834 text = rl_copy_text (start, end);
1835 matches = gen_completion_matches (text, start, end, our_func, found_quote, quote_char);
1836 /* nontrivial_lcd is set if the common prefix adds something to the word
1838 nontrivial_lcd = matches && strcmp (text, matches[0]) != 0;
1840 if (what_to_do == '!' || what_to_do == '@')
1841 tlen = strlen (text);
1848 FREE (saved_line_buffer);
1849 completion_changed_buffer = 0;
1850 RL_UNSETSTATE(RL_STATE_COMPLETING);
1851 _rl_reset_completion_state ();
1855 /* If we are matching filenames, the attempted completion function will
1856 have set rl_filename_completion_desired to a non-zero value. The basic
1857 rl_filename_completion_function does this. */
1858 i = rl_filename_completion_desired;
1860 if (postprocess_matches (&matches, i) == 0)
1863 FREE (saved_line_buffer);
1864 completion_changed_buffer = 0;
1865 RL_UNSETSTATE(RL_STATE_COMPLETING);
1866 _rl_reset_completion_state ();
1875 /* Insert the first match with proper quoting. */
1878 insert_match (matches[0], start, matches[1] ? MULT_MATCH : SINGLE_MATCH, "e_char);
1880 if (what_to_do == TAB)
1883 insert_match (matches[0], start, matches[1] ? MULT_MATCH : SINGLE_MATCH, "e_char);
1885 else if (*matches[0] && matches[1] == 0)
1886 /* should we perform the check only if there are multiple matches? */
1887 insert_match (matches[0], start, matches[1] ? MULT_MATCH : SINGLE_MATCH, "e_char);
1888 else if (*matches[0]) /* what_to_do != TAB && multiple matches */
1890 mlen = *matches[0] ? strlen (matches[0]) : 0;
1892 insert_match (matches[0], start, matches[1] ? MULT_MATCH : SINGLE_MATCH, "e_char);
1896 /* If there are more matches, ring the bell to indicate.
1897 If we are in vi mode, Posix.2 says to not ring the bell.
1898 If the `show-all-if-ambiguous' variable is set, display
1899 all the matches immediately. Otherwise, if this was the
1900 only match, and we are hacking files, check the file to
1901 see if it was a directory. If so, and the `mark-directories'
1902 variable is set, add a '/' to the name. If not, and we
1903 are at the end of the line, then add a space. */
1906 if (what_to_do == '!')
1908 display_matches (matches);
1911 else if (what_to_do == '@')
1913 if (nontrivial_lcd == 0)
1914 display_matches (matches);
1917 else if (rl_editing_mode != vi_mode)
1918 rl_ding (); /* There are other matches remaining. */
1921 append_to_match (matches[0], delimiter, quote_char, nontrivial_lcd);
1926 insert_all_matches (matches, start, "e_char);
1930 display_matches (matches);
1934 _rl_ttymsg ("bad value %d for what_to_do in rl_complete", what_to_do);
1936 FREE (saved_line_buffer);
1937 RL_UNSETSTATE(RL_STATE_COMPLETING);
1938 _rl_reset_completion_state ();
1942 _rl_free_match_list (matches);
1944 /* Check to see if the line has changed through all of this manipulation. */
1945 if (saved_line_buffer)
1947 completion_changed_buffer = strcmp (rl_line_buffer, saved_line_buffer) != 0;
1948 xfree (saved_line_buffer);
1951 RL_UNSETSTATE(RL_STATE_COMPLETING);
1952 _rl_reset_completion_state ();
1956 /***************************************************************/
1958 /* Application-callable completion match generator functions */
1960 /***************************************************************/
1962 /* Return an array of (char *) which is a list of completions for TEXT.
1963 If there are no completions, return a NULL pointer.
1964 The first entry in the returned array is the substitution for TEXT.
1965 The remaining entries are the possible completions.
1966 The array is terminated with a NULL pointer.
1968 ENTRY_FUNCTION is a function of two args, and returns a (char *).
1969 The first argument is TEXT.
1970 The second is a state argument; it should be zero on the first call, and
1971 non-zero on subsequent calls. It returns a NULL pointer to the caller
1972 when there are no more matches.
1975 rl_completion_matches (text, entry_function)
1977 rl_compentry_func_t *entry_function;
1979 /* Number of slots in match_list. */
1980 int match_list_size;
1982 /* The list of matches. */
1985 /* Number of matches actually found. */
1988 /* Temporary string binder. */
1992 match_list_size = 10;
1993 match_list = (char **)xmalloc ((match_list_size + 1) * sizeof (char *));
1994 match_list[1] = (char *)NULL;
1996 _rl_interrupt_immediately++;
1997 while (string = (*entry_function) (text, matches))
1999 if (matches + 1 == match_list_size)
2000 match_list = (char **)xrealloc
2001 (match_list, ((match_list_size += 10) + 1) * sizeof (char *));
2003 match_list[++matches] = string;
2004 match_list[matches + 1] = (char *)NULL;
2006 if (_rl_interrupt_immediately > 0)
2007 _rl_interrupt_immediately--;
2009 /* If there were any matches, then look through them finding out the
2010 lowest common denominator. That then becomes match_list[0]. */
2012 compute_lcd_of_matches (match_list, matches, text);
2013 else /* There were no matches. */
2016 match_list = (char **)NULL;
2018 return (match_list);
2021 /* A completion function for usernames.
2022 TEXT contains a partial username preceded by a random
2023 character (usually `~'). */
2025 rl_username_completion_function (text, state)
2029 #if defined (__WIN32__) || defined (__OPENNT)
2030 return (char *)NULL;
2031 #else /* !__WIN32__ && !__OPENNT) */
2032 static char *username = (char *)NULL;
2033 static struct passwd *entry;
2034 static int namelen, first_char, first_char_loc;
2042 first_char_loc = first_char == '~';
2044 username = savestring (&text[first_char_loc]);
2045 namelen = strlen (username);
2049 #if defined (HAVE_GETPWENT)
2050 while (entry = getpwent ())
2052 /* Null usernames should result in all users as possible completions. */
2053 if (namelen == 0 || (STREQN (username, entry->pw_name, namelen)))
2060 #if defined (HAVE_GETPWENT)
2063 return ((char *)NULL);
2067 value = (char *)xmalloc (2 + strlen (entry->pw_name));
2071 strcpy (value + first_char_loc, entry->pw_name);
2073 if (first_char == '~')
2074 rl_filename_completion_desired = 1;
2078 #endif /* !__WIN32__ && !__OPENNT */
2081 /* Return non-zero if CONVFN matches FILENAME up to the length of FILENAME
2082 (FILENAME_LEN). If _rl_completion_case_fold is set, compare without
2083 regard to the alphabetic case of characters. CONVFN is the possibly-
2084 converted directory entry; FILENAME is what the user typed. */
2086 complete_fncmp (convfn, convlen, filename, filename_len)
2089 const char *filename;
2092 register char *s1, *s2;
2095 /* Otherwise, if these match up to the length of filename, then
2097 if (_rl_completion_case_fold && _rl_completion_case_map)
2099 /* Case-insensitive comparison treating _ and - as equivalent */
2100 if (filename_len == 0)
2102 if (convlen < filename_len)
2104 s1 = (char *)convfn;
2105 s2 = (char *)filename;
2109 d = _rl_to_lower (*s1) - _rl_to_lower (*s2);
2110 /* *s1 == [-_] && *s2 == [-_] */
2111 if ((*s1 == '-' || *s1 == '_') && (*s2 == '-' || *s2 == '_'))
2115 s1++; s2++; /* already checked convlen >= filename_len */
2120 else if (_rl_completion_case_fold)
2122 if ((_rl_to_lower (convfn[0]) == _rl_to_lower (filename[0])) &&
2123 (convlen >= filename_len) &&
2124 (_rl_strnicmp (filename, convfn, filename_len) == 0))
2129 if ((convfn[0] == filename[0]) &&
2130 (convlen >= filename_len) &&
2131 (strncmp (filename, convfn, filename_len) == 0))
2137 /* Okay, now we write the entry_function for filename completion. In the
2138 general case. Note that completion in the shell is a little different
2139 because of all the pathnames that must be followed when looking up the
2140 completion for a command. */
2142 rl_filename_completion_function (text, state)
2146 static DIR *directory = (DIR *)NULL;
2147 static char *filename = (char *)NULL;
2148 static char *dirname = (char *)NULL;
2149 static char *users_dirname = (char *)NULL;
2150 static int filename_len;
2151 char *temp, *dentry, *convfn;
2152 int dirlen, dentlen, convlen;
2153 struct dirent *entry;
2155 /* If we don't have any state, then do some initialization. */
2158 /* If we were interrupted before closing the directory or reading
2159 all of its contents, close it. */
2162 closedir (directory);
2163 directory = (DIR *)NULL;
2167 FREE (users_dirname);
2169 filename = savestring (text);
2172 dirname = savestring (text);
2174 temp = strrchr (dirname, '/');
2176 #if defined (__MSDOS__)
2177 /* special hack for //X/... */
2178 if (dirname[0] == '/' && dirname[1] == '/' && ISALPHA ((unsigned char)dirname[2]) && dirname[3] == '/')
2179 temp = strrchr (dirname + 3, '/');
2184 strcpy (filename, ++temp);
2187 #if defined (__MSDOS__)
2188 /* searches from current directory on the drive */
2189 else if (ISALPHA ((unsigned char)dirname[0]) && dirname[1] == ':')
2191 strcpy (filename, dirname + 2);
2201 /* We aren't done yet. We also support the "~user" syntax. */
2203 /* Save the version of the directory that the user typed, dequoting
2205 if (rl_completion_found_quote && rl_filename_dequoting_function)
2206 users_dirname = (*rl_filename_dequoting_function) (dirname, rl_completion_quote_character);
2208 users_dirname = savestring (dirname);
2210 if (*dirname == '~')
2212 temp = tilde_expand (dirname);
2217 /* We have saved the possibly-dequoted version of the directory name
2218 the user typed. Now transform the directory name we're going to
2219 pass to opendir(2). The directory rewrite hook modifies only the
2220 directory name; the directory completion hook modifies both the
2221 directory name passed to opendir(2) and the version the user
2222 typed. Both the directory completion and rewrite hooks should perform
2223 any necessary dequoting. The hook functions return 1 if they modify
2224 the directory name argument. If either hook returns 0, it should
2225 not modify the directory name pointer passed as an argument. */
2226 if (rl_directory_rewrite_hook)
2227 (*rl_directory_rewrite_hook) (&dirname);
2228 else if (rl_directory_completion_hook && (*rl_directory_completion_hook) (&dirname))
2230 xfree (users_dirname);
2231 users_dirname = savestring (dirname);
2233 else if (rl_completion_found_quote && rl_filename_dequoting_function)
2235 /* delete single and double quotes */
2237 dirname = savestring (users_dirname);
2239 directory = opendir (dirname);
2241 /* Now dequote a non-null filename. */
2242 if (filename && *filename && rl_completion_found_quote && rl_filename_dequoting_function)
2244 /* delete single and double quotes */
2245 temp = (*rl_filename_dequoting_function) (filename, rl_completion_quote_character);
2249 filename_len = strlen (filename);
2251 rl_filename_completion_desired = 1;
2254 /* At this point we should entertain the possibility of hacking wildcarded
2255 filenames, like /usr/man/man<WILD>/te<TAB>. If the directory name
2256 contains globbing characters, then build an array of directories, and
2257 then map over that list while completing. */
2258 /* *** UNIMPLEMENTED *** */
2260 /* Now that we have some state, we can read the directory. */
2262 entry = (struct dirent *)NULL;
2263 while (directory && (entry = readdir (directory)))
2265 convfn = dentry = entry->d_name;
2266 convlen = dentlen = D_NAMLEN (entry);
2268 if (rl_filename_rewrite_hook)
2270 convfn = (*rl_filename_rewrite_hook) (dentry, dentlen);
2271 convlen = (convfn == dentry) ? dentlen : strlen (convfn);
2274 /* Special case for no filename. If the user has disabled the
2275 `match-hidden-files' variable, skip filenames beginning with `.'.
2276 All other entries except "." and ".." match. */
2277 if (filename_len == 0)
2279 if (_rl_match_hidden_files == 0 && HIDDEN_FILE (convfn))
2282 if (convfn[0] != '.' ||
2283 (convfn[1] && (convfn[1] != '.' || convfn[2])))
2288 if (complete_fncmp (convfn, convlen, filename, filename_len))
2297 closedir (directory);
2298 directory = (DIR *)NULL;
2303 dirname = (char *)NULL;
2308 filename = (char *)NULL;
2312 xfree (users_dirname);
2313 users_dirname = (char *)NULL;
2316 return (char *)NULL;
2320 /* dirname && (strcmp (dirname, ".") != 0) */
2321 if (dirname && (dirname[0] != '.' || dirname[1]))
2323 if (rl_complete_with_tilde_expansion && *users_dirname == '~')
2325 dirlen = strlen (dirname);
2326 temp = (char *)xmalloc (2 + dirlen + D_NAMLEN (entry));
2327 strcpy (temp, dirname);
2328 /* Canonicalization cuts off any final slash present. We
2329 may need to add it back. */
2330 if (dirname[dirlen - 1] != '/')
2332 temp[dirlen++] = '/';
2333 temp[dirlen] = '\0';
2338 dirlen = strlen (users_dirname);
2339 temp = (char *)xmalloc (2 + dirlen + D_NAMLEN (entry));
2340 strcpy (temp, users_dirname);
2341 /* Make sure that temp has a trailing slash here. */
2342 if (users_dirname[dirlen - 1] != '/')
2343 temp[dirlen++] = '/';
2346 strcpy (temp + dirlen, convfn);
2349 temp = savestring (convfn);
2351 if (convfn != dentry)
2358 /* An initial implementation of a menu completion function a la tcsh. The
2359 first time (if the last readline command was not rl_old_menu_complete), we
2360 generate the list of matches. This code is very similar to the code in
2361 rl_complete_internal -- there should be a way to combine the two. Then,
2362 for each item in the list of matches, we insert the match in an undoable
2363 fashion, with the appropriate character appended (this happens on the
2364 second and subsequent consecutive calls to rl_old_menu_complete). When we
2365 hit the end of the match list, we restore the original unmatched text,
2366 ring the bell, and reset the counter to zero. */
2368 rl_old_menu_complete (count, invoking_key)
2369 int count, invoking_key;
2371 rl_compentry_func_t *our_func;
2372 int matching_filenames, found_quote;
2374 static char *orig_text;
2375 static char **matches = (char **)0;
2376 static int match_list_index = 0;
2377 static int match_list_size = 0;
2378 static int orig_start, orig_end;
2379 static char quote_char;
2380 static int delimiter;
2382 /* The first time through, we generate the list of matches and set things
2383 up to insert them. */
2384 if (rl_last_func != rl_old_menu_complete)
2386 /* Clean up from previous call, if any. */
2389 _rl_free_match_list (matches);
2391 match_list_index = match_list_size = 0;
2392 matches = (char **)NULL;
2394 rl_completion_invoking_key = invoking_key;
2396 RL_SETSTATE(RL_STATE_COMPLETING);
2398 /* Only the completion entry function can change these. */
2399 set_completion_defaults ('%');
2401 our_func = rl_menu_completion_entry_function;
2403 our_func = rl_completion_entry_function
2404 ? rl_completion_entry_function
2405 : rl_filename_completion_function;
2407 /* We now look backwards for the start of a filename/variable word. */
2408 orig_end = rl_point;
2409 found_quote = delimiter = 0;
2413 /* This (possibly) changes rl_point. If it returns a non-zero char,
2414 we know we have an open quote. */
2415 quote_char = _rl_find_completion_word (&found_quote, &delimiter);
2417 orig_start = rl_point;
2418 rl_point = orig_end;
2420 orig_text = rl_copy_text (orig_start, orig_end);
2421 matches = gen_completion_matches (orig_text, orig_start, orig_end,
2422 our_func, found_quote, quote_char);
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++)
2445 /* matches[0] is lcd if match_list_size > 1, but the circular buffer
2446 code below should take care of it. */
2448 if (match_list_size > 1 && _rl_complete_show_all)
2449 display_matches (matches);
2452 /* Now we have the list of matches. Replace the text between
2453 rl_line_buffer[orig_start] and rl_line_buffer[rl_point] with
2454 matches[match_list_index], and add any necessary closing char. */
2456 if (matches == 0 || match_list_size == 0)
2460 matches = (char **)0;
2461 completion_changed_buffer = 0;
2465 match_list_index += count;
2466 if (match_list_index < 0)
2468 while (match_list_index < 0)
2469 match_list_index += match_list_size;
2472 match_list_index %= match_list_size;
2474 if (match_list_index == 0 && match_list_size > 1)
2477 insert_match (orig_text, orig_start, MULT_MATCH, "e_char);
2481 insert_match (matches[match_list_index], orig_start, SINGLE_MATCH, "e_char);
2482 append_to_match (matches[match_list_index], delimiter, quote_char,
2483 strcmp (orig_text, matches[match_list_index]));
2486 completion_changed_buffer = 1;
2491 rl_menu_complete (count, ignore)
2494 rl_compentry_func_t *our_func;
2495 int matching_filenames, found_quote;
2497 static char *orig_text;
2498 static char **matches = (char **)0;
2499 static int match_list_index = 0;
2500 static int match_list_size = 0;
2501 static int nontrivial_lcd = 0;
2502 static int full_completion = 0; /* set to 1 if menu completion should reinitialize on next call */
2503 static int orig_start, orig_end;
2504 static char quote_char;
2505 static int delimiter, cstate;
2507 /* The first time through, we generate the list of matches and set things
2508 up to insert them. */
2509 if ((rl_last_func != rl_menu_complete && rl_last_func != rl_backward_menu_complete) || full_completion)
2511 /* Clean up from previous call, if any. */
2514 _rl_free_match_list (matches);
2516 match_list_index = match_list_size = 0;
2517 matches = (char **)NULL;
2519 full_completion = 0;
2521 RL_SETSTATE(RL_STATE_COMPLETING);
2523 /* Only the completion entry function can change these. */
2524 set_completion_defaults ('%');
2526 our_func = rl_menu_completion_entry_function;
2528 our_func = rl_completion_entry_function
2529 ? rl_completion_entry_function
2530 : rl_filename_completion_function;
2532 /* We now look backwards for the start of a filename/variable word. */
2533 orig_end = rl_point;
2534 found_quote = delimiter = 0;
2538 /* This (possibly) changes rl_point. If it returns a non-zero char,
2539 we know we have an open quote. */
2540 quote_char = _rl_find_completion_word (&found_quote, &delimiter);
2542 orig_start = rl_point;
2543 rl_point = orig_end;
2545 orig_text = rl_copy_text (orig_start, orig_end);
2546 matches = gen_completion_matches (orig_text, orig_start, orig_end,
2547 our_func, found_quote, quote_char);
2549 nontrivial_lcd = matches && strcmp (orig_text, matches[0]) != 0;
2551 /* If we are matching filenames, the attempted completion function will
2552 have set rl_filename_completion_desired to a non-zero value. The basic
2553 rl_filename_completion_function does this. */
2554 matching_filenames = rl_filename_completion_desired;
2556 if (matches == 0 || postprocess_matches (&matches, matching_filenames) == 0)
2560 matches = (char **)0;
2562 orig_text = (char *)0;
2563 completion_changed_buffer = 0;
2564 RL_UNSETSTATE(RL_STATE_COMPLETING);
2568 RL_UNSETSTATE(RL_STATE_COMPLETING);
2570 for (match_list_size = 0; matches[match_list_size]; match_list_size++)
2573 if (match_list_size == 0)
2577 matches = (char **)0;
2578 match_list_index = 0;
2579 completion_changed_buffer = 0;
2583 /* matches[0] is lcd if match_list_size > 1, but the circular buffer
2584 code below should take care of it. */
2587 insert_match (matches[0], orig_start, matches[1] ? MULT_MATCH : SINGLE_MATCH, "e_char);
2588 orig_end = orig_start + strlen (matches[0]);
2589 completion_changed_buffer = STREQ (orig_text, matches[0]) == 0;
2592 if (match_list_size > 1 && _rl_complete_show_all)
2594 display_matches (matches);
2595 /* If there are so many matches that the user has to be asked
2596 whether or not he wants to see the matches, menu completion
2598 if (rl_completion_query_items > 0 && match_list_size >= rl_completion_query_items)
2602 matches = (char **)0;
2603 full_completion = 1;
2607 else if (match_list_size <= 1)
2609 append_to_match (matches[0], delimiter, quote_char, nontrivial_lcd);
2610 full_completion = 1;
2613 else if (_rl_menu_complete_prefix_first && match_list_size > 1)
2620 /* Now we have the list of matches. Replace the text between
2621 rl_line_buffer[orig_start] and rl_line_buffer[rl_point] with
2622 matches[match_list_index], and add any necessary closing char. */
2624 if (matches == 0 || match_list_size == 0)
2628 matches = (char **)0;
2629 completion_changed_buffer = 0;
2633 match_list_index += count;
2634 if (match_list_index < 0)
2636 while (match_list_index < 0)
2637 match_list_index += match_list_size;
2640 match_list_index %= match_list_size;
2642 if (match_list_index == 0 && match_list_size > 1)
2645 insert_match (matches[0], orig_start, MULT_MATCH, "e_char);
2649 insert_match (matches[match_list_index], orig_start, SINGLE_MATCH, "e_char);
2650 append_to_match (matches[match_list_index], delimiter, quote_char,
2651 strcmp (orig_text, matches[match_list_index]));
2654 completion_changed_buffer = 1;
2659 rl_backward_menu_complete (count, key)
2662 /* Positive arguments to backward-menu-complete translate into negative
2663 arguments for menu-complete, and vice versa. */
2664 return (rl_menu_complete (-count, key));