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);
217 rl_add_defun ("history-and-alias-expand-line", (Function *)history_and_alias_expand_line, -1);
221 /* Backwards compatibility. */
222 rl_add_defun ("insert-last-argument", rl_yank_last_arg, -1);
225 ("operate-and-get-next", (Function *)operate_and_get_next, CTRL('O'));
228 ("display-shell-version", (Function *)display_shell_version, -1);
230 (CTRL ('V'), (Function *)display_shell_version, emacs_ctlx_keymap);
232 /* In Bash, the user can switch editing modes with "set -o [vi emacs]",
233 so it is not necessary to allow C-M-j for context switching. Turn
234 off this occasionally confusing behaviour. */
235 rl_unbind_key_in_map (CTRL('J'), emacs_meta_keymap);
236 rl_unbind_key_in_map (CTRL('M'), emacs_meta_keymap);
237 #if defined (VI_MODE)
238 rl_unbind_key_in_map (CTRL('E'), vi_movement_keymap);
241 #if defined (BRACE_COMPLETION)
242 rl_add_defun ("complete-into-braces", bash_brace_completion, -1);
243 rl_bind_key_in_map ('{', bash_brace_completion, emacs_meta_keymap);
244 #endif /* BRACE_COMPLETION */
246 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
247 rl_add_defun ("complete-filename", bash_complete_filename, -1);
248 rl_bind_key_in_map ('/', bash_complete_filename, emacs_meta_keymap);
249 rl_add_defun ("possible-filename-completions",
250 bash_possible_filename_completions, -1);
251 rl_bind_key_in_map ('/', bash_possible_filename_completions, emacs_ctlx_keymap);
253 rl_add_defun ("complete-username", bash_complete_username, -1);
254 rl_bind_key_in_map ('~', bash_complete_username, emacs_meta_keymap);
255 rl_add_defun ("possible-username-completions",
256 bash_possible_username_completions, -1);
257 rl_bind_key_in_map ('~', bash_possible_username_completions, emacs_ctlx_keymap);
259 rl_add_defun ("complete-hostname", bash_complete_hostname, -1);
260 rl_bind_key_in_map ('@', bash_complete_hostname, emacs_meta_keymap);
261 rl_add_defun ("possible-hostname-completions",
262 bash_possible_hostname_completions, -1);
263 rl_bind_key_in_map ('@', bash_possible_hostname_completions, emacs_ctlx_keymap);
265 rl_add_defun ("complete-variable", bash_complete_variable, -1);
266 rl_bind_key_in_map ('$', bash_complete_variable, emacs_meta_keymap);
267 rl_add_defun ("possible-variable-completions",
268 bash_possible_variable_completions, -1);
269 rl_bind_key_in_map ('$', bash_possible_variable_completions, emacs_ctlx_keymap);
271 rl_add_defun ("complete-command", bash_complete_command, -1);
272 rl_bind_key_in_map ('!', bash_complete_command, emacs_meta_keymap);
273 rl_add_defun ("possible-command-completions",
274 bash_possible_command_completions, -1);
275 rl_bind_key_in_map ('!', bash_possible_command_completions, emacs_ctlx_keymap);
277 rl_add_defun ("glob-expand-word", bash_glob_expand_word, -1);
278 rl_add_defun ("glob-list-expansions", bash_glob_list_expansions, -1);
279 rl_bind_key_in_map ('*', bash_glob_expand_word, emacs_ctlx_keymap);
280 rl_bind_key_in_map ('g', bash_glob_list_expansions, emacs_ctlx_keymap);
282 #endif /* SPECIFIC_COMPLETION_FUNCTIONS */
284 rl_add_defun ("dynamic-complete-history", dynamic_complete_history, -1);
285 rl_bind_key_in_map (TAB, dynamic_complete_history, emacs_meta_keymap);
287 /* Tell the completer that we want a crack first. */
288 rl_attempted_completion_function = (CPPFunction *)attempt_shell_completion;
290 /* Tell the completer that we might want to follow symbolic links or
291 do other expansion on directory names. */
292 rl_directory_completion_hook = bash_directory_completion_hook;
294 /* Tell the filename completer we want a chance to ignore some names. */
295 rl_ignore_some_completions_function = (Function *)filename_completion_ignore;
297 #if defined (VI_MODE)
298 rl_bind_key_in_map ('v', vi_edit_and_execute_command, vi_movement_keymap);
300 rl_bind_key_in_map ('@', posix_edit_macros, vi_movement_keymap);
304 rl_completer_quote_characters = "'\"";
306 /* This sets rl_completer_word_break_characters and rl_special_prefixes
307 to the appropriate values, depending on whether or not hostname
308 completion is enabled. */
309 enable_hostname_completion (perform_hostname_completion);
311 /* characters that need to be quoted when appearing in filenames. */
312 rl_filename_quote_characters = " \t\n\\\"'@<>=;|&()#$`?*[!:";
313 rl_filename_quoting_function = bash_quote_filename;
314 rl_filename_dequoting_function = bash_dequote_filename;
315 rl_char_is_quoted_p = char_is_quoted;
318 posix_readline_initialize (1);
320 bash_readline_initialized = 1;
323 /* On Sun systems at least, rl_attempted_completion_function can end up
324 getting set to NULL, and rl_completion_entry_function set to do command
325 word completion if Bash is interrupted while trying to complete a command
326 word. This just resets all the completion functions to the right thing.
327 It's called from throw_to_top_level(). */
329 bashline_reinitialize ()
332 rl_attempted_completion_function = attempt_shell_completion;
333 rl_completion_entry_function = (Function *)NULL;
334 rl_directory_completion_hook = bash_directory_completion_hook;
335 rl_ignore_some_completions_function = (Function *)filename_completion_ignore;
338 /* Contains the line to push into readline. */
339 static char *push_to_readline = (char *)NULL;
341 /* Push the contents of push_to_readline into the
346 if (push_to_readline)
348 rl_insert_text (push_to_readline);
349 free (push_to_readline);
350 push_to_readline = (char *)NULL;
351 rl_startup_hook = old_rl_startup_hook;
355 /* Call this to set the initial text for the next line to read
361 FREE (push_to_readline);
363 push_to_readline = savestring (line);
364 old_rl_startup_hook = rl_startup_hook;
365 rl_startup_hook = (Function *)bash_push_line;
371 display_shell_version (count, c)
375 show_shell_version (0);
376 putc ('\r', rl_outstream);
377 fflush (rl_outstream);
382 /* **************************************************************** */
386 /* **************************************************************** */
388 /* If the user requests hostname completion, then simply build a list
389 of hosts, and complete from that forever more. */
391 /* The kept list of hostnames. */
392 static char **hostname_list = (char **)NULL;
394 /* The physical size of the above list. */
395 static int hostname_list_size;
397 /* The number of hostnames in the above list. */
398 static int hostname_list_length;
400 /* Whether or not HOSTNAME_LIST has been initialized. */
401 int hostname_list_initialized = 0;
403 /* Initialize the hostname completion table. */
405 initialize_hostname_list ()
409 temp = get_string_value ("HOSTFILE");
411 temp = get_string_value ("hostname_completion_file");
413 temp = DEFAULT_HOSTS_FILE;
415 snarf_hosts_from_file (temp);
418 hostname_list_initialized++;
421 /* Add NAME to the list of hosts. */
428 if (hostname_list_length + 2 > hostname_list_size)
430 hostname_list_size = (hostname_list_size + 32) - (hostname_list_size % 32);
431 size = hostname_list_size * sizeof (char *);
432 hostname_list = (char **)xrealloc (hostname_list, size);
435 hostname_list[hostname_list_length++] = savestring (name);
436 hostname_list[hostname_list_length] = (char *)NULL;
439 #define cr_whitespace(c) ((c) == '\r' || (c) == '\n' || whitespace(c))
442 snarf_hosts_from_file (filename)
446 char *temp, buffer[256], name[256];
447 register int i, start;
449 file = fopen (filename, "r");
453 while (temp = fgets (buffer, 255, file))
455 /* Skip to first character. */
456 for (i = 0; buffer[i] && cr_whitespace (buffer[i]); i++)
459 /* If comment or blank line, ignore. */
460 if (buffer[i] == '\0' || buffer[i] == '#')
463 /* If `preprocessor' directive, do the include. */
464 if (strncmp (buffer + i, "$include ", 9) == 0)
468 /* Find start of filename. */
469 for (incfile = buffer + i + 9; *incfile && whitespace (*incfile); incfile++)
472 /* Find end of filename. */
473 for (t = incfile; *t && cr_whitespace (*t) == 0; t++)
478 snarf_hosts_from_file (incfile);
482 /* Skip internet address if present. */
483 if (digit (buffer[i]))
484 for (; buffer[i] && cr_whitespace (buffer[i]) == 0; i++);
486 /* Gobble up names. Each name is separated with whitespace. */
489 for (; cr_whitespace (buffer[i]); i++)
491 if (buffer[i] == '\0' || buffer[i] == '#')
494 /* Isolate the current word. */
495 for (start = i; buffer[i] && cr_whitespace (buffer[i]) == 0; i++)
499 strncpy (name, buffer + start, i - start);
500 name[i - start] = '\0';
501 add_host_name (name);
507 /* Return a NULL terminated list of hostnames which begin with TEXT.
508 Initialize the hostname list the first time if neccessary.
509 The array is malloc ()'ed, but not the individual strings. */
511 hostnames_matching (text)
514 register int i, len, nmatch, rsize;
517 if (hostname_list_initialized == 0)
518 initialize_hostname_list ();
520 if (hostname_list_initialized == 0)
521 return ((char **)NULL);
523 /* Special case. If TEXT consists of nothing, then the whole list is
527 result = (char **)xmalloc ((1 + hostname_list_length) * sizeof (char *));
528 for (i = 0; i < hostname_list_length; i++)
529 result[i] = hostname_list[i];
530 result[i] = (char *)NULL;
534 /* Scan until found, or failure. */
536 result = (char **)NULL;
537 for (i = nmatch = rsize = 0; i < hostname_list_length; i++)
539 if (STREQN (text, hostname_list[i], len) == 0)
542 /* OK, it matches. Add it to the list. */
543 if (nmatch >= (rsize - 1))
545 rsize = (rsize + 16) - (rsize % 16);
546 result = (char **)xrealloc (result, rsize * sizeof (char *));
549 result[nmatch++] = hostname_list[i];
552 result[nmatch] = (char *)NULL;
556 /* The equivalent of the Korn shell C-o operate-and-get-next-history-line
558 static int saved_history_line_to_use = -1;
563 if (saved_history_line_to_use >= 0)
564 rl_get_previous_history (history_length - saved_history_line_to_use);
565 saved_history_line_to_use = -1;
566 rl_startup_hook = old_rl_startup_hook;
570 operate_and_get_next (count, c)
575 /* Accept the current line. */
578 /* Find the current line, and find the next line to use. */
579 where = where_history ();
581 if ((history_is_stifled () && (history_length >= max_input_history)) ||
582 (where >= history_length - 1))
583 saved_history_line_to_use = where;
585 saved_history_line_to_use = where + 1;
587 old_rl_startup_hook = rl_startup_hook;
588 rl_startup_hook = (Function *)set_saved_history;
591 #if defined (VI_MODE)
592 /* This vi mode command causes VI_EDIT_COMMAND to be run on the current
593 command being entered (if no explicit argument is given), otherwise on
594 a command from the history file. */
596 #define VI_EDIT_COMMAND "fc -e ${VISUAL:-${EDITOR:-vi}}"
599 vi_edit_and_execute_command (count, c)
604 /* Accept the current line. */
609 command = xmalloc (strlen (VI_EDIT_COMMAND) + 8);
610 sprintf (command, "%s %d", VI_EDIT_COMMAND, count);
614 /* Take the command we were just editing, add it to the history file,
615 then call fc to operate on it. We have to add a dummy command to
616 the end of the history because fc ignores the last command (assumes
617 it's supposed to deal with the command before the `fc'). */
619 bash_add_history (rl_line_buffer);
620 bash_add_history ("");
621 history_lines_this_session++;
623 command = savestring (VI_EDIT_COMMAND);
625 parse_and_execute (command, "v", SEVAL_NOHIST);
626 rl_line_buffer[0] = '\0'; /* XXX */
632 posix_edit_macros (count, key)
636 char alias_name[3], *alias_value, *macro;
641 alias_name[2] = '\0';
643 alias_value = get_alias_value (alias_name);
644 if (alias_value && *alias_value)
646 macro = savestring (alias_value);
647 rl_push_macro_input (macro);
653 /* **************************************************************** */
655 /* How To Do Shell Completion */
657 /* **************************************************************** */
659 /* Do some completion on TEXT. The indices of TEXT in RL_LINE_BUFFER are
660 at START and END. Return an array of matches, or NULL if none. */
662 attempt_shell_completion (text, start, end)
666 int in_command_position, ti;
667 char **matches, *command_separator_chars;
669 command_separator_chars = ";|&{(`";
670 matches = (char **)NULL;
671 rl_ignore_some_completions_function = (Function *)filename_completion_ignore;
673 /* Determine if this could be a command word. It is if it appears at
674 the start of the line (ignoring preceding whitespace), or if it
675 appears after a character that separates commands. It cannot be a
676 command word if we aren't at the top-level prompt. */
679 while ((ti > -1) && (whitespace (rl_line_buffer[ti])))
682 in_command_position = 0;
685 /* Only do command completion at the start of a line when we
686 are prompting at the top level. */
687 if (current_prompt_string == ps1_prompt)
688 in_command_position++;
690 else if (member (rl_line_buffer[ti], command_separator_chars))
692 register int this_char, prev_char;
694 in_command_position++;
696 /* Handle the two character tokens `>&', `<&', and `>|'.
697 We are not in a command position after one of these. */
698 this_char = rl_line_buffer[ti];
699 prev_char = rl_line_buffer[ti - 1];
701 if ((this_char == '&' && (prev_char == '<' || prev_char == '>')) ||
702 (this_char == '|' && prev_char == '>'))
703 in_command_position = 0;
704 else if ((this_char == '{' && prev_char == '$') ||
705 (char_is_quoted (rl_line_buffer, ti)))
706 in_command_position = 0;
710 /* This still could be in command position. It is possible
711 that all of the previous words on the line are variable
715 /* Check that we haven't incorrectly flagged a closed command substitution
716 as indicating we're in a command position. */
717 if (in_command_position && ti >= 0 && rl_line_buffer[ti] == '`' &&
718 *text != '`' && unclosed_pair (rl_line_buffer, 0, "`") == 0)
719 in_command_position = 0;
721 /* Special handling for command substitution. If *TEXT is a backquote,
722 it can be the start or end of an old-style command substitution, or
723 unmatched. If it's unmatched, both calls to unclosed_pair will
725 if (*text == '`' && unclosed_pair (rl_line_buffer, start, "`") &&
726 unclosed_pair (rl_line_buffer, end, "`"))
727 matches = completion_matches (text, command_subst_completion_function);
730 if (!matches && *text == '$')
731 matches = completion_matches (text, variable_completion_function);
733 /* If the word starts in `~', and there is no slash in the word, then
734 try completing this word as a username. */
735 if (!matches && *text == '~' && !strchr (text, '/'))
736 matches = completion_matches (text, username_completion_function);
738 /* Another one. Why not? If the word starts in '@', then look through
739 the world of known hostnames for completion first. */
740 if (!matches && perform_hostname_completion && *text == '@')
741 matches = completion_matches (text, hostname_completion_function);
743 /* And last, (but not least) if this word is in a command position, then
744 complete over possible command names, including aliases, functions,
745 and command names. */
746 if (!matches && in_command_position)
748 matches = completion_matches (text, command_word_completion_function);
749 /* If we are attempting command completion and nothing matches, we
750 do not want readline to perform filename completion for us. We
751 still want to be able to complete partial pathnames, so set the
752 completion ignore function to something which will remove filenames
753 and leave directories in the match list. */
755 rl_ignore_some_completions_function = (Function *)bash_ignore_filenames;
758 /* This could be a globbing pattern, so try to expand it using pathname
760 if (!matches && glob_pattern_p (text))
762 matches = completion_matches (text, glob_complete_word);
763 /* A glob expression that matches more than one filename is problematic.
764 If we match more than one filename, punt. */
765 if (matches && matches[1])
767 free_array (matches);
768 matches = (char **)0;
775 /* This is the function to call when the word to complete is in a position
776 where a command word can be found. It grovels $PATH, looking for commands
777 that match. It also scans aliases, function names, and the shell_builtin
780 command_word_completion_function (hint_text, state)
784 static char *hint = (char *)NULL;
785 static char *path = (char *)NULL;
786 static char *val = (char *)NULL;
787 static char *filename_hint = (char *)NULL;
788 static int path_index, hint_len, istate;
789 static int mapping_over, local_index;
790 static SHELL_VAR **varlist = (SHELL_VAR **)NULL;
792 static alias_t **alias_list = (alias_t **)NULL;
795 /* We have to map over the possibilities for command words. If we have
796 no state, then make one just for that purpose. */
805 /* If this is an absolute program name, do not check it against
806 aliases, reserved words, functions or builtins. We must check
807 whether or not it is unique, and, if so, whether that filename
809 if (absolute_program (hint_text))
811 /* Perform tilde expansion on what's passed, so we don't end up
812 passing filenames with tildes directly to stat(). */
813 if (*hint_text == '~')
814 hint = bash_tilde_expand (hint_text);
816 hint = savestring (hint_text);
817 hint_len = strlen (hint);
820 free (filename_hint);
821 filename_hint = savestring (hint);
828 hint = savestring (hint_text);
829 hint_len = strlen (hint);
831 path = get_string_value ("PATH");
834 /* Initialize the variables for each type of command word. */
840 varlist = all_visible_functions ();
846 alias_list = all_aliases ();
850 /* mapping_over says what we are currently hacking. Note that every case
851 in this list must fall through when there are no more possibilities. */
853 switch (mapping_over)
855 case 0: /* Aliases come first. */
857 while (alias_list && alias_list[local_index])
859 register char *alias;
861 alias = alias_list[local_index++]->name;
863 if (STREQN (alias, hint, hint_len))
864 return (savestring (alias));
870 case 1: /* Then shell reserved words. */
872 while (word_token_alist[local_index].word)
874 register char *reserved_word;
876 reserved_word = word_token_alist[local_index++].word;
878 if (STREQN (reserved_word, hint, hint_len))
879 return (savestring (reserved_word));
885 case 2: /* Then function names. */
886 while (varlist && varlist[local_index])
888 register char *varname;
890 varname = varlist[local_index++]->name;
892 if (STREQN (varname, hint, hint_len))
893 return (savestring (varname));
898 case 3: /* Then shell builtins. */
899 for (; local_index < num_shell_builtins; local_index++)
901 /* Ignore it if it doesn't have a function pointer or if it
902 is not currently enabled. */
903 if (!shell_builtins[local_index].function ||
904 (shell_builtins[local_index].flags & BUILTIN_ENABLED) == 0)
907 if (STREQN (shell_builtins[local_index].name, hint, hint_len))
909 int i = local_index++;
911 return (savestring (shell_builtins[i].name));
918 /* Repeatedly call filename_completion_function while we have
919 members of PATH left. Question: should we stat each file?
920 Answer: we call executable_file () on each file. */
923 istate = (val != (char *)NULL);
929 /* Get the next directory from the path. If there is none, then we
931 if (!path || !path[path_index] ||
932 (current_path = extract_colon_unit (path, &path_index)) == 0)
933 return ((char *)NULL);
935 if (*current_path == 0)
938 current_path = savestring (".");
941 if (*current_path == '~')
945 t = bash_tilde_expand (current_path);
951 free (filename_hint);
953 filename_hint = xmalloc (2 + strlen (current_path) + hint_len);
954 sprintf (filename_hint, "%s/%s", current_path, hint);
960 val = filename_completion_function (filename_hint, istate);
965 /* If the hint text is an absolute program, then don't bother
966 searching through PATH. */
967 if (absolute_program (hint))
968 return ((char *)NULL);
977 if (absolute_program (hint))
979 match = strncmp (val, hint, hint_len) == 0;
980 /* If we performed tilde expansion, restore the original
982 if (*hint_text == '~')
986 tl = strlen (hint_text);
987 l = vl - hint_len; /* # of chars added */
988 temp = xmalloc (l + 2 + tl);
989 strcpy (temp, hint_text);
990 strcpy (temp + tl, val + vl - l);
993 temp = savestring (val);
998 temp = strrchr (val, '/');
1003 freetemp = match = strncmp (temp, hint, hint_len) == 0;
1005 temp = savestring (temp);
1008 freetemp = match = 0;
1011 /* If we have found a match, and it is an executable file or a
1012 directory name, return it. */
1013 if (match && (executable_file (val) || is_directory (val)))
1016 val = ""; /* So it won't be NULL. */
1029 /* Completion inside an unterminated command substitution. */
1031 command_subst_completion_function (text, state)
1035 static char **matches = (char **)NULL;
1036 static char *orig_start, *filename_text = (char *)NULL;
1037 static int cmd_index, start_len;
1043 free (filename_text);
1047 else if (*text == '$' && text[1] == '(') /* ) */
1049 start_len = text - orig_start;
1050 filename_text = savestring (text);
1053 matches = completion_matches (filename_text, command_word_completion_function);
1057 if (!matches || !matches[cmd_index])
1059 rl_filename_quoting_desired = 0; /* disable quoting */
1060 return ((char *)NULL);
1064 value = xmalloc (1 + start_len + strlen (matches[cmd_index]));
1067 value[0] = *orig_start;
1069 strncpy (value, orig_start, start_len);
1071 strcpy (value + start_len, matches[cmd_index]);
1078 /* Okay, now we write the entry_function for variable completion. */
1080 variable_completion_function (text, state)
1084 register SHELL_VAR *var = (SHELL_VAR *)NULL;
1085 static SHELL_VAR **varlist = (SHELL_VAR **)NULL;
1086 static int varlist_index;
1087 static char *varname = (char *)NULL;
1089 static int first_char, first_char_loc;
1097 first_char = text[0];
1099 if (first_char == '$')
1102 if (text[first_char_loc] == '{')
1105 varname = savestring (text + first_char_loc);
1107 namelen = strlen (varname);
1110 varlist = all_visible_variables ();
1114 while (varlist && varlist[varlist_index])
1116 var = varlist[varlist_index];
1118 /* Compare. You can't do better than Zayre. No text is also
1120 if (!*varname || (strncmp (varname, var->name, namelen) == 0))
1125 if (!varlist || !varlist[varlist_index])
1127 return ((char *)NULL);
1131 char *value = xmalloc (4 + strlen (var->name));
1135 value[0] = first_char;
1136 if (first_char_loc == 2)
1140 strcpy (&value[first_char_loc], var->name);
1141 if (first_char_loc == 2)
1142 strcat (value, "}");
1149 /* How about a completion function for hostnames? */
1151 hostname_completion_function (text, state)
1155 static char **list = (char **)NULL;
1156 static int list_index = 0;
1157 static int first_char, first_char_loc;
1159 /* If we don't have any state, make some. */
1164 list = (char **)NULL;
1169 if (first_char == '@')
1172 list = hostnames_matching (&text[first_char_loc]);
1176 if (list && list[list_index])
1180 t = xmalloc (2 + strlen (list[list_index]));
1182 strcpy (t + first_char_loc, list[list_index]);
1187 return ((char *)NULL);
1190 /* Functions to perform history and alias expansions on the current line. */
1192 #if defined (BANG_HISTORY)
1193 /* Perform history expansion on the current line. If no history expansion
1194 is done, pre_process_line() returns what it was passed, so we need to
1195 allocate a new line here. */
1197 history_expand_line_internal (line)
1202 new_line = pre_process_line (line, 0, 0);
1203 return (new_line == line) ? savestring (line) : new_line;
1207 /* There was an error in expansion. Let the preprocessor print
1210 cleanup_expansion_error ()
1214 fprintf (rl_outstream, "\r\n");
1215 to_free = pre_process_line (rl_line_buffer, 1, 0);
1216 if (to_free != rl_line_buffer)
1218 putc ('\r', rl_outstream);
1219 rl_forced_update_display ();
1222 /* If NEW_LINE differs from what is in the readline line buffer, add an
1223 undo record to get from the readline line buffer contents to the new
1224 line and make NEW_LINE the current readline line. */
1226 maybe_make_readline_line (new_line)
1229 if (strcmp (new_line, rl_line_buffer) != 0)
1233 rl_add_undo (UNDO_BEGIN, 0, 0, 0);
1234 rl_delete_text (0, rl_point);
1235 rl_point = rl_end = 0;
1236 rl_insert_text (new_line);
1237 rl_add_undo (UNDO_END, 0, 0, 0);
1241 /* Make NEW_LINE be the current readline line. This frees NEW_LINE. */
1243 set_up_new_line (new_line)
1246 int old_point = rl_point;
1247 int at_end = rl_point == rl_end;
1249 /* If the line was history and alias expanded, then make that
1250 be one thing to undo. */
1251 maybe_make_readline_line (new_line);
1254 /* Place rl_point where we think it should go. */
1257 else if (old_point < rl_end)
1259 rl_point = old_point;
1260 if (!whitespace (rl_line_buffer[rl_point]))
1261 rl_forward_word (1);
1266 /* Expand aliases in the current readline line. */
1268 alias_expand_line (ignore)
1273 new_line = alias_expand (rl_line_buffer);
1277 set_up_new_line (new_line);
1282 cleanup_expansion_error ();
1288 #if defined (BANG_HISTORY)
1289 /* History expand the line. */
1291 history_expand_line (ignore)
1296 new_line = history_expand_line_internal (rl_line_buffer);
1300 set_up_new_line (new_line);
1305 cleanup_expansion_error ();
1310 /* Expand history substitutions in the current line and then insert a
1311 space wherever set_up_new_line decided to put rl_point. */
1313 tcsh_magic_space (ignore)
1316 if (history_expand_line (ignore) == 0)
1326 /* History and alias expand the line. */
1328 history_and_alias_expand_line (ignore)
1333 new_line = pre_process_line (rl_line_buffer, 0, 0);
1334 if (new_line == rl_line_buffer)
1335 new_line = savestring (new_line);
1342 alias_line = alias_expand (new_line);
1344 new_line = alias_line;
1350 set_up_new_line (new_line);
1355 cleanup_expansion_error ();
1360 /* History and alias expand the line, then perform the shell word
1361 expansions by calling expand_string. This can't use set_up_new_line()
1362 because we want the variable expansions as a separate undo'able
1363 set of operations. */
1365 shell_expand_line (ignore)
1369 WORD_LIST *expanded_string;
1371 new_line = pre_process_line (rl_line_buffer, 0, 0);
1372 if (new_line == rl_line_buffer)
1373 new_line = savestring (new_line);
1380 alias_line = alias_expand (new_line);
1382 new_line = alias_line;
1388 int old_point = rl_point;
1389 int at_end = rl_point == rl_end;
1391 /* If the line was history and alias expanded, then make that
1392 be one thing to undo. */
1393 maybe_make_readline_line (new_line);
1396 /* If there is variable expansion to perform, do that as a separate
1397 operation to be undone. */
1398 new_line = savestring (rl_line_buffer);
1399 expanded_string = expand_string (new_line, 0);
1401 if (expanded_string == 0)
1403 new_line = xmalloc (1);
1408 new_line = string_list (expanded_string);
1409 dispose_words (expanded_string);
1412 maybe_make_readline_line (new_line);
1415 /* Place rl_point where we think it should go. */
1418 else if (old_point < rl_end)
1420 rl_point = old_point;
1421 if (!whitespace (rl_line_buffer[rl_point]))
1422 rl_forward_word (1);
1426 cleanup_expansion_error ();
1429 /* Define NO_FORCE_FIGNORE if you want to match filenames that would
1430 otherwise be ignored if they are the only possible matches. */
1431 /* #define NO_FORCE_FIGNORE */
1433 /* If FIGNORE is set, then don't match files with the given suffixes when
1434 completing filenames. If only one of the possibilities has an acceptable
1435 suffix, delete the others, else just return and let the completer
1436 signal an error. It is called by the completer when real
1437 completions are done on filenames by the completer's internal
1438 function, not for completion lists (M-?) and not on "other"
1439 completion types, such as hostnames or commands. */
1441 static struct ignorevar fignore =
1451 _ignore_completion_names (names, name_func)
1453 Function *name_func;
1457 #ifdef NO_FORCE_FIGNORE
1462 /* If there is only one completion, see if it is acceptable. If it is
1463 not, free it up. In any case, short-circuit and return. This is a
1464 special case because names[0] is not the prefix of the list of names
1465 if there is only one completion; it is the completion itself. */
1466 if (names[1] == (char *)0)
1468 #ifndef NO_FORCE_FIGNORE
1469 if ((*name_func) (names[0]) == 0)
1472 names[0] = (char *)NULL;
1478 /* Allocate space for array to hold list of pointers to matching
1479 filenames. The pointers are copied back to NAMES when done. */
1480 for (nidx = 1; names[nidx]; nidx++)
1482 newnames = (char **)xmalloc ((nidx + 1) * (sizeof (char *)));
1483 #ifdef NO_FORCE_FIGNORE
1484 oldnames = (char **)xmalloc ((nidx - 1) * (sizeof (char *)));
1488 newnames[0] = names[0];
1489 for (idx = nidx = 1; names[idx]; idx++)
1491 if ((*name_func) (names[idx]))
1492 newnames[nidx++] = names[idx];
1494 #ifndef NO_FORCE_FIGNORE
1497 oldnames[oidx++] = names[idx];
1501 newnames[nidx] = (char *)NULL;
1503 /* If none are acceptable then let the completer handle it. */
1506 #ifndef NO_FORCE_FIGNORE
1508 names[0] = (char *)NULL;
1516 #ifdef NO_FORCE_FIGNORE
1518 free (oldnames[--oidx]);
1522 /* If only one is acceptable, copy it to names[0] and return. */
1526 names[0] = newnames[1];
1527 names[1] = (char *)NULL;
1532 /* Copy the acceptable names back to NAMES, set the new array end,
1534 for (nidx = 1; newnames[nidx]; nidx++)
1535 names[nidx] = newnames[nidx];
1536 names[nidx] = (char *)NULL;
1541 name_is_acceptable (name)
1547 for (nlen = strlen (name), p = fignore.ignores; p->val; p++)
1549 if (nlen > p->len && p->len > 0 && STREQ (p->val, &name[nlen - p->len]))
1557 filename_completion_ignore (names)
1560 setup_ignore_patterns (&fignore);
1562 if (fignore.num_ignores == 0)
1565 _ignore_completion_names (names, name_is_acceptable);
1568 /* Return 1 if NAME is a directory. */
1570 test_for_directory (name)
1576 fn = bash_tilde_expand (name);
1577 if (stat (fn, &finfo) != 0)
1583 return (S_ISDIR (finfo.st_mode));
1586 /* Remove files from NAMES, leaving directories. */
1588 bash_ignore_filenames (names)
1591 _ignore_completion_names (names, test_for_directory);
1594 /* Handle symbolic link references and other directory name
1595 expansions while hacking completion. */
1597 bash_directory_completion_hook (dirname)
1600 char *local_dirname, *t;
1601 int return_value = 0;
1604 local_dirname = *dirname;
1605 if (strchr (local_dirname, '$') || strchr (local_dirname, '`'))
1607 wl = expand_string (local_dirname, 0);
1610 *dirname = string_list (wl);
1611 /* Tell the completer to replace the directory name only if we
1612 actually expanded something. */
1613 return_value = STREQ (local_dirname, *dirname) == 0;
1614 free (local_dirname);
1616 local_dirname = *dirname;
1620 free (local_dirname);
1621 *dirname = xmalloc (1);
1627 if (!no_symbolic_links && (local_dirname[0] != '.' || local_dirname[1]))
1629 char *temp1, *temp2;
1632 t = get_working_directory ("symlink-hook");
1633 temp1 = make_absolute (local_dirname, t);
1635 temp2 = canonicalize_pathname (temp1);
1636 /* If we can't canonicalize, bail. */
1642 len1 = strlen (temp1);
1643 if (temp1[len1 - 1] == '/')
1645 len2 = strlen (temp2);
1646 temp2 = xrealloc (temp2, len2 + 2);
1648 temp2[len2 + 1] = '\0';
1650 free (local_dirname);
1654 return (return_value);
1657 static char **history_completion_array = (char **)NULL;
1658 static int harry_size;
1659 static int harry_len;
1662 build_history_completion_array ()
1668 /* First, clear out the current dynamic history completion list. */
1671 for (i = 0; history_completion_array[i]; i++)
1672 free (history_completion_array[i]);
1674 free (history_completion_array);
1676 history_completion_array = (char **)NULL;
1681 /* Next, grovel each line of history, making each shell-sized token
1682 a separate entry in the history_completion_array. */
1683 hlist = history_list ();
1687 for (i = 0; hlist[i]; i++)
1689 /* Separate each token, and place into an array. */
1690 tokens = history_tokenize (hlist[i]->line);
1692 for (j = 0; tokens && tokens[j]; j++)
1694 if (harry_len + 2 > harry_size)
1697 history_completion_array = (char **) xrealloc
1698 (history_completion_array, harry_size * sizeof (char *));
1701 history_completion_array[harry_len++] = tokens[j];
1702 history_completion_array[harry_len] = (char *)NULL;
1707 /* Sort the complete list of tokens. */
1708 qsort (history_completion_array, harry_len, sizeof (char *), (Function *)qsort_string_compare);
1713 history_completion_generator (hint_text, state)
1717 static int local_index, len;
1720 /* If this is the first call to the generator, then initialize the
1721 list of strings to complete over. */
1725 build_history_completion_array ();
1727 len = strlen (text);
1730 while (history_completion_array && history_completion_array[local_index])
1732 if (strncmp (text, history_completion_array[local_index++], len) == 0)
1733 return (savestring (history_completion_array[local_index - 1]));
1735 return ((char *)NULL);
1739 dynamic_complete_history (count, key)
1742 Function *orig_func;
1743 CPPFunction *orig_attempt_func;
1745 orig_func = rl_completion_entry_function;
1746 orig_attempt_func = rl_attempted_completion_function;
1747 rl_completion_entry_function = (Function *)history_completion_generator;
1748 rl_attempted_completion_function = (CPPFunction *)NULL;
1750 if (rl_last_func == (Function *)dynamic_complete_history)
1751 rl_complete_internal ('?');
1753 rl_complete_internal (TAB);
1755 rl_completion_entry_function = orig_func;
1756 rl_attempted_completion_function = orig_attempt_func;
1759 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
1761 bash_complete_username (ignore, ignore2)
1762 int ignore, ignore2;
1764 bash_complete_username_internal (TAB);
1768 bash_possible_username_completions (ignore, ignore2)
1769 int ignore, ignore2;
1771 bash_complete_username_internal ('?');
1775 bash_complete_username_internal (what_to_do)
1778 bash_specific_completion
1779 (what_to_do, (Function *)username_completion_function);
1783 bash_complete_filename (ignore, ignore2)
1784 int ignore, ignore2;
1786 bash_complete_filename_internal (TAB);
1790 bash_possible_filename_completions (ignore, ignore2)
1791 int ignore, ignore2;
1793 bash_complete_filename_internal ('?');
1797 bash_complete_filename_internal (what_to_do)
1800 Function *orig_func, *orig_dir_func;
1801 CPPFunction *orig_attempt_func;
1802 char *orig_rl_completer_word_break_characters;
1804 orig_func = rl_completion_entry_function;
1805 orig_attempt_func = rl_attempted_completion_function;
1806 orig_dir_func = rl_directory_completion_hook;
1807 orig_rl_completer_word_break_characters = rl_completer_word_break_characters;
1808 rl_completion_entry_function = (Function *)filename_completion_function;
1809 rl_attempted_completion_function = (CPPFunction *)NULL;
1810 rl_directory_completion_hook = (Function *)NULL;
1811 rl_completer_word_break_characters = " \t\n\"\'";
1813 rl_complete_internal (what_to_do);
1815 rl_completion_entry_function = orig_func;
1816 rl_attempted_completion_function = orig_attempt_func;
1817 rl_directory_completion_hook = orig_dir_func;
1818 rl_completer_word_break_characters = orig_rl_completer_word_break_characters;
1822 bash_complete_hostname (ignore, ignore2)
1823 int ignore, ignore2;
1825 bash_complete_hostname_internal (TAB);
1829 bash_possible_hostname_completions (ignore, ignore2)
1830 int ignore, ignore2;
1832 bash_complete_hostname_internal ('?');
1836 bash_complete_variable (ignore, ignore2)
1837 int ignore, ignore2;
1839 bash_complete_variable_internal (TAB);
1843 bash_possible_variable_completions (ignore, ignore2)
1844 int ignore, ignore2;
1846 bash_complete_variable_internal ('?');
1850 bash_complete_command (ignore, ignore2)
1851 int ignore, ignore2;
1853 bash_complete_command_internal (TAB);
1857 bash_possible_command_completions (ignore, ignore2)
1858 int ignore, ignore2;
1860 bash_complete_command_internal ('?');
1864 bash_complete_hostname_internal (what_to_do)
1867 bash_specific_completion
1868 (what_to_do, (Function *)hostname_completion_function);
1872 bash_complete_variable_internal (what_to_do)
1875 bash_specific_completion
1876 (what_to_do, (Function *)variable_completion_function);
1880 bash_complete_command_internal (what_to_do)
1883 bash_specific_completion
1884 (what_to_do, (Function *)command_word_completion_function);
1888 glob_complete_word (text, state)
1892 static char **matches = (char **)NULL;
1898 rl_filename_completion_desired = 1;
1901 matches = shell_glob_filename (text);
1902 if (GLOB_FAILED (matches))
1903 matches = (char **)NULL;
1907 ret = matches ? matches[ind] : (char *)NULL;
1913 bash_glob_completion_internal (what_to_do)
1916 bash_specific_completion (what_to_do, (Function *)glob_complete_word);
1920 bash_glob_expand_word (count, key)
1923 bash_glob_completion_internal ('*');
1927 bash_glob_list_expansions (count, key)
1930 bash_glob_completion_internal ('?');
1934 bash_specific_completion (what_to_do, generator)
1936 Function *generator;
1938 Function *orig_func;
1939 CPPFunction *orig_attempt_func;
1941 orig_func = rl_completion_entry_function;
1942 orig_attempt_func = rl_attempted_completion_function;
1943 rl_completion_entry_function = generator;
1944 rl_attempted_completion_function = (CPPFunction *)NULL;
1946 rl_complete_internal (what_to_do);
1948 rl_completion_entry_function = orig_func;
1949 rl_attempted_completion_function = orig_attempt_func;
1952 #endif /* SPECIFIC_COMPLETION_FUNCTIONS */
1954 /* Filename quoting for completion. */
1955 /* A function to strip quotes that are not protected by backquotes. It
1956 allows single quotes to appear within double quotes, and vice versa.
1957 It should be smarter. */
1959 bash_dequote_filename (text, quote_char)
1966 ret = xmalloc (l + 1);
1967 for (quoted = quote_char, p = text, r = ret; p && *p; p++)
1969 /* Allow backslash-quoted characters to pass through unscathed. */
1978 if (quoted && *p == quoted)
1984 if (quoted == 0 && (*p == '\'' || *p == '"'))
1995 /* Quote characters that the readline completion code would treat as
1996 word break characters with backslashes. Pass backslash-quoted
1997 characters through without examination. */
1999 quote_word_break_chars (text)
2006 ret = xmalloc ((2 * l) + 1);
2007 for (s = text, r = ret; *s; s++)
2009 /* Pass backslash-quoted characters through, including the backslash. */
2018 /* OK, we have an unquoted character. Check its presence in
2019 rl_completer_word_break_characters. */
2020 if (strchr (rl_completer_word_break_characters, *s))
2028 /* Quote a filename using double quotes, single quotes, or backslashes
2029 depending on the value of completion_quoting_style. If we're
2030 completing using backslashes, we need to quote some additional
2031 characters (those that readline treats as word breaks), so we call
2032 quote_word_break_chars on the result. */
2034 bash_quote_filename (s, rtype, qcp)
2039 char *rtext, *mtext, *ret;
2042 rtext = (char *)NULL;
2044 /* If RTYPE == MULT_MATCH, it means that there is
2045 more than one match. In this case, we do not add
2046 the closing quote or attempt to perform tilde
2047 expansion. If RTYPE == SINGLE_MATCH, we try
2048 to perform tilde expansion, because single and double
2049 quotes inhibit tilde expansion by the shell. */
2052 if (mtext[0] == '~' && rtype == SINGLE_MATCH)
2053 mtext = bash_tilde_expand (s);
2055 cs = completion_quoting_style;
2056 /* Might need to modify the default completion style based on *qcp,
2057 since it's set to any user-provided opening quote. */
2059 cs = COMPLETE_DQUOTE;
2060 else if (*qcp == '\'')
2061 cs = COMPLETE_SQUOTE;
2062 #if defined (BANG_HISTORY)
2063 else if (*qcp == '\0' && history_expansion && cs == COMPLETE_DQUOTE &&
2064 history_expansion_inhibited == 0 && strchr (mtext, '!'))
2065 cs = COMPLETE_BSQUOTE;
2067 if (*qcp == '"' && history_expansion && cs == COMPLETE_DQUOTE &&
2068 history_expansion_inhibited == 0 && strchr (mtext, '!'))
2070 cs = COMPLETE_BSQUOTE;
2077 case COMPLETE_DQUOTE:
2078 rtext = double_quote (mtext);
2080 case COMPLETE_SQUOTE:
2081 rtext = single_quote (mtext);
2083 case COMPLETE_BSQUOTE:
2084 rtext = backslash_quote (mtext);
2091 /* We may need to quote additional characters: those that readline treats
2092 as word breaks that are not quoted by backslash_quote. */
2093 if (rtext && cs == COMPLETE_BSQUOTE)
2095 mtext = quote_word_break_chars (rtext);
2100 /* Leave the opening quote intact. The readline completion code takes
2101 care of avoiding doubled opening quotes. */
2102 rlen = strlen (rtext);
2103 ret = xmalloc (rlen + 1);
2104 strcpy (ret, rtext);
2106 /* If there are multiple matches, cut off the closing quote. */
2107 if (rtype == MULT_MATCH && cs != COMPLETE_BSQUOTE)
2108 ret[rlen - 1] = '\0';
2113 #endif /* READLINE */