Deleted Added
full compact
complete.c (157188) complete.c (165675)
1/* $FreeBSD: head/contrib/libreadline/complete.c 157188 2006-03-27 23:11:32Z ache $ */
1/* $FreeBSD: head/contrib/libreadline/complete.c 165675 2006-12-31 09:22:31Z ache $ */
2/* complete.c -- filename completion for readline. */
3
4/* Copyright (C) 1987-2005 Free Software Foundation, Inc.
5
6 This file is part of the GNU Readline Library, a library for
7 reading lines of text with interactive input and history editing.
8
9 The GNU Readline Library is free software; you can redistribute it
10 and/or modify it under the terms of the GNU General Public License
11 as published by the Free Software Foundation; either version 2, or
12 (at your option) any later version.
13
14 The GNU Readline Library is distributed in the hope that it will be
15 useful, but WITHOUT ANY WARRANTY; without even the implied warranty
16 of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
18
19 The GNU General Public License is often shipped with GNU software, and
20 is generally kept in a file called COPYING or LICENSE. If you do not
21 have a copy of the license, write to the Free Software Foundation,
22 59 Temple Place, Suite 330, Boston, MA 02111 USA. */
23#define READLINE_LIBRARY
24
25#if defined (HAVE_CONFIG_H)
26# include <config.h>
27#endif
28
29#include <sys/types.h>
30#include <fcntl.h>
31#if defined (HAVE_SYS_FILE_H)
32# include <sys/file.h>
33#endif
34
35#if defined (HAVE_UNISTD_H)
36# include <unistd.h>
37#endif /* HAVE_UNISTD_H */
38
39#if defined (HAVE_STDLIB_H)
40# include <stdlib.h>
41#else
42# include "ansi_stdlib.h"
43#endif /* HAVE_STDLIB_H */
44
45#include <stdio.h>
46
47#include <errno.h>
48#if !defined (errno)
49extern int errno;
50#endif /* !errno */
51
52#if defined (HAVE_PWD_H)
53#include <pwd.h>
54#endif
55
56#include "posixdir.h"
57#include "posixstat.h"
58
59/* System-specific feature definitions and include files. */
60#include "rldefs.h"
61#include "rlmbutil.h"
62
63/* Some standard library routines. */
64#include "readline.h"
65#include "xmalloc.h"
66#include "rlprivate.h"
67
68#ifdef __STDC__
69typedef int QSFUNC (const void *, const void *);
70#else
71typedef int QSFUNC ();
72#endif
73
74#ifdef HAVE_LSTAT
75# define LSTAT lstat
76#else
77# define LSTAT stat
78#endif
79
80/* Unix version of a hidden file. Could be different on other systems. */
81#define HIDDEN_FILE(fname) ((fname)[0] == '.')
82
83/* Most systems don't declare getpwent in <pwd.h> if _POSIX_SOURCE is
84 defined. */
85#if defined (HAVE_GETPWENT) && (!defined (HAVE_GETPW_DECLS) || defined (_POSIX_SOURCE))
86extern struct passwd *getpwent PARAMS((void));
87#endif /* HAVE_GETPWENT && (!HAVE_GETPW_DECLS || _POSIX_SOURCE) */
88
89/* If non-zero, then this is the address of a function to call when
90 completing a word would normally display the list of possible matches.
91 This function is called instead of actually doing the display.
92 It takes three arguments: (char **matches, int num_matches, int max_length)
93 where MATCHES is the array of strings that matched, NUM_MATCHES is the
94 number of strings in that array, and MAX_LENGTH is the length of the
95 longest string in that array. */
96rl_compdisp_func_t *rl_completion_display_matches_hook = (rl_compdisp_func_t *)NULL;
97
98#if defined (VISIBLE_STATS)
99# if !defined (X_OK)
100# define X_OK 1
101# endif
102static int stat_char PARAMS((char *));
103#endif
104
105static int path_isdir PARAMS((const char *));
106
107static char *rl_quote_filename PARAMS((char *, int, char *));
108
109static void set_completion_defaults PARAMS((int));
110static int get_y_or_n PARAMS((int));
111static int _rl_internal_pager PARAMS((int));
112static char *printable_part PARAMS((char *));
113static int fnwidth PARAMS((const char *));
114static int fnprint PARAMS((const char *));
115static int print_filename PARAMS((char *, char *));
116
117static char **gen_completion_matches PARAMS((char *, int, int, rl_compentry_func_t *, int, int));
118
119static char **remove_duplicate_matches PARAMS((char **));
120static void insert_match PARAMS((char *, int, int, char *));
121static int append_to_match PARAMS((char *, int, int, int));
122static void insert_all_matches PARAMS((char **, int, char *));
123static void display_matches PARAMS((char **));
124static int compute_lcd_of_matches PARAMS((char **, int, const char *));
125static int postprocess_matches PARAMS((char ***, int));
126
127static char *make_quoted_replacement PARAMS((char *, int, char *));
128
129/* **************************************************************** */
130/* */
131/* Completion matching, from readline's point of view. */
132/* */
133/* **************************************************************** */
134
135/* Variables known only to the readline library. */
136
137/* If non-zero, non-unique completions always show the list of matches. */
138int _rl_complete_show_all = 0;
139
140/* If non-zero, non-unique completions show the list of matches, unless it
141 is not possible to do partial completion and modify the line. */
142int _rl_complete_show_unmodified = 0;
143
144/* If non-zero, completed directory names have a slash appended. */
145int _rl_complete_mark_directories = 1;
146
147/* If non-zero, the symlinked directory completion behavior introduced in
148 readline-4.2a is disabled, and symlinks that point to directories have
149 a slash appended (subject to the value of _rl_complete_mark_directories).
150 This is user-settable via the mark-symlinked-directories variable. */
151int _rl_complete_mark_symlink_dirs = 0;
152
153/* If non-zero, completions are printed horizontally in alphabetical order,
154 like `ls -x'. */
155int _rl_print_completions_horizontally;
156
157/* Non-zero means that case is not significant in filename completion. */
158#if defined (__MSDOS__) && !defined (__DJGPP__)
159int _rl_completion_case_fold = 1;
160#else
161int _rl_completion_case_fold;
162#endif
163
164/* If non-zero, don't match hidden files (filenames beginning with a `.' on
165 Unix) when doing filename completion. */
166int _rl_match_hidden_files = 1;
167
168/* Global variables available to applications using readline. */
169
170#if defined (VISIBLE_STATS)
171/* Non-zero means add an additional character to each filename displayed
172 during listing completion iff rl_filename_completion_desired which helps
173 to indicate the type of file being listed. */
174int rl_visible_stats = 0;
175#endif /* VISIBLE_STATS */
176
177/* If non-zero, then this is the address of a function to call when
178 completing on a directory name. The function is called with
179 the address of a string (the current directory name) as an arg. */
180rl_icppfunc_t *rl_directory_completion_hook = (rl_icppfunc_t *)NULL;
181
182rl_icppfunc_t *rl_directory_rewrite_hook = (rl_icppfunc_t *)NULL;
183
184/* Non-zero means readline completion functions perform tilde expansion. */
185int rl_complete_with_tilde_expansion = 0;
186
187/* Pointer to the generator function for completion_matches ().
188 NULL means to use rl_filename_completion_function (), the default filename
189 completer. */
190rl_compentry_func_t *rl_completion_entry_function = (rl_compentry_func_t *)NULL;
191
192/* Pointer to alternative function to create matches.
193 Function is called with TEXT, START, and END.
194 START and END are indices in RL_LINE_BUFFER saying what the boundaries
195 of TEXT are.
196 If this function exists and returns NULL then call the value of
197 rl_completion_entry_function to try to match, otherwise use the
198 array of strings returned. */
199rl_completion_func_t *rl_attempted_completion_function = (rl_completion_func_t *)NULL;
200
201/* Non-zero means to suppress normal filename completion after the
202 user-specified completion function has been called. */
203int rl_attempted_completion_over = 0;
204
205/* Set to a character indicating the type of completion being performed
206 by rl_complete_internal, available for use by application completion
207 functions. */
208int rl_completion_type = 0;
209
210/* Up to this many items will be displayed in response to a
211 possible-completions call. After that, we ask the user if
212 she is sure she wants to see them all. A negative value means
213 don't ask. */
214int rl_completion_query_items = 100;
215
216int _rl_page_completions = 1;
217
218/* The basic list of characters that signal a break between words for the
219 completer routine. The contents of this variable is what breaks words
220 in the shell, i.e. " \t\n\"\\'`@$><=" */
221const char *rl_basic_word_break_characters = " \t\n\"\\'`@$><=;|&{("; /* }) */
222
223/* List of basic quoting characters. */
224const char *rl_basic_quote_characters = "\"'";
225
226/* The list of characters that signal a break between words for
227 rl_complete_internal. The default list is the contents of
228 rl_basic_word_break_characters. */
229/*const*/ char *rl_completer_word_break_characters = (/*const*/ char *)NULL;
230
231/* Hook function to allow an application to set the completion word
232 break characters before readline breaks up the line. Allows
233 position-dependent word break characters. */
234rl_cpvfunc_t *rl_completion_word_break_hook = (rl_cpvfunc_t *)NULL;
235
236/* List of characters which can be used to quote a substring of the line.
237 Completion occurs on the entire substring, and within the substring
238 rl_completer_word_break_characters are treated as any other character,
239 unless they also appear within this list. */
240const char *rl_completer_quote_characters = (const char *)NULL;
241
242/* List of characters that should be quoted in filenames by the completer. */
243const char *rl_filename_quote_characters = (const char *)NULL;
244
245/* List of characters that are word break characters, but should be left
246 in TEXT when it is passed to the completion function. The shell uses
247 this to help determine what kind of completing to do. */
248const char *rl_special_prefixes = (const char *)NULL;
249
250/* If non-zero, then disallow duplicates in the matches. */
251int rl_ignore_completion_duplicates = 1;
252
253/* Non-zero means that the results of the matches are to be treated
254 as filenames. This is ALWAYS zero on entry, and can only be changed
255 within a completion entry finder function. */
256int rl_filename_completion_desired = 0;
257
258/* Non-zero means that the results of the matches are to be quoted using
259 double quotes (or an application-specific quoting mechanism) if the
260 filename contains any characters in rl_filename_quote_chars. This is
261 ALWAYS non-zero on entry, and can only be changed within a completion
262 entry finder function. */
263int rl_filename_quoting_desired = 1;
264
265/* This function, if defined, is called by the completer when real
266 filename completion is done, after all the matching names have been
267 generated. It is passed a (char**) known as matches in the code below.
268 It consists of a NULL-terminated array of pointers to potential
269 matching strings. The 1st element (matches[0]) is the maximal
270 substring that is common to all matches. This function can re-arrange
271 the list of matches as required, but all elements of the array must be
272 free()'d if they are deleted. The main intent of this function is
273 to implement FIGNORE a la SunOS csh. */
274rl_compignore_func_t *rl_ignore_some_completions_function = (rl_compignore_func_t *)NULL;
275
276/* Set to a function to quote a filename in an application-specific fashion.
277 Called with the text to quote, the type of match found (single or multiple)
278 and a pointer to the quoting character to be used, which the function can
279 reset if desired. */
280rl_quote_func_t *rl_filename_quoting_function = rl_quote_filename;
281
282/* Function to call to remove quoting characters from a filename. Called
283 before completion is attempted, so the embedded quotes do not interfere
284 with matching names in the file system. Readline doesn't do anything
285 with this; it's set only by applications. */
286rl_dequote_func_t *rl_filename_dequoting_function = (rl_dequote_func_t *)NULL;
287
288/* Function to call to decide whether or not a word break character is
289 quoted. If a character is quoted, it does not break words for the
290 completer. */
291rl_linebuf_func_t *rl_char_is_quoted_p = (rl_linebuf_func_t *)NULL;
292
293/* If non-zero, the completion functions don't append anything except a
294 possible closing quote. This is set to 0 by rl_complete_internal and
295 may be changed by an application-specific completion function. */
296int rl_completion_suppress_append = 0;
297
298/* Character appended to completed words when at the end of the line. The
299 default is a space. */
300int rl_completion_append_character = ' ';
301
302/* If non-zero, the completion functions don't append any closing quote.
303 This is set to 0 by rl_complete_internal and may be changed by an
304 application-specific completion function. */
305int rl_completion_suppress_quote = 0;
306
307/* Set to any quote character readline thinks it finds before any application
308 completion function is called. */
309int rl_completion_quote_character;
310
311/* Set to a non-zero value if readline found quoting anywhere in the word to
312 be completed; set before any application completion function is called. */
313int rl_completion_found_quote;
314
315/* If non-zero, a slash will be appended to completed filenames that are
316 symbolic links to directory names, subject to the value of the
317 mark-directories variable (which is user-settable). This exists so
318 that application completion functions can override the user's preference
319 (set via the mark-symlinked-directories variable) if appropriate.
320 It's set to the value of _rl_complete_mark_symlink_dirs in
321 rl_complete_internal before any application-specific completion
322 function is called, so without that function doing anything, the user's
323 preferences are honored. */
324int rl_completion_mark_symlink_dirs;
325
326/* If non-zero, inhibit completion (temporarily). */
327int rl_inhibit_completion;
328
329/* Variables local to this file. */
330
331/* Local variable states what happened during the last completion attempt. */
332static int completion_changed_buffer;
333
334/*************************************/
335/* */
336/* Bindable completion functions */
337/* */
338/*************************************/
339
340/* Complete the word at or before point. You have supplied the function
341 that does the initial simple matching selection algorithm (see
342 rl_completion_matches ()). The default is to do filename completion. */
343int
344rl_complete (ignore, invoking_key)
345 int ignore, invoking_key;
346{
347 if (rl_inhibit_completion)
348 return (_rl_insert_char (ignore, invoking_key));
349 else if (rl_last_func == rl_complete && !completion_changed_buffer)
350 return (rl_complete_internal ('?'));
351 else if (_rl_complete_show_all)
352 return (rl_complete_internal ('!'));
353 else if (_rl_complete_show_unmodified)
354 return (rl_complete_internal ('@'));
355 else
356 return (rl_complete_internal (TAB));
357}
358
359/* List the possible completions. See description of rl_complete (). */
360int
361rl_possible_completions (ignore, invoking_key)
362 int ignore, invoking_key;
363{
364 return (rl_complete_internal ('?'));
365}
366
367int
368rl_insert_completions (ignore, invoking_key)
369 int ignore, invoking_key;
370{
371 return (rl_complete_internal ('*'));
372}
373
374/* Return the correct value to pass to rl_complete_internal performing
375 the same tests as rl_complete. This allows consecutive calls to an
376 application's completion function to list possible completions and for
377 an application-specific completion function to honor the
378 show-all-if-ambiguous readline variable. */
379int
380rl_completion_mode (cfunc)
381 rl_command_func_t *cfunc;
382{
383 if (rl_last_func == cfunc && !completion_changed_buffer)
384 return '?';
385 else if (_rl_complete_show_all)
386 return '!';
387 else if (_rl_complete_show_unmodified)
388 return '@';
389 else
390 return TAB;
391}
392
393/************************************/
394/* */
395/* Completion utility functions */
396/* */
397/************************************/
398
399/* Set default values for readline word completion. These are the variables
400 that application completion functions can change or inspect. */
401static void
402set_completion_defaults (what_to_do)
403 int what_to_do;
404{
405 /* Only the completion entry function can change these. */
406 rl_filename_completion_desired = 0;
407 rl_filename_quoting_desired = 1;
408 rl_completion_type = what_to_do;
409 rl_completion_suppress_append = rl_completion_suppress_quote = 0;
410
411 /* The completion entry function may optionally change this. */
412 rl_completion_mark_symlink_dirs = _rl_complete_mark_symlink_dirs;
413}
414
415/* The user must press "y" or "n". Non-zero return means "y" pressed. */
416static int
417get_y_or_n (for_pager)
418 int for_pager;
419{
420 int c;
421
422 for (;;)
423 {
424 RL_SETSTATE(RL_STATE_MOREINPUT);
425 c = rl_read_key ();
426 RL_UNSETSTATE(RL_STATE_MOREINPUT);
427
428 if (c == 'y' || c == 'Y' || c == ' ')
429 return (1);
430 if (c == 'n' || c == 'N' || c == RUBOUT)
431 return (0);
432 if (c == ABORT_CHAR)
433 _rl_abort_internal ();
434 if (for_pager && (c == NEWLINE || c == RETURN))
435 return (2);
436 if (for_pager && (c == 'q' || c == 'Q'))
437 return (0);
438 rl_ding ();
439 }
440}
441
442static int
443_rl_internal_pager (lines)
444 int lines;
445{
446 int i;
447
448 fprintf (rl_outstream, "--More--");
449 fflush (rl_outstream);
450 i = get_y_or_n (1);
451 _rl_erase_entire_line ();
452 if (i == 0)
453 return -1;
454 else if (i == 2)
455 return (lines - 1);
456 else
457 return 0;
458}
459
460static int
461path_isdir (filename)
462 const char *filename;
463{
464 struct stat finfo;
465
466 return (stat (filename, &finfo) == 0 && S_ISDIR (finfo.st_mode));
467}
468
469#if defined (VISIBLE_STATS)
470/* Return the character which best describes FILENAME.
471 `@' for symbolic links
472 `/' for directories
473 `*' for executables
474 `=' for sockets
475 `|' for FIFOs
476 `%' for character special devices
477 `#' for block special devices */
478static int
479stat_char (filename)
480 char *filename;
481{
482 struct stat finfo;
483 int character, r;
484
485#if defined (HAVE_LSTAT) && defined (S_ISLNK)
486 r = lstat (filename, &finfo);
487#else
488 r = stat (filename, &finfo);
489#endif
490
491 if (r == -1)
492 return (0);
493
494 character = 0;
495 if (S_ISDIR (finfo.st_mode))
496 character = '/';
497#if defined (S_ISCHR)
498 else if (S_ISCHR (finfo.st_mode))
499 character = '%';
500#endif /* S_ISCHR */
501#if defined (S_ISBLK)
502 else if (S_ISBLK (finfo.st_mode))
503 character = '#';
504#endif /* S_ISBLK */
505#if defined (S_ISLNK)
506 else if (S_ISLNK (finfo.st_mode))
507 character = '@';
508#endif /* S_ISLNK */
509#if defined (S_ISSOCK)
510 else if (S_ISSOCK (finfo.st_mode))
511 character = '=';
512#endif /* S_ISSOCK */
513#if defined (S_ISFIFO)
514 else if (S_ISFIFO (finfo.st_mode))
515 character = '|';
516#endif
517 else if (S_ISREG (finfo.st_mode))
518 {
519 if (access (filename, X_OK) == 0)
520 character = '*';
521 }
522 return (character);
523}
524#endif /* VISIBLE_STATS */
525
526/* Return the portion of PATHNAME that should be output when listing
527 possible completions. If we are hacking filename completion, we
528 are only interested in the basename, the portion following the
529 final slash. Otherwise, we return what we were passed. Since
530 printing empty strings is not very informative, if we're doing
531 filename completion, and the basename is the empty string, we look
532 for the previous slash and return the portion following that. If
533 there's no previous slash, we just return what we were passed. */
534static char *
535printable_part (pathname)
536 char *pathname;
537{
538 char *temp, *x;
539
540 if (rl_filename_completion_desired == 0) /* don't need to do anything */
541 return (pathname);
542
543 temp = strrchr (pathname, '/');
544#if defined (__MSDOS__)
545 if (temp == 0 && ISALPHA ((unsigned char)pathname[0]) && pathname[1] == ':')
546 temp = pathname + 1;
547#endif
548
549 if (temp == 0 || *temp == '\0')
550 return (pathname);
551 /* If the basename is NULL, we might have a pathname like '/usr/src/'.
552 Look for a previous slash and, if one is found, return the portion
553 following that slash. If there's no previous slash, just return the
554 pathname we were passed. */
555 else if (temp[1] == '\0')
556 {
557 for (x = temp - 1; x > pathname; x--)
558 if (*x == '/')
559 break;
560 return ((*x == '/') ? x + 1 : pathname);
561 }
562 else
563 return ++temp;
564}
565
566/* Compute width of STRING when displayed on screen by print_filename */
567static int
568fnwidth (string)
569 const char *string;
570{
571 int width, pos;
572#if defined (HANDLE_MULTIBYTE)
573 mbstate_t ps;
574 int left, w;
575 size_t clen;
576 wchar_t wc;
577
578 left = strlen (string) + 1;
579 memset (&ps, 0, sizeof (mbstate_t));
580#endif
581
582 width = pos = 0;
583 while (string[pos])
584 {
585 if (CTRL_CHAR (*string) || *string == RUBOUT)
586 {
587 width += 2;
588 pos++;
589 }
590 else
591 {
592#if defined (HANDLE_MULTIBYTE)
593 clen = mbrtowc (&wc, string + pos, left - pos, &ps);
594 if (MB_INVALIDCH (clen))
595 {
596 width++;
597 pos++;
598 memset (&ps, 0, sizeof (mbstate_t));
599 }
600 else if (MB_NULLWCH (clen))
601 break;
602 else
603 {
604 pos += clen;
605 w = wcwidth (wc);
606 width += (w >= 0) ? w : 1;
607 }
608#else
609 width++;
610 pos++;
611#endif
612 }
613 }
614
615 return width;
616}
617
618static int
619fnprint (to_print)
620 const char *to_print;
621{
622 int printed_len;
623 const char *s;
624#if defined (HANDLE_MULTIBYTE)
625 mbstate_t ps;
626 const char *end;
627 size_t tlen;
628 int width, w;
629 wchar_t wc;
630
631 end = to_print + strlen (to_print) + 1;
632 memset (&ps, 0, sizeof (mbstate_t));
633#endif
634
635 printed_len = 0;
636 s = to_print;
637 while (*s)
638 {
639 if (CTRL_CHAR (*s))
640 {
641 putc ('^', rl_outstream);
642 putc (UNCTRL (*s), rl_outstream);
643 printed_len += 2;
644 s++;
645#if defined (HANDLE_MULTIBYTE)
646 memset (&ps, 0, sizeof (mbstate_t));
647#endif
648 }
649 else if (*s == RUBOUT)
650 {
651 putc ('^', rl_outstream);
652 putc ('?', rl_outstream);
653 printed_len += 2;
654 s++;
655#if defined (HANDLE_MULTIBYTE)
656 memset (&ps, 0, sizeof (mbstate_t));
657#endif
658 }
659 else
660 {
661#if defined (HANDLE_MULTIBYTE)
662 tlen = mbrtowc (&wc, s, end - s, &ps);
663 if (MB_INVALIDCH (tlen))
664 {
665 tlen = 1;
666 width = 1;
667 memset (&ps, 0, sizeof (mbstate_t));
668 }
669 else if (MB_NULLWCH (tlen))
670 break;
671 else
672 {
673 w = wcwidth (wc);
674 width = (w >= 0) ? w : 1;
675 }
676 fwrite (s, 1, tlen, rl_outstream);
677 s += tlen;
678 printed_len += width;
679#else
680 putc (*s, rl_outstream);
681 s++;
682 printed_len++;
683#endif
684 }
685 }
686
687 return printed_len;
688}
689
690/* Output TO_PRINT to rl_outstream. If VISIBLE_STATS is defined and we
691 are using it, check for and output a single character for `special'
692 filenames. Return the number of characters we output. */
693
694static int
695print_filename (to_print, full_pathname)
696 char *to_print, *full_pathname;
697{
698 int printed_len, extension_char, slen, tlen;
699 char *s, c, *new_full_pathname, *dn;
700
701 extension_char = 0;
702 printed_len = fnprint (to_print);
703
704#if defined (VISIBLE_STATS)
705 if (rl_filename_completion_desired && (rl_visible_stats || _rl_complete_mark_directories))
706#else
707 if (rl_filename_completion_desired && _rl_complete_mark_directories)
708#endif
709 {
710 /* If to_print != full_pathname, to_print is the basename of the
711 path passed. In this case, we try to expand the directory
712 name before checking for the stat character. */
713 if (to_print != full_pathname)
714 {
715 /* Terminate the directory name. */
716 c = to_print[-1];
717 to_print[-1] = '\0';
718
719 /* If setting the last slash in full_pathname to a NUL results in
720 full_pathname being the empty string, we are trying to complete
721 files in the root directory. If we pass a null string to the
722 bash directory completion hook, for example, it will expand it
723 to the current directory. We just want the `/'. */
724 if (full_pathname == 0 || *full_pathname == 0)
725 dn = "/";
726 else if (full_pathname[0] != '/')
727 dn = full_pathname;
728 else if (full_pathname[1] == 0)
729 dn = "//"; /* restore trailing slash to `//' */
730 else if (full_pathname[1] == '/' && full_pathname[2] == 0)
731 dn = "/"; /* don't turn /// into // */
732 else
733 dn = full_pathname;
734 s = tilde_expand (dn);
735 if (rl_directory_completion_hook)
736 (*rl_directory_completion_hook) (&s);
737
738 slen = strlen (s);
739 tlen = strlen (to_print);
740 new_full_pathname = (char *)xmalloc (slen + tlen + 2);
741 strcpy (new_full_pathname, s);
742 if (s[slen - 1] == '/')
743 slen--;
744 else
745 new_full_pathname[slen] = '/';
746 new_full_pathname[slen] = '/';
747 strcpy (new_full_pathname + slen + 1, to_print);
748
749#if defined (VISIBLE_STATS)
750 if (rl_visible_stats)
751 extension_char = stat_char (new_full_pathname);
752 else
753#endif
754 if (path_isdir (new_full_pathname))
755 extension_char = '/';
756
757 free (new_full_pathname);
758 to_print[-1] = c;
759 }
760 else
761 {
762 s = tilde_expand (full_pathname);
763#if defined (VISIBLE_STATS)
764 if (rl_visible_stats)
765 extension_char = stat_char (s);
766 else
767#endif
768 if (path_isdir (s))
769 extension_char = '/';
770 }
771
772 free (s);
773 if (extension_char)
774 {
775 putc (extension_char, rl_outstream);
776 printed_len++;
777 }
778 }
779
780 return printed_len;
781}
782
783static char *
784rl_quote_filename (s, rtype, qcp)
785 char *s;
786 int rtype;
787 char *qcp;
788{
789 char *r;
790
791 r = (char *)xmalloc (strlen (s) + 2);
792 *r = *rl_completer_quote_characters;
793 strcpy (r + 1, s);
794 if (qcp)
795 *qcp = *rl_completer_quote_characters;
796 return r;
797}
798
799/* Find the bounds of the current word for completion purposes, and leave
800 rl_point set to the end of the word. This function skips quoted
801 substrings (characters between matched pairs of characters in
802 rl_completer_quote_characters). First we try to find an unclosed
803 quoted substring on which to do matching. If one is not found, we use
804 the word break characters to find the boundaries of the current word.
805 We call an application-specific function to decide whether or not a
806 particular word break character is quoted; if that function returns a
807 non-zero result, the character does not break a word. This function
808 returns the opening quote character if we found an unclosed quoted
809 substring, '\0' otherwise. FP, if non-null, is set to a value saying
810 which (shell-like) quote characters we found (single quote, double
811 quote, or backslash) anywhere in the string. DP, if non-null, is set to
812 the value of the delimiter character that caused a word break. */
813
814char
815_rl_find_completion_word (fp, dp)
816 int *fp, *dp;
817{
818 int scan, end, found_quote, delimiter, pass_next, isbrk;
819 char quote_char, *brkchars;
820
821 end = rl_point;
822 found_quote = delimiter = 0;
823 quote_char = '\0';
824
825 brkchars = 0;
826 if (rl_completion_word_break_hook)
827 brkchars = (*rl_completion_word_break_hook) ();
828 if (brkchars == 0)
829 brkchars = rl_completer_word_break_characters;
830
831 if (rl_completer_quote_characters)
832 {
833 /* We have a list of characters which can be used in pairs to
834 quote substrings for the completer. Try to find the start
835 of an unclosed quoted substring. */
836 /* FOUND_QUOTE is set so we know what kind of quotes we found. */
837 for (scan = pass_next = 0; scan < end; scan = MB_NEXTCHAR (rl_line_buffer, scan, 1, MB_FIND_ANY))
838 {
839 if (pass_next)
840 {
841 pass_next = 0;
842 continue;
843 }
844
845 /* Shell-like semantics for single quotes -- don't allow backslash
846 to quote anything in single quotes, especially not the closing
847 quote. If you don't like this, take out the check on the value
848 of quote_char. */
849 if (quote_char != '\'' && rl_line_buffer[scan] == '\\')
850 {
851 pass_next = 1;
852 found_quote |= RL_QF_BACKSLASH;
853 continue;
854 }
855
856 if (quote_char != '\0')
857 {
858 /* Ignore everything until the matching close quote char. */
859 if (rl_line_buffer[scan] == quote_char)
860 {
861 /* Found matching close. Abandon this substring. */
862 quote_char = '\0';
863 rl_point = end;
864 }
865 }
866 else if (strchr (rl_completer_quote_characters, rl_line_buffer[scan]))
867 {
868 /* Found start of a quoted substring. */
869 quote_char = rl_line_buffer[scan];
870 rl_point = scan + 1;
871 /* Shell-like quoting conventions. */
872 if (quote_char == '\'')
873 found_quote |= RL_QF_SINGLE_QUOTE;
874 else if (quote_char == '"')
875 found_quote |= RL_QF_DOUBLE_QUOTE;
876 else
877 found_quote |= RL_QF_OTHER_QUOTE;
878 }
879 }
880 }
881
882 if (rl_point == end && quote_char == '\0')
883 {
884 /* We didn't find an unclosed quoted substring upon which to do
885 completion, so use the word break characters to find the
886 substring on which to complete. */
887 while (rl_point = MB_PREVCHAR (rl_line_buffer, rl_point, MB_FIND_ANY))
888 {
889 scan = rl_line_buffer[rl_point];
890
891 if (strchr (brkchars, scan) == 0)
892 continue;
893
894 /* Call the application-specific function to tell us whether
895 this word break character is quoted and should be skipped. */
896 if (rl_char_is_quoted_p && found_quote &&
897 (*rl_char_is_quoted_p) (rl_line_buffer, rl_point))
898 continue;
899
900 /* Convoluted code, but it avoids an n^2 algorithm with calls
901 to char_is_quoted. */
902 break;
903 }
904 }
905
906 /* If we are at an unquoted word break, then advance past it. */
907 scan = rl_line_buffer[rl_point];
908
909 /* If there is an application-specific function to say whether or not
910 a character is quoted and we found a quote character, let that
911 function decide whether or not a character is a word break, even
912 if it is found in rl_completer_word_break_characters. Don't bother
913 if we're at the end of the line, though. */
914 if (scan)
915 {
916 if (rl_char_is_quoted_p)
917 isbrk = (found_quote == 0 ||
918 (*rl_char_is_quoted_p) (rl_line_buffer, rl_point) == 0) &&
919 strchr (brkchars, scan) != 0;
920 else
921 isbrk = strchr (brkchars, scan) != 0;
922
923 if (isbrk)
924 {
925 /* If the character that caused the word break was a quoting
926 character, then remember it as the delimiter. */
927 if (rl_basic_quote_characters &&
928 strchr (rl_basic_quote_characters, scan) &&
929 (end - rl_point) > 1)
930 delimiter = scan;
931
932 /* If the character isn't needed to determine something special
933 about what kind of completion to perform, then advance past it. */
934 if (rl_special_prefixes == 0 || strchr (rl_special_prefixes, scan) == 0)
935 rl_point++;
936 }
937 }
938
939 if (fp)
940 *fp = found_quote;
941 if (dp)
942 *dp = delimiter;
943
944 return (quote_char);
945}
946
947static char **
948gen_completion_matches (text, start, end, our_func, found_quote, quote_char)
949 char *text;
950 int start, end;
951 rl_compentry_func_t *our_func;
952 int found_quote, quote_char;
953{
2/* complete.c -- filename completion for readline. */
3
4/* Copyright (C) 1987-2005 Free Software Foundation, Inc.
5
6 This file is part of the GNU Readline Library, a library for
7 reading lines of text with interactive input and history editing.
8
9 The GNU Readline Library is free software; you can redistribute it
10 and/or modify it under the terms of the GNU General Public License
11 as published by the Free Software Foundation; either version 2, or
12 (at your option) any later version.
13
14 The GNU Readline Library is distributed in the hope that it will be
15 useful, but WITHOUT ANY WARRANTY; without even the implied warranty
16 of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
18
19 The GNU General Public License is often shipped with GNU software, and
20 is generally kept in a file called COPYING or LICENSE. If you do not
21 have a copy of the license, write to the Free Software Foundation,
22 59 Temple Place, Suite 330, Boston, MA 02111 USA. */
23#define READLINE_LIBRARY
24
25#if defined (HAVE_CONFIG_H)
26# include <config.h>
27#endif
28
29#include <sys/types.h>
30#include <fcntl.h>
31#if defined (HAVE_SYS_FILE_H)
32# include <sys/file.h>
33#endif
34
35#if defined (HAVE_UNISTD_H)
36# include <unistd.h>
37#endif /* HAVE_UNISTD_H */
38
39#if defined (HAVE_STDLIB_H)
40# include <stdlib.h>
41#else
42# include "ansi_stdlib.h"
43#endif /* HAVE_STDLIB_H */
44
45#include <stdio.h>
46
47#include <errno.h>
48#if !defined (errno)
49extern int errno;
50#endif /* !errno */
51
52#if defined (HAVE_PWD_H)
53#include <pwd.h>
54#endif
55
56#include "posixdir.h"
57#include "posixstat.h"
58
59/* System-specific feature definitions and include files. */
60#include "rldefs.h"
61#include "rlmbutil.h"
62
63/* Some standard library routines. */
64#include "readline.h"
65#include "xmalloc.h"
66#include "rlprivate.h"
67
68#ifdef __STDC__
69typedef int QSFUNC (const void *, const void *);
70#else
71typedef int QSFUNC ();
72#endif
73
74#ifdef HAVE_LSTAT
75# define LSTAT lstat
76#else
77# define LSTAT stat
78#endif
79
80/* Unix version of a hidden file. Could be different on other systems. */
81#define HIDDEN_FILE(fname) ((fname)[0] == '.')
82
83/* Most systems don't declare getpwent in <pwd.h> if _POSIX_SOURCE is
84 defined. */
85#if defined (HAVE_GETPWENT) && (!defined (HAVE_GETPW_DECLS) || defined (_POSIX_SOURCE))
86extern struct passwd *getpwent PARAMS((void));
87#endif /* HAVE_GETPWENT && (!HAVE_GETPW_DECLS || _POSIX_SOURCE) */
88
89/* If non-zero, then this is the address of a function to call when
90 completing a word would normally display the list of possible matches.
91 This function is called instead of actually doing the display.
92 It takes three arguments: (char **matches, int num_matches, int max_length)
93 where MATCHES is the array of strings that matched, NUM_MATCHES is the
94 number of strings in that array, and MAX_LENGTH is the length of the
95 longest string in that array. */
96rl_compdisp_func_t *rl_completion_display_matches_hook = (rl_compdisp_func_t *)NULL;
97
98#if defined (VISIBLE_STATS)
99# if !defined (X_OK)
100# define X_OK 1
101# endif
102static int stat_char PARAMS((char *));
103#endif
104
105static int path_isdir PARAMS((const char *));
106
107static char *rl_quote_filename PARAMS((char *, int, char *));
108
109static void set_completion_defaults PARAMS((int));
110static int get_y_or_n PARAMS((int));
111static int _rl_internal_pager PARAMS((int));
112static char *printable_part PARAMS((char *));
113static int fnwidth PARAMS((const char *));
114static int fnprint PARAMS((const char *));
115static int print_filename PARAMS((char *, char *));
116
117static char **gen_completion_matches PARAMS((char *, int, int, rl_compentry_func_t *, int, int));
118
119static char **remove_duplicate_matches PARAMS((char **));
120static void insert_match PARAMS((char *, int, int, char *));
121static int append_to_match PARAMS((char *, int, int, int));
122static void insert_all_matches PARAMS((char **, int, char *));
123static void display_matches PARAMS((char **));
124static int compute_lcd_of_matches PARAMS((char **, int, const char *));
125static int postprocess_matches PARAMS((char ***, int));
126
127static char *make_quoted_replacement PARAMS((char *, int, char *));
128
129/* **************************************************************** */
130/* */
131/* Completion matching, from readline's point of view. */
132/* */
133/* **************************************************************** */
134
135/* Variables known only to the readline library. */
136
137/* If non-zero, non-unique completions always show the list of matches. */
138int _rl_complete_show_all = 0;
139
140/* If non-zero, non-unique completions show the list of matches, unless it
141 is not possible to do partial completion and modify the line. */
142int _rl_complete_show_unmodified = 0;
143
144/* If non-zero, completed directory names have a slash appended. */
145int _rl_complete_mark_directories = 1;
146
147/* If non-zero, the symlinked directory completion behavior introduced in
148 readline-4.2a is disabled, and symlinks that point to directories have
149 a slash appended (subject to the value of _rl_complete_mark_directories).
150 This is user-settable via the mark-symlinked-directories variable. */
151int _rl_complete_mark_symlink_dirs = 0;
152
153/* If non-zero, completions are printed horizontally in alphabetical order,
154 like `ls -x'. */
155int _rl_print_completions_horizontally;
156
157/* Non-zero means that case is not significant in filename completion. */
158#if defined (__MSDOS__) && !defined (__DJGPP__)
159int _rl_completion_case_fold = 1;
160#else
161int _rl_completion_case_fold;
162#endif
163
164/* If non-zero, don't match hidden files (filenames beginning with a `.' on
165 Unix) when doing filename completion. */
166int _rl_match_hidden_files = 1;
167
168/* Global variables available to applications using readline. */
169
170#if defined (VISIBLE_STATS)
171/* Non-zero means add an additional character to each filename displayed
172 during listing completion iff rl_filename_completion_desired which helps
173 to indicate the type of file being listed. */
174int rl_visible_stats = 0;
175#endif /* VISIBLE_STATS */
176
177/* If non-zero, then this is the address of a function to call when
178 completing on a directory name. The function is called with
179 the address of a string (the current directory name) as an arg. */
180rl_icppfunc_t *rl_directory_completion_hook = (rl_icppfunc_t *)NULL;
181
182rl_icppfunc_t *rl_directory_rewrite_hook = (rl_icppfunc_t *)NULL;
183
184/* Non-zero means readline completion functions perform tilde expansion. */
185int rl_complete_with_tilde_expansion = 0;
186
187/* Pointer to the generator function for completion_matches ().
188 NULL means to use rl_filename_completion_function (), the default filename
189 completer. */
190rl_compentry_func_t *rl_completion_entry_function = (rl_compentry_func_t *)NULL;
191
192/* Pointer to alternative function to create matches.
193 Function is called with TEXT, START, and END.
194 START and END are indices in RL_LINE_BUFFER saying what the boundaries
195 of TEXT are.
196 If this function exists and returns NULL then call the value of
197 rl_completion_entry_function to try to match, otherwise use the
198 array of strings returned. */
199rl_completion_func_t *rl_attempted_completion_function = (rl_completion_func_t *)NULL;
200
201/* Non-zero means to suppress normal filename completion after the
202 user-specified completion function has been called. */
203int rl_attempted_completion_over = 0;
204
205/* Set to a character indicating the type of completion being performed
206 by rl_complete_internal, available for use by application completion
207 functions. */
208int rl_completion_type = 0;
209
210/* Up to this many items will be displayed in response to a
211 possible-completions call. After that, we ask the user if
212 she is sure she wants to see them all. A negative value means
213 don't ask. */
214int rl_completion_query_items = 100;
215
216int _rl_page_completions = 1;
217
218/* The basic list of characters that signal a break between words for the
219 completer routine. The contents of this variable is what breaks words
220 in the shell, i.e. " \t\n\"\\'`@$><=" */
221const char *rl_basic_word_break_characters = " \t\n\"\\'`@$><=;|&{("; /* }) */
222
223/* List of basic quoting characters. */
224const char *rl_basic_quote_characters = "\"'";
225
226/* The list of characters that signal a break between words for
227 rl_complete_internal. The default list is the contents of
228 rl_basic_word_break_characters. */
229/*const*/ char *rl_completer_word_break_characters = (/*const*/ char *)NULL;
230
231/* Hook function to allow an application to set the completion word
232 break characters before readline breaks up the line. Allows
233 position-dependent word break characters. */
234rl_cpvfunc_t *rl_completion_word_break_hook = (rl_cpvfunc_t *)NULL;
235
236/* List of characters which can be used to quote a substring of the line.
237 Completion occurs on the entire substring, and within the substring
238 rl_completer_word_break_characters are treated as any other character,
239 unless they also appear within this list. */
240const char *rl_completer_quote_characters = (const char *)NULL;
241
242/* List of characters that should be quoted in filenames by the completer. */
243const char *rl_filename_quote_characters = (const char *)NULL;
244
245/* List of characters that are word break characters, but should be left
246 in TEXT when it is passed to the completion function. The shell uses
247 this to help determine what kind of completing to do. */
248const char *rl_special_prefixes = (const char *)NULL;
249
250/* If non-zero, then disallow duplicates in the matches. */
251int rl_ignore_completion_duplicates = 1;
252
253/* Non-zero means that the results of the matches are to be treated
254 as filenames. This is ALWAYS zero on entry, and can only be changed
255 within a completion entry finder function. */
256int rl_filename_completion_desired = 0;
257
258/* Non-zero means that the results of the matches are to be quoted using
259 double quotes (or an application-specific quoting mechanism) if the
260 filename contains any characters in rl_filename_quote_chars. This is
261 ALWAYS non-zero on entry, and can only be changed within a completion
262 entry finder function. */
263int rl_filename_quoting_desired = 1;
264
265/* This function, if defined, is called by the completer when real
266 filename completion is done, after all the matching names have been
267 generated. It is passed a (char**) known as matches in the code below.
268 It consists of a NULL-terminated array of pointers to potential
269 matching strings. The 1st element (matches[0]) is the maximal
270 substring that is common to all matches. This function can re-arrange
271 the list of matches as required, but all elements of the array must be
272 free()'d if they are deleted. The main intent of this function is
273 to implement FIGNORE a la SunOS csh. */
274rl_compignore_func_t *rl_ignore_some_completions_function = (rl_compignore_func_t *)NULL;
275
276/* Set to a function to quote a filename in an application-specific fashion.
277 Called with the text to quote, the type of match found (single or multiple)
278 and a pointer to the quoting character to be used, which the function can
279 reset if desired. */
280rl_quote_func_t *rl_filename_quoting_function = rl_quote_filename;
281
282/* Function to call to remove quoting characters from a filename. Called
283 before completion is attempted, so the embedded quotes do not interfere
284 with matching names in the file system. Readline doesn't do anything
285 with this; it's set only by applications. */
286rl_dequote_func_t *rl_filename_dequoting_function = (rl_dequote_func_t *)NULL;
287
288/* Function to call to decide whether or not a word break character is
289 quoted. If a character is quoted, it does not break words for the
290 completer. */
291rl_linebuf_func_t *rl_char_is_quoted_p = (rl_linebuf_func_t *)NULL;
292
293/* If non-zero, the completion functions don't append anything except a
294 possible closing quote. This is set to 0 by rl_complete_internal and
295 may be changed by an application-specific completion function. */
296int rl_completion_suppress_append = 0;
297
298/* Character appended to completed words when at the end of the line. The
299 default is a space. */
300int rl_completion_append_character = ' ';
301
302/* If non-zero, the completion functions don't append any closing quote.
303 This is set to 0 by rl_complete_internal and may be changed by an
304 application-specific completion function. */
305int rl_completion_suppress_quote = 0;
306
307/* Set to any quote character readline thinks it finds before any application
308 completion function is called. */
309int rl_completion_quote_character;
310
311/* Set to a non-zero value if readline found quoting anywhere in the word to
312 be completed; set before any application completion function is called. */
313int rl_completion_found_quote;
314
315/* If non-zero, a slash will be appended to completed filenames that are
316 symbolic links to directory names, subject to the value of the
317 mark-directories variable (which is user-settable). This exists so
318 that application completion functions can override the user's preference
319 (set via the mark-symlinked-directories variable) if appropriate.
320 It's set to the value of _rl_complete_mark_symlink_dirs in
321 rl_complete_internal before any application-specific completion
322 function is called, so without that function doing anything, the user's
323 preferences are honored. */
324int rl_completion_mark_symlink_dirs;
325
326/* If non-zero, inhibit completion (temporarily). */
327int rl_inhibit_completion;
328
329/* Variables local to this file. */
330
331/* Local variable states what happened during the last completion attempt. */
332static int completion_changed_buffer;
333
334/*************************************/
335/* */
336/* Bindable completion functions */
337/* */
338/*************************************/
339
340/* Complete the word at or before point. You have supplied the function
341 that does the initial simple matching selection algorithm (see
342 rl_completion_matches ()). The default is to do filename completion. */
343int
344rl_complete (ignore, invoking_key)
345 int ignore, invoking_key;
346{
347 if (rl_inhibit_completion)
348 return (_rl_insert_char (ignore, invoking_key));
349 else if (rl_last_func == rl_complete && !completion_changed_buffer)
350 return (rl_complete_internal ('?'));
351 else if (_rl_complete_show_all)
352 return (rl_complete_internal ('!'));
353 else if (_rl_complete_show_unmodified)
354 return (rl_complete_internal ('@'));
355 else
356 return (rl_complete_internal (TAB));
357}
358
359/* List the possible completions. See description of rl_complete (). */
360int
361rl_possible_completions (ignore, invoking_key)
362 int ignore, invoking_key;
363{
364 return (rl_complete_internal ('?'));
365}
366
367int
368rl_insert_completions (ignore, invoking_key)
369 int ignore, invoking_key;
370{
371 return (rl_complete_internal ('*'));
372}
373
374/* Return the correct value to pass to rl_complete_internal performing
375 the same tests as rl_complete. This allows consecutive calls to an
376 application's completion function to list possible completions and for
377 an application-specific completion function to honor the
378 show-all-if-ambiguous readline variable. */
379int
380rl_completion_mode (cfunc)
381 rl_command_func_t *cfunc;
382{
383 if (rl_last_func == cfunc && !completion_changed_buffer)
384 return '?';
385 else if (_rl_complete_show_all)
386 return '!';
387 else if (_rl_complete_show_unmodified)
388 return '@';
389 else
390 return TAB;
391}
392
393/************************************/
394/* */
395/* Completion utility functions */
396/* */
397/************************************/
398
399/* Set default values for readline word completion. These are the variables
400 that application completion functions can change or inspect. */
401static void
402set_completion_defaults (what_to_do)
403 int what_to_do;
404{
405 /* Only the completion entry function can change these. */
406 rl_filename_completion_desired = 0;
407 rl_filename_quoting_desired = 1;
408 rl_completion_type = what_to_do;
409 rl_completion_suppress_append = rl_completion_suppress_quote = 0;
410
411 /* The completion entry function may optionally change this. */
412 rl_completion_mark_symlink_dirs = _rl_complete_mark_symlink_dirs;
413}
414
415/* The user must press "y" or "n". Non-zero return means "y" pressed. */
416static int
417get_y_or_n (for_pager)
418 int for_pager;
419{
420 int c;
421
422 for (;;)
423 {
424 RL_SETSTATE(RL_STATE_MOREINPUT);
425 c = rl_read_key ();
426 RL_UNSETSTATE(RL_STATE_MOREINPUT);
427
428 if (c == 'y' || c == 'Y' || c == ' ')
429 return (1);
430 if (c == 'n' || c == 'N' || c == RUBOUT)
431 return (0);
432 if (c == ABORT_CHAR)
433 _rl_abort_internal ();
434 if (for_pager && (c == NEWLINE || c == RETURN))
435 return (2);
436 if (for_pager && (c == 'q' || c == 'Q'))
437 return (0);
438 rl_ding ();
439 }
440}
441
442static int
443_rl_internal_pager (lines)
444 int lines;
445{
446 int i;
447
448 fprintf (rl_outstream, "--More--");
449 fflush (rl_outstream);
450 i = get_y_or_n (1);
451 _rl_erase_entire_line ();
452 if (i == 0)
453 return -1;
454 else if (i == 2)
455 return (lines - 1);
456 else
457 return 0;
458}
459
460static int
461path_isdir (filename)
462 const char *filename;
463{
464 struct stat finfo;
465
466 return (stat (filename, &finfo) == 0 && S_ISDIR (finfo.st_mode));
467}
468
469#if defined (VISIBLE_STATS)
470/* Return the character which best describes FILENAME.
471 `@' for symbolic links
472 `/' for directories
473 `*' for executables
474 `=' for sockets
475 `|' for FIFOs
476 `%' for character special devices
477 `#' for block special devices */
478static int
479stat_char (filename)
480 char *filename;
481{
482 struct stat finfo;
483 int character, r;
484
485#if defined (HAVE_LSTAT) && defined (S_ISLNK)
486 r = lstat (filename, &finfo);
487#else
488 r = stat (filename, &finfo);
489#endif
490
491 if (r == -1)
492 return (0);
493
494 character = 0;
495 if (S_ISDIR (finfo.st_mode))
496 character = '/';
497#if defined (S_ISCHR)
498 else if (S_ISCHR (finfo.st_mode))
499 character = '%';
500#endif /* S_ISCHR */
501#if defined (S_ISBLK)
502 else if (S_ISBLK (finfo.st_mode))
503 character = '#';
504#endif /* S_ISBLK */
505#if defined (S_ISLNK)
506 else if (S_ISLNK (finfo.st_mode))
507 character = '@';
508#endif /* S_ISLNK */
509#if defined (S_ISSOCK)
510 else if (S_ISSOCK (finfo.st_mode))
511 character = '=';
512#endif /* S_ISSOCK */
513#if defined (S_ISFIFO)
514 else if (S_ISFIFO (finfo.st_mode))
515 character = '|';
516#endif
517 else if (S_ISREG (finfo.st_mode))
518 {
519 if (access (filename, X_OK) == 0)
520 character = '*';
521 }
522 return (character);
523}
524#endif /* VISIBLE_STATS */
525
526/* Return the portion of PATHNAME that should be output when listing
527 possible completions. If we are hacking filename completion, we
528 are only interested in the basename, the portion following the
529 final slash. Otherwise, we return what we were passed. Since
530 printing empty strings is not very informative, if we're doing
531 filename completion, and the basename is the empty string, we look
532 for the previous slash and return the portion following that. If
533 there's no previous slash, we just return what we were passed. */
534static char *
535printable_part (pathname)
536 char *pathname;
537{
538 char *temp, *x;
539
540 if (rl_filename_completion_desired == 0) /* don't need to do anything */
541 return (pathname);
542
543 temp = strrchr (pathname, '/');
544#if defined (__MSDOS__)
545 if (temp == 0 && ISALPHA ((unsigned char)pathname[0]) && pathname[1] == ':')
546 temp = pathname + 1;
547#endif
548
549 if (temp == 0 || *temp == '\0')
550 return (pathname);
551 /* If the basename is NULL, we might have a pathname like '/usr/src/'.
552 Look for a previous slash and, if one is found, return the portion
553 following that slash. If there's no previous slash, just return the
554 pathname we were passed. */
555 else if (temp[1] == '\0')
556 {
557 for (x = temp - 1; x > pathname; x--)
558 if (*x == '/')
559 break;
560 return ((*x == '/') ? x + 1 : pathname);
561 }
562 else
563 return ++temp;
564}
565
566/* Compute width of STRING when displayed on screen by print_filename */
567static int
568fnwidth (string)
569 const char *string;
570{
571 int width, pos;
572#if defined (HANDLE_MULTIBYTE)
573 mbstate_t ps;
574 int left, w;
575 size_t clen;
576 wchar_t wc;
577
578 left = strlen (string) + 1;
579 memset (&ps, 0, sizeof (mbstate_t));
580#endif
581
582 width = pos = 0;
583 while (string[pos])
584 {
585 if (CTRL_CHAR (*string) || *string == RUBOUT)
586 {
587 width += 2;
588 pos++;
589 }
590 else
591 {
592#if defined (HANDLE_MULTIBYTE)
593 clen = mbrtowc (&wc, string + pos, left - pos, &ps);
594 if (MB_INVALIDCH (clen))
595 {
596 width++;
597 pos++;
598 memset (&ps, 0, sizeof (mbstate_t));
599 }
600 else if (MB_NULLWCH (clen))
601 break;
602 else
603 {
604 pos += clen;
605 w = wcwidth (wc);
606 width += (w >= 0) ? w : 1;
607 }
608#else
609 width++;
610 pos++;
611#endif
612 }
613 }
614
615 return width;
616}
617
618static int
619fnprint (to_print)
620 const char *to_print;
621{
622 int printed_len;
623 const char *s;
624#if defined (HANDLE_MULTIBYTE)
625 mbstate_t ps;
626 const char *end;
627 size_t tlen;
628 int width, w;
629 wchar_t wc;
630
631 end = to_print + strlen (to_print) + 1;
632 memset (&ps, 0, sizeof (mbstate_t));
633#endif
634
635 printed_len = 0;
636 s = to_print;
637 while (*s)
638 {
639 if (CTRL_CHAR (*s))
640 {
641 putc ('^', rl_outstream);
642 putc (UNCTRL (*s), rl_outstream);
643 printed_len += 2;
644 s++;
645#if defined (HANDLE_MULTIBYTE)
646 memset (&ps, 0, sizeof (mbstate_t));
647#endif
648 }
649 else if (*s == RUBOUT)
650 {
651 putc ('^', rl_outstream);
652 putc ('?', rl_outstream);
653 printed_len += 2;
654 s++;
655#if defined (HANDLE_MULTIBYTE)
656 memset (&ps, 0, sizeof (mbstate_t));
657#endif
658 }
659 else
660 {
661#if defined (HANDLE_MULTIBYTE)
662 tlen = mbrtowc (&wc, s, end - s, &ps);
663 if (MB_INVALIDCH (tlen))
664 {
665 tlen = 1;
666 width = 1;
667 memset (&ps, 0, sizeof (mbstate_t));
668 }
669 else if (MB_NULLWCH (tlen))
670 break;
671 else
672 {
673 w = wcwidth (wc);
674 width = (w >= 0) ? w : 1;
675 }
676 fwrite (s, 1, tlen, rl_outstream);
677 s += tlen;
678 printed_len += width;
679#else
680 putc (*s, rl_outstream);
681 s++;
682 printed_len++;
683#endif
684 }
685 }
686
687 return printed_len;
688}
689
690/* Output TO_PRINT to rl_outstream. If VISIBLE_STATS is defined and we
691 are using it, check for and output a single character for `special'
692 filenames. Return the number of characters we output. */
693
694static int
695print_filename (to_print, full_pathname)
696 char *to_print, *full_pathname;
697{
698 int printed_len, extension_char, slen, tlen;
699 char *s, c, *new_full_pathname, *dn;
700
701 extension_char = 0;
702 printed_len = fnprint (to_print);
703
704#if defined (VISIBLE_STATS)
705 if (rl_filename_completion_desired && (rl_visible_stats || _rl_complete_mark_directories))
706#else
707 if (rl_filename_completion_desired && _rl_complete_mark_directories)
708#endif
709 {
710 /* If to_print != full_pathname, to_print is the basename of the
711 path passed. In this case, we try to expand the directory
712 name before checking for the stat character. */
713 if (to_print != full_pathname)
714 {
715 /* Terminate the directory name. */
716 c = to_print[-1];
717 to_print[-1] = '\0';
718
719 /* If setting the last slash in full_pathname to a NUL results in
720 full_pathname being the empty string, we are trying to complete
721 files in the root directory. If we pass a null string to the
722 bash directory completion hook, for example, it will expand it
723 to the current directory. We just want the `/'. */
724 if (full_pathname == 0 || *full_pathname == 0)
725 dn = "/";
726 else if (full_pathname[0] != '/')
727 dn = full_pathname;
728 else if (full_pathname[1] == 0)
729 dn = "//"; /* restore trailing slash to `//' */
730 else if (full_pathname[1] == '/' && full_pathname[2] == 0)
731 dn = "/"; /* don't turn /// into // */
732 else
733 dn = full_pathname;
734 s = tilde_expand (dn);
735 if (rl_directory_completion_hook)
736 (*rl_directory_completion_hook) (&s);
737
738 slen = strlen (s);
739 tlen = strlen (to_print);
740 new_full_pathname = (char *)xmalloc (slen + tlen + 2);
741 strcpy (new_full_pathname, s);
742 if (s[slen - 1] == '/')
743 slen--;
744 else
745 new_full_pathname[slen] = '/';
746 new_full_pathname[slen] = '/';
747 strcpy (new_full_pathname + slen + 1, to_print);
748
749#if defined (VISIBLE_STATS)
750 if (rl_visible_stats)
751 extension_char = stat_char (new_full_pathname);
752 else
753#endif
754 if (path_isdir (new_full_pathname))
755 extension_char = '/';
756
757 free (new_full_pathname);
758 to_print[-1] = c;
759 }
760 else
761 {
762 s = tilde_expand (full_pathname);
763#if defined (VISIBLE_STATS)
764 if (rl_visible_stats)
765 extension_char = stat_char (s);
766 else
767#endif
768 if (path_isdir (s))
769 extension_char = '/';
770 }
771
772 free (s);
773 if (extension_char)
774 {
775 putc (extension_char, rl_outstream);
776 printed_len++;
777 }
778 }
779
780 return printed_len;
781}
782
783static char *
784rl_quote_filename (s, rtype, qcp)
785 char *s;
786 int rtype;
787 char *qcp;
788{
789 char *r;
790
791 r = (char *)xmalloc (strlen (s) + 2);
792 *r = *rl_completer_quote_characters;
793 strcpy (r + 1, s);
794 if (qcp)
795 *qcp = *rl_completer_quote_characters;
796 return r;
797}
798
799/* Find the bounds of the current word for completion purposes, and leave
800 rl_point set to the end of the word. This function skips quoted
801 substrings (characters between matched pairs of characters in
802 rl_completer_quote_characters). First we try to find an unclosed
803 quoted substring on which to do matching. If one is not found, we use
804 the word break characters to find the boundaries of the current word.
805 We call an application-specific function to decide whether or not a
806 particular word break character is quoted; if that function returns a
807 non-zero result, the character does not break a word. This function
808 returns the opening quote character if we found an unclosed quoted
809 substring, '\0' otherwise. FP, if non-null, is set to a value saying
810 which (shell-like) quote characters we found (single quote, double
811 quote, or backslash) anywhere in the string. DP, if non-null, is set to
812 the value of the delimiter character that caused a word break. */
813
814char
815_rl_find_completion_word (fp, dp)
816 int *fp, *dp;
817{
818 int scan, end, found_quote, delimiter, pass_next, isbrk;
819 char quote_char, *brkchars;
820
821 end = rl_point;
822 found_quote = delimiter = 0;
823 quote_char = '\0';
824
825 brkchars = 0;
826 if (rl_completion_word_break_hook)
827 brkchars = (*rl_completion_word_break_hook) ();
828 if (brkchars == 0)
829 brkchars = rl_completer_word_break_characters;
830
831 if (rl_completer_quote_characters)
832 {
833 /* We have a list of characters which can be used in pairs to
834 quote substrings for the completer. Try to find the start
835 of an unclosed quoted substring. */
836 /* FOUND_QUOTE is set so we know what kind of quotes we found. */
837 for (scan = pass_next = 0; scan < end; scan = MB_NEXTCHAR (rl_line_buffer, scan, 1, MB_FIND_ANY))
838 {
839 if (pass_next)
840 {
841 pass_next = 0;
842 continue;
843 }
844
845 /* Shell-like semantics for single quotes -- don't allow backslash
846 to quote anything in single quotes, especially not the closing
847 quote. If you don't like this, take out the check on the value
848 of quote_char. */
849 if (quote_char != '\'' && rl_line_buffer[scan] == '\\')
850 {
851 pass_next = 1;
852 found_quote |= RL_QF_BACKSLASH;
853 continue;
854 }
855
856 if (quote_char != '\0')
857 {
858 /* Ignore everything until the matching close quote char. */
859 if (rl_line_buffer[scan] == quote_char)
860 {
861 /* Found matching close. Abandon this substring. */
862 quote_char = '\0';
863 rl_point = end;
864 }
865 }
866 else if (strchr (rl_completer_quote_characters, rl_line_buffer[scan]))
867 {
868 /* Found start of a quoted substring. */
869 quote_char = rl_line_buffer[scan];
870 rl_point = scan + 1;
871 /* Shell-like quoting conventions. */
872 if (quote_char == '\'')
873 found_quote |= RL_QF_SINGLE_QUOTE;
874 else if (quote_char == '"')
875 found_quote |= RL_QF_DOUBLE_QUOTE;
876 else
877 found_quote |= RL_QF_OTHER_QUOTE;
878 }
879 }
880 }
881
882 if (rl_point == end && quote_char == '\0')
883 {
884 /* We didn't find an unclosed quoted substring upon which to do
885 completion, so use the word break characters to find the
886 substring on which to complete. */
887 while (rl_point = MB_PREVCHAR (rl_line_buffer, rl_point, MB_FIND_ANY))
888 {
889 scan = rl_line_buffer[rl_point];
890
891 if (strchr (brkchars, scan) == 0)
892 continue;
893
894 /* Call the application-specific function to tell us whether
895 this word break character is quoted and should be skipped. */
896 if (rl_char_is_quoted_p && found_quote &&
897 (*rl_char_is_quoted_p) (rl_line_buffer, rl_point))
898 continue;
899
900 /* Convoluted code, but it avoids an n^2 algorithm with calls
901 to char_is_quoted. */
902 break;
903 }
904 }
905
906 /* If we are at an unquoted word break, then advance past it. */
907 scan = rl_line_buffer[rl_point];
908
909 /* If there is an application-specific function to say whether or not
910 a character is quoted and we found a quote character, let that
911 function decide whether or not a character is a word break, even
912 if it is found in rl_completer_word_break_characters. Don't bother
913 if we're at the end of the line, though. */
914 if (scan)
915 {
916 if (rl_char_is_quoted_p)
917 isbrk = (found_quote == 0 ||
918 (*rl_char_is_quoted_p) (rl_line_buffer, rl_point) == 0) &&
919 strchr (brkchars, scan) != 0;
920 else
921 isbrk = strchr (brkchars, scan) != 0;
922
923 if (isbrk)
924 {
925 /* If the character that caused the word break was a quoting
926 character, then remember it as the delimiter. */
927 if (rl_basic_quote_characters &&
928 strchr (rl_basic_quote_characters, scan) &&
929 (end - rl_point) > 1)
930 delimiter = scan;
931
932 /* If the character isn't needed to determine something special
933 about what kind of completion to perform, then advance past it. */
934 if (rl_special_prefixes == 0 || strchr (rl_special_prefixes, scan) == 0)
935 rl_point++;
936 }
937 }
938
939 if (fp)
940 *fp = found_quote;
941 if (dp)
942 *dp = delimiter;
943
944 return (quote_char);
945}
946
947static char **
948gen_completion_matches (text, start, end, our_func, found_quote, quote_char)
949 char *text;
950 int start, end;
951 rl_compentry_func_t *our_func;
952 int found_quote, quote_char;
953{
954 char **matches, *temp;
954 char **matches;
955
956 rl_completion_found_quote = found_quote;
957 rl_completion_quote_character = quote_char;
958
959 /* If the user wants to TRY to complete, but then wants to give
960 up and use the default completion function, they set the
961 variable rl_attempted_completion_function. */
962 if (rl_attempted_completion_function)
963 {
964 matches = (*rl_attempted_completion_function) (text, start, end);
965
966 if (matches || rl_attempted_completion_over)
967 {
968 rl_attempted_completion_over = 0;
969 return (matches);
970 }
971 }
972
955
956 rl_completion_found_quote = found_quote;
957 rl_completion_quote_character = quote_char;
958
959 /* If the user wants to TRY to complete, but then wants to give
960 up and use the default completion function, they set the
961 variable rl_attempted_completion_function. */
962 if (rl_attempted_completion_function)
963 {
964 matches = (*rl_attempted_completion_function) (text, start, end);
965
966 if (matches || rl_attempted_completion_over)
967 {
968 rl_attempted_completion_over = 0;
969 return (matches);
970 }
971 }
972
973 /* Beware -- we're stripping the quotes here. Do this only if we know
974 we are doing filename completion and the application has defined a
975 filename dequoting function. */
976 temp = (char *)NULL;
973 /* XXX -- filename dequoting moved into rl_filename_completion_function */
977
974
978 if (found_quote && our_func == rl_filename_completion_function &&
979 rl_filename_dequoting_function)
980 {
981 /* delete single and double quotes */
982 temp = (*rl_filename_dequoting_function) (text, quote_char);
983 text = temp; /* not freeing text is not a memory leak */
984 }
985
986 matches = rl_completion_matches (text, our_func);
975 matches = rl_completion_matches (text, our_func);
987 FREE (temp);
988 return matches;
989}
990
991/* Filter out duplicates in MATCHES. This frees up the strings in
992 MATCHES. */
993static char **
994remove_duplicate_matches (matches)
995 char **matches;
996{
997 char *lowest_common;
998 int i, j, newlen;
999 char dead_slot;
1000 char **temp_array;
1001
1002 /* Sort the items. */
1003 for (i = 0; matches[i]; i++)
1004 ;
1005
1006 /* Sort the array without matches[0], since we need it to
1007 stay in place no matter what. */
1008 if (i)
1009 qsort (matches+1, i-1, sizeof (char *), (QSFUNC *)_rl_qsort_string_compare);
1010
1011 /* Remember the lowest common denominator for it may be unique. */
1012 lowest_common = savestring (matches[0]);
1013
1014 for (i = newlen = 0; matches[i + 1]; i++)
1015 {
1016 if (strcmp (matches[i], matches[i + 1]) == 0)
1017 {
1018 free (matches[i]);
1019 matches[i] = (char *)&dead_slot;
1020 }
1021 else
1022 newlen++;
1023 }
1024
1025 /* We have marked all the dead slots with (char *)&dead_slot.
1026 Copy all the non-dead entries into a new array. */
1027 temp_array = (char **)xmalloc ((3 + newlen) * sizeof (char *));
1028 for (i = j = 1; matches[i]; i++)
1029 {
1030 if (matches[i] != (char *)&dead_slot)
1031 temp_array[j++] = matches[i];
1032 }
1033 temp_array[j] = (char *)NULL;
1034
1035 if (matches[0] != (char *)&dead_slot)
1036 free (matches[0]);
1037
1038 /* Place the lowest common denominator back in [0]. */
1039 temp_array[0] = lowest_common;
1040
1041 /* If there is one string left, and it is identical to the
1042 lowest common denominator, then the LCD is the string to
1043 insert. */
1044 if (j == 2 && strcmp (temp_array[0], temp_array[1]) == 0)
1045 {
1046 free (temp_array[1]);
1047 temp_array[1] = (char *)NULL;
1048 }
1049 return (temp_array);
1050}
1051
1052/* Find the common prefix of the list of matches, and put it into
1053 matches[0]. */
1054static int
1055compute_lcd_of_matches (match_list, matches, text)
1056 char **match_list;
1057 int matches;
1058 const char *text;
1059{
1060 register int i, c1, c2, si;
1061 int low; /* Count of max-matched characters. */
1062 char *dtext; /* dequoted TEXT, if needed */
1063#if defined (HANDLE_MULTIBYTE)
1064 int v;
1065 mbstate_t ps1, ps2;
1066 wchar_t wc1, wc2;
1067#endif
1068
1069 /* If only one match, just use that. Otherwise, compare each
1070 member of the list with the next, finding out where they
1071 stop matching. */
1072 if (matches == 1)
1073 {
1074 match_list[0] = match_list[1];
1075 match_list[1] = (char *)NULL;
1076 return 1;
1077 }
1078
1079 for (i = 1, low = 100000; i < matches; i++)
1080 {
1081#if defined (HANDLE_MULTIBYTE)
1082 if (MB_CUR_MAX > 1 && rl_byte_oriented == 0)
1083 {
1084 memset (&ps1, 0, sizeof (mbstate_t));
1085 memset (&ps2, 0, sizeof (mbstate_t));
1086 }
1087#endif
1088 if (_rl_completion_case_fold)
1089 {
1090 for (si = 0;
1091 (c1 = _rl_to_lower(match_list[i][si])) &&
1092 (c2 = _rl_to_lower(match_list[i + 1][si]));
1093 si++)
1094#if defined (HANDLE_MULTIBYTE)
1095 if (MB_CUR_MAX > 1 && rl_byte_oriented == 0)
1096 {
1097 v = mbrtowc (&wc1, match_list[i]+si, strlen (match_list[i]+si), &ps1);
1098 mbrtowc (&wc2, match_list[i+1]+si, strlen (match_list[i+1]+si), &ps2);
1099 wc1 = towlower (wc1);
1100 wc2 = towlower (wc2);
1101 if (wc1 != wc2)
1102 break;
1103 else if (v > 1)
1104 si += v - 1;
1105 }
1106 else
1107#endif
1108 if (c1 != c2)
1109 break;
1110 }
1111 else
1112 {
1113 for (si = 0;
1114 (c1 = match_list[i][si]) &&
1115 (c2 = match_list[i + 1][si]);
1116 si++)
1117#if defined (HANDLE_MULTIBYTE)
1118 if (MB_CUR_MAX > 1 && rl_byte_oriented == 0)
1119 {
976 return matches;
977}
978
979/* Filter out duplicates in MATCHES. This frees up the strings in
980 MATCHES. */
981static char **
982remove_duplicate_matches (matches)
983 char **matches;
984{
985 char *lowest_common;
986 int i, j, newlen;
987 char dead_slot;
988 char **temp_array;
989
990 /* Sort the items. */
991 for (i = 0; matches[i]; i++)
992 ;
993
994 /* Sort the array without matches[0], since we need it to
995 stay in place no matter what. */
996 if (i)
997 qsort (matches+1, i-1, sizeof (char *), (QSFUNC *)_rl_qsort_string_compare);
998
999 /* Remember the lowest common denominator for it may be unique. */
1000 lowest_common = savestring (matches[0]);
1001
1002 for (i = newlen = 0; matches[i + 1]; i++)
1003 {
1004 if (strcmp (matches[i], matches[i + 1]) == 0)
1005 {
1006 free (matches[i]);
1007 matches[i] = (char *)&dead_slot;
1008 }
1009 else
1010 newlen++;
1011 }
1012
1013 /* We have marked all the dead slots with (char *)&dead_slot.
1014 Copy all the non-dead entries into a new array. */
1015 temp_array = (char **)xmalloc ((3 + newlen) * sizeof (char *));
1016 for (i = j = 1; matches[i]; i++)
1017 {
1018 if (matches[i] != (char *)&dead_slot)
1019 temp_array[j++] = matches[i];
1020 }
1021 temp_array[j] = (char *)NULL;
1022
1023 if (matches[0] != (char *)&dead_slot)
1024 free (matches[0]);
1025
1026 /* Place the lowest common denominator back in [0]. */
1027 temp_array[0] = lowest_common;
1028
1029 /* If there is one string left, and it is identical to the
1030 lowest common denominator, then the LCD is the string to
1031 insert. */
1032 if (j == 2 && strcmp (temp_array[0], temp_array[1]) == 0)
1033 {
1034 free (temp_array[1]);
1035 temp_array[1] = (char *)NULL;
1036 }
1037 return (temp_array);
1038}
1039
1040/* Find the common prefix of the list of matches, and put it into
1041 matches[0]. */
1042static int
1043compute_lcd_of_matches (match_list, matches, text)
1044 char **match_list;
1045 int matches;
1046 const char *text;
1047{
1048 register int i, c1, c2, si;
1049 int low; /* Count of max-matched characters. */
1050 char *dtext; /* dequoted TEXT, if needed */
1051#if defined (HANDLE_MULTIBYTE)
1052 int v;
1053 mbstate_t ps1, ps2;
1054 wchar_t wc1, wc2;
1055#endif
1056
1057 /* If only one match, just use that. Otherwise, compare each
1058 member of the list with the next, finding out where they
1059 stop matching. */
1060 if (matches == 1)
1061 {
1062 match_list[0] = match_list[1];
1063 match_list[1] = (char *)NULL;
1064 return 1;
1065 }
1066
1067 for (i = 1, low = 100000; i < matches; i++)
1068 {
1069#if defined (HANDLE_MULTIBYTE)
1070 if (MB_CUR_MAX > 1 && rl_byte_oriented == 0)
1071 {
1072 memset (&ps1, 0, sizeof (mbstate_t));
1073 memset (&ps2, 0, sizeof (mbstate_t));
1074 }
1075#endif
1076 if (_rl_completion_case_fold)
1077 {
1078 for (si = 0;
1079 (c1 = _rl_to_lower(match_list[i][si])) &&
1080 (c2 = _rl_to_lower(match_list[i + 1][si]));
1081 si++)
1082#if defined (HANDLE_MULTIBYTE)
1083 if (MB_CUR_MAX > 1 && rl_byte_oriented == 0)
1084 {
1085 v = mbrtowc (&wc1, match_list[i]+si, strlen (match_list[i]+si), &ps1);
1086 mbrtowc (&wc2, match_list[i+1]+si, strlen (match_list[i+1]+si), &ps2);
1087 wc1 = towlower (wc1);
1088 wc2 = towlower (wc2);
1089 if (wc1 != wc2)
1090 break;
1091 else if (v > 1)
1092 si += v - 1;
1093 }
1094 else
1095#endif
1096 if (c1 != c2)
1097 break;
1098 }
1099 else
1100 {
1101 for (si = 0;
1102 (c1 = match_list[i][si]) &&
1103 (c2 = match_list[i + 1][si]);
1104 si++)
1105#if defined (HANDLE_MULTIBYTE)
1106 if (MB_CUR_MAX > 1 && rl_byte_oriented == 0)
1107 {
1120 mbstate_t ps_back = ps1;
1108 mbstate_t ps_back;
1109 ps_back = ps1;
1121 if (!_rl_compare_chars (match_list[i], si, &ps1, match_list[i+1], si, &ps2))
1122 break;
1123 else if ((v = _rl_get_char_len (&match_list[i][si], &ps_back)) > 1)
1124 si += v - 1;
1125 }
1126 else
1127#endif
1128 if (c1 != c2)
1129 break;
1130 }
1131
1132 if (low > si)
1133 low = si;
1134 }
1135
1136 /* If there were multiple matches, but none matched up to even the
1137 first character, and the user typed something, use that as the
1138 value of matches[0]. */
1139 if (low == 0 && text && *text)
1140 {
1141 match_list[0] = (char *)xmalloc (strlen (text) + 1);
1142 strcpy (match_list[0], text);
1143 }
1144 else
1145 {
1146 match_list[0] = (char *)xmalloc (low + 1);
1147
1148 /* XXX - this might need changes in the presence of multibyte chars */
1149
1150 /* If we are ignoring case, try to preserve the case of the string
1151 the user typed in the face of multiple matches differing in case. */
1152 if (_rl_completion_case_fold)
1153 {
1154 /* We're making an assumption here:
1155 IF we're completing filenames AND
1156 the application has defined a filename dequoting function AND
1157 we found a quote character AND
1158 the application has requested filename quoting
1159 THEN
1160 we assume that TEXT was dequoted before checking against
1161 the file system and needs to be dequoted here before we
1162 check against the list of matches
1163 FI */
1164 dtext = (char *)NULL;
1165 if (rl_filename_completion_desired &&
1166 rl_filename_dequoting_function &&
1167 rl_completion_found_quote &&
1168 rl_filename_quoting_desired)
1169 {
1170 dtext = (*rl_filename_dequoting_function) ((char *)text, rl_completion_quote_character);
1171 text = dtext;
1172 }
1173
1174 /* sort the list to get consistent answers. */
1175 qsort (match_list+1, matches, sizeof(char *), (QSFUNC *)_rl_qsort_string_compare);
1176
1177 si = strlen (text);
1178 if (si <= low)
1179 {
1180 for (i = 1; i <= matches; i++)
1181 if (strncmp (match_list[i], text, si) == 0)
1182 {
1183 strncpy (match_list[0], match_list[i], low);
1184 break;
1185 }
1186 /* no casematch, use first entry */
1187 if (i > matches)
1188 strncpy (match_list[0], match_list[1], low);
1189 }
1190 else
1191 /* otherwise, just use the text the user typed. */
1192 strncpy (match_list[0], text, low);
1193
1194 FREE (dtext);
1195 }
1196 else
1197 strncpy (match_list[0], match_list[1], low);
1198
1199 match_list[0][low] = '\0';
1200 }
1201
1202 return matches;
1203}
1204
1205static int
1206postprocess_matches (matchesp, matching_filenames)
1207 char ***matchesp;
1208 int matching_filenames;
1209{
1210 char *t, **matches, **temp_matches;
1211 int nmatch, i;
1212
1213 matches = *matchesp;
1214
1215 if (matches == 0)
1216 return 0;
1217
1218 /* It seems to me that in all the cases we handle we would like
1219 to ignore duplicate possiblilities. Scan for the text to
1220 insert being identical to the other completions. */
1221 if (rl_ignore_completion_duplicates)
1222 {
1223 temp_matches = remove_duplicate_matches (matches);
1224 free (matches);
1225 matches = temp_matches;
1226 }
1227
1228 /* If we are matching filenames, then here is our chance to
1229 do clever processing by re-examining the list. Call the
1230 ignore function with the array as a parameter. It can
1231 munge the array, deleting matches as it desires. */
1232 if (rl_ignore_some_completions_function && matching_filenames)
1233 {
1234 for (nmatch = 1; matches[nmatch]; nmatch++)
1235 ;
1236 (void)(*rl_ignore_some_completions_function) (matches);
1237 if (matches == 0 || matches[0] == 0)
1238 {
1239 FREE (matches);
1240 *matchesp = (char **)0;
1241 return 0;
1242 }
1243 else
1244 {
1245 /* If we removed some matches, recompute the common prefix. */
1246 for (i = 1; matches[i]; i++)
1247 ;
1248 if (i > 1 && i < nmatch)
1249 {
1250 t = matches[0];
1251 compute_lcd_of_matches (matches, i - 1, t);
1252 FREE (t);
1253 }
1254 }
1255 }
1256
1257 *matchesp = matches;
1258 return (1);
1259}
1260
1261/* A convenience function for displaying a list of strings in
1262 columnar format on readline's output stream. MATCHES is the list
1263 of strings, in argv format, LEN is the number of strings in MATCHES,
1264 and MAX is the length of the longest string in MATCHES. */
1265void
1266rl_display_match_list (matches, len, max)
1267 char **matches;
1268 int len, max;
1269{
1270 int count, limit, printed_len, lines;
1271 int i, j, k, l;
1272 char *temp;
1273
1274 /* How many items of MAX length can we fit in the screen window? */
1275 max += 2;
1276 limit = _rl_screenwidth / max;
1277 if (limit != 1 && (limit * max == _rl_screenwidth))
1278 limit--;
1279
1280 /* Avoid a possible floating exception. If max > _rl_screenwidth,
1281 limit will be 0 and a divide-by-zero fault will result. */
1282 if (limit == 0)
1283 limit = 1;
1284
1285 /* How many iterations of the printing loop? */
1286 count = (len + (limit - 1)) / limit;
1287
1288 /* Watch out for special case. If LEN is less than LIMIT, then
1289 just do the inner printing loop.
1290 0 < len <= limit implies count = 1. */
1291
1292 /* Sort the items if they are not already sorted. */
1293 if (rl_ignore_completion_duplicates == 0)
1294 qsort (matches + 1, len, sizeof (char *), (QSFUNC *)_rl_qsort_string_compare);
1295
1296 rl_crlf ();
1297
1298 lines = 0;
1299 if (_rl_print_completions_horizontally == 0)
1300 {
1301 /* Print the sorted items, up-and-down alphabetically, like ls. */
1302 for (i = 1; i <= count; i++)
1303 {
1304 for (j = 0, l = i; j < limit; j++)
1305 {
1306 if (l > len || matches[l] == 0)
1307 break;
1308 else
1309 {
1310 temp = printable_part (matches[l]);
1311 printed_len = print_filename (temp, matches[l]);
1312
1313 if (j + 1 < limit)
1314 for (k = 0; k < max - printed_len; k++)
1315 putc (' ', rl_outstream);
1316 }
1317 l += count;
1318 }
1319 rl_crlf ();
1320 lines++;
1321 if (_rl_page_completions && lines >= (_rl_screenheight - 1) && i < count)
1322 {
1323 lines = _rl_internal_pager (lines);
1324 if (lines < 0)
1325 return;
1326 }
1327 }
1328 }
1329 else
1330 {
1331 /* Print the sorted items, across alphabetically, like ls -x. */
1332 for (i = 1; matches[i]; i++)
1333 {
1334 temp = printable_part (matches[i]);
1335 printed_len = print_filename (temp, matches[i]);
1336 /* Have we reached the end of this line? */
1337 if (matches[i+1])
1338 {
1339 if (i && (limit > 1) && (i % limit) == 0)
1340 {
1341 rl_crlf ();
1342 lines++;
1343 if (_rl_page_completions && lines >= _rl_screenheight - 1)
1344 {
1345 lines = _rl_internal_pager (lines);
1346 if (lines < 0)
1347 return;
1348 }
1349 }
1350 else
1351 for (k = 0; k < max - printed_len; k++)
1352 putc (' ', rl_outstream);
1353 }
1354 }
1355 rl_crlf ();
1356 }
1357}
1358
1359/* Display MATCHES, a list of matching filenames in argv format. This
1360 handles the simple case -- a single match -- first. If there is more
1361 than one match, we compute the number of strings in the list and the
1362 length of the longest string, which will be needed by the display
1363 function. If the application wants to handle displaying the list of
1364 matches itself, it sets RL_COMPLETION_DISPLAY_MATCHES_HOOK to the
1365 address of a function, and we just call it. If we're handling the
1366 display ourselves, we just call rl_display_match_list. We also check
1367 that the list of matches doesn't exceed the user-settable threshold,
1368 and ask the user if he wants to see the list if there are more matches
1369 than RL_COMPLETION_QUERY_ITEMS. */
1370static void
1371display_matches (matches)
1372 char **matches;
1373{
1374 int len, max, i;
1375 char *temp;
1376
1377 /* Move to the last visible line of a possibly-multiple-line command. */
1378 _rl_move_vert (_rl_vis_botlin);
1379
1380 /* Handle simple case first. What if there is only one answer? */
1381 if (matches[1] == 0)
1382 {
1383 temp = printable_part (matches[0]);
1384 rl_crlf ();
1385 print_filename (temp, matches[0]);
1386 rl_crlf ();
1387
1388 rl_forced_update_display ();
1389 rl_display_fixed = 1;
1390
1391 return;
1392 }
1393
1394 /* There is more than one answer. Find out how many there are,
1395 and find the maximum printed length of a single entry. */
1396 for (max = 0, i = 1; matches[i]; i++)
1397 {
1398 temp = printable_part (matches[i]);
1399 len = fnwidth (temp);
1400
1401 if (len > max)
1402 max = len;
1403 }
1404
1405 len = i - 1;
1406
1407 /* If the caller has defined a display hook, then call that now. */
1408 if (rl_completion_display_matches_hook)
1409 {
1410 (*rl_completion_display_matches_hook) (matches, len, max);
1411 return;
1412 }
1413
1414 /* If there are many items, then ask the user if she really wants to
1415 see them all. */
1416 if (rl_completion_query_items > 0 && len >= rl_completion_query_items)
1417 {
1418 rl_crlf ();
1419 fprintf (rl_outstream, "Display all %d possibilities? (y or n)", len);
1420 fflush (rl_outstream);
1421 if (get_y_or_n (0) == 0)
1422 {
1423 rl_crlf ();
1424
1425 rl_forced_update_display ();
1426 rl_display_fixed = 1;
1427
1428 return;
1429 }
1430 }
1431
1432 rl_display_match_list (matches, len, max);
1433
1434 rl_forced_update_display ();
1435 rl_display_fixed = 1;
1436}
1437
1438static char *
1439make_quoted_replacement (match, mtype, qc)
1440 char *match;
1441 int mtype;
1442 char *qc; /* Pointer to quoting character, if any */
1443{
1444 int should_quote, do_replace;
1445 char *replacement;
1446
1447 /* If we are doing completion on quoted substrings, and any matches
1448 contain any of the completer_word_break_characters, then auto-
1449 matically prepend the substring with a quote character (just pick
1450 the first one from the list of such) if it does not already begin
1451 with a quote string. FIXME: Need to remove any such automatically
1452 inserted quote character when it no longer is necessary, such as
1453 if we change the string we are completing on and the new set of
1454 matches don't require a quoted substring. */
1455 replacement = match;
1456
1457 should_quote = match && rl_completer_quote_characters &&
1458 rl_filename_completion_desired &&
1459 rl_filename_quoting_desired;
1460
1461 if (should_quote)
1462 should_quote = should_quote && (!qc || !*qc ||
1463 (rl_completer_quote_characters && strchr (rl_completer_quote_characters, *qc)));
1464
1465 if (should_quote)
1466 {
1467 /* If there is a single match, see if we need to quote it.
1468 This also checks whether the common prefix of several
1469 matches needs to be quoted. */
1470 should_quote = rl_filename_quote_characters
1471 ? (_rl_strpbrk (match, rl_filename_quote_characters) != 0)
1472 : 0;
1473
1474 do_replace = should_quote ? mtype : NO_MATCH;
1475 /* Quote the replacement, since we found an embedded
1476 word break character in a potential match. */
1477 if (do_replace != NO_MATCH && rl_filename_quoting_function)
1478 replacement = (*rl_filename_quoting_function) (match, do_replace, qc);
1479 }
1480 return (replacement);
1481}
1482
1483static void
1484insert_match (match, start, mtype, qc)
1485 char *match;
1486 int start, mtype;
1487 char *qc;
1488{
1489 char *replacement;
1490 char oqc;
1491
1492 oqc = qc ? *qc : '\0';
1493 replacement = make_quoted_replacement (match, mtype, qc);
1494
1495 /* Now insert the match. */
1496 if (replacement)
1497 {
1498 /* Don't double an opening quote character. */
1499 if (qc && *qc && start && rl_line_buffer[start - 1] == *qc &&
1500 replacement[0] == *qc)
1501 start--;
1502 /* If make_quoted_replacement changed the quoting character, remove
1503 the opening quote and insert the (fully-quoted) replacement. */
1504 else if (qc && (*qc != oqc) && start && rl_line_buffer[start - 1] == oqc &&
1505 replacement[0] != oqc)
1506 start--;
1507 _rl_replace_text (replacement, start, rl_point - 1);
1508 if (replacement != match)
1509 free (replacement);
1510 }
1511}
1512
1513/* Append any necessary closing quote and a separator character to the
1514 just-inserted match. If the user has specified that directories
1515 should be marked by a trailing `/', append one of those instead. The
1516 default trailing character is a space. Returns the number of characters
1517 appended. If NONTRIVIAL_MATCH is set, we test for a symlink (if the OS
1518 has them) and don't add a suffix for a symlink to a directory. A
1519 nontrivial match is one that actually adds to the word being completed.
1520 The variable rl_completion_mark_symlink_dirs controls this behavior
1521 (it's initially set to the what the user has chosen, indicated by the
1522 value of _rl_complete_mark_symlink_dirs, but may be modified by an
1523 application's completion function). */
1524static int
1525append_to_match (text, delimiter, quote_char, nontrivial_match)
1526 char *text;
1527 int delimiter, quote_char, nontrivial_match;
1528{
1529 char temp_string[4], *filename;
1530 int temp_string_index, s;
1531 struct stat finfo;
1532
1533 temp_string_index = 0;
1534 if (quote_char && rl_point && rl_completion_suppress_quote == 0 &&
1535 rl_line_buffer[rl_point - 1] != quote_char)
1536 temp_string[temp_string_index++] = quote_char;
1537
1538 if (delimiter)
1539 temp_string[temp_string_index++] = delimiter;
1540 else if (rl_completion_suppress_append == 0 && rl_completion_append_character)
1541 temp_string[temp_string_index++] = rl_completion_append_character;
1542
1543 temp_string[temp_string_index++] = '\0';
1544
1545 if (rl_filename_completion_desired)
1546 {
1547 filename = tilde_expand (text);
1548 s = (nontrivial_match && rl_completion_mark_symlink_dirs == 0)
1549 ? LSTAT (filename, &finfo)
1550 : stat (filename, &finfo);
1551 if (s == 0 && S_ISDIR (finfo.st_mode))
1552 {
1553 if (_rl_complete_mark_directories /* && rl_completion_suppress_append == 0 */)
1554 {
1555 /* This is clumsy. Avoid putting in a double slash if point
1556 is at the end of the line and the previous character is a
1557 slash. */
1558 if (rl_point && rl_line_buffer[rl_point] == '\0' && rl_line_buffer[rl_point - 1] == '/')
1559 ;
1560 else if (rl_line_buffer[rl_point] != '/')
1561 rl_insert_text ("/");
1562 }
1563 }
1564#ifdef S_ISLNK
1565 /* Don't add anything if the filename is a symlink and resolves to a
1566 directory. */
1567 else if (s == 0 && S_ISLNK (finfo.st_mode) &&
1568 stat (filename, &finfo) == 0 && S_ISDIR (finfo.st_mode))
1569 ;
1570#endif
1571 else
1572 {
1573 if (rl_point == rl_end && temp_string_index)
1574 rl_insert_text (temp_string);
1575 }
1576 free (filename);
1577 }
1578 else
1579 {
1580 if (rl_point == rl_end && temp_string_index)
1581 rl_insert_text (temp_string);
1582 }
1583
1584 return (temp_string_index);
1585}
1586
1587static void
1588insert_all_matches (matches, point, qc)
1589 char **matches;
1590 int point;
1591 char *qc;
1592{
1593 int i;
1594 char *rp;
1595
1596 rl_begin_undo_group ();
1597 /* remove any opening quote character; make_quoted_replacement will add
1598 it back. */
1599 if (qc && *qc && point && rl_line_buffer[point - 1] == *qc)
1600 point--;
1601 rl_delete_text (point, rl_point);
1602 rl_point = point;
1603
1604 if (matches[1])
1605 {
1606 for (i = 1; matches[i]; i++)
1607 {
1608 rp = make_quoted_replacement (matches[i], SINGLE_MATCH, qc);
1609 rl_insert_text (rp);
1610 rl_insert_text (" ");
1611 if (rp != matches[i])
1612 free (rp);
1613 }
1614 }
1615 else
1616 {
1617 rp = make_quoted_replacement (matches[0], SINGLE_MATCH, qc);
1618 rl_insert_text (rp);
1619 rl_insert_text (" ");
1620 if (rp != matches[0])
1621 free (rp);
1622 }
1623 rl_end_undo_group ();
1624}
1625
1626void
1627_rl_free_match_list (matches)
1628 char **matches;
1629{
1630 register int i;
1631
1632 if (matches == 0)
1633 return;
1634
1635 for (i = 0; matches[i]; i++)
1636 free (matches[i]);
1637 free (matches);
1638}
1639
1640/* Complete the word at or before point.
1641 WHAT_TO_DO says what to do with the completion.
1642 `?' means list the possible completions.
1643 TAB means do standard completion.
1644 `*' means insert all of the possible completions.
1645 `!' means to do standard completion, and list all possible completions if
1646 there is more than one.
1647 `@' means to do standard completion, and list all possible completions if
1648 there is more than one and partial completion is not possible. */
1649int
1650rl_complete_internal (what_to_do)
1651 int what_to_do;
1652{
1653 char **matches;
1654 rl_compentry_func_t *our_func;
1655 int start, end, delimiter, found_quote, i, nontrivial_lcd;
1656 char *text, *saved_line_buffer;
1657 char quote_char;
1658
1659 RL_SETSTATE(RL_STATE_COMPLETING);
1660
1661 set_completion_defaults (what_to_do);
1662
1663 saved_line_buffer = rl_line_buffer ? savestring (rl_line_buffer) : (char *)NULL;
1664 our_func = rl_completion_entry_function
1665 ? rl_completion_entry_function
1666 : rl_filename_completion_function;
1667 /* We now look backwards for the start of a filename/variable word. */
1668 end = rl_point;
1669 found_quote = delimiter = 0;
1670 quote_char = '\0';
1671
1672 if (rl_point)
1673 /* This (possibly) changes rl_point. If it returns a non-zero char,
1674 we know we have an open quote. */
1675 quote_char = _rl_find_completion_word (&found_quote, &delimiter);
1676
1677 start = rl_point;
1678 rl_point = end;
1679
1680 text = rl_copy_text (start, end);
1681 matches = gen_completion_matches (text, start, end, our_func, found_quote, quote_char);
1682 /* nontrivial_lcd is set if the common prefix adds something to the word
1683 being completed. */
1684 nontrivial_lcd = matches && strcmp (text, matches[0]) != 0;
1685 free (text);
1686
1687 if (matches == 0)
1688 {
1689 rl_ding ();
1690 FREE (saved_line_buffer);
1691 completion_changed_buffer = 0;
1692 RL_UNSETSTATE(RL_STATE_COMPLETING);
1693 return (0);
1694 }
1695
1696 /* If we are matching filenames, the attempted completion function will
1697 have set rl_filename_completion_desired to a non-zero value. The basic
1698 rl_filename_completion_function does this. */
1699 i = rl_filename_completion_desired;
1700
1701 if (postprocess_matches (&matches, i) == 0)
1702 {
1703 rl_ding ();
1704 FREE (saved_line_buffer);
1705 completion_changed_buffer = 0;
1706 RL_UNSETSTATE(RL_STATE_COMPLETING);
1707 return (0);
1708 }
1709
1710 switch (what_to_do)
1711 {
1712 case TAB:
1713 case '!':
1714 case '@':
1715 /* Insert the first match with proper quoting. */
1716 if (*matches[0])
1717 insert_match (matches[0], start, matches[1] ? MULT_MATCH : SINGLE_MATCH, &quote_char);
1718
1719 /* If there are more matches, ring the bell to indicate.
1720 If we are in vi mode, Posix.2 says to not ring the bell.
1721 If the `show-all-if-ambiguous' variable is set, display
1722 all the matches immediately. Otherwise, if this was the
1723 only match, and we are hacking files, check the file to
1724 see if it was a directory. If so, and the `mark-directories'
1725 variable is set, add a '/' to the name. If not, and we
1726 are at the end of the line, then add a space. */
1727 if (matches[1])
1728 {
1729 if (what_to_do == '!')
1730 {
1731 display_matches (matches);
1732 break;
1733 }
1734 else if (what_to_do == '@')
1735 {
1736 if (nontrivial_lcd == 0)
1737 display_matches (matches);
1738 break;
1739 }
1740 else if (rl_editing_mode != vi_mode)
1741 rl_ding (); /* There are other matches remaining. */
1742 }
1743 else
1744 append_to_match (matches[0], delimiter, quote_char, nontrivial_lcd);
1745
1746 break;
1747
1748 case '*':
1749 insert_all_matches (matches, start, &quote_char);
1750 break;
1751
1752 case '?':
1753 display_matches (matches);
1754 break;
1755
1756 default:
1757 fprintf (stderr, "\r\nreadline: bad value %d for what_to_do in rl_complete\n", what_to_do);
1758 rl_ding ();
1759 FREE (saved_line_buffer);
1760 RL_UNSETSTATE(RL_STATE_COMPLETING);
1761 return 1;
1762 }
1763
1764 _rl_free_match_list (matches);
1765
1766 /* Check to see if the line has changed through all of this manipulation. */
1767 if (saved_line_buffer)
1768 {
1769 completion_changed_buffer = strcmp (rl_line_buffer, saved_line_buffer) != 0;
1770 free (saved_line_buffer);
1771 }
1772
1773 RL_UNSETSTATE(RL_STATE_COMPLETING);
1774 return 0;
1775}
1776
1777/***************************************************************/
1778/* */
1779/* Application-callable completion match generator functions */
1780/* */
1781/***************************************************************/
1782
1783/* Return an array of (char *) which is a list of completions for TEXT.
1784 If there are no completions, return a NULL pointer.
1785 The first entry in the returned array is the substitution for TEXT.
1786 The remaining entries are the possible completions.
1787 The array is terminated with a NULL pointer.
1788
1789 ENTRY_FUNCTION is a function of two args, and returns a (char *).
1790 The first argument is TEXT.
1791 The second is a state argument; it should be zero on the first call, and
1792 non-zero on subsequent calls. It returns a NULL pointer to the caller
1793 when there are no more matches.
1794 */
1795char **
1796rl_completion_matches (text, entry_function)
1797 const char *text;
1798 rl_compentry_func_t *entry_function;
1799{
1800 /* Number of slots in match_list. */
1801 int match_list_size;
1802
1803 /* The list of matches. */
1804 char **match_list;
1805
1806 /* Number of matches actually found. */
1807 int matches;
1808
1809 /* Temporary string binder. */
1810 char *string;
1811
1812 matches = 0;
1813 match_list_size = 10;
1814 match_list = (char **)xmalloc ((match_list_size + 1) * sizeof (char *));
1815 match_list[1] = (char *)NULL;
1816
1817 while (string = (*entry_function) (text, matches))
1818 {
1819 if (matches + 1 == match_list_size)
1820 match_list = (char **)xrealloc
1821 (match_list, ((match_list_size += 10) + 1) * sizeof (char *));
1822
1823 match_list[++matches] = string;
1824 match_list[matches + 1] = (char *)NULL;
1825 }
1826
1827 /* If there were any matches, then look through them finding out the
1828 lowest common denominator. That then becomes match_list[0]. */
1829 if (matches)
1830 compute_lcd_of_matches (match_list, matches, text);
1831 else /* There were no matches. */
1832 {
1833 free (match_list);
1834 match_list = (char **)NULL;
1835 }
1836 return (match_list);
1837}
1838
1839/* A completion function for usernames.
1840 TEXT contains a partial username preceded by a random
1841 character (usually `~'). */
1842char *
1843rl_username_completion_function (text, state)
1844 const char *text;
1845 int state;
1846{
1847#if defined (__WIN32__) || defined (__OPENNT)
1848 return (char *)NULL;
1849#else /* !__WIN32__ && !__OPENNT) */
1850 static char *username = (char *)NULL;
1851 static struct passwd *entry;
1852 static int namelen, first_char, first_char_loc;
1853 char *value;
1854
1855 if (state == 0)
1856 {
1857 FREE (username);
1858
1859 first_char = *text;
1860 first_char_loc = first_char == '~';
1861
1862 username = savestring (&text[first_char_loc]);
1863 namelen = strlen (username);
1864 setpwent ();
1865 }
1866
1867#if defined (HAVE_GETPWENT)
1868 while (entry = getpwent ())
1869 {
1870 /* Null usernames should result in all users as possible completions. */
1871 if (namelen == 0 || (STREQN (username, entry->pw_name, namelen)))
1872 break;
1873 }
1874#endif
1875
1876 if (entry == 0)
1877 {
1878#if defined (HAVE_GETPWENT)
1879 endpwent ();
1880#endif
1881 return ((char *)NULL);
1882 }
1883 else
1884 {
1885 value = (char *)xmalloc (2 + strlen (entry->pw_name));
1886
1887 *value = *text;
1888
1889 strcpy (value + first_char_loc, entry->pw_name);
1890
1891 if (first_char == '~')
1892 rl_filename_completion_desired = 1;
1893
1894 return (value);
1895 }
1896#endif /* !__WIN32__ && !__OPENNT */
1897}
1898
1899/* Okay, now we write the entry_function for filename completion. In the
1900 general case. Note that completion in the shell is a little different
1901 because of all the pathnames that must be followed when looking up the
1902 completion for a command. */
1903char *
1904rl_filename_completion_function (text, state)
1905 const char *text;
1906 int state;
1907{
1908 static DIR *directory = (DIR *)NULL;
1909 static char *filename = (char *)NULL;
1910 static char *dirname = (char *)NULL;
1911 static char *users_dirname = (char *)NULL;
1912 static int filename_len;
1913 char *temp;
1914 int dirlen;
1915 struct dirent *entry;
1916
1917 /* If we don't have any state, then do some initialization. */
1918 if (state == 0)
1919 {
1920 /* If we were interrupted before closing the directory or reading
1921 all of its contents, close it. */
1922 if (directory)
1923 {
1924 closedir (directory);
1925 directory = (DIR *)NULL;
1926 }
1927 FREE (dirname);
1928 FREE (filename);
1929 FREE (users_dirname);
1930
1931 filename = savestring (text);
1932 if (*text == 0)
1933 text = ".";
1934 dirname = savestring (text);
1935
1936 temp = strrchr (dirname, '/');
1937
1938#if defined (__MSDOS__)
1939 /* special hack for //X/... */
1940 if (dirname[0] == '/' && dirname[1] == '/' && ISALPHA ((unsigned char)dirname[2]) && dirname[3] == '/')
1941 temp = strrchr (dirname + 3, '/');
1942#endif
1943
1944 if (temp)
1945 {
1946 strcpy (filename, ++temp);
1947 *temp = '\0';
1948 }
1949#if defined (__MSDOS__)
1950 /* searches from current directory on the drive */
1951 else if (ISALPHA ((unsigned char)dirname[0]) && dirname[1] == ':')
1952 {
1953 strcpy (filename, dirname + 2);
1954 dirname[2] = '\0';
1955 }
1956#endif
1957 else
1958 {
1959 dirname[0] = '.';
1960 dirname[1] = '\0';
1961 }
1962
1963 /* We aren't done yet. We also support the "~user" syntax. */
1964
1965 /* Save the version of the directory that the user typed. */
1966 users_dirname = savestring (dirname);
1967
1968 if (*dirname == '~')
1969 {
1970 temp = tilde_expand (dirname);
1971 free (dirname);
1972 dirname = temp;
1973 }
1974
1975 if (rl_directory_rewrite_hook)
1976 (*rl_directory_rewrite_hook) (&dirname);
1977
1110 if (!_rl_compare_chars (match_list[i], si, &ps1, match_list[i+1], si, &ps2))
1111 break;
1112 else if ((v = _rl_get_char_len (&match_list[i][si], &ps_back)) > 1)
1113 si += v - 1;
1114 }
1115 else
1116#endif
1117 if (c1 != c2)
1118 break;
1119 }
1120
1121 if (low > si)
1122 low = si;
1123 }
1124
1125 /* If there were multiple matches, but none matched up to even the
1126 first character, and the user typed something, use that as the
1127 value of matches[0]. */
1128 if (low == 0 && text && *text)
1129 {
1130 match_list[0] = (char *)xmalloc (strlen (text) + 1);
1131 strcpy (match_list[0], text);
1132 }
1133 else
1134 {
1135 match_list[0] = (char *)xmalloc (low + 1);
1136
1137 /* XXX - this might need changes in the presence of multibyte chars */
1138
1139 /* If we are ignoring case, try to preserve the case of the string
1140 the user typed in the face of multiple matches differing in case. */
1141 if (_rl_completion_case_fold)
1142 {
1143 /* We're making an assumption here:
1144 IF we're completing filenames AND
1145 the application has defined a filename dequoting function AND
1146 we found a quote character AND
1147 the application has requested filename quoting
1148 THEN
1149 we assume that TEXT was dequoted before checking against
1150 the file system and needs to be dequoted here before we
1151 check against the list of matches
1152 FI */
1153 dtext = (char *)NULL;
1154 if (rl_filename_completion_desired &&
1155 rl_filename_dequoting_function &&
1156 rl_completion_found_quote &&
1157 rl_filename_quoting_desired)
1158 {
1159 dtext = (*rl_filename_dequoting_function) ((char *)text, rl_completion_quote_character);
1160 text = dtext;
1161 }
1162
1163 /* sort the list to get consistent answers. */
1164 qsort (match_list+1, matches, sizeof(char *), (QSFUNC *)_rl_qsort_string_compare);
1165
1166 si = strlen (text);
1167 if (si <= low)
1168 {
1169 for (i = 1; i <= matches; i++)
1170 if (strncmp (match_list[i], text, si) == 0)
1171 {
1172 strncpy (match_list[0], match_list[i], low);
1173 break;
1174 }
1175 /* no casematch, use first entry */
1176 if (i > matches)
1177 strncpy (match_list[0], match_list[1], low);
1178 }
1179 else
1180 /* otherwise, just use the text the user typed. */
1181 strncpy (match_list[0], text, low);
1182
1183 FREE (dtext);
1184 }
1185 else
1186 strncpy (match_list[0], match_list[1], low);
1187
1188 match_list[0][low] = '\0';
1189 }
1190
1191 return matches;
1192}
1193
1194static int
1195postprocess_matches (matchesp, matching_filenames)
1196 char ***matchesp;
1197 int matching_filenames;
1198{
1199 char *t, **matches, **temp_matches;
1200 int nmatch, i;
1201
1202 matches = *matchesp;
1203
1204 if (matches == 0)
1205 return 0;
1206
1207 /* It seems to me that in all the cases we handle we would like
1208 to ignore duplicate possiblilities. Scan for the text to
1209 insert being identical to the other completions. */
1210 if (rl_ignore_completion_duplicates)
1211 {
1212 temp_matches = remove_duplicate_matches (matches);
1213 free (matches);
1214 matches = temp_matches;
1215 }
1216
1217 /* If we are matching filenames, then here is our chance to
1218 do clever processing by re-examining the list. Call the
1219 ignore function with the array as a parameter. It can
1220 munge the array, deleting matches as it desires. */
1221 if (rl_ignore_some_completions_function && matching_filenames)
1222 {
1223 for (nmatch = 1; matches[nmatch]; nmatch++)
1224 ;
1225 (void)(*rl_ignore_some_completions_function) (matches);
1226 if (matches == 0 || matches[0] == 0)
1227 {
1228 FREE (matches);
1229 *matchesp = (char **)0;
1230 return 0;
1231 }
1232 else
1233 {
1234 /* If we removed some matches, recompute the common prefix. */
1235 for (i = 1; matches[i]; i++)
1236 ;
1237 if (i > 1 && i < nmatch)
1238 {
1239 t = matches[0];
1240 compute_lcd_of_matches (matches, i - 1, t);
1241 FREE (t);
1242 }
1243 }
1244 }
1245
1246 *matchesp = matches;
1247 return (1);
1248}
1249
1250/* A convenience function for displaying a list of strings in
1251 columnar format on readline's output stream. MATCHES is the list
1252 of strings, in argv format, LEN is the number of strings in MATCHES,
1253 and MAX is the length of the longest string in MATCHES. */
1254void
1255rl_display_match_list (matches, len, max)
1256 char **matches;
1257 int len, max;
1258{
1259 int count, limit, printed_len, lines;
1260 int i, j, k, l;
1261 char *temp;
1262
1263 /* How many items of MAX length can we fit in the screen window? */
1264 max += 2;
1265 limit = _rl_screenwidth / max;
1266 if (limit != 1 && (limit * max == _rl_screenwidth))
1267 limit--;
1268
1269 /* Avoid a possible floating exception. If max > _rl_screenwidth,
1270 limit will be 0 and a divide-by-zero fault will result. */
1271 if (limit == 0)
1272 limit = 1;
1273
1274 /* How many iterations of the printing loop? */
1275 count = (len + (limit - 1)) / limit;
1276
1277 /* Watch out for special case. If LEN is less than LIMIT, then
1278 just do the inner printing loop.
1279 0 < len <= limit implies count = 1. */
1280
1281 /* Sort the items if they are not already sorted. */
1282 if (rl_ignore_completion_duplicates == 0)
1283 qsort (matches + 1, len, sizeof (char *), (QSFUNC *)_rl_qsort_string_compare);
1284
1285 rl_crlf ();
1286
1287 lines = 0;
1288 if (_rl_print_completions_horizontally == 0)
1289 {
1290 /* Print the sorted items, up-and-down alphabetically, like ls. */
1291 for (i = 1; i <= count; i++)
1292 {
1293 for (j = 0, l = i; j < limit; j++)
1294 {
1295 if (l > len || matches[l] == 0)
1296 break;
1297 else
1298 {
1299 temp = printable_part (matches[l]);
1300 printed_len = print_filename (temp, matches[l]);
1301
1302 if (j + 1 < limit)
1303 for (k = 0; k < max - printed_len; k++)
1304 putc (' ', rl_outstream);
1305 }
1306 l += count;
1307 }
1308 rl_crlf ();
1309 lines++;
1310 if (_rl_page_completions && lines >= (_rl_screenheight - 1) && i < count)
1311 {
1312 lines = _rl_internal_pager (lines);
1313 if (lines < 0)
1314 return;
1315 }
1316 }
1317 }
1318 else
1319 {
1320 /* Print the sorted items, across alphabetically, like ls -x. */
1321 for (i = 1; matches[i]; i++)
1322 {
1323 temp = printable_part (matches[i]);
1324 printed_len = print_filename (temp, matches[i]);
1325 /* Have we reached the end of this line? */
1326 if (matches[i+1])
1327 {
1328 if (i && (limit > 1) && (i % limit) == 0)
1329 {
1330 rl_crlf ();
1331 lines++;
1332 if (_rl_page_completions && lines >= _rl_screenheight - 1)
1333 {
1334 lines = _rl_internal_pager (lines);
1335 if (lines < 0)
1336 return;
1337 }
1338 }
1339 else
1340 for (k = 0; k < max - printed_len; k++)
1341 putc (' ', rl_outstream);
1342 }
1343 }
1344 rl_crlf ();
1345 }
1346}
1347
1348/* Display MATCHES, a list of matching filenames in argv format. This
1349 handles the simple case -- a single match -- first. If there is more
1350 than one match, we compute the number of strings in the list and the
1351 length of the longest string, which will be needed by the display
1352 function. If the application wants to handle displaying the list of
1353 matches itself, it sets RL_COMPLETION_DISPLAY_MATCHES_HOOK to the
1354 address of a function, and we just call it. If we're handling the
1355 display ourselves, we just call rl_display_match_list. We also check
1356 that the list of matches doesn't exceed the user-settable threshold,
1357 and ask the user if he wants to see the list if there are more matches
1358 than RL_COMPLETION_QUERY_ITEMS. */
1359static void
1360display_matches (matches)
1361 char **matches;
1362{
1363 int len, max, i;
1364 char *temp;
1365
1366 /* Move to the last visible line of a possibly-multiple-line command. */
1367 _rl_move_vert (_rl_vis_botlin);
1368
1369 /* Handle simple case first. What if there is only one answer? */
1370 if (matches[1] == 0)
1371 {
1372 temp = printable_part (matches[0]);
1373 rl_crlf ();
1374 print_filename (temp, matches[0]);
1375 rl_crlf ();
1376
1377 rl_forced_update_display ();
1378 rl_display_fixed = 1;
1379
1380 return;
1381 }
1382
1383 /* There is more than one answer. Find out how many there are,
1384 and find the maximum printed length of a single entry. */
1385 for (max = 0, i = 1; matches[i]; i++)
1386 {
1387 temp = printable_part (matches[i]);
1388 len = fnwidth (temp);
1389
1390 if (len > max)
1391 max = len;
1392 }
1393
1394 len = i - 1;
1395
1396 /* If the caller has defined a display hook, then call that now. */
1397 if (rl_completion_display_matches_hook)
1398 {
1399 (*rl_completion_display_matches_hook) (matches, len, max);
1400 return;
1401 }
1402
1403 /* If there are many items, then ask the user if she really wants to
1404 see them all. */
1405 if (rl_completion_query_items > 0 && len >= rl_completion_query_items)
1406 {
1407 rl_crlf ();
1408 fprintf (rl_outstream, "Display all %d possibilities? (y or n)", len);
1409 fflush (rl_outstream);
1410 if (get_y_or_n (0) == 0)
1411 {
1412 rl_crlf ();
1413
1414 rl_forced_update_display ();
1415 rl_display_fixed = 1;
1416
1417 return;
1418 }
1419 }
1420
1421 rl_display_match_list (matches, len, max);
1422
1423 rl_forced_update_display ();
1424 rl_display_fixed = 1;
1425}
1426
1427static char *
1428make_quoted_replacement (match, mtype, qc)
1429 char *match;
1430 int mtype;
1431 char *qc; /* Pointer to quoting character, if any */
1432{
1433 int should_quote, do_replace;
1434 char *replacement;
1435
1436 /* If we are doing completion on quoted substrings, and any matches
1437 contain any of the completer_word_break_characters, then auto-
1438 matically prepend the substring with a quote character (just pick
1439 the first one from the list of such) if it does not already begin
1440 with a quote string. FIXME: Need to remove any such automatically
1441 inserted quote character when it no longer is necessary, such as
1442 if we change the string we are completing on and the new set of
1443 matches don't require a quoted substring. */
1444 replacement = match;
1445
1446 should_quote = match && rl_completer_quote_characters &&
1447 rl_filename_completion_desired &&
1448 rl_filename_quoting_desired;
1449
1450 if (should_quote)
1451 should_quote = should_quote && (!qc || !*qc ||
1452 (rl_completer_quote_characters && strchr (rl_completer_quote_characters, *qc)));
1453
1454 if (should_quote)
1455 {
1456 /* If there is a single match, see if we need to quote it.
1457 This also checks whether the common prefix of several
1458 matches needs to be quoted. */
1459 should_quote = rl_filename_quote_characters
1460 ? (_rl_strpbrk (match, rl_filename_quote_characters) != 0)
1461 : 0;
1462
1463 do_replace = should_quote ? mtype : NO_MATCH;
1464 /* Quote the replacement, since we found an embedded
1465 word break character in a potential match. */
1466 if (do_replace != NO_MATCH && rl_filename_quoting_function)
1467 replacement = (*rl_filename_quoting_function) (match, do_replace, qc);
1468 }
1469 return (replacement);
1470}
1471
1472static void
1473insert_match (match, start, mtype, qc)
1474 char *match;
1475 int start, mtype;
1476 char *qc;
1477{
1478 char *replacement;
1479 char oqc;
1480
1481 oqc = qc ? *qc : '\0';
1482 replacement = make_quoted_replacement (match, mtype, qc);
1483
1484 /* Now insert the match. */
1485 if (replacement)
1486 {
1487 /* Don't double an opening quote character. */
1488 if (qc && *qc && start && rl_line_buffer[start - 1] == *qc &&
1489 replacement[0] == *qc)
1490 start--;
1491 /* If make_quoted_replacement changed the quoting character, remove
1492 the opening quote and insert the (fully-quoted) replacement. */
1493 else if (qc && (*qc != oqc) && start && rl_line_buffer[start - 1] == oqc &&
1494 replacement[0] != oqc)
1495 start--;
1496 _rl_replace_text (replacement, start, rl_point - 1);
1497 if (replacement != match)
1498 free (replacement);
1499 }
1500}
1501
1502/* Append any necessary closing quote and a separator character to the
1503 just-inserted match. If the user has specified that directories
1504 should be marked by a trailing `/', append one of those instead. The
1505 default trailing character is a space. Returns the number of characters
1506 appended. If NONTRIVIAL_MATCH is set, we test for a symlink (if the OS
1507 has them) and don't add a suffix for a symlink to a directory. A
1508 nontrivial match is one that actually adds to the word being completed.
1509 The variable rl_completion_mark_symlink_dirs controls this behavior
1510 (it's initially set to the what the user has chosen, indicated by the
1511 value of _rl_complete_mark_symlink_dirs, but may be modified by an
1512 application's completion function). */
1513static int
1514append_to_match (text, delimiter, quote_char, nontrivial_match)
1515 char *text;
1516 int delimiter, quote_char, nontrivial_match;
1517{
1518 char temp_string[4], *filename;
1519 int temp_string_index, s;
1520 struct stat finfo;
1521
1522 temp_string_index = 0;
1523 if (quote_char && rl_point && rl_completion_suppress_quote == 0 &&
1524 rl_line_buffer[rl_point - 1] != quote_char)
1525 temp_string[temp_string_index++] = quote_char;
1526
1527 if (delimiter)
1528 temp_string[temp_string_index++] = delimiter;
1529 else if (rl_completion_suppress_append == 0 && rl_completion_append_character)
1530 temp_string[temp_string_index++] = rl_completion_append_character;
1531
1532 temp_string[temp_string_index++] = '\0';
1533
1534 if (rl_filename_completion_desired)
1535 {
1536 filename = tilde_expand (text);
1537 s = (nontrivial_match && rl_completion_mark_symlink_dirs == 0)
1538 ? LSTAT (filename, &finfo)
1539 : stat (filename, &finfo);
1540 if (s == 0 && S_ISDIR (finfo.st_mode))
1541 {
1542 if (_rl_complete_mark_directories /* && rl_completion_suppress_append == 0 */)
1543 {
1544 /* This is clumsy. Avoid putting in a double slash if point
1545 is at the end of the line and the previous character is a
1546 slash. */
1547 if (rl_point && rl_line_buffer[rl_point] == '\0' && rl_line_buffer[rl_point - 1] == '/')
1548 ;
1549 else if (rl_line_buffer[rl_point] != '/')
1550 rl_insert_text ("/");
1551 }
1552 }
1553#ifdef S_ISLNK
1554 /* Don't add anything if the filename is a symlink and resolves to a
1555 directory. */
1556 else if (s == 0 && S_ISLNK (finfo.st_mode) &&
1557 stat (filename, &finfo) == 0 && S_ISDIR (finfo.st_mode))
1558 ;
1559#endif
1560 else
1561 {
1562 if (rl_point == rl_end && temp_string_index)
1563 rl_insert_text (temp_string);
1564 }
1565 free (filename);
1566 }
1567 else
1568 {
1569 if (rl_point == rl_end && temp_string_index)
1570 rl_insert_text (temp_string);
1571 }
1572
1573 return (temp_string_index);
1574}
1575
1576static void
1577insert_all_matches (matches, point, qc)
1578 char **matches;
1579 int point;
1580 char *qc;
1581{
1582 int i;
1583 char *rp;
1584
1585 rl_begin_undo_group ();
1586 /* remove any opening quote character; make_quoted_replacement will add
1587 it back. */
1588 if (qc && *qc && point && rl_line_buffer[point - 1] == *qc)
1589 point--;
1590 rl_delete_text (point, rl_point);
1591 rl_point = point;
1592
1593 if (matches[1])
1594 {
1595 for (i = 1; matches[i]; i++)
1596 {
1597 rp = make_quoted_replacement (matches[i], SINGLE_MATCH, qc);
1598 rl_insert_text (rp);
1599 rl_insert_text (" ");
1600 if (rp != matches[i])
1601 free (rp);
1602 }
1603 }
1604 else
1605 {
1606 rp = make_quoted_replacement (matches[0], SINGLE_MATCH, qc);
1607 rl_insert_text (rp);
1608 rl_insert_text (" ");
1609 if (rp != matches[0])
1610 free (rp);
1611 }
1612 rl_end_undo_group ();
1613}
1614
1615void
1616_rl_free_match_list (matches)
1617 char **matches;
1618{
1619 register int i;
1620
1621 if (matches == 0)
1622 return;
1623
1624 for (i = 0; matches[i]; i++)
1625 free (matches[i]);
1626 free (matches);
1627}
1628
1629/* Complete the word at or before point.
1630 WHAT_TO_DO says what to do with the completion.
1631 `?' means list the possible completions.
1632 TAB means do standard completion.
1633 `*' means insert all of the possible completions.
1634 `!' means to do standard completion, and list all possible completions if
1635 there is more than one.
1636 `@' means to do standard completion, and list all possible completions if
1637 there is more than one and partial completion is not possible. */
1638int
1639rl_complete_internal (what_to_do)
1640 int what_to_do;
1641{
1642 char **matches;
1643 rl_compentry_func_t *our_func;
1644 int start, end, delimiter, found_quote, i, nontrivial_lcd;
1645 char *text, *saved_line_buffer;
1646 char quote_char;
1647
1648 RL_SETSTATE(RL_STATE_COMPLETING);
1649
1650 set_completion_defaults (what_to_do);
1651
1652 saved_line_buffer = rl_line_buffer ? savestring (rl_line_buffer) : (char *)NULL;
1653 our_func = rl_completion_entry_function
1654 ? rl_completion_entry_function
1655 : rl_filename_completion_function;
1656 /* We now look backwards for the start of a filename/variable word. */
1657 end = rl_point;
1658 found_quote = delimiter = 0;
1659 quote_char = '\0';
1660
1661 if (rl_point)
1662 /* This (possibly) changes rl_point. If it returns a non-zero char,
1663 we know we have an open quote. */
1664 quote_char = _rl_find_completion_word (&found_quote, &delimiter);
1665
1666 start = rl_point;
1667 rl_point = end;
1668
1669 text = rl_copy_text (start, end);
1670 matches = gen_completion_matches (text, start, end, our_func, found_quote, quote_char);
1671 /* nontrivial_lcd is set if the common prefix adds something to the word
1672 being completed. */
1673 nontrivial_lcd = matches && strcmp (text, matches[0]) != 0;
1674 free (text);
1675
1676 if (matches == 0)
1677 {
1678 rl_ding ();
1679 FREE (saved_line_buffer);
1680 completion_changed_buffer = 0;
1681 RL_UNSETSTATE(RL_STATE_COMPLETING);
1682 return (0);
1683 }
1684
1685 /* If we are matching filenames, the attempted completion function will
1686 have set rl_filename_completion_desired to a non-zero value. The basic
1687 rl_filename_completion_function does this. */
1688 i = rl_filename_completion_desired;
1689
1690 if (postprocess_matches (&matches, i) == 0)
1691 {
1692 rl_ding ();
1693 FREE (saved_line_buffer);
1694 completion_changed_buffer = 0;
1695 RL_UNSETSTATE(RL_STATE_COMPLETING);
1696 return (0);
1697 }
1698
1699 switch (what_to_do)
1700 {
1701 case TAB:
1702 case '!':
1703 case '@':
1704 /* Insert the first match with proper quoting. */
1705 if (*matches[0])
1706 insert_match (matches[0], start, matches[1] ? MULT_MATCH : SINGLE_MATCH, &quote_char);
1707
1708 /* If there are more matches, ring the bell to indicate.
1709 If we are in vi mode, Posix.2 says to not ring the bell.
1710 If the `show-all-if-ambiguous' variable is set, display
1711 all the matches immediately. Otherwise, if this was the
1712 only match, and we are hacking files, check the file to
1713 see if it was a directory. If so, and the `mark-directories'
1714 variable is set, add a '/' to the name. If not, and we
1715 are at the end of the line, then add a space. */
1716 if (matches[1])
1717 {
1718 if (what_to_do == '!')
1719 {
1720 display_matches (matches);
1721 break;
1722 }
1723 else if (what_to_do == '@')
1724 {
1725 if (nontrivial_lcd == 0)
1726 display_matches (matches);
1727 break;
1728 }
1729 else if (rl_editing_mode != vi_mode)
1730 rl_ding (); /* There are other matches remaining. */
1731 }
1732 else
1733 append_to_match (matches[0], delimiter, quote_char, nontrivial_lcd);
1734
1735 break;
1736
1737 case '*':
1738 insert_all_matches (matches, start, &quote_char);
1739 break;
1740
1741 case '?':
1742 display_matches (matches);
1743 break;
1744
1745 default:
1746 fprintf (stderr, "\r\nreadline: bad value %d for what_to_do in rl_complete\n", what_to_do);
1747 rl_ding ();
1748 FREE (saved_line_buffer);
1749 RL_UNSETSTATE(RL_STATE_COMPLETING);
1750 return 1;
1751 }
1752
1753 _rl_free_match_list (matches);
1754
1755 /* Check to see if the line has changed through all of this manipulation. */
1756 if (saved_line_buffer)
1757 {
1758 completion_changed_buffer = strcmp (rl_line_buffer, saved_line_buffer) != 0;
1759 free (saved_line_buffer);
1760 }
1761
1762 RL_UNSETSTATE(RL_STATE_COMPLETING);
1763 return 0;
1764}
1765
1766/***************************************************************/
1767/* */
1768/* Application-callable completion match generator functions */
1769/* */
1770/***************************************************************/
1771
1772/* Return an array of (char *) which is a list of completions for TEXT.
1773 If there are no completions, return a NULL pointer.
1774 The first entry in the returned array is the substitution for TEXT.
1775 The remaining entries are the possible completions.
1776 The array is terminated with a NULL pointer.
1777
1778 ENTRY_FUNCTION is a function of two args, and returns a (char *).
1779 The first argument is TEXT.
1780 The second is a state argument; it should be zero on the first call, and
1781 non-zero on subsequent calls. It returns a NULL pointer to the caller
1782 when there are no more matches.
1783 */
1784char **
1785rl_completion_matches (text, entry_function)
1786 const char *text;
1787 rl_compentry_func_t *entry_function;
1788{
1789 /* Number of slots in match_list. */
1790 int match_list_size;
1791
1792 /* The list of matches. */
1793 char **match_list;
1794
1795 /* Number of matches actually found. */
1796 int matches;
1797
1798 /* Temporary string binder. */
1799 char *string;
1800
1801 matches = 0;
1802 match_list_size = 10;
1803 match_list = (char **)xmalloc ((match_list_size + 1) * sizeof (char *));
1804 match_list[1] = (char *)NULL;
1805
1806 while (string = (*entry_function) (text, matches))
1807 {
1808 if (matches + 1 == match_list_size)
1809 match_list = (char **)xrealloc
1810 (match_list, ((match_list_size += 10) + 1) * sizeof (char *));
1811
1812 match_list[++matches] = string;
1813 match_list[matches + 1] = (char *)NULL;
1814 }
1815
1816 /* If there were any matches, then look through them finding out the
1817 lowest common denominator. That then becomes match_list[0]. */
1818 if (matches)
1819 compute_lcd_of_matches (match_list, matches, text);
1820 else /* There were no matches. */
1821 {
1822 free (match_list);
1823 match_list = (char **)NULL;
1824 }
1825 return (match_list);
1826}
1827
1828/* A completion function for usernames.
1829 TEXT contains a partial username preceded by a random
1830 character (usually `~'). */
1831char *
1832rl_username_completion_function (text, state)
1833 const char *text;
1834 int state;
1835{
1836#if defined (__WIN32__) || defined (__OPENNT)
1837 return (char *)NULL;
1838#else /* !__WIN32__ && !__OPENNT) */
1839 static char *username = (char *)NULL;
1840 static struct passwd *entry;
1841 static int namelen, first_char, first_char_loc;
1842 char *value;
1843
1844 if (state == 0)
1845 {
1846 FREE (username);
1847
1848 first_char = *text;
1849 first_char_loc = first_char == '~';
1850
1851 username = savestring (&text[first_char_loc]);
1852 namelen = strlen (username);
1853 setpwent ();
1854 }
1855
1856#if defined (HAVE_GETPWENT)
1857 while (entry = getpwent ())
1858 {
1859 /* Null usernames should result in all users as possible completions. */
1860 if (namelen == 0 || (STREQN (username, entry->pw_name, namelen)))
1861 break;
1862 }
1863#endif
1864
1865 if (entry == 0)
1866 {
1867#if defined (HAVE_GETPWENT)
1868 endpwent ();
1869#endif
1870 return ((char *)NULL);
1871 }
1872 else
1873 {
1874 value = (char *)xmalloc (2 + strlen (entry->pw_name));
1875
1876 *value = *text;
1877
1878 strcpy (value + first_char_loc, entry->pw_name);
1879
1880 if (first_char == '~')
1881 rl_filename_completion_desired = 1;
1882
1883 return (value);
1884 }
1885#endif /* !__WIN32__ && !__OPENNT */
1886}
1887
1888/* Okay, now we write the entry_function for filename completion. In the
1889 general case. Note that completion in the shell is a little different
1890 because of all the pathnames that must be followed when looking up the
1891 completion for a command. */
1892char *
1893rl_filename_completion_function (text, state)
1894 const char *text;
1895 int state;
1896{
1897 static DIR *directory = (DIR *)NULL;
1898 static char *filename = (char *)NULL;
1899 static char *dirname = (char *)NULL;
1900 static char *users_dirname = (char *)NULL;
1901 static int filename_len;
1902 char *temp;
1903 int dirlen;
1904 struct dirent *entry;
1905
1906 /* If we don't have any state, then do some initialization. */
1907 if (state == 0)
1908 {
1909 /* If we were interrupted before closing the directory or reading
1910 all of its contents, close it. */
1911 if (directory)
1912 {
1913 closedir (directory);
1914 directory = (DIR *)NULL;
1915 }
1916 FREE (dirname);
1917 FREE (filename);
1918 FREE (users_dirname);
1919
1920 filename = savestring (text);
1921 if (*text == 0)
1922 text = ".";
1923 dirname = savestring (text);
1924
1925 temp = strrchr (dirname, '/');
1926
1927#if defined (__MSDOS__)
1928 /* special hack for //X/... */
1929 if (dirname[0] == '/' && dirname[1] == '/' && ISALPHA ((unsigned char)dirname[2]) && dirname[3] == '/')
1930 temp = strrchr (dirname + 3, '/');
1931#endif
1932
1933 if (temp)
1934 {
1935 strcpy (filename, ++temp);
1936 *temp = '\0';
1937 }
1938#if defined (__MSDOS__)
1939 /* searches from current directory on the drive */
1940 else if (ISALPHA ((unsigned char)dirname[0]) && dirname[1] == ':')
1941 {
1942 strcpy (filename, dirname + 2);
1943 dirname[2] = '\0';
1944 }
1945#endif
1946 else
1947 {
1948 dirname[0] = '.';
1949 dirname[1] = '\0';
1950 }
1951
1952 /* We aren't done yet. We also support the "~user" syntax. */
1953
1954 /* Save the version of the directory that the user typed. */
1955 users_dirname = savestring (dirname);
1956
1957 if (*dirname == '~')
1958 {
1959 temp = tilde_expand (dirname);
1960 free (dirname);
1961 dirname = temp;
1962 }
1963
1964 if (rl_directory_rewrite_hook)
1965 (*rl_directory_rewrite_hook) (&dirname);
1966
1967 /* The directory completion hook should perform any necessary
1968 dequoting. */
1978 if (rl_directory_completion_hook && (*rl_directory_completion_hook) (&dirname))
1979 {
1980 free (users_dirname);
1981 users_dirname = savestring (dirname);
1982 }
1969 if (rl_directory_completion_hook && (*rl_directory_completion_hook) (&dirname))
1970 {
1971 free (users_dirname);
1972 users_dirname = savestring (dirname);
1973 }
1983
1974 else if (rl_completion_found_quote && rl_filename_dequoting_function)
1975 {
1976 /* delete single and double quotes */
1977 temp = (*rl_filename_dequoting_function) (users_dirname, rl_completion_quote_character);
1978 free (users_dirname);
1979 users_dirname = temp;
1980 }
1984 directory = opendir (dirname);
1981 directory = opendir (dirname);
1982
1983 /* Now dequote a non-null filename. */
1984 if (filename && *filename && rl_completion_found_quote && rl_filename_dequoting_function)
1985 {
1986 /* delete single and double quotes */
1987 temp = (*rl_filename_dequoting_function) (filename, rl_completion_quote_character);
1988 free (filename);
1989 filename = temp;
1990 }
1985 filename_len = strlen (filename);
1986
1987 rl_filename_completion_desired = 1;
1988 }
1989
1990 /* At this point we should entertain the possibility of hacking wildcarded
1991 filenames, like /usr/man/man<WILD>/te<TAB>. If the directory name
1992 contains globbing characters, then build an array of directories, and
1993 then map over that list while completing. */
1994 /* *** UNIMPLEMENTED *** */
1995
1996 /* Now that we have some state, we can read the directory. */
1997
1998 entry = (struct dirent *)NULL;
1999 while (directory && (entry = readdir (directory)))
2000 {
2001 /* Special case for no filename. If the user has disabled the
2002 `match-hidden-files' variable, skip filenames beginning with `.'.
2003 All other entries except "." and ".." match. */
2004 if (filename_len == 0)
2005 {
2006 if (_rl_match_hidden_files == 0 && HIDDEN_FILE (entry->d_name))
2007 continue;
2008
2009 if (entry->d_name[0] != '.' ||
2010 (entry->d_name[1] &&
2011 (entry->d_name[1] != '.' || entry->d_name[2])))
2012 break;
2013 }
2014 else
2015 {
2016 /* Otherwise, if these match up to the length of filename, then
2017 it is a match. */
2018 if (_rl_completion_case_fold)
2019 {
2020 if ((_rl_to_lower (entry->d_name[0]) == _rl_to_lower (filename[0])) &&
2021 (((int)D_NAMLEN (entry)) >= filename_len) &&
2022 (_rl_strnicmp (filename, entry->d_name, filename_len) == 0))
2023 break;
2024 }
2025 else
2026 {
2027 if ((entry->d_name[0] == filename[0]) &&
2028 (((int)D_NAMLEN (entry)) >= filename_len) &&
2029 (strncmp (filename, entry->d_name, filename_len) == 0))
2030 break;
2031 }
2032 }
2033 }
2034
2035 if (entry == 0)
2036 {
2037 if (directory)
2038 {
2039 closedir (directory);
2040 directory = (DIR *)NULL;
2041 }
2042 if (dirname)
2043 {
2044 free (dirname);
2045 dirname = (char *)NULL;
2046 }
2047 if (filename)
2048 {
2049 free (filename);
2050 filename = (char *)NULL;
2051 }
2052 if (users_dirname)
2053 {
2054 free (users_dirname);
2055 users_dirname = (char *)NULL;
2056 }
2057
2058 return (char *)NULL;
2059 }
2060 else
2061 {
2062 /* dirname && (strcmp (dirname, ".") != 0) */
2063 if (dirname && (dirname[0] != '.' || dirname[1]))
2064 {
2065 if (rl_complete_with_tilde_expansion && *users_dirname == '~')
2066 {
2067 dirlen = strlen (dirname);
2068 temp = (char *)xmalloc (2 + dirlen + D_NAMLEN (entry));
2069 strcpy (temp, dirname);
2070 /* Canonicalization cuts off any final slash present. We
2071 may need to add it back. */
2072 if (dirname[dirlen - 1] != '/')
2073 {
2074 temp[dirlen++] = '/';
2075 temp[dirlen] = '\0';
2076 }
2077 }
2078 else
2079 {
2080 dirlen = strlen (users_dirname);
2081 temp = (char *)xmalloc (2 + dirlen + D_NAMLEN (entry));
2082 strcpy (temp, users_dirname);
2083 /* Make sure that temp has a trailing slash here. */
2084 if (users_dirname[dirlen - 1] != '/')
2085 temp[dirlen++] = '/';
2086 }
2087
2088 strcpy (temp + dirlen, entry->d_name);
2089 }
2090 else
2091 temp = savestring (entry->d_name);
2092
2093 return (temp);
2094 }
2095}
2096
2097/* An initial implementation of a menu completion function a la tcsh. The
2098 first time (if the last readline command was not rl_menu_complete), we
2099 generate the list of matches. This code is very similar to the code in
2100 rl_complete_internal -- there should be a way to combine the two. Then,
2101 for each item in the list of matches, we insert the match in an undoable
2102 fashion, with the appropriate character appended (this happens on the
2103 second and subsequent consecutive calls to rl_menu_complete). When we
2104 hit the end of the match list, we restore the original unmatched text,
2105 ring the bell, and reset the counter to zero. */
2106int
2107rl_menu_complete (count, ignore)
2108 int count, ignore;
2109{
2110 rl_compentry_func_t *our_func;
2111 int matching_filenames, found_quote;
2112
2113 static char *orig_text;
2114 static char **matches = (char **)0;
2115 static int match_list_index = 0;
2116 static int match_list_size = 0;
2117 static int orig_start, orig_end;
2118 static char quote_char;
2119 static int delimiter;
2120
2121 /* The first time through, we generate the list of matches and set things
2122 up to insert them. */
2123 if (rl_last_func != rl_menu_complete)
2124 {
2125 /* Clean up from previous call, if any. */
2126 FREE (orig_text);
2127 if (matches)
2128 _rl_free_match_list (matches);
2129
2130 match_list_index = match_list_size = 0;
2131 matches = (char **)NULL;
2132
2133 /* Only the completion entry function can change these. */
2134 set_completion_defaults ('%');
2135
2136 our_func = rl_completion_entry_function
2137 ? rl_completion_entry_function
2138 : rl_filename_completion_function;
2139
2140 /* We now look backwards for the start of a filename/variable word. */
2141 orig_end = rl_point;
2142 found_quote = delimiter = 0;
2143 quote_char = '\0';
2144
2145 if (rl_point)
2146 /* This (possibly) changes rl_point. If it returns a non-zero char,
2147 we know we have an open quote. */
2148 quote_char = _rl_find_completion_word (&found_quote, &delimiter);
2149
2150 orig_start = rl_point;
2151 rl_point = orig_end;
2152
2153 orig_text = rl_copy_text (orig_start, orig_end);
2154 matches = gen_completion_matches (orig_text, orig_start, orig_end,
2155 our_func, found_quote, quote_char);
2156
2157 /* If we are matching filenames, the attempted completion function will
2158 have set rl_filename_completion_desired to a non-zero value. The basic
2159 rl_filename_completion_function does this. */
2160 matching_filenames = rl_filename_completion_desired;
2161
2162 if (matches == 0 || postprocess_matches (&matches, matching_filenames) == 0)
2163 {
2164 rl_ding ();
2165 FREE (matches);
2166 matches = (char **)0;
2167 FREE (orig_text);
2168 orig_text = (char *)0;
2169 completion_changed_buffer = 0;
2170 return (0);
2171 }
2172
2173 for (match_list_size = 0; matches[match_list_size]; match_list_size++)
2174 ;
2175 /* matches[0] is lcd if match_list_size > 1, but the circular buffer
2176 code below should take care of it. */
2177 }
2178
2179 /* Now we have the list of matches. Replace the text between
2180 rl_line_buffer[orig_start] and rl_line_buffer[rl_point] with
2181 matches[match_list_index], and add any necessary closing char. */
2182
2183 if (matches == 0 || match_list_size == 0)
2184 {
2185 rl_ding ();
2186 FREE (matches);
2187 matches = (char **)0;
2188 completion_changed_buffer = 0;
2189 return (0);
2190 }
2191
2192 match_list_index += count;
2193 if (match_list_index < 0)
2194 match_list_index += match_list_size;
2195 else
2196 match_list_index %= match_list_size;
2197
2198 if (match_list_index == 0 && match_list_size > 1)
2199 {
2200 rl_ding ();
2201 insert_match (orig_text, orig_start, MULT_MATCH, &quote_char);
2202 }
2203 else
2204 {
2205 insert_match (matches[match_list_index], orig_start, SINGLE_MATCH, &quote_char);
2206 append_to_match (matches[match_list_index], delimiter, quote_char,
2207 strcmp (orig_text, matches[match_list_index]));
2208 }
2209
2210 completion_changed_buffer = 1;
2211 return (0);
2212}
1991 filename_len = strlen (filename);
1992
1993 rl_filename_completion_desired = 1;
1994 }
1995
1996 /* At this point we should entertain the possibility of hacking wildcarded
1997 filenames, like /usr/man/man<WILD>/te<TAB>. If the directory name
1998 contains globbing characters, then build an array of directories, and
1999 then map over that list while completing. */
2000 /* *** UNIMPLEMENTED *** */
2001
2002 /* Now that we have some state, we can read the directory. */
2003
2004 entry = (struct dirent *)NULL;
2005 while (directory && (entry = readdir (directory)))
2006 {
2007 /* Special case for no filename. If the user has disabled the
2008 `match-hidden-files' variable, skip filenames beginning with `.'.
2009 All other entries except "." and ".." match. */
2010 if (filename_len == 0)
2011 {
2012 if (_rl_match_hidden_files == 0 && HIDDEN_FILE (entry->d_name))
2013 continue;
2014
2015 if (entry->d_name[0] != '.' ||
2016 (entry->d_name[1] &&
2017 (entry->d_name[1] != '.' || entry->d_name[2])))
2018 break;
2019 }
2020 else
2021 {
2022 /* Otherwise, if these match up to the length of filename, then
2023 it is a match. */
2024 if (_rl_completion_case_fold)
2025 {
2026 if ((_rl_to_lower (entry->d_name[0]) == _rl_to_lower (filename[0])) &&
2027 (((int)D_NAMLEN (entry)) >= filename_len) &&
2028 (_rl_strnicmp (filename, entry->d_name, filename_len) == 0))
2029 break;
2030 }
2031 else
2032 {
2033 if ((entry->d_name[0] == filename[0]) &&
2034 (((int)D_NAMLEN (entry)) >= filename_len) &&
2035 (strncmp (filename, entry->d_name, filename_len) == 0))
2036 break;
2037 }
2038 }
2039 }
2040
2041 if (entry == 0)
2042 {
2043 if (directory)
2044 {
2045 closedir (directory);
2046 directory = (DIR *)NULL;
2047 }
2048 if (dirname)
2049 {
2050 free (dirname);
2051 dirname = (char *)NULL;
2052 }
2053 if (filename)
2054 {
2055 free (filename);
2056 filename = (char *)NULL;
2057 }
2058 if (users_dirname)
2059 {
2060 free (users_dirname);
2061 users_dirname = (char *)NULL;
2062 }
2063
2064 return (char *)NULL;
2065 }
2066 else
2067 {
2068 /* dirname && (strcmp (dirname, ".") != 0) */
2069 if (dirname && (dirname[0] != '.' || dirname[1]))
2070 {
2071 if (rl_complete_with_tilde_expansion && *users_dirname == '~')
2072 {
2073 dirlen = strlen (dirname);
2074 temp = (char *)xmalloc (2 + dirlen + D_NAMLEN (entry));
2075 strcpy (temp, dirname);
2076 /* Canonicalization cuts off any final slash present. We
2077 may need to add it back. */
2078 if (dirname[dirlen - 1] != '/')
2079 {
2080 temp[dirlen++] = '/';
2081 temp[dirlen] = '\0';
2082 }
2083 }
2084 else
2085 {
2086 dirlen = strlen (users_dirname);
2087 temp = (char *)xmalloc (2 + dirlen + D_NAMLEN (entry));
2088 strcpy (temp, users_dirname);
2089 /* Make sure that temp has a trailing slash here. */
2090 if (users_dirname[dirlen - 1] != '/')
2091 temp[dirlen++] = '/';
2092 }
2093
2094 strcpy (temp + dirlen, entry->d_name);
2095 }
2096 else
2097 temp = savestring (entry->d_name);
2098
2099 return (temp);
2100 }
2101}
2102
2103/* An initial implementation of a menu completion function a la tcsh. The
2104 first time (if the last readline command was not rl_menu_complete), we
2105 generate the list of matches. This code is very similar to the code in
2106 rl_complete_internal -- there should be a way to combine the two. Then,
2107 for each item in the list of matches, we insert the match in an undoable
2108 fashion, with the appropriate character appended (this happens on the
2109 second and subsequent consecutive calls to rl_menu_complete). When we
2110 hit the end of the match list, we restore the original unmatched text,
2111 ring the bell, and reset the counter to zero. */
2112int
2113rl_menu_complete (count, ignore)
2114 int count, ignore;
2115{
2116 rl_compentry_func_t *our_func;
2117 int matching_filenames, found_quote;
2118
2119 static char *orig_text;
2120 static char **matches = (char **)0;
2121 static int match_list_index = 0;
2122 static int match_list_size = 0;
2123 static int orig_start, orig_end;
2124 static char quote_char;
2125 static int delimiter;
2126
2127 /* The first time through, we generate the list of matches and set things
2128 up to insert them. */
2129 if (rl_last_func != rl_menu_complete)
2130 {
2131 /* Clean up from previous call, if any. */
2132 FREE (orig_text);
2133 if (matches)
2134 _rl_free_match_list (matches);
2135
2136 match_list_index = match_list_size = 0;
2137 matches = (char **)NULL;
2138
2139 /* Only the completion entry function can change these. */
2140 set_completion_defaults ('%');
2141
2142 our_func = rl_completion_entry_function
2143 ? rl_completion_entry_function
2144 : rl_filename_completion_function;
2145
2146 /* We now look backwards for the start of a filename/variable word. */
2147 orig_end = rl_point;
2148 found_quote = delimiter = 0;
2149 quote_char = '\0';
2150
2151 if (rl_point)
2152 /* This (possibly) changes rl_point. If it returns a non-zero char,
2153 we know we have an open quote. */
2154 quote_char = _rl_find_completion_word (&found_quote, &delimiter);
2155
2156 orig_start = rl_point;
2157 rl_point = orig_end;
2158
2159 orig_text = rl_copy_text (orig_start, orig_end);
2160 matches = gen_completion_matches (orig_text, orig_start, orig_end,
2161 our_func, found_quote, quote_char);
2162
2163 /* If we are matching filenames, the attempted completion function will
2164 have set rl_filename_completion_desired to a non-zero value. The basic
2165 rl_filename_completion_function does this. */
2166 matching_filenames = rl_filename_completion_desired;
2167
2168 if (matches == 0 || postprocess_matches (&matches, matching_filenames) == 0)
2169 {
2170 rl_ding ();
2171 FREE (matches);
2172 matches = (char **)0;
2173 FREE (orig_text);
2174 orig_text = (char *)0;
2175 completion_changed_buffer = 0;
2176 return (0);
2177 }
2178
2179 for (match_list_size = 0; matches[match_list_size]; match_list_size++)
2180 ;
2181 /* matches[0] is lcd if match_list_size > 1, but the circular buffer
2182 code below should take care of it. */
2183 }
2184
2185 /* Now we have the list of matches. Replace the text between
2186 rl_line_buffer[orig_start] and rl_line_buffer[rl_point] with
2187 matches[match_list_index], and add any necessary closing char. */
2188
2189 if (matches == 0 || match_list_size == 0)
2190 {
2191 rl_ding ();
2192 FREE (matches);
2193 matches = (char **)0;
2194 completion_changed_buffer = 0;
2195 return (0);
2196 }
2197
2198 match_list_index += count;
2199 if (match_list_index < 0)
2200 match_list_index += match_list_size;
2201 else
2202 match_list_index %= match_list_size;
2203
2204 if (match_list_index == 0 && match_list_size > 1)
2205 {
2206 rl_ding ();
2207 insert_match (orig_text, orig_start, MULT_MATCH, &quote_char);
2208 }
2209 else
2210 {
2211 insert_match (matches[match_list_index], orig_start, SINGLE_MATCH, &quote_char);
2212 append_to_match (matches[match_list_index], delimiter, quote_char,
2213 strcmp (orig_text, matches[match_list_index]));
2214 }
2215
2216 completion_changed_buffer = 1;
2217 return (0);
2218}