HAMMER 60I/Many: Mirroring
[dragonfly.git] / contrib / readline-5.0 / complete.c
blobd212f61840e088cd5b66761835ef7d3a3e026411
1 /* complete.c -- filename completion for readline. */
3 /* Copyright (C) 1987-2004 Free Software Foundation, Inc.
5 This file is part of the GNU Readline Library, a library for
6 reading lines of text with interactive input and history editing.
8 The GNU Readline Library is free software; you can redistribute it
9 and/or modify it under the terms of the GNU General Public License
10 as published by the Free Software Foundation; either version 2, or
11 (at your option) any later version.
13 The GNU Readline Library is distributed in the hope that it will be
14 useful, but WITHOUT ANY WARRANTY; without even the implied warranty
15 of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 The GNU General Public License is often shipped with GNU software, and
19 is generally kept in a file called COPYING or LICENSE. If you do not
20 have a copy of the license, write to the Free Software Foundation,
21 59 Temple Place, Suite 330, Boston, MA 02111 USA. */
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 #include <pwd.h>
53 #include "posixdir.h"
54 #include "posixstat.h"
56 /* System-specific feature definitions and include files. */
57 #include "rldefs.h"
58 #include "rlmbutil.h"
60 /* Some standard library routines. */
61 #include "readline.h"
62 #include "xmalloc.h"
63 #include "rlprivate.h"
65 #ifdef __STDC__
66 typedef int QSFUNC (const void *, const void *);
67 #else
68 typedef int QSFUNC ();
69 #endif
71 #ifdef HAVE_LSTAT
72 # define LSTAT lstat
73 #else
74 # define LSTAT stat
75 #endif
77 /* Unix version of a hidden file. Could be different on other systems. */
78 #define HIDDEN_FILE(fname) ((fname)[0] == '.')
80 /* Most systems don't declare getpwent in <pwd.h> if _POSIX_SOURCE is
81 defined. */
82 #if !defined (HAVE_GETPW_DECLS) || defined (_POSIX_SOURCE)
83 extern struct passwd *getpwent PARAMS((void));
84 #endif /* !HAVE_GETPW_DECLS || _POSIX_SOURCE */
86 /* If non-zero, then this is the address of a function to call when
87 completing a word would normally display the list of possible matches.
88 This function is called instead of actually doing the display.
89 It takes three arguments: (char **matches, int num_matches, int max_length)
90 where MATCHES is the array of strings that matched, NUM_MATCHES is the
91 number of strings in that array, and MAX_LENGTH is the length of the
92 longest string in that array. */
93 rl_compdisp_func_t *rl_completion_display_matches_hook = (rl_compdisp_func_t *)NULL;
95 #if defined (VISIBLE_STATS)
96 # if !defined (X_OK)
97 # define X_OK 1
98 # endif
99 static int stat_char PARAMS((char *));
100 #endif
102 static int path_isdir PARAMS((const char *));
104 static char *rl_quote_filename PARAMS((char *, int, char *));
106 static void set_completion_defaults PARAMS((int));
107 static int get_y_or_n PARAMS((int));
108 static int _rl_internal_pager PARAMS((int));
109 static char *printable_part PARAMS((char *));
110 static int fnwidth PARAMS((const char *));
111 static int fnprint PARAMS((const char *));
112 static int print_filename PARAMS((char *, char *));
114 static char **gen_completion_matches PARAMS((char *, int, int, rl_compentry_func_t *, int, int));
116 static char **remove_duplicate_matches PARAMS((char **));
117 static void insert_match PARAMS((char *, int, int, char *));
118 static int append_to_match PARAMS((char *, int, int, int));
119 static void insert_all_matches PARAMS((char **, int, char *));
120 static void display_matches PARAMS((char **));
121 static int compute_lcd_of_matches PARAMS((char **, int, const char *));
122 static int postprocess_matches PARAMS((char ***, int));
124 static char *make_quoted_replacement PARAMS((char *, int, char *));
126 /* **************************************************************** */
127 /* */
128 /* Completion matching, from readline's point of view. */
129 /* */
130 /* **************************************************************** */
132 /* Variables known only to the readline library. */
134 /* If non-zero, non-unique completions always show the list of matches. */
135 int _rl_complete_show_all = 0;
137 /* If non-zero, non-unique completions show the list of matches, unless it
138 is not possible to do partial completion and modify the line. */
139 int _rl_complete_show_unmodified = 0;
141 /* If non-zero, completed directory names have a slash appended. */
142 int _rl_complete_mark_directories = 1;
144 /* If non-zero, the symlinked directory completion behavior introduced in
145 readline-4.2a is disabled, and symlinks that point to directories have
146 a slash appended (subject to the value of _rl_complete_mark_directories).
147 This is user-settable via the mark-symlinked-directories variable. */
148 int _rl_complete_mark_symlink_dirs = 0;
150 /* If non-zero, completions are printed horizontally in alphabetical order,
151 like `ls -x'. */
152 int _rl_print_completions_horizontally;
154 /* Non-zero means that case is not significant in filename completion. */
155 #if defined (__MSDOS__) && !defined (__DJGPP__)
156 int _rl_completion_case_fold = 1;
157 #else
158 int _rl_completion_case_fold;
159 #endif
161 /* If non-zero, don't match hidden files (filenames beginning with a `.' on
162 Unix) when doing filename completion. */
163 int _rl_match_hidden_files = 1;
165 /* Global variables available to applications using readline. */
167 #if defined (VISIBLE_STATS)
168 /* Non-zero means add an additional character to each filename displayed
169 during listing completion iff rl_filename_completion_desired which helps
170 to indicate the type of file being listed. */
171 int rl_visible_stats = 0;
172 #endif /* VISIBLE_STATS */
174 /* If non-zero, then this is the address of a function to call when
175 completing on a directory name. The function is called with
176 the address of a string (the current directory name) as an arg. */
177 rl_icppfunc_t *rl_directory_completion_hook = (rl_icppfunc_t *)NULL;
179 rl_icppfunc_t *rl_directory_rewrite_hook = (rl_icppfunc_t *)NULL;
181 /* Non-zero means readline completion functions perform tilde expansion. */
182 int rl_complete_with_tilde_expansion = 0;
184 /* Pointer to the generator function for completion_matches ().
185 NULL means to use rl_filename_completion_function (), the default filename
186 completer. */
187 rl_compentry_func_t *rl_completion_entry_function = (rl_compentry_func_t *)NULL;
189 /* Pointer to alternative function to create matches.
190 Function is called with TEXT, START, and END.
191 START and END are indices in RL_LINE_BUFFER saying what the boundaries
192 of TEXT are.
193 If this function exists and returns NULL then call the value of
194 rl_completion_entry_function to try to match, otherwise use the
195 array of strings returned. */
196 rl_completion_func_t *rl_attempted_completion_function = (rl_completion_func_t *)NULL;
198 /* Non-zero means to suppress normal filename completion after the
199 user-specified completion function has been called. */
200 int rl_attempted_completion_over = 0;
202 /* Set to a character indicating the type of completion being performed
203 by rl_complete_internal, available for use by application completion
204 functions. */
205 int rl_completion_type = 0;
207 /* Up to this many items will be displayed in response to a
208 possible-completions call. After that, we ask the user if
209 she is sure she wants to see them all. */
210 int rl_completion_query_items = 100;
212 int _rl_page_completions = 1;
214 /* The basic list of characters that signal a break between words for the
215 completer routine. The contents of this variable is what breaks words
216 in the shell, i.e. " \t\n\"\\'`@$><=" */
217 const char *rl_basic_word_break_characters = " \t\n\"\\'`@$><=;|&{("; /* }) */
219 /* List of basic quoting characters. */
220 const char *rl_basic_quote_characters = "\"'";
222 /* The list of characters that signal a break between words for
223 rl_complete_internal. The default list is the contents of
224 rl_basic_word_break_characters. */
225 /*const*/ char *rl_completer_word_break_characters = (/*const*/ char *)NULL;
227 /* Hook function to allow an application to set the completion word
228 break characters before readline breaks up the line. Allows
229 position-dependent word break characters. */
230 rl_cpvfunc_t *rl_completion_word_break_hook = (rl_cpvfunc_t *)NULL;
232 /* List of characters which can be used to quote a substring of the line.
233 Completion occurs on the entire substring, and within the substring
234 rl_completer_word_break_characters are treated as any other character,
235 unless they also appear within this list. */
236 const char *rl_completer_quote_characters = (const char *)NULL;
238 /* List of characters that should be quoted in filenames by the completer. */
239 const char *rl_filename_quote_characters = (const char *)NULL;
241 /* List of characters that are word break characters, but should be left
242 in TEXT when it is passed to the completion function. The shell uses
243 this to help determine what kind of completing to do. */
244 const char *rl_special_prefixes = (const char *)NULL;
246 /* If non-zero, then disallow duplicates in the matches. */
247 int rl_ignore_completion_duplicates = 1;
249 /* Non-zero means that the results of the matches are to be treated
250 as filenames. This is ALWAYS zero on entry, and can only be changed
251 within a completion entry finder function. */
252 int rl_filename_completion_desired = 0;
254 /* Non-zero means that the results of the matches are to be quoted using
255 double quotes (or an application-specific quoting mechanism) if the
256 filename contains any characters in rl_filename_quote_chars. This is
257 ALWAYS non-zero on entry, and can only be changed within a completion
258 entry finder function. */
259 int rl_filename_quoting_desired = 1;
261 /* This function, if defined, is called by the completer when real
262 filename completion is done, after all the matching names have been
263 generated. It is passed a (char**) known as matches in the code below.
264 It consists of a NULL-terminated array of pointers to potential
265 matching strings. The 1st element (matches[0]) is the maximal
266 substring that is common to all matches. This function can re-arrange
267 the list of matches as required, but all elements of the array must be
268 free()'d if they are deleted. The main intent of this function is
269 to implement FIGNORE a la SunOS csh. */
270 rl_compignore_func_t *rl_ignore_some_completions_function = (rl_compignore_func_t *)NULL;
272 /* Set to a function to quote a filename in an application-specific fashion.
273 Called with the text to quote, the type of match found (single or multiple)
274 and a pointer to the quoting character to be used, which the function can
275 reset if desired. */
276 rl_quote_func_t *rl_filename_quoting_function = rl_quote_filename;
278 /* Function to call to remove quoting characters from a filename. Called
279 before completion is attempted, so the embedded quotes do not interfere
280 with matching names in the file system. Readline doesn't do anything
281 with this; it's set only by applications. */
282 rl_dequote_func_t *rl_filename_dequoting_function = (rl_dequote_func_t *)NULL;
284 /* Function to call to decide whether or not a word break character is
285 quoted. If a character is quoted, it does not break words for the
286 completer. */
287 rl_linebuf_func_t *rl_char_is_quoted_p = (rl_linebuf_func_t *)NULL;
289 /* If non-zero, the completion functions don't append anything except a
290 possible closing quote. This is set to 0 by rl_complete_internal and
291 may be changed by an application-specific completion function. */
292 int rl_completion_suppress_append = 0;
294 /* Character appended to completed words when at the end of the line. The
295 default is a space. */
296 int rl_completion_append_character = ' ';
298 /* If non-zero, the completion functions don't append any closing quote.
299 This is set to 0 by rl_complete_internal and may be changed by an
300 application-specific completion function. */
301 int rl_completion_suppress_quote = 0;
303 /* Set to any quote character readline thinks it finds before any application
304 completion function is called. */
305 int rl_completion_quote_character;
307 /* Set to a non-zero value if readline found quoting anywhere in the word to
308 be completed; set before any application completion function is called. */
309 int rl_completion_found_quote;
311 /* If non-zero, a slash will be appended to completed filenames that are
312 symbolic links to directory names, subject to the value of the
313 mark-directories variable (which is user-settable). This exists so
314 that application completion functions can override the user's preference
315 (set via the mark-symlinked-directories variable) if appropriate.
316 It's set to the value of _rl_complete_mark_symlink_dirs in
317 rl_complete_internal before any application-specific completion
318 function is called, so without that function doing anything, the user's
319 preferences are honored. */
320 int rl_completion_mark_symlink_dirs;
322 /* If non-zero, inhibit completion (temporarily). */
323 int rl_inhibit_completion;
325 /* Variables local to this file. */
327 /* Local variable states what happened during the last completion attempt. */
328 static int completion_changed_buffer;
330 /*************************************/
331 /* */
332 /* Bindable completion functions */
333 /* */
334 /*************************************/
336 /* Complete the word at or before point. You have supplied the function
337 that does the initial simple matching selection algorithm (see
338 rl_completion_matches ()). The default is to do filename completion. */
340 rl_complete (ignore, invoking_key)
341 int ignore, invoking_key;
343 if (rl_inhibit_completion)
344 return (_rl_insert_char (ignore, invoking_key));
345 else if (rl_last_func == rl_complete && !completion_changed_buffer)
346 return (rl_complete_internal ('?'));
347 else if (_rl_complete_show_all)
348 return (rl_complete_internal ('!'));
349 else if (_rl_complete_show_unmodified)
350 return (rl_complete_internal ('@'));
351 else
352 return (rl_complete_internal (TAB));
355 /* List the possible completions. See description of rl_complete (). */
357 rl_possible_completions (ignore, invoking_key)
358 int ignore, invoking_key;
360 return (rl_complete_internal ('?'));
364 rl_insert_completions (ignore, invoking_key)
365 int ignore, invoking_key;
367 return (rl_complete_internal ('*'));
370 /* Return the correct value to pass to rl_complete_internal performing
371 the same tests as rl_complete. This allows consecutive calls to an
372 application's completion function to list possible completions and for
373 an application-specific completion function to honor the
374 show-all-if-ambiguous readline variable. */
376 rl_completion_mode (cfunc)
377 rl_command_func_t *cfunc;
379 if (rl_last_func == cfunc && !completion_changed_buffer)
380 return '?';
381 else if (_rl_complete_show_all)
382 return '!';
383 else if (_rl_complete_show_unmodified)
384 return '@';
385 else
386 return TAB;
389 /************************************/
390 /* */
391 /* Completion utility functions */
392 /* */
393 /************************************/
395 /* Set default values for readline word completion. These are the variables
396 that application completion functions can change or inspect. */
397 static void
398 set_completion_defaults (what_to_do)
399 int what_to_do;
401 /* Only the completion entry function can change these. */
402 rl_filename_completion_desired = 0;
403 rl_filename_quoting_desired = 1;
404 rl_completion_type = what_to_do;
405 rl_completion_suppress_append = rl_completion_suppress_quote = 0;
407 /* The completion entry function may optionally change this. */
408 rl_completion_mark_symlink_dirs = _rl_complete_mark_symlink_dirs;
411 /* The user must press "y" or "n". Non-zero return means "y" pressed. */
412 static int
413 get_y_or_n (for_pager)
414 int for_pager;
416 int c;
418 for (;;)
420 RL_SETSTATE(RL_STATE_MOREINPUT);
421 c = rl_read_key ();
422 RL_UNSETSTATE(RL_STATE_MOREINPUT);
424 if (c == 'y' || c == 'Y' || c == ' ')
425 return (1);
426 if (c == 'n' || c == 'N' || c == RUBOUT)
427 return (0);
428 if (c == ABORT_CHAR)
429 _rl_abort_internal ();
430 if (for_pager && (c == NEWLINE || c == RETURN))
431 return (2);
432 if (for_pager && (c == 'q' || c == 'Q'))
433 return (0);
434 rl_ding ();
438 static int
439 _rl_internal_pager (lines)
440 int lines;
442 int i;
444 fprintf (rl_outstream, "--More--");
445 fflush (rl_outstream);
446 i = get_y_or_n (1);
447 _rl_erase_entire_line ();
448 if (i == 0)
449 return -1;
450 else if (i == 2)
451 return (lines - 1);
452 else
453 return 0;
456 static int
457 path_isdir (filename)
458 const char *filename;
460 struct stat finfo;
462 return (stat (filename, &finfo) == 0 && S_ISDIR (finfo.st_mode));
465 #if defined (VISIBLE_STATS)
466 /* Return the character which best describes FILENAME.
467 `@' for symbolic links
468 `/' for directories
469 `*' for executables
470 `=' for sockets
471 `|' for FIFOs
472 `%' for character special devices
473 `#' for block special devices */
474 static int
475 stat_char (filename)
476 char *filename;
478 struct stat finfo;
479 int character, r;
481 #if defined (HAVE_LSTAT) && defined (S_ISLNK)
482 r = lstat (filename, &finfo);
483 #else
484 r = stat (filename, &finfo);
485 #endif
487 if (r == -1)
488 return (0);
490 character = 0;
491 if (S_ISDIR (finfo.st_mode))
492 character = '/';
493 #if defined (S_ISCHR)
494 else if (S_ISCHR (finfo.st_mode))
495 character = '%';
496 #endif /* S_ISCHR */
497 #if defined (S_ISBLK)
498 else if (S_ISBLK (finfo.st_mode))
499 character = '#';
500 #endif /* S_ISBLK */
501 #if defined (S_ISLNK)
502 else if (S_ISLNK (finfo.st_mode))
503 character = '@';
504 #endif /* S_ISLNK */
505 #if defined (S_ISSOCK)
506 else if (S_ISSOCK (finfo.st_mode))
507 character = '=';
508 #endif /* S_ISSOCK */
509 #if defined (S_ISFIFO)
510 else if (S_ISFIFO (finfo.st_mode))
511 character = '|';
512 #endif
513 else if (S_ISREG (finfo.st_mode))
515 if (access (filename, X_OK) == 0)
516 character = '*';
518 return (character);
520 #endif /* VISIBLE_STATS */
522 /* Return the portion of PATHNAME that should be output when listing
523 possible completions. If we are hacking filename completion, we
524 are only interested in the basename, the portion following the
525 final slash. Otherwise, we return what we were passed. Since
526 printing empty strings is not very informative, if we're doing
527 filename completion, and the basename is the empty string, we look
528 for the previous slash and return the portion following that. If
529 there's no previous slash, we just return what we were passed. */
530 static char *
531 printable_part (pathname)
532 char *pathname;
534 char *temp, *x;
536 if (rl_filename_completion_desired == 0) /* don't need to do anything */
537 return (pathname);
539 temp = strrchr (pathname, '/');
540 #if defined (__MSDOS__)
541 if (temp == 0 && ISALPHA ((unsigned char)pathname[0]) && pathname[1] == ':')
542 temp = pathname + 1;
543 #endif
545 if (temp == 0 || *temp == '\0')
546 return (pathname);
547 /* If the basename is NULL, we might have a pathname like '/usr/src/'.
548 Look for a previous slash and, if one is found, return the portion
549 following that slash. If there's no previous slash, just return the
550 pathname we were passed. */
551 else if (temp[1] == '\0')
553 for (x = temp - 1; x > pathname; x--)
554 if (*x == '/')
555 break;
556 return ((*x == '/') ? x + 1 : pathname);
558 else
559 return ++temp;
562 /* Compute width of STRING when displayed on screen by print_filename */
563 static int
564 fnwidth (string)
565 const char *string;
567 int width, pos;
568 #if defined (HANDLE_MULTIBYTE)
569 mbstate_t ps;
570 int left, w;
571 size_t clen;
572 wchar_t wc;
574 left = strlen (string) + 1;
575 memset (&ps, 0, sizeof (mbstate_t));
576 #endif
578 width = pos = 0;
579 while (string[pos])
581 if (CTRL_CHAR (*string) || *string == RUBOUT)
583 width += 2;
584 pos++;
586 else
588 #if defined (HANDLE_MULTIBYTE)
589 clen = mbrtowc (&wc, string + pos, left - pos, &ps);
590 if (MB_INVALIDCH (clen))
592 width++;
593 pos++;
594 memset (&ps, 0, sizeof (mbstate_t));
596 else if (MB_NULLWCH (clen))
597 break;
598 else
600 pos += clen;
601 w = wcwidth (wc);
602 width += (w >= 0) ? w : 1;
604 #else
605 width++;
606 pos++;
607 #endif
611 return width;
614 static int
615 fnprint (to_print)
616 const char *to_print;
618 int printed_len;
619 const char *s;
620 #if defined (HANDLE_MULTIBYTE)
621 mbstate_t ps;
622 const char *end;
623 size_t tlen;
625 end = to_print + strlen (to_print) + 1;
626 memset (&ps, 0, sizeof (mbstate_t));
627 #endif
629 printed_len = 0;
630 s = to_print;
631 while (*s)
633 if (CTRL_CHAR (*s))
635 putc ('^', rl_outstream);
636 putc (UNCTRL (*s), rl_outstream);
637 printed_len += 2;
638 s++;
639 #if defined (HANDLE_MULTIBYTE)
640 memset (&ps, 0, sizeof (mbstate_t));
641 #endif
643 else if (*s == RUBOUT)
645 putc ('^', rl_outstream);
646 putc ('?', rl_outstream);
647 printed_len += 2;
648 s++;
649 #if defined (HANDLE_MULTIBYTE)
650 memset (&ps, 0, sizeof (mbstate_t));
651 #endif
653 else
655 #if defined (HANDLE_MULTIBYTE)
656 tlen = mbrlen (s, end - s, &ps);
657 if (MB_INVALIDCH (tlen))
659 tlen = 1;
660 memset (&ps, 0, sizeof (mbstate_t));
662 else if (MB_NULLWCH (tlen))
663 break;
664 fwrite (s, 1, tlen, rl_outstream);
665 s += tlen;
666 #else
667 putc (*s, rl_outstream);
668 s++;
669 #endif
670 printed_len++;
674 return printed_len;
677 /* Output TO_PRINT to rl_outstream. If VISIBLE_STATS is defined and we
678 are using it, check for and output a single character for `special'
679 filenames. Return the number of characters we output. */
681 static int
682 print_filename (to_print, full_pathname)
683 char *to_print, *full_pathname;
685 int printed_len, extension_char, slen, tlen;
686 char *s, c, *new_full_pathname;
688 extension_char = 0;
689 printed_len = fnprint (to_print);
691 #if defined (VISIBLE_STATS)
692 if (rl_filename_completion_desired && (rl_visible_stats || _rl_complete_mark_directories))
693 #else
694 if (rl_filename_completion_desired && _rl_complete_mark_directories)
695 #endif
697 /* If to_print != full_pathname, to_print is the basename of the
698 path passed. In this case, we try to expand the directory
699 name before checking for the stat character. */
700 if (to_print != full_pathname)
702 /* Terminate the directory name. */
703 c = to_print[-1];
704 to_print[-1] = '\0';
706 /* If setting the last slash in full_pathname to a NUL results in
707 full_pathname being the empty string, we are trying to complete
708 files in the root directory. If we pass a null string to the
709 bash directory completion hook, for example, it will expand it
710 to the current directory. We just want the `/'. */
711 s = tilde_expand (full_pathname && *full_pathname ? full_pathname : "/");
712 if (rl_directory_completion_hook)
713 (*rl_directory_completion_hook) (&s);
715 slen = strlen (s);
716 tlen = strlen (to_print);
717 new_full_pathname = (char *)xmalloc (slen + tlen + 2);
718 strcpy (new_full_pathname, s);
719 new_full_pathname[slen] = '/';
720 strcpy (new_full_pathname + slen + 1, to_print);
722 #if defined (VISIBLE_STATS)
723 if (rl_visible_stats)
724 extension_char = stat_char (new_full_pathname);
725 else
726 #endif
727 if (path_isdir (new_full_pathname))
728 extension_char = '/';
730 free (new_full_pathname);
731 to_print[-1] = c;
733 else
735 s = tilde_expand (full_pathname);
736 #if defined (VISIBLE_STATS)
737 if (rl_visible_stats)
738 extension_char = stat_char (s);
739 else
740 #endif
741 if (path_isdir (s))
742 extension_char = '/';
745 free (s);
746 if (extension_char)
748 putc (extension_char, rl_outstream);
749 printed_len++;
753 return printed_len;
756 static char *
757 rl_quote_filename (s, rtype, qcp)
758 char *s;
759 int rtype;
760 char *qcp;
762 char *r;
764 r = (char *)xmalloc (strlen (s) + 2);
765 *r = *rl_completer_quote_characters;
766 strcpy (r + 1, s);
767 if (qcp)
768 *qcp = *rl_completer_quote_characters;
769 return r;
772 /* Find the bounds of the current word for completion purposes, and leave
773 rl_point set to the end of the word. This function skips quoted
774 substrings (characters between matched pairs of characters in
775 rl_completer_quote_characters). First we try to find an unclosed
776 quoted substring on which to do matching. If one is not found, we use
777 the word break characters to find the boundaries of the current word.
778 We call an application-specific function to decide whether or not a
779 particular word break character is quoted; if that function returns a
780 non-zero result, the character does not break a word. This function
781 returns the opening quote character if we found an unclosed quoted
782 substring, '\0' otherwise. FP, if non-null, is set to a value saying
783 which (shell-like) quote characters we found (single quote, double
784 quote, or backslash) anywhere in the string. DP, if non-null, is set to
785 the value of the delimiter character that caused a word break. */
787 char
788 _rl_find_completion_word (fp, dp)
789 int *fp, *dp;
791 int scan, end, found_quote, delimiter, pass_next, isbrk;
792 char quote_char, *brkchars;
794 end = rl_point;
795 found_quote = delimiter = 0;
796 quote_char = '\0';
798 brkchars = 0;
799 if (rl_completion_word_break_hook)
800 brkchars = (*rl_completion_word_break_hook) ();
801 if (brkchars == 0)
802 brkchars = rl_completer_word_break_characters;
804 if (rl_completer_quote_characters)
806 /* We have a list of characters which can be used in pairs to
807 quote substrings for the completer. Try to find the start
808 of an unclosed quoted substring. */
809 /* FOUND_QUOTE is set so we know what kind of quotes we found. */
810 #if defined (HANDLE_MULTIBYTE)
811 for (scan = pass_next = 0; scan < end;
812 scan = ((MB_CUR_MAX == 1 || rl_byte_oriented)
813 ? (scan + 1)
814 : _rl_find_next_mbchar (rl_line_buffer, scan, 1, MB_FIND_ANY)))
815 #else
816 for (scan = pass_next = 0; scan < end; scan++)
817 #endif
819 if (pass_next)
821 pass_next = 0;
822 continue;
825 /* Shell-like semantics for single quotes -- don't allow backslash
826 to quote anything in single quotes, especially not the closing
827 quote. If you don't like this, take out the check on the value
828 of quote_char. */
829 if (quote_char != '\'' && rl_line_buffer[scan] == '\\')
831 pass_next = 1;
832 found_quote |= RL_QF_BACKSLASH;
833 continue;
836 if (quote_char != '\0')
838 /* Ignore everything until the matching close quote char. */
839 if (rl_line_buffer[scan] == quote_char)
841 /* Found matching close. Abandon this substring. */
842 quote_char = '\0';
843 rl_point = end;
846 else if (strchr (rl_completer_quote_characters, rl_line_buffer[scan]))
848 /* Found start of a quoted substring. */
849 quote_char = rl_line_buffer[scan];
850 rl_point = scan + 1;
851 /* Shell-like quoting conventions. */
852 if (quote_char == '\'')
853 found_quote |= RL_QF_SINGLE_QUOTE;
854 else if (quote_char == '"')
855 found_quote |= RL_QF_DOUBLE_QUOTE;
856 else
857 found_quote |= RL_QF_OTHER_QUOTE;
862 if (rl_point == end && quote_char == '\0')
864 /* We didn't find an unclosed quoted substring upon which to do
865 completion, so use the word break characters to find the
866 substring on which to complete. */
867 #if defined (HANDLE_MULTIBYTE)
868 while (rl_point = _rl_find_prev_mbchar (rl_line_buffer, rl_point, MB_FIND_ANY))
869 #else
870 while (--rl_point)
871 #endif
873 scan = rl_line_buffer[rl_point];
875 if (strchr (brkchars, scan) == 0)
876 continue;
878 /* Call the application-specific function to tell us whether
879 this word break character is quoted and should be skipped. */
880 if (rl_char_is_quoted_p && found_quote &&
881 (*rl_char_is_quoted_p) (rl_line_buffer, rl_point))
882 continue;
884 /* Convoluted code, but it avoids an n^2 algorithm with calls
885 to char_is_quoted. */
886 break;
890 /* If we are at an unquoted word break, then advance past it. */
891 scan = rl_line_buffer[rl_point];
893 /* If there is an application-specific function to say whether or not
894 a character is quoted and we found a quote character, let that
895 function decide whether or not a character is a word break, even
896 if it is found in rl_completer_word_break_characters. Don't bother
897 if we're at the end of the line, though. */
898 if (scan)
900 if (rl_char_is_quoted_p)
901 isbrk = (found_quote == 0 ||
902 (*rl_char_is_quoted_p) (rl_line_buffer, rl_point) == 0) &&
903 strchr (brkchars, scan) != 0;
904 else
905 isbrk = strchr (brkchars, scan) != 0;
907 if (isbrk)
909 /* If the character that caused the word break was a quoting
910 character, then remember it as the delimiter. */
911 if (rl_basic_quote_characters &&
912 strchr (rl_basic_quote_characters, scan) &&
913 (end - rl_point) > 1)
914 delimiter = scan;
916 /* If the character isn't needed to determine something special
917 about what kind of completion to perform, then advance past it. */
918 if (rl_special_prefixes == 0 || strchr (rl_special_prefixes, scan) == 0)
919 rl_point++;
923 if (fp)
924 *fp = found_quote;
925 if (dp)
926 *dp = delimiter;
928 return (quote_char);
931 static char **
932 gen_completion_matches (text, start, end, our_func, found_quote, quote_char)
933 char *text;
934 int start, end;
935 rl_compentry_func_t *our_func;
936 int found_quote, quote_char;
938 char **matches, *temp;
940 rl_completion_found_quote = found_quote;
941 rl_completion_quote_character = quote_char;
943 /* If the user wants to TRY to complete, but then wants to give
944 up and use the default completion function, they set the
945 variable rl_attempted_completion_function. */
946 if (rl_attempted_completion_function)
948 matches = (*rl_attempted_completion_function) (text, start, end);
950 if (matches || rl_attempted_completion_over)
952 rl_attempted_completion_over = 0;
953 return (matches);
957 /* Beware -- we're stripping the quotes here. Do this only if we know
958 we are doing filename completion and the application has defined a
959 filename dequoting function. */
960 temp = (char *)NULL;
962 if (found_quote && our_func == rl_filename_completion_function &&
963 rl_filename_dequoting_function)
965 /* delete single and double quotes */
966 temp = (*rl_filename_dequoting_function) (text, quote_char);
967 text = temp; /* not freeing text is not a memory leak */
970 matches = rl_completion_matches (text, our_func);
971 FREE (temp);
972 return matches;
975 /* Filter out duplicates in MATCHES. This frees up the strings in
976 MATCHES. */
977 static char **
978 remove_duplicate_matches (matches)
979 char **matches;
981 char *lowest_common;
982 int i, j, newlen;
983 char dead_slot;
984 char **temp_array;
986 /* Sort the items. */
987 for (i = 0; matches[i]; i++)
990 /* Sort the array without matches[0], since we need it to
991 stay in place no matter what. */
992 if (i)
993 qsort (matches+1, i-1, sizeof (char *), (QSFUNC *)_rl_qsort_string_compare);
995 /* Remember the lowest common denominator for it may be unique. */
996 lowest_common = savestring (matches[0]);
998 for (i = newlen = 0; matches[i + 1]; i++)
1000 if (strcmp (matches[i], matches[i + 1]) == 0)
1002 free (matches[i]);
1003 matches[i] = (char *)&dead_slot;
1005 else
1006 newlen++;
1009 /* We have marked all the dead slots with (char *)&dead_slot.
1010 Copy all the non-dead entries into a new array. */
1011 temp_array = (char **)xmalloc ((3 + newlen) * sizeof (char *));
1012 for (i = j = 1; matches[i]; i++)
1014 if (matches[i] != (char *)&dead_slot)
1015 temp_array[j++] = matches[i];
1017 temp_array[j] = (char *)NULL;
1019 if (matches[0] != (char *)&dead_slot)
1020 free (matches[0]);
1022 /* Place the lowest common denominator back in [0]. */
1023 temp_array[0] = lowest_common;
1025 /* If there is one string left, and it is identical to the
1026 lowest common denominator, then the LCD is the string to
1027 insert. */
1028 if (j == 2 && strcmp (temp_array[0], temp_array[1]) == 0)
1030 free (temp_array[1]);
1031 temp_array[1] = (char *)NULL;
1033 return (temp_array);
1036 /* Find the common prefix of the list of matches, and put it into
1037 matches[0]. */
1038 static int
1039 compute_lcd_of_matches (match_list, matches, text)
1040 char **match_list;
1041 int matches;
1042 const char *text;
1044 register int i, c1, c2, si;
1045 int low; /* Count of max-matched characters. */
1046 char *dtext; /* dequoted TEXT, if needed */
1047 #if defined (HANDLE_MULTIBYTE)
1048 int v;
1049 mbstate_t ps1, ps2;
1050 wchar_t wc1, wc2;
1051 #endif
1053 /* If only one match, just use that. Otherwise, compare each
1054 member of the list with the next, finding out where they
1055 stop matching. */
1056 if (matches == 1)
1058 match_list[0] = match_list[1];
1059 match_list[1] = (char *)NULL;
1060 return 1;
1063 for (i = 1, low = 100000; i < matches; i++)
1065 #if defined (HANDLE_MULTIBYTE)
1066 if (MB_CUR_MAX > 1 && rl_byte_oriented == 0)
1068 memset (&ps1, 0, sizeof (mbstate_t));
1069 memset (&ps2, 0, sizeof (mbstate_t));
1071 #endif
1072 if (_rl_completion_case_fold)
1074 for (si = 0;
1075 (c1 = _rl_to_lower(match_list[i][si])) &&
1076 (c2 = _rl_to_lower(match_list[i + 1][si]));
1077 si++)
1078 #if defined (HANDLE_MULTIBYTE)
1079 if (MB_CUR_MAX > 1 && rl_byte_oriented == 0)
1081 v = mbrtowc (&wc1, match_list[i]+si, strlen (match_list[i]+si), &ps1);
1082 mbrtowc (&wc2, match_list[i+1]+si, strlen (match_list[i+1]+si), &ps2);
1083 wc1 = towlower (wc1);
1084 wc2 = towlower (wc2);
1085 if (wc1 != wc2)
1086 break;
1087 else if (v > 1)
1088 si += v - 1;
1090 else
1091 #endif
1092 if (c1 != c2)
1093 break;
1095 else
1097 for (si = 0;
1098 (c1 = match_list[i][si]) &&
1099 (c2 = match_list[i + 1][si]);
1100 si++)
1101 #if defined (HANDLE_MULTIBYTE)
1102 if (MB_CUR_MAX > 1 && rl_byte_oriented == 0)
1104 mbstate_t ps_back = ps1;
1105 if (!_rl_compare_chars (match_list[i], si, &ps1, match_list[i+1], si, &ps2))
1106 break;
1107 else if ((v = _rl_get_char_len (&match_list[i][si], &ps_back)) > 1)
1108 si += v - 1;
1110 else
1111 #endif
1112 if (c1 != c2)
1113 break;
1116 if (low > si)
1117 low = si;
1120 /* If there were multiple matches, but none matched up to even the
1121 first character, and the user typed something, use that as the
1122 value of matches[0]. */
1123 if (low == 0 && text && *text)
1125 match_list[0] = (char *)xmalloc (strlen (text) + 1);
1126 strcpy (match_list[0], text);
1128 else
1130 match_list[0] = (char *)xmalloc (low + 1);
1132 /* XXX - this might need changes in the presence of multibyte chars */
1134 /* If we are ignoring case, try to preserve the case of the string
1135 the user typed in the face of multiple matches differing in case. */
1136 if (_rl_completion_case_fold)
1138 /* We're making an assumption here:
1139 IF we're completing filenames AND
1140 the application has defined a filename dequoting function AND
1141 we found a quote character AND
1142 the application has requested filename quoting
1143 THEN
1144 we assume that TEXT was dequoted before checking against
1145 the file system and needs to be dequoted here before we
1146 check against the list of matches
1147 FI */
1148 dtext = (char *)NULL;
1149 if (rl_filename_completion_desired &&
1150 rl_filename_dequoting_function &&
1151 rl_completion_found_quote &&
1152 rl_filename_quoting_desired)
1154 dtext = (*rl_filename_dequoting_function) (text, rl_completion_quote_character);
1155 text = dtext;
1158 /* sort the list to get consistent answers. */
1159 qsort (match_list+1, matches, sizeof(char *), (QSFUNC *)_rl_qsort_string_compare);
1161 si = strlen (text);
1162 if (si <= low)
1164 for (i = 1; i <= matches; i++)
1165 if (strncmp (match_list[i], text, si) == 0)
1167 strncpy (match_list[0], match_list[i], low);
1168 break;
1170 /* no casematch, use first entry */
1171 if (i > matches)
1172 strncpy (match_list[0], match_list[1], low);
1174 else
1175 /* otherwise, just use the text the user typed. */
1176 strncpy (match_list[0], text, low);
1178 FREE (dtext);
1180 else
1181 strncpy (match_list[0], match_list[1], low);
1183 match_list[0][low] = '\0';
1186 return matches;
1189 static int
1190 postprocess_matches (matchesp, matching_filenames)
1191 char ***matchesp;
1192 int matching_filenames;
1194 char *t, **matches, **temp_matches;
1195 int nmatch, i;
1197 matches = *matchesp;
1199 if (matches == 0)
1200 return 0;
1202 /* It seems to me that in all the cases we handle we would like
1203 to ignore duplicate possiblilities. Scan for the text to
1204 insert being identical to the other completions. */
1205 if (rl_ignore_completion_duplicates)
1207 temp_matches = remove_duplicate_matches (matches);
1208 free (matches);
1209 matches = temp_matches;
1212 /* If we are matching filenames, then here is our chance to
1213 do clever processing by re-examining the list. Call the
1214 ignore function with the array as a parameter. It can
1215 munge the array, deleting matches as it desires. */
1216 if (rl_ignore_some_completions_function && matching_filenames)
1218 for (nmatch = 1; matches[nmatch]; nmatch++)
1220 (void)(*rl_ignore_some_completions_function) (matches);
1221 if (matches == 0 || matches[0] == 0)
1223 FREE (matches);
1224 *matchesp = (char **)0;
1225 return 0;
1227 else
1229 /* If we removed some matches, recompute the common prefix. */
1230 for (i = 1; matches[i]; i++)
1232 if (i > 1 && i < nmatch)
1234 t = matches[0];
1235 compute_lcd_of_matches (matches, i - 1, t);
1236 FREE (t);
1241 *matchesp = matches;
1242 return (1);
1245 /* A convenience function for displaying a list of strings in
1246 columnar format on readline's output stream. MATCHES is the list
1247 of strings, in argv format, LEN is the number of strings in MATCHES,
1248 and MAX is the length of the longest string in MATCHES. */
1249 void
1250 rl_display_match_list (matches, len, max)
1251 char **matches;
1252 int len, max;
1254 int count, limit, printed_len, lines;
1255 int i, j, k, l;
1256 char *temp;
1258 /* How many items of MAX length can we fit in the screen window? */
1259 max += 2;
1260 limit = _rl_screenwidth / max;
1261 if (limit != 1 && (limit * max == _rl_screenwidth))
1262 limit--;
1264 /* Avoid a possible floating exception. If max > _rl_screenwidth,
1265 limit will be 0 and a divide-by-zero fault will result. */
1266 if (limit == 0)
1267 limit = 1;
1269 /* How many iterations of the printing loop? */
1270 count = (len + (limit - 1)) / limit;
1272 /* Watch out for special case. If LEN is less than LIMIT, then
1273 just do the inner printing loop.
1274 0 < len <= limit implies count = 1. */
1276 /* Sort the items if they are not already sorted. */
1277 if (rl_ignore_completion_duplicates == 0)
1278 qsort (matches + 1, len, sizeof (char *), (QSFUNC *)_rl_qsort_string_compare);
1280 rl_crlf ();
1282 lines = 0;
1283 if (_rl_print_completions_horizontally == 0)
1285 /* Print the sorted items, up-and-down alphabetically, like ls. */
1286 for (i = 1; i <= count; i++)
1288 for (j = 0, l = i; j < limit; j++)
1290 if (l > len || matches[l] == 0)
1291 break;
1292 else
1294 temp = printable_part (matches[l]);
1295 printed_len = print_filename (temp, matches[l]);
1297 if (j + 1 < limit)
1298 for (k = 0; k < max - printed_len; k++)
1299 putc (' ', rl_outstream);
1301 l += count;
1303 rl_crlf ();
1304 lines++;
1305 if (_rl_page_completions && lines >= (_rl_screenheight - 1) && i < count)
1307 lines = _rl_internal_pager (lines);
1308 if (lines < 0)
1309 return;
1313 else
1315 /* Print the sorted items, across alphabetically, like ls -x. */
1316 for (i = 1; matches[i]; i++)
1318 temp = printable_part (matches[i]);
1319 printed_len = print_filename (temp, matches[i]);
1320 /* Have we reached the end of this line? */
1321 if (matches[i+1])
1323 if (i && (limit > 1) && (i % limit) == 0)
1325 rl_crlf ();
1326 lines++;
1327 if (_rl_page_completions && lines >= _rl_screenheight - 1)
1329 lines = _rl_internal_pager (lines);
1330 if (lines < 0)
1331 return;
1334 else
1335 for (k = 0; k < max - printed_len; k++)
1336 putc (' ', rl_outstream);
1339 rl_crlf ();
1343 /* Display MATCHES, a list of matching filenames in argv format. This
1344 handles the simple case -- a single match -- first. If there is more
1345 than one match, we compute the number of strings in the list and the
1346 length of the longest string, which will be needed by the display
1347 function. If the application wants to handle displaying the list of
1348 matches itself, it sets RL_COMPLETION_DISPLAY_MATCHES_HOOK to the
1349 address of a function, and we just call it. If we're handling the
1350 display ourselves, we just call rl_display_match_list. We also check
1351 that the list of matches doesn't exceed the user-settable threshold,
1352 and ask the user if he wants to see the list if there are more matches
1353 than RL_COMPLETION_QUERY_ITEMS. */
1354 static void
1355 display_matches (matches)
1356 char **matches;
1358 int len, max, i;
1359 char *temp;
1361 /* Move to the last visible line of a possibly-multiple-line command. */
1362 _rl_move_vert (_rl_vis_botlin);
1364 /* Handle simple case first. What if there is only one answer? */
1365 if (matches[1] == 0)
1367 temp = printable_part (matches[0]);
1368 rl_crlf ();
1369 print_filename (temp, matches[0]);
1370 rl_crlf ();
1372 rl_forced_update_display ();
1373 rl_display_fixed = 1;
1375 return;
1378 /* There is more than one answer. Find out how many there are,
1379 and find the maximum printed length of a single entry. */
1380 for (max = 0, i = 1; matches[i]; i++)
1382 temp = printable_part (matches[i]);
1383 len = fnwidth (temp);
1385 if (len > max)
1386 max = len;
1389 len = i - 1;
1391 /* If the caller has defined a display hook, then call that now. */
1392 if (rl_completion_display_matches_hook)
1394 (*rl_completion_display_matches_hook) (matches, len, max);
1395 return;
1398 /* If there are many items, then ask the user if she really wants to
1399 see them all. */
1400 if (len >= rl_completion_query_items)
1402 rl_crlf ();
1403 fprintf (rl_outstream, "Display all %d possibilities? (y or n)", len);
1404 fflush (rl_outstream);
1405 if (get_y_or_n (0) == 0)
1407 rl_crlf ();
1409 rl_forced_update_display ();
1410 rl_display_fixed = 1;
1412 return;
1416 rl_display_match_list (matches, len, max);
1418 rl_forced_update_display ();
1419 rl_display_fixed = 1;
1422 static char *
1423 make_quoted_replacement (match, mtype, qc)
1424 char *match;
1425 int mtype;
1426 char *qc; /* Pointer to quoting character, if any */
1428 int should_quote, do_replace;
1429 char *replacement;
1431 /* If we are doing completion on quoted substrings, and any matches
1432 contain any of the completer_word_break_characters, then auto-
1433 matically prepend the substring with a quote character (just pick
1434 the first one from the list of such) if it does not already begin
1435 with a quote string. FIXME: Need to remove any such automatically
1436 inserted quote character when it no longer is necessary, such as
1437 if we change the string we are completing on and the new set of
1438 matches don't require a quoted substring. */
1439 replacement = match;
1441 should_quote = match && rl_completer_quote_characters &&
1442 rl_filename_completion_desired &&
1443 rl_filename_quoting_desired;
1445 if (should_quote)
1446 should_quote = should_quote && (!qc || !*qc ||
1447 (rl_completer_quote_characters && strchr (rl_completer_quote_characters, *qc)));
1449 if (should_quote)
1451 /* If there is a single match, see if we need to quote it.
1452 This also checks whether the common prefix of several
1453 matches needs to be quoted. */
1454 should_quote = rl_filename_quote_characters
1455 ? (_rl_strpbrk (match, rl_filename_quote_characters) != 0)
1456 : 0;
1458 do_replace = should_quote ? mtype : NO_MATCH;
1459 /* Quote the replacement, since we found an embedded
1460 word break character in a potential match. */
1461 if (do_replace != NO_MATCH && rl_filename_quoting_function)
1462 replacement = (*rl_filename_quoting_function) (match, do_replace, qc);
1464 return (replacement);
1467 static void
1468 insert_match (match, start, mtype, qc)
1469 char *match;
1470 int start, mtype;
1471 char *qc;
1473 char *replacement;
1474 char oqc;
1476 oqc = qc ? *qc : '\0';
1477 replacement = make_quoted_replacement (match, mtype, qc);
1479 /* Now insert the match. */
1480 if (replacement)
1482 /* Don't double an opening quote character. */
1483 if (qc && *qc && start && rl_line_buffer[start - 1] == *qc &&
1484 replacement[0] == *qc)
1485 start--;
1486 /* If make_quoted_replacement changed the quoting character, remove
1487 the opening quote and insert the (fully-quoted) replacement. */
1488 else if (qc && (*qc != oqc) && start && rl_line_buffer[start - 1] == oqc &&
1489 replacement[0] != oqc)
1490 start--;
1491 _rl_replace_text (replacement, start, rl_point - 1);
1492 if (replacement != match)
1493 free (replacement);
1497 /* Append any necessary closing quote and a separator character to the
1498 just-inserted match. If the user has specified that directories
1499 should be marked by a trailing `/', append one of those instead. The
1500 default trailing character is a space. Returns the number of characters
1501 appended. If NONTRIVIAL_MATCH is set, we test for a symlink (if the OS
1502 has them) and don't add a suffix for a symlink to a directory. A
1503 nontrivial match is one that actually adds to the word being completed.
1504 The variable rl_completion_mark_symlink_dirs controls this behavior
1505 (it's initially set to the what the user has chosen, indicated by the
1506 value of _rl_complete_mark_symlink_dirs, but may be modified by an
1507 application's completion function). */
1508 static int
1509 append_to_match (text, delimiter, quote_char, nontrivial_match)
1510 char *text;
1511 int delimiter, quote_char, nontrivial_match;
1513 char temp_string[4], *filename;
1514 int temp_string_index, s;
1515 struct stat finfo;
1517 temp_string_index = 0;
1518 if (quote_char && rl_point && rl_completion_suppress_quote == 0 &&
1519 rl_line_buffer[rl_point - 1] != quote_char)
1520 temp_string[temp_string_index++] = quote_char;
1522 if (delimiter)
1523 temp_string[temp_string_index++] = delimiter;
1524 else if (rl_completion_suppress_append == 0 && rl_completion_append_character)
1525 temp_string[temp_string_index++] = rl_completion_append_character;
1527 temp_string[temp_string_index++] = '\0';
1529 if (rl_filename_completion_desired)
1531 filename = tilde_expand (text);
1532 s = (nontrivial_match && rl_completion_mark_symlink_dirs == 0)
1533 ? LSTAT (filename, &finfo)
1534 : stat (filename, &finfo);
1535 if (s == 0 && S_ISDIR (finfo.st_mode))
1537 if (_rl_complete_mark_directories)
1539 /* This is clumsy. Avoid putting in a double slash if point
1540 is at the end of the line and the previous character is a
1541 slash. */
1542 if (rl_point && rl_line_buffer[rl_point] == '\0' && rl_line_buffer[rl_point - 1] == '/')
1544 else if (rl_line_buffer[rl_point] != '/')
1545 rl_insert_text ("/");
1548 #ifdef S_ISLNK
1549 /* Don't add anything if the filename is a symlink and resolves to a
1550 directory. */
1551 else if (s == 0 && S_ISLNK (finfo.st_mode) &&
1552 stat (filename, &finfo) == 0 && S_ISDIR (finfo.st_mode))
1554 #endif
1555 else
1557 if (rl_point == rl_end && temp_string_index)
1558 rl_insert_text (temp_string);
1560 free (filename);
1562 else
1564 if (rl_point == rl_end && temp_string_index)
1565 rl_insert_text (temp_string);
1568 return (temp_string_index);
1571 static void
1572 insert_all_matches (matches, point, qc)
1573 char **matches;
1574 int point;
1575 char *qc;
1577 int i;
1578 char *rp;
1580 rl_begin_undo_group ();
1581 /* remove any opening quote character; make_quoted_replacement will add
1582 it back. */
1583 if (qc && *qc && point && rl_line_buffer[point - 1] == *qc)
1584 point--;
1585 rl_delete_text (point, rl_point);
1586 rl_point = point;
1588 if (matches[1])
1590 for (i = 1; matches[i]; i++)
1592 rp = make_quoted_replacement (matches[i], SINGLE_MATCH, qc);
1593 rl_insert_text (rp);
1594 rl_insert_text (" ");
1595 if (rp != matches[i])
1596 free (rp);
1599 else
1601 rp = make_quoted_replacement (matches[0], SINGLE_MATCH, qc);
1602 rl_insert_text (rp);
1603 rl_insert_text (" ");
1604 if (rp != matches[0])
1605 free (rp);
1607 rl_end_undo_group ();
1610 void
1611 _rl_free_match_list (matches)
1612 char **matches;
1614 register int i;
1616 if (matches == 0)
1617 return;
1619 for (i = 0; matches[i]; i++)
1620 free (matches[i]);
1621 free (matches);
1624 /* Complete the word at or before point.
1625 WHAT_TO_DO says what to do with the completion.
1626 `?' means list the possible completions.
1627 TAB means do standard completion.
1628 `*' means insert all of the possible completions.
1629 `!' means to do standard completion, and list all possible completions if
1630 there is more than one.
1631 `@' means to do standard completion, and list all possible completions if
1632 there is more than one and partial completion is not possible. */
1634 rl_complete_internal (what_to_do)
1635 int what_to_do;
1637 char **matches;
1638 rl_compentry_func_t *our_func;
1639 int start, end, delimiter, found_quote, i, nontrivial_lcd;
1640 char *text, *saved_line_buffer;
1641 char quote_char;
1643 RL_SETSTATE(RL_STATE_COMPLETING);
1645 set_completion_defaults (what_to_do);
1647 saved_line_buffer = rl_line_buffer ? savestring (rl_line_buffer) : (char *)NULL;
1648 our_func = rl_completion_entry_function
1649 ? rl_completion_entry_function
1650 : rl_filename_completion_function;
1651 /* We now look backwards for the start of a filename/variable word. */
1652 end = rl_point;
1653 found_quote = delimiter = 0;
1654 quote_char = '\0';
1656 if (rl_point)
1657 /* This (possibly) changes rl_point. If it returns a non-zero char,
1658 we know we have an open quote. */
1659 quote_char = _rl_find_completion_word (&found_quote, &delimiter);
1661 start = rl_point;
1662 rl_point = end;
1664 text = rl_copy_text (start, end);
1665 matches = gen_completion_matches (text, start, end, our_func, found_quote, quote_char);
1666 /* nontrivial_lcd is set if the common prefix adds something to the word
1667 being completed. */
1668 nontrivial_lcd = matches && strcmp (text, matches[0]) != 0;
1669 free (text);
1671 if (matches == 0)
1673 rl_ding ();
1674 FREE (saved_line_buffer);
1675 completion_changed_buffer = 0;
1676 RL_UNSETSTATE(RL_STATE_COMPLETING);
1677 return (0);
1680 /* If we are matching filenames, the attempted completion function will
1681 have set rl_filename_completion_desired to a non-zero value. The basic
1682 rl_filename_completion_function does this. */
1683 i = rl_filename_completion_desired;
1685 if (postprocess_matches (&matches, i) == 0)
1687 rl_ding ();
1688 FREE (saved_line_buffer);
1689 completion_changed_buffer = 0;
1690 RL_UNSETSTATE(RL_STATE_COMPLETING);
1691 return (0);
1694 switch (what_to_do)
1696 case TAB:
1697 case '!':
1698 case '@':
1699 /* Insert the first match with proper quoting. */
1700 if (*matches[0])
1701 insert_match (matches[0], start, matches[1] ? MULT_MATCH : SINGLE_MATCH, &quote_char);
1703 /* If there are more matches, ring the bell to indicate.
1704 If we are in vi mode, Posix.2 says to not ring the bell.
1705 If the `show-all-if-ambiguous' variable is set, display
1706 all the matches immediately. Otherwise, if this was the
1707 only match, and we are hacking files, check the file to
1708 see if it was a directory. If so, and the `mark-directories'
1709 variable is set, add a '/' to the name. If not, and we
1710 are at the end of the line, then add a space. */
1711 if (matches[1])
1713 if (what_to_do == '!')
1715 display_matches (matches);
1716 break;
1718 else if (what_to_do == '@')
1720 if (nontrivial_lcd == 0)
1721 display_matches (matches);
1722 break;
1724 else if (rl_editing_mode != vi_mode)
1725 rl_ding (); /* There are other matches remaining. */
1727 else
1728 append_to_match (matches[0], delimiter, quote_char, nontrivial_lcd);
1730 break;
1732 case '*':
1733 insert_all_matches (matches, start, &quote_char);
1734 break;
1736 case '?':
1737 display_matches (matches);
1738 break;
1740 default:
1741 fprintf (stderr, "\r\nreadline: bad value %d for what_to_do in rl_complete\n", what_to_do);
1742 rl_ding ();
1743 FREE (saved_line_buffer);
1744 RL_UNSETSTATE(RL_STATE_COMPLETING);
1745 return 1;
1748 _rl_free_match_list (matches);
1750 /* Check to see if the line has changed through all of this manipulation. */
1751 if (saved_line_buffer)
1753 completion_changed_buffer = strcmp (rl_line_buffer, saved_line_buffer) != 0;
1754 free (saved_line_buffer);
1757 RL_UNSETSTATE(RL_STATE_COMPLETING);
1758 return 0;
1761 /***************************************************************/
1762 /* */
1763 /* Application-callable completion match generator functions */
1764 /* */
1765 /***************************************************************/
1767 /* Return an array of (char *) which is a list of completions for TEXT.
1768 If there are no completions, return a NULL pointer.
1769 The first entry in the returned array is the substitution for TEXT.
1770 The remaining entries are the possible completions.
1771 The array is terminated with a NULL pointer.
1773 ENTRY_FUNCTION is a function of two args, and returns a (char *).
1774 The first argument is TEXT.
1775 The second is a state argument; it should be zero on the first call, and
1776 non-zero on subsequent calls. It returns a NULL pointer to the caller
1777 when there are no more matches.
1779 char **
1780 rl_completion_matches (text, entry_function)
1781 const char *text;
1782 rl_compentry_func_t *entry_function;
1784 /* Number of slots in match_list. */
1785 int match_list_size;
1787 /* The list of matches. */
1788 char **match_list;
1790 /* Number of matches actually found. */
1791 int matches;
1793 /* Temporary string binder. */
1794 char *string;
1796 matches = 0;
1797 match_list_size = 10;
1798 match_list = (char **)xmalloc ((match_list_size + 1) * sizeof (char *));
1799 match_list[1] = (char *)NULL;
1801 while (string = (*entry_function) (text, matches))
1803 if (matches + 1 == match_list_size)
1804 match_list = (char **)xrealloc
1805 (match_list, ((match_list_size += 10) + 1) * sizeof (char *));
1807 match_list[++matches] = string;
1808 match_list[matches + 1] = (char *)NULL;
1811 /* If there were any matches, then look through them finding out the
1812 lowest common denominator. That then becomes match_list[0]. */
1813 if (matches)
1814 compute_lcd_of_matches (match_list, matches, text);
1815 else /* There were no matches. */
1817 free (match_list);
1818 match_list = (char **)NULL;
1820 return (match_list);
1823 /* A completion function for usernames.
1824 TEXT contains a partial username preceded by a random
1825 character (usually `~'). */
1826 char *
1827 rl_username_completion_function (text, state)
1828 const char *text;
1829 int state;
1831 #if defined (__WIN32__) || defined (__OPENNT)
1832 return (char *)NULL;
1833 #else /* !__WIN32__ && !__OPENNT) */
1834 static char *username = (char *)NULL;
1835 static struct passwd *entry;
1836 static int namelen, first_char, first_char_loc;
1837 char *value;
1839 if (state == 0)
1841 FREE (username);
1843 first_char = *text;
1844 first_char_loc = first_char == '~';
1846 username = savestring (&text[first_char_loc]);
1847 namelen = strlen (username);
1848 setpwent ();
1851 while (entry = getpwent ())
1853 /* Null usernames should result in all users as possible completions. */
1854 if (namelen == 0 || (STREQN (username, entry->pw_name, namelen)))
1855 break;
1858 if (entry == 0)
1860 endpwent ();
1861 return ((char *)NULL);
1863 else
1865 value = (char *)xmalloc (2 + strlen (entry->pw_name));
1867 *value = *text;
1869 strcpy (value + first_char_loc, entry->pw_name);
1871 if (first_char == '~')
1872 rl_filename_completion_desired = 1;
1874 return (value);
1876 #endif /* !__WIN32__ && !__OPENNT */
1879 /* Okay, now we write the entry_function for filename completion. In the
1880 general case. Note that completion in the shell is a little different
1881 because of all the pathnames that must be followed when looking up the
1882 completion for a command. */
1883 char *
1884 rl_filename_completion_function (text, state)
1885 const char *text;
1886 int state;
1888 static DIR *directory = (DIR *)NULL;
1889 static char *filename = (char *)NULL;
1890 static char *dirname = (char *)NULL;
1891 static char *users_dirname = (char *)NULL;
1892 static int filename_len;
1893 char *temp;
1894 int dirlen;
1895 struct dirent *entry;
1897 /* If we don't have any state, then do some initialization. */
1898 if (state == 0)
1900 /* If we were interrupted before closing the directory or reading
1901 all of its contents, close it. */
1902 if (directory)
1904 closedir (directory);
1905 directory = (DIR *)NULL;
1907 FREE (dirname);
1908 FREE (filename);
1909 FREE (users_dirname);
1911 filename = savestring (text);
1912 if (*text == 0)
1913 text = ".";
1914 dirname = savestring (text);
1916 temp = strrchr (dirname, '/');
1918 #if defined (__MSDOS__)
1919 /* special hack for //X/... */
1920 if (dirname[0] == '/' && dirname[1] == '/' && ISALPHA ((unsigned char)dirname[2]) && dirname[3] == '/')
1921 temp = strrchr (dirname + 3, '/');
1922 #endif
1924 if (temp)
1926 strcpy (filename, ++temp);
1927 *temp = '\0';
1929 #if defined (__MSDOS__)
1930 /* searches from current directory on the drive */
1931 else if (ISALPHA ((unsigned char)dirname[0]) && dirname[1] == ':')
1933 strcpy (filename, dirname + 2);
1934 dirname[2] = '\0';
1936 #endif
1937 else
1939 dirname[0] = '.';
1940 dirname[1] = '\0';
1943 /* We aren't done yet. We also support the "~user" syntax. */
1945 /* Save the version of the directory that the user typed. */
1946 users_dirname = savestring (dirname);
1948 if (*dirname == '~')
1950 temp = tilde_expand (dirname);
1951 free (dirname);
1952 dirname = temp;
1955 if (rl_directory_rewrite_hook)
1956 (*rl_directory_rewrite_hook) (&dirname);
1958 if (rl_directory_completion_hook && (*rl_directory_completion_hook) (&dirname))
1960 free (users_dirname);
1961 users_dirname = savestring (dirname);
1964 directory = opendir (dirname);
1965 filename_len = strlen (filename);
1967 rl_filename_completion_desired = 1;
1970 /* At this point we should entertain the possibility of hacking wildcarded
1971 filenames, like /usr/man/man<WILD>/te<TAB>. If the directory name
1972 contains globbing characters, then build an array of directories, and
1973 then map over that list while completing. */
1974 /* *** UNIMPLEMENTED *** */
1976 /* Now that we have some state, we can read the directory. */
1978 entry = (struct dirent *)NULL;
1979 while (directory && (entry = readdir (directory)))
1981 /* Special case for no filename. If the user has disabled the
1982 `match-hidden-files' variable, skip filenames beginning with `.'.
1983 All other entries except "." and ".." match. */
1984 if (filename_len == 0)
1986 if (_rl_match_hidden_files == 0 && HIDDEN_FILE (entry->d_name))
1987 continue;
1989 if (entry->d_name[0] != '.' ||
1990 (entry->d_name[1] &&
1991 (entry->d_name[1] != '.' || entry->d_name[2])))
1992 break;
1994 else
1996 /* Otherwise, if these match up to the length of filename, then
1997 it is a match. */
1998 if (_rl_completion_case_fold)
2000 if ((_rl_to_lower (entry->d_name[0]) == _rl_to_lower (filename[0])) &&
2001 (((int)D_NAMLEN (entry)) >= filename_len) &&
2002 (_rl_strnicmp (filename, entry->d_name, filename_len) == 0))
2003 break;
2005 else
2007 if ((entry->d_name[0] == filename[0]) &&
2008 (((int)D_NAMLEN (entry)) >= filename_len) &&
2009 (strncmp (filename, entry->d_name, filename_len) == 0))
2010 break;
2015 if (entry == 0)
2017 if (directory)
2019 closedir (directory);
2020 directory = (DIR *)NULL;
2022 if (dirname)
2024 free (dirname);
2025 dirname = (char *)NULL;
2027 if (filename)
2029 free (filename);
2030 filename = (char *)NULL;
2032 if (users_dirname)
2034 free (users_dirname);
2035 users_dirname = (char *)NULL;
2038 return (char *)NULL;
2040 else
2042 /* dirname && (strcmp (dirname, ".") != 0) */
2043 if (dirname && (dirname[0] != '.' || dirname[1]))
2045 if (rl_complete_with_tilde_expansion && *users_dirname == '~')
2047 dirlen = strlen (dirname);
2048 temp = (char *)xmalloc (2 + dirlen + D_NAMLEN (entry));
2049 strcpy (temp, dirname);
2050 /* Canonicalization cuts off any final slash present. We
2051 may need to add it back. */
2052 if (dirname[dirlen - 1] != '/')
2054 temp[dirlen++] = '/';
2055 temp[dirlen] = '\0';
2058 else
2060 dirlen = strlen (users_dirname);
2061 temp = (char *)xmalloc (2 + dirlen + D_NAMLEN (entry));
2062 strcpy (temp, users_dirname);
2063 /* Make sure that temp has a trailing slash here. */
2064 if (users_dirname[dirlen - 1] != '/')
2065 temp[dirlen++] = '/';
2068 strcpy (temp + dirlen, entry->d_name);
2070 else
2071 temp = savestring (entry->d_name);
2073 return (temp);
2077 /* An initial implementation of a menu completion function a la tcsh. The
2078 first time (if the last readline command was not rl_menu_complete), we
2079 generate the list of matches. This code is very similar to the code in
2080 rl_complete_internal -- there should be a way to combine the two. Then,
2081 for each item in the list of matches, we insert the match in an undoable
2082 fashion, with the appropriate character appended (this happens on the
2083 second and subsequent consecutive calls to rl_menu_complete). When we
2084 hit the end of the match list, we restore the original unmatched text,
2085 ring the bell, and reset the counter to zero. */
2087 rl_menu_complete (count, ignore)
2088 int count, ignore;
2090 rl_compentry_func_t *our_func;
2091 int matching_filenames, found_quote;
2093 static char *orig_text;
2094 static char **matches = (char **)0;
2095 static int match_list_index = 0;
2096 static int match_list_size = 0;
2097 static int orig_start, orig_end;
2098 static char quote_char;
2099 static int delimiter;
2101 /* The first time through, we generate the list of matches and set things
2102 up to insert them. */
2103 if (rl_last_func != rl_menu_complete)
2105 /* Clean up from previous call, if any. */
2106 FREE (orig_text);
2107 if (matches)
2108 _rl_free_match_list (matches);
2110 match_list_index = match_list_size = 0;
2111 matches = (char **)NULL;
2113 /* Only the completion entry function can change these. */
2114 set_completion_defaults ('%');
2116 our_func = rl_completion_entry_function
2117 ? rl_completion_entry_function
2118 : rl_filename_completion_function;
2120 /* We now look backwards for the start of a filename/variable word. */
2121 orig_end = rl_point;
2122 found_quote = delimiter = 0;
2123 quote_char = '\0';
2125 if (rl_point)
2126 /* This (possibly) changes rl_point. If it returns a non-zero char,
2127 we know we have an open quote. */
2128 quote_char = _rl_find_completion_word (&found_quote, &delimiter);
2130 orig_start = rl_point;
2131 rl_point = orig_end;
2133 orig_text = rl_copy_text (orig_start, orig_end);
2134 matches = gen_completion_matches (orig_text, orig_start, orig_end,
2135 our_func, found_quote, quote_char);
2137 /* If we are matching filenames, the attempted completion function will
2138 have set rl_filename_completion_desired to a non-zero value. The basic
2139 rl_filename_completion_function does this. */
2140 matching_filenames = rl_filename_completion_desired;
2142 if (matches == 0 || postprocess_matches (&matches, matching_filenames) == 0)
2144 rl_ding ();
2145 FREE (matches);
2146 matches = (char **)0;
2147 FREE (orig_text);
2148 orig_text = (char *)0;
2149 completion_changed_buffer = 0;
2150 return (0);
2153 for (match_list_size = 0; matches[match_list_size]; match_list_size++)
2155 /* matches[0] is lcd if match_list_size > 1, but the circular buffer
2156 code below should take care of it. */
2159 /* Now we have the list of matches. Replace the text between
2160 rl_line_buffer[orig_start] and rl_line_buffer[rl_point] with
2161 matches[match_list_index], and add any necessary closing char. */
2163 if (matches == 0 || match_list_size == 0)
2165 rl_ding ();
2166 FREE (matches);
2167 matches = (char **)0;
2168 completion_changed_buffer = 0;
2169 return (0);
2172 match_list_index = (match_list_index + count) % match_list_size;
2173 if (match_list_index < 0)
2174 match_list_index += match_list_size;
2176 if (match_list_index == 0 && match_list_size > 1)
2178 rl_ding ();
2179 insert_match (orig_text, orig_start, MULT_MATCH, &quote_char);
2181 else
2183 insert_match (matches[match_list_index], orig_start, SINGLE_MATCH, &quote_char);
2184 append_to_match (matches[match_list_index], delimiter, quote_char,
2185 strcmp (orig_text, matches[match_list_index]));
2188 completion_changed_buffer = 1;
2189 return (0);