* test case for PR 18230, over from d30v branch
[binutils-gdb.git] / readline / complete.c
blob0a996a742485a08f8752bb073598bac91ee2d0fe
1 /* complete.c -- filename completion for readline. */
3 /* Copyright (C) 1987, 1989, 1992 Free Software Foundation, Inc.
5 This file is part of the GNU Readline Library, a library for
6 reading lines of text with interactive input and history editing.
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.
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.
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. */
23 #include "sysdep.h"
24 #include <stdio.h>
25 #include <fcntl.h>
26 #if !defined (NO_SYS_FILE)
27 # include <sys/file.h>
28 #endif /* !NO_SYS_FILE */
30 #include <errno.h>
31 /* Not all systems declare ERRNO in errno.h... and some systems #define it! */
32 #if !defined (errno)
33 extern int errno;
34 #endif /* !errno */
36 /* These next are for filename completion. Perhaps this belongs
37 in a different place. */
38 #if !defined(__MSDOS__) && !defined(_MSC_VER)
39 #include <pwd.h>
40 #endif /* __MSDOS__ */
41 #if defined (USG) && !defined (isc386) && !defined (sgi)
42 extern struct passwd *getpwuid (), *getpwent ();
43 #endif
44 #if defined (isc386) && !defined (__STDC__) && defined (_POSIX_SOURCE)
45 extern struct passwd *getpwent ();
46 #endif
48 /* Included by <fcntl.h> on some systems, but not SCO, so include it here. */
49 #include <sys/stat.h>
51 /* System-specific feature definitions and include files. */
52 #include "rldefs.h"
54 /* Some standard library routines. */
55 #include "readline.h"
57 /* Possible values for do_replace in rl_complete_internal. */
58 #define NO_MATCH 0
59 #define SINGLE_MATCH 1
60 #define MULT_MATCH 2
62 #if !defined (strchr) && !defined (__STDC__)
63 extern char *strchr (), *strrchr ();
64 #endif /* !strchr && !__STDC__ */
66 extern char *tilde_expand ();
67 extern char *rl_copy_text ();
69 extern Function *rl_last_func;
70 extern int rl_editing_mode;
71 extern int screenwidth;
73 /* Forward declarations for functions defined and used in this file. */
74 char *filename_completion_function ();
75 char **completion_matches ();
77 static int compare_strings ();
78 static char *rl_strpbrk ();
80 #if defined (STATIC_MALLOC)
81 static char *xmalloc (), *xrealloc ();
82 #else
83 extern char *xmalloc (), *xrealloc ();
84 #endif /* STATIC_MALLOC */
86 /* If non-zero, then this is the address of a function to call when
87 completing on a directory name. The function is called with
88 the address of a string (the current directory name) as an arg. */
89 Function *rl_symbolic_link_hook = (Function *)NULL;
91 /* Non-zero means readline completion functions perform tilde expansion. */
92 int rl_complete_with_tilde_expansion = 0;
94 #define VISIBLE_STATS
96 #if defined (VISIBLE_STATS)
97 # if !defined (X_OK)
98 # define X_OK 1
99 # endif
101 static int stat_char ();
103 /* Non-zero means add an additional character to each filename displayed
104 during listing completion iff rl_filename_completion_desired which helps
105 to indicate the type of file being listed. */
106 int rl_visible_stats = 0;
107 #endif /* VISIBLE_STATS */
109 /* **************************************************************** */
110 /* */
111 /* Completion matching, from readline's point of view. */
112 /* */
113 /* **************************************************************** */
115 /* Pointer to the generator function for completion_matches ().
116 NULL means to use filename_entry_function (), the default filename
117 completer. */
118 Function *rl_completion_entry_function = (Function *)NULL;
120 /* Pointer to alternative function to create matches.
121 Function is called with TEXT, START, and END.
122 START and END are indices in RL_LINE_BUFFER saying what the boundaries
123 of TEXT are.
124 If this function exists and returns NULL then call the value of
125 rl_completion_entry_function to try to match, otherwise use the
126 array of strings returned. */
127 CPPFunction *rl_attempted_completion_function = (CPPFunction *)NULL;
129 /* Local variable states what happened during the last completion attempt. */
130 static int completion_changed_buffer = 0;
132 /* Complete the word at or before point. You have supplied the function
133 that does the initial simple matching selection algorithm (see
134 completion_matches ()). The default is to do filename completion. */
136 rl_complete (ignore, invoking_key)
137 int ignore, invoking_key;
139 if (rl_last_func == rl_complete && !completion_changed_buffer)
140 rl_complete_internal ('?');
141 else
142 rl_complete_internal (TAB);
145 /* List the possible completions. See description of rl_complete (). */
146 rl_possible_completions (ignore, invoking_key)
147 int ignore, invoking_key;
149 rl_complete_internal ('?');
152 rl_insert_completions (ignore, invoking_key)
153 int ignore, invoking_key;
155 rl_complete_internal ('*');
158 /* The user must press "y" or "n". Non-zero return means "y" pressed. */
159 get_y_or_n ()
161 int c;
163 for (;;)
165 c = rl_read_key ();
166 if (c == 'y' || c == 'Y')
167 return (1);
168 if (c == 'n' || c == 'N')
169 return (0);
170 if (c == ABORT_CHAR)
171 rl_abort ();
172 ding ();
176 /* Up to this many items will be displayed in response to a
177 possible-completions call. After that, we ask the user if
178 she is sure she wants to see them all. */
179 int rl_completion_query_items = 100;
181 /* The basic list of characters that signal a break between words for the
182 completer routine. The contents of this variable is what breaks words
183 in the shell, i.e. " \t\n\"\\'`@$><=" */
184 char *rl_basic_word_break_characters = " \t\n\"\\'`@$><=;|&{(";
186 /* The list of characters that signal a break between words for
187 rl_complete_internal. The default list is the contents of
188 rl_basic_word_break_characters. */
189 char *rl_completer_word_break_characters = (char *)NULL;
191 /* List of characters which can be used to quote a substring of the line.
192 Completion occurs on the entire substring, and within the substring
193 rl_completer_word_break_characters are treated as any other character,
194 unless they also appear within this list. */
195 char *rl_completer_quote_characters = (char *)NULL;
197 /* List of characters that are word break characters, but should be left
198 in TEXT when it is passed to the completion function. The shell uses
199 this to help determine what kind of completing to do. */
200 char *rl_special_prefixes = (char *)NULL;
202 /* If non-zero, then disallow duplicates in the matches. */
203 int rl_ignore_completion_duplicates = 1;
205 /* Non-zero means that the results of the matches are to be treated
206 as filenames. This is ALWAYS zero on entry, and can only be changed
207 within a completion entry finder function. */
208 int rl_filename_completion_desired = 0;
210 /* This function, if defined, is called by the completer when real
211 filename completion is done, after all the matching names have been
212 generated. It is passed a (char**) known as matches in the code below.
213 It consists of a NULL-terminated array of pointers to potential
214 matching strings. The 1st element (matches[0]) is the maximal
215 substring that is common to all matches. This function can re-arrange
216 the list of matches as required, but all elements of the array must be
217 free()'d if they are deleted. The main intent of this function is
218 to implement FIGNORE a la SunOS csh. */
219 Function *rl_ignore_some_completions_function = (Function *)NULL;
221 #if defined (SHELL)
222 /* A function to strip quotes that are not protected by backquotes. It
223 allows single quotes to appear within double quotes, and vice versa.
224 It should be smarter. It's fairly shell-specific, hence the SHELL
225 definition wrapper. */
226 static char *
227 _delete_quotes (text)
228 char *text;
230 char *ret, *p, *r;
231 int l, quoted;
233 l = strlen (text);
234 ret = xmalloc (l + 1);
235 for (quoted = 0, p = text, r = ret; p && *p; p++)
237 /* Allow backslash-quoted characters to pass through unscathed. */
238 if (*p == '\\')
239 continue;
240 /* Close quote. */
241 if (quoted && *p == quoted)
243 quoted = 0;
244 continue;
246 /* Open quote. */
247 if (quoted == 0 && (*p == '\'' || *p == '"'))
249 quoted = *p;
250 continue;
252 *r++ = *p;
254 *r = '\0';
255 return ret;
257 #endif /* SHELL */
259 /* Complete the word at or before point.
260 WHAT_TO_DO says what to do with the completion.
261 `?' means list the possible completions.
262 TAB means do standard completion.
263 `*' means insert all of the possible completions. */
264 rl_complete_internal (what_to_do)
265 int what_to_do;
267 char **matches;
268 Function *our_func;
269 int start, scan, end, delimiter = 0, pass_next;
270 char *text, *saved_line_buffer;
271 char *replacement;
272 char quote_char = '\0';
273 #if defined (SHELL)
274 int found_quote = 0;
275 #endif
277 if (rl_line_buffer)
278 saved_line_buffer = savestring (rl_line_buffer);
279 else
280 saved_line_buffer = (char *)NULL;
282 if (rl_completion_entry_function)
283 our_func = rl_completion_entry_function;
284 else
285 our_func = (Function *)filename_completion_function;
287 /* Only the completion entry function can change this. */
288 rl_filename_completion_desired = 0;
290 /* We now look backwards for the start of a filename/variable word. */
291 end = rl_point;
293 if (rl_point)
295 if (rl_completer_quote_characters)
297 /* We have a list of characters which can be used in pairs to
298 quote substrings for the completer. Try to find the start
299 of an unclosed quoted substring. */
300 /* FOUND_QUOTE is set so we know what kind of quotes we found. */
301 for (scan = pass_next = 0; scan < end; scan++)
303 if (pass_next)
305 pass_next = 0;
306 continue;
309 if (rl_line_buffer[scan] == '\\')
311 pass_next = 1;
312 continue;
315 if (quote_char != '\0')
317 /* Ignore everything until the matching close quote char. */
318 if (rl_line_buffer[scan] == quote_char)
320 /* Found matching close. Abandon this substring. */
321 quote_char = '\0';
322 rl_point = end;
325 else if (strchr (rl_completer_quote_characters, rl_line_buffer[scan]))
327 /* Found start of a quoted substring. */
328 quote_char = rl_line_buffer[scan];
329 rl_point = scan + 1;
330 #if defined (SHELL)
331 if (quote_char == '\'')
332 found_quote |= 1;
333 else if (quote_char == '"')
334 found_quote |= 2;
335 #endif
340 if (rl_point == end)
342 int quoted = 0;
343 /* We didn't find an unclosed quoted substring up which to do
344 completion, so use the word break characters to find the
345 substring on which to complete. */
346 while (--rl_point)
348 #if defined (SHELL)
349 /* Don't let word break characters in quoted substrings break
350 words for the completer. */
351 if (found_quote)
353 if (strchr (rl_completer_quote_characters, rl_line_buffer[rl_point]))
355 quoted = !quoted;
356 continue;
358 if (quoted)
359 continue;
361 #endif /* SHELL */
362 if (strchr (rl_completer_word_break_characters, rl_line_buffer[rl_point]))
363 break;
367 /* If we are at a word break, then advance past it. */
368 if (strchr (rl_completer_word_break_characters, rl_line_buffer[rl_point]))
370 /* If the character that caused the word break was a quoting
371 character, then remember it as the delimiter. */
372 if (strchr ("\"'", rl_line_buffer[rl_point]) && (end - rl_point) > 1)
373 delimiter = rl_line_buffer[rl_point];
375 /* If the character isn't needed to determine something special
376 about what kind of completion to perform, then advance past it. */
377 if (!rl_special_prefixes ||
378 !strchr (rl_special_prefixes, rl_line_buffer[rl_point]))
379 rl_point++;
383 /* At this point, we know we have an open quote if quote_char != '\0'. */
384 start = rl_point;
385 rl_point = end;
386 text = rl_copy_text (start, end);
388 /* If the user wants to TRY to complete, but then wants to give
389 up and use the default completion function, they set the
390 variable rl_attempted_completion_function. */
391 if (rl_attempted_completion_function)
393 matches = (*rl_attempted_completion_function) (text, start, end);
395 if (matches)
397 /* XXX - This is questionable code. - XXX */
398 if (matches == (char **)-1)
399 matches = (char **)NULL;
400 our_func = (Function *)NULL;
401 goto after_usual_completion;
405 #if defined (SHELL)
406 /* Beware -- we're stripping the quotes here. Do this only if we know
407 we are doing filename completion. */
408 if (found_quote && our_func == (Function *)filename_completion_function)
410 /* delete single and double quotes */
411 replacement = _delete_quotes (text);
412 free (text);
413 text = replacement;
414 replacement = (char *)0;
416 #endif /* SHELL */
418 matches = completion_matches (text, our_func);
420 after_usual_completion:
421 free (text);
423 if (!matches)
424 ding ();
425 else
427 register int i;
429 /* It seems to me that in all the cases we handle we would like
430 to ignore duplicate possiblilities. Scan for the text to
431 insert being identical to the other completions. */
432 if (rl_ignore_completion_duplicates)
434 char *lowest_common;
435 int j, newlen = 0;
436 char dead_slot;
438 /* Sort the items. */
439 /* It is safe to sort this array, because the lowest common
440 denominator found in matches[0] will remain in place. */
441 for (i = 0; matches[i]; i++);
442 qsort (matches, i, sizeof (char *), compare_strings);
444 /* Remember the lowest common denominator for it may be unique. */
445 lowest_common = savestring (matches[0]);
447 for (i = 0; matches[i + 1]; i++)
449 if (strcmp (matches[i], matches[i + 1]) == 0)
451 free (matches[i]);
452 matches[i] = (char *)&dead_slot;
454 else
455 newlen++;
458 /* We have marked all the dead slots with (char *)&dead_slot.
459 Copy all the non-dead entries into a new array. */
461 char **temp_array =
462 (char **)xmalloc ((3 + newlen) * sizeof (char *));
464 for (i = 1, j = 1; matches[i]; i++)
466 if (matches[i] != (char *)&dead_slot)
467 temp_array[j++] = matches[i];
470 temp_array[j] = (char *)NULL;
472 if (matches[0] != (char *)&dead_slot)
473 free (matches[0]);
475 free (matches);
477 matches = temp_array;
480 /* Place the lowest common denominator back in [0]. */
481 matches[0] = lowest_common;
483 /* If there is one string left, and it is identical to the
484 lowest common denominator, then the LCD is the string to
485 insert. */
486 if (j == 2 && strcmp (matches[0], matches[1]) == 0)
488 free (matches[1]);
489 matches[1] = (char *)NULL;
493 switch (what_to_do)
495 case TAB:
496 /* If we are matching filenames, then here is our chance to
497 do clever processing by re-examining the list. Call the
498 ignore function with the array as a parameter. It can
499 munge the array, deleting matches as it desires. */
500 if (rl_ignore_some_completions_function &&
501 our_func == (Function *)filename_completion_function)
502 (void)(*rl_ignore_some_completions_function)(matches);
504 /* If we are doing completion on quoted substrings, and any matches
505 contain any of the completer_word_break_characters, then auto-
506 matically prepend the substring with a quote character (just pick
507 the first one from the list of such) if it does not already begin
508 with a quote string. FIXME: Need to remove any such automatically
509 inserted quote character when it no longer is necessary, such as
510 if we change the string we are completing on and the new set of
511 matches don't require a quoted substring. */
512 replacement = matches[0];
514 if (matches[0] && rl_completer_quote_characters && !quote_char &&
515 rl_filename_completion_desired)
517 int do_replace;
519 do_replace = NO_MATCH;
521 /* If there is a single match, see if we need to quote it.
522 This also checks whether the common prefix of several
523 matches needs to be quoted. If the common prefix should
524 not be checked, add !matches[1] to the if clause. */
525 if (rl_strpbrk (matches[0], rl_completer_word_break_characters))
526 do_replace = matches[1] ? MULT_MATCH : SINGLE_MATCH;
528 if (do_replace != NO_MATCH)
530 #if defined (SHELL)
531 /* XXX - experimental */
532 /* Quote the replacement, since we found an
533 embedded word break character in a potential
534 match. */
535 char *rtext, *mtext;
536 int rlen;
537 extern char *double_quote (); /* in builtins/common.c */
539 /* If DO_REPLACE == MULT_MATCH, it means that there is
540 more than one match. In this case, we do not add
541 the closing quote or attempt to perform tilde
542 expansion. If DO_REPLACE == SINGLE_MATCH, we try
543 to perform tilde expansion, because double quotes
544 inhibit tilde expansion by the shell. */
546 mtext = matches[0];
547 if (mtext[0] == '~' && do_replace == SINGLE_MATCH)
548 mtext = tilde_expand (matches[0]);
549 rtext = double_quote (mtext);
550 if (mtext != matches[0])
551 free (mtext);
553 rlen = strlen (rtext);
554 replacement = (char *)alloca (rlen + 1);
555 strcpy (replacement, rtext);
556 if (do_replace == MULT_MATCH)
557 replacement[rlen - 1] = '\0';
558 free (rtext);
559 #else /* !SHELL */
560 /* Found an embedded word break character in a potential
561 match, so we need to prepend a quote character if we
562 are replacing the completion string. */
563 replacement = (char *)alloca (strlen (matches[0]) + 2);
564 quote_char = *rl_completer_quote_characters;
565 *replacement = quote_char;
566 strcpy (replacement + 1, matches[0]);
567 #endif /* SHELL */
571 if (replacement)
573 rl_delete_text (start, rl_point);
574 rl_point = start;
575 rl_insert_text (replacement);
578 /* If there are more matches, ring the bell to indicate.
579 If this was the only match, and we are hacking files,
580 check the file to see if it was a directory. If so,
581 add a '/' to the name. If not, and we are at the end
582 of the line, then add a space. */
583 if (matches[1])
585 if (rl_editing_mode != vi_mode)
586 ding (); /* There are other matches remaining. */
588 else
590 char temp_string[4];
591 int temp_string_index = 0;
593 if (quote_char)
594 temp_string[temp_string_index++] = quote_char;
596 temp_string[temp_string_index++] = delimiter ? delimiter : ' ';
597 temp_string[temp_string_index++] = '\0';
599 if (rl_filename_completion_desired)
601 struct stat finfo;
602 char *filename = tilde_expand (matches[0]);
604 if ((stat (filename, &finfo) == 0) &&
605 S_ISDIR (finfo.st_mode))
607 if (rl_line_buffer[rl_point] != '/')
608 rl_insert_text ("/");
610 else
612 if (rl_point == rl_end)
613 rl_insert_text (temp_string);
615 free (filename);
617 else
619 if (rl_point == rl_end)
620 rl_insert_text (temp_string);
623 break;
625 case '*':
627 int i = 1;
629 rl_delete_text (start, rl_point);
630 rl_point = start;
631 rl_begin_undo_group ();
632 if (matches[1])
634 while (matches[i])
636 rl_insert_text (matches[i++]);
637 rl_insert_text (" ");
640 else
642 rl_insert_text (matches[0]);
643 rl_insert_text (" ");
645 rl_end_undo_group ();
647 break;
649 case '?':
651 int len, count, limit, max = 0;
652 int j, k, l;
654 /* Handle simple case first. What if there is only one answer? */
655 if (!matches[1])
657 char *temp = (char *)NULL;
659 if (rl_filename_completion_desired)
660 temp = strrchr (matches[0], '/');
662 if (!temp)
663 temp = matches[0];
664 else
665 temp++;
667 crlf ();
668 fprintf (rl_outstream, "%s", temp);
669 #if defined (VISIBLE_STATS)
670 if (rl_filename_completion_desired && rl_visible_stats)
672 int extension_char;
674 extension_char = stat_char (matches[0]);
675 if (extension_char)
676 putc (extension_char, rl_outstream);
678 #endif /* VISIBLE_STATS */
679 crlf ();
680 goto restart;
683 /* There is more than one answer. Find out how many there are,
684 and find out what the maximum printed length of a single entry
685 is. */
686 for (i = 1; matches[i]; i++)
688 char *temp;
689 int name_length;
691 /* If we are hacking filenames, then only count the characters
692 after the last slash in the pathname. */
693 if (rl_filename_completion_desired)
694 temp = strrchr (matches[i], '/');
695 else
696 temp = (char *)NULL;
698 if (!temp)
699 temp = matches[i];
700 else
701 temp++;
703 name_length = strlen (temp);
705 if (name_length > max)
706 max = name_length;
709 len = i - 1;
711 /* If there are many items, then ask the user if she
712 really wants to see them all. */
713 if (len >= rl_completion_query_items)
715 crlf ();
716 fprintf (rl_outstream,
717 "There are %d possibilities. Do you really", len);
718 crlf ();
719 fprintf (rl_outstream, "wish to see them all? (y or n)");
720 fflush (rl_outstream);
721 if (!get_y_or_n ())
723 crlf ();
724 goto restart;
728 /* How many items of MAX length can we fit in the screen window? */
729 max += 2;
730 limit = screenwidth / max;
731 if (limit != 1 && (limit * max == screenwidth))
732 limit--;
734 /* Avoid a possible floating exception. If max > screenwidth,
735 limit will be 0 and a divide-by-zero fault will result. */
736 if (limit == 0)
737 limit = 1;
739 /* How many iterations of the printing loop? */
740 count = (len + (limit - 1)) / limit;
742 /* Watch out for special case. If LEN is less than LIMIT, then
743 just do the inner printing loop. */
744 if (len < limit)
745 count = 1;
747 /* Sort the items if they are not already sorted. */
748 if (!rl_ignore_completion_duplicates)
749 qsort (matches, len, sizeof (char *), compare_strings);
751 /* Print the sorted items, up-and-down alphabetically, like
752 ls might. */
753 crlf ();
755 for (i = 1; i < count + 1; i++)
757 for (j = 0, l = i; j < limit; j++)
759 if (l > len || !matches[l])
761 break;
763 else
765 char *temp = (char *)NULL;
766 int printed_length;
768 if (rl_filename_completion_desired)
769 temp = strrchr (matches[l], '/');
771 if (!temp)
772 temp = matches[l];
773 else
774 temp++;
776 printed_length = strlen (temp);
777 fprintf (rl_outstream, "%s", temp);
779 #if defined (VISIBLE_STATS)
780 if (rl_filename_completion_desired &&
781 rl_visible_stats)
783 int extension_char;
785 extension_char = stat_char (matches[l]);
787 if (extension_char)
789 putc (extension_char, rl_outstream);
790 printed_length++;
793 #endif /* VISIBLE_STATS */
795 if (j + 1 < limit)
797 for (k = 0; k < max - printed_length; k++)
798 putc (' ', rl_outstream);
801 l += count;
803 crlf ();
805 restart:
807 rl_on_new_line ();
809 break;
811 default:
812 fprintf (stderr, "\r\nreadline: bad value for what_to_do in rl_complete\n");
813 abort ();
816 for (i = 0; matches[i]; i++)
817 free (matches[i]);
818 free (matches);
821 /* Check to see if the line has changed through all of this manipulation. */
822 if (saved_line_buffer)
824 if (strcmp (rl_line_buffer, saved_line_buffer) != 0)
825 completion_changed_buffer = 1;
826 else
827 completion_changed_buffer = 0;
829 free (saved_line_buffer);
833 #if defined (VISIBLE_STATS)
834 /* Return the character which best describes FILENAME.
835 `@' for symbolic links
836 `/' for directories
837 `*' for executables
838 `=' for sockets */
839 static int
840 stat_char (filename)
841 char *filename;
843 struct stat finfo;
844 int character = 0;
846 if (stat (filename, &finfo) == -1)
847 return (character);
849 if (S_ISDIR (finfo.st_mode))
850 character = '/';
851 #if defined (S_ISLNK)
852 else if (S_ISLNK (finfo.st_mode))
853 character = '@';
854 #endif /* S_ISLNK */
855 #if defined (S_ISSOCK)
856 else if (S_ISSOCK (finfo.st_mode))
857 character = '=';
858 #endif /* S_ISSOCK */
859 else if (S_ISREG (finfo.st_mode))
861 if (access (filename, X_OK) == 0)
862 character = '*';
864 return (character);
866 #endif /* VISIBLE_STATS */
868 /* Stupid comparison routine for qsort () ing strings. */
869 static int
870 compare_strings (s1, s2)
871 char **s1, **s2;
873 return (strcmp (*s1, *s2));
876 /* A completion function for usernames.
877 TEXT contains a partial username preceded by a random
878 character (usually `~'). */
879 char *
880 username_completion_function (text, state)
881 int state;
882 char *text;
884 #if defined (MINIMAL)
885 return (char *)NULL;
886 #else /* !MINIMAL */
887 static char *username = (char *)NULL;
888 static struct passwd *entry;
889 static int namelen, first_char, first_char_loc;
891 if (!state)
893 if (username)
894 free (username);
896 first_char = *text;
898 if (first_char == '~')
899 first_char_loc = 1;
900 else
901 first_char_loc = 0;
903 username = savestring (&text[first_char_loc]);
904 namelen = strlen (username);
905 setpwent ();
908 while (entry = getpwent ())
910 if (strncmp (username, entry->pw_name, namelen) == 0)
911 break;
914 if (!entry)
916 endpwent ();
917 return ((char *)NULL);
919 else
921 char *value = (char *)xmalloc (2 + strlen (entry->pw_name));
923 *value = *text;
925 strcpy (value + first_char_loc, entry->pw_name);
927 if (first_char == '~')
928 rl_filename_completion_desired = 1;
930 return (value);
932 #endif /* !MINIMAL */
935 /* **************************************************************** */
936 /* */
937 /* Completion */
938 /* */
939 /* **************************************************************** */
941 /* Non-zero means that case is not significant in completion. */
942 int completion_case_fold = 0;
944 /* Return an array of (char *) which is a list of completions for TEXT.
945 If there are no completions, return a NULL pointer.
946 The first entry in the returned array is the substitution for TEXT.
947 The remaining entries are the possible completions.
948 The array is terminated with a NULL pointer.
950 ENTRY_FUNCTION is a function of two args, and returns a (char *).
951 The first argument is TEXT.
952 The second is a state argument; it should be zero on the first call, and
953 non-zero on subsequent calls. It returns a NULL pointer to the caller
954 when there are no more matches.
956 char **
957 completion_matches (text, entry_function)
958 char *text;
959 CPFunction *entry_function;
961 /* Number of slots in match_list. */
962 int match_list_size;
964 /* The list of matches. */
965 char **match_list =
966 (char **)xmalloc (((match_list_size = 10) + 1) * sizeof (char *));
968 /* Number of matches actually found. */
969 int matches = 0;
971 /* Temporary string binder. */
972 char *string;
974 match_list[1] = (char *)NULL;
976 while (string = (*entry_function) (text, matches))
978 if (matches + 1 == match_list_size)
979 match_list = (char **)xrealloc
980 (match_list, ((match_list_size += 10) + 1) * sizeof (char *));
982 match_list[++matches] = string;
983 match_list[matches + 1] = (char *)NULL;
986 /* If there were any matches, then look through them finding out the
987 lowest common denominator. That then becomes match_list[0]. */
988 if (matches)
990 register int i = 1;
991 int low = 100000; /* Count of max-matched characters. */
993 /* If only one match, just use that. */
994 if (matches == 1)
996 match_list[0] = match_list[1];
997 match_list[1] = (char *)NULL;
999 else
1001 /* Otherwise, compare each member of the list with
1002 the next, finding out where they stop matching. */
1004 while (i < matches)
1006 register int c1, c2, si;
1008 if (completion_case_fold)
1010 for (si = 0;
1011 (c1 = to_lower(match_list[i][si])) &&
1012 (c2 = to_lower(match_list[i + 1][si]));
1013 si++)
1014 if (c1 != c2) break;
1016 else
1018 for (si = 0;
1019 (c1 = match_list[i][si]) &&
1020 (c2 = match_list[i + 1][si]);
1021 si++)
1022 if (c1 != c2) break;
1025 if (low > si) low = si;
1026 i++;
1028 match_list[0] = (char *)xmalloc (low + 1);
1029 strncpy (match_list[0], match_list[1], low);
1030 match_list[0][low] = '\0';
1033 else /* There were no matches. */
1035 free (match_list);
1036 match_list = (char **)NULL;
1038 return (match_list);
1041 /* Okay, now we write the entry_function for filename completion. In the
1042 general case. Note that completion in the shell is a little different
1043 because of all the pathnames that must be followed when looking up the
1044 completion for a command. */
1045 char *
1046 filename_completion_function (text, state)
1047 int state;
1048 char *text;
1050 #ifndef WIN32
1051 static DIR *directory;
1052 static char *filename = (char *)NULL;
1053 static char *dirname = (char *)NULL;
1054 static char *users_dirname = (char *)NULL;
1055 static int filename_len;
1057 dirent *entry = (dirent *)NULL;
1059 /* If we don't have any state, then do some initialization. */
1060 if (!state)
1062 char *temp;
1064 if (dirname) free (dirname);
1065 if (filename) free (filename);
1066 if (users_dirname) free (users_dirname);
1068 filename = savestring (text);
1069 if (!*text) text = ".";
1070 dirname = savestring (text);
1072 temp = strrchr (dirname, '/');
1074 if (temp)
1076 strcpy (filename, ++temp);
1077 *temp = '\0';
1079 else
1080 strcpy (dirname, ".");
1082 /* We aren't done yet. We also support the "~user" syntax. */
1084 /* Save the version of the directory that the user typed. */
1085 users_dirname = savestring (dirname);
1087 char *temp_dirname;
1089 temp_dirname = tilde_expand (dirname);
1090 free (dirname);
1091 dirname = temp_dirname;
1093 if (rl_symbolic_link_hook)
1094 (*rl_symbolic_link_hook) (&dirname);
1096 directory = opendir (dirname);
1097 filename_len = strlen (filename);
1099 rl_filename_completion_desired = 1;
1102 /* At this point we should entertain the possibility of hacking wildcarded
1103 filenames, like /usr/man/man<WILD>/te<TAB>. If the directory name
1104 contains globbing characters, then build an array of directories, and
1105 then map over that list while completing. */
1106 /* *** UNIMPLEMENTED *** */
1108 /* Now that we have some state, we can read the directory. */
1110 while (directory && (entry = readdir (directory)))
1112 /* Special case for no filename.
1113 All entries except "." and ".." match. */
1114 if (!filename_len)
1116 if ((strcmp (entry->d_name, ".") != 0) &&
1117 (strcmp (entry->d_name, "..") != 0))
1118 break;
1120 else
1122 /* Otherwise, if these match upto the length of filename, then
1123 it is a match. */
1124 if (((int)D_NAMLEN (entry)) >= filename_len &&
1125 (entry->d_name[0] == filename[0]) &&
1126 (strncmp (filename, entry->d_name, filename_len) == 0))
1128 break;
1133 if (!entry)
1135 if (directory)
1137 closedir (directory);
1138 directory = (DIR *)NULL;
1141 if (dirname)
1143 free (dirname);
1144 dirname = (char *)NULL;
1146 if (filename)
1148 free (filename);
1149 filename = (char *)NULL;
1151 if (users_dirname)
1153 free (users_dirname);
1154 users_dirname = (char *)NULL;
1157 return (char *)NULL;
1159 else
1161 char *temp;
1163 if (dirname && (strcmp (dirname, ".") != 0))
1165 if (rl_complete_with_tilde_expansion && *users_dirname == '~')
1167 int dirlen = strlen (dirname);
1168 temp = (char *)xmalloc (2 + dirlen + D_NAMLEN (entry));
1169 strcpy (temp, dirname);
1170 /* Canonicalization cuts off any final slash present. We need
1171 to add it back. */
1172 if (dirname[dirlen - 1] != '/')
1174 temp[dirlen] = '/';
1175 temp[dirlen + 1] = '\0';
1178 else
1180 temp = (char *)
1181 xmalloc (1 + strlen (users_dirname) + D_NAMLEN (entry));
1182 strcpy (temp, users_dirname);
1185 strcat (temp, entry->d_name);
1187 else
1189 temp = (savestring (entry->d_name));
1191 return (temp);
1193 #endif
1196 /* A function for simple tilde expansion. */
1198 rl_tilde_expand (ignore, key)
1199 int ignore, key;
1201 register int start, end;
1202 char *homedir;
1204 end = rl_point;
1205 start = end - 1;
1207 if (rl_point == rl_end && rl_line_buffer[rl_point] == '~')
1209 homedir = tilde_expand ("~");
1210 goto insert;
1212 else if (rl_line_buffer[start] != '~')
1214 for (; !whitespace (rl_line_buffer[start]) && start >= 0; start--);
1215 start++;
1218 end = start;
1221 end++;
1223 while (!whitespace (rl_line_buffer[end]) && end < rl_end);
1225 if (whitespace (rl_line_buffer[end]) || end >= rl_end)
1226 end--;
1228 /* If the first character of the current word is a tilde, perform
1229 tilde expansion and insert the result. If not a tilde, do
1230 nothing. */
1231 if (rl_line_buffer[start] == '~')
1233 char *temp;
1234 int len;
1236 len = end - start + 1;
1237 temp = (char *)alloca (len + 1);
1238 strncpy (temp, rl_line_buffer + start, len);
1239 temp[len] = '\0';
1240 homedir = tilde_expand (temp);
1242 insert:
1243 rl_begin_undo_group ();
1244 rl_delete_text (start, end + 1);
1245 rl_point = start;
1246 rl_insert_text (homedir);
1247 rl_end_undo_group ();
1250 return (0);
1253 /* Find the first occurrence in STRING1 of any character from STRING2.
1254 Return a pointer to the character in STRING1. */
1255 static char *
1256 rl_strpbrk (string1, string2)
1257 char *string1, *string2;
1259 register char *scan;
1261 for (; *string1; string1++)
1263 for (scan = string2; *scan; scan++)
1265 if (*string1 == *scan)
1267 return (string1);
1271 return ((char *)NULL);
1274 #if defined (STATIC_MALLOC)
1276 /* **************************************************************** */
1277 /* */
1278 /* xmalloc and xrealloc () */
1279 /* */
1280 /* **************************************************************** */
1282 static void memory_error_and_abort ();
1284 static char *
1285 xmalloc (bytes)
1286 int bytes;
1288 char *temp = (char *)malloc (bytes);
1290 if (!temp)
1291 memory_error_and_abort ();
1292 return (temp);
1295 static char *
1296 xrealloc (pointer, bytes)
1297 char *pointer;
1298 int bytes;
1300 char *temp;
1302 if (!pointer)
1303 temp = (char *)malloc (bytes);
1304 else
1305 temp = (char *)realloc (pointer, bytes);
1307 if (!temp)
1308 memory_error_and_abort ();
1310 return (temp);
1313 static void
1314 memory_error_and_abort ()
1316 fprintf (stderr, "readline: Out of virtual memory!\n");
1317 abort ();
1319 #endif /* STATIC_MALLOC */