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