[PATCH 1/57][Arm][GAS]: Add support for +mve and +mve.fp
[binutils-gdb.git] / readline / complete.c
blob5733d4e1a98f98fa428eeb4ae338ae2aa4983b68
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)
25 # include <config.h>
26 #endif
28 #include <sys/types.h>
29 #include <fcntl.h>
30 #if defined (HAVE_SYS_FILE_H)
31 # include <sys/file.h>
32 #endif
34 #if defined (HAVE_UNISTD_H)
35 # include <unistd.h>
36 #endif /* HAVE_UNISTD_H */
38 #if defined (HAVE_STDLIB_H)
39 # include <stdlib.h>
40 #else
41 # include "ansi_stdlib.h"
42 #endif /* HAVE_STDLIB_H */
44 #include <stdio.h>
46 #include <errno.h>
47 #if !defined (errno)
48 extern int errno;
49 #endif /* !errno */
51 #if defined (HAVE_PWD_H)
52 #include <pwd.h>
53 #endif
55 #include "posixdir.h"
56 #include "posixstat.h"
58 /* System-specific feature definitions and include files. */
59 #include "rldefs.h"
60 #include "rlmbutil.h"
62 /* Some standard library routines. */
63 #include "readline.h"
64 #include "xmalloc.h"
65 #include "rlprivate.h"
67 #ifdef __STDC__
68 typedef int QSFUNC (const void *, const void *);
69 #else
70 typedef int QSFUNC ();
71 #endif
73 #ifdef HAVE_LSTAT
74 # define LSTAT lstat
75 #else
76 # define LSTAT stat
77 #endif
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
83 defined. */
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)
98 # if !defined (X_OK)
99 # define X_OK 1
100 # endif
101 static int stat_char PARAMS((char *));
102 #endif
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 /* **************************************************************** */
131 /* */
132 /* Completion matching, from readline's point of view. */
133 /* */
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,
155 like `ls -x'. */
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 || (defined (_WIN32) && !defined (__CYGWIN__))
161 int _rl_completion_case_fold = 1;
162 #else
163 int _rl_completion_case_fold = 0;
164 #endif
166 /* Non-zero means that `-' and `_' are equivalent when comparing filenames
167 for completion. */
168 int _rl_completion_case_map = 0;
170 /* If zero, don't match hidden files (filenames beginning with a `.' on
171 Unix) when doing filename completion. */
172 int _rl_match_hidden_files = 1;
174 /* Length in characters of a common prefix replaced with an ellipsis (`...')
175 when displaying completion matches. Matches whose printable portion has
176 more than this number of displaying characters in common will have the common
177 display prefix replaced with an ellipsis. */
178 int _rl_completion_prefix_display_length = 0;
180 /* The readline-private number of screen columns to use when displaying
181 matches. If < 0 or > _rl_screenwidth, it is ignored. */
182 int _rl_completion_columns = -1;
184 /* Global variables available to applications using readline. */
186 #if defined (VISIBLE_STATS)
187 /* Non-zero means add an additional character to each filename displayed
188 during listing completion iff rl_filename_completion_desired which helps
189 to indicate the type of file being listed. */
190 int rl_visible_stats = 0;
191 #endif /* VISIBLE_STATS */
193 /* If non-zero, when completing in the middle of a word, don't insert
194 characters from the match that match characters following point in
195 the word. This means, for instance, completing when the cursor is
196 after the `e' in `Makefile' won't result in `Makefilefile'. */
197 int _rl_skip_completed_text = 0;
199 /* If non-zero, menu completion displays the common prefix first in the
200 cycle of possible completions instead of the last. */
201 int _rl_menu_complete_prefix_first = 0;
203 /* If non-zero, then this is the address of a function to call when
204 completing on a directory name. The function is called with
205 the address of a string (the current directory name) as an arg. */
206 rl_icppfunc_t *rl_directory_completion_hook = (rl_icppfunc_t *)NULL;
208 rl_icppfunc_t *rl_directory_rewrite_hook = (rl_icppfunc_t *)NULL;
210 /* If non-zero, this is the address of a function to call when reading
211 directory entries from the filesystem for completion and comparing
212 them to the partial word to be completed. The function should
213 either return its first argument (if no conversion takes place) or
214 newly-allocated memory. This can, for instance, convert filenames
215 between character sets for comparison against what's typed at the
216 keyboard. The returned value is what is added to the list of
217 matches. The second argument is the length of the filename to be
218 converted. */
219 rl_dequote_func_t *rl_filename_rewrite_hook = (rl_dequote_func_t *)NULL;
221 /* Non-zero means readline completion functions perform tilde expansion. */
222 int rl_complete_with_tilde_expansion = 0;
224 /* Pointer to the generator function for completion_matches ().
225 NULL means to use rl_filename_completion_function (), the default filename
226 completer. */
227 rl_compentry_func_t *rl_completion_entry_function = (rl_compentry_func_t *)NULL;
229 /* Pointer to generator function for rl_menu_complete (). NULL means to use
230 *rl_completion_entry_function (see above). */
231 rl_compentry_func_t *rl_menu_completion_entry_function = (rl_compentry_func_t *)NULL;
233 /* Pointer to alternative function to create matches.
234 Function is called with TEXT, START, and END.
235 START and END are indices in RL_LINE_BUFFER saying what the boundaries
236 of TEXT are.
237 If this function exists and returns NULL then call the value of
238 rl_completion_entry_function to try to match, otherwise use the
239 array of strings returned. */
240 rl_completion_func_t *rl_attempted_completion_function = (rl_completion_func_t *)NULL;
242 /* Non-zero means to suppress normal filename completion after the
243 user-specified completion function has been called. */
244 int rl_attempted_completion_over = 0;
246 /* Set to a character indicating the type of completion being performed
247 by rl_complete_internal, available for use by application completion
248 functions. */
249 int rl_completion_type = 0;
251 /* Up to this many items will be displayed in response to a
252 possible-completions call. After that, we ask the user if
253 she is sure she wants to see them all. A negative value means
254 don't ask. */
255 int rl_completion_query_items = 100;
257 int _rl_page_completions = 1;
259 /* The basic list of characters that signal a break between words for the
260 completer routine. The contents of this variable is what breaks words
261 in the shell, i.e. " \t\n\"\\'`@$><=" */
262 const char *rl_basic_word_break_characters = " \t\n\"\\'`@$><=;|&{("; /* }) */
264 /* List of basic quoting characters. */
265 const char *rl_basic_quote_characters = "\"'";
267 /* The list of characters that signal a break between words for
268 rl_complete_internal. The default list is the contents of
269 rl_basic_word_break_characters. */
270 /*const*/ char *rl_completer_word_break_characters = (/*const*/ char *)NULL;
272 /* Hook function to allow an application to set the completion word
273 break characters before readline breaks up the line. Allows
274 position-dependent word break characters. */
275 rl_cpvfunc_t *rl_completion_word_break_hook = (rl_cpvfunc_t *)NULL;
277 /* List of characters which can be used to quote a substring of the line.
278 Completion occurs on the entire substring, and within the substring
279 rl_completer_word_break_characters are treated as any other character,
280 unless they also appear within this list. */
281 const char *rl_completer_quote_characters = (const char *)NULL;
283 /* List of characters that should be quoted in filenames by the completer. */
284 const char *rl_filename_quote_characters = (const char *)NULL;
286 /* List of characters that are word break characters, but should be left
287 in TEXT when it is passed to the completion function. The shell uses
288 this to help determine what kind of completing to do. */
289 const char *rl_special_prefixes = (const char *)NULL;
291 /* If non-zero, then disallow duplicates in the matches. */
292 int rl_ignore_completion_duplicates = 1;
294 /* Non-zero means that the results of the matches are to be treated
295 as filenames. This is ALWAYS zero on entry, and can only be changed
296 within a completion entry finder function. */
297 int rl_filename_completion_desired = 0;
299 /* Non-zero means that the results of the matches are to be quoted using
300 double quotes (or an application-specific quoting mechanism) if the
301 filename contains any characters in rl_filename_quote_chars. This is
302 ALWAYS non-zero on entry, and can only be changed within a completion
303 entry finder function. */
304 int rl_filename_quoting_desired = 1;
306 /* This function, if defined, is called by the completer when real
307 filename completion is done, after all the matching names have been
308 generated. It is passed a (char**) known as matches in the code below.
309 It consists of a NULL-terminated array of pointers to potential
310 matching strings. The 1st element (matches[0]) is the maximal
311 substring that is common to all matches. This function can re-arrange
312 the list of matches as required, but all elements of the array must be
313 free()'d if they are deleted. The main intent of this function is
314 to implement FIGNORE a la SunOS csh. */
315 rl_compignore_func_t *rl_ignore_some_completions_function = (rl_compignore_func_t *)NULL;
317 /* Set to a function to quote a filename in an application-specific fashion.
318 Called with the text to quote, the type of match found (single or multiple)
319 and a pointer to the quoting character to be used, which the function can
320 reset if desired. */
321 rl_quote_func_t *rl_filename_quoting_function = rl_quote_filename;
323 /* Function to call to remove quoting characters from a filename. Called
324 before completion is attempted, so the embedded quotes do not interfere
325 with matching names in the file system. Readline doesn't do anything
326 with this; it's set only by applications. */
327 rl_dequote_func_t *rl_filename_dequoting_function = (rl_dequote_func_t *)NULL;
329 /* Function to call to decide whether or not a word break character is
330 quoted. If a character is quoted, it does not break words for the
331 completer. */
332 rl_linebuf_func_t *rl_char_is_quoted_p = (rl_linebuf_func_t *)NULL;
334 /* If non-zero, the completion functions don't append anything except a
335 possible closing quote. This is set to 0 by rl_complete_internal and
336 may be changed by an application-specific completion function. */
337 int rl_completion_suppress_append = 0;
339 /* Character appended to completed words when at the end of the line. The
340 default is a space. */
341 int rl_completion_append_character = ' ';
343 /* If non-zero, the completion functions don't append any closing quote.
344 This is set to 0 by rl_complete_internal and may be changed by an
345 application-specific completion function. */
346 int rl_completion_suppress_quote = 0;
348 /* Set to any quote character readline thinks it finds before any application
349 completion function is called. */
350 int rl_completion_quote_character;
352 /* Set to a non-zero value if readline found quoting anywhere in the word to
353 be completed; set before any application completion function is called. */
354 int rl_completion_found_quote;
356 /* If non-zero, a slash will be appended to completed filenames that are
357 symbolic links to directory names, subject to the value of the
358 mark-directories variable (which is user-settable). This exists so
359 that application completion functions can override the user's preference
360 (set via the mark-symlinked-directories variable) if appropriate.
361 It's set to the value of _rl_complete_mark_symlink_dirs in
362 rl_complete_internal before any application-specific completion
363 function is called, so without that function doing anything, the user's
364 preferences are honored. */
365 int rl_completion_mark_symlink_dirs;
367 /* If non-zero, inhibit completion (temporarily). */
368 int rl_inhibit_completion;
370 /* Set to the last key used to invoke one of the completion functions */
371 int rl_completion_invoking_key;
373 /* If non-zero, sort the completion matches. On by default. */
374 int rl_sort_completion_matches = 1;
376 /* Variables local to this file. */
378 /* Local variable states what happened during the last completion attempt. */
379 static int completion_changed_buffer;
381 /* The result of the query to the user about displaying completion matches */
382 static int completion_y_or_n;
384 /*************************************/
385 /* */
386 /* Bindable completion functions */
387 /* */
388 /*************************************/
390 /* Complete the word at or before point. You have supplied the function
391 that does the initial simple matching selection algorithm (see
392 rl_completion_matches ()). The default is to do filename completion. */
394 rl_complete (ignore, invoking_key)
395 int ignore, invoking_key;
397 rl_completion_invoking_key = invoking_key;
399 if (rl_inhibit_completion)
400 return (_rl_insert_char (ignore, invoking_key));
401 else if (rl_last_func == rl_complete && !completion_changed_buffer)
402 return (rl_complete_internal ('?'));
403 else if (_rl_complete_show_all)
404 return (rl_complete_internal ('!'));
405 else if (_rl_complete_show_unmodified)
406 return (rl_complete_internal ('@'));
407 else
408 return (rl_complete_internal (TAB));
411 /* List the possible completions. See description of rl_complete (). */
413 rl_possible_completions (ignore, invoking_key)
414 int ignore, invoking_key;
416 rl_completion_invoking_key = invoking_key;
417 return (rl_complete_internal ('?'));
421 rl_insert_completions (ignore, invoking_key)
422 int ignore, invoking_key;
424 rl_completion_invoking_key = invoking_key;
425 return (rl_complete_internal ('*'));
428 /* Return the correct value to pass to rl_complete_internal performing
429 the same tests as rl_complete. This allows consecutive calls to an
430 application's completion function to list possible completions and for
431 an application-specific completion function to honor the
432 show-all-if-ambiguous readline variable. */
434 rl_completion_mode (cfunc)
435 rl_command_func_t *cfunc;
437 if (rl_last_func == cfunc && !completion_changed_buffer)
438 return '?';
439 else if (_rl_complete_show_all)
440 return '!';
441 else if (_rl_complete_show_unmodified)
442 return '@';
443 else
444 return TAB;
447 /************************************/
448 /* */
449 /* Completion utility functions */
450 /* */
451 /************************************/
453 /* Reset readline state on a signal or other event. */
454 void
455 _rl_reset_completion_state ()
457 rl_completion_found_quote = 0;
458 rl_completion_quote_character = 0;
461 /* Set default values for readline word completion. These are the variables
462 that application completion functions can change or inspect. */
463 static void
464 set_completion_defaults (what_to_do)
465 int what_to_do;
467 /* Only the completion entry function can change these. */
468 rl_filename_completion_desired = 0;
469 rl_filename_quoting_desired = 1;
470 rl_completion_type = what_to_do;
471 rl_completion_suppress_append = rl_completion_suppress_quote = 0;
472 rl_completion_append_character = ' ';
474 /* The completion entry function may optionally change this. */
475 rl_completion_mark_symlink_dirs = _rl_complete_mark_symlink_dirs;
478 /* The user must press "y" or "n". Non-zero return means "y" pressed. */
479 static int
480 get_y_or_n (for_pager)
481 int for_pager;
483 int c;
485 /* Disabled for GDB due to the gdb.base/readline-ask.exp regression.
486 [patch] testsuite: Test readline-6.2 "ask" regression
487 http://sourceware.org/ml/gdb-patches/2011-05/msg00002.html */
488 #if 0
489 /* For now, disable pager in callback mode, until we later convert to state
490 driven functions. Have to wait until next major version to add new
491 state definition, since it will change value of RL_STATE_DONE. */
492 #if defined (READLINE_CALLBACKS)
493 if (RL_ISSTATE (RL_STATE_CALLBACK))
494 return 1;
495 #endif
496 #endif
498 for (;;)
500 RL_SETSTATE(RL_STATE_MOREINPUT);
501 c = rl_read_key ();
502 RL_UNSETSTATE(RL_STATE_MOREINPUT);
504 if (c == 'y' || c == 'Y' || c == ' ')
505 return (1);
506 if (c == 'n' || c == 'N' || c == RUBOUT)
507 return (0);
508 if (c == ABORT_CHAR || c < 0)
509 _rl_abort_internal ();
510 if (for_pager && (c == NEWLINE || c == RETURN))
511 return (2);
512 if (for_pager && (c == 'q' || c == 'Q'))
513 return (0);
514 rl_ding ();
518 static int
519 _rl_internal_pager (lines)
520 int lines;
522 int i;
524 fprintf (rl_outstream, "--More--");
525 fflush (rl_outstream);
526 i = get_y_or_n (1);
527 _rl_erase_entire_line ();
528 if (i == 0)
529 return -1;
530 else if (i == 2)
531 return (lines - 1);
532 else
533 return 0;
536 static int
537 path_isdir (filename)
538 const char *filename;
540 struct stat finfo;
542 return (stat (filename, &finfo) == 0 && S_ISDIR (finfo.st_mode));
545 #if defined (VISIBLE_STATS)
546 /* Return the character which best describes FILENAME.
547 `@' for symbolic links
548 `/' for directories
549 `*' for executables
550 `=' for sockets
551 `|' for FIFOs
552 `%' for character special devices
553 `#' for block special devices */
554 static int
555 stat_char (filename)
556 char *filename;
558 struct stat finfo;
559 int character, r;
561 /* Short-circuit a //server on cygwin, since that will always behave as
562 a directory. */
563 #if __CYGWIN__
564 if (filename[0] == '/' && filename[1] == '/' && strchr (filename+2, '/') == 0)
565 return '/';
566 #endif
568 #if defined (HAVE_LSTAT) && defined (S_ISLNK)
569 r = lstat (filename, &finfo);
570 #else
571 r = stat (filename, &finfo);
572 #endif
574 if (r == -1)
575 return (0);
577 character = 0;
578 if (S_ISDIR (finfo.st_mode))
579 character = '/';
580 #if defined (S_ISCHR)
581 else if (S_ISCHR (finfo.st_mode))
582 character = '%';
583 #endif /* S_ISCHR */
584 #if defined (S_ISBLK)
585 else if (S_ISBLK (finfo.st_mode))
586 character = '#';
587 #endif /* S_ISBLK */
588 #if defined (S_ISLNK)
589 else if (S_ISLNK (finfo.st_mode))
590 character = '@';
591 #endif /* S_ISLNK */
592 #if defined (S_ISSOCK)
593 else if (S_ISSOCK (finfo.st_mode))
594 character = '=';
595 #endif /* S_ISSOCK */
596 #if defined (S_ISFIFO)
597 else if (S_ISFIFO (finfo.st_mode))
598 character = '|';
599 #endif
600 else if (S_ISREG (finfo.st_mode))
602 #if defined (_WIN32) && !defined (__CYGWIN__)
603 /* Windows 'access' doesn't support X_OK and on latest Windows
604 versions even invokes an invalid parameter exception. */
605 char *ext = strrchr (filename, '.');
607 if (ext
608 && (_rl_stricmp (ext, ".exe") == 0
609 || _rl_stricmp (ext, ".cmd") == 0
610 || _rl_stricmp (ext, ".bat") == 0
611 || _rl_stricmp (ext, ".com") == 0))
612 character = '*';
613 #else
614 if (access (filename, X_OK) == 0)
615 character = '*';
616 #endif
618 return (character);
620 #endif /* VISIBLE_STATS */
622 /* Return the portion of PATHNAME that should be output when listing
623 possible completions. If we are hacking filename completion, we
624 are only interested in the basename, the portion following the
625 final slash. Otherwise, we return what we were passed. Since
626 printing empty strings is not very informative, if we're doing
627 filename completion, and the basename is the empty string, we look
628 for the previous slash and return the portion following that. If
629 there's no previous slash, we just return what we were passed. */
630 static char *
631 printable_part (pathname)
632 char *pathname;
634 char *temp, *x;
636 if (rl_filename_completion_desired == 0) /* don't need to do anything */
637 return (pathname);
639 temp = strrchr (pathname, '/');
640 #if defined (__MSDOS__) || defined (_WIN32)
641 if (temp == 0 && ISALPHA ((unsigned char)pathname[0]) && pathname[1] == ':')
642 temp = pathname + 1;
643 #endif
645 if (temp == 0 || *temp == '\0')
646 return (pathname);
647 /* If the basename is NULL, we might have a pathname like '/usr/src/'.
648 Look for a previous slash and, if one is found, return the portion
649 following that slash. If there's no previous slash, just return the
650 pathname we were passed. */
651 else if (temp[1] == '\0')
653 for (x = temp - 1; x > pathname; x--)
654 if (*x == '/')
655 break;
656 return ((*x == '/') ? x + 1 : pathname);
658 else
659 return ++temp;
662 /* Compute width of STRING when displayed on screen by print_filename */
663 static int
664 fnwidth (string)
665 const char *string;
667 int width, pos;
668 #if defined (HANDLE_MULTIBYTE)
669 mbstate_t ps;
670 int left, w;
671 size_t clen;
672 wchar_t wc;
674 left = strlen (string) + 1;
675 memset (&ps, 0, sizeof (mbstate_t));
676 #endif
678 width = pos = 0;
679 while (string[pos])
681 if (CTRL_CHAR (string[pos]) || string[pos] == RUBOUT)
683 width += 2;
684 pos++;
686 else
688 #if defined (HANDLE_MULTIBYTE)
689 clen = mbrtowc (&wc, string + pos, left - pos, &ps);
690 if (MB_INVALIDCH (clen))
692 width++;
693 pos++;
694 memset (&ps, 0, sizeof (mbstate_t));
696 else if (MB_NULLWCH (clen))
697 break;
698 else
700 pos += clen;
701 w = wcwidth (wc);
702 width += (w >= 0) ? w : 1;
704 #else
705 width++;
706 pos++;
707 #endif
711 return width;
714 #define ELLIPSIS_LEN 3
716 static int
717 fnprint (to_print, prefix_bytes)
718 const char *to_print;
719 int prefix_bytes;
721 int printed_len, w;
722 const char *s;
723 #if defined (HANDLE_MULTIBYTE)
724 mbstate_t ps;
725 const char *end;
726 size_t tlen;
727 int width;
728 wchar_t wc;
730 end = to_print + strlen (to_print) + 1;
731 memset (&ps, 0, sizeof (mbstate_t));
732 #endif
734 printed_len = 0;
736 /* Don't print only the ellipsis if the common prefix is one of the
737 possible completions */
738 if (to_print[prefix_bytes] == '\0')
739 prefix_bytes = 0;
741 if (prefix_bytes)
743 char ellipsis;
745 ellipsis = (to_print[prefix_bytes] == '.') ? '_' : '.';
746 for (w = 0; w < ELLIPSIS_LEN; w++)
747 putc (ellipsis, rl_outstream);
748 printed_len = ELLIPSIS_LEN;
751 s = to_print + prefix_bytes;
752 while (*s)
754 if (CTRL_CHAR (*s))
756 putc ('^', rl_outstream);
757 putc (UNCTRL (*s), rl_outstream);
758 printed_len += 2;
759 s++;
760 #if defined (HANDLE_MULTIBYTE)
761 memset (&ps, 0, sizeof (mbstate_t));
762 #endif
764 else if (*s == RUBOUT)
766 putc ('^', rl_outstream);
767 putc ('?', rl_outstream);
768 printed_len += 2;
769 s++;
770 #if defined (HANDLE_MULTIBYTE)
771 memset (&ps, 0, sizeof (mbstate_t));
772 #endif
774 else
776 #if defined (HANDLE_MULTIBYTE)
777 tlen = mbrtowc (&wc, s, end - s, &ps);
778 if (MB_INVALIDCH (tlen))
780 tlen = 1;
781 width = 1;
782 memset (&ps, 0, sizeof (mbstate_t));
784 else if (MB_NULLWCH (tlen))
785 break;
786 else
788 w = wcwidth (wc);
789 width = (w >= 0) ? w : 1;
791 fwrite (s, 1, tlen, rl_outstream);
792 s += tlen;
793 printed_len += width;
794 #else
795 putc (*s, rl_outstream);
796 s++;
797 printed_len++;
798 #endif
802 return printed_len;
805 /* Output TO_PRINT to rl_outstream. If VISIBLE_STATS is defined and we
806 are using it, check for and output a single character for `special'
807 filenames. Return the number of characters we output. */
809 static int
810 print_filename (to_print, full_pathname, prefix_bytes)
811 char *to_print, *full_pathname;
812 int prefix_bytes;
814 int printed_len, extension_char, slen, tlen;
815 char *s, c, *new_full_pathname, *dn;
817 extension_char = 0;
818 printed_len = fnprint (to_print, prefix_bytes);
820 #if defined (VISIBLE_STATS)
821 if (rl_filename_completion_desired && (rl_visible_stats || _rl_complete_mark_directories))
822 #else
823 if (rl_filename_completion_desired && _rl_complete_mark_directories)
824 #endif
826 /* If to_print != full_pathname, to_print is the basename of the
827 path passed. In this case, we try to expand the directory
828 name before checking for the stat character. */
829 if (to_print != full_pathname)
831 /* Terminate the directory name. */
832 c = to_print[-1];
833 to_print[-1] = '\0';
835 /* If setting the last slash in full_pathname to a NUL results in
836 full_pathname being the empty string, we are trying to complete
837 files in the root directory. If we pass a null string to the
838 bash directory completion hook, for example, it will expand it
839 to the current directory. We just want the `/'. */
840 if (full_pathname == 0 || *full_pathname == 0)
841 dn = "/";
842 else if (full_pathname[0] != '/')
843 dn = full_pathname;
844 else if (full_pathname[1] == 0)
845 dn = "//"; /* restore trailing slash to `//' */
846 else if (full_pathname[1] == '/' && full_pathname[2] == 0)
847 dn = "/"; /* don't turn /// into // */
848 else
849 dn = full_pathname;
850 s = tilde_expand (dn);
851 if (rl_directory_completion_hook)
852 (*rl_directory_completion_hook) (&s);
854 slen = strlen (s);
855 tlen = strlen (to_print);
856 new_full_pathname = (char *)xmalloc (slen + tlen + 2);
857 strcpy (new_full_pathname, s);
858 if (s[slen - 1] == '/')
859 slen--;
860 else
861 new_full_pathname[slen] = '/';
862 new_full_pathname[slen] = '/';
863 strcpy (new_full_pathname + slen + 1, to_print);
865 #if defined (VISIBLE_STATS)
866 if (rl_visible_stats)
867 extension_char = stat_char (new_full_pathname);
868 else
869 #endif
870 if (path_isdir (new_full_pathname))
871 extension_char = '/';
873 xfree (new_full_pathname);
874 to_print[-1] = c;
876 else
878 s = tilde_expand (full_pathname);
879 #if defined (VISIBLE_STATS)
880 if (rl_visible_stats)
881 extension_char = stat_char (s);
882 else
883 #endif
884 if (path_isdir (s))
885 extension_char = '/';
888 xfree (s);
889 if (extension_char)
891 putc (extension_char, rl_outstream);
892 printed_len++;
896 return printed_len;
899 static char *
900 rl_quote_filename (s, rtype, qcp)
901 char *s;
902 int rtype;
903 char *qcp;
905 char *r;
907 r = (char *)xmalloc (strlen (s) + 2);
908 *r = *rl_completer_quote_characters;
909 strcpy (r + 1, s);
910 if (qcp)
911 *qcp = *rl_completer_quote_characters;
912 return r;
915 /* Find the bounds of the current word for completion purposes, and leave
916 rl_point set to the end of the word. This function skips quoted
917 substrings (characters between matched pairs of characters in
918 rl_completer_quote_characters). First we try to find an unclosed
919 quoted substring on which to do matching. If one is not found, we use
920 the word break characters to find the boundaries of the current word.
921 We call an application-specific function to decide whether or not a
922 particular word break character is quoted; if that function returns a
923 non-zero result, the character does not break a word. This function
924 returns the opening quote character if we found an unclosed quoted
925 substring, '\0' otherwise. FP, if non-null, is set to a value saying
926 which (shell-like) quote characters we found (single quote, double
927 quote, or backslash) anywhere in the string. DP, if non-null, is set to
928 the value of the delimiter character that caused a word break. */
930 char
931 _rl_find_completion_word (fp, dp)
932 int *fp, *dp;
934 int scan, end, found_quote, delimiter, pass_next, isbrk;
935 char quote_char, *brkchars;
937 end = rl_point;
938 found_quote = delimiter = 0;
939 quote_char = '\0';
941 brkchars = 0;
942 if (rl_completion_word_break_hook)
943 brkchars = (*rl_completion_word_break_hook) ();
944 if (brkchars == 0)
945 brkchars = rl_completer_word_break_characters;
947 if (rl_completer_quote_characters)
949 /* We have a list of characters which can be used in pairs to
950 quote substrings for the completer. Try to find the start
951 of an unclosed quoted substring. */
952 /* FOUND_QUOTE is set so we know what kind of quotes we found. */
953 for (scan = pass_next = 0; scan < end; scan = MB_NEXTCHAR (rl_line_buffer, scan, 1, MB_FIND_ANY))
955 if (pass_next)
957 pass_next = 0;
958 continue;
961 /* Shell-like semantics for single quotes -- don't allow backslash
962 to quote anything in single quotes, especially not the closing
963 quote. If you don't like this, take out the check on the value
964 of quote_char. */
965 if (quote_char != '\'' && rl_line_buffer[scan] == '\\')
967 pass_next = 1;
968 found_quote |= RL_QF_BACKSLASH;
969 continue;
972 if (quote_char != '\0')
974 /* Ignore everything until the matching close quote char. */
975 if (rl_line_buffer[scan] == quote_char)
977 /* Found matching close. Abandon this substring. */
978 quote_char = '\0';
979 rl_point = end;
982 else if (strchr (rl_completer_quote_characters, rl_line_buffer[scan]))
984 /* Found start of a quoted substring. */
985 quote_char = rl_line_buffer[scan];
986 rl_point = scan + 1;
987 /* Shell-like quoting conventions. */
988 if (quote_char == '\'')
989 found_quote |= RL_QF_SINGLE_QUOTE;
990 else if (quote_char == '"')
991 found_quote |= RL_QF_DOUBLE_QUOTE;
992 else
993 found_quote |= RL_QF_OTHER_QUOTE;
998 if (rl_point == end && quote_char == '\0')
1000 /* We didn't find an unclosed quoted substring upon which to do
1001 completion, so use the word break characters to find the
1002 substring on which to complete. */
1003 while (rl_point = MB_PREVCHAR (rl_line_buffer, rl_point, MB_FIND_ANY))
1005 scan = rl_line_buffer[rl_point];
1007 if (strchr (brkchars, scan) == 0)
1008 continue;
1010 /* Call the application-specific function to tell us whether
1011 this word break character is quoted and should be skipped. */
1012 if (rl_char_is_quoted_p && found_quote &&
1013 (*rl_char_is_quoted_p) (rl_line_buffer, rl_point))
1014 continue;
1016 /* Convoluted code, but it avoids an n^2 algorithm with calls
1017 to char_is_quoted. */
1018 break;
1022 /* If we are at an unquoted word break, then advance past it. */
1023 scan = rl_line_buffer[rl_point];
1025 /* If there is an application-specific function to say whether or not
1026 a character is quoted and we found a quote character, let that
1027 function decide whether or not a character is a word break, even
1028 if it is found in rl_completer_word_break_characters. Don't bother
1029 if we're at the end of the line, though. */
1030 if (scan)
1032 if (rl_char_is_quoted_p)
1033 isbrk = (found_quote == 0 ||
1034 (*rl_char_is_quoted_p) (rl_line_buffer, rl_point) == 0) &&
1035 strchr (brkchars, scan) != 0;
1036 else
1037 isbrk = strchr (brkchars, scan) != 0;
1039 if (isbrk)
1041 /* If the character that caused the word break was a quoting
1042 character, then remember it as the delimiter. */
1043 if (rl_basic_quote_characters &&
1044 strchr (rl_basic_quote_characters, scan) &&
1045 (end - rl_point) > 1)
1046 delimiter = scan;
1048 /* If the character isn't needed to determine something special
1049 about what kind of completion to perform, then advance past it. */
1050 if (rl_special_prefixes == 0 || strchr (rl_special_prefixes, scan) == 0)
1051 rl_point++;
1055 if (fp)
1056 *fp = found_quote;
1057 if (dp)
1058 *dp = delimiter;
1060 return (quote_char);
1063 static char **
1064 gen_completion_matches (text, start, end, our_func, found_quote, quote_char)
1065 char *text;
1066 int start, end;
1067 rl_compentry_func_t *our_func;
1068 int found_quote, quote_char;
1070 char **matches;
1072 rl_completion_found_quote = found_quote;
1073 rl_completion_quote_character = quote_char;
1075 /* If the user wants to TRY to complete, but then wants to give
1076 up and use the default completion function, they set the
1077 variable rl_attempted_completion_function. */
1078 if (rl_attempted_completion_function)
1080 _rl_interrupt_immediately++;
1081 matches = (*rl_attempted_completion_function) (text, start, end);
1082 if (_rl_interrupt_immediately > 0)
1083 _rl_interrupt_immediately--;
1085 if (matches || rl_attempted_completion_over)
1087 rl_attempted_completion_over = 0;
1088 return (matches);
1092 /* XXX -- filename dequoting moved into rl_filename_completion_function */
1094 matches = rl_completion_matches (text, our_func);
1095 return matches;
1098 /* Filter out duplicates in MATCHES. This frees up the strings in
1099 MATCHES. */
1100 static char **
1101 remove_duplicate_matches (matches)
1102 char **matches;
1104 char *lowest_common;
1105 int i, j, newlen;
1106 char dead_slot;
1107 char **temp_array;
1109 /* Sort the items. */
1110 for (i = 0; matches[i]; i++)
1113 /* Sort the array without matches[0], since we need it to
1114 stay in place no matter what. */
1115 if (i && rl_sort_completion_matches)
1116 qsort (matches+1, i-1, sizeof (char *), (QSFUNC *)_rl_qsort_string_compare);
1118 /* Remember the lowest common denominator for it may be unique. */
1119 lowest_common = savestring (matches[0]);
1121 for (i = newlen = 0; matches[i + 1]; i++)
1123 if (strcmp (matches[i], matches[i + 1]) == 0)
1125 xfree (matches[i]);
1126 matches[i] = (char *)&dead_slot;
1128 else
1129 newlen++;
1132 /* We have marked all the dead slots with (char *)&dead_slot.
1133 Copy all the non-dead entries into a new array. */
1134 temp_array = (char **)xmalloc ((3 + newlen) * sizeof (char *));
1135 for (i = j = 1; matches[i]; i++)
1137 if (matches[i] != (char *)&dead_slot)
1138 temp_array[j++] = matches[i];
1140 temp_array[j] = (char *)NULL;
1142 if (matches[0] != (char *)&dead_slot)
1143 xfree (matches[0]);
1145 /* Place the lowest common denominator back in [0]. */
1146 temp_array[0] = lowest_common;
1148 /* If there is one string left, and it is identical to the
1149 lowest common denominator, then the LCD is the string to
1150 insert. */
1151 if (j == 2 && strcmp (temp_array[0], temp_array[1]) == 0)
1153 xfree (temp_array[1]);
1154 temp_array[1] = (char *)NULL;
1156 return (temp_array);
1159 /* Find the common prefix of the list of matches, and put it into
1160 matches[0]. */
1161 static int
1162 compute_lcd_of_matches (match_list, matches, text)
1163 char **match_list;
1164 int matches;
1165 const char *text;
1167 register int i, c1, c2, si;
1168 int low; /* Count of max-matched characters. */
1169 char *dtext; /* dequoted TEXT, if needed */
1170 #if defined (HANDLE_MULTIBYTE)
1171 int v;
1172 mbstate_t ps1, ps2;
1173 wchar_t wc1, wc2;
1174 #endif
1176 /* If only one match, just use that. Otherwise, compare each
1177 member of the list with the next, finding out where they
1178 stop matching. */
1179 if (matches == 1)
1181 match_list[0] = match_list[1];
1182 match_list[1] = (char *)NULL;
1183 return 1;
1186 for (i = 1, low = 100000; i < matches; i++)
1188 #if defined (HANDLE_MULTIBYTE)
1189 if (MB_CUR_MAX > 1 && rl_byte_oriented == 0)
1191 memset (&ps1, 0, sizeof (mbstate_t));
1192 memset (&ps2, 0, sizeof (mbstate_t));
1194 #endif
1195 if (_rl_completion_case_fold)
1197 for (si = 0;
1198 (c1 = _rl_to_lower(match_list[i][si])) &&
1199 (c2 = _rl_to_lower(match_list[i + 1][si]));
1200 si++)
1201 #if defined (HANDLE_MULTIBYTE)
1202 if (MB_CUR_MAX > 1 && rl_byte_oriented == 0)
1204 v = mbrtowc (&wc1, match_list[i]+si, strlen (match_list[i]+si), &ps1);
1205 mbrtowc (&wc2, match_list[i+1]+si, strlen (match_list[i+1]+si), &ps2);
1206 wc1 = towlower (wc1);
1207 wc2 = towlower (wc2);
1208 if (wc1 != wc2)
1209 break;
1210 else if (v > 1)
1211 si += v - 1;
1213 else
1214 #endif
1215 if (c1 != c2)
1216 break;
1218 else
1220 for (si = 0;
1221 (c1 = match_list[i][si]) &&
1222 (c2 = match_list[i + 1][si]);
1223 si++)
1224 #if defined (HANDLE_MULTIBYTE)
1225 if (MB_CUR_MAX > 1 && rl_byte_oriented == 0)
1227 mbstate_t ps_back;
1228 ps_back = ps1;
1229 if (!_rl_compare_chars (match_list[i], si, &ps1, match_list[i+1], si, &ps2))
1230 break;
1231 else if ((v = _rl_get_char_len (&match_list[i][si], &ps_back)) > 1)
1232 si += v - 1;
1234 else
1235 #endif
1236 if (c1 != c2)
1237 break;
1240 if (low > si)
1241 low = si;
1244 /* If there were multiple matches, but none matched up to even the
1245 first character, and the user typed something, use that as the
1246 value of matches[0]. */
1247 if (low == 0 && text && *text)
1249 match_list[0] = (char *)xmalloc (strlen (text) + 1);
1250 strcpy (match_list[0], text);
1252 else
1254 match_list[0] = (char *)xmalloc (low + 1);
1256 /* XXX - this might need changes in the presence of multibyte chars */
1258 /* If we are ignoring case, try to preserve the case of the string
1259 the user typed in the face of multiple matches differing in case. */
1260 if (_rl_completion_case_fold)
1262 /* We're making an assumption here:
1263 IF we're completing filenames AND
1264 the application has defined a filename dequoting function AND
1265 we found a quote character AND
1266 the application has requested filename quoting
1267 THEN
1268 we assume that TEXT was dequoted before checking against
1269 the file system and needs to be dequoted here before we
1270 check against the list of matches
1271 FI */
1272 dtext = (char *)NULL;
1273 if (rl_filename_completion_desired &&
1274 rl_filename_dequoting_function &&
1275 rl_completion_found_quote &&
1276 rl_filename_quoting_desired)
1278 dtext = (*rl_filename_dequoting_function) ((char *)text, rl_completion_quote_character);
1279 text = dtext;
1282 /* sort the list to get consistent answers. */
1283 qsort (match_list+1, matches, sizeof(char *), (QSFUNC *)_rl_qsort_string_compare);
1285 si = strlen (text);
1286 if (si <= low)
1288 for (i = 1; i <= matches; i++)
1289 if (strncmp (match_list[i], text, si) == 0)
1291 strncpy (match_list[0], match_list[i], low);
1292 break;
1294 /* no casematch, use first entry */
1295 if (i > matches)
1296 strncpy (match_list[0], match_list[1], low);
1298 else
1299 /* otherwise, just use the text the user typed. */
1300 strncpy (match_list[0], text, low);
1302 FREE (dtext);
1304 else
1305 strncpy (match_list[0], match_list[1], low);
1307 match_list[0][low] = '\0';
1310 return matches;
1313 static int
1314 postprocess_matches (matchesp, matching_filenames)
1315 char ***matchesp;
1316 int matching_filenames;
1318 char *t, **matches, **temp_matches;
1319 int nmatch, i;
1321 matches = *matchesp;
1323 if (matches == 0)
1324 return 0;
1326 /* It seems to me that in all the cases we handle we would like
1327 to ignore duplicate possiblilities. Scan for the text to
1328 insert being identical to the other completions. */
1329 if (rl_ignore_completion_duplicates)
1331 temp_matches = remove_duplicate_matches (matches);
1332 xfree (matches);
1333 matches = temp_matches;
1336 /* If we are matching filenames, then here is our chance to
1337 do clever processing by re-examining the list. Call the
1338 ignore function with the array as a parameter. It can
1339 munge the array, deleting matches as it desires. */
1340 if (rl_ignore_some_completions_function && matching_filenames)
1342 for (nmatch = 1; matches[nmatch]; nmatch++)
1344 (void)(*rl_ignore_some_completions_function) (matches);
1345 if (matches == 0 || matches[0] == 0)
1347 FREE (matches);
1348 *matchesp = (char **)0;
1349 return 0;
1351 else
1353 /* If we removed some matches, recompute the common prefix. */
1354 for (i = 1; matches[i]; i++)
1356 if (i > 1 && i < nmatch)
1358 t = matches[0];
1359 compute_lcd_of_matches (matches, i - 1, t);
1360 FREE (t);
1365 *matchesp = matches;
1366 return (1);
1369 static int
1370 complete_get_screenwidth ()
1372 int cols;
1373 char *envcols;
1375 cols = _rl_completion_columns;
1376 if (cols >= 0 && cols <= _rl_screenwidth)
1377 return cols;
1378 envcols = getenv ("COLUMNS");
1379 if (envcols && *envcols)
1380 cols = atoi (envcols);
1381 if (cols >= 0 && cols <= _rl_screenwidth)
1382 return cols;
1383 return _rl_screenwidth;
1386 /* A convenience function for displaying a list of strings in
1387 columnar format on readline's output stream. MATCHES is the list
1388 of strings, in argv format, LEN is the number of strings in MATCHES,
1389 and MAX is the length of the longest string in MATCHES. */
1390 void
1391 rl_display_match_list (matches, len, max)
1392 char **matches;
1393 int len, max;
1395 int count, limit, printed_len, lines, cols;
1396 int i, j, k, l, common_length, sind;
1397 char *temp, *t;
1399 /* Find the length of the prefix common to all items: length as displayed
1400 characters (common_length) and as a byte index into the matches (sind) */
1401 common_length = sind = 0;
1402 if (_rl_completion_prefix_display_length > 0)
1404 t = printable_part (matches[0]);
1405 temp = strrchr (t, '/');
1406 common_length = temp ? fnwidth (temp) : fnwidth (t);
1407 sind = temp ? strlen (temp) : strlen (t);
1409 if (common_length > _rl_completion_prefix_display_length && common_length > ELLIPSIS_LEN)
1410 max -= common_length - ELLIPSIS_LEN;
1411 else
1412 common_length = sind = 0;
1415 /* How many items of MAX length can we fit in the screen window? */
1416 cols = complete_get_screenwidth ();
1417 max += 2;
1418 limit = cols / max;
1419 if (limit != 1 && (limit * max == cols))
1420 limit--;
1422 /* If cols == 0, limit will end up -1 */
1423 if (cols < _rl_screenwidth && limit < 0)
1424 limit = 1;
1426 /* Avoid a possible floating exception. If max > cols,
1427 limit will be 0 and a divide-by-zero fault will result. */
1428 if (limit == 0)
1429 limit = 1;
1431 /* How many iterations of the printing loop? */
1432 count = (len + (limit - 1)) / limit;
1434 /* Watch out for special case. If LEN is less than LIMIT, then
1435 just do the inner printing loop.
1436 0 < len <= limit implies count = 1. */
1438 /* Sort the items if they are not already sorted. */
1439 if (rl_ignore_completion_duplicates == 0 && rl_sort_completion_matches)
1440 qsort (matches + 1, len, sizeof (char *), (QSFUNC *)_rl_qsort_string_compare);
1442 rl_crlf ();
1444 lines = 0;
1445 if (_rl_print_completions_horizontally == 0)
1447 /* Print the sorted items, up-and-down alphabetically, like ls. */
1448 for (i = 1; i <= count; i++)
1450 for (j = 0, l = i; j < limit; j++)
1452 if (l > len || matches[l] == 0)
1453 break;
1454 else
1456 temp = printable_part (matches[l]);
1457 printed_len = print_filename (temp, matches[l], sind);
1459 if (j + 1 < limit)
1460 for (k = 0; k < max - printed_len; k++)
1461 putc (' ', rl_outstream);
1463 l += count;
1465 rl_crlf ();
1466 lines++;
1467 if (_rl_page_completions && lines >= (_rl_screenheight - 1) && i < count)
1469 lines = _rl_internal_pager (lines);
1470 if (lines < 0)
1471 return;
1475 else
1477 /* Print the sorted items, across alphabetically, like ls -x. */
1478 for (i = 1; matches[i]; i++)
1480 temp = printable_part (matches[i]);
1481 printed_len = print_filename (temp, matches[i], sind);
1482 /* Have we reached the end of this line? */
1483 if (matches[i+1])
1485 if (i && (limit > 1) && (i % limit) == 0)
1487 rl_crlf ();
1488 lines++;
1489 if (_rl_page_completions && lines >= _rl_screenheight - 1)
1491 lines = _rl_internal_pager (lines);
1492 if (lines < 0)
1493 return;
1496 else
1497 for (k = 0; k < max - printed_len; k++)
1498 putc (' ', rl_outstream);
1501 rl_crlf ();
1505 /* Display MATCHES, a list of matching filenames in argv format. This
1506 handles the simple case -- a single match -- first. If there is more
1507 than one match, we compute the number of strings in the list and the
1508 length of the longest string, which will be needed by the display
1509 function. If the application wants to handle displaying the list of
1510 matches itself, it sets RL_COMPLETION_DISPLAY_MATCHES_HOOK to the
1511 address of a function, and we just call it. If we're handling the
1512 display ourselves, we just call rl_display_match_list. We also check
1513 that the list of matches doesn't exceed the user-settable threshold,
1514 and ask the user if he wants to see the list if there are more matches
1515 than RL_COMPLETION_QUERY_ITEMS. */
1516 static void
1517 display_matches (matches)
1518 char **matches;
1520 int len, max, i;
1521 char *temp;
1523 /* Move to the last visible line of a possibly-multiple-line command. */
1524 _rl_move_vert (_rl_vis_botlin);
1526 /* Handle simple case first. What if there is only one answer? */
1527 if (matches[1] == 0)
1529 temp = printable_part (matches[0]);
1530 rl_crlf ();
1531 print_filename (temp, matches[0], 0);
1532 rl_crlf ();
1534 rl_forced_update_display ();
1535 rl_display_fixed = 1;
1537 return;
1540 /* There is more than one answer. Find out how many there are,
1541 and find the maximum printed length of a single entry. */
1542 for (max = 0, i = 1; matches[i]; i++)
1544 temp = printable_part (matches[i]);
1545 len = fnwidth (temp);
1547 if (len > max)
1548 max = len;
1551 len = i - 1;
1553 /* If the caller has defined a display hook, then call that now. */
1554 if (rl_completion_display_matches_hook)
1556 (*rl_completion_display_matches_hook) (matches, len, max);
1557 return;
1560 /* If there are many items, then ask the user if she really wants to
1561 see them all. */
1562 if (rl_completion_query_items > 0 && len >= rl_completion_query_items)
1564 rl_crlf ();
1565 fprintf (rl_outstream, "Display all %d possibilities? (y or n)", len);
1566 fflush (rl_outstream);
1567 if ((completion_y_or_n = get_y_or_n (0)) == 0)
1569 rl_crlf ();
1571 rl_forced_update_display ();
1572 rl_display_fixed = 1;
1574 return;
1578 rl_display_match_list (matches, len, max);
1580 rl_forced_update_display ();
1581 rl_display_fixed = 1;
1584 static char *
1585 make_quoted_replacement (match, mtype, qc)
1586 char *match;
1587 int mtype;
1588 char *qc; /* Pointer to quoting character, if any */
1590 int should_quote, do_replace;
1591 char *replacement;
1593 /* If we are doing completion on quoted substrings, and any matches
1594 contain any of the completer_word_break_characters, then auto-
1595 matically prepend the substring with a quote character (just pick
1596 the first one from the list of such) if it does not already begin
1597 with a quote string. FIXME: Need to remove any such automatically
1598 inserted quote character when it no longer is necessary, such as
1599 if we change the string we are completing on and the new set of
1600 matches don't require a quoted substring. */
1601 replacement = match;
1603 should_quote = match && rl_completer_quote_characters &&
1604 rl_filename_completion_desired &&
1605 rl_filename_quoting_desired;
1607 if (should_quote)
1608 should_quote = should_quote && (!qc || !*qc ||
1609 (rl_completer_quote_characters && strchr (rl_completer_quote_characters, *qc)));
1611 if (should_quote)
1613 /* If there is a single match, see if we need to quote it.
1614 This also checks whether the common prefix of several
1615 matches needs to be quoted. */
1616 should_quote = rl_filename_quote_characters
1617 ? (_rl_strpbrk (match, rl_filename_quote_characters) != 0)
1618 : 0;
1620 do_replace = should_quote ? mtype : NO_MATCH;
1621 /* Quote the replacement, since we found an embedded
1622 word break character in a potential match. */
1623 if (do_replace != NO_MATCH && rl_filename_quoting_function)
1624 replacement = (*rl_filename_quoting_function) (match, do_replace, qc);
1626 return (replacement);
1629 static void
1630 insert_match (match, start, mtype, qc)
1631 char *match;
1632 int start, mtype;
1633 char *qc;
1635 char *replacement, *r;
1636 char oqc;
1637 int end, rlen;
1639 oqc = qc ? *qc : '\0';
1640 replacement = make_quoted_replacement (match, mtype, qc);
1642 /* Now insert the match. */
1643 if (replacement)
1645 rlen = strlen (replacement);
1646 /* Don't double an opening quote character. */
1647 if (qc && *qc && start && rl_line_buffer[start - 1] == *qc &&
1648 replacement[0] == *qc)
1649 start--;
1650 /* If make_quoted_replacement changed the quoting character, remove
1651 the opening quote and insert the (fully-quoted) replacement. */
1652 else if (qc && (*qc != oqc) && start && rl_line_buffer[start - 1] == oqc &&
1653 replacement[0] != oqc)
1654 start--;
1655 end = rl_point - 1;
1656 /* Don't double a closing quote character */
1657 if (qc && *qc && end && rl_line_buffer[rl_point] == *qc && replacement[rlen - 1] == *qc)
1658 end++;
1659 if (_rl_skip_completed_text)
1661 r = replacement;
1662 while (start < rl_end && *r && rl_line_buffer[start] == *r)
1664 start++;
1665 r++;
1667 if (start <= end || *r)
1668 _rl_replace_text (r, start, end);
1669 rl_point = start + strlen (r);
1671 else
1672 _rl_replace_text (replacement, start, end);
1673 if (replacement != match)
1674 xfree (replacement);
1678 /* Append any necessary closing quote and a separator character to the
1679 just-inserted match. If the user has specified that directories
1680 should be marked by a trailing `/', append one of those instead. The
1681 default trailing character is a space. Returns the number of characters
1682 appended. If NONTRIVIAL_MATCH is set, we test for a symlink (if the OS
1683 has them) and don't add a suffix for a symlink to a directory. A
1684 nontrivial match is one that actually adds to the word being completed.
1685 The variable rl_completion_mark_symlink_dirs controls this behavior
1686 (it's initially set to the what the user has chosen, indicated by the
1687 value of _rl_complete_mark_symlink_dirs, but may be modified by an
1688 application's completion function). */
1689 static int
1690 append_to_match (text, delimiter, quote_char, nontrivial_match)
1691 char *text;
1692 int delimiter, quote_char, nontrivial_match;
1694 char temp_string[4], *filename;
1695 int temp_string_index, s;
1696 struct stat finfo;
1698 temp_string_index = 0;
1699 if (quote_char && rl_point && rl_completion_suppress_quote == 0 &&
1700 rl_line_buffer[rl_point - 1] != quote_char)
1701 temp_string[temp_string_index++] = quote_char;
1703 if (delimiter)
1704 temp_string[temp_string_index++] = delimiter;
1705 else if (rl_completion_suppress_append == 0 && rl_completion_append_character)
1706 temp_string[temp_string_index++] = rl_completion_append_character;
1708 temp_string[temp_string_index++] = '\0';
1710 if (rl_filename_completion_desired)
1712 filename = tilde_expand (text);
1713 s = (nontrivial_match && rl_completion_mark_symlink_dirs == 0)
1714 ? LSTAT (filename, &finfo)
1715 : stat (filename, &finfo);
1716 if (s == 0 && S_ISDIR (finfo.st_mode))
1718 if (_rl_complete_mark_directories /* && rl_completion_suppress_append == 0 */)
1720 /* This is clumsy. Avoid putting in a double slash if point
1721 is at the end of the line and the previous character is a
1722 slash. */
1723 if (rl_point && rl_line_buffer[rl_point] == '\0' && rl_line_buffer[rl_point - 1] == '/')
1725 else if (rl_line_buffer[rl_point] != '/')
1726 rl_insert_text ("/");
1729 #ifdef S_ISLNK
1730 /* Don't add anything if the filename is a symlink and resolves to a
1731 directory. */
1732 else if (s == 0 && S_ISLNK (finfo.st_mode) &&
1733 stat (filename, &finfo) == 0 && S_ISDIR (finfo.st_mode))
1735 #endif
1736 else
1738 if (rl_point == rl_end && temp_string_index)
1739 rl_insert_text (temp_string);
1741 xfree (filename);
1743 else
1745 if (rl_point == rl_end && temp_string_index)
1746 rl_insert_text (temp_string);
1749 return (temp_string_index);
1752 static void
1753 insert_all_matches (matches, point, qc)
1754 char **matches;
1755 int point;
1756 char *qc;
1758 int i;
1759 char *rp;
1761 rl_begin_undo_group ();
1762 /* remove any opening quote character; make_quoted_replacement will add
1763 it back. */
1764 if (qc && *qc && point && rl_line_buffer[point - 1] == *qc)
1765 point--;
1766 rl_delete_text (point, rl_point);
1767 rl_point = point;
1769 if (matches[1])
1771 for (i = 1; matches[i]; i++)
1773 rp = make_quoted_replacement (matches[i], SINGLE_MATCH, qc);
1774 rl_insert_text (rp);
1775 rl_insert_text (" ");
1776 if (rp != matches[i])
1777 xfree (rp);
1780 else
1782 rp = make_quoted_replacement (matches[0], SINGLE_MATCH, qc);
1783 rl_insert_text (rp);
1784 rl_insert_text (" ");
1785 if (rp != matches[0])
1786 xfree (rp);
1788 rl_end_undo_group ();
1791 void
1792 _rl_free_match_list (matches)
1793 char **matches;
1795 register int i;
1797 if (matches == 0)
1798 return;
1800 for (i = 0; matches[i]; i++)
1801 xfree (matches[i]);
1802 xfree (matches);
1805 /* Complete the word at or before point.
1806 WHAT_TO_DO says what to do with the completion.
1807 `?' means list the possible completions.
1808 TAB means do standard completion.
1809 `*' means insert all of the possible completions.
1810 `!' means to do standard completion, and list all possible completions if
1811 there is more than one.
1812 `@' means to do standard completion, and list all possible completions if
1813 there is more than one and partial completion is not possible. */
1815 rl_complete_internal (what_to_do)
1816 int what_to_do;
1818 char **matches;
1819 rl_compentry_func_t *our_func;
1820 int start, end, delimiter, found_quote, i, nontrivial_lcd;
1821 char *text, *saved_line_buffer;
1822 char quote_char;
1823 #if 1
1824 int tlen, mlen;
1825 #endif
1827 RL_SETSTATE(RL_STATE_COMPLETING);
1829 set_completion_defaults (what_to_do);
1831 saved_line_buffer = rl_line_buffer ? savestring (rl_line_buffer) : (char *)NULL;
1832 our_func = rl_completion_entry_function
1833 ? rl_completion_entry_function
1834 : rl_filename_completion_function;
1835 /* We now look backwards for the start of a filename/variable word. */
1836 end = rl_point;
1837 found_quote = delimiter = 0;
1838 quote_char = '\0';
1840 if (rl_point)
1841 /* This (possibly) changes rl_point. If it returns a non-zero char,
1842 we know we have an open quote. */
1843 quote_char = _rl_find_completion_word (&found_quote, &delimiter);
1845 start = rl_point;
1846 rl_point = end;
1848 text = rl_copy_text (start, end);
1849 matches = gen_completion_matches (text, start, end, our_func, found_quote, quote_char);
1850 /* nontrivial_lcd is set if the common prefix adds something to the word
1851 being completed. */
1852 nontrivial_lcd = matches && strcmp (text, matches[0]) != 0;
1853 #if 1
1854 if (what_to_do == '!' || what_to_do == '@')
1855 tlen = strlen (text);
1856 #endif
1857 xfree (text);
1859 if (matches == 0)
1861 rl_ding ();
1862 FREE (saved_line_buffer);
1863 completion_changed_buffer = 0;
1864 RL_UNSETSTATE(RL_STATE_COMPLETING);
1865 _rl_reset_completion_state ();
1866 return (0);
1869 /* If we are matching filenames, the attempted completion function will
1870 have set rl_filename_completion_desired to a non-zero value. The basic
1871 rl_filename_completion_function does this. */
1872 i = rl_filename_completion_desired;
1874 if (postprocess_matches (&matches, i) == 0)
1876 rl_ding ();
1877 FREE (saved_line_buffer);
1878 completion_changed_buffer = 0;
1879 RL_UNSETSTATE(RL_STATE_COMPLETING);
1880 _rl_reset_completion_state ();
1881 return (0);
1884 switch (what_to_do)
1886 case TAB:
1887 case '!':
1888 case '@':
1889 /* Insert the first match with proper quoting. */
1890 #if 0
1891 if (*matches[0])
1892 insert_match (matches[0], start, matches[1] ? MULT_MATCH : SINGLE_MATCH, &quote_char);
1893 #else
1894 if (what_to_do == TAB)
1896 if (*matches[0])
1897 insert_match (matches[0], start, matches[1] ? MULT_MATCH : SINGLE_MATCH, &quote_char);
1899 else if (*matches[0] && matches[1] == 0)
1900 /* should we perform the check only if there are multiple matches? */
1901 insert_match (matches[0], start, matches[1] ? MULT_MATCH : SINGLE_MATCH, &quote_char);
1902 else if (*matches[0]) /* what_to_do != TAB && multiple matches */
1904 mlen = *matches[0] ? strlen (matches[0]) : 0;
1905 if (mlen >= tlen)
1906 insert_match (matches[0], start, matches[1] ? MULT_MATCH : SINGLE_MATCH, &quote_char);
1908 #endif
1910 /* If there are more matches, ring the bell to indicate.
1911 If we are in vi mode, Posix.2 says to not ring the bell.
1912 If the `show-all-if-ambiguous' variable is set, display
1913 all the matches immediately. Otherwise, if this was the
1914 only match, and we are hacking files, check the file to
1915 see if it was a directory. If so, and the `mark-directories'
1916 variable is set, add a '/' to the name. If not, and we
1917 are at the end of the line, then add a space. */
1918 if (matches[1])
1920 if (what_to_do == '!')
1922 display_matches (matches);
1923 break;
1925 else if (what_to_do == '@')
1927 if (nontrivial_lcd == 0)
1928 display_matches (matches);
1929 break;
1931 else if (rl_editing_mode != vi_mode)
1932 rl_ding (); /* There are other matches remaining. */
1934 else
1935 append_to_match (matches[0], delimiter, quote_char, nontrivial_lcd);
1937 break;
1939 case '*':
1940 insert_all_matches (matches, start, &quote_char);
1941 break;
1943 case '?':
1944 display_matches (matches);
1945 break;
1947 default:
1948 _rl_ttymsg ("bad value %d for what_to_do in rl_complete", what_to_do);
1949 rl_ding ();
1950 FREE (saved_line_buffer);
1951 RL_UNSETSTATE(RL_STATE_COMPLETING);
1952 _rl_reset_completion_state ();
1953 return 1;
1956 _rl_free_match_list (matches);
1958 /* Check to see if the line has changed through all of this manipulation. */
1959 if (saved_line_buffer)
1961 completion_changed_buffer = strcmp (rl_line_buffer, saved_line_buffer) != 0;
1962 xfree (saved_line_buffer);
1965 RL_UNSETSTATE(RL_STATE_COMPLETING);
1966 _rl_reset_completion_state ();
1967 return 0;
1970 /***************************************************************/
1971 /* */
1972 /* Application-callable completion match generator functions */
1973 /* */
1974 /***************************************************************/
1976 /* Return an array of (char *) which is a list of completions for TEXT.
1977 If there are no completions, return a NULL pointer.
1978 The first entry in the returned array is the substitution for TEXT.
1979 The remaining entries are the possible completions.
1980 The array is terminated with a NULL pointer.
1982 ENTRY_FUNCTION is a function of two args, and returns a (char *).
1983 The first argument is TEXT.
1984 The second is a state argument; it should be zero on the first call, and
1985 non-zero on subsequent calls. It returns a NULL pointer to the caller
1986 when there are no more matches.
1988 char **
1989 rl_completion_matches (text, entry_function)
1990 const char *text;
1991 rl_compentry_func_t *entry_function;
1993 /* Number of slots in match_list. */
1994 int match_list_size;
1996 /* The list of matches. */
1997 char **match_list;
1999 /* Number of matches actually found. */
2000 int matches;
2002 /* Temporary string binder. */
2003 char *string;
2005 matches = 0;
2006 match_list_size = 10;
2007 match_list = (char **)xmalloc ((match_list_size + 1) * sizeof (char *));
2008 match_list[1] = (char *)NULL;
2010 _rl_interrupt_immediately++;
2011 while (string = (*entry_function) (text, matches))
2013 if (matches + 1 == match_list_size)
2014 match_list = (char **)xrealloc
2015 (match_list, ((match_list_size += 10) + 1) * sizeof (char *));
2017 match_list[++matches] = string;
2018 match_list[matches + 1] = (char *)NULL;
2020 if (_rl_interrupt_immediately > 0)
2021 _rl_interrupt_immediately--;
2023 /* If there were any matches, then look through them finding out the
2024 lowest common denominator. That then becomes match_list[0]. */
2025 if (matches)
2026 compute_lcd_of_matches (match_list, matches, text);
2027 else /* There were no matches. */
2029 xfree (match_list);
2030 match_list = (char **)NULL;
2032 return (match_list);
2035 /* A completion function for usernames.
2036 TEXT contains a partial username preceded by a random
2037 character (usually `~'). */
2038 char *
2039 rl_username_completion_function (text, state)
2040 const char *text;
2041 int state;
2043 #if defined (__WIN32__) || defined (__OPENNT)
2044 return (char *)NULL;
2045 #else /* !__WIN32__ && !__OPENNT) */
2046 static char *username = (char *)NULL;
2047 static struct passwd *entry;
2048 static int namelen, first_char, first_char_loc;
2049 char *value;
2051 if (state == 0)
2053 FREE (username);
2055 first_char = *text;
2056 first_char_loc = first_char == '~';
2058 username = savestring (&text[first_char_loc]);
2059 namelen = strlen (username);
2060 setpwent ();
2063 #if defined (HAVE_GETPWENT)
2064 while (entry = getpwent ())
2066 /* Null usernames should result in all users as possible completions. */
2067 if (namelen == 0 || (STREQN (username, entry->pw_name, namelen)))
2068 break;
2070 #endif
2072 if (entry == 0)
2074 #if defined (HAVE_GETPWENT)
2075 endpwent ();
2076 #endif
2077 return ((char *)NULL);
2079 else
2081 value = (char *)xmalloc (2 + strlen (entry->pw_name));
2083 *value = *text;
2085 strcpy (value + first_char_loc, entry->pw_name);
2087 if (first_char == '~')
2088 rl_filename_completion_desired = 1;
2090 return (value);
2092 #endif /* !__WIN32__ && !__OPENNT */
2095 /* Return non-zero if CONVFN matches FILENAME up to the length of FILENAME
2096 (FILENAME_LEN). If _rl_completion_case_fold is set, compare without
2097 regard to the alphabetic case of characters. CONVFN is the possibly-
2098 converted directory entry; FILENAME is what the user typed. */
2099 static int
2100 complete_fncmp (convfn, convlen, filename, filename_len)
2101 const char *convfn;
2102 int convlen;
2103 const char *filename;
2104 int filename_len;
2106 register char *s1, *s2;
2107 int d, len;
2109 /* Otherwise, if these match up to the length of filename, then
2110 it is a match. */
2111 if (_rl_completion_case_fold && _rl_completion_case_map)
2113 /* Case-insensitive comparison treating _ and - as equivalent */
2114 if (filename_len == 0)
2115 return 1;
2116 if (convlen < filename_len)
2117 return 0;
2118 s1 = (char *)convfn;
2119 s2 = (char *)filename;
2120 len = filename_len;
2123 d = _rl_to_lower (*s1) - _rl_to_lower (*s2);
2124 /* *s1 == [-_] && *s2 == [-_] */
2125 if ((*s1 == '-' || *s1 == '_') && (*s2 == '-' || *s2 == '_'))
2126 d = 0;
2127 if (d != 0)
2128 return 0;
2129 s1++; s2++; /* already checked convlen >= filename_len */
2131 while (--len != 0);
2132 return 1;
2134 else if (_rl_completion_case_fold)
2136 if ((_rl_to_lower (convfn[0]) == _rl_to_lower (filename[0])) &&
2137 (convlen >= filename_len) &&
2138 (_rl_strnicmp (filename, convfn, filename_len) == 0))
2139 return 1;
2141 else
2143 if ((convfn[0] == filename[0]) &&
2144 (convlen >= filename_len) &&
2145 (strncmp (filename, convfn, filename_len) == 0))
2146 return 1;
2148 return 0;
2151 /* Okay, now we write the entry_function for filename completion. In the
2152 general case. Note that completion in the shell is a little different
2153 because of all the pathnames that must be followed when looking up the
2154 completion for a command. */
2155 char *
2156 rl_filename_completion_function (text, state)
2157 const char *text;
2158 int state;
2160 static DIR *directory = (DIR *)NULL;
2161 static char *filename = (char *)NULL;
2162 static char *dirname = (char *)NULL;
2163 static char *users_dirname = (char *)NULL;
2164 static int filename_len;
2165 char *temp, *dentry, *convfn;
2166 int dirlen, dentlen, convlen;
2167 struct dirent *entry;
2169 /* If we don't have any state, then do some initialization. */
2170 if (state == 0)
2172 /* If we were interrupted before closing the directory or reading
2173 all of its contents, close it. */
2174 if (directory)
2176 closedir (directory);
2177 directory = (DIR *)NULL;
2179 FREE (dirname);
2180 FREE (filename);
2181 FREE (users_dirname);
2183 filename = savestring (text);
2184 if (*text == 0)
2185 text = ".";
2186 dirname = savestring (text);
2188 temp = strrchr (dirname, '/');
2190 #if defined (__MSDOS__) || defined (_WIN32)
2191 /* special hack for //X/... */
2192 if (dirname[0] == '/' && dirname[1] == '/' && ISALPHA ((unsigned char)dirname[2]) && dirname[3] == '/')
2193 temp = strrchr (dirname + 3, '/');
2194 #endif
2196 if (temp)
2198 strcpy (filename, ++temp);
2199 *temp = '\0';
2201 #if defined (__MSDOS__) || (defined (_WIN32) && !defined (__CYGWIN__))
2202 /* searches from current directory on the drive */
2203 else if (ISALPHA ((unsigned char)dirname[0]) && dirname[1] == ':')
2205 strcpy (filename, dirname + 2);
2206 dirname[2] = '\0';
2208 #endif
2209 else
2211 dirname[0] = '.';
2212 dirname[1] = '\0';
2215 /* We aren't done yet. We also support the "~user" syntax. */
2217 /* Save the version of the directory that the user typed, dequoting
2218 it if necessary. */
2219 if (rl_completion_found_quote && rl_filename_dequoting_function)
2220 users_dirname = (*rl_filename_dequoting_function) (dirname, rl_completion_quote_character);
2221 else
2222 users_dirname = savestring (dirname);
2224 if (*dirname == '~')
2226 temp = tilde_expand (dirname);
2227 xfree (dirname);
2228 dirname = temp;
2231 /* We have saved the possibly-dequoted version of the directory name
2232 the user typed. Now transform the directory name we're going to
2233 pass to opendir(2). The directory rewrite hook modifies only the
2234 directory name; the directory completion hook modifies both the
2235 directory name passed to opendir(2) and the version the user
2236 typed. Both the directory completion and rewrite hooks should perform
2237 any necessary dequoting. The hook functions return 1 if they modify
2238 the directory name argument. If either hook returns 0, it should
2239 not modify the directory name pointer passed as an argument. */
2240 if (rl_directory_rewrite_hook)
2241 (*rl_directory_rewrite_hook) (&dirname);
2242 else if (rl_directory_completion_hook && (*rl_directory_completion_hook) (&dirname))
2244 xfree (users_dirname);
2245 users_dirname = savestring (dirname);
2247 else if (rl_completion_found_quote && rl_filename_dequoting_function)
2249 /* delete single and double quotes */
2250 xfree (dirname);
2251 dirname = savestring (users_dirname);
2253 directory = opendir (dirname);
2255 /* Now dequote a non-null filename. */
2256 if (filename && *filename && rl_completion_found_quote && rl_filename_dequoting_function)
2258 /* delete single and double quotes */
2259 temp = (*rl_filename_dequoting_function) (filename, rl_completion_quote_character);
2260 xfree (filename);
2261 filename = temp;
2263 filename_len = strlen (filename);
2265 rl_filename_completion_desired = 1;
2268 /* At this point we should entertain the possibility of hacking wildcarded
2269 filenames, like /usr/man/man<WILD>/te<TAB>. If the directory name
2270 contains globbing characters, then build an array of directories, and
2271 then map over that list while completing. */
2272 /* *** UNIMPLEMENTED *** */
2274 /* Now that we have some state, we can read the directory. */
2276 entry = (struct dirent *)NULL;
2277 while (directory && (entry = readdir (directory)))
2279 convfn = dentry = entry->d_name;
2280 convlen = dentlen = D_NAMLEN (entry);
2282 if (rl_filename_rewrite_hook)
2284 convfn = (*rl_filename_rewrite_hook) (dentry, dentlen);
2285 convlen = (convfn == dentry) ? dentlen : strlen (convfn);
2288 /* Special case for no filename. If the user has disabled the
2289 `match-hidden-files' variable, skip filenames beginning with `.'.
2290 All other entries except "." and ".." match. */
2291 if (filename_len == 0)
2293 if (_rl_match_hidden_files == 0 && HIDDEN_FILE (convfn))
2294 continue;
2296 if (convfn[0] != '.' ||
2297 (convfn[1] && (convfn[1] != '.' || convfn[2])))
2298 break;
2300 else
2302 if (complete_fncmp (convfn, convlen, filename, filename_len))
2303 break;
2307 if (entry == 0)
2309 if (directory)
2311 closedir (directory);
2312 directory = (DIR *)NULL;
2314 if (dirname)
2316 xfree (dirname);
2317 dirname = (char *)NULL;
2319 if (filename)
2321 xfree (filename);
2322 filename = (char *)NULL;
2324 if (users_dirname)
2326 xfree (users_dirname);
2327 users_dirname = (char *)NULL;
2330 return (char *)NULL;
2332 else
2334 /* dirname && (strcmp (dirname, ".") != 0) */
2335 if (dirname && (dirname[0] != '.' || dirname[1]))
2337 if (rl_complete_with_tilde_expansion && *users_dirname == '~')
2339 dirlen = strlen (dirname);
2340 temp = (char *)xmalloc (2 + dirlen + D_NAMLEN (entry));
2341 strcpy (temp, dirname);
2342 /* Canonicalization cuts off any final slash present. We
2343 may need to add it back. */
2344 if (dirname[dirlen - 1] != '/')
2346 temp[dirlen++] = '/';
2347 temp[dirlen] = '\0';
2350 else
2352 dirlen = strlen (users_dirname);
2353 temp = (char *)xmalloc (2 + dirlen + D_NAMLEN (entry));
2354 strcpy (temp, users_dirname);
2355 /* Make sure that temp has a trailing slash here. */
2356 if (users_dirname[dirlen - 1] != '/')
2357 temp[dirlen++] = '/';
2360 strcpy (temp + dirlen, convfn);
2362 else
2363 temp = savestring (convfn);
2365 if (convfn != dentry)
2366 xfree (convfn);
2368 return (temp);
2372 /* An initial implementation of a menu completion function a la tcsh. The
2373 first time (if the last readline command was not rl_old_menu_complete), we
2374 generate the list of matches. This code is very similar to the code in
2375 rl_complete_internal -- there should be a way to combine the two. Then,
2376 for each item in the list of matches, we insert the match in an undoable
2377 fashion, with the appropriate character appended (this happens on the
2378 second and subsequent consecutive calls to rl_old_menu_complete). When we
2379 hit the end of the match list, we restore the original unmatched text,
2380 ring the bell, and reset the counter to zero. */
2382 rl_old_menu_complete (count, invoking_key)
2383 int count, invoking_key;
2385 rl_compentry_func_t *our_func;
2386 int matching_filenames, found_quote;
2388 static char *orig_text;
2389 static char **matches = (char **)0;
2390 static int match_list_index = 0;
2391 static int match_list_size = 0;
2392 static int orig_start, orig_end;
2393 static char quote_char;
2394 static int delimiter;
2396 /* The first time through, we generate the list of matches and set things
2397 up to insert them. */
2398 if (rl_last_func != rl_old_menu_complete)
2400 /* Clean up from previous call, if any. */
2401 FREE (orig_text);
2402 if (matches)
2403 _rl_free_match_list (matches);
2405 match_list_index = match_list_size = 0;
2406 matches = (char **)NULL;
2408 rl_completion_invoking_key = invoking_key;
2410 RL_SETSTATE(RL_STATE_COMPLETING);
2412 /* Only the completion entry function can change these. */
2413 set_completion_defaults ('%');
2415 our_func = rl_menu_completion_entry_function;
2416 if (our_func == 0)
2417 our_func = rl_completion_entry_function
2418 ? rl_completion_entry_function
2419 : rl_filename_completion_function;
2421 /* We now look backwards for the start of a filename/variable word. */
2422 orig_end = rl_point;
2423 found_quote = delimiter = 0;
2424 quote_char = '\0';
2426 if (rl_point)
2427 /* This (possibly) changes rl_point. If it returns a non-zero char,
2428 we know we have an open quote. */
2429 quote_char = _rl_find_completion_word (&found_quote, &delimiter);
2431 orig_start = rl_point;
2432 rl_point = orig_end;
2434 orig_text = rl_copy_text (orig_start, orig_end);
2435 matches = gen_completion_matches (orig_text, orig_start, orig_end,
2436 our_func, found_quote, quote_char);
2438 /* If we are matching filenames, the attempted completion function will
2439 have set rl_filename_completion_desired to a non-zero value. The basic
2440 rl_filename_completion_function does this. */
2441 matching_filenames = rl_filename_completion_desired;
2443 if (matches == 0 || postprocess_matches (&matches, matching_filenames) == 0)
2445 rl_ding ();
2446 FREE (matches);
2447 matches = (char **)0;
2448 FREE (orig_text);
2449 orig_text = (char *)0;
2450 completion_changed_buffer = 0;
2451 RL_UNSETSTATE(RL_STATE_COMPLETING);
2452 return (0);
2455 RL_UNSETSTATE(RL_STATE_COMPLETING);
2457 for (match_list_size = 0; matches[match_list_size]; match_list_size++)
2459 /* matches[0] is lcd if match_list_size > 1, but the circular buffer
2460 code below should take care of it. */
2462 if (match_list_size > 1 && _rl_complete_show_all)
2463 display_matches (matches);
2466 /* Now we have the list of matches. Replace the text between
2467 rl_line_buffer[orig_start] and rl_line_buffer[rl_point] with
2468 matches[match_list_index], and add any necessary closing char. */
2470 if (matches == 0 || match_list_size == 0)
2472 rl_ding ();
2473 FREE (matches);
2474 matches = (char **)0;
2475 completion_changed_buffer = 0;
2476 return (0);
2479 match_list_index += count;
2480 if (match_list_index < 0)
2482 while (match_list_index < 0)
2483 match_list_index += match_list_size;
2485 else
2486 match_list_index %= match_list_size;
2488 if (match_list_index == 0 && match_list_size > 1)
2490 rl_ding ();
2491 insert_match (orig_text, orig_start, MULT_MATCH, &quote_char);
2493 else
2495 insert_match (matches[match_list_index], orig_start, SINGLE_MATCH, &quote_char);
2496 append_to_match (matches[match_list_index], delimiter, quote_char,
2497 strcmp (orig_text, matches[match_list_index]));
2500 completion_changed_buffer = 1;
2501 return (0);
2505 rl_menu_complete (count, ignore)
2506 int count, ignore;
2508 rl_compentry_func_t *our_func;
2509 int matching_filenames, found_quote;
2511 static char *orig_text;
2512 static char **matches = (char **)0;
2513 static int match_list_index = 0;
2514 static int match_list_size = 0;
2515 static int nontrivial_lcd = 0;
2516 static int full_completion = 0; /* set to 1 if menu completion should reinitialize on next call */
2517 static int orig_start, orig_end;
2518 static char quote_char;
2519 static int delimiter, cstate;
2521 /* The first time through, we generate the list of matches and set things
2522 up to insert them. */
2523 if ((rl_last_func != rl_menu_complete && rl_last_func != rl_backward_menu_complete) || full_completion)
2525 /* Clean up from previous call, if any. */
2526 FREE (orig_text);
2527 if (matches)
2528 _rl_free_match_list (matches);
2530 match_list_index = match_list_size = 0;
2531 matches = (char **)NULL;
2533 full_completion = 0;
2535 RL_SETSTATE(RL_STATE_COMPLETING);
2537 /* Only the completion entry function can change these. */
2538 set_completion_defaults ('%');
2540 our_func = rl_menu_completion_entry_function;
2541 if (our_func == 0)
2542 our_func = rl_completion_entry_function
2543 ? rl_completion_entry_function
2544 : rl_filename_completion_function;
2546 /* We now look backwards for the start of a filename/variable word. */
2547 orig_end = rl_point;
2548 found_quote = delimiter = 0;
2549 quote_char = '\0';
2551 if (rl_point)
2552 /* This (possibly) changes rl_point. If it returns a non-zero char,
2553 we know we have an open quote. */
2554 quote_char = _rl_find_completion_word (&found_quote, &delimiter);
2556 orig_start = rl_point;
2557 rl_point = orig_end;
2559 orig_text = rl_copy_text (orig_start, orig_end);
2560 matches = gen_completion_matches (orig_text, orig_start, orig_end,
2561 our_func, found_quote, quote_char);
2563 nontrivial_lcd = matches && strcmp (orig_text, matches[0]) != 0;
2565 /* If we are matching filenames, the attempted completion function will
2566 have set rl_filename_completion_desired to a non-zero value. The basic
2567 rl_filename_completion_function does this. */
2568 matching_filenames = rl_filename_completion_desired;
2570 if (matches == 0 || postprocess_matches (&matches, matching_filenames) == 0)
2572 rl_ding ();
2573 FREE (matches);
2574 matches = (char **)0;
2575 FREE (orig_text);
2576 orig_text = (char *)0;
2577 completion_changed_buffer = 0;
2578 RL_UNSETSTATE(RL_STATE_COMPLETING);
2579 return (0);
2582 RL_UNSETSTATE(RL_STATE_COMPLETING);
2584 for (match_list_size = 0; matches[match_list_size]; match_list_size++)
2587 if (match_list_size == 0)
2589 rl_ding ();
2590 FREE (matches);
2591 matches = (char **)0;
2592 match_list_index = 0;
2593 completion_changed_buffer = 0;
2594 return (0);
2597 /* matches[0] is lcd if match_list_size > 1, but the circular buffer
2598 code below should take care of it. */
2599 if (*matches[0])
2601 insert_match (matches[0], orig_start, matches[1] ? MULT_MATCH : SINGLE_MATCH, &quote_char);
2602 orig_end = orig_start + strlen (matches[0]);
2603 completion_changed_buffer = STREQ (orig_text, matches[0]) == 0;
2606 if (match_list_size > 1 && _rl_complete_show_all)
2608 display_matches (matches);
2609 /* If there are so many matches that the user has to be asked
2610 whether or not he wants to see the matches, menu completion
2611 is unwieldy. */
2612 if (rl_completion_query_items > 0 && match_list_size >= rl_completion_query_items)
2614 rl_ding ();
2615 FREE (matches);
2616 matches = (char **)0;
2617 full_completion = 1;
2618 return (0);
2621 else if (match_list_size <= 1)
2623 append_to_match (matches[0], delimiter, quote_char, nontrivial_lcd);
2624 full_completion = 1;
2625 return (0);
2627 else if (_rl_menu_complete_prefix_first && match_list_size > 1)
2629 rl_ding ();
2630 return (0);
2634 /* Now we have the list of matches. Replace the text between
2635 rl_line_buffer[orig_start] and rl_line_buffer[rl_point] with
2636 matches[match_list_index], and add any necessary closing char. */
2638 if (matches == 0 || match_list_size == 0)
2640 rl_ding ();
2641 FREE (matches);
2642 matches = (char **)0;
2643 completion_changed_buffer = 0;
2644 return (0);
2647 match_list_index += count;
2648 if (match_list_index < 0)
2650 while (match_list_index < 0)
2651 match_list_index += match_list_size;
2653 else
2654 match_list_index %= match_list_size;
2656 if (match_list_index == 0 && match_list_size > 1)
2658 rl_ding ();
2659 insert_match (matches[0], orig_start, MULT_MATCH, &quote_char);
2661 else
2663 insert_match (matches[match_list_index], orig_start, SINGLE_MATCH, &quote_char);
2664 append_to_match (matches[match_list_index], delimiter, quote_char,
2665 strcmp (orig_text, matches[match_list_index]));
2668 completion_changed_buffer = 1;
2669 return (0);
2673 rl_backward_menu_complete (count, key)
2674 int count, key;
2676 /* Positive arguments to backward-menu-complete translate into negative
2677 arguments for menu-complete, and vice versa. */
2678 return (rl_menu_complete (-count, key));