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"
41 #include "builtins/common.h"
42 #include <readline/rlconf.h>
43 #include <readline/readline.h>
44 #include <readline/history.h>
46 #include <glob/glob.h>
52 #if defined (BRACE_COMPLETION)
53 extern void bash_brace_completion ();
54 #endif /* BRACE_COMPLETION */
56 /* Functions bound to keys in Readline for Bash users. */
57 static void shell_expand_line ();
58 static void display_shell_version (), operate_and_get_next ();
59 static void bash_ignore_filenames ();
60 static void cleanup_expansion_error (), set_up_new_line ();
62 #if defined (BANG_HISTORY)
63 static int history_expand_line ();
64 static int tcsh_magic_space ();
65 #endif /* BANG_HISTORY */
67 static int alias_expand_line ();
69 #if defined (BANG_HISTORY) && defined (ALIAS)
70 static int history_and_alias_expand_line ();
73 /* Helper functions for Readline. */
74 static int bash_directory_completion_hook ();
75 static void filename_completion_ignore ();
76 static void bash_push_line ();
78 static char **attempt_shell_completion ();
79 static char *variable_completion_function ();
80 static char *hostname_completion_function ();
81 static char *command_word_completion_function ();
82 static char *command_subst_completion_function ();
83 static void dynamic_complete_history ();
85 static char *glob_complete_word ();
86 static void bash_glob_expand_word ();
87 static void bash_glob_list_expansions ();
89 static void snarf_hosts_from_file (), add_host_name ();
91 static char *bash_dequote_filename ();
92 static char *bash_quote_filename ();
95 static int posix_edit_macros ();
98 /* Variables used here but defined in other files. */
99 extern int posixly_correct, no_symbolic_links;
100 extern int rl_explicit_arg;
101 extern char *current_prompt_string, *ps1_prompt;
102 extern STRING_INT_ALIST word_token_alist[];
103 extern Function *rl_last_func;
104 extern int rl_filename_completion_desired;
106 /* Helper functions from subst.c */
107 extern int char_is_quoted ();
108 extern int unclosed_pair ();
110 /* SPECIFIC_COMPLETION_FUNCTIONS specifies that we have individual
111 completion functions which indicate what type of completion should be
112 done (at or before point) that can be bound to key sequences with
113 the readline library. */
114 #define SPECIFIC_COMPLETION_FUNCTIONS
116 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
117 static void bash_specific_completion ();
118 static void bash_complete_filename (), bash_possible_filename_completions ();
119 static void bash_complete_filename_internal ();
120 static void bash_complete_username (), bash_possible_username_completions ();
121 static void bash_complete_username_internal ();
122 static void bash_complete_hostname (), bash_possible_hostname_completions ();
123 static void bash_complete_hostname_internal ();
124 static void bash_complete_variable (), bash_possible_variable_completions ();
125 static void bash_complete_variable_internal ();
126 static void bash_complete_command (), bash_possible_command_completions ();
127 static void bash_complete_command_internal ();
128 #endif /* SPECIFIC_COMPLETION_FUNCTIONS */
130 #if defined (VI_MODE)
131 static void vi_edit_and_execute_command ();
134 /* Non-zero once initalize_readline () has been called. */
135 int bash_readline_initialized = 0;
137 /* If non-zero, we do hostname completion, breaking words at `@' and
138 trying to complete the stuff after the `@' from our own internal
140 int perform_hostname_completion = 1;
142 static char *bash_completer_word_break_characters = " \t\n\"'@><=;|&(:";
143 static char *bash_nohostname_word_break_characters = " \t\n\"'><=;|&(:";
145 static Function *old_rl_startup_hook = (Function *) NULL;
147 /* What kind of quoting is performed by bash_quote_filename:
148 COMPLETE_DQUOTE = double-quoting the filename
149 COMPLETE_SQUOTE = single_quoting the filename
150 COMPLETE_BSQUOTE = backslash-quoting special chars in the filename
152 #define COMPLETE_DQUOTE 1
153 #define COMPLETE_SQUOTE 2
154 #define COMPLETE_BSQUOTE 3
155 static int completion_quoting_style = COMPLETE_BSQUOTE;
157 /* Change the readline VI-mode keymaps into or out of Posix.2 compliance.
158 Called when the shell is put into or out of `posix' mode. */
160 posix_readline_initialize (on_or_off)
164 rl_variable_bind ("comment-begin", "#");
165 #if defined (VI_MODE)
166 rl_bind_key_in_map (CTRL('I'), on_or_off ? rl_insert : rl_complete, vi_insertion_keymap);
171 enable_hostname_completion (on_or_off)
176 perform_hostname_completion = 1;
177 rl_special_prefixes = "$@";
178 rl_completer_word_break_characters = bash_completer_word_break_characters;
182 perform_hostname_completion = 0;
183 rl_special_prefixes = "$";
184 rl_completer_word_break_characters = bash_nohostname_word_break_characters;
188 /* Called once from parse.y if we are going to use readline. */
190 initialize_readline ()
192 if (bash_readline_initialized)
195 rl_terminal_name = get_string_value ("TERM");
197 rl_outstream = stderr;
199 /* Allow conditional parsing of the ~/.inputrc file. */
200 rl_readline_name = "Bash";
202 /* Bind up our special shell functions. */
203 rl_add_defun ("shell-expand-line", (Function *)shell_expand_line, -1);
204 rl_bind_key_in_map (CTRL('E'), (Function *)shell_expand_line, emacs_meta_keymap);
206 /* Bind up our special shell functions. */
208 rl_add_defun ("history-expand-line", (Function *)history_expand_line, -1);
209 rl_bind_key_in_map ('^', (Function *)history_expand_line, emacs_meta_keymap);
211 rl_add_defun ("magic-space", (Function *)tcsh_magic_space, -1);
215 rl_add_defun ("alias-expand-line", (Function *)alias_expand_line, -1);
216 rl_add_defun ("history-and-alias-expand-line", (Function *)history_and_alias_expand_line, -1);
219 /* Backwards compatibility. */
220 rl_add_defun ("insert-last-argument", rl_yank_last_arg, -1);
223 ("operate-and-get-next", (Function *)operate_and_get_next, CTRL('O'));
226 ("display-shell-version", (Function *)display_shell_version, -1);
228 (CTRL ('V'), (Function *)display_shell_version, emacs_ctlx_keymap);
230 /* In Bash, the user can switch editing modes with "set -o [vi emacs]",
231 so it is not necessary to allow C-M-j for context switching. Turn
232 off this occasionally confusing behaviour. */
233 rl_unbind_key_in_map (CTRL('J'), emacs_meta_keymap);
234 rl_unbind_key_in_map (CTRL('M'), emacs_meta_keymap);
235 #if defined (VI_MODE)
236 rl_unbind_key_in_map (CTRL('E'), vi_movement_keymap);
239 #if defined (BRACE_COMPLETION)
240 rl_add_defun ("complete-into-braces", bash_brace_completion, -1);
241 rl_bind_key_in_map ('{', bash_brace_completion, emacs_meta_keymap);
242 #endif /* BRACE_COMPLETION */
244 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
245 rl_add_defun ("complete-filename", bash_complete_filename, -1);
246 rl_bind_key_in_map ('/', bash_complete_filename, emacs_meta_keymap);
247 rl_add_defun ("possible-filename-completions",
248 bash_possible_filename_completions, -1);
249 rl_bind_key_in_map ('/', bash_possible_filename_completions, emacs_ctlx_keymap);
251 rl_add_defun ("complete-username", bash_complete_username, -1);
252 rl_bind_key_in_map ('~', bash_complete_username, emacs_meta_keymap);
253 rl_add_defun ("possible-username-completions",
254 bash_possible_username_completions, -1);
255 rl_bind_key_in_map ('~', bash_possible_username_completions, emacs_ctlx_keymap);
257 rl_add_defun ("complete-hostname", bash_complete_hostname, -1);
258 rl_bind_key_in_map ('@', bash_complete_hostname, emacs_meta_keymap);
259 rl_add_defun ("possible-hostname-completions",
260 bash_possible_hostname_completions, -1);
261 rl_bind_key_in_map ('@', bash_possible_hostname_completions, emacs_ctlx_keymap);
263 rl_add_defun ("complete-variable", bash_complete_variable, -1);
264 rl_bind_key_in_map ('$', bash_complete_variable, emacs_meta_keymap);
265 rl_add_defun ("possible-variable-completions",
266 bash_possible_variable_completions, -1);
267 rl_bind_key_in_map ('$', bash_possible_variable_completions, emacs_ctlx_keymap);
269 rl_add_defun ("complete-command", bash_complete_command, -1);
270 rl_bind_key_in_map ('!', bash_complete_command, emacs_meta_keymap);
271 rl_add_defun ("possible-command-completions",
272 bash_possible_command_completions, -1);
273 rl_bind_key_in_map ('!', bash_possible_command_completions, emacs_ctlx_keymap);
275 rl_add_defun ("glob-expand-word", bash_glob_expand_word, -1);
276 rl_add_defun ("glob-list-expansions", bash_glob_list_expansions, -1);
277 rl_bind_key_in_map ('*', bash_glob_expand_word, emacs_ctlx_keymap);
278 rl_bind_key_in_map ('g', bash_glob_list_expansions, emacs_ctlx_keymap);
280 #endif /* SPECIFIC_COMPLETION_FUNCTIONS */
282 rl_add_defun ("dynamic-complete-history", dynamic_complete_history, -1);
283 rl_bind_key_in_map (TAB, dynamic_complete_history, emacs_meta_keymap);
285 /* Tell the completer that we want a crack first. */
286 rl_attempted_completion_function = (CPPFunction *)attempt_shell_completion;
288 /* Tell the completer that we might want to follow symbolic links or
289 do other expansion on directory names. */
290 rl_directory_completion_hook = bash_directory_completion_hook;
292 /* Tell the filename completer we want a chance to ignore some names. */
293 rl_ignore_some_completions_function = (Function *)filename_completion_ignore;
295 #if defined (VI_MODE)
296 rl_bind_key_in_map ('v', vi_edit_and_execute_command, vi_movement_keymap);
298 rl_bind_key_in_map ('@', posix_edit_macros, vi_movement_keymap);
302 rl_completer_quote_characters = "'\"";
304 /* This sets rl_completer_word_break_characters and rl_special_prefixes
305 to the appropriate values, depending on whether or not hostname
306 completion is enabled. */
307 enable_hostname_completion (perform_hostname_completion);
309 /* characters that need to be quoted when appearing in filenames. */
310 rl_filename_quote_characters = " \t\n\\\"'@<>=;|&()#$`?*[!:";
311 rl_filename_quoting_function = bash_quote_filename;
312 rl_filename_dequoting_function = bash_dequote_filename;
313 rl_char_is_quoted_p = char_is_quoted;
316 posix_readline_initialize (1);
318 bash_readline_initialized = 1;
321 /* On Sun systems at least, rl_attempted_completion_function can end up
322 getting set to NULL, and rl_completion_entry_function set to do command
323 word completion if Bash is interrupted while trying to complete a command
324 word. This just resets all the completion functions to the right thing.
325 It's called from throw_to_top_level(). */
327 bashline_reinitialize ()
330 rl_attempted_completion_function = attempt_shell_completion;
331 rl_completion_entry_function = (Function *)NULL;
332 rl_directory_completion_hook = bash_directory_completion_hook;
333 rl_ignore_some_completions_function = (Function *)filename_completion_ignore;
336 /* Contains the line to push into readline. */
337 static char *push_to_readline = (char *)NULL;
339 /* Push the contents of push_to_readline into the
344 if (push_to_readline)
346 rl_insert_text (push_to_readline);
347 free (push_to_readline);
348 push_to_readline = (char *)NULL;
349 rl_startup_hook = old_rl_startup_hook;
353 /* Call this to set the initial text for the next line to read
359 FREE (push_to_readline);
361 push_to_readline = savestring (line);
362 old_rl_startup_hook = rl_startup_hook;
363 rl_startup_hook = (Function *)bash_push_line;
369 display_shell_version (count, c)
373 show_shell_version (0);
374 putc ('\r', rl_outstream);
375 fflush (rl_outstream);
380 /* **************************************************************** */
384 /* **************************************************************** */
386 /* If the user requests hostname completion, then simply build a list
387 of hosts, and complete from that forever more. */
389 /* The kept list of hostnames. */
390 static char **hostname_list = (char **)NULL;
392 /* The physical size of the above list. */
393 static int hostname_list_size;
395 /* The number of hostnames in the above list. */
396 static int hostname_list_length;
398 /* Whether or not HOSTNAME_LIST has been initialized. */
399 int hostname_list_initialized = 0;
401 /* Initialize the hostname completion table. */
403 initialize_hostname_list ()
407 temp = get_string_value ("HOSTFILE");
409 temp = get_string_value ("hostname_completion_file");
411 temp = DEFAULT_HOSTS_FILE;
413 snarf_hosts_from_file (temp);
416 hostname_list_initialized++;
419 /* Add NAME to the list of hosts. */
426 if (hostname_list_length + 2 > hostname_list_size)
428 hostname_list_size = (hostname_list_size + 32) - (hostname_list_size % 32);
429 size = hostname_list_size * sizeof (char *);
430 hostname_list = (char **)xrealloc (hostname_list, size);
433 hostname_list[hostname_list_length++] = savestring (name);
434 hostname_list[hostname_list_length] = (char *)NULL;
437 #define cr_whitespace(c) ((c) == '\r' || (c) == '\n' || whitespace(c))
440 snarf_hosts_from_file (filename)
444 char *temp, buffer[256], name[256];
445 register int i, start;
447 file = fopen (filename, "r");
451 while (temp = fgets (buffer, 255, file))
453 /* Skip to first character. */
454 for (i = 0; buffer[i] && cr_whitespace (buffer[i]); i++)
457 /* If comment or blank line, ignore. */
458 if (buffer[i] == '\0' || buffer[i] == '#')
461 /* If `preprocessor' directive, do the include. */
462 if (strncmp (buffer + i, "$include ", 9) == 0)
466 /* Find start of filename. */
467 for (incfile = buffer + i + 9; *incfile && whitespace (*incfile); incfile++)
470 /* Find end of filename. */
471 for (t = incfile; *t && cr_whitespace (*t) == 0; t++)
476 snarf_hosts_from_file (incfile);
480 /* Skip internet address if present. */
481 if (digit (buffer[i]))
482 for (; buffer[i] && cr_whitespace (buffer[i]) == 0; i++);
484 /* Gobble up names. Each name is separated with whitespace. */
487 for (; cr_whitespace (buffer[i]); i++)
489 if (buffer[i] == '\0' || buffer[i] == '#')
492 /* Isolate the current word. */
493 for (start = i; buffer[i] && cr_whitespace (buffer[i]) == 0; i++)
497 strncpy (name, buffer + start, i - start);
498 name[i - start] = '\0';
499 add_host_name (name);
505 /* Return a NULL terminated list of hostnames which begin with TEXT.
506 Initialize the hostname list the first time if neccessary.
507 The array is malloc ()'ed, but not the individual strings. */
509 hostnames_matching (text)
512 register int i, len, nmatch, rsize;
515 if (hostname_list_initialized == 0)
516 initialize_hostname_list ();
518 if (hostname_list_initialized == 0)
519 return ((char **)NULL);
521 /* Special case. If TEXT consists of nothing, then the whole list is
525 result = (char **)xmalloc ((1 + hostname_list_length) * sizeof (char *));
526 for (i = 0; i < hostname_list_length; i++)
527 result[i] = hostname_list[i];
528 result[i] = (char *)NULL;
532 /* Scan until found, or failure. */
534 result = (char **)NULL;
535 for (i = nmatch = rsize = 0; i < hostname_list_length; i++)
537 if (STREQN (text, hostname_list[i], len) == 0)
540 /* OK, it matches. Add it to the list. */
543 rsize = (rsize + 16) - (rsize % 16);
544 result = (char **)xrealloc (result, rsize * sizeof (char *));
547 result[nmatch++] = hostname_list[i];
550 result[nmatch] = (char *)NULL;
554 /* The equivalent of the Korn shell C-o operate-and-get-next-history-line
556 static int saved_history_line_to_use = -1;
561 if (saved_history_line_to_use >= 0)
562 rl_get_previous_history (history_length - saved_history_line_to_use);
563 saved_history_line_to_use = -1;
564 rl_startup_hook = old_rl_startup_hook;
568 operate_and_get_next (count, c)
573 /* Accept the current line. */
576 /* Find the current line, and find the next line to use. */
577 where = where_history ();
579 if ((history_is_stifled () && (history_length >= max_input_history)) ||
580 (where >= history_length - 1))
581 saved_history_line_to_use = where;
583 saved_history_line_to_use = where + 1;
585 old_rl_startup_hook = rl_startup_hook;
586 rl_startup_hook = (Function *)set_saved_history;
589 #if defined (VI_MODE)
590 /* This vi mode command causes VI_EDIT_COMMAND to be run on the current
591 command being entered (if no explicit argument is given), otherwise on
592 a command from the history file. */
594 #define VI_EDIT_COMMAND "fc -e ${VISUAL:-${EDITOR:-vi}}"
597 vi_edit_and_execute_command (count, c)
602 /* Accept the current line. */
607 command = xmalloc (strlen (VI_EDIT_COMMAND) + 8);
608 sprintf (command, "%s %d", VI_EDIT_COMMAND, count);
612 /* Take the command we were just editing, add it to the history file,
613 then call fc to operate on it. We have to add a dummy command to
614 the end of the history because fc ignores the last command (assumes
615 it's supposed to deal with the command before the `fc'). */
617 bash_add_history (rl_line_buffer);
618 bash_add_history ("");
619 history_lines_this_session++;
621 command = savestring (VI_EDIT_COMMAND);
623 parse_and_execute (command, "v", SEVAL_NOHIST);
624 rl_line_buffer[0] = '\0'; /* XXX */
630 posix_edit_macros (count, key)
634 char alias_name[3], *alias_value, *macro;
639 alias_name[2] = '\0';
641 alias_value = get_alias_value (alias_name);
642 if (alias_value && *alias_value)
644 macro = savestring (alias_value);
645 rl_push_macro_input (macro);
651 /* **************************************************************** */
653 /* How To Do Shell Completion */
655 /* **************************************************************** */
657 /* Do some completion on TEXT. The indices of TEXT in RL_LINE_BUFFER are
658 at START and END. Return an array of matches, or NULL if none. */
660 attempt_shell_completion (text, start, end)
664 int in_command_position, ti;
665 char **matches, *command_separator_chars;
667 command_separator_chars = ";|&{(`";
668 matches = (char **)NULL;
669 rl_ignore_some_completions_function = (Function *)filename_completion_ignore;
671 /* Determine if this could be a command word. It is if it appears at
672 the start of the line (ignoring preceding whitespace), or if it
673 appears after a character that separates commands. It cannot be a
674 command word if we aren't at the top-level prompt. */
677 while ((ti > -1) && (whitespace (rl_line_buffer[ti])))
680 in_command_position = 0;
683 /* Only do command completion at the start of a line when we
684 are prompting at the top level. */
685 if (current_prompt_string == ps1_prompt)
686 in_command_position++;
688 else if (member (rl_line_buffer[ti], command_separator_chars))
690 register int this_char, prev_char;
692 in_command_position++;
694 /* Handle the two character tokens `>&', `<&', and `>|'.
695 We are not in a command position after one of these. */
696 this_char = rl_line_buffer[ti];
697 prev_char = rl_line_buffer[ti - 1];
699 if ((this_char == '&' && (prev_char == '<' || prev_char == '>')) ||
700 (this_char == '|' && prev_char == '>'))
701 in_command_position = 0;
702 else if ((this_char == '{' && prev_char == '$') ||
703 (char_is_quoted (rl_line_buffer, ti)))
704 in_command_position = 0;
708 /* This still could be in command position. It is possible
709 that all of the previous words on the line are variable
713 /* Check that we haven't incorrectly flagged a closed command substitution
714 as indicating we're in a command position. */
715 if (in_command_position && ti >= 0 && rl_line_buffer[ti] == '`' &&
716 *text != '`' && unclosed_pair (rl_line_buffer, 0, "`") == 0)
717 in_command_position = 0;
719 /* Special handling for command substitution. If *TEXT is a backquote,
720 it can be the start or end of an old-style command substitution, or
721 unmatched. If it's unmatched, both calls to unclosed_pair will
723 if (*text == '`' && unclosed_pair (rl_line_buffer, start, "`") &&
724 unclosed_pair (rl_line_buffer, end, "`"))
725 matches = completion_matches (text, command_subst_completion_function);
728 if (!matches && *text == '$')
729 matches = completion_matches (text, variable_completion_function);
731 /* If the word starts in `~', and there is no slash in the word, then
732 try completing this word as a username. */
733 if (!matches && *text == '~' && !strchr (text, '/'))
734 matches = completion_matches (text, username_completion_function);
736 /* Another one. Why not? If the word starts in '@', then look through
737 the world of known hostnames for completion first. */
738 if (!matches && perform_hostname_completion && *text == '@')
739 matches = completion_matches (text, hostname_completion_function);
741 /* And last, (but not least) if this word is in a command position, then
742 complete over possible command names, including aliases, functions,
743 and command names. */
744 if (!matches && in_command_position)
746 matches = completion_matches (text, command_word_completion_function);
747 /* If we are attempting command completion and nothing matches, we
748 do not want readline to perform filename completion for us. We
749 still want to be able to complete partial pathnames, so set the
750 completion ignore function to something which will remove filenames
751 and leave directories in the match list. */
753 rl_ignore_some_completions_function = (Function *)bash_ignore_filenames;
756 /* This could be a globbing pattern, so try to expand it using pathname
758 if (!matches && glob_pattern_p (text))
760 matches = completion_matches (text, glob_complete_word);
761 /* A glob expression that matches more than one filename is problematic.
762 If we match more than one filename, punt. */
763 if (matches && matches[1])
765 free_array (matches);
766 matches = (char **)0;
773 /* This is the function to call when the word to complete is in a position
774 where a command word can be found. It grovels $PATH, looking for commands
775 that match. It also scans aliases, function names, and the shell_builtin
778 command_word_completion_function (hint_text, state)
782 static char *hint = (char *)NULL;
783 static char *path = (char *)NULL;
784 static char *val = (char *)NULL;
785 static char *filename_hint = (char *)NULL;
786 static int path_index, hint_len, istate;
787 static int mapping_over, local_index;
788 static SHELL_VAR **varlist = (SHELL_VAR **)NULL;
790 static alias_t **alias_list = (alias_t **)NULL;
793 /* We have to map over the possibilities for command words. If we have
794 no state, then make one just for that purpose. */
803 /* If this is an absolute program name, do not check it against
804 aliases, reserved words, functions or builtins. We must check
805 whether or not it is unique, and, if so, whether that filename
807 if (absolute_program (hint_text))
809 /* Perform tilde expansion on what's passed, so we don't end up
810 passing filenames with tildes directly to stat(). */
811 if (*hint_text == '~')
812 hint = bash_tilde_expand (hint_text);
814 hint = savestring (hint_text);
815 hint_len = strlen (hint);
818 free (filename_hint);
819 filename_hint = savestring (hint);
826 hint = savestring (hint_text);
827 hint_len = strlen (hint);
829 path = get_string_value ("PATH");
832 /* Initialize the variables for each type of command word. */
838 varlist = all_visible_functions ();
844 alias_list = all_aliases ();
848 /* mapping_over says what we are currently hacking. Note that every case
849 in this list must fall through when there are no more possibilities. */
851 switch (mapping_over)
853 case 0: /* Aliases come first. */
855 while (alias_list && alias_list[local_index])
857 register char *alias;
859 alias = alias_list[local_index++]->name;
861 if (STREQN (alias, hint, hint_len))
862 return (savestring (alias));
868 case 1: /* Then shell reserved words. */
870 while (word_token_alist[local_index].word)
872 register char *reserved_word;
874 reserved_word = word_token_alist[local_index++].word;
876 if (STREQN (reserved_word, hint, hint_len))
877 return (savestring (reserved_word));
883 case 2: /* Then function names. */
884 while (varlist && varlist[local_index])
886 register char *varname;
888 varname = varlist[local_index++]->name;
890 if (STREQN (varname, hint, hint_len))
891 return (savestring (varname));
896 case 3: /* Then shell builtins. */
897 for (; local_index < num_shell_builtins; local_index++)
899 /* Ignore it if it doesn't have a function pointer or if it
900 is not currently enabled. */
901 if (!shell_builtins[local_index].function ||
902 (shell_builtins[local_index].flags & BUILTIN_ENABLED) == 0)
905 if (STREQN (shell_builtins[local_index].name, hint, hint_len))
907 int i = local_index++;
909 return (savestring (shell_builtins[i].name));
916 /* Repeatedly call filename_completion_function while we have
917 members of PATH left. Question: should we stat each file?
918 Answer: we call executable_file () on each file. */
921 istate = (val != (char *)NULL);
927 /* Get the next directory from the path. If there is none, then we
929 if (!path || !path[path_index] ||
930 (current_path = extract_colon_unit (path, &path_index)) == 0)
931 return ((char *)NULL);
933 if (*current_path == 0)
936 current_path = savestring (".");
939 if (*current_path == '~')
943 t = bash_tilde_expand (current_path);
949 free (filename_hint);
951 filename_hint = xmalloc (2 + strlen (current_path) + hint_len);
952 sprintf (filename_hint, "%s/%s", current_path, hint);
958 val = filename_completion_function (filename_hint, istate);
963 /* If the hint text is an absolute program, then don't bother
964 searching through PATH. */
965 if (absolute_program (hint))
966 return ((char *)NULL);
975 if (absolute_program (hint))
977 match = strncmp (val, hint, hint_len) == 0;
978 /* If we performed tilde expansion, restore the original
980 if (*hint_text == '~')
984 tl = strlen (hint_text);
985 l = vl - hint_len; /* # of chars added */
986 temp = xmalloc (l + 2 + tl);
987 strcpy (temp, hint_text);
988 strcpy (temp + tl, val + vl - l);
991 temp = savestring (val);
996 temp = strrchr (val, '/');
1001 freetemp = match = strncmp (temp, hint, hint_len) == 0;
1003 temp = savestring (temp);
1006 freetemp = match = 0;
1009 /* If we have found a match, and it is an executable file or a
1010 directory name, return it. */
1011 if (match && (executable_file (val) || is_directory (val)))
1014 val = ""; /* So it won't be NULL. */
1027 /* Completion inside an unterminated command substitution. */
1029 command_subst_completion_function (text, state)
1033 static char **matches = (char **)NULL;
1034 static char *orig_start, *filename_text = (char *)NULL;
1035 static int cmd_index, start_len;
1041 free (filename_text);
1045 else if (*text == '$' && text[1] == '(') /* ) */
1047 start_len = text - orig_start;
1048 filename_text = savestring (text);
1051 matches = completion_matches (filename_text, command_word_completion_function);
1055 if (!matches || !matches[cmd_index])
1057 rl_filename_quoting_desired = 0; /* disable quoting */
1058 return ((char *)NULL);
1062 value = xmalloc (1 + start_len + strlen (matches[cmd_index]));
1065 value[0] = *orig_start;
1067 strncpy (value, orig_start, start_len);
1069 strcpy (value + start_len, matches[cmd_index]);
1076 /* Okay, now we write the entry_function for variable completion. */
1078 variable_completion_function (text, state)
1082 register SHELL_VAR *var = (SHELL_VAR *)NULL;
1083 static SHELL_VAR **varlist = (SHELL_VAR **)NULL;
1084 static int varlist_index;
1085 static char *varname = (char *)NULL;
1087 static int first_char, first_char_loc;
1095 first_char = text[0];
1097 if (first_char == '$')
1100 if (text[first_char_loc] == '{')
1103 varname = savestring (text + first_char_loc);
1105 namelen = strlen (varname);
1108 varlist = all_visible_variables ();
1112 while (varlist && varlist[varlist_index])
1114 var = varlist[varlist_index];
1116 /* Compare. You can't do better than Zayre. No text is also
1118 if (!*varname || (strncmp (varname, var->name, namelen) == 0))
1123 if (!varlist || !varlist[varlist_index])
1125 return ((char *)NULL);
1129 char *value = xmalloc (4 + strlen (var->name));
1133 value[0] = first_char;
1134 if (first_char_loc == 2)
1138 strcpy (&value[first_char_loc], var->name);
1139 if (first_char_loc == 2)
1140 strcat (value, "}");
1147 /* How about a completion function for hostnames? */
1149 hostname_completion_function (text, state)
1153 static char **list = (char **)NULL;
1154 static int list_index = 0;
1155 static int first_char, first_char_loc;
1157 /* If we don't have any state, make some. */
1162 list = (char **)NULL;
1167 if (first_char == '@')
1170 list = hostnames_matching (&text[first_char_loc]);
1174 if (list && list[list_index])
1178 t = xmalloc (2 + strlen (list[list_index]));
1180 strcpy (t + first_char_loc, list[list_index]);
1185 return ((char *)NULL);
1188 /* Functions to perform history and alias expansions on the current line. */
1190 #if defined (BANG_HISTORY)
1191 /* Perform history expansion on the current line. If no history expansion
1192 is done, pre_process_line() returns what it was passed, so we need to
1193 allocate a new line here. */
1195 history_expand_line_internal (line)
1200 new_line = pre_process_line (line, 0, 0);
1201 return (new_line == line) ? savestring (line) : new_line;
1205 /* There was an error in expansion. Let the preprocessor print
1208 cleanup_expansion_error ()
1212 fprintf (rl_outstream, "\r\n");
1213 to_free = pre_process_line (rl_line_buffer, 1, 0);
1214 if (to_free != rl_line_buffer)
1216 putc ('\r', rl_outstream);
1217 rl_forced_update_display ();
1220 /* If NEW_LINE differs from what is in the readline line buffer, add an
1221 undo record to get from the readline line buffer contents to the new
1222 line and make NEW_LINE the current readline line. */
1224 maybe_make_readline_line (new_line)
1227 if (strcmp (new_line, rl_line_buffer) != 0)
1231 rl_add_undo (UNDO_BEGIN, 0, 0, 0);
1232 rl_delete_text (0, rl_point);
1233 rl_point = rl_end = 0;
1234 rl_insert_text (new_line);
1235 rl_add_undo (UNDO_END, 0, 0, 0);
1239 /* Make NEW_LINE be the current readline line. This frees NEW_LINE. */
1241 set_up_new_line (new_line)
1244 int old_point = rl_point;
1245 int at_end = rl_point == rl_end;
1247 /* If the line was history and alias expanded, then make that
1248 be one thing to undo. */
1249 maybe_make_readline_line (new_line);
1252 /* Place rl_point where we think it should go. */
1255 else if (old_point < rl_end)
1257 rl_point = old_point;
1258 if (!whitespace (rl_line_buffer[rl_point]))
1259 rl_forward_word (1);
1264 /* Expand aliases in the current readline line. */
1266 alias_expand_line (ignore)
1271 new_line = alias_expand (rl_line_buffer);
1275 set_up_new_line (new_line);
1280 cleanup_expansion_error ();
1286 #if defined (BANG_HISTORY)
1287 /* History expand the line. */
1289 history_expand_line (ignore)
1294 new_line = history_expand_line_internal (rl_line_buffer);
1298 set_up_new_line (new_line);
1303 cleanup_expansion_error ();
1308 /* Expand history substitutions in the current line and then insert a
1309 space wherever set_up_new_line decided to put rl_point. */
1311 tcsh_magic_space (ignore)
1314 if (history_expand_line (ignore) == 0)
1324 /* History and alias expand the line. */
1326 history_and_alias_expand_line (ignore)
1331 new_line = pre_process_line (rl_line_buffer, 0, 0);
1332 if (new_line == rl_line_buffer)
1333 new_line = savestring (new_line);
1340 alias_line = alias_expand (new_line);
1342 new_line = alias_line;
1348 set_up_new_line (new_line);
1353 cleanup_expansion_error ();
1358 /* History and alias expand the line, then perform the shell word
1359 expansions by calling expand_string. This can't use set_up_new_line()
1360 because we want the variable expansions as a separate undo'able
1361 set of operations. */
1363 shell_expand_line (ignore)
1367 WORD_LIST *expanded_string;
1369 new_line = pre_process_line (rl_line_buffer, 0, 0);
1370 if (new_line == rl_line_buffer)
1371 new_line = savestring (new_line);
1378 alias_line = alias_expand (new_line);
1380 new_line = alias_line;
1386 int old_point = rl_point;
1387 int at_end = rl_point == rl_end;
1389 /* If the line was history and alias expanded, then make that
1390 be one thing to undo. */
1391 maybe_make_readline_line (new_line);
1394 /* If there is variable expansion to perform, do that as a separate
1395 operation to be undone. */
1396 new_line = savestring (rl_line_buffer);
1397 expanded_string = expand_string (new_line, 0);
1399 if (expanded_string == 0)
1401 new_line = xmalloc (1);
1406 new_line = string_list (expanded_string);
1407 dispose_words (expanded_string);
1410 maybe_make_readline_line (new_line);
1413 /* Place rl_point where we think it should go. */
1416 else if (old_point < rl_end)
1418 rl_point = old_point;
1419 if (!whitespace (rl_line_buffer[rl_point]))
1420 rl_forward_word (1);
1424 cleanup_expansion_error ();
1427 /* Define NO_FORCE_FIGNORE if you want to match filenames that would
1428 otherwise be ignored if they are the only possible matches. */
1429 /* #define NO_FORCE_FIGNORE */
1431 /* If FIGNORE is set, then don't match files with the given suffixes when
1432 completing filenames. If only one of the possibilities has an acceptable
1433 suffix, delete the others, else just return and let the completer
1434 signal an error. It is called by the completer when real
1435 completions are done on filenames by the completer's internal
1436 function, not for completion lists (M-?) and not on "other"
1437 completion types, such as hostnames or commands. */
1439 static struct ignorevar fignore =
1449 _ignore_completion_names (names, name_func)
1451 Function *name_func;
1455 #ifdef NO_FORCE_FIGNORE
1460 /* If there is only one completion, see if it is acceptable. If it is
1461 not, free it up. In any case, short-circuit and return. This is a
1462 special case because names[0] is not the prefix of the list of names
1463 if there is only one completion; it is the completion itself. */
1464 if (names[1] == (char *)0)
1466 #ifndef NO_FORCE_FIGNORE
1467 if ((*name_func) (names[0]) == 0)
1470 names[0] = (char *)NULL;
1476 /* Allocate space for array to hold list of pointers to matching
1477 filenames. The pointers are copied back to NAMES when done. */
1478 for (nidx = 1; names[nidx]; nidx++)
1480 newnames = (char **)xmalloc ((nidx + 1) * (sizeof (char *)));
1481 #ifdef NO_FORCE_FIGNORE
1482 oldnames = (char **)xmalloc ((nidx - 1) * (sizeof (char *)));
1486 newnames[0] = names[0];
1487 for (idx = nidx = 1; names[idx]; idx++)
1489 if ((*name_func) (names[idx]))
1490 newnames[nidx++] = names[idx];
1492 #ifndef NO_FORCE_FIGNORE
1495 oldnames[oidx++] = names[idx];
1499 newnames[nidx] = (char *)NULL;
1501 /* If none are acceptable then let the completer handle it. */
1504 #ifndef NO_FORCE_FIGNORE
1506 names[0] = (char *)NULL;
1514 #ifdef NO_FORCE_FIGNORE
1516 free (oldnames[--oidx]);
1520 /* If only one is acceptable, copy it to names[0] and return. */
1524 names[0] = newnames[1];
1525 names[1] = (char *)NULL;
1530 /* Copy the acceptable names back to NAMES, set the new array end,
1532 for (nidx = 1; newnames[nidx]; nidx++)
1533 names[nidx] = newnames[nidx];
1534 names[nidx] = (char *)NULL;
1539 name_is_acceptable (name)
1545 for (nlen = strlen (name), p = fignore.ignores; p->val; p++)
1547 if (nlen > p->len && p->len > 0 && STREQ (p->val, &name[nlen - p->len]))
1555 filename_completion_ignore (names)
1558 setup_ignore_patterns (&fignore);
1560 if (fignore.num_ignores == 0)
1563 _ignore_completion_names (names, name_is_acceptable);
1566 /* Return 1 if NAME is a directory. */
1568 test_for_directory (name)
1574 fn = bash_tilde_expand (name);
1575 if (stat (fn, &finfo) != 0)
1581 return (S_ISDIR (finfo.st_mode));
1584 /* Remove files from NAMES, leaving directories. */
1586 bash_ignore_filenames (names)
1589 _ignore_completion_names (names, test_for_directory);
1592 /* Handle symbolic link references and other directory name
1593 expansions while hacking completion. */
1595 bash_directory_completion_hook (dirname)
1598 char *local_dirname, *t;
1599 int return_value = 0;
1602 local_dirname = *dirname;
1603 if (strchr (local_dirname, '$') || strchr (local_dirname, '`'))
1605 wl = expand_string (local_dirname, 0);
1608 *dirname = string_list (wl);
1609 /* Tell the completer to replace the directory name only if we
1610 actually expanded something. */
1611 return_value = STREQ (local_dirname, *dirname) == 0;
1612 free (local_dirname);
1614 local_dirname = *dirname;
1618 free (local_dirname);
1619 *dirname = xmalloc (1);
1625 if (!no_symbolic_links && (local_dirname[0] != '.' || local_dirname[1]))
1627 char *temp1, *temp2;
1630 t = get_working_directory ("symlink-hook");
1631 temp1 = make_absolute (local_dirname, t);
1633 temp2 = canonicalize_pathname (temp1);
1634 /* If we can't canonicalize, bail. */
1640 len1 = strlen (temp1);
1641 if (temp1[len1 - 1] == '/')
1643 len2 = strlen (temp2);
1644 temp2 = xrealloc (temp2, len2 + 2);
1646 temp2[len2 + 1] = '\0';
1648 free (local_dirname);
1652 return (return_value);
1655 static char **history_completion_array = (char **)NULL;
1656 static int harry_size;
1657 static int harry_len;
1660 build_history_completion_array ()
1666 /* First, clear out the current dynamic history completion list. */
1669 for (i = 0; history_completion_array[i]; i++)
1670 free (history_completion_array[i]);
1672 free (history_completion_array);
1674 history_completion_array = (char **)NULL;
1679 /* Next, grovel each line of history, making each shell-sized token
1680 a separate entry in the history_completion_array. */
1681 hlist = history_list ();
1685 for (i = 0; hlist[i]; i++)
1687 /* Separate each token, and place into an array. */
1688 tokens = history_tokenize (hlist[i]->line);
1690 for (j = 0; tokens && tokens[j]; j++)
1692 if (harry_len + 2 > harry_size)
1695 history_completion_array = (char **) xrealloc
1696 (history_completion_array, harry_size * sizeof (char *));
1699 history_completion_array[harry_len++] = tokens[j];
1700 history_completion_array[harry_len] = (char *)NULL;
1705 /* Sort the complete list of tokens. */
1706 qsort (history_completion_array, harry_len, sizeof (char *), (Function *)qsort_string_compare);
1711 history_completion_generator (hint_text, state)
1715 static int local_index, len;
1718 /* If this is the first call to the generator, then initialize the
1719 list of strings to complete over. */
1723 build_history_completion_array ();
1725 len = strlen (text);
1728 while (history_completion_array && history_completion_array[local_index])
1730 if (strncmp (text, history_completion_array[local_index++], len) == 0)
1731 return (savestring (history_completion_array[local_index - 1]));
1733 return ((char *)NULL);
1737 dynamic_complete_history (count, key)
1740 Function *orig_func;
1741 CPPFunction *orig_attempt_func;
1743 orig_func = rl_completion_entry_function;
1744 orig_attempt_func = rl_attempted_completion_function;
1745 rl_completion_entry_function = (Function *)history_completion_generator;
1746 rl_attempted_completion_function = (CPPFunction *)NULL;
1748 if (rl_last_func == (Function *)dynamic_complete_history)
1749 rl_complete_internal ('?');
1751 rl_complete_internal (TAB);
1753 rl_completion_entry_function = orig_func;
1754 rl_attempted_completion_function = orig_attempt_func;
1757 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
1759 bash_complete_username (ignore, ignore2)
1760 int ignore, ignore2;
1762 bash_complete_username_internal (TAB);
1766 bash_possible_username_completions (ignore, ignore2)
1767 int ignore, ignore2;
1769 bash_complete_username_internal ('?');
1773 bash_complete_username_internal (what_to_do)
1776 bash_specific_completion
1777 (what_to_do, (Function *)username_completion_function);
1781 bash_complete_filename (ignore, ignore2)
1782 int ignore, ignore2;
1784 bash_complete_filename_internal (TAB);
1788 bash_possible_filename_completions (ignore, ignore2)
1789 int ignore, ignore2;
1791 bash_complete_filename_internal ('?');
1795 bash_complete_filename_internal (what_to_do)
1798 Function *orig_func, *orig_dir_func;
1799 CPPFunction *orig_attempt_func;
1800 char *orig_rl_completer_word_break_characters;
1802 orig_func = rl_completion_entry_function;
1803 orig_attempt_func = rl_attempted_completion_function;
1804 orig_dir_func = rl_directory_completion_hook;
1805 orig_rl_completer_word_break_characters = rl_completer_word_break_characters;
1806 rl_completion_entry_function = (Function *)filename_completion_function;
1807 rl_attempted_completion_function = (CPPFunction *)NULL;
1808 rl_directory_completion_hook = (Function *)NULL;
1809 rl_completer_word_break_characters = " \t\n\"\'";
1811 rl_complete_internal (what_to_do);
1813 rl_completion_entry_function = orig_func;
1814 rl_attempted_completion_function = orig_attempt_func;
1815 rl_directory_completion_hook = orig_dir_func;
1816 rl_completer_word_break_characters = orig_rl_completer_word_break_characters;
1820 bash_complete_hostname (ignore, ignore2)
1821 int ignore, ignore2;
1823 bash_complete_hostname_internal (TAB);
1827 bash_possible_hostname_completions (ignore, ignore2)
1828 int ignore, ignore2;
1830 bash_complete_hostname_internal ('?');
1834 bash_complete_variable (ignore, ignore2)
1835 int ignore, ignore2;
1837 bash_complete_variable_internal (TAB);
1841 bash_possible_variable_completions (ignore, ignore2)
1842 int ignore, ignore2;
1844 bash_complete_variable_internal ('?');
1848 bash_complete_command (ignore, ignore2)
1849 int ignore, ignore2;
1851 bash_complete_command_internal (TAB);
1855 bash_possible_command_completions (ignore, ignore2)
1856 int ignore, ignore2;
1858 bash_complete_command_internal ('?');
1862 bash_complete_hostname_internal (what_to_do)
1865 bash_specific_completion
1866 (what_to_do, (Function *)hostname_completion_function);
1870 bash_complete_variable_internal (what_to_do)
1873 bash_specific_completion
1874 (what_to_do, (Function *)variable_completion_function);
1878 bash_complete_command_internal (what_to_do)
1881 bash_specific_completion
1882 (what_to_do, (Function *)command_word_completion_function);
1886 glob_complete_word (text, state)
1890 static char **matches = (char **)NULL;
1896 rl_filename_completion_desired = 1;
1899 matches = shell_glob_filename (text);
1900 if (GLOB_FAILED (matches))
1901 matches = (char **)NULL;
1905 ret = matches ? matches[ind] : (char *)NULL;
1911 bash_glob_completion_internal (what_to_do)
1914 bash_specific_completion (what_to_do, (Function *)glob_complete_word);
1918 bash_glob_expand_word (count, key)
1921 bash_glob_completion_internal ('*');
1925 bash_glob_list_expansions (count, key)
1928 bash_glob_completion_internal ('?');
1932 bash_specific_completion (what_to_do, generator)
1934 Function *generator;
1936 Function *orig_func;
1937 CPPFunction *orig_attempt_func;
1939 orig_func = rl_completion_entry_function;
1940 orig_attempt_func = rl_attempted_completion_function;
1941 rl_completion_entry_function = generator;
1942 rl_attempted_completion_function = (CPPFunction *)NULL;
1944 rl_complete_internal (what_to_do);
1946 rl_completion_entry_function = orig_func;
1947 rl_attempted_completion_function = orig_attempt_func;
1950 #endif /* SPECIFIC_COMPLETION_FUNCTIONS */
1952 /* Filename quoting for completion. */
1953 /* A function to strip quotes that are not protected by backquotes. It
1954 allows single quotes to appear within double quotes, and vice versa.
1955 It should be smarter. */
1957 bash_dequote_filename (text, quote_char)
1964 ret = xmalloc (l + 1);
1965 for (quoted = quote_char, p = text, r = ret; p && *p; p++)
1967 /* Allow backslash-quoted characters to pass through unscathed. */
1976 if (quoted && *p == quoted)
1982 if (quoted == 0 && (*p == '\'' || *p == '"'))
1993 /* Quote characters that the readline completion code would treat as
1994 word break characters with backslashes. Pass backslash-quoted
1995 characters through without examination. */
1997 quote_word_break_chars (text)
2004 ret = xmalloc ((2 * l) + 1);
2005 for (s = text, r = ret; *s; s++)
2007 /* Pass backslash-quoted characters through, including the backslash. */
2016 /* OK, we have an unquoted character. Check its presence in
2017 rl_completer_word_break_characters. */
2018 if (strchr (rl_completer_word_break_characters, *s))
2026 /* Quote a filename using double quotes, single quotes, or backslashes
2027 depending on the value of completion_quoting_style. If we're
2028 completing using backslashes, we need to quote some additional
2029 characters (those that readline treats as word breaks), so we call
2030 quote_word_break_chars on the result. */
2032 bash_quote_filename (s, rtype, qcp)
2037 char *rtext, *mtext, *ret;
2040 rtext = (char *)NULL;
2042 /* If RTYPE == MULT_MATCH, it means that there is
2043 more than one match. In this case, we do not add
2044 the closing quote or attempt to perform tilde
2045 expansion. If RTYPE == SINGLE_MATCH, we try
2046 to perform tilde expansion, because single and double
2047 quotes inhibit tilde expansion by the shell. */
2050 if (mtext[0] == '~' && rtype == SINGLE_MATCH)
2051 mtext = bash_tilde_expand (s);
2053 cs = completion_quoting_style;
2054 /* Might need to modify the default completion style based on *qcp,
2055 since it's set to any user-provided opening quote. */
2057 cs = COMPLETE_DQUOTE;
2058 else if (*qcp == '\'')
2059 cs = COMPLETE_SQUOTE;
2060 #if defined (BANG_HISTORY)
2061 else if (*qcp == '\0' && history_expansion && cs == COMPLETE_DQUOTE &&
2062 history_expansion_inhibited == 0 && strchr (mtext, '!'))
2063 cs = COMPLETE_BSQUOTE;
2065 if (*qcp == '"' && history_expansion && cs == COMPLETE_DQUOTE &&
2066 history_expansion_inhibited == 0 && strchr (mtext, '!'))
2068 cs = COMPLETE_BSQUOTE;
2075 case COMPLETE_DQUOTE:
2076 rtext = double_quote (mtext);
2078 case COMPLETE_SQUOTE:
2079 rtext = single_quote (mtext);
2081 case COMPLETE_BSQUOTE:
2082 rtext = backslash_quote (mtext);
2089 /* We may need to quote additional characters: those that readline treats
2090 as word breaks that are not quoted by backslash_quote. */
2091 if (rtext && cs == COMPLETE_BSQUOTE)
2093 mtext = quote_word_break_chars (rtext);
2098 /* Leave the opening quote intact. The readline completion code takes
2099 care of avoiding doubled opening quotes. */
2100 rlen = strlen (rtext);
2101 ret = xmalloc (rlen + 1);
2102 strcpy (ret, rtext);
2104 /* If there are multiple matches, cut off the closing quote. */
2105 if (rtype == MULT_MATCH && cs != COMPLETE_BSQUOTE)
2106 ret[rlen - 1] = '\0';
2111 #endif /* READLINE */