Debian Codegraph @

libsrc/readline/complete.c

raw
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 1, 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 675 Mass Ave, Cambridge, MA 02139, USA.
22
23 .VERSION
24 051021 last modif
25 */
26
27 #define READLINE_LIBRARY
28
29 #include <stdio.h>
30 #include <sys/types.h>
31 #include <fcntl.h>
32 #if !defined (NO_SYS_FILE)
33 # include <sys/file.h>
34 #endif /* !NO_SYS_FILE */
35
36 #if defined (HAVE_UNISTD_H)
37 # include <unistd.h>
38 #endif /* HAVE_UNISTD_H */
39
40 #if defined (HAVE_STDLIB_H)
41 # include <stdlib.h>
42 #else
43 # include "ansi_stdlib.h"
44 #endif /* HAVE_STDLIB_H */
45
46 #include <errno.h>
47 /* Not all systems declare ERRNO in errno.h... and some systems #define it! */
48 #if !defined (errno)
49 extern int errno;
50 #endif /* !errno */
51
52 #include <pwd.h>
53 #if defined (USG) && !defined (HAVE_GETPW_DECLS)
54 extern struct passwd *getpwent ();
55 #endif /* USG && !HAVE_GETPW_DECLS */
56
57 /* ISC systems don't define getpwent() if _POSIX_SOURCE is defined. */
58 #if defined (isc386) && defined (_POSIX_SOURCE)
59 # if defined (__STDC__)
60 extern struct passwd *getpwent (void);
61 # else
62 extern struct passwd *getpwent ();
63 # endif /* !__STDC__ */
64 #endif /* isc386 && _POSIX_SOURCE */
65
66 #include "posixstat.h"
67
68 /* System-specific feature definitions and include files. */
69 #include "rldefs.h"
70
71 /* Some standard library routines. */
72 #include "readline.h"
73
74 /* Possible values for do_replace in rl_complete_internal. */
75 #define NO_MATCH 0
76 #define SINGLE_MATCH 1
77 #define MULT_MATCH 2
78
79 #if !defined (strchr) && !defined (__STDC__)
80 extern char *strchr (), *strrchr ();
81 #endif /* !strchr && !__STDC__ */
82
83 extern char *tilde_expand ();
84 extern char *rl_copy_text ();
85
86 extern Function *rl_last_func;
87 extern int rl_editing_mode;
88 extern int screenwidth;
89
90 /* Forward declarations for functions defined and used in this file. */
91 char *filename_completion_function ();
92 char **completion_matches ();
93
94 static int compare_strings ();
95 static char *rl_strpbrk ();
96
97 #if defined (STATIC_MALLOC)
98 static char *xmalloc (), *xrealloc ();
99 #else
100 extern char *xmalloc (), *xrealloc ();
101 #endif /* STATIC_MALLOC */
102
103 /* If non-zero, then this is the address of a function to call when
104 completing on a directory name. The function is called with
105 the address of a string (the current directory name) as an arg. */
106 Function *rl_directory_completion_hook = (Function *)NULL;
107
108 /* Non-zero means readline completion functions perform tilde expansion. */
109 int rl_complete_with_tilde_expansion = 0;
110
111 /* If non-zero, non-unique completions always show the list of matches. */
112 int _rl_complete_show_all = 0;
113
114 #if defined (VISIBLE_STATS)
115 # if !defined (X_OK)
116 # define X_OK 1
117 # endif
118
119 static int stat_char ();
120
121 /* Non-zero means add an additional character to each filename displayed
122 during listing completion iff rl_filename_completion_desired which helps
123 to indicate the type of file being listed. */
124 int rl_visible_stats = 0;
125 #endif /* VISIBLE_STATS */
126
127 /* **************************************************************** */
128 /* */
129 /* Completion matching, from readline's point of view. */
130 /* */
131 /* **************************************************************** */
132
133 /* Pointer to the generator function for completion_matches ().
134 NULL means to use filename_entry_function (), the default filename
135 completer. */
136 Function *rl_completion_entry_function = (Function *)NULL;
137
138 /* Pointer to alternative function to create matches.
139 Function is called with TEXT, START, and END.
140 START and END are indices in RL_LINE_BUFFER saying what the boundaries
141 of TEXT are.
142 If this function exists and returns NULL then call the value of
143 rl_completion_entry_function to try to match, otherwise use the
144 array of strings returned. */
145 CPPFunction *rl_attempted_completion_function = (CPPFunction *)NULL;
146
147 /* Non-zero means to suppress normal filename completion after the
148 user-specified completion function has been called. */
149 int rl_attempted_completion_over = 0;
150
151 /* Local variable states what happened during the last completion attempt. */
152 static int completion_changed_buffer = 0;
153
154 /* Complete the word at or before point. You have supplied the function
155 that does the initial simple matching selection algorithm (see
156 completion_matches ()). The default is to do filename completion. */
157
158 rl_complete (ignore, invoking_key)
159 int ignore, invoking_key;
160 {
161 if (rl_last_func == rl_complete && !completion_changed_buffer)
162 return (rl_complete_internal ('?'));
163 else if (_rl_complete_show_all)
164 return (rl_complete_internal ('!'));
165 else
166 return (rl_complete_internal (TAB));
167 }
168
169 /* List the possible completions. See description of rl_complete (). */
170 rl_possible_completions (ignore, invoking_key)
171 int ignore, invoking_key;
172 {
173 return (rl_complete_internal ('?'));
174 }
175
176 rl_insert_completions (ignore, invoking_key)
177 int ignore, invoking_key;
178 {
179 return (rl_complete_internal ('*'));
180 }
181
182 /* The user must press "y" or "n". Non-zero return means "y" pressed. */
183 get_y_or_n ()
184 {
185 int c;
186
187 for (;;)
188 {
189 c = rl_read_key ();
190 if (c == 'y' || c == 'Y' || c == ' ')
191 return (1);
192 if (c == 'n' || c == 'N' || c == RUBOUT)
193 return (0);
194 if (c == ABORT_CHAR)
195 rl_abort ();
196 ding ();
197 }
198 }
199
200 /* Up to this many items will be displayed in response to a
201 possible-completions call. After that, we ask the user if
202 she is sure she wants to see them all. */
203 int rl_completion_query_items = 100;
204
205 /* The basic list of characters that signal a break between words for the
206 completer routine. The contents of this variable is what breaks words
207 in the shell, i.e. " \t\n\"\\'`@$><=" */
208 char *rl_basic_word_break_characters = " \t\n\"\\'`@$><=;|&{(";
209
210 /* The list of characters that signal a break between words for
211 rl_complete_internal. The default list is the contents of
212 rl_basic_word_break_characters. */
213 char *rl_completer_word_break_characters = (char *)NULL;
214
215 /* List of characters which can be used to quote a substring of the line.
216 Completion occurs on the entire substring, and within the substring
217 rl_completer_word_break_characters are treated as any other character,
218 unless they also appear within this list. */
219 char *rl_completer_quote_characters = (char *)NULL;
220
221 /* List of characters that are word break characters, but should be left
222 in TEXT when it is passed to the completion function. The shell uses
223 this to help determine what kind of completing to do. */
224 char *rl_special_prefixes = (char *)NULL;
225
226 /* If non-zero, then disallow duplicates in the matches. */
227 int rl_ignore_completion_duplicates = 1;
228
229 /* Non-zero means that the results of the matches are to be treated
230 as filenames. This is ALWAYS zero on entry, and can only be changed
231 within a completion entry finder function. */
232 int rl_filename_completion_desired = 0;
233
234 /* This function, if defined, is called by the completer when real
235 filename completion is done, after all the matching names have been
236 generated. It is passed a (char**) known as matches in the code below.
237 It consists of a NULL-terminated array of pointers to potential
238 matching strings. The 1st element (matches[0]) is the maximal
239 substring that is common to all matches. This function can re-arrange
240 the list of matches as required, but all elements of the array must be
241 free()'d if they are deleted. The main intent of this function is
242 to implement FIGNORE a la SunOS csh. */
243 Function *rl_ignore_some_completions_function = (Function *)NULL;
244
245 #if defined (SHELL)
246 /* A function to strip quotes that are not protected by backquotes. It
247 allows single quotes to appear within double quotes, and vice versa.
248 It should be smarter. It's fairly shell-specific, hence the SHELL
249 definition wrapper. */
250 static char *
251 _delete_quotes (text)
252 char *text;
253 {
254 char *ret, *p, *r;
255 int l, quoted;
256
257 l = strlen (text);
258 ret = xmalloc (l + 1);
259 for (quoted = 0, p = text, r = ret; p && *p; p++)
260 {
261 /* Allow backslash-quoted characters to pass through unscathed. */
262 if (*p == '\\')
263 continue;
264 /* Close quote. */
265 if (quoted && *p == quoted)
266 {
267 quoted = 0;
268 continue;
269 }
270 /* Open quote. */
271 if (quoted == 0 && (*p == '\'' || *p == '"'))
272 {
273 quoted = *p;
274 continue;
275 }
276 *r++ = *p;
277 }
278 *r = '\0';
279 return ret;
280 }
281 #endif /* SHELL */
282
283 /* Return the portion of PATHNAME that should be output when listing
284 possible completions. If we are hacking filename completion, we
285 are only interested in the basename, the portion following the
286 final slash. Otherwise, we return what we were passed. */
287 static char *
288 printable_part (pathname)
289 char *pathname;
290 {
291 char *temp = (char *)NULL;
292
293 if (rl_filename_completion_desired)
294 temp = strrchr (pathname, '/');
295
296 if (!temp)
297 return (pathname);
298 else
299 return (++temp);
300 }
301
302 /* Output TO_PRINT to rl_outstream. If VISIBLE_STATS is defined and we
303 are using it, check for and output a single character for `special'
304 filenames. Return 1 if we printed an extension character, 0 if not. */
305 static int
306 print_filename (to_print, full_pathname)
307 char *to_print, *full_pathname;
308 {
309 #if !defined (VISIBLE_STATS)
310 fputs (to_print, rl_outstream);
311 return 0;
312 #else
313 char *s, c, *new_full_pathname;
314 int extension_char = 0, slen, tlen;
315
316 fputs (to_print, rl_outstream);
317 if (rl_filename_completion_desired && rl_visible_stats)
318 {
319 /* If to_print != full_pathname, to_print is the basename of the
320 path passed. In this case, we try to expand the directory
321 name before checking for the stat character. */
322 if (to_print != full_pathname)
323 {
324 /* Terminate the directory name. */
325 c = to_print[-1];
326 to_print[-1] = '\0';
327
328 s = tilde_expand (full_pathname);
329 if (rl_directory_completion_hook)
330 (*rl_directory_completion_hook) (&s);
331
332 slen = strlen (s);
333 tlen = strlen (to_print);
334 new_full_pathname = xmalloc (slen + tlen + 2);
335 strcpy (new_full_pathname, s);
336 new_full_pathname[slen] = '/';
337 strcpy (new_full_pathname + slen + 1, to_print);
338
339 extension_char = stat_char (new_full_pathname);
340
341 free (new_full_pathname);
342 to_print[-1] = c;
343 }
344 else
345 {
346 s = tilde_expand (full_pathname);
347 extension_char = stat_char (s);
348 }
349
350 free (s);
351 if (extension_char)
352 putc (extension_char, rl_outstream);
353 return (extension_char != 0);
354 }
355 else
356 return 0;
357 #endif /* VISIBLE_STATS */
358 }
359
360 /* Complete the word at or before point.
361 WHAT_TO_DO says what to do with the completion.
362 `?' means list the possible completions.
363 TAB means do standard completion.
364 `*' means insert all of the possible completions.
365 `!' means to do standard completion, and list all possible completions if
366 there is more than one. */
367 rl_complete_internal (what_to_do)
368 int what_to_do;
369 {
370 char **matches;
371 Function *our_func;
372 int start, scan, end, delimiter = 0, pass_next;
373 char *text, *saved_line_buffer;
374 char *replacement;
375 char quote_char = '\0';
376 int found_quote = 0;
377
378 if (rl_line_buffer)
379 saved_line_buffer = savestring (rl_line_buffer);
380 else
381 saved_line_buffer = (char *)NULL;
382
383 if (rl_completion_entry_function)
384 our_func = rl_completion_entry_function;
385 else
386 our_func = (Function *)filename_completion_function;
387
388 /* Only the completion entry function can change this. */
389 rl_filename_completion_desired = 0;
390
391 /* We now look backwards for the start of a filename/variable word. */
392 end = rl_point;
393
394 if (rl_point)
395 {
396 if (rl_completer_quote_characters)
397 {
398 /* We have a list of characters which can be used in pairs to
399 quote substrings for the completer. Try to find the start
400 of an unclosed quoted substring. */
401 /* FOUND_QUOTE is set so we know what kind of quotes we found. */
402 for (scan = pass_next = 0; scan < end; scan++)
403 {
404 if (pass_next)
405 {
406 pass_next = 0;
407 continue;
408 }
409
410 if (rl_line_buffer[scan] == '\\')
411 {
412 pass_next = 1;
413 found_quote |= 4;
414 continue;
415 }
416
417 if (quote_char != '\0')
418 {
419 /* Ignore everything until the matching close quote char. */
420 if (rl_line_buffer[scan] == quote_char)
421 {
422 /* Found matching close. Abandon this substring. */
423 quote_char = '\0';
424 rl_point = end;
425 }
426 }
427 else if (strchr (rl_completer_quote_characters, rl_line_buffer[scan]))
428 {
429 /* Found start of a quoted substring. */
430 quote_char = rl_line_buffer[scan];
431 rl_point = scan + 1;
432 /* Shell-like quoting conventions. */
433 if (quote_char == '\'')
434 found_quote |= 1;
435 else if (quote_char == '"')
436 found_quote |= 2;
437 }
438 }
439 }
440
441 if (rl_point == end)
442 {
443 int quoted = 0;
444 /* We didn't find an unclosed quoted substring upon which to do
445 completion, so use the word break characters to find the
446 substring on which to complete. */
447 while (--rl_point)
448 {
449 scan = rl_line_buffer[rl_point];
450
451 if (strchr (rl_completer_word_break_characters, scan) == 0)
452 continue;
453
454 #if defined (SHELL)
455 /* Don't let word break characters in quoted substrings break
456 words for the completer. */
457 if (found_quote && char_is_quoted (rl_line_buffer, rl_point))
458 continue;
459 #endif /* SHELL */
460
461 /* Convoluted code, but it avoids an n2 algorithm with calls
462 to char_is_quoted. */
463 break;
464 }
465 }
466
467 /* If we are at a word break, then advance past it. */
468 scan = rl_line_buffer[rl_point];
469 if (strchr (rl_completer_word_break_characters, scan))
470 {
471 /* If the character that caused the word break was a quoting
472 character, then remember it as the delimiter. */
473 if (strchr ("\"'", scan) && (end - rl_point) > 1)
474 delimiter = scan;
475
476 /* If the character isn't needed to determine something special
477 about what kind of completion to perform, then advance past it. */
478 if (!rl_special_prefixes || strchr (rl_special_prefixes, scan) == 0)
479 rl_point++;
480 }
481 }
482
483 /* At this point, we know we have an open quote if quote_char != '\0'. */
484 start = rl_point;
485 rl_point = end;
486 text = rl_copy_text (start, end);
487
488 /* If the user wants to TRY to complete, but then wants to give
489 up and use the default completion function, they set the
490 variable rl_attempted_completion_function. */
491 if (rl_attempted_completion_function)
492 {
493 matches = (*rl_attempted_completion_function) (text, start, end);
494
495 if (matches || rl_attempted_completion_over)
496 {
497 rl_attempted_completion_over = 0;
498 our_func = (Function *)NULL;
499 goto after_usual_completion;
500 }
501 }
502
503 #if defined (SHELL)
504 /* Beware -- we're stripping the quotes here. Do this only if we know
505 we are doing filename completion. */
506 if (found_quote && our_func == (Function *)filename_completion_function)
507 {
508 /* delete single and double quotes */
509 replacement = _delete_quotes (text);
510 free (text);
511 text = replacement;
512 replacement = (char *)0;
513 }
514 #endif /* SHELL */
515
516 matches = completion_matches (text, our_func);
517
518 after_usual_completion:
519 free (text);
520
521 if (!matches)
522 ding ();
523 else
524 {
525 register int i;
526 int should_quote;
527
528 /* It seems to me that in all the cases we handle we would like
529 to ignore duplicate possiblilities. Scan for the text to
530 insert being identical to the other completions. */
531 if (rl_ignore_completion_duplicates)
532 {
533 char *lowest_common;
534 int j, newlen = 0;
535 char dead_slot;
536 char **temp_array;
537
538 /* Sort the items. */
539 /* It is safe to sort this array, because the lowest common
540 denominator found in matches[0] will remain in place. */
541 for (i = 0; matches[i]; i++);
542 qsort (matches, i, sizeof (char *), compare_strings);
543
544 /* Remember the lowest common denominator for it may be unique. */
545 lowest_common = savestring (matches[0]);
546
547 for (i = 0; matches[i + 1]; i++)
548 {
549 if (strcmp (matches[i], matches[i + 1]) == 0)
550 {
551 free (matches[i]);
552 matches[i] = (char *)&dead_slot;
553 }
554 else
555 newlen++;
556 }
557
558 /* We have marked all the dead slots with (char *)&dead_slot.
559 Copy all the non-dead entries into a new array. */
560 temp_array = (char **)xmalloc ((3 + newlen) * sizeof (char *));
561 for (i = j = 1; matches[i]; i++)
562 {
563 if (matches[i] != (char *)&dead_slot)
564 temp_array[j++] = matches[i];
565 }
566 temp_array[j] = (char *)NULL;
567
568 if (matches[0] != (char *)&dead_slot)
569 free (matches[0]);
570 free (matches);
571
572 matches = temp_array;
573
574 /* Place the lowest common denominator back in [0]. */
575 matches[0] = lowest_common;
576
577 /* If there is one string left, and it is identical to the
578 lowest common denominator, then the LCD is the string to
579 insert. */
580 if (j == 2 && strcmp (matches[0], matches[1]) == 0)
581 {
582 free (matches[1]);
583 matches[1] = (char *)NULL;
584 }
585 }
586
587 switch (what_to_do)
588 {
589 case TAB:
590 case '!':
591 /* If we are matching filenames, then here is our chance to
592 do clever processing by re-examining the list. Call the
593 ignore function with the array as a parameter. It can
594 munge the array, deleting matches as it desires. */
595 if (rl_ignore_some_completions_function &&
596 our_func == (Function *)filename_completion_function)
597 (void)(*rl_ignore_some_completions_function)(matches);
598
599 /* If we are doing completion on quoted substrings, and any matches
600 contain any of the completer_word_break_characters, then auto-
601 matically prepend the substring with a quote character (just pick
602 the first one from the list of such) if it does not already begin
603 with a quote string. FIXME: Need to remove any such automatically
604 inserted quote character when it no longer is necessary, such as
605 if we change the string we are completing on and the new set of
606 matches don't require a quoted substring. */
607 replacement = matches[0];
608
609 should_quote = matches[0] && rl_completer_quote_characters &&
610 rl_filename_completion_desired;
611
612 #if defined (SHELL)
613 should_quote = should_quote && (!quote_char || quote_char == '"');
614 #else
615 should_quote = should_quote && !quote_char;
616 #endif
617
618 if (should_quote)
619 {
620 int do_replace;
621
622 do_replace = NO_MATCH;
623
624 /* If there is a single match, see if we need to quote it.
625 This also checks whether the common prefix of several
626 matches needs to be quoted. If the common prefix should
627 not be checked, add !matches[1] to the if clause. */
628 should_quote = rl_strpbrk (matches[0], rl_completer_word_break_characters) != 0;
629 #if defined (SHELL)
630 should_quote = should_quote || rl_strpbrk (matches[0], "#$`") != 0;
631 #endif
632
633 if (should_quote)
634 do_replace = matches[1] ? MULT_MATCH : SINGLE_MATCH;
635
636 if (do_replace != NO_MATCH)
637 {
638 #if defined (SHELL)
639 /* Quote the replacement, since we found an
640 embedded word break character in a potential
641 match. */
642 char *rtext, *mtext;
643 int rlen;
644 extern char *double_quote (); /* in builtins/common.c */
645
646 /* If DO_REPLACE == MULT_MATCH, it means that there is
647 more than one match. In this case, we do not add
648 the closing quote or attempt to perform tilde
649 expansion. If DO_REPLACE == SINGLE_MATCH, we try
650 to perform tilde expansion, because double quotes
651 inhibit tilde expansion by the shell. */
652
653 mtext = matches[0];
654 if (mtext[0] == '~' && do_replace == SINGLE_MATCH)
655 mtext = tilde_expand (matches[0]);
656 rtext = double_quote (mtext);
657 if (mtext != matches[0])
658 free (mtext);
659
660 rlen = strlen (rtext);
661 replacement = xmalloc (rlen + 1);
662 /* If we're completing on a quoted string where the user
663 has already supplied the opening quote, we don't want
664 the quote in the replacement text, and we reset
665 QUOTE_CHAR to 0 to avoid an extra closing quote. */
666 if (quote_char == '"')
667 {
668 strcpy (replacement, rtext + 1);
669 rlen--;
670 quote_char = 0;
671 }
672 else
673 strcpy (replacement, rtext);
674 if (do_replace == MULT_MATCH)
675 replacement[rlen - 1] = '\0';
676 free (rtext);
677 #else /* !SHELL */
678 /* Found an embedded word break character in a potential
679 match, so we need to prepend a quote character if we
680 are replacing the completion string. */
681 replacement = xmalloc (strlen (matches[0]) + 2);
682 quote_char = *rl_completer_quote_characters;
683 *replacement = quote_char;
684 strcpy (replacement + 1, matches[0]);
685 #endif /* SHELL */
686 }
687 }
688
689 if (replacement)
690 {
691 rl_begin_undo_group ();
692 rl_delete_text (start, rl_point);
693 rl_point = start;
694 rl_insert_text (replacement);
695 rl_end_undo_group ();
696 if (replacement != matches[0])
697 free (replacement);
698 }
699
700 /* If there are more matches, ring the bell to indicate.
701 If this was the only match, and we are hacking files,
702 check the file to see if it was a directory. If so,
703 add a '/' to the name. If not, and we are at the end
704 of the line, then add a space. */
705 if (matches[1])
706 {
707 if (what_to_do == '!')
708 goto display_matches; /* XXX */
709 else if (rl_editing_mode != vi_mode)
710 ding (); /* There are other matches remaining. */
711 }
712 else
713 {
714 char temp_string[4];
715 int temp_string_index = 0;
716
717 if (quote_char)
718 temp_string[temp_string_index++] = quote_char;
719
720 temp_string[temp_string_index++] = delimiter ? delimiter : ' ';
721 temp_string[temp_string_index++] = '\0';
722
723 if (rl_filename_completion_desired)
724 {
725 struct stat finfo;
726 char *filename = tilde_expand (matches[0]);
727
728 if ((stat (filename, &finfo) == 0) && S_ISDIR (finfo.st_mode))
729 {
730 if (rl_line_buffer[rl_point] != '/')
731 rl_insert_text ("/");
732 }
733 else
734 {
735 if (rl_point == rl_end)
736 rl_insert_text (temp_string);
737 }
738 free (filename);
739 }
740 else
741 {
742 if (rl_point == rl_end)
743 rl_insert_text (temp_string);
744 }
745 }
746 break;
747
748 case '*':
749 {
750 int i = 1;
751
752 rl_begin_undo_group ();
753 rl_delete_text (start, rl_point);
754 rl_point = start;
755 if (matches[1])
756 {
757 while (matches[i])
758 {
759 rl_insert_text (matches[i++]);
760 rl_insert_text (" ");
761 }
762 }
763 else
764 {
765 rl_insert_text (matches[0]);
766 rl_insert_text (" ");
767 }
768 rl_end_undo_group ();
769 }
770 break;
771
772 case '?':
773 {
774 int len, count, limit, max;
775 int j, k, l;
776
777 /* Handle simple case first. What if there is only one answer? */
778 if (!matches[1])
779 {
780 char *temp;
781
782 temp = printable_part (matches[0]);
783 crlf ();
784 print_filename (temp, matches[0]);
785 crlf ();
786 goto restart;
787 }
788
789 /* There is more than one answer. Find out how many there are,
790 and find out what the maximum printed length of a single entry
791 is. */
792 display_matches:
793 for (max = 0, i = 1; matches[i]; i++)
794 {
795 char *temp;
796 int name_length;
797
798 temp = printable_part (matches[i]);
799 name_length = strlen (temp);
800
801 if (name_length > max)
802 max = name_length;
803 }
804
805 len = i - 1;
806
807 /* If there are many items, then ask the user if she
808 really wants to see them all. */
809 if (len >= rl_completion_query_items)
810 {
811 crlf ();
812 fprintf (rl_outstream,
813 "There are %d possibilities. Do you really", len);
814 crlf ();
815 fprintf (rl_outstream, "wish to see them all? (y or n)");
816 fflush (rl_outstream);
817 if (!get_y_or_n ())
818 {
819 crlf ();
820 goto restart;
821 }
822 }
823
824 /* How many items of MAX length can we fit in the screen window? */
825 max += 2;
826 limit = screenwidth / max;
827 if (limit != 1 && (limit * max == screenwidth))
828 limit--;
829
830 /* Avoid a possible floating exception. If max > screenwidth,
831 limit will be 0 and a divide-by-zero fault will result. */
832 if (limit == 0)
833 limit = 1;
834
835 /* How many iterations of the printing loop? */
836 count = (len + (limit - 1)) / limit;
837
838 /* Watch out for special case. If LEN is less than LIMIT, then
839 just do the inner printing loop. */
840 if (len < limit)
841 count = 1;
842
843 /* Sort the items if they are not already sorted. */
844 if (!rl_ignore_completion_duplicates)
845 qsort (matches, len, sizeof (char *), compare_strings);
846
847 /* Print the sorted items, up-and-down alphabetically, like
848 ls might. */
849 crlf ();
850
851 for (i = 1; i < count + 1; i++)
852 {
853 for (j = 0, l = i; j < limit; j++)
854 {
855 if (l > len || !matches[l])
856 break;
857 else
858 {
859 char *temp;
860 int printed_length;
861
862 temp = printable_part (matches[l]);
863 printed_length = strlen (temp);
864 printed_length += print_filename (temp, matches[l]);
865
866 if (j + 1 < limit)
867 {
868 for (k = 0; k < max - printed_length; k++)
869 putc (' ', rl_outstream);
870 }
871 }
872 l += count;
873 }
874 crlf ();
875 }
876 restart:
877
878 rl_on_new_line ();
879 }
880 break;
881
882 default:
883 fprintf (stderr, "\r\nreadline: bad value for what_to_do in rl_complete\n");
884 abort ();
885 }
886
887 for (i = 0; matches[i]; i++)
888 free (matches[i]);
889 free (matches);
890 }
891
892 /* Check to see if the line has changed through all of this manipulation. */
893 if (saved_line_buffer)
894 {
895 if (strcmp (rl_line_buffer, saved_line_buffer) != 0)
896 completion_changed_buffer = 1;
897 else
898 completion_changed_buffer = 0;
899
900 free (saved_line_buffer);
901 }
902 return 0;
903 }
904
905 #if defined (VISIBLE_STATS)
906 /* Return the character which best describes FILENAME.
907 `@' for symbolic links
908 `/' for directories
909 `*' for executables
910 `=' for sockets */
911 static int
912 stat_char (filename)
913 char *filename;
914 {
915 struct stat finfo;
916 int character, r;
917
918 #if defined (S_ISLNK)
919 r = lstat (filename, &finfo);
920 #else
921 r = stat (filename, &finfo);
922 #endif
923
924 if (r == -1)
925 return (0);
926
927 character = 0;
928 if (S_ISDIR (finfo.st_mode))
929 character = '/';
930 #if defined (S_ISLNK)
931 else if (S_ISLNK (finfo.st_mode))
932 character = '@';
933 #endif /* S_ISLNK */
934 #if defined (S_ISSOCK)
935 else if (S_ISSOCK (finfo.st_mode))
936 character = '=';
937 #endif /* S_ISSOCK */
938 else if (S_ISREG (finfo.st_mode))
939 {
940 if (access (filename, X_OK) == 0)
941 character = '*';
942 }
943 return (character);
944 }
945 #endif /* VISIBLE_STATS */
946
947 /* Stupid comparison routine for qsort () ing strings. */
948 static int
949 compare_strings (s1, s2)
950 char **s1, **s2;
951 {
952 return (strcmp (*s1, *s2));
953 }
954
955 /* A completion function for usernames.
956 TEXT contains a partial username preceded by a random
957 character (usually `~'). */
958 char *
959 username_completion_function (text, state)
960 int state;
961 char *text;
962 {
963 #if defined (__GO32__)
964 return (char *)NULL;
965 #else /* !__GO32__ */
966 static char *username = (char *)NULL;
967 static struct passwd *entry;
968 static int namelen, first_char, first_char_loc;
969
970 if (!state)
971 {
972 if (username)
973 free (username);
974
975 first_char = *text;
976
977 if (first_char == '~')
978 first_char_loc = 1;
979 else
980 first_char_loc = 0;
981
982 username = savestring (&text[first_char_loc]);
983 namelen = strlen (username);
984 setpwent ();
985 }
986
987 while (entry = getpwent ())
988 {
989 if ((username[0] == entry->pw_name[0]) &&
990 (strncmp (username, entry->pw_name, namelen) == 0))
991 break;
992 }
993
994 if (!entry)
995 {
996 endpwent ();
997 return ((char *)NULL);
998 }
999 else
1000 {
1001 char *value = xmalloc (2 + strlen (entry->pw_name));
1002
1003 *value = *text;
1004
1005 strcpy (value + first_char_loc, entry->pw_name);
1006
1007 if (first_char == '~')
1008 rl_filename_completion_desired = 1;
1009
1010 return (value);
1011 }
1012 #endif /* !__GO32__ */
1013 }
1014
1015 /* **************************************************************** */
1016 /* */
1017 /* Completion */
1018 /* */
1019 /* **************************************************************** */
1020
1021 /* Non-zero means that case is not significant in completion. */
1022 int completion_case_fold = 0;
1023
1024 /* Return an array of (char *) which is a list of completions for TEXT.
1025 If there are no completions, return a NULL pointer.
1026 The first entry in the returned array is the substitution for TEXT.
1027 The remaining entries are the possible completions.
1028 The array is terminated with a NULL pointer.
1029
1030 ENTRY_FUNCTION is a function of two args, and returns a (char *).
1031 The first argument is TEXT.
1032 The second is a state argument; it should be zero on the first call, and
1033 non-zero on subsequent calls. It returns a NULL pointer to the caller
1034 when there are no more matches.
1035 */
1036 char **
1037 completion_matches (text, entry_function)
1038 char *text;
1039 CPFunction *entry_function;
1040 {
1041 /* Number of slots in match_list. */
1042 int match_list_size;
1043
1044 /* The list of matches. */
1045 char **match_list =
1046 (char **)xmalloc (((match_list_size = 10) + 1) * sizeof (char *));
1047
1048 /* Number of matches actually found. */
1049 int matches = 0;
1050
1051 /* Temporary string binder. */
1052 char *string;
1053
1054 match_list[1] = (char *)NULL;
1055
1056 while (string = (*entry_function) (text, matches))
1057 {
1058 if (matches + 1 == match_list_size)
1059 match_list = (char **)xrealloc
1060 (match_list, ((match_list_size += 10) + 1) * sizeof (char *));
1061
1062 match_list[++matches] = string;
1063 match_list[matches + 1] = (char *)NULL;
1064 }
1065
1066 /* If there were any matches, then look through them finding out the
1067 lowest common denominator. That then becomes match_list[0]. */
1068 if (matches)
1069 {
1070 register int i = 1;
1071 int low = 100000; /* Count of max-matched characters. */
1072
1073 /* If only one match, just use that. */
1074 if (matches == 1)
1075 {
1076 match_list[0] = match_list[1];
1077 match_list[1] = (char *)NULL;
1078 }
1079 else
1080 {
1081 /* Otherwise, compare each member of the list with
1082 the next, finding out where they stop matching. */
1083
1084 while (i < matches)
1085 {
1086 register int c1, c2, si;
1087
1088 if (completion_case_fold)
1089 {
1090 for (si = 0;
1091 (c1 = to_lower(match_list[i][si])) &&
1092 (c2 = to_lower(match_list[i + 1][si]));
1093 si++)
1094 if (c1 != c2) break;
1095 }
1096 else
1097 {
1098 for (si = 0;
1099 (c1 = match_list[i][si]) &&
1100 (c2 = match_list[i + 1][si]);
1101 si++)
1102 if (c1 != c2) break;
1103 }
1104
1105 if (low > si) low = si;
1106 i++;
1107 }
1108 match_list[0] = xmalloc (low + 1);
1109 strncpy (match_list[0], match_list[1], low);
1110 match_list[0][low] = '\0';
1111 }
1112 }
1113 else /* There were no matches. */
1114 {
1115 free (match_list);
1116 match_list = (char **)NULL;
1117 }
1118 return (match_list);
1119 }
1120
1121 /* Okay, now we write the entry_function for filename completion. In the
1122 general case. Note that completion in the shell is a little different
1123 because of all the pathnames that must be followed when looking up the
1124 completion for a command. */
1125 char *
1126 filename_completion_function (text, state)
1127 int state;
1128 char *text;
1129 {
1130 static DIR *directory;
1131 static char *filename = (char *)NULL;
1132 static char *dirname = (char *)NULL;
1133 static char *users_dirname = (char *)NULL;
1134 static int filename_len;
1135
1136 struct dirent *entry = (struct dirent *)NULL;
1137
1138 /* If we don't have any state, then do some initialization. */
1139 if (!state)
1140 {
1141 char *temp;
1142
1143 if (dirname) free (dirname);
1144 if (filename) free (filename);
1145 if (users_dirname) free (users_dirname);
1146
1147 filename = savestring (text);
1148 if (!*text) text = ".";
1149 dirname = savestring (text);
1150
1151 temp = strrchr (dirname, '/');
1152
1153 if (temp)
1154 {
1155 strcpy (filename, ++temp);
1156 *temp = '\0';
1157 }
1158 else
1159 strcpy (dirname, ".");
1160
1161 /* We aren't done yet. We also support the "~user" syntax. */
1162
1163 /* Save the version of the directory that the user typed. */
1164 users_dirname = savestring (dirname);
1165 {
1166 char *temp_dirname;
1167 int replace_dirname;
1168
1169 temp_dirname = tilde_expand (dirname);
1170 free (dirname);
1171 dirname = temp_dirname;
1172
1173 replace_dirname = 0;
1174 if (rl_directory_completion_hook)
1175 replace_dirname = (*rl_directory_completion_hook) (&dirname);
1176 if (replace_dirname)
1177 {
1178 free (users_dirname);
1179 users_dirname = savestring (dirname);
1180 }
1181 }
1182 directory = opendir (dirname);
1183 filename_len = strlen (filename);
1184
1185 rl_filename_completion_desired = 1;
1186 }
1187
1188 /* At this point we should entertain the possibility of hacking wildcarded
1189 filenames, like /usr/man/man<WILD>/te<TAB>. If the directory name
1190 contains globbing characters, then build an array of directories, and
1191 then map over that list while completing. */
1192 /* *** UNIMPLEMENTED *** */
1193
1194 /* Now that we have some state, we can read the directory. */
1195
1196 while (directory && (entry = readdir (directory)))
1197 {
1198 /* Special case for no filename.
1199 All entries except "." and ".." match. */
1200 if (!filename_len)
1201 {
1202 if ((strcmp (entry->d_name, ".") != 0) &&
1203 (strcmp (entry->d_name, "..") != 0))
1204 break;
1205 }
1206 else
1207 {
1208 /* Otherwise, if these match up to the length of filename, then
1209 it is a match. */
1210 if ((entry->d_name[0] == filename[0]) &&
1211 (((int)D_NAMLEN (entry)) >= filename_len) &&
1212 (strncmp (filename, entry->d_name, filename_len) == 0))
1213 break;
1214 }
1215 }
1216
1217 if (!entry)
1218 {
1219 if (directory)
1220 {
1221 closedir (directory);
1222 directory = (DIR *)NULL;
1223 }
1224 if (dirname)
1225 {
1226 free (dirname);
1227 dirname = (char *)NULL;
1228 }
1229 if (filename)
1230 {
1231 free (filename);
1232 filename = (char *)NULL;
1233 }
1234 if (users_dirname)
1235 {
1236 free (users_dirname);
1237 users_dirname = (char *)NULL;
1238 }
1239
1240 return (char *)NULL;
1241 }
1242 else
1243 {
1244 char *temp;
1245
1246 /* dirname && (strcmp (dirname, ".") != 0) */
1247 if (dirname && (dirname[0] != '.' || dirname[1]))
1248 {
1249 if (rl_complete_with_tilde_expansion && *users_dirname == '~')
1250 {
1251 int dirlen = strlen (dirname);
1252 temp = xmalloc (2 + dirlen + D_NAMLEN (entry));
1253 strcpy (temp, dirname);
1254 /* Canonicalization cuts off any final slash present. We need
1255 to add it back. */
1256 if (dirname[dirlen - 1] != '/')
1257 {
1258 temp[dirlen] = '/';
1259 temp[dirlen + 1] = '\0';
1260 }
1261 }
1262 else
1263 {
1264 temp = xmalloc (1 + strlen (users_dirname) + D_NAMLEN (entry));
1265 strcpy (temp, users_dirname);
1266 }
1267
1268 strcat (temp, entry->d_name);
1269 }
1270 else
1271 temp = (savestring (entry->d_name));
1272
1273 return (temp);
1274 }
1275 }
1276
1277 /* A function for simple tilde expansion. */
1278 int
1279 rl_tilde_expand (ignore, key)
1280 int ignore, key;
1281 {
1282 register int start, end;
1283 char *homedir;
1284
1285 end = rl_point;
1286 start = end - 1;
1287
1288 if (rl_point == rl_end && rl_line_buffer[rl_point] == '~')
1289 {
1290 homedir = tilde_expand ("~");
1291 goto insert;
1292 }
1293 else if (rl_line_buffer[start] != '~')
1294 {
1295 for (; !whitespace (rl_line_buffer[start]) && start >= 0; start--);
1296 start++;
1297 }
1298
1299 end = start;
1300 do
1301 {
1302 end++;
1303 }
1304 while (!whitespace (rl_line_buffer[end]) && end < rl_end);
1305
1306 if (whitespace (rl_line_buffer[end]) || end >= rl_end)
1307 end--;
1308
1309 /* If the first character of the current word is a tilde, perform
1310 tilde expansion and insert the result. If not a tilde, do
1311 nothing. */
1312 if (rl_line_buffer[start] == '~')
1313 {
1314 char *temp;
1315 int len;
1316
1317 len = end - start + 1;
1318 temp = xmalloc (len + 1);
1319 strncpy (temp, rl_line_buffer + start, len);
1320 temp[len] = '\0';
1321 homedir = tilde_expand (temp);
1322 free (temp);
1323
1324 insert:
1325 rl_begin_undo_group ();
1326 rl_delete_text (start, end + 1);
1327 rl_point = start;
1328 rl_insert_text (homedir);
1329 rl_end_undo_group ();
1330 }
1331
1332 return (0);
1333 }
1334
1335 /* Find the first occurrence in STRING1 of any character from STRING2.
1336 Return a pointer to the character in STRING1. */
1337 static char *
1338 rl_strpbrk (string1, string2)
1339 char *string1, *string2;
1340 {
1341 register char *scan;
1342
1343 for (; *string1; string1++)
1344 {
1345 for (scan = string2; *scan; scan++)
1346 {
1347 if (*string1 == *scan)
1348 {
1349 return (string1);
1350 }
1351 }
1352 }
1353 return ((char *)NULL);
1354 }
1355
1356 #if defined (STATIC_MALLOC)
1357
1358 /* **************************************************************** */
1359 /* */
1360 /* xmalloc and xrealloc () */
1361 /* */
1362 /* **************************************************************** */
1363
1364 static void memory_error_and_abort ();
1365
1366 static char *
1367 xmalloc (bytes)
1368 int bytes;
1369 {
1370 char *temp = (char *)malloc (bytes);
1371
1372 if (!temp)
1373 memory_error_and_abort ();
1374 return (temp);
1375 }
1376
1377 static char *
1378 xrealloc (pointer, bytes)
1379 char *pointer;
1380 int bytes;
1381 {
1382 char *temp;
1383
1384 if (!pointer)
1385 temp = (char *)malloc ((size_t)bytes);
1386 else
1387 temp = (char *)realloc ((void *)pointer,(size_t)bytes);
1388
1389 if (!temp)
1390 memory_error_and_abort ();
1391
1392 return (temp);
1393 }
1394
1395 static void
1396 memory_error_and_abort ()
1397 {
1398 fprintf (stderr, "readline: Out of virtual memory!\n");
1399 abort ();
1400 }
1401 #endif /* STATIC_MALLOC */