1 /* bashline.c -- Bash's interface to the readline library. */
3 /* Copyright (C) 1987,1991 Free Software Foundation, Inc.
5 This file is part of GNU Bash, the Bourne Again SHell.
7 Bash is free software; you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 1, or (at your option)
12 Bash is distributed in the hope that it will be useful, but WITHOUT
13 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
15 License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Bash; see the file COPYING. If not, write to the Free
19 Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */
23 #if defined (READLINE)
25 #include "bashtypes.h"
26 #include "posixstat.h"
28 #if defined (HAVE_UNISTD_H)
38 #include "execute_cmd.h"
40 #include "builtins/common.h"
41 #include <readline/rlconf.h>
42 #include <readline/readline.h>
43 #include <readline/history.h>
45 #include <glob/glob.h>
51 #if defined (BRACE_COMPLETION)
52 extern void bash_brace_completion ();
53 #endif /* BRACE_COMPLETION */
55 /* Functions bound to keys in Readline for Bash users. */
56 static void shell_expand_line ();
57 static void display_shell_version (), operate_and_get_next ();
58 static void history_expand_line (), bash_ignore_filenames ();
60 static void alias_expand_line ();
62 static void history_and_alias_expand_line ();
63 static void cleanup_expansion_error (), set_up_new_line ();
65 /* Helper functions for Readline. */
66 static int bash_directory_completion_hook ();
67 static void filename_completion_ignore ();
68 static void bash_push_line ();
70 static char **attempt_shell_completion ();
71 static char *variable_completion_function ();
72 static char *hostname_completion_function ();
73 static char *command_word_completion_function ();
74 static char *command_subst_completion_function ();
75 static void dynamic_complete_history ();
77 static char *glob_complete_word ();
78 static void bash_glob_expand_word ();
79 static void bash_glob_list_expansions ();
81 static void snarf_hosts_from_file (), add_host_name ();
83 static char *bash_dequote_filename ();
84 static char *bash_quote_filename ();
87 static int posix_edit_macros ();
90 /* Variables used here but defined in other files. */
91 extern int posixly_correct, no_symbolic_links;
92 extern int rl_explicit_arg;
93 extern char *current_prompt_string, *ps1_prompt;
94 extern STRING_INT_ALIST word_token_alist[];
95 extern Function *rl_last_func;
96 extern int rl_filename_completion_desired;
98 /* Helper functions from subst.c */
99 extern int char_is_quoted ();
100 extern int unclosed_pair ();
102 /* SPECIFIC_COMPLETION_FUNCTIONS specifies that we have individual
103 completion functions which indicate what type of completion should be
104 done (at or before point) that can be bound to key sequences with
105 the readline library. */
106 #define SPECIFIC_COMPLETION_FUNCTIONS
108 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
109 static void bash_specific_completion ();
110 static void bash_complete_filename (), bash_possible_filename_completions ();
111 static void bash_complete_filename_internal ();
112 static void bash_complete_username (), bash_possible_username_completions ();
113 static void bash_complete_username_internal ();
114 static void bash_complete_hostname (), bash_possible_hostname_completions ();
115 static void bash_complete_hostname_internal ();
116 static void bash_complete_variable (), bash_possible_variable_completions ();
117 static void bash_complete_variable_internal ();
118 static void bash_complete_command (), bash_possible_command_completions ();
119 static void bash_complete_command_internal ();
120 #endif /* SPECIFIC_COMPLETION_FUNCTIONS */
122 #if defined (VI_MODE)
123 static void vi_edit_and_execute_command ();
126 /* Non-zero once initalize_readline () has been called. */
127 int bash_readline_initialized = 0;
129 /* If non-zero, we do hostname completion, breaking words at `@' and
130 trying to complete the stuff after the `@' from our own internal
132 int perform_hostname_completion = 1;
134 static char *bash_completer_word_break_characters = " \t\n\"'@><=;|&(:";
135 static char *bash_nohostname_word_break_characters = " \t\n\"'><=;|&(:";
137 static Function *old_rl_startup_hook = (Function *) NULL;
139 /* What kind of quoting is performed by bash_quote_filename:
140 COMPLETE_DQUOTE = double-quoting the filename
141 COMPLETE_SQUOTE = single_quoting the filename
142 COMPLETE_BSQUOTE = backslash-quoting special chars in the filename
144 #define COMPLETE_DQUOTE 1
145 #define COMPLETE_SQUOTE 2
146 #define COMPLETE_BSQUOTE 3
147 static int completion_quoting_style = COMPLETE_BSQUOTE;
149 /* Change the readline VI-mode keymaps into or out of Posix.2 compliance.
150 Called when the shell is put into or out of `posix' mode. */
152 posix_readline_initialize (on_or_off)
156 rl_variable_bind ("comment-begin", "#");
157 #if defined (VI_MODE)
158 rl_bind_key_in_map (CTRL('I'), on_or_off ? rl_insert : rl_complete, vi_insertion_keymap);
163 enable_hostname_completion (on_or_off)
168 perform_hostname_completion = 1;
169 rl_special_prefixes = "$@";
170 rl_completer_word_break_characters = bash_completer_word_break_characters;
174 perform_hostname_completion = 0;
175 rl_special_prefixes = "$";
176 rl_completer_word_break_characters = bash_nohostname_word_break_characters;
180 /* Called once from parse.y if we are going to use readline. */
182 initialize_readline ()
184 if (bash_readline_initialized)
187 rl_terminal_name = get_string_value ("TERM");
189 rl_outstream = stderr;
191 /* Allow conditional parsing of the ~/.inputrc file. */
192 rl_readline_name = "Bash";
194 /* Bind up our special shell functions. */
195 rl_add_defun ("shell-expand-line", (Function *)shell_expand_line, -1);
196 rl_bind_key_in_map (CTRL('E'), (Function *)shell_expand_line, emacs_meta_keymap);
198 /* Bind up our special shell functions. */
199 rl_add_defun ("history-expand-line", (Function *)history_expand_line, -1);
200 rl_bind_key_in_map ('^', (Function *)history_expand_line, emacs_meta_keymap);
203 rl_add_defun ("alias-expand-line", (Function *)alias_expand_line, -1);
204 rl_add_defun ("history-and-alias-expand-line", (Function *)history_and_alias_expand_line, -1);
207 /* Backwards compatibility. */
208 rl_add_defun ("insert-last-argument", rl_yank_last_arg, -1);
211 ("operate-and-get-next", (Function *)operate_and_get_next, CTRL('O'));
214 ("display-shell-version", (Function *)display_shell_version, -1);
216 (CTRL ('V'), (Function *)display_shell_version, emacs_ctlx_keymap);
218 /* In Bash, the user can switch editing modes with "set -o [vi emacs]",
219 so it is not necessary to allow C-M-j for context switching. Turn
220 off this occasionally confusing behaviour. */
221 rl_unbind_key_in_map (CTRL('J'), emacs_meta_keymap);
222 rl_unbind_key_in_map (CTRL('M'), emacs_meta_keymap);
223 #if defined (VI_MODE)
224 rl_unbind_key_in_map (CTRL('E'), vi_movement_keymap);
227 #if defined (BRACE_COMPLETION)
228 rl_add_defun ("complete-into-braces", bash_brace_completion, -1);
229 rl_bind_key_in_map ('{', bash_brace_completion, emacs_meta_keymap);
230 #endif /* BRACE_COMPLETION */
232 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
233 rl_add_defun ("complete-filename", bash_complete_filename, -1);
234 rl_bind_key_in_map ('/', bash_complete_filename, emacs_meta_keymap);
235 rl_add_defun ("possible-filename-completions",
236 bash_possible_filename_completions, -1);
237 rl_bind_key_in_map ('/', bash_possible_filename_completions, emacs_ctlx_keymap);
239 rl_add_defun ("complete-username", bash_complete_username, -1);
240 rl_bind_key_in_map ('~', bash_complete_username, emacs_meta_keymap);
241 rl_add_defun ("possible-username-completions",
242 bash_possible_username_completions, -1);
243 rl_bind_key_in_map ('~', bash_possible_username_completions, emacs_ctlx_keymap);
245 rl_add_defun ("complete-hostname", bash_complete_hostname, -1);
246 rl_bind_key_in_map ('@', bash_complete_hostname, emacs_meta_keymap);
247 rl_add_defun ("possible-hostname-completions",
248 bash_possible_hostname_completions, -1);
249 rl_bind_key_in_map ('@', bash_possible_hostname_completions, emacs_ctlx_keymap);
251 rl_add_defun ("complete-variable", bash_complete_variable, -1);
252 rl_bind_key_in_map ('$', bash_complete_variable, emacs_meta_keymap);
253 rl_add_defun ("possible-variable-completions",
254 bash_possible_variable_completions, -1);
255 rl_bind_key_in_map ('$', bash_possible_variable_completions, emacs_ctlx_keymap);
257 rl_add_defun ("complete-command", bash_complete_command, -1);
258 rl_bind_key_in_map ('!', bash_complete_command, emacs_meta_keymap);
259 rl_add_defun ("possible-command-completions",
260 bash_possible_command_completions, -1);
261 rl_bind_key_in_map ('!', bash_possible_command_completions, emacs_ctlx_keymap);
263 rl_add_defun ("glob-expand-word", bash_glob_expand_word, -1);
264 rl_add_defun ("glob-list-expansions", bash_glob_list_expansions, -1);
265 rl_bind_key_in_map ('*', bash_glob_expand_word, emacs_ctlx_keymap);
266 rl_bind_key_in_map ('g', bash_glob_list_expansions, emacs_ctlx_keymap);
268 #endif /* SPECIFIC_COMPLETION_FUNCTIONS */
270 rl_add_defun ("dynamic-complete-history", dynamic_complete_history, -1);
271 rl_bind_key_in_map (TAB, dynamic_complete_history, emacs_meta_keymap);
273 /* Tell the completer that we want a crack first. */
274 rl_attempted_completion_function = (CPPFunction *)attempt_shell_completion;
276 /* Tell the completer that we might want to follow symbolic links or
277 do other expansion on directory names. */
278 rl_directory_completion_hook = bash_directory_completion_hook;
280 /* Tell the filename completer we want a chance to ignore some names. */
281 rl_ignore_some_completions_function = (Function *)filename_completion_ignore;
283 #if defined (VI_MODE)
284 rl_bind_key_in_map ('v', vi_edit_and_execute_command, vi_movement_keymap);
286 rl_bind_key_in_map ('@', posix_edit_macros, vi_movement_keymap);
290 rl_completer_quote_characters = "'\"";
292 /* This sets rl_completer_word_break_characters and rl_special_prefixes
293 to the appropriate values, depending on whether or not hostname
294 completion is enabled. */
295 enable_hostname_completion (perform_hostname_completion);
297 /* characters that need to be quoted when appearing in filenames. */
298 rl_filename_quote_characters = " \t\n\\\"'@<>=;|&()#$`?*[!:";
299 rl_filename_quoting_function = bash_quote_filename;
300 rl_filename_dequoting_function = bash_dequote_filename;
301 rl_char_is_quoted_p = char_is_quoted;
304 posix_readline_initialize (1);
306 bash_readline_initialized = 1;
309 /* On Sun systems at least, rl_attempted_completion_function can end up
310 getting set to NULL, and rl_completion_entry_function set to do command
311 word completion if Bash is interrupted while trying to complete a command
312 word. This just resets all the completion functions to the right thing.
313 It's called from throw_to_top_level(). */
315 bashline_reinitialize ()
318 rl_attempted_completion_function = attempt_shell_completion;
319 rl_completion_entry_function = (Function *)NULL;
320 rl_directory_completion_hook = bash_directory_completion_hook;
321 rl_ignore_some_completions_function = (Function *)filename_completion_ignore;
324 /* Contains the line to push into readline. */
325 static char *push_to_readline = (char *)NULL;
327 /* Push the contents of push_to_readline into the
332 if (push_to_readline)
334 rl_insert_text (push_to_readline);
335 free (push_to_readline);
336 push_to_readline = (char *)NULL;
337 rl_startup_hook = old_rl_startup_hook;
341 /* Call this to set the initial text for the next line to read
347 FREE (push_to_readline);
349 push_to_readline = savestring (line);
350 old_rl_startup_hook = rl_startup_hook;
351 rl_startup_hook = (Function *)bash_push_line;
357 display_shell_version (count, c)
361 show_shell_version (0);
362 putc ('\r', rl_outstream);
363 fflush (rl_outstream);
368 /* **************************************************************** */
372 /* **************************************************************** */
374 /* If the user requests hostname completion, then simply build a list
375 of hosts, and complete from that forever more. */
377 /* The kept list of hostnames. */
378 static char **hostname_list = (char **)NULL;
380 /* The physical size of the above list. */
381 static int hostname_list_size;
383 /* The number of hostnames in the above list. */
384 static int hostname_list_length;
386 /* Whether or not HOSTNAME_LIST has been initialized. */
387 int hostname_list_initialized = 0;
389 /* Initialize the hostname completion table. */
391 initialize_hostname_list ()
395 temp = get_string_value ("HOSTFILE");
397 temp = get_string_value ("hostname_completion_file");
399 temp = DEFAULT_HOSTS_FILE;
401 snarf_hosts_from_file (temp);
404 hostname_list_initialized++;
407 /* Add NAME to the list of hosts. */
414 if (hostname_list_length + 2 > hostname_list_size)
416 hostname_list_size = (hostname_list_size + 32) - (hostname_list_size % 32);
417 size = hostname_list_size * sizeof (char *);
418 hostname_list = (char **)xrealloc (hostname_list, size);
421 hostname_list[hostname_list_length++] = savestring (name);
422 hostname_list[hostname_list_length] = (char *)NULL;
425 #define cr_whitespace(c) ((c) == '\r' || (c) == '\n' || whitespace(c))
428 snarf_hosts_from_file (filename)
432 char *temp, buffer[256], name[256];
433 register int i, start;
435 file = fopen (filename, "r");
439 while (temp = fgets (buffer, 255, file))
441 /* Skip to first character. */
442 for (i = 0; buffer[i] && cr_whitespace (buffer[i]); i++)
445 /* If comment or blank line, ignore. */
446 if (buffer[i] == '\0' || buffer[i] == '#')
449 /* If `preprocessor' directive, do the include. */
450 if (strncmp (buffer + i, "$include ", 9) == 0)
454 /* Find start of filename. */
455 for (incfile = buffer + i + 9; *incfile && whitespace (*incfile); incfile++)
458 /* Find end of filename. */
459 for (t = incfile; *t && cr_whitespace (*t) == 0; t++)
464 snarf_hosts_from_file (incfile);
468 /* Skip internet address if present. */
469 if (digit (buffer[i]))
470 for (; buffer[i] && cr_whitespace (buffer[i]) == 0; i++);
472 /* Gobble up names. Each name is separated with whitespace. */
475 for (; cr_whitespace (buffer[i]); i++)
477 if (buffer[i] == '\0' || buffer[i] == '#')
480 /* Isolate the current word. */
481 for (start = i; buffer[i] && cr_whitespace (buffer[i]) == 0; i++)
485 strncpy (name, buffer + start, i - start);
486 name[i - start] = '\0';
487 add_host_name (name);
493 /* Return a NULL terminated list of hostnames which begin with TEXT.
494 Initialize the hostname list the first time if neccessary.
495 The array is malloc ()'ed, but not the individual strings. */
497 hostnames_matching (text)
500 register int i, len, nmatch, rsize;
503 if (hostname_list_initialized == 0)
504 initialize_hostname_list ();
506 if (hostname_list_initialized == 0)
507 return ((char **)NULL);
509 /* Special case. If TEXT consists of nothing, then the whole list is
513 result = (char **)xmalloc ((1 + hostname_list_length) * sizeof (char *));
514 for (i = 0; i < hostname_list_length; i++)
515 result[i] = hostname_list[i];
516 result[i] = (char *)NULL;
520 /* Scan until found, or failure. */
522 result = (char **)NULL;
523 for (i = nmatch = rsize = 0; i < hostname_list_length; i++)
525 if (STREQN (text, hostname_list[i], len) == 0)
528 /* OK, it matches. Add it to the list. */
531 rsize = (rsize + 16) - (rsize % 16);
532 result = (char **)xrealloc (result, rsize * sizeof (char *));
535 result[nmatch++] = hostname_list[i];
538 result[nmatch] = (char *)NULL;
542 /* The equivalent of the Korn shell C-o operate-and-get-next-history-line
544 static int saved_history_line_to_use = -1;
549 if (saved_history_line_to_use >= 0)
550 rl_get_previous_history (history_length - saved_history_line_to_use);
551 saved_history_line_to_use = -1;
552 rl_startup_hook = old_rl_startup_hook;
556 operate_and_get_next (count, c)
561 /* Accept the current line. */
564 /* Find the current line, and find the next line to use. */
565 where = where_history ();
567 if ((history_is_stifled () && (history_length >= max_input_history)) ||
568 (where >= history_length - 1))
569 saved_history_line_to_use = where;
571 saved_history_line_to_use = where + 1;
573 old_rl_startup_hook = rl_startup_hook;
574 rl_startup_hook = (Function *)set_saved_history;
577 #if defined (VI_MODE)
578 /* This vi mode command causes VI_EDIT_COMMAND to be run on the current
579 command being entered (if no explicit argument is given), otherwise on
580 a command from the history file. */
582 #define VI_EDIT_COMMAND "fc -e ${VISUAL:-${EDITOR:-vi}}"
585 vi_edit_and_execute_command (count, c)
590 /* Accept the current line. */
595 command = xmalloc (strlen (VI_EDIT_COMMAND) + 8);
596 sprintf (command, "%s %d", VI_EDIT_COMMAND, count);
600 /* Take the command we were just editing, add it to the history file,
601 then call fc to operate on it. We have to add a dummy command to
602 the end of the history because fc ignores the last command (assumes
603 it's supposed to deal with the command before the `fc'). */
605 bash_add_history (rl_line_buffer);
606 bash_add_history ("");
607 history_lines_this_session++;
609 command = savestring (VI_EDIT_COMMAND);
611 parse_and_execute (command, "v", SEVAL_NOHIST);
612 rl_line_buffer[0] = '\0'; /* XXX */
618 posix_edit_macros (count, key)
622 char alias_name[3], *alias_value, *macro;
627 alias_name[2] = '\0';
629 alias_value = get_alias_value (alias_name);
630 if (alias_value && *alias_value)
632 macro = savestring (alias_value);
633 rl_push_macro_input (macro);
639 /* **************************************************************** */
641 /* How To Do Shell Completion */
643 /* **************************************************************** */
645 /* Do some completion on TEXT. The indices of TEXT in RL_LINE_BUFFER are
646 at START and END. Return an array of matches, or NULL if none. */
648 attempt_shell_completion (text, start, end)
652 int in_command_position, ti;
653 char **matches, *command_separator_chars;
655 command_separator_chars = ";|&{(`";
656 matches = (char **)NULL;
657 rl_ignore_some_completions_function = (Function *)filename_completion_ignore;
659 /* Determine if this could be a command word. It is if it appears at
660 the start of the line (ignoring preceding whitespace), or if it
661 appears after a character that separates commands. It cannot be a
662 command word if we aren't at the top-level prompt. */
665 while ((ti > -1) && (whitespace (rl_line_buffer[ti])))
668 in_command_position = 0;
671 /* Only do command completion at the start of a line when we
672 are prompting at the top level. */
673 if (current_prompt_string == ps1_prompt)
674 in_command_position++;
676 else if (member (rl_line_buffer[ti], command_separator_chars))
678 register int this_char, prev_char;
680 in_command_position++;
682 /* Handle the two character tokens `>&', `<&', and `>|'.
683 We are not in a command position after one of these. */
684 this_char = rl_line_buffer[ti];
685 prev_char = rl_line_buffer[ti - 1];
687 if ((this_char == '&' && (prev_char == '<' || prev_char == '>')) ||
688 (this_char == '|' && prev_char == '>'))
689 in_command_position = 0;
690 else if ((this_char == '{' && prev_char == '$') ||
691 (char_is_quoted (rl_line_buffer, ti)))
692 in_command_position = 0;
696 /* This still could be in command position. It is possible
697 that all of the previous words on the line are variable
701 /* Check that we haven't incorrectly flagged a closed command substitution
702 as indicating we're in a command position. */
703 if (in_command_position && rl_line_buffer[ti] == '`' && *text != '`' &&
704 unclosed_pair (rl_line_buffer, 0, "`") == 0)
705 in_command_position = 0;
707 /* Special handling for command substitution. If *TEXT is a backquote,
708 it can be the start or end of an old-style command substitution, or
709 unmatched. If it's unmatched, both calls to unclosed_pair will
711 if (*text == '`' && unclosed_pair (rl_line_buffer, start, "`") &&
712 unclosed_pair (rl_line_buffer, end, "`"))
713 matches = completion_matches (text, command_subst_completion_function);
716 if (!matches && *text == '$')
717 matches = completion_matches (text, variable_completion_function);
719 /* If the word starts in `~', and there is no slash in the word, then
720 try completing this word as a username. */
721 if (!matches && *text == '~' && !strchr (text, '/'))
722 matches = completion_matches (text, username_completion_function);
724 /* Another one. Why not? If the word starts in '@', then look through
725 the world of known hostnames for completion first. */
726 if (!matches && perform_hostname_completion && *text == '@')
727 matches = completion_matches (text, hostname_completion_function);
729 /* And last, (but not least) if this word is in a command position, then
730 complete over possible command names, including aliases, functions,
731 and command names. */
732 if (!matches && in_command_position)
734 matches = completion_matches (text, command_word_completion_function);
735 /* If we are attempting command completion and nothing matches, we
736 do not want readline to perform filename completion for us. We
737 still want to be able to complete partial pathnames, so set the
738 completion ignore function to something which will remove filenames
739 and leave directories in the match list. */
741 rl_ignore_some_completions_function = (Function *)bash_ignore_filenames;
744 /* This could be a globbing pattern, so try to expand it using pathname
746 if (!matches && glob_pattern_p (text))
747 matches = completion_matches (text, glob_complete_word);
752 /* This is the function to call when the word to complete is in a position
753 where a command word can be found. It grovels $PATH, looking for commands
754 that match. It also scans aliases, function names, and the shell_builtin
757 command_word_completion_function (hint_text, state)
761 static char *hint = (char *)NULL;
762 static char *path = (char *)NULL;
763 static char *val = (char *)NULL;
764 static char *filename_hint = (char *)NULL;
765 static int path_index, hint_len, istate;
766 static int mapping_over, local_index;
767 static SHELL_VAR **varlist = (SHELL_VAR **)NULL;
769 static alias_t **alias_list = (alias_t **)NULL;
772 /* We have to map over the possibilities for command words. If we have
773 no state, then make one just for that purpose. */
782 /* If this is an absolute program name, do not check it against
783 aliases, reserved words, functions or builtins. We must check
784 whether or not it is unique, and, if so, whether that filename
786 if (absolute_program (hint_text))
788 /* Perform tilde expansion on what's passed, so we don't end up
789 passing filenames with tildes directly to stat(). */
790 if (*hint_text == '~')
791 hint = bash_tilde_expand (hint_text);
793 hint = savestring (hint_text);
794 hint_len = strlen (hint);
797 free (filename_hint);
798 filename_hint = savestring (hint);
805 hint = savestring (hint_text);
806 hint_len = strlen (hint);
808 path = get_string_value ("PATH");
811 /* Initialize the variables for each type of command word. */
817 varlist = all_visible_functions ();
823 alias_list = all_aliases ();
827 /* mapping_over says what we are currently hacking. Note that every case
828 in this list must fall through when there are no more possibilities. */
830 switch (mapping_over)
832 case 0: /* Aliases come first. */
834 while (alias_list && alias_list[local_index])
836 register char *alias;
838 alias = alias_list[local_index++]->name;
840 if (STREQN (alias, hint, hint_len))
841 return (savestring (alias));
847 case 1: /* Then shell reserved words. */
849 while (word_token_alist[local_index].word)
851 register char *reserved_word;
853 reserved_word = word_token_alist[local_index++].word;
855 if (STREQN (reserved_word, hint, hint_len))
856 return (savestring (reserved_word));
862 case 2: /* Then function names. */
863 while (varlist && varlist[local_index])
865 register char *varname;
867 varname = varlist[local_index++]->name;
869 if (STREQN (varname, hint, hint_len))
870 return (savestring (varname));
875 case 3: /* Then shell builtins. */
876 for (; local_index < num_shell_builtins; local_index++)
878 /* Ignore it if it doesn't have a function pointer or if it
879 is not currently enabled. */
880 if (!shell_builtins[local_index].function ||
881 (shell_builtins[local_index].flags & BUILTIN_ENABLED) == 0)
884 if (STREQN (shell_builtins[local_index].name, hint, hint_len))
886 int i = local_index++;
888 return (savestring (shell_builtins[i].name));
895 /* Repeatedly call filename_completion_function while we have
896 members of PATH left. Question: should we stat each file?
897 Answer: we call executable_file () on each file. */
900 istate = (val != (char *)NULL);
906 /* Get the next directory from the path. If there is none, then we
908 if (!path || !path[path_index] ||
909 (current_path = extract_colon_unit (path, &path_index)) == 0)
910 return ((char *)NULL);
912 if (*current_path == 0)
915 current_path = savestring (".");
918 if (*current_path == '~')
922 t = bash_tilde_expand (current_path);
928 free (filename_hint);
930 filename_hint = xmalloc (2 + strlen (current_path) + hint_len);
931 sprintf (filename_hint, "%s/%s", current_path, hint);
937 val = filename_completion_function (filename_hint, istate);
942 /* If the hint text is an absolute program, then don't bother
943 searching through PATH. */
944 if (absolute_program (hint))
945 return ((char *)NULL);
954 if (absolute_program (hint))
956 match = strncmp (val, hint, hint_len) == 0;
957 /* If we performed tilde expansion, restore the original
959 if (*hint_text == '~')
963 tl = strlen (hint_text);
964 l = vl - hint_len; /* # of chars added */
965 temp = xmalloc (l + 2 + tl);
966 strcpy (temp, hint_text);
967 strcpy (temp + tl, val + vl - l);
970 temp = savestring (val);
975 temp = strrchr (val, '/');
980 freetemp = match = strncmp (temp, hint, hint_len) == 0;
982 temp = savestring (temp);
985 freetemp = match = 0;
988 /* If we have found a match, and it is an executable file or a
989 directory name, return it. */
990 if (match && (executable_file (val) || is_directory (val)))
993 val = ""; /* So it won't be NULL. */
1006 /* Completion inside an unterminated command substitution. */
1008 command_subst_completion_function (text, state)
1012 static char **matches = (char **)NULL;
1013 static char *orig_start, *filename_text = (char *)NULL;
1014 static int cmd_index, start_len;
1020 free (filename_text);
1024 else if (*text == '$' && text[1] == '(')
1026 start_len = text - orig_start;
1027 filename_text = savestring (text);
1030 matches = completion_matches (filename_text, command_word_completion_function);
1034 if (!matches || !matches[cmd_index])
1036 rl_filename_quoting_desired = 0; /* disable quoting */
1037 return ((char *)NULL);
1041 value = xmalloc (1 + start_len + strlen (matches[cmd_index]));
1044 value[0] = *orig_start;
1046 strncpy (value, orig_start, start_len);
1048 strcpy (value + start_len, matches[cmd_index]);
1055 /* Okay, now we write the entry_function for variable completion. */
1057 variable_completion_function (text, state)
1061 register SHELL_VAR *var = (SHELL_VAR *)NULL;
1062 static SHELL_VAR **varlist = (SHELL_VAR **)NULL;
1063 static int varlist_index;
1064 static char *varname = (char *)NULL;
1066 static int first_char, first_char_loc;
1074 first_char = text[0];
1076 if (first_char == '$')
1079 if (text[first_char_loc] == '{')
1082 varname = savestring (text + first_char_loc);
1084 namelen = strlen (varname);
1087 varlist = all_visible_variables ();
1091 while (varlist && varlist[varlist_index])
1093 var = varlist[varlist_index];
1095 /* Compare. You can't do better than Zayre. No text is also
1097 if (!*varname || (strncmp (varname, var->name, namelen) == 0))
1102 if (!varlist || !varlist[varlist_index])
1104 return ((char *)NULL);
1108 char *value = xmalloc (4 + strlen (var->name));
1112 value[0] = first_char;
1113 if (first_char_loc == 2)
1117 strcpy (&value[first_char_loc], var->name);
1118 if (first_char_loc == 2)
1119 strcat (value, "}");
1126 /* How about a completion function for hostnames? */
1128 hostname_completion_function (text, state)
1132 static char **list = (char **)NULL;
1133 static int list_index = 0;
1134 static int first_char, first_char_loc;
1136 /* If we don't have any state, make some. */
1141 list = (char **)NULL;
1146 if (first_char == '@')
1149 list = hostnames_matching (&text[first_char_loc]);
1153 if (list && list[list_index])
1157 t = xmalloc (2 + strlen (list[list_index]));
1159 strcpy (t + first_char_loc, list[list_index]);
1164 return ((char *)NULL);
1167 /* History and alias expand the line. */
1169 history_expand_line_internal (line)
1174 new_line = pre_process_line (line, 0, 0);
1175 return (new_line == line) ? savestring (line) : new_line;
1179 /* Expand aliases in the current readline line. */
1181 alias_expand_line (ignore)
1186 new_line = alias_expand (rl_line_buffer);
1189 set_up_new_line (new_line);
1191 cleanup_expansion_error ();
1195 /* There was an error in expansion. Let the preprocessor print
1198 cleanup_expansion_error ()
1202 fprintf (rl_outstream, "\r\n");
1203 to_free = pre_process_line (rl_line_buffer, 1, 0);
1204 if (to_free != rl_line_buffer)
1206 putc ('\r', rl_outstream);
1207 rl_forced_update_display ();
1210 /* If NEW_LINE differs from what is in the readline line buffer, add an
1211 undo record to get from the readline line buffer contents to the new
1212 line and make NEW_LINE the current readline line. */
1214 maybe_make_readline_line (new_line)
1217 if (strcmp (new_line, rl_line_buffer) != 0)
1221 rl_add_undo (UNDO_BEGIN, 0, 0, 0);
1222 rl_delete_text (0, rl_point);
1223 rl_point = rl_end = 0;
1224 rl_insert_text (new_line);
1225 rl_add_undo (UNDO_END, 0, 0, 0);
1229 /* Make NEW_LINE be the current readline line. This frees NEW_LINE. */
1231 set_up_new_line (new_line)
1234 int old_point = rl_point;
1235 int at_end = rl_point == rl_end;
1237 /* If the line was history and alias expanded, then make that
1238 be one thing to undo. */
1239 maybe_make_readline_line (new_line);
1242 /* Place rl_point where we think it should go. */
1245 else if (old_point < rl_end)
1247 rl_point = old_point;
1248 if (!whitespace (rl_line_buffer[rl_point]))
1249 rl_forward_word (1);
1253 /* History expand the line. */
1255 history_expand_line (ignore)
1260 new_line = history_expand_line_internal (rl_line_buffer);
1263 set_up_new_line (new_line);
1265 cleanup_expansion_error ();
1268 /* History and alias expand the line. */
1270 history_and_alias_expand_line (ignore)
1275 new_line = pre_process_line (rl_line_buffer, 0, 0);
1276 if (new_line == rl_line_buffer)
1277 new_line = savestring (new_line);
1284 alias_line = alias_expand (new_line);
1286 new_line = alias_line;
1291 set_up_new_line (new_line);
1293 cleanup_expansion_error ();
1296 /* History and alias expand the line, then perform the shell word
1297 expansions by calling expand_string. */
1299 shell_expand_line (ignore)
1303 WORD_LIST *expanded_string;
1305 new_line = pre_process_line (rl_line_buffer, 0, 0);
1306 if (new_line == rl_line_buffer)
1307 new_line = savestring (new_line);
1314 alias_line = alias_expand (new_line);
1316 new_line = alias_line;
1322 int old_point = rl_point;
1323 int at_end = rl_point == rl_end;
1325 /* If the line was history and alias expanded, then make that
1326 be one thing to undo. */
1327 maybe_make_readline_line (new_line);
1330 /* If there is variable expansion to perform, do that as a separate
1331 operation to be undone. */
1332 new_line = savestring (rl_line_buffer);
1333 expanded_string = expand_string (new_line, 0);
1335 if (expanded_string == 0)
1337 new_line = xmalloc (1);
1342 new_line = string_list (expanded_string);
1343 dispose_words (expanded_string);
1346 maybe_make_readline_line (new_line);
1349 /* Place rl_point where we think it should go. */
1352 else if (old_point < rl_end)
1354 rl_point = old_point;
1355 if (!whitespace (rl_line_buffer[rl_point]))
1356 rl_forward_word (1);
1360 cleanup_expansion_error ();
1363 /* If FIGNORE is set, then don't match files with the given suffixes when
1364 completing filenames. If only one of the possibilities has an acceptable
1365 suffix, delete the others, else just return and let the completer
1366 signal an error. It is called by the completer when real
1367 completions are done on filenames by the completer's internal
1368 function, not for completion lists (M-?) and not on "other"
1369 completion types, such as hostnames or commands. */
1371 static struct ignorevar fignore =
1381 _ignore_completion_names (names, name_func)
1383 Function *name_func;
1388 /* If there is only one completion, see if it is acceptable. If it is
1389 not, free it up. In any case, short-circuit and return. This is a
1390 special case because names[0] is not the prefix of the list of names
1391 if there is only one completion; it is the completion itself. */
1392 if (names[1] == (char *)0)
1394 if ((*name_func) (names[0]) == 0)
1397 names[0] = (char *)NULL;
1402 /* Allocate space for array to hold list of pointers to matching
1403 filenames. The pointers are copied back to NAMES when done. */
1404 for (nidx = 1; names[nidx]; nidx++)
1406 newnames = (char **)xmalloc ((nidx + 1) * (sizeof (char *)));
1408 newnames[0] = names[0];
1409 for (idx = nidx = 1; names[idx]; idx++)
1411 if ((*name_func) (names[idx]))
1412 newnames[nidx++] = names[idx];
1417 newnames[nidx] = (char *)NULL;
1419 /* If none are acceptable then let the completer handle it. */
1423 names[0] = (char *)NULL;
1428 /* If only one is acceptable, copy it to names[0] and return. */
1432 names[0] = newnames[1];
1433 names[1] = (char *)NULL;
1438 /* Copy the acceptable names back to NAMES, set the new array end,
1440 for (nidx = 1; newnames[nidx]; nidx++)
1441 names[nidx] = newnames[nidx];
1442 names[nidx] = (char *)NULL;
1447 name_is_acceptable (name)
1453 for (nlen = strlen (name), p = fignore.ignores; p->val; p++)
1455 if (nlen > p->len && p->len > 0 && STREQ (p->val, &name[nlen - p->len]))
1463 filename_completion_ignore (names)
1466 setup_ignore_patterns (&fignore);
1468 if (fignore.num_ignores == 0)
1471 _ignore_completion_names (names, name_is_acceptable);
1474 /* Return 1 if NAME is a directory. */
1476 test_for_directory (name)
1482 fn = bash_tilde_expand (name);
1483 if (stat (fn, &finfo) != 0)
1489 return (S_ISDIR (finfo.st_mode));
1492 /* Remove files from NAMES, leaving directories. */
1494 bash_ignore_filenames (names)
1497 _ignore_completion_names (names, test_for_directory);
1500 /* Handle symbolic link references and other directory name
1501 expansions while hacking completion. */
1503 bash_directory_completion_hook (dirname)
1506 char *local_dirname, *t;
1507 int return_value = 0;
1510 local_dirname = *dirname;
1511 if (strchr (local_dirname, '$') || strchr (local_dirname, '`'))
1513 wl = expand_string (local_dirname, 0);
1516 *dirname = string_list (wl);
1517 /* Tell the completer to replace the directory name only if we
1518 actually expanded something. */
1519 return_value = STREQ (local_dirname, *dirname) == 0;
1520 free (local_dirname);
1522 local_dirname = *dirname;
1526 free (local_dirname);
1527 *dirname = xmalloc (1);
1533 if (!no_symbolic_links && (local_dirname[0] != '.' || local_dirname[1]))
1535 char *temp1, *temp2;
1538 t = get_working_directory ("symlink-hook");
1539 temp1 = make_absolute (local_dirname, t);
1541 temp2 = canonicalize_pathname (temp1);
1542 /* If we can't canonicalize, bail. */
1548 len1 = strlen (temp1);
1549 if (temp1[len1 - 1] == '/')
1551 len2 = strlen (temp2);
1552 temp2 = xrealloc (temp2, len2 + 2);
1554 temp2[len2 + 1] = '\0';
1556 free (local_dirname);
1560 return (return_value);
1563 static char **history_completion_array = (char **)NULL;
1564 static int harry_size;
1565 static int harry_len;
1568 build_history_completion_array ()
1574 /* First, clear out the current dynamic history completion list. */
1577 for (i = 0; history_completion_array[i]; i++)
1578 free (history_completion_array[i]);
1580 free (history_completion_array);
1582 history_completion_array = (char **)NULL;
1587 /* Next, grovel each line of history, making each shell-sized token
1588 a separate entry in the history_completion_array. */
1589 hlist = history_list ();
1593 for (i = 0; hlist[i]; i++)
1595 /* Separate each token, and place into an array. */
1596 tokens = history_tokenize (hlist[i]->line);
1598 for (j = 0; tokens && tokens[j]; j++)
1600 if (harry_len + 2 > harry_size)
1603 history_completion_array = (char **) xrealloc
1604 (history_completion_array, harry_size * sizeof (char *));
1607 history_completion_array[harry_len++] = tokens[j];
1608 history_completion_array[harry_len] = (char *)NULL;
1613 /* Sort the complete list of tokens. */
1614 qsort (history_completion_array, harry_len, sizeof (char *), (Function *)qsort_string_compare);
1619 history_completion_generator (hint_text, state)
1623 static int local_index, len;
1626 /* If this is the first call to the generator, then initialize the
1627 list of strings to complete over. */
1631 build_history_completion_array ();
1633 len = strlen (text);
1636 while (history_completion_array && history_completion_array[local_index])
1638 if (strncmp (text, history_completion_array[local_index++], len) == 0)
1639 return (savestring (history_completion_array[local_index - 1]));
1641 return ((char *)NULL);
1645 dynamic_complete_history (count, key)
1648 Function *orig_func;
1649 CPPFunction *orig_attempt_func;
1651 orig_func = rl_completion_entry_function;
1652 orig_attempt_func = rl_attempted_completion_function;
1653 rl_completion_entry_function = (Function *)history_completion_generator;
1654 rl_attempted_completion_function = (CPPFunction *)NULL;
1656 if (rl_last_func == (Function *)dynamic_complete_history)
1657 rl_complete_internal ('?');
1659 rl_complete_internal (TAB);
1661 rl_completion_entry_function = orig_func;
1662 rl_attempted_completion_function = orig_attempt_func;
1665 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
1667 bash_complete_username (ignore, ignore2)
1668 int ignore, ignore2;
1670 bash_complete_username_internal (TAB);
1674 bash_possible_username_completions (ignore, ignore2)
1675 int ignore, ignore2;
1677 bash_complete_username_internal ('?');
1681 bash_complete_username_internal (what_to_do)
1684 bash_specific_completion
1685 (what_to_do, (Function *)username_completion_function);
1689 bash_complete_filename (ignore, ignore2)
1690 int ignore, ignore2;
1692 bash_complete_filename_internal (TAB);
1696 bash_possible_filename_completions (ignore, ignore2)
1697 int ignore, ignore2;
1699 bash_complete_filename_internal ('?');
1703 bash_complete_filename_internal (what_to_do)
1706 Function *orig_func, *orig_dir_func;
1707 CPPFunction *orig_attempt_func;
1708 char *orig_rl_completer_word_break_characters;
1710 orig_func = rl_completion_entry_function;
1711 orig_attempt_func = rl_attempted_completion_function;
1712 orig_dir_func = rl_directory_completion_hook;
1713 orig_rl_completer_word_break_characters = rl_completer_word_break_characters;
1714 rl_completion_entry_function = (Function *)filename_completion_function;
1715 rl_attempted_completion_function = (CPPFunction *)NULL;
1716 rl_directory_completion_hook = (Function *)NULL;
1717 rl_completer_word_break_characters = " \t\n\"\'";
1719 rl_complete_internal (what_to_do);
1721 rl_completion_entry_function = orig_func;
1722 rl_attempted_completion_function = orig_attempt_func;
1723 rl_directory_completion_hook = orig_dir_func;
1724 rl_completer_word_break_characters = orig_rl_completer_word_break_characters;
1728 bash_complete_hostname (ignore, ignore2)
1729 int ignore, ignore2;
1731 bash_complete_hostname_internal (TAB);
1735 bash_possible_hostname_completions (ignore, ignore2)
1736 int ignore, ignore2;
1738 bash_complete_hostname_internal ('?');
1742 bash_complete_variable (ignore, ignore2)
1743 int ignore, ignore2;
1745 bash_complete_variable_internal (TAB);
1749 bash_possible_variable_completions (ignore, ignore2)
1750 int ignore, ignore2;
1752 bash_complete_variable_internal ('?');
1756 bash_complete_command (ignore, ignore2)
1757 int ignore, ignore2;
1759 bash_complete_command_internal (TAB);
1763 bash_possible_command_completions (ignore, ignore2)
1764 int ignore, ignore2;
1766 bash_complete_command_internal ('?');
1770 bash_complete_hostname_internal (what_to_do)
1773 bash_specific_completion
1774 (what_to_do, (Function *)hostname_completion_function);
1778 bash_complete_variable_internal (what_to_do)
1781 bash_specific_completion
1782 (what_to_do, (Function *)variable_completion_function);
1786 bash_complete_command_internal (what_to_do)
1789 bash_specific_completion
1790 (what_to_do, (Function *)command_word_completion_function);
1794 glob_complete_word (text, state)
1798 static char **matches = (char **)NULL;
1806 matches = shell_glob_filename (text);
1807 if (GLOB_FAILED (matches))
1808 matches = (char **)NULL;
1812 ret = matches ? matches[ind] : (char *)NULL;
1818 bash_glob_completion_internal (what_to_do)
1821 bash_specific_completion (what_to_do, (Function *)glob_complete_word);
1825 bash_glob_expand_word (count, key)
1828 bash_glob_completion_internal ('*');
1832 bash_glob_list_expansions (count, key)
1835 bash_glob_completion_internal ('?');
1839 bash_specific_completion (what_to_do, generator)
1841 Function *generator;
1843 Function *orig_func;
1844 CPPFunction *orig_attempt_func;
1846 orig_func = rl_completion_entry_function;
1847 orig_attempt_func = rl_attempted_completion_function;
1848 rl_completion_entry_function = generator;
1849 rl_attempted_completion_function = (CPPFunction *)NULL;
1851 rl_complete_internal (what_to_do);
1853 rl_completion_entry_function = orig_func;
1854 rl_attempted_completion_function = orig_attempt_func;
1857 #endif /* SPECIFIC_COMPLETION_FUNCTIONS */
1859 /* Filename quoting for completion. */
1860 /* A function to strip quotes that are not protected by backquotes. It
1861 allows single quotes to appear within double quotes, and vice versa.
1862 It should be smarter. */
1864 bash_dequote_filename (text, quote_char)
1871 ret = xmalloc (l + 1);
1872 for (quoted = quote_char, p = text, r = ret; p && *p; p++)
1874 /* Allow backslash-quoted characters to pass through unscathed. */
1883 if (quoted && *p == quoted)
1889 if (quoted == 0 && (*p == '\'' || *p == '"'))
1900 /* Quote characters that the readline completion code would treat as
1901 word break characters with backslashes. Pass backslash-quoted
1902 characters through without examination. */
1904 quote_word_break_chars (text)
1911 ret = xmalloc ((2 * l) + 1);
1912 for (s = text, r = ret; *s; s++)
1914 /* Pass backslash-quoted characters through, including the backslash. */
1923 /* OK, we have an unquoted character. Check its presence in
1924 rl_completer_word_break_characters. */
1925 if (strchr (rl_completer_word_break_characters, *s))
1933 /* Quote a filename using double quotes, single quotes, or backslashes
1934 depending on the value of completion_quoting_style. If we're
1935 completing using backslashes, we need to quote some additional
1936 characters (those that readline treats as word breaks), so we call
1937 quote_word_break_chars on the result. */
1939 bash_quote_filename (s, rtype, qcp)
1944 char *rtext, *mtext, *ret;
1947 rtext = (char *)NULL;
1949 /* If RTYPE == MULT_MATCH, it means that there is
1950 more than one match. In this case, we do not add
1951 the closing quote or attempt to perform tilde
1952 expansion. If RTYPE == SINGLE_MATCH, we try
1953 to perform tilde expansion, because single and double
1954 quotes inhibit tilde expansion by the shell. */
1957 if (mtext[0] == '~' && rtype == SINGLE_MATCH)
1958 mtext = bash_tilde_expand (s);
1960 cs = completion_quoting_style;
1961 /* Might need to modify the default completion style based on *qcp,
1962 since it's set to any user-provided opening quote. */
1964 cs = COMPLETE_DQUOTE;
1965 else if (*qcp == '\'')
1966 cs = COMPLETE_SQUOTE;
1967 #if defined (BANG_HISTORY)
1968 else if (*qcp == '\0' && history_expansion && cs == COMPLETE_DQUOTE &&
1969 history_expansion_inhibited == 0 && strchr (mtext, '!'))
1970 cs = COMPLETE_BSQUOTE;
1972 if (*qcp == '"' && history_expansion && cs == COMPLETE_DQUOTE &&
1973 history_expansion_inhibited == 0 && strchr (mtext, '!'))
1975 cs = COMPLETE_BSQUOTE;
1982 case COMPLETE_DQUOTE:
1983 rtext = double_quote (mtext);
1985 case COMPLETE_SQUOTE:
1986 rtext = single_quote (mtext);
1988 case COMPLETE_BSQUOTE:
1989 rtext = backslash_quote (mtext);
1996 /* We may need to quote additional characters: those that readline treats
1997 as word breaks that are not quoted by backslash_quote. */
1998 if (rtext && cs == COMPLETE_BSQUOTE)
2000 mtext = quote_word_break_chars (rtext);
2005 /* Leave the opening quote intact. The readline completion code takes
2006 care of avoiding doubled opening quotes. */
2007 rlen = strlen (rtext);
2008 ret = xmalloc (rlen + 1);
2009 strcpy (ret, rtext);
2011 /* If there are multiple matches, cut off the closing quote. */
2012 if (rtype == MULT_MATCH && cs != COMPLETE_BSQUOTE)
2013 ret[rlen - 1] = '\0';
2018 #endif /* READLINE */