]> git.ipfire.org Git - thirdparty/bash.git/blob - lib/readline/complete.c
commit bash-20120614 snapshot
[thirdparty/bash.git] / lib / readline / complete.c
1 /* complete.c -- filename completion for readline. */
2
3 /* Copyright (C) 1987-2012 Free Software Foundation, Inc.
4
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.
7
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.
12
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.
17
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/>.
20 */
21
22 #define READLINE_LIBRARY
23
24 #if defined (HAVE_CONFIG_H)
25 # include <config.h>
26 #endif
27
28 #include <sys/types.h>
29 #include <fcntl.h>
30 #if defined (HAVE_SYS_FILE_H)
31 # include <sys/file.h>
32 #endif
33
34 #include <signal.h>
35
36 #if defined (HAVE_UNISTD_H)
37 # include <unistd.h>
38 #endif /* HAVE_UNISTD_H */
39
40 #if defined (HAVE_STDLIB_H)
41 # include <stdlib.h>
42 #else
43 # include "ansi_stdlib.h"
44 #endif /* HAVE_STDLIB_H */
45
46 #include <stdio.h>
47
48 #include <errno.h>
49 #if !defined (errno)
50 extern int errno;
51 #endif /* !errno */
52
53 #if defined (HAVE_PWD_H)
54 #include <pwd.h>
55 #endif
56
57 #include "posixdir.h"
58 #include "posixstat.h"
59
60 /* System-specific feature definitions and include files. */
61 #include "rldefs.h"
62 #include "rlmbutil.h"
63
64 /* Some standard library routines. */
65 #include "readline.h"
66 #include "xmalloc.h"
67 #include "rlprivate.h"
68
69 #if defined (COLOR_SUPPORT)
70 # include "colors.h"
71 #endif
72
73 #ifdef __STDC__
74 typedef int QSFUNC (const void *, const void *);
75 #else
76 typedef int QSFUNC ();
77 #endif
78
79 #ifdef HAVE_LSTAT
80 # define LSTAT lstat
81 #else
82 # define LSTAT stat
83 #endif
84
85 /* Unix version of a hidden file. Could be different on other systems. */
86 #define HIDDEN_FILE(fname) ((fname)[0] == '.')
87
88 /* Most systems don't declare getpwent in <pwd.h> if _POSIX_SOURCE is
89 defined. */
90 #if defined (HAVE_GETPWENT) && (!defined (HAVE_GETPW_DECLS) || defined (_POSIX_SOURCE))
91 extern struct passwd *getpwent PARAMS((void));
92 #endif /* HAVE_GETPWENT && (!HAVE_GETPW_DECLS || _POSIX_SOURCE) */
93
94 /* If non-zero, then this is the address of a function to call when
95 completing a word would normally display the list of possible matches.
96 This function is called instead of actually doing the display.
97 It takes three arguments: (char **matches, int num_matches, int max_length)
98 where MATCHES is the array of strings that matched, NUM_MATCHES is the
99 number of strings in that array, and MAX_LENGTH is the length of the
100 longest string in that array. */
101 rl_compdisp_func_t *rl_completion_display_matches_hook = (rl_compdisp_func_t *)NULL;
102
103 #if defined (VISIBLE_STATS) || defined (COLOR_SUPPORT)
104 # if !defined (X_OK)
105 # define X_OK 1
106 # endif
107 #endif
108
109 #if defined (VISIBLE_STATS)
110 static int stat_char PARAMS((char *));
111 #endif
112
113 #if defined (COLOR_SUPPORT)
114 static int colored_stat_start PARAMS((char *));
115 static void colored_stat_end PARAMS((void));
116 #endif
117
118 static int path_isdir PARAMS((const char *));
119
120 static char *rl_quote_filename PARAMS((char *, int, char *));
121
122 static void _rl_complete_sigcleanup PARAMS((int, void *));
123
124 static void set_completion_defaults PARAMS((int));
125 static int get_y_or_n PARAMS((int));
126 static int _rl_internal_pager PARAMS((int));
127 static char *printable_part PARAMS((char *));
128 static int fnwidth PARAMS((const char *));
129 static int fnprint PARAMS((const char *, int));
130 static int print_filename PARAMS((char *, char *, int));
131
132 static char **gen_completion_matches PARAMS((char *, int, int, rl_compentry_func_t *, int, int));
133
134 static char **remove_duplicate_matches PARAMS((char **));
135 static void insert_match PARAMS((char *, int, int, char *));
136 static int append_to_match PARAMS((char *, int, int, int));
137 static void insert_all_matches PARAMS((char **, int, char *));
138 static int complete_fncmp PARAMS((const char *, int, const char *, int));
139 static void display_matches PARAMS((char **));
140 static int compute_lcd_of_matches PARAMS((char **, int, const char *));
141 static int postprocess_matches PARAMS((char ***, int));
142 static int complete_get_screenwidth PARAMS((void));
143
144 static char *make_quoted_replacement PARAMS((char *, int, char *));
145
146 /* **************************************************************** */
147 /* */
148 /* Completion matching, from readline's point of view. */
149 /* */
150 /* **************************************************************** */
151
152 /* Variables known only to the readline library. */
153
154 /* If non-zero, non-unique completions always show the list of matches. */
155 int _rl_complete_show_all = 0;
156
157 /* If non-zero, non-unique completions show the list of matches, unless it
158 is not possible to do partial completion and modify the line. */
159 int _rl_complete_show_unmodified = 0;
160
161 /* If non-zero, completed directory names have a slash appended. */
162 int _rl_complete_mark_directories = 1;
163
164 /* If non-zero, the symlinked directory completion behavior introduced in
165 readline-4.2a is disabled, and symlinks that point to directories have
166 a slash appended (subject to the value of _rl_complete_mark_directories).
167 This is user-settable via the mark-symlinked-directories variable. */
168 int _rl_complete_mark_symlink_dirs = 0;
169
170 /* If non-zero, completions are printed horizontally in alphabetical order,
171 like `ls -x'. */
172 int _rl_print_completions_horizontally;
173
174 /* Non-zero means that case is not significant in filename completion. */
175 #if defined (__MSDOS__) && !defined (__DJGPP__)
176 int _rl_completion_case_fold = 1;
177 #else
178 int _rl_completion_case_fold = 0;
179 #endif
180
181 /* Non-zero means that `-' and `_' are equivalent when comparing filenames
182 for completion. */
183 int _rl_completion_case_map = 0;
184
185 /* If zero, don't match hidden files (filenames beginning with a `.' on
186 Unix) when doing filename completion. */
187 int _rl_match_hidden_files = 1;
188
189 /* Length in characters of a common prefix replaced with an ellipsis (`...')
190 when displaying completion matches. Matches whose printable portion has
191 more than this number of displaying characters in common will have the common
192 display prefix replaced with an ellipsis. */
193 int _rl_completion_prefix_display_length = 0;
194
195 /* The readline-private number of screen columns to use when displaying
196 matches. If < 0 or > _rl_screenwidth, it is ignored. */
197 int _rl_completion_columns = -1;
198
199 /* Global variables available to applications using readline. */
200
201 #if defined (VISIBLE_STATS)
202 /* Non-zero means add an additional character to each filename displayed
203 during listing completion iff rl_filename_completion_desired which helps
204 to indicate the type of file being listed. */
205 int rl_visible_stats = 0;
206 #endif /* VISIBLE_STATS */
207
208 #if defined (COLOR_SUPPORT)
209 /* Non-zero means to use colors to indicate file type when listing possible
210 completions. The colors used are taken from $LS_COLORS, if set. */
211 int _rl_colored_stats = 1;
212 #endif
213
214 /* If non-zero, when completing in the middle of a word, don't insert
215 characters from the match that match characters following point in
216 the word. This means, for instance, completing when the cursor is
217 after the `e' in `Makefile' won't result in `Makefilefile'. */
218 int _rl_skip_completed_text = 0;
219
220 /* If non-zero, menu completion displays the common prefix first in the
221 cycle of possible completions instead of the last. */
222 int _rl_menu_complete_prefix_first = 0;
223
224 /* If non-zero, then this is the address of a function to call when
225 completing on a directory name. The function is called with
226 the address of a string (the current directory name) as an arg. */
227 rl_icppfunc_t *rl_directory_completion_hook = (rl_icppfunc_t *)NULL;
228
229 rl_icppfunc_t *rl_directory_rewrite_hook = (rl_icppfunc_t *)NULL;
230
231 rl_icppfunc_t *rl_filename_stat_hook = (rl_icppfunc_t *)NULL;
232
233 /* If non-zero, this is the address of a function to call when reading
234 directory entries from the filesystem for completion and comparing
235 them to the partial word to be completed. The function should
236 either return its first argument (if no conversion takes place) or
237 newly-allocated memory. This can, for instance, convert filenames
238 between character sets for comparison against what's typed at the
239 keyboard. The returned value is what is added to the list of
240 matches. The second argument is the length of the filename to be
241 converted. */
242 rl_dequote_func_t *rl_filename_rewrite_hook = (rl_dequote_func_t *)NULL;
243
244 /* Non-zero means readline completion functions perform tilde expansion. */
245 int rl_complete_with_tilde_expansion = 0;
246
247 /* Pointer to the generator function for completion_matches ().
248 NULL means to use rl_filename_completion_function (), the default filename
249 completer. */
250 rl_compentry_func_t *rl_completion_entry_function = (rl_compentry_func_t *)NULL;
251
252 /* Pointer to generator function for rl_menu_complete (). NULL means to use
253 *rl_completion_entry_function (see above). */
254 rl_compentry_func_t *rl_menu_completion_entry_function = (rl_compentry_func_t *)NULL;
255
256 /* Pointer to alternative function to create matches.
257 Function is called with TEXT, START, and END.
258 START and END are indices in RL_LINE_BUFFER saying what the boundaries
259 of TEXT are.
260 If this function exists and returns NULL then call the value of
261 rl_completion_entry_function to try to match, otherwise use the
262 array of strings returned. */
263 rl_completion_func_t *rl_attempted_completion_function = (rl_completion_func_t *)NULL;
264
265 /* Non-zero means to suppress normal filename completion after the
266 user-specified completion function has been called. */
267 int rl_attempted_completion_over = 0;
268
269 /* Set to a character indicating the type of completion being performed
270 by rl_complete_internal, available for use by application completion
271 functions. */
272 int rl_completion_type = 0;
273
274 /* Up to this many items will be displayed in response to a
275 possible-completions call. After that, we ask the user if
276 she is sure she wants to see them all. A negative value means
277 don't ask. */
278 int rl_completion_query_items = 100;
279
280 int _rl_page_completions = 1;
281
282 /* The basic list of characters that signal a break between words for the
283 completer routine. The contents of this variable is what breaks words
284 in the shell, i.e. " \t\n\"\\'`@$><=" */
285 const char *rl_basic_word_break_characters = " \t\n\"\\'`@$><=;|&{("; /* }) */
286
287 /* List of basic quoting characters. */
288 const char *rl_basic_quote_characters = "\"'";
289
290 /* The list of characters that signal a break between words for
291 rl_complete_internal. The default list is the contents of
292 rl_basic_word_break_characters. */
293 /*const*/ char *rl_completer_word_break_characters = (/*const*/ char *)NULL;
294
295 /* Hook function to allow an application to set the completion word
296 break characters before readline breaks up the line. Allows
297 position-dependent word break characters. */
298 rl_cpvfunc_t *rl_completion_word_break_hook = (rl_cpvfunc_t *)NULL;
299
300 /* List of characters which can be used to quote a substring of the line.
301 Completion occurs on the entire substring, and within the substring
302 rl_completer_word_break_characters are treated as any other character,
303 unless they also appear within this list. */
304 const char *rl_completer_quote_characters = (const char *)NULL;
305
306 /* List of characters that should be quoted in filenames by the completer. */
307 const char *rl_filename_quote_characters = (const char *)NULL;
308
309 /* List of characters that are word break characters, but should be left
310 in TEXT when it is passed to the completion function. The shell uses
311 this to help determine what kind of completing to do. */
312 const char *rl_special_prefixes = (const char *)NULL;
313
314 /* If non-zero, then disallow duplicates in the matches. */
315 int rl_ignore_completion_duplicates = 1;
316
317 /* Non-zero means that the results of the matches are to be treated
318 as filenames. This is ALWAYS zero on entry, and can only be changed
319 within a completion entry finder function. */
320 int rl_filename_completion_desired = 0;
321
322 /* Non-zero means that the results of the matches are to be quoted using
323 double quotes (or an application-specific quoting mechanism) if the
324 filename contains any characters in rl_filename_quote_chars. This is
325 ALWAYS non-zero on entry, and can only be changed within a completion
326 entry finder function. */
327 int rl_filename_quoting_desired = 1;
328
329 /* This function, if defined, is called by the completer when real
330 filename completion is done, after all the matching names have been
331 generated. It is passed a (char**) known as matches in the code below.
332 It consists of a NULL-terminated array of pointers to potential
333 matching strings. The 1st element (matches[0]) is the maximal
334 substring that is common to all matches. This function can re-arrange
335 the list of matches as required, but all elements of the array must be
336 free()'d if they are deleted. The main intent of this function is
337 to implement FIGNORE a la SunOS csh. */
338 rl_compignore_func_t *rl_ignore_some_completions_function = (rl_compignore_func_t *)NULL;
339
340 /* Set to a function to quote a filename in an application-specific fashion.
341 Called with the text to quote, the type of match found (single or multiple)
342 and a pointer to the quoting character to be used, which the function can
343 reset if desired. */
344 rl_quote_func_t *rl_filename_quoting_function = rl_quote_filename;
345
346 /* Function to call to remove quoting characters from a filename. Called
347 before completion is attempted, so the embedded quotes do not interfere
348 with matching names in the file system. Readline doesn't do anything
349 with this; it's set only by applications. */
350 rl_dequote_func_t *rl_filename_dequoting_function = (rl_dequote_func_t *)NULL;
351
352 /* Function to call to decide whether or not a word break character is
353 quoted. If a character is quoted, it does not break words for the
354 completer. */
355 rl_linebuf_func_t *rl_char_is_quoted_p = (rl_linebuf_func_t *)NULL;
356
357 /* If non-zero, the completion functions don't append anything except a
358 possible closing quote. This is set to 0 by rl_complete_internal and
359 may be changed by an application-specific completion function. */
360 int rl_completion_suppress_append = 0;
361
362 /* Character appended to completed words when at the end of the line. The
363 default is a space. */
364 int rl_completion_append_character = ' ';
365
366 /* If non-zero, the completion functions don't append any closing quote.
367 This is set to 0 by rl_complete_internal and may be changed by an
368 application-specific completion function. */
369 int rl_completion_suppress_quote = 0;
370
371 /* Set to any quote character readline thinks it finds before any application
372 completion function is called. */
373 int rl_completion_quote_character;
374
375 /* Set to a non-zero value if readline found quoting anywhere in the word to
376 be completed; set before any application completion function is called. */
377 int rl_completion_found_quote;
378
379 /* If non-zero, a slash will be appended to completed filenames that are
380 symbolic links to directory names, subject to the value of the
381 mark-directories variable (which is user-settable). This exists so
382 that application completion functions can override the user's preference
383 (set via the mark-symlinked-directories variable) if appropriate.
384 It's set to the value of _rl_complete_mark_symlink_dirs in
385 rl_complete_internal before any application-specific completion
386 function is called, so without that function doing anything, the user's
387 preferences are honored. */
388 int rl_completion_mark_symlink_dirs;
389
390 /* If non-zero, inhibit completion (temporarily). */
391 int rl_inhibit_completion;
392
393 /* Set to the last key used to invoke one of the completion functions */
394 int rl_completion_invoking_key;
395
396 /* If non-zero, sort the completion matches. On by default. */
397 int rl_sort_completion_matches = 1;
398
399 /* Variables local to this file. */
400
401 /* Local variable states what happened during the last completion attempt. */
402 static int completion_changed_buffer;
403
404 /* The result of the query to the user about displaying completion matches */
405 static int completion_y_or_n;
406
407 /*************************************/
408 /* */
409 /* Bindable completion functions */
410 /* */
411 /*************************************/
412
413 /* Complete the word at or before point. You have supplied the function
414 that does the initial simple matching selection algorithm (see
415 rl_completion_matches ()). The default is to do filename completion. */
416 int
417 rl_complete (ignore, invoking_key)
418 int ignore, invoking_key;
419 {
420 rl_completion_invoking_key = invoking_key;
421
422 if (rl_inhibit_completion)
423 return (_rl_insert_char (ignore, invoking_key));
424 else if (rl_last_func == rl_complete && !completion_changed_buffer)
425 return (rl_complete_internal ('?'));
426 else if (_rl_complete_show_all)
427 return (rl_complete_internal ('!'));
428 else if (_rl_complete_show_unmodified)
429 return (rl_complete_internal ('@'));
430 else
431 return (rl_complete_internal (TAB));
432 }
433
434 /* List the possible completions. See description of rl_complete (). */
435 int
436 rl_possible_completions (ignore, invoking_key)
437 int ignore, invoking_key;
438 {
439 rl_completion_invoking_key = invoking_key;
440 return (rl_complete_internal ('?'));
441 }
442
443 int
444 rl_insert_completions (ignore, invoking_key)
445 int ignore, invoking_key;
446 {
447 rl_completion_invoking_key = invoking_key;
448 return (rl_complete_internal ('*'));
449 }
450
451 /* Return the correct value to pass to rl_complete_internal performing
452 the same tests as rl_complete. This allows consecutive calls to an
453 application's completion function to list possible completions and for
454 an application-specific completion function to honor the
455 show-all-if-ambiguous readline variable. */
456 int
457 rl_completion_mode (cfunc)
458 rl_command_func_t *cfunc;
459 {
460 if (rl_last_func == cfunc && !completion_changed_buffer)
461 return '?';
462 else if (_rl_complete_show_all)
463 return '!';
464 else if (_rl_complete_show_unmodified)
465 return '@';
466 else
467 return TAB;
468 }
469
470 /************************************/
471 /* */
472 /* Completion utility functions */
473 /* */
474 /************************************/
475
476 /* Reset readline state on a signal or other event. */
477 void
478 _rl_reset_completion_state ()
479 {
480 rl_completion_found_quote = 0;
481 rl_completion_quote_character = 0;
482 }
483
484 static void
485 _rl_complete_sigcleanup (sig, ptr)
486 int sig;
487 void *ptr;
488 {
489 if (sig == SIGINT) /* XXX - for now */
490 _rl_free_match_list ((char **)ptr);
491 }
492
493 /* Set default values for readline word completion. These are the variables
494 that application completion functions can change or inspect. */
495 static void
496 set_completion_defaults (what_to_do)
497 int what_to_do;
498 {
499 /* Only the completion entry function can change these. */
500 rl_filename_completion_desired = 0;
501 rl_filename_quoting_desired = 1;
502 rl_completion_type = what_to_do;
503 rl_completion_suppress_append = rl_completion_suppress_quote = 0;
504 rl_completion_append_character = ' ';
505
506 /* The completion entry function may optionally change this. */
507 rl_completion_mark_symlink_dirs = _rl_complete_mark_symlink_dirs;
508 }
509
510 /* The user must press "y" or "n". Non-zero return means "y" pressed. */
511 static int
512 get_y_or_n (for_pager)
513 int for_pager;
514 {
515 int c;
516
517 /* For now, disable pager in callback mode, until we later convert to state
518 driven functions. Have to wait until next major version to add new
519 state definition, since it will change value of RL_STATE_DONE. */
520 #if defined (READLINE_CALLBACKS)
521 if (RL_ISSTATE (RL_STATE_CALLBACK))
522 return 1;
523 #endif
524
525 for (;;)
526 {
527 RL_SETSTATE(RL_STATE_MOREINPUT);
528 c = rl_read_key ();
529 RL_UNSETSTATE(RL_STATE_MOREINPUT);
530
531 if (c == 'y' || c == 'Y' || c == ' ')
532 return (1);
533 if (c == 'n' || c == 'N' || c == RUBOUT)
534 return (0);
535 if (c == ABORT_CHAR || c < 0)
536 _rl_abort_internal ();
537 if (for_pager && (c == NEWLINE || c == RETURN))
538 return (2);
539 if (for_pager && (c == 'q' || c == 'Q'))
540 return (0);
541 rl_ding ();
542 }
543 }
544
545 static int
546 _rl_internal_pager (lines)
547 int lines;
548 {
549 int i;
550
551 fprintf (rl_outstream, "--More--");
552 fflush (rl_outstream);
553 i = get_y_or_n (1);
554 _rl_erase_entire_line ();
555 if (i == 0)
556 return -1;
557 else if (i == 2)
558 return (lines - 1);
559 else
560 return 0;
561 }
562
563 static int
564 path_isdir (filename)
565 const char *filename;
566 {
567 struct stat finfo;
568
569 return (stat (filename, &finfo) == 0 && S_ISDIR (finfo.st_mode));
570 }
571
572 #if defined (VISIBLE_STATS)
573 /* Return the character which best describes FILENAME.
574 `@' for symbolic links
575 `/' for directories
576 `*' for executables
577 `=' for sockets
578 `|' for FIFOs
579 `%' for character special devices
580 `#' for block special devices */
581 static int
582 stat_char (filename)
583 char *filename;
584 {
585 struct stat finfo;
586 int character, r;
587 char *f;
588 const char *fn;
589
590 /* Short-circuit a //server on cygwin, since that will always behave as
591 a directory. */
592 #if __CYGWIN__
593 if (filename[0] == '/' && filename[1] == '/' && strchr (filename+2, '/') == 0)
594 return '/';
595 #endif
596
597 f = 0;
598 if (rl_filename_stat_hook)
599 {
600 f = savestring (filename);
601 (*rl_filename_stat_hook) (&f);
602 fn = f;
603 }
604 else
605 fn = filename;
606
607 #if defined (HAVE_LSTAT) && defined (S_ISLNK)
608 r = lstat (fn, &finfo);
609 #else
610 r = stat (fn, &finfo);
611 #endif
612
613 if (r == -1)
614 return (0);
615
616 character = 0;
617 if (S_ISDIR (finfo.st_mode))
618 character = '/';
619 #if defined (S_ISCHR)
620 else if (S_ISCHR (finfo.st_mode))
621 character = '%';
622 #endif /* S_ISCHR */
623 #if defined (S_ISBLK)
624 else if (S_ISBLK (finfo.st_mode))
625 character = '#';
626 #endif /* S_ISBLK */
627 #if defined (S_ISLNK)
628 else if (S_ISLNK (finfo.st_mode))
629 character = '@';
630 #endif /* S_ISLNK */
631 #if defined (S_ISSOCK)
632 else if (S_ISSOCK (finfo.st_mode))
633 character = '=';
634 #endif /* S_ISSOCK */
635 #if defined (S_ISFIFO)
636 else if (S_ISFIFO (finfo.st_mode))
637 character = '|';
638 #endif
639 else if (S_ISREG (finfo.st_mode))
640 {
641 if (access (filename, X_OK) == 0)
642 character = '*';
643 }
644
645 free (f);
646 return (character);
647 }
648 #endif /* VISIBLE_STATS */
649
650 #if defined (COLOR_SUPPORT)
651 static int
652 colored_stat_start (filename)
653 char *filename;
654 {
655 _rl_set_normal_color ();
656 return (_rl_print_color_indicator (filename));
657 }
658
659 static void
660 colored_stat_end ()
661 {
662 _rl_prep_non_filename_text ();
663 _rl_put_indicator (&_rl_color_indicator[C_CLR_TO_EOL]);
664 }
665 #endif
666
667 /* Return the portion of PATHNAME that should be output when listing
668 possible completions. If we are hacking filename completion, we
669 are only interested in the basename, the portion following the
670 final slash. Otherwise, we return what we were passed. Since
671 printing empty strings is not very informative, if we're doing
672 filename completion, and the basename is the empty string, we look
673 for the previous slash and return the portion following that. If
674 there's no previous slash, we just return what we were passed. */
675 static char *
676 printable_part (pathname)
677 char *pathname;
678 {
679 char *temp, *x;
680
681 if (rl_filename_completion_desired == 0) /* don't need to do anything */
682 return (pathname);
683
684 temp = strrchr (pathname, '/');
685 #if defined (__MSDOS__)
686 if (temp == 0 && ISALPHA ((unsigned char)pathname[0]) && pathname[1] == ':')
687 temp = pathname + 1;
688 #endif
689
690 if (temp == 0 || *temp == '\0')
691 return (pathname);
692 /* If the basename is NULL, we might have a pathname like '/usr/src/'.
693 Look for a previous slash and, if one is found, return the portion
694 following that slash. If there's no previous slash, just return the
695 pathname we were passed. */
696 else if (temp[1] == '\0')
697 {
698 for (x = temp - 1; x > pathname; x--)
699 if (*x == '/')
700 break;
701 return ((*x == '/') ? x + 1 : pathname);
702 }
703 else
704 return ++temp;
705 }
706
707 /* Compute width of STRING when displayed on screen by print_filename */
708 static int
709 fnwidth (string)
710 const char *string;
711 {
712 int width, pos;
713 #if defined (HANDLE_MULTIBYTE)
714 mbstate_t ps;
715 int left, w;
716 size_t clen;
717 wchar_t wc;
718
719 left = strlen (string) + 1;
720 memset (&ps, 0, sizeof (mbstate_t));
721 #endif
722
723 width = pos = 0;
724 while (string[pos])
725 {
726 if (CTRL_CHAR (string[pos]) || string[pos] == RUBOUT)
727 {
728 width += 2;
729 pos++;
730 }
731 else
732 {
733 #if defined (HANDLE_MULTIBYTE)
734 clen = mbrtowc (&wc, string + pos, left - pos, &ps);
735 if (MB_INVALIDCH (clen))
736 {
737 width++;
738 pos++;
739 memset (&ps, 0, sizeof (mbstate_t));
740 }
741 else if (MB_NULLWCH (clen))
742 break;
743 else
744 {
745 pos += clen;
746 w = WCWIDTH (wc);
747 width += (w >= 0) ? w : 1;
748 }
749 #else
750 width++;
751 pos++;
752 #endif
753 }
754 }
755
756 return width;
757 }
758
759 #define ELLIPSIS_LEN 3
760
761 static int
762 fnprint (to_print, prefix_bytes)
763 const char *to_print;
764 int prefix_bytes;
765 {
766 int printed_len, w;
767 const char *s;
768 #if defined (HANDLE_MULTIBYTE)
769 mbstate_t ps;
770 const char *end;
771 size_t tlen;
772 int width;
773 wchar_t wc;
774
775 end = to_print + strlen (to_print) + 1;
776 memset (&ps, 0, sizeof (mbstate_t));
777 #endif
778
779 printed_len = 0;
780
781 /* Don't print only the ellipsis if the common prefix is one of the
782 possible completions */
783 if (to_print[prefix_bytes] == '\0')
784 prefix_bytes = 0;
785
786 if (prefix_bytes)
787 {
788 char ellipsis;
789
790 ellipsis = (to_print[prefix_bytes] == '.') ? '_' : '.';
791 for (w = 0; w < ELLIPSIS_LEN; w++)
792 putc (ellipsis, rl_outstream);
793 printed_len = ELLIPSIS_LEN;
794 }
795
796 s = to_print + prefix_bytes;
797 while (*s)
798 {
799 if (CTRL_CHAR (*s))
800 {
801 putc ('^', rl_outstream);
802 putc (UNCTRL (*s), rl_outstream);
803 printed_len += 2;
804 s++;
805 #if defined (HANDLE_MULTIBYTE)
806 memset (&ps, 0, sizeof (mbstate_t));
807 #endif
808 }
809 else if (*s == RUBOUT)
810 {
811 putc ('^', rl_outstream);
812 putc ('?', rl_outstream);
813 printed_len += 2;
814 s++;
815 #if defined (HANDLE_MULTIBYTE)
816 memset (&ps, 0, sizeof (mbstate_t));
817 #endif
818 }
819 else
820 {
821 #if defined (HANDLE_MULTIBYTE)
822 tlen = mbrtowc (&wc, s, end - s, &ps);
823 if (MB_INVALIDCH (tlen))
824 {
825 tlen = 1;
826 width = 1;
827 memset (&ps, 0, sizeof (mbstate_t));
828 }
829 else if (MB_NULLWCH (tlen))
830 break;
831 else
832 {
833 w = WCWIDTH (wc);
834 width = (w >= 0) ? w : 1;
835 }
836 fwrite (s, 1, tlen, rl_outstream);
837 s += tlen;
838 printed_len += width;
839 #else
840 putc (*s, rl_outstream);
841 s++;
842 printed_len++;
843 #endif
844 }
845 }
846
847 return printed_len;
848 }
849
850 /* Output TO_PRINT to rl_outstream. If VISIBLE_STATS is defined and we
851 are using it, check for and output a single character for `special'
852 filenames. Return the number of characters we output. */
853
854 static int
855 print_filename (to_print, full_pathname, prefix_bytes)
856 char *to_print, *full_pathname;
857 int prefix_bytes;
858 {
859 int printed_len, extension_char, slen, tlen;
860 char *s, c, *new_full_pathname, *dn;
861
862 extension_char = 0;
863 #if defined (COLOR_SUPPORT)
864 /* Defer printing if we want to prefix with a color indicator */
865 if (_rl_colored_stats == 0 || rl_filename_completion_desired == 0)
866 #endif
867 printed_len = fnprint (to_print, prefix_bytes);
868
869 if (rl_filename_completion_desired && (
870 #if defined (VISIBLE_STATS)
871 rl_visible_stats ||
872 #endif
873 #if defined (COLOR_SUPPORT)
874 _rl_colored_stats ||
875 #endif
876 _rl_complete_mark_directories))
877 {
878 /* If to_print != full_pathname, to_print is the basename of the
879 path passed. In this case, we try to expand the directory
880 name before checking for the stat character. */
881 if (to_print != full_pathname)
882 {
883 /* Terminate the directory name. */
884 c = to_print[-1];
885 to_print[-1] = '\0';
886
887 /* If setting the last slash in full_pathname to a NUL results in
888 full_pathname being the empty string, we are trying to complete
889 files in the root directory. If we pass a null string to the
890 bash directory completion hook, for example, it will expand it
891 to the current directory. We just want the `/'. */
892 if (full_pathname == 0 || *full_pathname == 0)
893 dn = "/";
894 else if (full_pathname[0] != '/')
895 dn = full_pathname;
896 else if (full_pathname[1] == 0)
897 dn = "//"; /* restore trailing slash to `//' */
898 else if (full_pathname[1] == '/' && full_pathname[2] == 0)
899 dn = "/"; /* don't turn /// into // */
900 else
901 dn = full_pathname;
902 s = tilde_expand (dn);
903 if (rl_directory_completion_hook)
904 (*rl_directory_completion_hook) (&s);
905
906 slen = strlen (s);
907 tlen = strlen (to_print);
908 new_full_pathname = (char *)xmalloc (slen + tlen + 2);
909 strcpy (new_full_pathname, s);
910 if (s[slen - 1] == '/')
911 slen--;
912 else
913 new_full_pathname[slen] = '/';
914 new_full_pathname[slen] = '/';
915 strcpy (new_full_pathname + slen + 1, to_print);
916
917 #if defined (VISIBLE_STATS)
918 if (rl_visible_stats)
919 extension_char = stat_char (new_full_pathname);
920 else
921 #endif
922 if (_rl_complete_mark_directories)
923 {
924 dn = 0;
925 if (rl_directory_completion_hook == 0 && rl_filename_stat_hook)
926 {
927 dn = savestring (new_full_pathname);
928 (*rl_filename_stat_hook) (&dn);
929 free (new_full_pathname);
930 new_full_pathname = dn;
931 }
932 if (path_isdir (new_full_pathname))
933 extension_char = '/';
934 }
935
936 #if defined (COLOR_SUPPORT)
937 if (_rl_colored_stats)
938 {
939 colored_stat_start (new_full_pathname);
940 printed_len = fnprint (to_print, prefix_bytes);
941 colored_stat_end ();
942 }
943 #endif
944
945 xfree (new_full_pathname);
946 to_print[-1] = c;
947 }
948 else
949 {
950 s = tilde_expand (full_pathname);
951 #if defined (VISIBLE_STATS)
952 if (rl_visible_stats)
953 extension_char = stat_char (s);
954 else
955 #endif
956 if (_rl_complete_mark_directories && path_isdir (s))
957 extension_char = '/';
958
959 #if defined (COLOR_SUPPORT)
960 if (_rl_colored_stats)
961 {
962 colored_stat_start (s);
963 printed_len = fnprint (to_print, prefix_bytes);
964 colored_stat_end ();
965 }
966 #endif
967
968 }
969
970 xfree (s);
971 if (extension_char)
972 {
973 putc (extension_char, rl_outstream);
974 printed_len++;
975 }
976 }
977
978 return printed_len;
979 }
980
981 static char *
982 rl_quote_filename (s, rtype, qcp)
983 char *s;
984 int rtype;
985 char *qcp;
986 {
987 char *r;
988
989 r = (char *)xmalloc (strlen (s) + 2);
990 *r = *rl_completer_quote_characters;
991 strcpy (r + 1, s);
992 if (qcp)
993 *qcp = *rl_completer_quote_characters;
994 return r;
995 }
996
997 /* Find the bounds of the current word for completion purposes, and leave
998 rl_point set to the end of the word. This function skips quoted
999 substrings (characters between matched pairs of characters in
1000 rl_completer_quote_characters). First we try to find an unclosed
1001 quoted substring on which to do matching. If one is not found, we use
1002 the word break characters to find the boundaries of the current word.
1003 We call an application-specific function to decide whether or not a
1004 particular word break character is quoted; if that function returns a
1005 non-zero result, the character does not break a word. This function
1006 returns the opening quote character if we found an unclosed quoted
1007 substring, '\0' otherwise. FP, if non-null, is set to a value saying
1008 which (shell-like) quote characters we found (single quote, double
1009 quote, or backslash) anywhere in the string. DP, if non-null, is set to
1010 the value of the delimiter character that caused a word break. */
1011
1012 char
1013 _rl_find_completion_word (fp, dp)
1014 int *fp, *dp;
1015 {
1016 int scan, end, found_quote, delimiter, pass_next, isbrk;
1017 char quote_char, *brkchars;
1018
1019 end = rl_point;
1020 found_quote = delimiter = 0;
1021 quote_char = '\0';
1022
1023 brkchars = 0;
1024 if (rl_completion_word_break_hook)
1025 brkchars = (*rl_completion_word_break_hook) ();
1026 if (brkchars == 0)
1027 brkchars = rl_completer_word_break_characters;
1028
1029 if (rl_completer_quote_characters)
1030 {
1031 /* We have a list of characters which can be used in pairs to
1032 quote substrings for the completer. Try to find the start
1033 of an unclosed quoted substring. */
1034 /* FOUND_QUOTE is set so we know what kind of quotes we found. */
1035 for (scan = pass_next = 0; scan < end; scan = MB_NEXTCHAR (rl_line_buffer, scan, 1, MB_FIND_ANY))
1036 {
1037 if (pass_next)
1038 {
1039 pass_next = 0;
1040 continue;
1041 }
1042
1043 /* Shell-like semantics for single quotes -- don't allow backslash
1044 to quote anything in single quotes, especially not the closing
1045 quote. If you don't like this, take out the check on the value
1046 of quote_char. */
1047 if (quote_char != '\'' && rl_line_buffer[scan] == '\\')
1048 {
1049 pass_next = 1;
1050 found_quote |= RL_QF_BACKSLASH;
1051 continue;
1052 }
1053
1054 if (quote_char != '\0')
1055 {
1056 /* Ignore everything until the matching close quote char. */
1057 if (rl_line_buffer[scan] == quote_char)
1058 {
1059 /* Found matching close. Abandon this substring. */
1060 quote_char = '\0';
1061 rl_point = end;
1062 }
1063 }
1064 else if (strchr (rl_completer_quote_characters, rl_line_buffer[scan]))
1065 {
1066 /* Found start of a quoted substring. */
1067 quote_char = rl_line_buffer[scan];
1068 rl_point = scan + 1;
1069 /* Shell-like quoting conventions. */
1070 if (quote_char == '\'')
1071 found_quote |= RL_QF_SINGLE_QUOTE;
1072 else if (quote_char == '"')
1073 found_quote |= RL_QF_DOUBLE_QUOTE;
1074 else
1075 found_quote |= RL_QF_OTHER_QUOTE;
1076 }
1077 }
1078 }
1079
1080 if (rl_point == end && quote_char == '\0')
1081 {
1082 /* We didn't find an unclosed quoted substring upon which to do
1083 completion, so use the word break characters to find the
1084 substring on which to complete. */
1085 while (rl_point = MB_PREVCHAR (rl_line_buffer, rl_point, MB_FIND_ANY))
1086 {
1087 scan = rl_line_buffer[rl_point];
1088
1089 if (strchr (brkchars, scan) == 0)
1090 continue;
1091
1092 /* Call the application-specific function to tell us whether
1093 this word break character is quoted and should be skipped. */
1094 if (rl_char_is_quoted_p && found_quote &&
1095 (*rl_char_is_quoted_p) (rl_line_buffer, rl_point))
1096 continue;
1097
1098 /* Convoluted code, but it avoids an n^2 algorithm with calls
1099 to char_is_quoted. */
1100 break;
1101 }
1102 }
1103
1104 /* If we are at an unquoted word break, then advance past it. */
1105 scan = rl_line_buffer[rl_point];
1106
1107 /* If there is an application-specific function to say whether or not
1108 a character is quoted and we found a quote character, let that
1109 function decide whether or not a character is a word break, even
1110 if it is found in rl_completer_word_break_characters. Don't bother
1111 if we're at the end of the line, though. */
1112 if (scan)
1113 {
1114 if (rl_char_is_quoted_p)
1115 isbrk = (found_quote == 0 ||
1116 (*rl_char_is_quoted_p) (rl_line_buffer, rl_point) == 0) &&
1117 strchr (brkchars, scan) != 0;
1118 else
1119 isbrk = strchr (brkchars, scan) != 0;
1120
1121 if (isbrk)
1122 {
1123 /* If the character that caused the word break was a quoting
1124 character, then remember it as the delimiter. */
1125 if (rl_basic_quote_characters &&
1126 strchr (rl_basic_quote_characters, scan) &&
1127 (end - rl_point) > 1)
1128 delimiter = scan;
1129
1130 /* If the character isn't needed to determine something special
1131 about what kind of completion to perform, then advance past it. */
1132 if (rl_special_prefixes == 0 || strchr (rl_special_prefixes, scan) == 0)
1133 rl_point++;
1134 }
1135 }
1136
1137 if (fp)
1138 *fp = found_quote;
1139 if (dp)
1140 *dp = delimiter;
1141
1142 return (quote_char);
1143 }
1144
1145 static char **
1146 gen_completion_matches (text, start, end, our_func, found_quote, quote_char)
1147 char *text;
1148 int start, end;
1149 rl_compentry_func_t *our_func;
1150 int found_quote, quote_char;
1151 {
1152 char **matches;
1153
1154 rl_completion_found_quote = found_quote;
1155 rl_completion_quote_character = quote_char;
1156
1157 /* If the user wants to TRY to complete, but then wants to give
1158 up and use the default completion function, they set the
1159 variable rl_attempted_completion_function. */
1160 if (rl_attempted_completion_function)
1161 {
1162 matches = (*rl_attempted_completion_function) (text, start, end);
1163 if (RL_SIG_RECEIVED())
1164 {
1165 _rl_free_match_list (matches);
1166 matches = 0;
1167 RL_CHECK_SIGNALS ();
1168 }
1169
1170 if (matches || rl_attempted_completion_over)
1171 {
1172 rl_attempted_completion_over = 0;
1173 return (matches);
1174 }
1175 }
1176
1177 /* XXX -- filename dequoting moved into rl_filename_completion_function */
1178
1179 /* rl_completion_matches will check for signals as well to avoid a long
1180 delay while reading a directory. */
1181 matches = rl_completion_matches (text, our_func);
1182 if (RL_SIG_RECEIVED())
1183 {
1184 _rl_free_match_list (matches);
1185 matches = 0;
1186 RL_CHECK_SIGNALS ();
1187 }
1188 return matches;
1189 }
1190
1191 /* Filter out duplicates in MATCHES. This frees up the strings in
1192 MATCHES. */
1193 static char **
1194 remove_duplicate_matches (matches)
1195 char **matches;
1196 {
1197 char *lowest_common;
1198 int i, j, newlen;
1199 char dead_slot;
1200 char **temp_array;
1201
1202 /* Sort the items. */
1203 for (i = 0; matches[i]; i++)
1204 ;
1205
1206 /* Sort the array without matches[0], since we need it to
1207 stay in place no matter what. */
1208 if (i && rl_sort_completion_matches)
1209 qsort (matches+1, i-1, sizeof (char *), (QSFUNC *)_rl_qsort_string_compare);
1210
1211 /* Remember the lowest common denominator for it may be unique. */
1212 lowest_common = savestring (matches[0]);
1213
1214 for (i = newlen = 0; matches[i + 1]; i++)
1215 {
1216 if (strcmp (matches[i], matches[i + 1]) == 0)
1217 {
1218 xfree (matches[i]);
1219 matches[i] = (char *)&dead_slot;
1220 }
1221 else
1222 newlen++;
1223 }
1224
1225 /* We have marked all the dead slots with (char *)&dead_slot.
1226 Copy all the non-dead entries into a new array. */
1227 temp_array = (char **)xmalloc ((3 + newlen) * sizeof (char *));
1228 for (i = j = 1; matches[i]; i++)
1229 {
1230 if (matches[i] != (char *)&dead_slot)
1231 temp_array[j++] = matches[i];
1232 }
1233 temp_array[j] = (char *)NULL;
1234
1235 if (matches[0] != (char *)&dead_slot)
1236 xfree (matches[0]);
1237
1238 /* Place the lowest common denominator back in [0]. */
1239 temp_array[0] = lowest_common;
1240
1241 /* If there is one string left, and it is identical to the
1242 lowest common denominator, then the LCD is the string to
1243 insert. */
1244 if (j == 2 && strcmp (temp_array[0], temp_array[1]) == 0)
1245 {
1246 xfree (temp_array[1]);
1247 temp_array[1] = (char *)NULL;
1248 }
1249 return (temp_array);
1250 }
1251
1252 /* Find the common prefix of the list of matches, and put it into
1253 matches[0]. */
1254 static int
1255 compute_lcd_of_matches (match_list, matches, text)
1256 char **match_list;
1257 int matches;
1258 const char *text;
1259 {
1260 register int i, c1, c2, si;
1261 int low; /* Count of max-matched characters. */
1262 int lx;
1263 char *dtext; /* dequoted TEXT, if needed */
1264 #if defined (HANDLE_MULTIBYTE)
1265 int v;
1266 size_t v1, v2;
1267 mbstate_t ps1, ps2;
1268 wchar_t wc1, wc2;
1269 #endif
1270
1271 /* If only one match, just use that. Otherwise, compare each
1272 member of the list with the next, finding out where they
1273 stop matching. */
1274 if (matches == 1)
1275 {
1276 match_list[0] = match_list[1];
1277 match_list[1] = (char *)NULL;
1278 return 1;
1279 }
1280
1281 for (i = 1, low = 100000; i < matches; i++)
1282 {
1283 #if defined (HANDLE_MULTIBYTE)
1284 if (MB_CUR_MAX > 1 && rl_byte_oriented == 0)
1285 {
1286 memset (&ps1, 0, sizeof (mbstate_t));
1287 memset (&ps2, 0, sizeof (mbstate_t));
1288 }
1289 #endif
1290 if (_rl_completion_case_fold)
1291 {
1292 for (si = 0;
1293 (c1 = _rl_to_lower(match_list[i][si])) &&
1294 (c2 = _rl_to_lower(match_list[i + 1][si]));
1295 si++)
1296 #if defined (HANDLE_MULTIBYTE)
1297 if (MB_CUR_MAX > 1 && rl_byte_oriented == 0)
1298 {
1299 v1 = mbrtowc(&wc1, match_list[i]+si, strlen (match_list[i]+si), &ps1);
1300 v2 = mbrtowc (&wc2, match_list[i+1]+si, strlen (match_list[i+1]+si), &ps2);
1301 if (MB_INVALIDCH (v1) || MB_INVALIDCH (v2))
1302 {
1303 if (c1 != c2) /* do byte comparison */
1304 break;
1305 continue;
1306 }
1307 wc1 = towlower (wc1);
1308 wc2 = towlower (wc2);
1309 if (wc1 != wc2)
1310 break;
1311 else if (v1 > 1)
1312 si += v1 - 1;
1313 }
1314 else
1315 #endif
1316 if (c1 != c2)
1317 break;
1318 }
1319 else
1320 {
1321 for (si = 0;
1322 (c1 = match_list[i][si]) &&
1323 (c2 = match_list[i + 1][si]);
1324 si++)
1325 #if defined (HANDLE_MULTIBYTE)
1326 if (MB_CUR_MAX > 1 && rl_byte_oriented == 0)
1327 {
1328 mbstate_t ps_back;
1329 ps_back = ps1;
1330 if (!_rl_compare_chars (match_list[i], si, &ps1, match_list[i+1], si, &ps2))
1331 break;
1332 else if ((v = _rl_get_char_len (&match_list[i][si], &ps_back)) > 1)
1333 si += v - 1;
1334 }
1335 else
1336 #endif
1337 if (c1 != c2)
1338 break;
1339 }
1340
1341 if (low > si)
1342 low = si;
1343 }
1344
1345 /* If there were multiple matches, but none matched up to even the
1346 first character, and the user typed something, use that as the
1347 value of matches[0]. */
1348 if (low == 0 && text && *text)
1349 {
1350 match_list[0] = (char *)xmalloc (strlen (text) + 1);
1351 strcpy (match_list[0], text);
1352 }
1353 else
1354 {
1355 match_list[0] = (char *)xmalloc (low + 1);
1356
1357 /* XXX - this might need changes in the presence of multibyte chars */
1358
1359 /* If we are ignoring case, try to preserve the case of the string
1360 the user typed in the face of multiple matches differing in case. */
1361 if (_rl_completion_case_fold)
1362 {
1363 /* We're making an assumption here:
1364 IF we're completing filenames AND
1365 the application has defined a filename dequoting function AND
1366 we found a quote character AND
1367 the application has requested filename quoting
1368 THEN
1369 we assume that TEXT was dequoted before checking against
1370 the file system and needs to be dequoted here before we
1371 check against the list of matches
1372 FI */
1373 dtext = (char *)NULL;
1374 if (rl_filename_completion_desired &&
1375 rl_filename_dequoting_function &&
1376 rl_completion_found_quote &&
1377 rl_filename_quoting_desired)
1378 {
1379 dtext = (*rl_filename_dequoting_function) ((char *)text, rl_completion_quote_character);
1380 text = dtext;
1381 }
1382
1383 /* sort the list to get consistent answers. */
1384 qsort (match_list+1, matches, sizeof(char *), (QSFUNC *)_rl_qsort_string_compare);
1385
1386 si = strlen (text);
1387 lx = (si <= low) ? si : low; /* check shorter of text and matches */
1388 /* Try to preserve the case of what the user typed in the presence of
1389 multiple matches: check each match for something that matches
1390 what the user typed taking case into account; use it up to common
1391 length of matches if one is found. If not, just use first match. */
1392 for (i = 1; i <= matches; i++)
1393 if (strncmp (match_list[i], text, lx) == 0)
1394 {
1395 strncpy (match_list[0], match_list[i], low);
1396 break;
1397 }
1398 /* no casematch, use first entry */
1399 if (i > matches)
1400 strncpy (match_list[0], match_list[1], low);
1401
1402 FREE (dtext);
1403 }
1404 else
1405 strncpy (match_list[0], match_list[1], low);
1406
1407 match_list[0][low] = '\0';
1408 }
1409
1410 return matches;
1411 }
1412
1413 static int
1414 postprocess_matches (matchesp, matching_filenames)
1415 char ***matchesp;
1416 int matching_filenames;
1417 {
1418 char *t, **matches, **temp_matches;
1419 int nmatch, i;
1420
1421 matches = *matchesp;
1422
1423 if (matches == 0)
1424 return 0;
1425
1426 /* It seems to me that in all the cases we handle we would like
1427 to ignore duplicate possiblilities. Scan for the text to
1428 insert being identical to the other completions. */
1429 if (rl_ignore_completion_duplicates)
1430 {
1431 temp_matches = remove_duplicate_matches (matches);
1432 xfree (matches);
1433 matches = temp_matches;
1434 }
1435
1436 /* If we are matching filenames, then here is our chance to
1437 do clever processing by re-examining the list. Call the
1438 ignore function with the array as a parameter. It can
1439 munge the array, deleting matches as it desires. */
1440 if (rl_ignore_some_completions_function && matching_filenames)
1441 {
1442 for (nmatch = 1; matches[nmatch]; nmatch++)
1443 ;
1444 (void)(*rl_ignore_some_completions_function) (matches);
1445 if (matches == 0 || matches[0] == 0)
1446 {
1447 FREE (matches);
1448 *matchesp = (char **)0;
1449 return 0;
1450 }
1451 else
1452 {
1453 /* If we removed some matches, recompute the common prefix. */
1454 for (i = 1; matches[i]; i++)
1455 ;
1456 if (i > 1 && i < nmatch)
1457 {
1458 t = matches[0];
1459 compute_lcd_of_matches (matches, i - 1, t);
1460 FREE (t);
1461 }
1462 }
1463 }
1464
1465 *matchesp = matches;
1466 return (1);
1467 }
1468
1469 static int
1470 complete_get_screenwidth ()
1471 {
1472 int cols;
1473 char *envcols;
1474
1475 cols = _rl_completion_columns;
1476 if (cols >= 0 && cols <= _rl_screenwidth)
1477 return cols;
1478 envcols = getenv ("COLUMNS");
1479 if (envcols && *envcols)
1480 cols = atoi (envcols);
1481 if (cols >= 0 && cols <= _rl_screenwidth)
1482 return cols;
1483 return _rl_screenwidth;
1484 }
1485
1486 /* A convenience function for displaying a list of strings in
1487 columnar format on readline's output stream. MATCHES is the list
1488 of strings, in argv format, LEN is the number of strings in MATCHES,
1489 and MAX is the length of the longest string in MATCHES. */
1490 void
1491 rl_display_match_list (matches, len, max)
1492 char **matches;
1493 int len, max;
1494 {
1495 int count, limit, printed_len, lines, cols;
1496 int i, j, k, l, common_length, sind;
1497 char *temp, *t;
1498
1499 /* Find the length of the prefix common to all items: length as displayed
1500 characters (common_length) and as a byte index into the matches (sind) */
1501 common_length = sind = 0;
1502 if (_rl_completion_prefix_display_length > 0)
1503 {
1504 t = printable_part (matches[0]);
1505 temp = strrchr (t, '/');
1506 common_length = temp ? fnwidth (temp) : fnwidth (t);
1507 sind = temp ? strlen (temp) : strlen (t);
1508
1509 if (common_length > _rl_completion_prefix_display_length && common_length > ELLIPSIS_LEN)
1510 max -= common_length - ELLIPSIS_LEN;
1511 else
1512 common_length = sind = 0;
1513 }
1514
1515 /* How many items of MAX length can we fit in the screen window? */
1516 cols = complete_get_screenwidth ();
1517 max += 2;
1518 limit = cols / max;
1519 if (limit != 1 && (limit * max == cols))
1520 limit--;
1521
1522 /* If cols == 0, limit will end up -1 */
1523 if (cols < _rl_screenwidth && limit < 0)
1524 limit = 1;
1525
1526 /* Avoid a possible floating exception. If max > cols,
1527 limit will be 0 and a divide-by-zero fault will result. */
1528 if (limit == 0)
1529 limit = 1;
1530
1531 /* How many iterations of the printing loop? */
1532 count = (len + (limit - 1)) / limit;
1533
1534 /* Watch out for special case. If LEN is less than LIMIT, then
1535 just do the inner printing loop.
1536 0 < len <= limit implies count = 1. */
1537
1538 /* Sort the items if they are not already sorted. */
1539 if (rl_ignore_completion_duplicates == 0 && rl_sort_completion_matches)
1540 qsort (matches + 1, len, sizeof (char *), (QSFUNC *)_rl_qsort_string_compare);
1541
1542 rl_crlf ();
1543
1544 lines = 0;
1545 if (_rl_print_completions_horizontally == 0)
1546 {
1547 /* Print the sorted items, up-and-down alphabetically, like ls. */
1548 for (i = 1; i <= count; i++)
1549 {
1550 for (j = 0, l = i; j < limit; j++)
1551 {
1552 if (l > len || matches[l] == 0)
1553 break;
1554 else
1555 {
1556 temp = printable_part (matches[l]);
1557 printed_len = print_filename (temp, matches[l], sind);
1558
1559 if (j + 1 < limit)
1560 for (k = 0; k < max - printed_len; k++)
1561 putc (' ', rl_outstream);
1562 }
1563 l += count;
1564 }
1565 rl_crlf ();
1566 lines++;
1567 if (_rl_page_completions && lines >= (_rl_screenheight - 1) && i < count)
1568 {
1569 lines = _rl_internal_pager (lines);
1570 if (lines < 0)
1571 return;
1572 }
1573 }
1574 }
1575 else
1576 {
1577 /* Print the sorted items, across alphabetically, like ls -x. */
1578 for (i = 1; matches[i]; i++)
1579 {
1580 temp = printable_part (matches[i]);
1581 printed_len = print_filename (temp, matches[i], sind);
1582 /* Have we reached the end of this line? */
1583 if (matches[i+1])
1584 {
1585 if (i && (limit > 1) && (i % limit) == 0)
1586 {
1587 rl_crlf ();
1588 lines++;
1589 if (_rl_page_completions && lines >= _rl_screenheight - 1)
1590 {
1591 lines = _rl_internal_pager (lines);
1592 if (lines < 0)
1593 return;
1594 }
1595 }
1596 else
1597 for (k = 0; k < max - printed_len; k++)
1598 putc (' ', rl_outstream);
1599 }
1600 }
1601 rl_crlf ();
1602 }
1603 }
1604
1605 /* Display MATCHES, a list of matching filenames in argv format. This
1606 handles the simple case -- a single match -- first. If there is more
1607 than one match, we compute the number of strings in the list and the
1608 length of the longest string, which will be needed by the display
1609 function. If the application wants to handle displaying the list of
1610 matches itself, it sets RL_COMPLETION_DISPLAY_MATCHES_HOOK to the
1611 address of a function, and we just call it. If we're handling the
1612 display ourselves, we just call rl_display_match_list. We also check
1613 that the list of matches doesn't exceed the user-settable threshold,
1614 and ask the user if he wants to see the list if there are more matches
1615 than RL_COMPLETION_QUERY_ITEMS. */
1616 static void
1617 display_matches (matches)
1618 char **matches;
1619 {
1620 int len, max, i;
1621 char *temp;
1622
1623 /* Move to the last visible line of a possibly-multiple-line command. */
1624 _rl_move_vert (_rl_vis_botlin);
1625
1626 /* Handle simple case first. What if there is only one answer? */
1627 if (matches[1] == 0)
1628 {
1629 temp = printable_part (matches[0]);
1630 rl_crlf ();
1631 print_filename (temp, matches[0], 0);
1632 rl_crlf ();
1633
1634 rl_forced_update_display ();
1635 rl_display_fixed = 1;
1636
1637 return;
1638 }
1639
1640 /* There is more than one answer. Find out how many there are,
1641 and find the maximum printed length of a single entry. */
1642 for (max = 0, i = 1; matches[i]; i++)
1643 {
1644 temp = printable_part (matches[i]);
1645 len = fnwidth (temp);
1646
1647 if (len > max)
1648 max = len;
1649 }
1650
1651 len = i - 1;
1652
1653 /* If the caller has defined a display hook, then call that now. */
1654 if (rl_completion_display_matches_hook)
1655 {
1656 (*rl_completion_display_matches_hook) (matches, len, max);
1657 return;
1658 }
1659
1660 /* If there are many items, then ask the user if she really wants to
1661 see them all. */
1662 if (rl_completion_query_items > 0 && len >= rl_completion_query_items)
1663 {
1664 rl_crlf ();
1665 fprintf (rl_outstream, "Display all %d possibilities? (y or n)", len);
1666 fflush (rl_outstream);
1667 if ((completion_y_or_n = get_y_or_n (0)) == 0)
1668 {
1669 rl_crlf ();
1670
1671 rl_forced_update_display ();
1672 rl_display_fixed = 1;
1673
1674 return;
1675 }
1676 }
1677
1678 rl_display_match_list (matches, len, max);
1679
1680 rl_forced_update_display ();
1681 rl_display_fixed = 1;
1682 }
1683
1684 static char *
1685 make_quoted_replacement (match, mtype, qc)
1686 char *match;
1687 int mtype;
1688 char *qc; /* Pointer to quoting character, if any */
1689 {
1690 int should_quote, do_replace;
1691 char *replacement;
1692
1693 /* If we are doing completion on quoted substrings, and any matches
1694 contain any of the completer_word_break_characters, then auto-
1695 matically prepend the substring with a quote character (just pick
1696 the first one from the list of such) if it does not already begin
1697 with a quote string. FIXME: Need to remove any such automatically
1698 inserted quote character when it no longer is necessary, such as
1699 if we change the string we are completing on and the new set of
1700 matches don't require a quoted substring. */
1701 replacement = match;
1702
1703 should_quote = match && rl_completer_quote_characters &&
1704 rl_filename_completion_desired &&
1705 rl_filename_quoting_desired;
1706
1707 if (should_quote)
1708 should_quote = should_quote && (!qc || !*qc ||
1709 (rl_completer_quote_characters && strchr (rl_completer_quote_characters, *qc)));
1710
1711 if (should_quote)
1712 {
1713 /* If there is a single match, see if we need to quote it.
1714 This also checks whether the common prefix of several
1715 matches needs to be quoted. */
1716 should_quote = rl_filename_quote_characters
1717 ? (_rl_strpbrk (match, rl_filename_quote_characters) != 0)
1718 : 0;
1719
1720 do_replace = should_quote ? mtype : NO_MATCH;
1721 /* Quote the replacement, since we found an embedded
1722 word break character in a potential match. */
1723 if (do_replace != NO_MATCH && rl_filename_quoting_function)
1724 replacement = (*rl_filename_quoting_function) (match, do_replace, qc);
1725 }
1726 return (replacement);
1727 }
1728
1729 static void
1730 insert_match (match, start, mtype, qc)
1731 char *match;
1732 int start, mtype;
1733 char *qc;
1734 {
1735 char *replacement, *r;
1736 char oqc;
1737 int end, rlen;
1738
1739 oqc = qc ? *qc : '\0';
1740 replacement = make_quoted_replacement (match, mtype, qc);
1741
1742 /* Now insert the match. */
1743 if (replacement)
1744 {
1745 rlen = strlen (replacement);
1746 /* Don't double an opening quote character. */
1747 if (qc && *qc && start && rl_line_buffer[start - 1] == *qc &&
1748 replacement[0] == *qc)
1749 start--;
1750 /* If make_quoted_replacement changed the quoting character, remove
1751 the opening quote and insert the (fully-quoted) replacement. */
1752 else if (qc && (*qc != oqc) && start && rl_line_buffer[start - 1] == oqc &&
1753 replacement[0] != oqc)
1754 start--;
1755 end = rl_point - 1;
1756 /* Don't double a closing quote character */
1757 if (qc && *qc && end && rl_line_buffer[rl_point] == *qc && replacement[rlen - 1] == *qc)
1758 end++;
1759 if (_rl_skip_completed_text)
1760 {
1761 r = replacement;
1762 while (start < rl_end && *r && rl_line_buffer[start] == *r)
1763 {
1764 start++;
1765 r++;
1766 }
1767 if (start <= end || *r)
1768 _rl_replace_text (r, start, end);
1769 rl_point = start + strlen (r);
1770 }
1771 else
1772 _rl_replace_text (replacement, start, end);
1773 if (replacement != match)
1774 xfree (replacement);
1775 }
1776 }
1777
1778 /* Append any necessary closing quote and a separator character to the
1779 just-inserted match. If the user has specified that directories
1780 should be marked by a trailing `/', append one of those instead. The
1781 default trailing character is a space. Returns the number of characters
1782 appended. If NONTRIVIAL_MATCH is set, we test for a symlink (if the OS
1783 has them) and don't add a suffix for a symlink to a directory. A
1784 nontrivial match is one that actually adds to the word being completed.
1785 The variable rl_completion_mark_symlink_dirs controls this behavior
1786 (it's initially set to the what the user has chosen, indicated by the
1787 value of _rl_complete_mark_symlink_dirs, but may be modified by an
1788 application's completion function). */
1789 static int
1790 append_to_match (text, delimiter, quote_char, nontrivial_match)
1791 char *text;
1792 int delimiter, quote_char, nontrivial_match;
1793 {
1794 char temp_string[4], *filename;
1795 int temp_string_index, s;
1796 struct stat finfo;
1797
1798 temp_string_index = 0;
1799 if (quote_char && rl_point && rl_completion_suppress_quote == 0 &&
1800 rl_line_buffer[rl_point - 1] != quote_char)
1801 temp_string[temp_string_index++] = quote_char;
1802
1803 if (delimiter)
1804 temp_string[temp_string_index++] = delimiter;
1805 else if (rl_completion_suppress_append == 0 && rl_completion_append_character)
1806 temp_string[temp_string_index++] = rl_completion_append_character;
1807
1808 temp_string[temp_string_index++] = '\0';
1809
1810 if (rl_filename_completion_desired)
1811 {
1812 filename = tilde_expand (text);
1813 if (rl_filename_stat_hook)
1814 (*rl_filename_stat_hook) (&filename);
1815 s = (nontrivial_match && rl_completion_mark_symlink_dirs == 0)
1816 ? LSTAT (filename, &finfo)
1817 : stat (filename, &finfo);
1818 if (s == 0 && S_ISDIR (finfo.st_mode))
1819 {
1820 if (_rl_complete_mark_directories /* && rl_completion_suppress_append == 0 */)
1821 {
1822 /* This is clumsy. Avoid putting in a double slash if point
1823 is at the end of the line and the previous character is a
1824 slash. */
1825 if (rl_point && rl_line_buffer[rl_point] == '\0' && rl_line_buffer[rl_point - 1] == '/')
1826 ;
1827 else if (rl_line_buffer[rl_point] != '/')
1828 rl_insert_text ("/");
1829 }
1830 }
1831 #ifdef S_ISLNK
1832 /* Don't add anything if the filename is a symlink and resolves to a
1833 directory. */
1834 else if (s == 0 && S_ISLNK (finfo.st_mode) && path_isdir (filename))
1835 ;
1836 #endif
1837 else
1838 {
1839 if (rl_point == rl_end && temp_string_index)
1840 rl_insert_text (temp_string);
1841 }
1842 xfree (filename);
1843 }
1844 else
1845 {
1846 if (rl_point == rl_end && temp_string_index)
1847 rl_insert_text (temp_string);
1848 }
1849
1850 return (temp_string_index);
1851 }
1852
1853 static void
1854 insert_all_matches (matches, point, qc)
1855 char **matches;
1856 int point;
1857 char *qc;
1858 {
1859 int i;
1860 char *rp;
1861
1862 rl_begin_undo_group ();
1863 /* remove any opening quote character; make_quoted_replacement will add
1864 it back. */
1865 if (qc && *qc && point && rl_line_buffer[point - 1] == *qc)
1866 point--;
1867 rl_delete_text (point, rl_point);
1868 rl_point = point;
1869
1870 if (matches[1])
1871 {
1872 for (i = 1; matches[i]; i++)
1873 {
1874 rp = make_quoted_replacement (matches[i], SINGLE_MATCH, qc);
1875 rl_insert_text (rp);
1876 rl_insert_text (" ");
1877 if (rp != matches[i])
1878 xfree (rp);
1879 }
1880 }
1881 else
1882 {
1883 rp = make_quoted_replacement (matches[0], SINGLE_MATCH, qc);
1884 rl_insert_text (rp);
1885 rl_insert_text (" ");
1886 if (rp != matches[0])
1887 xfree (rp);
1888 }
1889 rl_end_undo_group ();
1890 }
1891
1892 void
1893 _rl_free_match_list (matches)
1894 char **matches;
1895 {
1896 register int i;
1897
1898 if (matches == 0)
1899 return;
1900
1901 for (i = 0; matches[i]; i++)
1902 xfree (matches[i]);
1903 xfree (matches);
1904 }
1905
1906 /* Complete the word at or before point.
1907 WHAT_TO_DO says what to do with the completion.
1908 `?' means list the possible completions.
1909 TAB means do standard completion.
1910 `*' means insert all of the possible completions.
1911 `!' means to do standard completion, and list all possible completions if
1912 there is more than one.
1913 `@' means to do standard completion, and list all possible completions if
1914 there is more than one and partial completion is not possible. */
1915 int
1916 rl_complete_internal (what_to_do)
1917 int what_to_do;
1918 {
1919 char **matches;
1920 rl_compentry_func_t *our_func;
1921 int start, end, delimiter, found_quote, i, nontrivial_lcd;
1922 char *text, *saved_line_buffer;
1923 char quote_char;
1924 #if 1
1925 int tlen, mlen;
1926 #endif
1927
1928 RL_SETSTATE(RL_STATE_COMPLETING);
1929
1930 set_completion_defaults (what_to_do);
1931
1932 saved_line_buffer = rl_line_buffer ? savestring (rl_line_buffer) : (char *)NULL;
1933 our_func = rl_completion_entry_function
1934 ? rl_completion_entry_function
1935 : rl_filename_completion_function;
1936 /* We now look backwards for the start of a filename/variable word. */
1937 end = rl_point;
1938 found_quote = delimiter = 0;
1939 quote_char = '\0';
1940
1941 if (rl_point)
1942 /* This (possibly) changes rl_point. If it returns a non-zero char,
1943 we know we have an open quote. */
1944 quote_char = _rl_find_completion_word (&found_quote, &delimiter);
1945
1946 start = rl_point;
1947 rl_point = end;
1948
1949 text = rl_copy_text (start, end);
1950 matches = gen_completion_matches (text, start, end, our_func, found_quote, quote_char);
1951 /* nontrivial_lcd is set if the common prefix adds something to the word
1952 being completed. */
1953 nontrivial_lcd = matches && strcmp (text, matches[0]) != 0;
1954 if (what_to_do == '!' || what_to_do == '@')
1955 tlen = strlen (text);
1956 xfree (text);
1957
1958 if (matches == 0)
1959 {
1960 rl_ding ();
1961 FREE (saved_line_buffer);
1962 completion_changed_buffer = 0;
1963 RL_UNSETSTATE(RL_STATE_COMPLETING);
1964 _rl_reset_completion_state ();
1965 return (0);
1966 }
1967
1968 /* If we are matching filenames, the attempted completion function will
1969 have set rl_filename_completion_desired to a non-zero value. The basic
1970 rl_filename_completion_function does this. */
1971 i = rl_filename_completion_desired;
1972
1973 if (postprocess_matches (&matches, i) == 0)
1974 {
1975 rl_ding ();
1976 FREE (saved_line_buffer);
1977 completion_changed_buffer = 0;
1978 RL_UNSETSTATE(RL_STATE_COMPLETING);
1979 _rl_reset_completion_state ();
1980 return (0);
1981 }
1982
1983 switch (what_to_do)
1984 {
1985 case TAB:
1986 case '!':
1987 case '@':
1988 /* Insert the first match with proper quoting. */
1989 if (what_to_do == TAB)
1990 {
1991 if (*matches[0])
1992 insert_match (matches[0], start, matches[1] ? MULT_MATCH : SINGLE_MATCH, &quote_char);
1993 }
1994 else if (*matches[0] && matches[1] == 0)
1995 /* should we perform the check only if there are multiple matches? */
1996 insert_match (matches[0], start, matches[1] ? MULT_MATCH : SINGLE_MATCH, &quote_char);
1997 else if (*matches[0]) /* what_to_do != TAB && multiple matches */
1998 {
1999 mlen = *matches[0] ? strlen (matches[0]) : 0;
2000 if (mlen >= tlen)
2001 insert_match (matches[0], start, matches[1] ? MULT_MATCH : SINGLE_MATCH, &quote_char);
2002 }
2003
2004 /* If there are more matches, ring the bell to indicate.
2005 If we are in vi mode, Posix.2 says to not ring the bell.
2006 If the `show-all-if-ambiguous' variable is set, display
2007 all the matches immediately. Otherwise, if this was the
2008 only match, and we are hacking files, check the file to
2009 see if it was a directory. If so, and the `mark-directories'
2010 variable is set, add a '/' to the name. If not, and we
2011 are at the end of the line, then add a space. */
2012 if (matches[1])
2013 {
2014 if (what_to_do == '!')
2015 {
2016 display_matches (matches);
2017 break;
2018 }
2019 else if (what_to_do == '@')
2020 {
2021 if (nontrivial_lcd == 0)
2022 display_matches (matches);
2023 break;
2024 }
2025 else if (rl_editing_mode != vi_mode)
2026 rl_ding (); /* There are other matches remaining. */
2027 }
2028 else
2029 append_to_match (matches[0], delimiter, quote_char, nontrivial_lcd);
2030
2031 break;
2032
2033 case '*':
2034 insert_all_matches (matches, start, &quote_char);
2035 break;
2036
2037 case '?':
2038 if (rl_completion_display_matches_hook == 0)
2039 {
2040 _rl_sigcleanup = _rl_complete_sigcleanup;
2041 _rl_sigcleanarg = matches;
2042 }
2043 display_matches (matches);
2044 _rl_sigcleanup = 0;
2045 _rl_sigcleanarg = 0;
2046 break;
2047
2048 default:
2049 _rl_ttymsg ("bad value %d for what_to_do in rl_complete", what_to_do);
2050 rl_ding ();
2051 FREE (saved_line_buffer);
2052 RL_UNSETSTATE(RL_STATE_COMPLETING);
2053 _rl_free_match_list (matches);
2054 _rl_reset_completion_state ();
2055 return 1;
2056 }
2057
2058 _rl_free_match_list (matches);
2059
2060 /* Check to see if the line has changed through all of this manipulation. */
2061 if (saved_line_buffer)
2062 {
2063 completion_changed_buffer = strcmp (rl_line_buffer, saved_line_buffer) != 0;
2064 xfree (saved_line_buffer);
2065 }
2066
2067 RL_UNSETSTATE(RL_STATE_COMPLETING);
2068 _rl_reset_completion_state ();
2069 return 0;
2070 }
2071
2072 /***************************************************************/
2073 /* */
2074 /* Application-callable completion match generator functions */
2075 /* */
2076 /***************************************************************/
2077
2078 /* Return an array of (char *) which is a list of completions for TEXT.
2079 If there are no completions, return a NULL pointer.
2080 The first entry in the returned array is the substitution for TEXT.
2081 The remaining entries are the possible completions.
2082 The array is terminated with a NULL pointer.
2083
2084 ENTRY_FUNCTION is a function of two args, and returns a (char *).
2085 The first argument is TEXT.
2086 The second is a state argument; it should be zero on the first call, and
2087 non-zero on subsequent calls. It returns a NULL pointer to the caller
2088 when there are no more matches.
2089 */
2090 char **
2091 rl_completion_matches (text, entry_function)
2092 const char *text;
2093 rl_compentry_func_t *entry_function;
2094 {
2095 register int i;
2096
2097 /* Number of slots in match_list. */
2098 int match_list_size;
2099
2100 /* The list of matches. */
2101 char **match_list;
2102
2103 /* Number of matches actually found. */
2104 int matches;
2105
2106 /* Temporary string binder. */
2107 char *string;
2108
2109 matches = 0;
2110 match_list_size = 10;
2111 match_list = (char **)xmalloc ((match_list_size + 1) * sizeof (char *));
2112 match_list[1] = (char *)NULL;
2113
2114 while (string = (*entry_function) (text, matches))
2115 {
2116 if (RL_SIG_RECEIVED ())
2117 {
2118 /* Start at 1 because we don't set matches[0] in this function.
2119 Only free the list members if we're building match list from
2120 rl_filename_completion_function, since we know that doesn't
2121 free the strings it returns. */
2122 if (entry_function == rl_filename_completion_function)
2123 {
2124 for (i = 1; match_list[i]; i++)
2125 xfree (match_list[i]);
2126 }
2127 xfree (match_list);
2128 match_list = 0;
2129 match_list_size = 0;
2130 RL_CHECK_SIGNALS ();
2131 }
2132
2133 if (matches + 1 == match_list_size)
2134 match_list = (char **)xrealloc
2135 (match_list, ((match_list_size += 10) + 1) * sizeof (char *));
2136
2137 match_list[++matches] = string;
2138 match_list[matches + 1] = (char *)NULL;
2139 }
2140
2141 /* If there were any matches, then look through them finding out the
2142 lowest common denominator. That then becomes match_list[0]. */
2143 if (matches)
2144 compute_lcd_of_matches (match_list, matches, text);
2145 else /* There were no matches. */
2146 {
2147 xfree (match_list);
2148 match_list = (char **)NULL;
2149 }
2150 return (match_list);
2151 }
2152
2153 /* A completion function for usernames.
2154 TEXT contains a partial username preceded by a random
2155 character (usually `~'). */
2156 char *
2157 rl_username_completion_function (text, state)
2158 const char *text;
2159 int state;
2160 {
2161 #if defined (__WIN32__) || defined (__OPENNT)
2162 return (char *)NULL;
2163 #else /* !__WIN32__ && !__OPENNT) */
2164 static char *username = (char *)NULL;
2165 static struct passwd *entry;
2166 static int namelen, first_char, first_char_loc;
2167 char *value;
2168
2169 if (state == 0)
2170 {
2171 FREE (username);
2172
2173 first_char = *text;
2174 first_char_loc = first_char == '~';
2175
2176 username = savestring (&text[first_char_loc]);
2177 namelen = strlen (username);
2178 setpwent ();
2179 }
2180
2181 #if defined (HAVE_GETPWENT)
2182 while (entry = getpwent ())
2183 {
2184 /* Null usernames should result in all users as possible completions. */
2185 if (namelen == 0 || (STREQN (username, entry->pw_name, namelen)))
2186 break;
2187 }
2188 #endif
2189
2190 if (entry == 0)
2191 {
2192 #if defined (HAVE_GETPWENT)
2193 endpwent ();
2194 #endif
2195 return ((char *)NULL);
2196 }
2197 else
2198 {
2199 value = (char *)xmalloc (2 + strlen (entry->pw_name));
2200
2201 *value = *text;
2202
2203 strcpy (value + first_char_loc, entry->pw_name);
2204
2205 if (first_char == '~')
2206 rl_filename_completion_desired = 1;
2207
2208 return (value);
2209 }
2210 #endif /* !__WIN32__ && !__OPENNT */
2211 }
2212
2213 /* Return non-zero if CONVFN matches FILENAME up to the length of FILENAME
2214 (FILENAME_LEN). If _rl_completion_case_fold is set, compare without
2215 regard to the alphabetic case of characters. If
2216 _rl_completion_case_map is set, make `-' and `_' equivalent. CONVFN is
2217 the possibly-converted directory entry; FILENAME is what the user typed. */
2218 static int
2219 complete_fncmp (convfn, convlen, filename, filename_len)
2220 const char *convfn;
2221 int convlen;
2222 const char *filename;
2223 int filename_len;
2224 {
2225 register char *s1, *s2;
2226 int d, len;
2227 #if defined (HANDLE_MULTIBYTE)
2228 size_t v1, v2;
2229 mbstate_t ps1, ps2;
2230 wchar_t wc1, wc2;
2231 #endif
2232
2233 #if defined (HANDLE_MULTIBYTE)
2234 memset (&ps1, 0, sizeof (mbstate_t));
2235 memset (&ps2, 0, sizeof (mbstate_t));
2236 #endif
2237
2238 if (filename_len == 0)
2239 return 1;
2240 if (convlen < filename_len)
2241 return 0;
2242
2243 len = filename_len;
2244 s1 = (char *)convfn;
2245 s2 = (char *)filename;
2246
2247 /* Otherwise, if these match up to the length of filename, then
2248 it is a match. */
2249 if (_rl_completion_case_fold && _rl_completion_case_map)
2250 {
2251 /* Case-insensitive comparison treating _ and - as equivalent */
2252 #if defined (HANDLE_MULTIBYTE)
2253 if (MB_CUR_MAX > 1 && rl_byte_oriented == 0)
2254 {
2255 do
2256 {
2257 v1 = mbrtowc (&wc1, s1, convlen, &ps1);
2258 v2 = mbrtowc (&wc2, s2, filename_len, &ps2);
2259 if (v1 == 0 && v2 == 0)
2260 return 1;
2261 else if (MB_INVALIDCH (v1) || MB_INVALIDCH (v2))
2262 {
2263 if (*s1 != *s2) /* do byte comparison */
2264 return 0;
2265 else if ((*s1 == '-' || *s1 == '_') && (*s2 == '-' || *s2 == '_'))
2266 return 0;
2267 s1++; s2++; len--;
2268 continue;
2269 }
2270 wc1 = towlower (wc1);
2271 wc2 = towlower (wc2);
2272 s1 += v1;
2273 s2 += v1;
2274 len -= v1;
2275 if ((wc1 == L'-' || wc1 == L'_') && (wc2 == L'-' || wc2 == L'_'))
2276 continue;
2277 if (wc1 != wc2)
2278 return 0;
2279 }
2280 while (len != 0);
2281 }
2282 else
2283 #endif
2284 {
2285 do
2286 {
2287 d = _rl_to_lower (*s1) - _rl_to_lower (*s2);
2288 /* *s1 == [-_] && *s2 == [-_] */
2289 if ((*s1 == '-' || *s1 == '_') && (*s2 == '-' || *s2 == '_'))
2290 d = 0;
2291 if (d != 0)
2292 return 0;
2293 s1++; s2++; /* already checked convlen >= filename_len */
2294 }
2295 while (--len != 0);
2296 }
2297
2298 return 1;
2299 }
2300 else if (_rl_completion_case_fold)
2301 {
2302 #if defined (HANDLE_MULTIBYTE)
2303 if (MB_CUR_MAX > 1 && rl_byte_oriented == 0)
2304 {
2305 do
2306 {
2307 v1 = mbrtowc (&wc1, s1, convlen, &ps1);
2308 v2 = mbrtowc (&wc2, s2, filename_len, &ps2);
2309 if (v1 == 0 && v2 == 0)
2310 return 1;
2311 else if (MB_INVALIDCH (v1) || MB_INVALIDCH (v2))
2312 {
2313 if (*s1 != *s2) /* do byte comparison */
2314 return 0;
2315 s1++; s2++; len--;
2316 continue;
2317 }
2318 wc1 = towlower (wc1);
2319 wc2 = towlower (wc2);
2320 if (wc1 != wc2)
2321 return 0;
2322 s1 += v1;
2323 s2 += v1;
2324 len -= v1;
2325 }
2326 while (len != 0);
2327 return 1;
2328 }
2329 else
2330 #endif
2331 if ((_rl_to_lower (convfn[0]) == _rl_to_lower (filename[0])) &&
2332 (convlen >= filename_len) &&
2333 (_rl_strnicmp (filename, convfn, filename_len) == 0))
2334 return 1;
2335 }
2336 else
2337 {
2338 if ((convfn[0] == filename[0]) &&
2339 (convlen >= filename_len) &&
2340 (strncmp (filename, convfn, filename_len) == 0))
2341 return 1;
2342 }
2343 return 0;
2344 }
2345
2346 /* Okay, now we write the entry_function for filename completion. In the
2347 general case. Note that completion in the shell is a little different
2348 because of all the pathnames that must be followed when looking up the
2349 completion for a command. */
2350 char *
2351 rl_filename_completion_function (text, state)
2352 const char *text;
2353 int state;
2354 {
2355 static DIR *directory = (DIR *)NULL;
2356 static char *filename = (char *)NULL;
2357 static char *dirname = (char *)NULL;
2358 static char *users_dirname = (char *)NULL;
2359 static int filename_len;
2360 char *temp, *dentry, *convfn;
2361 int dirlen, dentlen, convlen;
2362 struct dirent *entry;
2363
2364 /* If we don't have any state, then do some initialization. */
2365 if (state == 0)
2366 {
2367 /* If we were interrupted before closing the directory or reading
2368 all of its contents, close it. */
2369 if (directory)
2370 {
2371 closedir (directory);
2372 directory = (DIR *)NULL;
2373 }
2374 FREE (dirname);
2375 FREE (filename);
2376 FREE (users_dirname);
2377
2378 filename = savestring (text);
2379 if (*text == 0)
2380 text = ".";
2381 dirname = savestring (text);
2382
2383 temp = strrchr (dirname, '/');
2384
2385 #if defined (__MSDOS__)
2386 /* special hack for //X/... */
2387 if (dirname[0] == '/' && dirname[1] == '/' && ISALPHA ((unsigned char)dirname[2]) && dirname[3] == '/')
2388 temp = strrchr (dirname + 3, '/');
2389 #endif
2390
2391 if (temp)
2392 {
2393 strcpy (filename, ++temp);
2394 *temp = '\0';
2395 }
2396 #if defined (__MSDOS__)
2397 /* searches from current directory on the drive */
2398 else if (ISALPHA ((unsigned char)dirname[0]) && dirname[1] == ':')
2399 {
2400 strcpy (filename, dirname + 2);
2401 dirname[2] = '\0';
2402 }
2403 #endif
2404 else
2405 {
2406 dirname[0] = '.';
2407 dirname[1] = '\0';
2408 }
2409
2410 /* We aren't done yet. We also support the "~user" syntax. */
2411
2412 /* Save the version of the directory that the user typed, dequoting
2413 it if necessary. */
2414 if (rl_completion_found_quote && rl_filename_dequoting_function)
2415 users_dirname = (*rl_filename_dequoting_function) (dirname, rl_completion_quote_character);
2416 else
2417 users_dirname = savestring (dirname);
2418
2419 if (*dirname == '~')
2420 {
2421 temp = tilde_expand (dirname);
2422 xfree (dirname);
2423 dirname = temp;
2424 }
2425
2426 /* We have saved the possibly-dequoted version of the directory name
2427 the user typed. Now transform the directory name we're going to
2428 pass to opendir(2). The directory rewrite hook modifies only the
2429 directory name; the directory completion hook modifies both the
2430 directory name passed to opendir(2) and the version the user
2431 typed. Both the directory completion and rewrite hooks should perform
2432 any necessary dequoting. The hook functions return 1 if they modify
2433 the directory name argument. If either hook returns 0, it should
2434 not modify the directory name pointer passed as an argument. */
2435 if (rl_directory_rewrite_hook)
2436 (*rl_directory_rewrite_hook) (&dirname);
2437 else if (rl_directory_completion_hook && (*rl_directory_completion_hook) (&dirname))
2438 {
2439 xfree (users_dirname);
2440 users_dirname = savestring (dirname);
2441 }
2442 else if (rl_completion_found_quote && rl_filename_dequoting_function)
2443 {
2444 /* delete single and double quotes */
2445 xfree (dirname);
2446 dirname = savestring (users_dirname);
2447 }
2448 directory = opendir (dirname);
2449
2450 /* Now dequote a non-null filename. FILENAME will not be NULL, but may
2451 be empty. */
2452 if (*filename && rl_completion_found_quote && rl_filename_dequoting_function)
2453 {
2454 /* delete single and double quotes */
2455 temp = (*rl_filename_dequoting_function) (filename, rl_completion_quote_character);
2456 xfree (filename);
2457 filename = temp;
2458 }
2459 filename_len = strlen (filename);
2460
2461 rl_filename_completion_desired = 1;
2462 }
2463
2464 /* At this point we should entertain the possibility of hacking wildcarded
2465 filenames, like /usr/man/man<WILD>/te<TAB>. If the directory name
2466 contains globbing characters, then build an array of directories, and
2467 then map over that list while completing. */
2468 /* *** UNIMPLEMENTED *** */
2469
2470 /* Now that we have some state, we can read the directory. */
2471
2472 entry = (struct dirent *)NULL;
2473 while (directory && (entry = readdir (directory)))
2474 {
2475 convfn = dentry = entry->d_name;
2476 convlen = dentlen = D_NAMLEN (entry);
2477
2478 if (rl_filename_rewrite_hook)
2479 {
2480 convfn = (*rl_filename_rewrite_hook) (dentry, dentlen);
2481 convlen = (convfn == dentry) ? dentlen : strlen (convfn);
2482 }
2483
2484 /* Special case for no filename. If the user has disabled the
2485 `match-hidden-files' variable, skip filenames beginning with `.'.
2486 All other entries except "." and ".." match. */
2487 if (filename_len == 0)
2488 {
2489 if (_rl_match_hidden_files == 0 && HIDDEN_FILE (convfn))
2490 continue;
2491
2492 if (convfn[0] != '.' ||
2493 (convfn[1] && (convfn[1] != '.' || convfn[2])))
2494 break;
2495 }
2496 else
2497 {
2498 if (complete_fncmp (convfn, convlen, filename, filename_len))
2499 break;
2500 }
2501 }
2502
2503 if (entry == 0)
2504 {
2505 if (directory)
2506 {
2507 closedir (directory);
2508 directory = (DIR *)NULL;
2509 }
2510 if (dirname)
2511 {
2512 xfree (dirname);
2513 dirname = (char *)NULL;
2514 }
2515 if (filename)
2516 {
2517 xfree (filename);
2518 filename = (char *)NULL;
2519 }
2520 if (users_dirname)
2521 {
2522 xfree (users_dirname);
2523 users_dirname = (char *)NULL;
2524 }
2525
2526 return (char *)NULL;
2527 }
2528 else
2529 {
2530 /* dirname && (strcmp (dirname, ".") != 0) */
2531 if (dirname && (dirname[0] != '.' || dirname[1]))
2532 {
2533 if (rl_complete_with_tilde_expansion && *users_dirname == '~')
2534 {
2535 dirlen = strlen (dirname);
2536 temp = (char *)xmalloc (2 + dirlen + D_NAMLEN (entry));
2537 strcpy (temp, dirname);
2538 /* Canonicalization cuts off any final slash present. We
2539 may need to add it back. */
2540 if (dirname[dirlen - 1] != '/')
2541 {
2542 temp[dirlen++] = '/';
2543 temp[dirlen] = '\0';
2544 }
2545 }
2546 else
2547 {
2548 dirlen = strlen (users_dirname);
2549 temp = (char *)xmalloc (2 + dirlen + D_NAMLEN (entry));
2550 strcpy (temp, users_dirname);
2551 /* Make sure that temp has a trailing slash here. */
2552 if (users_dirname[dirlen - 1] != '/')
2553 temp[dirlen++] = '/';
2554 }
2555
2556 strcpy (temp + dirlen, convfn);
2557 }
2558 else
2559 temp = savestring (convfn);
2560
2561 if (convfn != dentry)
2562 xfree (convfn);
2563
2564 return (temp);
2565 }
2566 }
2567
2568 /* An initial implementation of a menu completion function a la tcsh. The
2569 first time (if the last readline command was not rl_old_menu_complete), we
2570 generate the list of matches. This code is very similar to the code in
2571 rl_complete_internal -- there should be a way to combine the two. Then,
2572 for each item in the list of matches, we insert the match in an undoable
2573 fashion, with the appropriate character appended (this happens on the
2574 second and subsequent consecutive calls to rl_old_menu_complete). When we
2575 hit the end of the match list, we restore the original unmatched text,
2576 ring the bell, and reset the counter to zero. */
2577 int
2578 rl_old_menu_complete (count, invoking_key)
2579 int count, invoking_key;
2580 {
2581 rl_compentry_func_t *our_func;
2582 int matching_filenames, found_quote;
2583
2584 static char *orig_text;
2585 static char **matches = (char **)0;
2586 static int match_list_index = 0;
2587 static int match_list_size = 0;
2588 static int orig_start, orig_end;
2589 static char quote_char;
2590 static int delimiter;
2591
2592 /* The first time through, we generate the list of matches and set things
2593 up to insert them. */
2594 if (rl_last_func != rl_old_menu_complete)
2595 {
2596 /* Clean up from previous call, if any. */
2597 FREE (orig_text);
2598 if (matches)
2599 _rl_free_match_list (matches);
2600
2601 match_list_index = match_list_size = 0;
2602 matches = (char **)NULL;
2603
2604 rl_completion_invoking_key = invoking_key;
2605
2606 RL_SETSTATE(RL_STATE_COMPLETING);
2607
2608 /* Only the completion entry function can change these. */
2609 set_completion_defaults ('%');
2610
2611 our_func = rl_menu_completion_entry_function;
2612 if (our_func == 0)
2613 our_func = rl_completion_entry_function
2614 ? rl_completion_entry_function
2615 : rl_filename_completion_function;
2616
2617 /* We now look backwards for the start of a filename/variable word. */
2618 orig_end = rl_point;
2619 found_quote = delimiter = 0;
2620 quote_char = '\0';
2621
2622 if (rl_point)
2623 /* This (possibly) changes rl_point. If it returns a non-zero char,
2624 we know we have an open quote. */
2625 quote_char = _rl_find_completion_word (&found_quote, &delimiter);
2626
2627 orig_start = rl_point;
2628 rl_point = orig_end;
2629
2630 orig_text = rl_copy_text (orig_start, orig_end);
2631 matches = gen_completion_matches (orig_text, orig_start, orig_end,
2632 our_func, found_quote, quote_char);
2633
2634 /* If we are matching filenames, the attempted completion function will
2635 have set rl_filename_completion_desired to a non-zero value. The basic
2636 rl_filename_completion_function does this. */
2637 matching_filenames = rl_filename_completion_desired;
2638
2639 if (matches == 0 || postprocess_matches (&matches, matching_filenames) == 0)
2640 {
2641 rl_ding ();
2642 FREE (matches);
2643 matches = (char **)0;
2644 FREE (orig_text);
2645 orig_text = (char *)0;
2646 completion_changed_buffer = 0;
2647 RL_UNSETSTATE(RL_STATE_COMPLETING);
2648 return (0);
2649 }
2650
2651 RL_UNSETSTATE(RL_STATE_COMPLETING);
2652
2653 for (match_list_size = 0; matches[match_list_size]; match_list_size++)
2654 ;
2655 /* matches[0] is lcd if match_list_size > 1, but the circular buffer
2656 code below should take care of it. */
2657
2658 if (match_list_size > 1 && _rl_complete_show_all)
2659 display_matches (matches);
2660 }
2661
2662 /* Now we have the list of matches. Replace the text between
2663 rl_line_buffer[orig_start] and rl_line_buffer[rl_point] with
2664 matches[match_list_index], and add any necessary closing char. */
2665
2666 if (matches == 0 || match_list_size == 0)
2667 {
2668 rl_ding ();
2669 FREE (matches);
2670 matches = (char **)0;
2671 completion_changed_buffer = 0;
2672 return (0);
2673 }
2674
2675 match_list_index += count;
2676 if (match_list_index < 0)
2677 {
2678 while (match_list_index < 0)
2679 match_list_index += match_list_size;
2680 }
2681 else
2682 match_list_index %= match_list_size;
2683
2684 if (match_list_index == 0 && match_list_size > 1)
2685 {
2686 rl_ding ();
2687 insert_match (orig_text, orig_start, MULT_MATCH, &quote_char);
2688 }
2689 else
2690 {
2691 insert_match (matches[match_list_index], orig_start, SINGLE_MATCH, &quote_char);
2692 append_to_match (matches[match_list_index], delimiter, quote_char,
2693 strcmp (orig_text, matches[match_list_index]));
2694 }
2695
2696 completion_changed_buffer = 1;
2697 return (0);
2698 }
2699
2700 int
2701 rl_menu_complete (count, ignore)
2702 int count, ignore;
2703 {
2704 rl_compentry_func_t *our_func;
2705 int matching_filenames, found_quote;
2706
2707 static char *orig_text;
2708 static char **matches = (char **)0;
2709 static int match_list_index = 0;
2710 static int match_list_size = 0;
2711 static int nontrivial_lcd = 0;
2712 static int full_completion = 0; /* set to 1 if menu completion should reinitialize on next call */
2713 static int orig_start, orig_end;
2714 static char quote_char;
2715 static int delimiter, cstate;
2716
2717 /* The first time through, we generate the list of matches and set things
2718 up to insert them. */
2719 if ((rl_last_func != rl_menu_complete && rl_last_func != rl_backward_menu_complete) || full_completion)
2720 {
2721 /* Clean up from previous call, if any. */
2722 FREE (orig_text);
2723 if (matches)
2724 _rl_free_match_list (matches);
2725
2726 match_list_index = match_list_size = 0;
2727 matches = (char **)NULL;
2728
2729 full_completion = 0;
2730
2731 RL_SETSTATE(RL_STATE_COMPLETING);
2732
2733 /* Only the completion entry function can change these. */
2734 set_completion_defaults ('%');
2735
2736 our_func = rl_menu_completion_entry_function;
2737 if (our_func == 0)
2738 our_func = rl_completion_entry_function
2739 ? rl_completion_entry_function
2740 : rl_filename_completion_function;
2741
2742 /* We now look backwards for the start of a filename/variable word. */
2743 orig_end = rl_point;
2744 found_quote = delimiter = 0;
2745 quote_char = '\0';
2746
2747 if (rl_point)
2748 /* This (possibly) changes rl_point. If it returns a non-zero char,
2749 we know we have an open quote. */
2750 quote_char = _rl_find_completion_word (&found_quote, &delimiter);
2751
2752 orig_start = rl_point;
2753 rl_point = orig_end;
2754
2755 orig_text = rl_copy_text (orig_start, orig_end);
2756 matches = gen_completion_matches (orig_text, orig_start, orig_end,
2757 our_func, found_quote, quote_char);
2758
2759 nontrivial_lcd = matches && strcmp (orig_text, matches[0]) != 0;
2760
2761 /* If we are matching filenames, the attempted completion function will
2762 have set rl_filename_completion_desired to a non-zero value. The basic
2763 rl_filename_completion_function does this. */
2764 matching_filenames = rl_filename_completion_desired;
2765
2766 if (matches == 0 || postprocess_matches (&matches, matching_filenames) == 0)
2767 {
2768 rl_ding ();
2769 FREE (matches);
2770 matches = (char **)0;
2771 FREE (orig_text);
2772 orig_text = (char *)0;
2773 completion_changed_buffer = 0;
2774 RL_UNSETSTATE(RL_STATE_COMPLETING);
2775 return (0);
2776 }
2777
2778 RL_UNSETSTATE(RL_STATE_COMPLETING);
2779
2780 for (match_list_size = 0; matches[match_list_size]; match_list_size++)
2781 ;
2782
2783 if (match_list_size == 0)
2784 {
2785 rl_ding ();
2786 FREE (matches);
2787 matches = (char **)0;
2788 match_list_index = 0;
2789 completion_changed_buffer = 0;
2790 return (0);
2791 }
2792
2793 /* matches[0] is lcd if match_list_size > 1, but the circular buffer
2794 code below should take care of it. */
2795 if (*matches[0])
2796 {
2797 insert_match (matches[0], orig_start, matches[1] ? MULT_MATCH : SINGLE_MATCH, &quote_char);
2798 orig_end = orig_start + strlen (matches[0]);
2799 completion_changed_buffer = STREQ (orig_text, matches[0]) == 0;
2800 }
2801
2802 if (match_list_size > 1 && _rl_complete_show_all)
2803 {
2804 display_matches (matches);
2805 /* If there are so many matches that the user has to be asked
2806 whether or not he wants to see the matches, menu completion
2807 is unwieldy. */
2808 if (rl_completion_query_items > 0 && match_list_size >= rl_completion_query_items)
2809 {
2810 rl_ding ();
2811 FREE (matches);
2812 matches = (char **)0;
2813 full_completion = 1;
2814 return (0);
2815 }
2816 else if (_rl_menu_complete_prefix_first)
2817 {
2818 rl_ding ();
2819 return (0);
2820 }
2821 }
2822 else if (match_list_size <= 1)
2823 {
2824 append_to_match (matches[0], delimiter, quote_char, nontrivial_lcd);
2825 full_completion = 1;
2826 return (0);
2827 }
2828 else if (_rl_menu_complete_prefix_first && match_list_size > 1)
2829 {
2830 rl_ding ();
2831 return (0);
2832 }
2833 }
2834
2835 /* Now we have the list of matches. Replace the text between
2836 rl_line_buffer[orig_start] and rl_line_buffer[rl_point] with
2837 matches[match_list_index], and add any necessary closing char. */
2838
2839 if (matches == 0 || match_list_size == 0)
2840 {
2841 rl_ding ();
2842 FREE (matches);
2843 matches = (char **)0;
2844 completion_changed_buffer = 0;
2845 return (0);
2846 }
2847
2848 match_list_index += count;
2849 if (match_list_index < 0)
2850 {
2851 while (match_list_index < 0)
2852 match_list_index += match_list_size;
2853 }
2854 else
2855 match_list_index %= match_list_size;
2856
2857 if (match_list_index == 0 && match_list_size > 1)
2858 {
2859 rl_ding ();
2860 insert_match (matches[0], orig_start, MULT_MATCH, &quote_char);
2861 }
2862 else
2863 {
2864 insert_match (matches[match_list_index], orig_start, SINGLE_MATCH, &quote_char);
2865 append_to_match (matches[match_list_index], delimiter, quote_char,
2866 strcmp (orig_text, matches[match_list_index]));
2867 }
2868
2869 completion_changed_buffer = 1;
2870 return (0);
2871 }
2872
2873 int
2874 rl_backward_menu_complete (count, key)
2875 int count, key;
2876 {
2877 /* Positive arguments to backward-menu-complete translate into negative
2878 arguments for menu-complete, and vice versa. */
2879 return (rl_menu_complete (-count, key));
2880 }