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