1 /* bashline.c -- Bash's interface to the readline library. */
3 /* Copyright (C) 1987-2004 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 2, 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, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */
23 #if defined (READLINE)
25 #include "bashtypes.h"
26 #include "posixstat.h"
28 #if defined (HAVE_UNISTD_H)
32 #if defined (HAVE_GRP_H)
36 #if defined (HAVE_NETDB_H)
41 #include "chartypes.h"
50 #include "execute_cmd.h"
53 #include "builtins/common.h"
54 #include <readline/rlconf.h>
55 #include <readline/readline.h>
56 #include <readline/history.h>
58 #include <glob/glob.h>
64 #if defined (PROGRAMMABLE_COMPLETION)
65 # include "pcomplete.h"
68 /* These should agree with the defines for emacs_mode and vi_mode in
69 rldefs.h, even though that's not a public readline header file. */
70 #ifndef EMACS_EDITING_MODE
71 # define NO_EDITING_MODE -1
72 # define EMACS_EDITING_MODE 1
73 # define VI_EDITING_MODE 0
76 #if defined (BRACE_COMPLETION)
77 extern int bash_brace_completion __P((int, int));
78 #endif /* BRACE_COMPLETION */
80 /* Forward declarations */
82 /* Functions bound to keys in Readline for Bash users. */
83 static int shell_expand_line __P((int, int));
84 static int display_shell_version __P((int, int));
85 static int operate_and_get_next __P((int, int));
87 static int bash_ignore_filenames __P((char **));
88 static int bash_ignore_everything __P((char **));
90 #if defined (BANG_HISTORY)
91 static char *history_expand_line_internal __P((char *));
92 static int history_expand_line __P((int, int));
93 static int tcsh_magic_space __P((int, int));
94 #endif /* BANG_HISTORY */
96 static int alias_expand_line __P((int, int));
98 #if defined (BANG_HISTORY) && defined (ALIAS)
99 static int history_and_alias_expand_line __P((int, int));
102 /* Helper functions for Readline. */
103 static int bash_directory_completion_hook __P((char **));
104 static int filename_completion_ignore __P((char **));
105 static int bash_push_line __P((void));
107 static void cleanup_expansion_error __P((void));
108 static void maybe_make_readline_line __P((char *));
109 static void set_up_new_line __P((char *));
111 static int check_redir __P((int));
112 static char **attempt_shell_completion __P((const char *, int, int));
113 static char *variable_completion_function __P((const char *, int));
114 static char *hostname_completion_function __P((const char *, int));
115 static char *command_subst_completion_function __P((const char *, int));
117 static void build_history_completion_array __P((void));
118 static char *history_completion_generator __P((const char *, int));
119 static int dynamic_complete_history __P((int, int));
121 static void initialize_hostname_list __P((void));
122 static void add_host_name __P((char *));
123 static void snarf_hosts_from_file __P((char *));
124 static char **hostnames_matching __P((char *));
126 static void _ignore_completion_names __P((char **, sh_ignore_func_t *));
127 static int name_is_acceptable __P((const char *));
128 static int test_for_directory __P((const char *));
129 static int return_zero __P((const char *));
131 static char *bash_dequote_filename __P((char *, int));
132 static char *quote_word_break_chars __P((char *));
133 static char *bash_quote_filename __P((char *, int, char *));
135 static int bash_execute_unix_command __P((int, int));
136 static void init_unix_command_map __P((void));
137 static int isolate_sequence __P((char *, int, int, int *));
139 static int set_saved_history __P((void));
142 static int posix_edit_macros __P((int, int));
145 #if defined (PROGRAMMABLE_COMPLETION)
146 static int find_cmd_start __P((int));
147 static int find_cmd_end __P((int));
148 static char *find_cmd_name __P((int));
149 static char *prog_complete_return __P((const char *, int));
151 static char **prog_complete_matches;
154 /* Variables used here but defined in other files. */
155 #if defined (BANG_HISTORY)
156 extern int hist_verify;
159 extern int current_command_line_count, last_command_exit_value;
160 extern int posixly_correct, no_symbolic_links;
161 extern char *current_prompt_string, *ps1_prompt;
162 extern STRING_INT_ALIST word_token_alist[];
163 extern sh_builtin_func_t *last_shell_builtin, *this_shell_builtin;
165 /* SPECIFIC_COMPLETION_FUNCTIONS specifies that we have individual
166 completion functions which indicate what type of completion should be
167 done (at or before point) that can be bound to key sequences with
168 the readline library. */
169 #define SPECIFIC_COMPLETION_FUNCTIONS
171 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
172 static int bash_specific_completion __P((int, rl_compentry_func_t *));
174 static int bash_complete_filename_internal __P((int));
175 static int bash_complete_username_internal __P((int));
176 static int bash_complete_hostname_internal __P((int));
177 static int bash_complete_variable_internal __P((int));
178 static int bash_complete_command_internal __P((int));
180 static int bash_complete_filename __P((int, int));
181 static int bash_possible_filename_completions __P((int, int));
182 static int bash_complete_username __P((int, int));
183 static int bash_possible_username_completions __P((int, int));
184 static int bash_complete_hostname __P((int, int));
185 static int bash_possible_hostname_completions __P((int, int));
186 static int bash_complete_variable __P((int, int));
187 static int bash_possible_variable_completions __P((int, int));
188 static int bash_complete_command __P((int, int));
189 static int bash_possible_command_completions __P((int, int));
191 static char *glob_complete_word __P((const char *, int));
192 static int bash_glob_completion_internal __P((int));
193 static int bash_glob_complete_word __P((int, int));
194 static int bash_glob_expand_word __P((int, int));
195 static int bash_glob_list_expansions __P((int, int));
197 #endif /* SPECIFIC_COMPLETION_FUNCTIONS */
199 static int edit_and_execute_command __P((int, int, int, char *));
200 #if defined (VI_MODE)
201 static int vi_edit_and_execute_command __P((int, int));
202 static int bash_vi_complete __P((int, int));
204 static int emacs_edit_and_execute_command __P((int, int));
206 /* Non-zero once initalize_readline () has been called. */
207 int bash_readline_initialized = 0;
209 /* If non-zero, we do hostname completion, breaking words at `@' and
210 trying to complete the stuff after the `@' from our own internal
212 int perform_hostname_completion = 1;
214 /* If non-zero, we don't do command completion on an empty line. */
215 int no_empty_command_completion;
217 /* Set FORCE_FIGNORE if you want to honor FIGNORE even if it ignores the
218 only possible matches. Set to 0 if you want to match filenames if they
219 are the only possible matches, even if FIGNORE says to. */
220 int force_fignore = 1;
222 static char *bash_completer_word_break_characters = " \t\n\"'@><=;|&(:";
223 static char *bash_nohostname_word_break_characters = " \t\n\"'><=;|&(:";
226 static rl_hook_func_t *old_rl_startup_hook = (rl_hook_func_t *)NULL;
228 /* What kind of quoting is performed by bash_quote_filename:
229 COMPLETE_DQUOTE = double-quoting the filename
230 COMPLETE_SQUOTE = single_quoting the filename
231 COMPLETE_BSQUOTE = backslash-quoting special chars in the filename
233 #define COMPLETE_DQUOTE 1
234 #define COMPLETE_SQUOTE 2
235 #define COMPLETE_BSQUOTE 3
236 static int completion_quoting_style = COMPLETE_BSQUOTE;
238 /* Change the readline VI-mode keymaps into or out of Posix.2 compliance.
239 Called when the shell is put into or out of `posix' mode. */
241 posix_readline_initialize (on_or_off)
245 rl_variable_bind ("comment-begin", "#");
246 #if defined (VI_MODE)
247 rl_bind_key_in_map (CTRL ('I'), on_or_off ? rl_insert : rl_complete, vi_insertion_keymap);
251 /* When this function returns, rl_completer_word_break_characters points to
252 dynamically allocated memory. */
254 enable_hostname_completion (on_or_off)
258 char *at, *nv, *nval;
260 old_value = perform_hostname_completion;
264 perform_hostname_completion = 1;
265 rl_special_prefixes = "$@";
269 perform_hostname_completion = 0;
270 rl_special_prefixes = "$";
273 /* Now we need to figure out how to appropriately modify and assign
274 rl_completer_word_break_characters depending on whether we want
275 hostname completion on or off. */
277 /* If this is the first time this has been called
278 (bash_readline_initialized == 0), use the sames values as before, but
279 allocate new memory for rl_completer_word_break_characters. */
281 if (bash_readline_initialized == 0 &&
282 (rl_completer_word_break_characters == 0 ||
283 rl_completer_word_break_characters == rl_basic_word_break_characters))
286 rl_completer_word_break_characters = savestring (bash_completer_word_break_characters);
288 rl_completer_word_break_characters = savestring (bash_nohostname_word_break_characters);
292 /* See if we have anything to do. */
293 at = strchr (rl_completer_word_break_characters, '@');
294 if ((at == 0 && on_or_off == 0) || (at != 0 && on_or_off != 0))
297 /* We have something to do. Do it. */
298 nval = (char *)xmalloc (strlen (rl_completer_word_break_characters) + 1 + on_or_off);
302 /* Turn it off -- just remove `@' from word break chars. We want
303 to remove all occurrences of `@' from the char list, so we loop
304 rather than just copy the rest of the list over AT. */
305 for (nv = nval, at = rl_completer_word_break_characters; *at; )
315 strcpy (nval + 1, rl_completer_word_break_characters);
318 free (rl_completer_word_break_characters);
319 rl_completer_word_break_characters = nval;
325 /* Called once from parse.y if we are going to use readline. */
327 initialize_readline ()
329 rl_command_func_t *func;
332 if (bash_readline_initialized)
335 rl_terminal_name = get_string_value ("TERM");
337 rl_outstream = stderr;
339 /* Allow conditional parsing of the ~/.inputrc file. */
340 rl_readline_name = "Bash";
342 /* Add bindable names before calling rl_initialize so they may be
343 referenced in the various inputrc files. */
344 rl_add_defun ("shell-expand-line", shell_expand_line, -1);
346 rl_add_defun ("history-expand-line", history_expand_line, -1);
347 rl_add_defun ("magic-space", tcsh_magic_space, -1);
351 rl_add_defun ("alias-expand-line", alias_expand_line, -1);
353 rl_add_defun ("history-and-alias-expand-line", history_and_alias_expand_line, -1);
357 /* Backwards compatibility. */
358 rl_add_defun ("insert-last-argument", rl_yank_last_arg, -1);
360 rl_add_defun ("operate-and-get-next", operate_and_get_next, -1);
361 rl_add_defun ("display-shell-version", display_shell_version, -1);
362 rl_add_defun ("edit-and-execute-command", emacs_edit_and_execute_command, -1);
364 #if defined (BRACE_COMPLETION)
365 rl_add_defun ("complete-into-braces", bash_brace_completion, -1);
368 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
369 rl_add_defun ("complete-filename", bash_complete_filename, -1);
370 rl_add_defun ("possible-filename-completions", bash_possible_filename_completions, -1);
371 rl_add_defun ("complete-username", bash_complete_username, -1);
372 rl_add_defun ("possible-username-completions", bash_possible_username_completions, -1);
373 rl_add_defun ("complete-hostname", bash_complete_hostname, -1);
374 rl_add_defun ("possible-hostname-completions", bash_possible_hostname_completions, -1);
375 rl_add_defun ("complete-variable", bash_complete_variable, -1);
376 rl_add_defun ("possible-variable-completions", bash_possible_variable_completions, -1);
377 rl_add_defun ("complete-command", bash_complete_command, -1);
378 rl_add_defun ("possible-command-completions", bash_possible_command_completions, -1);
379 rl_add_defun ("glob-complete-word", bash_glob_complete_word, -1);
380 rl_add_defun ("glob-expand-word", bash_glob_expand_word, -1);
381 rl_add_defun ("glob-list-expansions", bash_glob_list_expansions, -1);
384 rl_add_defun ("dynamic-complete-history", dynamic_complete_history, -1);
386 /* Bind defaults before binding our custom shell keybindings. */
387 if (RL_ISSTATE(RL_STATE_INITIALIZED) == 0)
390 /* Bind up our special shell functions. */
391 rl_bind_key_if_unbound_in_map (CTRL('E'), shell_expand_line, emacs_meta_keymap);
394 rl_bind_key_if_unbound_in_map ('^', history_expand_line, emacs_meta_keymap);
397 rl_bind_key_if_unbound_in_map (CTRL ('O'), operate_and_get_next, emacs_standard_keymap);
398 rl_bind_key_if_unbound_in_map (CTRL ('V'), display_shell_version, emacs_ctlx_keymap);
400 /* In Bash, the user can switch editing modes with "set -o [vi emacs]",
401 so it is not necessary to allow C-M-j for context switching. Turn
402 off this occasionally confusing behaviour. */
405 func = rl_function_of_keyseq (kseq, emacs_meta_keymap, (int *)NULL);
406 if (func == rl_vi_editing_mode)
407 rl_unbind_key_in_map (CTRL('J'), emacs_meta_keymap);
409 func = rl_function_of_keyseq (kseq, emacs_meta_keymap, (int *)NULL);
410 if (func == rl_vi_editing_mode)
411 rl_unbind_key_in_map (CTRL('M'), emacs_meta_keymap);
412 #if defined (VI_MODE)
413 rl_unbind_key_in_map (CTRL('E'), vi_movement_keymap);
416 #if defined (BRACE_COMPLETION)
417 rl_bind_key_if_unbound_in_map ('{', bash_brace_completion, emacs_meta_keymap); /*}*/
418 #endif /* BRACE_COMPLETION */
420 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
421 rl_bind_key_if_unbound_in_map ('/', bash_complete_filename, emacs_meta_keymap);
422 rl_bind_key_if_unbound_in_map ('/', bash_possible_filename_completions, emacs_ctlx_keymap);
424 /* Have to jump through hoops here because there is a default binding for
425 M-~ (rl_tilde_expand) */
428 func = rl_function_of_keyseq (kseq, emacs_meta_keymap, (int *)NULL);
429 if (func == 0 || func == rl_tilde_expand)
430 rl_bind_keyseq_in_map (kseq, bash_complete_username, emacs_meta_keymap);
432 rl_bind_key_if_unbound_in_map ('~', bash_possible_username_completions, emacs_ctlx_keymap);
434 rl_bind_key_if_unbound_in_map ('@', bash_complete_hostname, emacs_meta_keymap);
435 rl_bind_key_if_unbound_in_map ('@', bash_possible_hostname_completions, emacs_ctlx_keymap);
437 rl_bind_key_if_unbound_in_map ('$', bash_complete_variable, emacs_meta_keymap);
438 rl_bind_key_if_unbound_in_map ('$', bash_possible_variable_completions, emacs_ctlx_keymap);
440 rl_bind_key_if_unbound_in_map ('!', bash_complete_command, emacs_meta_keymap);
441 rl_bind_key_if_unbound_in_map ('!', bash_possible_command_completions, emacs_ctlx_keymap);
443 rl_bind_key_if_unbound_in_map ('g', bash_glob_complete_word, emacs_meta_keymap);
444 rl_bind_key_if_unbound_in_map ('*', bash_glob_expand_word, emacs_ctlx_keymap);
445 rl_bind_key_if_unbound_in_map ('g', bash_glob_list_expansions, emacs_ctlx_keymap);
447 #endif /* SPECIFIC_COMPLETION_FUNCTIONS */
449 rl_bind_key_if_unbound_in_map (TAB, dynamic_complete_history, emacs_meta_keymap);
451 /* Tell the completer that we want a crack first. */
452 rl_attempted_completion_function = attempt_shell_completion;
454 /* Tell the completer that we might want to follow symbolic links or
455 do other expansion on directory names. */
456 rl_directory_completion_hook = bash_directory_completion_hook;
458 /* Tell the filename completer we want a chance to ignore some names. */
459 rl_ignore_some_completions_function = filename_completion_ignore;
461 /* Bind C-xC-e to invoke emacs and run result as commands. */
462 rl_bind_key_if_unbound_in_map (CTRL ('E'), emacs_edit_and_execute_command, emacs_ctlx_keymap);
463 #if defined (VI_MODE)
464 rl_bind_key_if_unbound_in_map ('v', vi_edit_and_execute_command, vi_movement_keymap);
466 rl_bind_key_if_unbound_in_map ('@', posix_edit_macros, vi_movement_keymap);
469 rl_bind_key_in_map ('\\', bash_vi_complete, vi_movement_keymap);
470 rl_bind_key_in_map ('*', bash_vi_complete, vi_movement_keymap);
471 rl_bind_key_in_map ('=', bash_vi_complete, vi_movement_keymap);
474 rl_completer_quote_characters = "'\"";
476 /* This sets rl_completer_word_break_characters and rl_special_prefixes
477 to the appropriate values, depending on whether or not hostname
478 completion is enabled. */
479 enable_hostname_completion (perform_hostname_completion);
481 /* characters that need to be quoted when appearing in filenames. */
482 rl_filename_quote_characters = " \t\n\\\"'@<>=;|&()#$`?*[!:{"; /*}*/
483 rl_filename_quoting_function = bash_quote_filename;
484 rl_filename_dequoting_function = bash_dequote_filename;
485 rl_char_is_quoted_p = char_is_quoted;
488 /* This is superfluous and makes it impossible to use tab completion in
489 vi mode even when explicitly binding it in ~/.inputrc. sv_strict_posix()
490 should already have called posix_readline_initialize() when
491 posixly_correct was set. */
493 posix_readline_initialize (1);
496 bash_readline_initialized = 1;
499 /* On Sun systems at least, rl_attempted_completion_function can end up
500 getting set to NULL, and rl_completion_entry_function set to do command
501 word completion if Bash is interrupted while trying to complete a command
502 word. This just resets all the completion functions to the right thing.
503 It's called from throw_to_top_level(). */
505 bashline_reinitialize ()
508 rl_attempted_completion_function = attempt_shell_completion;
509 rl_completion_entry_function = NULL;
510 rl_directory_completion_hook = bash_directory_completion_hook;
511 rl_ignore_some_completions_function = filename_completion_ignore;
514 /* Contains the line to push into readline. */
515 static char *push_to_readline = (char *)NULL;
517 /* Push the contents of push_to_readline into the
522 if (push_to_readline)
524 rl_insert_text (push_to_readline);
525 free (push_to_readline);
526 push_to_readline = (char *)NULL;
527 rl_startup_hook = old_rl_startup_hook;
532 /* Call this to set the initial text for the next line to read
538 FREE (push_to_readline);
540 push_to_readline = savestring (line);
541 old_rl_startup_hook = rl_startup_hook;
542 rl_startup_hook = bash_push_line;
548 display_shell_version (count, c)
552 show_shell_version (0);
553 putc ('\r', rl_outstream);
554 fflush (rl_outstream);
560 /* **************************************************************** */
564 /* **************************************************************** */
566 /* If the user requests hostname completion, then simply build a list
567 of hosts, and complete from that forever more, or at least until
568 HOSTFILE is unset. */
570 /* THIS SHOULD BE A STRINGLIST. */
571 /* The kept list of hostnames. */
572 static char **hostname_list = (char **)NULL;
574 /* The physical size of the above list. */
575 static int hostname_list_size;
577 /* The number of hostnames in the above list. */
578 static int hostname_list_length;
580 /* Whether or not HOSTNAME_LIST has been initialized. */
581 int hostname_list_initialized = 0;
583 /* Initialize the hostname completion table. */
585 initialize_hostname_list ()
589 temp = get_string_value ("HOSTFILE");
591 temp = get_string_value ("hostname_completion_file");
593 temp = DEFAULT_HOSTS_FILE;
595 snarf_hosts_from_file (temp);
598 hostname_list_initialized++;
601 /* Add NAME to the list of hosts. */
606 if (hostname_list_length + 2 > hostname_list_size)
608 hostname_list_size = (hostname_list_size + 32) - (hostname_list_size % 32);
609 hostname_list = strvec_resize (hostname_list, hostname_list_size);
612 hostname_list[hostname_list_length++] = savestring (name);
613 hostname_list[hostname_list_length] = (char *)NULL;
616 #define cr_whitespace(c) ((c) == '\r' || (c) == '\n' || whitespace(c))
619 snarf_hosts_from_file (filename)
623 char *temp, buffer[256], name[256];
624 register int i, start;
626 file = fopen (filename, "r");
630 while (temp = fgets (buffer, 255, file))
632 /* Skip to first character. */
633 for (i = 0; buffer[i] && cr_whitespace (buffer[i]); i++)
636 /* If comment or blank line, ignore. */
637 if (buffer[i] == '\0' || buffer[i] == '#')
640 /* If `preprocessor' directive, do the include. */
641 if (strncmp (buffer + i, "$include ", 9) == 0)
645 /* Find start of filename. */
646 for (incfile = buffer + i + 9; *incfile && whitespace (*incfile); incfile++)
649 /* Find end of filename. */
650 for (t = incfile; *t && cr_whitespace (*t) == 0; t++)
655 snarf_hosts_from_file (incfile);
659 /* Skip internet address if present. */
660 if (DIGIT (buffer[i]))
661 for (; buffer[i] && cr_whitespace (buffer[i]) == 0; i++);
663 /* Gobble up names. Each name is separated with whitespace. */
666 for (; cr_whitespace (buffer[i]); i++)
668 if (buffer[i] == '\0' || buffer[i] == '#')
671 /* Isolate the current word. */
672 for (start = i; buffer[i] && cr_whitespace (buffer[i]) == 0; i++)
676 strncpy (name, buffer + start, i - start);
677 name[i - start] = '\0';
678 add_host_name (name);
684 /* Return the hostname list. */
688 if (hostname_list_initialized == 0)
689 initialize_hostname_list ();
690 return (hostname_list);
694 clear_hostname_list ()
698 if (hostname_list_initialized == 0)
700 for (i = 0; i < hostname_list_length; i++)
701 free (hostname_list[i]);
702 hostname_list_length = 0;
705 /* Return a NULL terminated list of hostnames which begin with TEXT.
706 Initialize the hostname list the first time if neccessary.
707 The array is malloc ()'ed, but not the individual strings. */
709 hostnames_matching (text)
712 register int i, len, nmatch, rsize;
715 if (hostname_list_initialized == 0)
716 initialize_hostname_list ();
718 if (hostname_list_initialized == 0)
719 return ((char **)NULL);
721 /* Special case. If TEXT consists of nothing, then the whole list is
725 result = strvec_create (1 + hostname_list_length);
726 for (i = 0; i < hostname_list_length; i++)
727 result[i] = hostname_list[i];
728 result[i] = (char *)NULL;
732 /* Scan until found, or failure. */
734 result = (char **)NULL;
735 for (i = nmatch = rsize = 0; i < hostname_list_length; i++)
737 if (STREQN (text, hostname_list[i], len) == 0)
740 /* OK, it matches. Add it to the list. */
741 if (nmatch >= (rsize - 1))
743 rsize = (rsize + 16) - (rsize % 16);
744 result = strvec_resize (result, rsize);
747 result[nmatch++] = hostname_list[i];
750 result[nmatch] = (char *)NULL;
754 /* The equivalent of the Korn shell C-o operate-and-get-next-history-line
756 static int saved_history_line_to_use = -1;
761 if (saved_history_line_to_use >= 0)
762 rl_get_previous_history (history_length - saved_history_line_to_use, 0);
763 saved_history_line_to_use = -1;
764 rl_startup_hook = old_rl_startup_hook;
769 operate_and_get_next (count, c)
774 /* Accept the current line. */
777 /* Find the current line, and find the next line to use. */
778 where = where_history ();
780 if ((history_is_stifled () && (history_length >= history_max_entries)) ||
781 (where >= history_length - 1))
782 saved_history_line_to_use = where;
784 saved_history_line_to_use = where + 1;
786 old_rl_startup_hook = rl_startup_hook;
787 rl_startup_hook = set_saved_history;
792 /* This vi mode command causes VI_EDIT_COMMAND to be run on the current
793 command being entered (if no explicit argument is given), otherwise on
794 a command from the history file. */
796 #define VI_EDIT_COMMAND "fc -e \"${VISUAL:-${EDITOR:-vi}}\""
797 #define EMACS_EDIT_COMMAND "fc -e \"${VISUAL:-${EDITOR:-emacs}}\""
800 edit_and_execute_command (count, c, editing_mode, edit_command)
801 int count, c, editing_mode;
807 rrs = rl_readline_state;
808 cclc = current_command_line_count;
810 /* Accept the current line. */
815 command = (char *)xmalloc (strlen (edit_command) + 8);
816 sprintf (command, "%s %d", edit_command, count);
820 /* Take the command we were just editing, add it to the history file,
821 then call fc to operate on it. We have to add a dummy command to
822 the end of the history because fc ignores the last command (assumes
823 it's supposed to deal with the command before the `fc'). */
825 bash_add_history (rl_line_buffer);
826 bash_add_history ("");
827 history_lines_this_session++;
829 command = savestring (edit_command);
832 /* Now, POSIX.1-2001 and SUSv3 say that the commands executed from the
833 temporary file should be placed into the history. We don't do that
835 r = parse_and_execute (command, (editing_mode == VI_EDITING_MODE) ? "v" : "C-xC-e", SEVAL_NOHIST);
837 current_command_line_count = cclc;
839 /* Now erase the contents of the current line and undo the effects of the
840 rl_accept_line() above. We don't even want to make the text we just
841 executed available for undoing. */
842 rl_line_buffer[0] = '\0'; /* XXX */
843 rl_point = rl_end = 0;
845 rl_readline_state = rrs;
847 rl_forced_update_display ();
852 #if defined (VI_MODE)
854 vi_edit_and_execute_command (count, c)
857 return (edit_and_execute_command (count, c, VI_EDITING_MODE, VI_EDIT_COMMAND));
862 emacs_edit_and_execute_command (count, c)
865 return (edit_and_execute_command (count, c, EMACS_EDITING_MODE, EMACS_EDIT_COMMAND));
870 posix_edit_macros (count, key)
874 char alias_name[3], *alias_value, *macro;
879 alias_name[2] = '\0';
881 alias_value = get_alias_value (alias_name);
882 if (alias_value && *alias_value)
884 macro = savestring (alias_value);
885 rl_push_macro_input (macro);
891 /* **************************************************************** */
893 /* How To Do Shell Completion */
895 /* **************************************************************** */
897 #define COMMAND_SEPARATORS ";|&{(`"
904 register int this_char, prev_char;
906 /* Handle the two character tokens `>&', `<&', and `>|'.
907 We are not in a command position after one of these. */
908 this_char = rl_line_buffer[ti];
909 prev_char = rl_line_buffer[ti - 1];
911 if ((this_char == '&' && (prev_char == '<' || prev_char == '>')) ||
912 (this_char == '|' && prev_char == '>'))
914 else if ((this_char == '{' && prev_char == '$') || /* } */
915 (char_is_quoted (rl_line_buffer, ti)))
920 #if defined (PROGRAMMABLE_COMPLETION)
922 * XXX - because of the <= start test, and setting os = s+1, this can
923 * potentially return os > start. This is probably not what we want to
924 * happen, but fix later after 2.05a-release.
927 find_cmd_start (start)
933 while (((s = skip_to_delim (rl_line_buffer, os, COMMAND_SEPARATORS)) <= start) &&
945 e = skip_to_delim (rl_line_buffer, end, COMMAND_SEPARATORS);
950 find_cmd_name (start)
956 for (s = start; whitespace (rl_line_buffer[s]); s++)
959 /* skip until a shell break character */
960 e = skip_to_delim (rl_line_buffer, s, "()<>;&| \t\n");
962 name = substring (rl_line_buffer, s, e);
968 prog_complete_return (text, matchnum)
977 if (prog_complete_matches == 0 || prog_complete_matches[ind] == 0)
979 return (prog_complete_matches[ind++]);
982 #endif /* PROGRAMMABLE_COMPLETION */
984 /* Do some completion on TEXT. The indices of TEXT in RL_LINE_BUFFER are
985 at START and END. Return an array of matches, or NULL if none. */
987 attempt_shell_completion (text, start, end)
991 int in_command_position, ti, saveti, qc;
992 char **matches, *command_separator_chars;
994 command_separator_chars = COMMAND_SEPARATORS;
995 matches = (char **)NULL;
996 rl_ignore_some_completions_function = filename_completion_ignore;
998 /* Determine if this could be a command word. It is if it appears at
999 the start of the line (ignoring preceding whitespace), or if it
1000 appears after a character that separates commands. It cannot be a
1001 command word if we aren't at the top-level prompt. */
1005 while ((ti > -1) && (whitespace (rl_line_buffer[ti])))
1009 /* If this is an open quote, maybe we're trying to complete a quoted
1011 if (ti >= 0 && (rl_line_buffer[ti] == '"' || rl_line_buffer[ti] == '\''))
1013 qc = rl_line_buffer[ti];
1015 while (ti > -1 && (whitespace (rl_line_buffer[ti])))
1020 in_command_position = 0;
1023 /* Only do command completion at the start of a line when we
1024 are prompting at the top level. */
1025 if (current_prompt_string == ps1_prompt)
1026 in_command_position++;
1028 else if (member (rl_line_buffer[ti], command_separator_chars))
1030 in_command_position++;
1032 if (check_redir (ti) == 1)
1033 in_command_position = 0;
1037 /* This still could be in command position. It is possible
1038 that all of the previous words on the line are variable
1042 /* Check that we haven't incorrectly flagged a closed command substitution
1043 as indicating we're in a command position. */
1044 if (in_command_position && ti >= 0 && rl_line_buffer[ti] == '`' &&
1045 *text != '`' && unclosed_pair (rl_line_buffer, end, "`") == 0)
1046 in_command_position = 0;
1048 /* Special handling for command substitution. If *TEXT is a backquote,
1049 it can be the start or end of an old-style command substitution, or
1050 unmatched. If it's unmatched, both calls to unclosed_pair will
1053 (in_command_position || (unclosed_pair (rl_line_buffer, start, "`") &&
1054 unclosed_pair (rl_line_buffer, end, "`"))))
1055 matches = rl_completion_matches (text, command_subst_completion_function);
1057 #if defined (PROGRAMMABLE_COMPLETION)
1058 /* Attempt programmable completion. */
1059 if (!matches && in_command_position == 0 && prog_completion_enabled &&
1060 (progcomp_size () > 0) && current_prompt_string == ps1_prompt)
1065 /* XXX - don't free the members */
1066 if (prog_complete_matches)
1067 free (prog_complete_matches);
1068 prog_complete_matches = (char **)NULL;
1070 s = find_cmd_start (start);
1071 e = find_cmd_end (end);
1072 n = find_cmd_name (s);
1074 prog_complete_matches = programmable_completions (n, text, s, e, &foundcs);
1078 /* XXX - if we found a COMPSPEC for the command, just return whatever
1079 the programmable completion code returns, and disable the default
1080 filename completion that readline will do unless the COPT_DEFAULT
1081 option has been set with the `-o default' option to complete. */
1084 /* If the user specified that the compspec returns filenames, make
1085 sure that readline knows it. */
1086 if (foundcs & COPT_FILENAMES)
1087 rl_filename_completion_desired = 1;
1088 /* If the user doesn't want a space appended, tell readline. */
1089 if (foundcs & COPT_NOSPACE)
1090 rl_completion_suppress_append = 1;
1091 /* Turn what the programmable completion code returns into what
1092 readline wants. I should have made compute_lcd_of_matches
1094 matches = rl_completion_matches (text, prog_complete_return);
1095 if ((foundcs & COPT_DEFAULT) == 0)
1096 rl_attempted_completion_over = 1; /* no default */
1097 if (matches || ((foundcs & COPT_BASHDEFAULT) == 0))
1104 matches = bash_default_completion (text, start, end, qc, in_command_position);
1110 bash_default_completion (text, start, end, qc, in_command_position)
1112 int start, end, qc, in_command_position;
1116 matches = (char **)NULL;
1118 /* New posix-style command substitution or variable name? */
1119 if (!matches && *text == '$')
1121 if (qc != '\'' && text[1] == '(') /* ) */
1122 matches = rl_completion_matches (text, command_subst_completion_function);
1124 matches = rl_completion_matches (text, variable_completion_function);
1127 /* If the word starts in `~', and there is no slash in the word, then
1128 try completing this word as a username. */
1129 if (!matches && *text == '~' && !xstrchr (text, '/'))
1130 matches = rl_completion_matches (text, rl_username_completion_function);
1132 /* Another one. Why not? If the word starts in '@', then look through
1133 the world of known hostnames for completion first. */
1134 if (!matches && perform_hostname_completion && *text == '@')
1135 matches = rl_completion_matches (text, hostname_completion_function);
1137 /* And last, (but not least) if this word is in a command position, then
1138 complete over possible command names, including aliases, functions,
1139 and command names. */
1140 if (!matches && in_command_position)
1142 if (start == 0 && end == 0 && text[0] == '\0' && no_empty_command_completion)
1144 matches = (char **)NULL;
1145 rl_ignore_some_completions_function = bash_ignore_everything;
1149 #define CMD_IS_DIR(x) (absolute_pathname(x) == 0 && absolute_program(x) == 0 && *(x) != '~' && test_for_directory (x))
1151 matches = rl_completion_matches (text, command_word_completion_function);
1153 /* If we are attempting command completion and nothing matches, we
1154 do not want readline to perform filename completion for us. We
1155 still want to be able to complete partial pathnames, so set the
1156 completion ignore function to something which will remove
1157 filenames and leave directories in the match list. */
1158 if (matches == (char **)NULL)
1159 rl_ignore_some_completions_function = bash_ignore_filenames;
1161 else if (matches[1] == 0 && CMD_IS_DIR(matches[0]))
1162 /* Turn off rl_filename_completion_desired so readline doesn't
1163 append a slash if there is a directory with the same name
1164 in the current directory, or other filename-specific things.
1165 If the name begins with a slash, we're either completing a
1166 full pathname or a directory pathname, and readline won't be
1167 looking in the current directory anyway, so there's no
1169 rl_filename_completion_desired = 0;
1170 else if (matches[0] && matches[1] && STREQ (matches[0], matches[1]) && CMD_IS_DIR (matches[0]))
1171 /* There are multiple instances of the same match (duplicate
1172 completions haven't yet been removed). In this case, all of
1173 the matches will be the same, and the duplicate removal code
1174 will distill them all down to one. We turn off
1175 rl_filename_completion_desired for the same reason as above.
1176 Remember: we only care if there's eventually a single unique
1177 completion. If there are multiple completions this won't
1178 make a difference and the problem won't occur. */
1179 rl_filename_completion_desired = 0;
1184 /* This could be a globbing pattern, so try to expand it using pathname
1186 if (!matches && glob_pattern_p (text))
1188 matches = rl_completion_matches (text, glob_complete_word);
1189 /* A glob expression that matches more than one filename is problematic.
1190 If we match more than one filename, punt. */
1191 if (matches && matches[1] && rl_completion_type == TAB)
1193 strvec_dispose (matches);
1194 matches = (char **)0;
1201 /* This is the function to call when the word to complete is in a position
1202 where a command word can be found. It grovels $PATH, looking for commands
1203 that match. It also scans aliases, function names, and the shell_builtin
1206 command_word_completion_function (hint_text, state)
1207 const char *hint_text;
1210 static char *hint = (char *)NULL;
1211 static char *path = (char *)NULL;
1212 static char *val = (char *)NULL;
1213 static char *filename_hint = (char *)NULL;
1214 static int path_index, hint_len, istate;
1215 static int mapping_over, local_index;
1216 static SHELL_VAR **varlist = (SHELL_VAR **)NULL;
1218 static alias_t **alias_list = (alias_t **)NULL;
1221 /* We have to map over the possibilities for command words. If we have
1222 no state, then make one just for that purpose. */
1231 /* If this is an absolute program name, do not check it against
1232 aliases, reserved words, functions or builtins. We must check
1233 whether or not it is unique, and, if so, whether that filename
1235 if (absolute_program (hint_text))
1237 /* Perform tilde expansion on what's passed, so we don't end up
1238 passing filenames with tildes directly to stat(). */
1239 if (*hint_text == '~')
1240 hint = bash_tilde_expand (hint_text, 0);
1242 hint = savestring (hint_text);
1243 hint_len = strlen (hint);
1246 free (filename_hint);
1247 filename_hint = savestring (hint);
1254 hint = savestring (hint_text);
1255 hint_len = strlen (hint);
1257 path = get_string_value ("PATH");
1260 /* Initialize the variables for each type of command word. */
1266 varlist = all_visible_functions ();
1272 alias_list = all_aliases ();
1276 /* mapping_over says what we are currently hacking. Note that every case
1277 in this list must fall through when there are no more possibilities. */
1279 switch (mapping_over)
1281 case 0: /* Aliases come first. */
1283 while (alias_list && alias_list[local_index])
1285 register char *alias;
1287 alias = alias_list[local_index++]->name;
1289 if (STREQN (alias, hint, hint_len))
1290 return (savestring (alias));
1296 case 1: /* Then shell reserved words. */
1298 while (word_token_alist[local_index].word)
1300 register char *reserved_word;
1302 reserved_word = word_token_alist[local_index++].word;
1304 if (STREQN (reserved_word, hint, hint_len))
1305 return (savestring (reserved_word));
1311 case 2: /* Then function names. */
1312 while (varlist && varlist[local_index])
1314 register char *varname;
1316 varname = varlist[local_index++]->name;
1318 if (STREQN (varname, hint, hint_len))
1319 return (savestring (varname));
1324 case 3: /* Then shell builtins. */
1325 for (; local_index < num_shell_builtins; local_index++)
1327 /* Ignore it if it doesn't have a function pointer or if it
1328 is not currently enabled. */
1329 if (!shell_builtins[local_index].function ||
1330 (shell_builtins[local_index].flags & BUILTIN_ENABLED) == 0)
1333 if (STREQN (shell_builtins[local_index].name, hint, hint_len))
1335 int i = local_index++;
1337 return (savestring (shell_builtins[i].name));
1344 /* Repeatedly call filename_completion_function while we have
1345 members of PATH left. Question: should we stat each file?
1346 Answer: we call executable_file () on each file. */
1349 istate = (val != (char *)NULL);
1355 /* Get the next directory from the path. If there is none, then we
1357 if (!path || !path[path_index] ||
1358 (current_path = extract_colon_unit (path, &path_index)) == 0)
1359 return ((char *)NULL);
1361 if (*current_path == 0)
1363 free (current_path);
1364 current_path = savestring (".");
1367 if (*current_path == '~')
1371 t = bash_tilde_expand (current_path, 0);
1372 free (current_path);
1377 free (filename_hint);
1379 filename_hint = sh_makepath (current_path, hint, 0);
1381 free (current_path);
1385 val = rl_filename_completion_function (filename_hint, istate);
1390 /* If the hint text is an absolute program, then don't bother
1391 searching through PATH. */
1392 if (absolute_program (hint))
1393 return ((char *)NULL);
1399 int match, freetemp;
1402 if (absolute_program (hint))
1404 match = strncmp (val, hint, hint_len) == 0;
1405 /* If we performed tilde expansion, restore the original
1407 if (*hint_text == '~')
1411 tl = strlen (hint_text);
1412 l = vl - hint_len; /* # of chars added */
1413 temp = (char *)xmalloc (l + 2 + tl);
1414 strcpy (temp, hint_text);
1415 strcpy (temp + tl, val + vl - l);
1418 temp = savestring (val);
1423 temp = strrchr (val, '/');
1428 freetemp = match = strncmp (temp, hint, hint_len) == 0;
1430 temp = savestring (temp);
1433 freetemp = match = 0;
1436 /* If we have found a match, and it is an executable file or a
1437 directory name, return it. */
1438 if (match && executable_or_directory (val))
1441 val = ""; /* So it won't be NULL. */
1454 /* Completion inside an unterminated command substitution. */
1456 command_subst_completion_function (text, state)
1460 static char **matches = (char **)NULL;
1461 static const char *orig_start;
1462 static char *filename_text = (char *)NULL;
1463 static int cmd_index, start_len;
1469 free (filename_text);
1473 else if (*text == '$' && text[1] == '(') /* ) */
1475 /* If the text was quoted, suppress any quote character that the
1476 readline completion code would insert. */
1477 rl_completion_suppress_quote = 1;
1478 start_len = text - orig_start;
1479 filename_text = savestring (text);
1484 * At this point we can entertain the idea of re-parsing
1485 * `filename_text' into a (possibly incomplete) command name and
1486 * arguments, and doing completion based on that. This is
1487 * currently very rudimentary, but it is a small improvement.
1489 for (value = filename_text + strlen (filename_text) - 1; value > filename_text; value--)
1490 if (whitespace (*value) || member (*value, COMMAND_SEPARATORS))
1492 if (value <= filename_text)
1493 matches = rl_completion_matches (filename_text, command_word_completion_function);
1497 start_len += value - filename_text;
1498 if (whitespace (value[-1]))
1499 matches = rl_completion_matches (value, rl_filename_completion_function);
1501 matches = rl_completion_matches (value, command_word_completion_function);
1504 /* If there is more than one match, rl_completion_matches has already
1505 put the lcd in matches[0]. Skip over it. */
1506 cmd_index = matches && matches[0] && matches[1];
1509 if (!matches || !matches[cmd_index])
1511 rl_filename_quoting_desired = 0; /* disable quoting */
1512 return ((char *)NULL);
1516 value = (char *)xmalloc (1 + start_len + strlen (matches[cmd_index]));
1519 value[0] = *orig_start;
1521 strncpy (value, orig_start, start_len);
1523 strcpy (value + start_len, matches[cmd_index]);
1530 /* Okay, now we write the entry_function for variable completion. */
1532 variable_completion_function (text, state)
1536 static char **varlist = (char **)NULL;
1537 static int varlist_index;
1538 static char *varname = (char *)NULL;
1540 static int first_char, first_char_loc;
1548 first_char = text[0];
1550 if (first_char == '$')
1553 if (text[first_char_loc] == '{')
1556 varname = savestring (text + first_char_loc);
1558 namelen = strlen (varname);
1560 strvec_dispose (varlist);
1562 varlist = all_variables_matching_prefix (varname);
1566 if (!varlist || !varlist[varlist_index])
1568 return ((char *)NULL);
1574 value = (char *)xmalloc (4 + strlen (varlist[varlist_index]));
1578 value[0] = first_char;
1579 if (first_char_loc == 2)
1583 strcpy (value + first_char_loc, varlist[varlist_index]);
1584 if (first_char_loc == 2)
1585 strcat (value, "}");
1592 /* How about a completion function for hostnames? */
1594 hostname_completion_function (text, state)
1598 static char **list = (char **)NULL;
1599 static int list_index = 0;
1600 static int first_char, first_char_loc;
1602 /* If we don't have any state, make some. */
1607 list = (char **)NULL;
1612 if (first_char == '@')
1615 list = hostnames_matching ((char *)text+first_char_loc);
1619 if (list && list[list_index])
1623 t = (char *)xmalloc (2 + strlen (list[list_index]));
1625 strcpy (t + first_char_loc, list[list_index]);
1630 return ((char *)NULL);
1634 * A completion function for service names from /etc/services (or wherever).
1637 bash_servicename_completion_function (text, state)
1641 #if defined (__WIN32__) || defined (__OPENNT) || !defined (HAVE_GETSERVENT)
1642 return ((char *)NULL);
1644 static char *sname = (char *)NULL;
1645 static struct servent *srvent;
1646 static int snamelen, firstc;
1648 char **alist, *aentry;
1656 sname = savestring (text);
1657 snamelen = strlen (sname);
1661 while (srvent = getservent ())
1664 if (snamelen == 0 || (STREQN (sname, srvent->s_name, snamelen)))
1666 /* Not primary, check aliases */
1667 for (alist = srvent->s_aliases; aentry = *alist; alist++)
1669 if (STREQN (sname, aentry, snamelen))
1683 return ((char *)NULL);
1686 value = afound ? savestring (aentry) : savestring (srvent->s_name);
1692 * A completion function for group names from /etc/group (or wherever).
1695 bash_groupname_completion_function (text, state)
1699 #if defined (__WIN32__) || defined (__OPENNT) || !defined (HAVE_GRP_H)
1700 return ((char *)NULL);
1702 static char *gname = (char *)NULL;
1703 static struct group *grent;
1704 static int gnamelen;
1710 gname = savestring (text);
1711 gnamelen = strlen (gname);
1716 while (grent = getgrent ())
1718 if (gnamelen == 0 || (STREQN (gname, grent->gr_name, gnamelen)))
1725 return ((char *)NULL);
1728 value = savestring (grent->gr_name);
1733 /* Functions to perform history and alias expansions on the current line. */
1735 #if defined (BANG_HISTORY)
1736 /* Perform history expansion on the current line. If no history expansion
1737 is done, pre_process_line() returns what it was passed, so we need to
1738 allocate a new line here. */
1740 history_expand_line_internal (line)
1746 old_verify = hist_verify;
1748 new_line = pre_process_line (line, 0, 0);
1749 hist_verify = old_verify;
1751 return (new_line == line) ? savestring (line) : new_line;
1755 /* There was an error in expansion. Let the preprocessor print
1758 cleanup_expansion_error ()
1761 #if defined (BANG_HISTORY)
1764 old_verify = hist_verify;
1768 fprintf (rl_outstream, "\r\n");
1769 to_free = pre_process_line (rl_line_buffer, 1, 0);
1770 #if defined (BANG_HISTORY)
1771 hist_verify = old_verify;
1773 if (to_free != rl_line_buffer)
1775 putc ('\r', rl_outstream);
1776 rl_forced_update_display ();
1779 /* If NEW_LINE differs from what is in the readline line buffer, add an
1780 undo record to get from the readline line buffer contents to the new
1781 line and make NEW_LINE the current readline line. */
1783 maybe_make_readline_line (new_line)
1786 if (strcmp (new_line, rl_line_buffer) != 0)
1790 rl_add_undo (UNDO_BEGIN, 0, 0, 0);
1791 rl_delete_text (0, rl_point);
1792 rl_point = rl_end = rl_mark = 0;
1793 rl_insert_text (new_line);
1794 rl_add_undo (UNDO_END, 0, 0, 0);
1798 /* Make NEW_LINE be the current readline line. This frees NEW_LINE. */
1800 set_up_new_line (new_line)
1803 int old_point, at_end;
1805 old_point = rl_point;
1806 at_end = rl_point == rl_end;
1808 /* If the line was history and alias expanded, then make that
1809 be one thing to undo. */
1810 maybe_make_readline_line (new_line);
1813 /* Place rl_point where we think it should go. */
1816 else if (old_point < rl_end)
1818 rl_point = old_point;
1819 if (!whitespace (rl_line_buffer[rl_point]))
1820 rl_forward_word (1, 0);
1825 /* Expand aliases in the current readline line. */
1827 alias_expand_line (count, ignore)
1832 new_line = alias_expand (rl_line_buffer);
1836 set_up_new_line (new_line);
1841 cleanup_expansion_error ();
1847 #if defined (BANG_HISTORY)
1848 /* History expand the line. */
1850 history_expand_line (count, ignore)
1855 new_line = history_expand_line_internal (rl_line_buffer);
1859 set_up_new_line (new_line);
1864 cleanup_expansion_error ();
1869 /* Expand history substitutions in the current line and then insert a
1870 space (hopefully close to where we were before). */
1872 tcsh_magic_space (count, ignore)
1875 int dist_from_end, old_point;
1877 old_point = rl_point;
1878 dist_from_end = rl_end - rl_point;
1879 if (history_expand_line (count, ignore) == 0)
1881 /* Try a simple heuristic from Stephen Gildea <gildea@intouchsys.com>.
1882 This works if all expansions were before rl_point or if no expansions
1884 rl_point = (old_point == 0) ? old_point : rl_end - dist_from_end;
1893 /* History and alias expand the line. */
1895 history_and_alias_expand_line (count, ignore)
1900 new_line = history_expand_line_internal (rl_line_buffer);
1907 alias_line = alias_expand (new_line);
1909 new_line = alias_line;
1915 set_up_new_line (new_line);
1920 cleanup_expansion_error ();
1925 /* History and alias expand the line, then perform the shell word
1926 expansions by calling expand_string. This can't use set_up_new_line()
1927 because we want the variable expansions as a separate undo'able
1928 set of operations. */
1930 shell_expand_line (count, ignore)
1934 WORD_LIST *expanded_string;
1936 new_line = history_expand_line_internal (rl_line_buffer);
1943 alias_line = alias_expand (new_line);
1945 new_line = alias_line;
1951 int old_point = rl_point;
1952 int at_end = rl_point == rl_end;
1954 /* If the line was history and alias expanded, then make that
1955 be one thing to undo. */
1956 maybe_make_readline_line (new_line);
1959 /* If there is variable expansion to perform, do that as a separate
1960 operation to be undone. */
1961 new_line = savestring (rl_line_buffer);
1962 expanded_string = expand_string (new_line, 0);
1964 if (expanded_string == 0)
1966 new_line = (char *)xmalloc (1);
1971 new_line = string_list (expanded_string);
1972 dispose_words (expanded_string);
1975 maybe_make_readline_line (new_line);
1978 /* Place rl_point where we think it should go. */
1981 else if (old_point < rl_end)
1983 rl_point = old_point;
1984 if (!whitespace (rl_line_buffer[rl_point]))
1985 rl_forward_word (1, 0);
1991 cleanup_expansion_error ();
1996 /* If FIGNORE is set, then don't match files with the given suffixes when
1997 completing filenames. If only one of the possibilities has an acceptable
1998 suffix, delete the others, else just return and let the completer
1999 signal an error. It is called by the completer when real
2000 completions are done on filenames by the completer's internal
2001 function, not for completion lists (M-?) and not on "other"
2002 completion types, such as hostnames or commands. */
2004 static struct ignorevar fignore =
2010 (sh_iv_item_func_t *) 0,
2014 _ignore_completion_names (names, name_func)
2016 sh_ignore_func_t *name_func;
2023 /* If there is only one completion, see if it is acceptable. If it is
2024 not, free it up. In any case, short-circuit and return. This is a
2025 special case because names[0] is not the prefix of the list of names
2026 if there is only one completion; it is the completion itself. */
2027 if (names[1] == (char *)0)
2030 if ((*name_func) (names[0]) == 0)
2033 names[0] = (char *)NULL;
2039 /* Allocate space for array to hold list of pointers to matching
2040 filenames. The pointers are copied back to NAMES when done. */
2041 for (nidx = 1; names[nidx]; nidx++)
2043 newnames = strvec_create (nidx + 1);
2045 if (force_fignore == 0)
2047 oldnames = strvec_create (nidx - 1);
2051 newnames[0] = names[0];
2052 for (idx = nidx = 1; names[idx]; idx++)
2054 if ((*name_func) (names[idx]))
2055 newnames[nidx++] = names[idx];
2056 else if (force_fignore == 0)
2057 oldnames[oidx++] = names[idx];
2062 newnames[nidx] = (char *)NULL;
2064 /* If none are acceptable then let the completer handle it. */
2070 names[0] = (char *)NULL;
2079 if (force_fignore == 0)
2082 free (oldnames[--oidx]);
2086 /* If only one is acceptable, copy it to names[0] and return. */
2090 names[0] = newnames[1];
2091 names[1] = (char *)NULL;
2096 /* Copy the acceptable names back to NAMES, set the new array end,
2098 for (nidx = 1; newnames[nidx]; nidx++)
2099 names[nidx] = newnames[nidx];
2100 names[nidx] = (char *)NULL;
2105 name_is_acceptable (name)
2111 for (nlen = strlen (name), p = fignore.ignores; p->val; p++)
2113 if (nlen > p->len && p->len > 0 && STREQ (p->val, &name[nlen - p->len]))
2122 ignore_dot_names (name)
2125 return (name[0] != '.');
2130 filename_completion_ignore (names)
2134 if (glob_dot_filenames == 0)
2135 _ignore_completion_names (names, ignore_dot_names);
2138 setup_ignore_patterns (&fignore);
2140 if (fignore.num_ignores == 0)
2143 _ignore_completion_names (names, name_is_acceptable);
2148 /* Return 1 if NAME is a directory. */
2150 test_for_directory (name)
2156 fn = bash_tilde_expand (name, 0);
2157 if (stat (fn, &finfo) != 0)
2163 return (S_ISDIR (finfo.st_mode));
2166 /* Remove files from NAMES, leaving directories. */
2168 bash_ignore_filenames (names)
2171 _ignore_completion_names (names, test_for_directory);
2183 bash_ignore_everything (names)
2186 _ignore_completion_names (names, return_zero);
2190 /* Handle symbolic link references and other directory name
2191 expansions while hacking completion. */
2193 bash_directory_completion_hook (dirname)
2196 char *local_dirname, *new_dirname, *t;
2197 int return_value, should_expand_dirname;
2201 return_value = should_expand_dirname = 0;
2202 local_dirname = *dirname;
2205 should_expand_dirname = xstrchr (local_dirname, '$') || xstrchr (local_dirname, '`');
2207 if (xstrchr (local_dirname, '$'))
2208 should_expand_dirname = 1;
2211 t = xstrchr (local_dirname, '`');
2212 if (t && unclosed_pair (local_dirname, strlen (local_dirname), "`") == 0)
2213 should_expand_dirname = 1;
2217 #if defined (HAVE_LSTAT)
2218 if (should_expand_dirname && lstat (local_dirname, &sb) == 0)
2220 if (should_expand_dirname && stat (local_dirname, &sb) == 0)
2222 should_expand_dirname = 0;
2224 if (should_expand_dirname)
2226 new_dirname = savestring (local_dirname);
2227 wl = expand_prompt_string (new_dirname, 0); /* does the right thing */
2230 *dirname = string_list (wl);
2231 /* Tell the completer to replace the directory name only if we
2232 actually expanded something. */
2233 return_value = STREQ (local_dirname, *dirname) == 0;
2234 free (local_dirname);
2237 local_dirname = *dirname;
2242 free (local_dirname);
2243 *dirname = (char *)xmalloc (1);
2249 if (!no_symbolic_links && (local_dirname[0] != '.' || local_dirname[1]))
2251 char *temp1, *temp2;
2254 t = get_working_directory ("symlink-hook");
2255 temp1 = make_absolute (local_dirname, t);
2257 temp2 = sh_canonpath (temp1, PATH_CHECKDOTDOT|PATH_CHECKEXISTS);
2258 /* If we can't canonicalize, bail. */
2264 len1 = strlen (temp1);
2265 if (temp1[len1 - 1] == '/')
2267 len2 = strlen (temp2);
2268 temp2 = (char *)xrealloc (temp2, len2 + 2);
2270 temp2[len2 + 1] = '\0';
2272 free (local_dirname);
2276 return (return_value);
2279 static char **history_completion_array = (char **)NULL;
2280 static int harry_size;
2281 static int harry_len;
2284 build_history_completion_array ()
2290 /* First, clear out the current dynamic history completion list. */
2293 strvec_dispose (history_completion_array);
2294 history_completion_array = (char **)NULL;
2299 /* Next, grovel each line of history, making each shell-sized token
2300 a separate entry in the history_completion_array. */
2301 hlist = history_list ();
2305 for (i = 0; hlist[i]; i++)
2307 /* Separate each token, and place into an array. */
2308 tokens = history_tokenize (hlist[i]->line);
2310 for (j = 0; tokens && tokens[j]; j++)
2312 if (harry_len + 2 > harry_size)
2313 history_completion_array = strvec_resize (history_completion_array, harry_size += 10);
2315 history_completion_array[harry_len++] = tokens[j];
2316 history_completion_array[harry_len] = (char *)NULL;
2321 /* Sort the complete list of tokens. */
2322 qsort (history_completion_array, harry_len, sizeof (char *), (QSFUNC *)strvec_strcmp);
2327 history_completion_generator (hint_text, state)
2328 const char *hint_text;
2331 static int local_index, len;
2332 static const char *text;
2334 /* If this is the first call to the generator, then initialize the
2335 list of strings to complete over. */
2339 build_history_completion_array ();
2341 len = strlen (text);
2344 while (history_completion_array && history_completion_array[local_index])
2346 if (strncmp (text, history_completion_array[local_index++], len) == 0)
2347 return (savestring (history_completion_array[local_index - 1]));
2349 return ((char *)NULL);
2353 dynamic_complete_history (count, key)
2358 rl_compentry_func_t *orig_func;
2359 rl_completion_func_t *orig_attempt_func;
2361 orig_func = rl_completion_entry_function;
2362 orig_attempt_func = rl_attempted_completion_function;
2363 rl_completion_entry_function = history_completion_generator;
2364 rl_attempted_completion_function = (rl_completion_func_t *)NULL;
2366 /* XXX - use rl_completion_mode here? */
2367 if (rl_last_func == dynamic_complete_history)
2368 r = rl_complete_internal ('?');
2370 r = rl_complete_internal (TAB);
2372 rl_completion_entry_function = orig_func;
2373 rl_attempted_completion_function = orig_attempt_func;
2377 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
2379 bash_complete_username (ignore, ignore2)
2380 int ignore, ignore2;
2382 return bash_complete_username_internal (rl_completion_mode (bash_complete_username));
2386 bash_possible_username_completions (ignore, ignore2)
2387 int ignore, ignore2;
2389 return bash_complete_username_internal ('?');
2393 bash_complete_username_internal (what_to_do)
2396 return bash_specific_completion (what_to_do, rl_username_completion_function);
2400 bash_complete_filename (ignore, ignore2)
2401 int ignore, ignore2;
2403 return bash_complete_filename_internal (rl_completion_mode (bash_complete_filename));
2407 bash_possible_filename_completions (ignore, ignore2)
2408 int ignore, ignore2;
2410 return bash_complete_filename_internal ('?');
2414 bash_complete_filename_internal (what_to_do)
2417 rl_compentry_func_t *orig_func;
2418 rl_completion_func_t *orig_attempt_func;
2419 rl_icppfunc_t *orig_dir_func;
2420 /*const*/ char *orig_rl_completer_word_break_characters;
2423 orig_func = rl_completion_entry_function;
2424 orig_attempt_func = rl_attempted_completion_function;
2425 orig_dir_func = rl_directory_completion_hook;
2426 orig_rl_completer_word_break_characters = rl_completer_word_break_characters;
2427 rl_completion_entry_function = rl_filename_completion_function;
2428 rl_attempted_completion_function = (rl_completion_func_t *)NULL;
2429 rl_directory_completion_hook = (rl_icppfunc_t *)NULL;
2430 rl_completer_word_break_characters = " \t\n\"\'";
2432 r = rl_complete_internal (what_to_do);
2434 rl_completion_entry_function = orig_func;
2435 rl_attempted_completion_function = orig_attempt_func;
2436 rl_directory_completion_hook = orig_dir_func;
2437 rl_completer_word_break_characters = orig_rl_completer_word_break_characters;
2443 bash_complete_hostname (ignore, ignore2)
2444 int ignore, ignore2;
2446 return bash_complete_hostname_internal (rl_completion_mode (bash_complete_hostname));
2450 bash_possible_hostname_completions (ignore, ignore2)
2451 int ignore, ignore2;
2453 return bash_complete_hostname_internal ('?');
2457 bash_complete_variable (ignore, ignore2)
2458 int ignore, ignore2;
2460 return bash_complete_variable_internal (rl_completion_mode (bash_complete_variable));
2464 bash_possible_variable_completions (ignore, ignore2)
2465 int ignore, ignore2;
2467 return bash_complete_variable_internal ('?');
2471 bash_complete_command (ignore, ignore2)
2472 int ignore, ignore2;
2474 return bash_complete_command_internal (rl_completion_mode (bash_complete_command));
2478 bash_possible_command_completions (ignore, ignore2)
2479 int ignore, ignore2;
2481 return bash_complete_command_internal ('?');
2485 bash_complete_hostname_internal (what_to_do)
2488 return bash_specific_completion (what_to_do, hostname_completion_function);
2492 bash_complete_variable_internal (what_to_do)
2495 return bash_specific_completion (what_to_do, variable_completion_function);
2499 bash_complete_command_internal (what_to_do)
2502 return bash_specific_completion (what_to_do, command_word_completion_function);
2505 static char *globtext;
2506 static char *globorig;
2509 glob_complete_word (text, state)
2513 static char **matches = (char **)NULL;
2520 rl_filename_completion_desired = 1;
2522 if (globorig != globtext)
2526 if (rl_explicit_arg)
2528 globorig = savestring (text);
2529 glen = strlen (text);
2530 globtext = (char *)xmalloc (glen + 2);
2531 strcpy (globtext, text);
2532 globtext[glen] = '*';
2533 globtext[glen+1] = '\0';
2536 globtext = globorig = savestring (text);
2538 matches = shell_glob_filename (globtext);
2539 if (GLOB_FAILED (matches))
2540 matches = (char **)NULL;
2544 ret = matches ? matches[ind] : (char *)NULL;
2550 bash_glob_completion_internal (what_to_do)
2553 return bash_specific_completion (what_to_do, glob_complete_word);
2556 /* A special quoting function so we don't end up quoting globbing characters
2557 in the word if there are no matches or multiple matches. */
2559 bash_glob_quote_filename (s, rtype, qcp)
2564 if (globorig && qcp && *qcp == '\0' && STREQ (s, globorig))
2565 return (savestring (s));
2567 return (bash_quote_filename (s, rtype, qcp));
2571 bash_glob_complete_word (count, key)
2575 rl_quote_func_t *orig_quoting_function;
2577 if (rl_editing_mode == EMACS_EDITING_MODE)
2578 rl_explicit_arg = 1; /* force `*' append */
2579 orig_quoting_function = rl_filename_quoting_function;
2580 rl_filename_quoting_function = bash_glob_quote_filename;
2582 r = bash_glob_completion_internal (rl_completion_mode (bash_glob_complete_word));
2584 rl_filename_quoting_function = orig_quoting_function;
2589 bash_glob_expand_word (count, key)
2592 return bash_glob_completion_internal ('*');
2596 bash_glob_list_expansions (count, key)
2599 return bash_glob_completion_internal ('?');
2603 bash_specific_completion (what_to_do, generator)
2605 rl_compentry_func_t *generator;
2607 rl_compentry_func_t *orig_func;
2608 rl_completion_func_t *orig_attempt_func;
2611 orig_func = rl_completion_entry_function;
2612 orig_attempt_func = rl_attempted_completion_function;
2613 rl_completion_entry_function = generator;
2614 rl_attempted_completion_function = NULL;
2616 r = rl_complete_internal (what_to_do);
2618 rl_completion_entry_function = orig_func;
2619 rl_attempted_completion_function = orig_attempt_func;
2624 #endif /* SPECIFIC_COMPLETION_FUNCTIONS */
2626 #if defined (VI_MODE)
2627 /* Completion, from vi mode's point of view. This is a modified version of
2628 rl_vi_complete which uses the bash globbing code to implement what POSIX
2629 specifies, which is to append a `*' and attempt filename generation (which
2630 has the side effect of expanding any globbing characters in the word). */
2632 bash_vi_complete (count, key)
2635 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
2639 if ((rl_point < rl_end) && (!whitespace (rl_line_buffer[rl_point])))
2641 if (!whitespace (rl_line_buffer[rl_point + 1]))
2642 rl_vi_end_word (1, 'E');
2646 /* Find boundaries of current word, according to vi definition of a
2652 rl_vi_bWord (1, 'B');
2657 t = substring (rl_line_buffer, p, rl_point);
2660 if (t && glob_pattern_p (t) == 0)
2661 rl_explicit_arg = 1; /* XXX - force glob_complete_word to append `*' */
2664 if (key == '*') /* Expansion and replacement. */
2665 r = bash_glob_expand_word (count, key);
2666 else if (key == '=') /* List possible completions. */
2667 r = bash_glob_list_expansions (count, key);
2668 else if (key == '\\') /* Standard completion */
2669 r = bash_glob_complete_word (count, key);
2671 r = rl_complete (0, key);
2673 if (key == '*' || key == '\\')
2674 rl_vi_start_inserting (key, 1, 1);
2678 return rl_vi_complete (count, key);
2679 #endif /* !SPECIFIC_COMPLETION_FUNCTIONS */
2681 #endif /* VI_MODE */
2683 /* Filename quoting for completion. */
2684 /* A function to strip unquoted quote characters (single quotes, double
2685 quotes, and backslashes). It allows single quotes to appear
2686 within double quotes, and vice versa. It should be smarter. */
2688 bash_dequote_filename (text, quote_char)
2696 ret = (char *)xmalloc (l + 1);
2697 for (quoted = quote_char, p = text, r = ret; p && *p; p++)
2699 /* Allow backslash-quoted characters to pass through unscathed. */
2708 if (quoted && *p == quoted)
2714 if (quoted == 0 && (*p == '\'' || *p == '"'))
2725 /* Quote characters that the readline completion code would treat as
2726 word break characters with backslashes. Pass backslash-quoted
2727 characters through without examination. */
2729 quote_word_break_chars (text)
2736 ret = (char *)xmalloc ((2 * l) + 1);
2737 for (s = text, r = ret; *s; s++)
2739 /* Pass backslash-quoted characters through, including the backslash. */
2748 /* OK, we have an unquoted character. Check its presence in
2749 rl_completer_word_break_characters. */
2750 if (xstrchr (rl_completer_word_break_characters, *s))
2758 /* Quote a filename using double quotes, single quotes, or backslashes
2759 depending on the value of completion_quoting_style. If we're
2760 completing using backslashes, we need to quote some additional
2761 characters (those that readline treats as word breaks), so we call
2762 quote_word_break_chars on the result. This returns newly-allocated
2765 bash_quote_filename (s, rtype, qcp)
2770 char *rtext, *mtext, *ret;
2773 rtext = (char *)NULL;
2775 /* If RTYPE == MULT_MATCH, it means that there is
2776 more than one match. In this case, we do not add
2777 the closing quote or attempt to perform tilde
2778 expansion. If RTYPE == SINGLE_MATCH, we try
2779 to perform tilde expansion, because single and double
2780 quotes inhibit tilde expansion by the shell. */
2783 if (mtext[0] == '~' && rtype == SINGLE_MATCH)
2784 mtext = bash_tilde_expand (s, 0);
2786 cs = completion_quoting_style;
2787 /* Might need to modify the default completion style based on *qcp,
2788 since it's set to any user-provided opening quote. We also change
2789 to single-quoting if there is no user-provided opening quote and
2790 the word being completed contains newlines, since those are not
2791 quoted correctly using backslashes (a backslash-newline pair is
2792 special to the shell parser). */
2793 if (*qcp == '\0' && cs == COMPLETE_BSQUOTE && xstrchr (mtext, '\n'))
2794 cs = COMPLETE_SQUOTE;
2795 else if (*qcp == '"')
2796 cs = COMPLETE_DQUOTE;
2797 else if (*qcp == '\'')
2798 cs = COMPLETE_SQUOTE;
2799 #if defined (BANG_HISTORY)
2800 else if (*qcp == '\0' && history_expansion && cs == COMPLETE_DQUOTE &&
2801 history_expansion_inhibited == 0 && xstrchr (mtext, '!'))
2802 cs = COMPLETE_BSQUOTE;
2804 if (*qcp == '"' && history_expansion && cs == COMPLETE_DQUOTE &&
2805 history_expansion_inhibited == 0 && xstrchr (mtext, '!'))
2807 cs = COMPLETE_BSQUOTE;
2814 case COMPLETE_DQUOTE:
2815 rtext = sh_double_quote (mtext);
2817 case COMPLETE_SQUOTE:
2818 rtext = sh_single_quote (mtext);
2820 case COMPLETE_BSQUOTE:
2821 rtext = sh_backslash_quote (mtext);
2828 /* We may need to quote additional characters: those that readline treats
2829 as word breaks that are not quoted by backslash_quote. */
2830 if (rtext && cs == COMPLETE_BSQUOTE)
2832 mtext = quote_word_break_chars (rtext);
2837 /* Leave the opening quote intact. The readline completion code takes
2838 care of avoiding doubled opening quotes. */
2839 rlen = strlen (rtext);
2840 ret = (char *)xmalloc (rlen + 1);
2841 strcpy (ret, rtext);
2843 /* If there are multiple matches, cut off the closing quote. */
2844 if (rtype == MULT_MATCH && cs != COMPLETE_BSQUOTE)
2845 ret[rlen - 1] = '\0';
2850 /* Support for binding readline key sequences to Unix commands. */
2851 static Keymap cmd_xmap;
2854 bash_execute_unix_command (count, key)
2855 int count; /* ignored */
2858 Keymap ckmap; /* current keymap */
2859 Keymap xkmap; /* unix command executing keymap */
2862 sh_parser_state_t ps;
2864 /* First, we need to find the right command to execute. This is tricky,
2865 because we might have already indirected into another keymap. */
2866 ckmap = rl_get_keymap ();
2867 if (ckmap != rl_executing_keymap)
2869 /* bogus. we have to search. only handle one level of indirection. */
2870 for (i = 0; i < KEYMAP_SIZE; i++)
2872 if (ckmap[i].type == ISKMAP && (Keymap)ckmap[i].function == rl_executing_keymap)
2875 if (i < KEYMAP_SIZE)
2876 xkmap = (Keymap)cmd_xmap[i].function;
2880 internal_error (_("bash_execute_unix_command: cannot find keymap for command"));
2881 rl_forced_update_display ();
2888 cmd = (char *)xkmap[key].function;
2896 rl_crlf (); /* move to a new line */
2898 save_parser_state (&ps);
2900 cmd = savestring (cmd);
2901 parse_and_execute (cmd, "bash_execute_unix_command", SEVAL_NOHIST);
2903 restore_parser_state (&ps);
2905 /* and restore the readline buffer and display after command execution. */
2906 rl_forced_update_display ();
2911 init_unix_command_map ()
2913 cmd_xmap = rl_make_bare_keymap ();
2917 isolate_sequence (string, ind, need_dquote, startp)
2919 int ind, need_dquote, *startp;
2922 int c, passc, delim;
2924 for (i = ind; string[i] && whitespace (string[i]); i++)
2926 /* NEED_DQUOTE means that the first non-white character *must* be `"'. */
2927 if (need_dquote && string[i] != '"')
2929 builtin_error (_("%s: first non-whitespace character is not `\"'"), string);
2933 /* We can have delimited strings even if NEED_DQUOTE == 0, like the command
2934 string to bind the key sequence to. */
2935 delim = (string[i] == '"' || string[i] == '\'') ? string[i] : 0;
2938 *startp = delim ? ++i : i;
2940 for (passc = 0; c = string[i]; i++)
2956 if (delim && string[i] != delim)
2958 builtin_error (_("no closing `%c' in %s"), delim, string);
2966 bind_keyseq_to_unix_command (line)
2974 init_unix_command_map ();
2976 kmap = rl_get_keymap ();
2978 /* We duplicate some of the work done by rl_parse_and_bind here, but
2979 this code only has to handle `"keyseq": ["]command["]' and can
2980 generate an error for anything else. */
2981 i = isolate_sequence (line, 0, 1, &kstart);
2985 /* Create the key sequence string to pass to rl_generic_bind */
2986 kseq = substring (line, kstart, i);
2988 for ( ; line[i] && line[i] != ':'; i++)
2992 builtin_error (_("%s: missing colon separator"), line);
2996 i = isolate_sequence (line, i + 1, 0, &kstart);
3000 /* Create the value string containing the command to execute. */
3001 value = substring (line, kstart, i);
3003 /* Save the command to execute and the key sequence in the CMD_XMAP */
3004 rl_generic_bind (ISMACR, kseq, value, cmd_xmap);
3006 /* and bind the key sequence in the current keymap to a function that
3007 understands how to execute from CMD_XMAP */
3008 rl_bind_keyseq_in_map (kseq, bash_execute_unix_command, kmap);
3013 /* Used by the programmable completion code. Complete TEXT as a filename,
3014 but return only directories as matches. Dequotes the filename before
3015 attempting to find matches. */
3017 bash_directory_completion_matches (text)
3025 qc = (text[0] == '"' || text[0] == '\'') ? text[0] : 0;
3027 qc = rl_dispatching ? rl_completion_quote_character : 0;
3029 dfn = bash_dequote_filename ((char *)text, qc);
3030 m1 = rl_completion_matches (dfn, rl_filename_completion_function);
3033 if (m1 == 0 || m1[0] == 0)
3035 /* We don't bother recomputing the lcd of the matches, because it will just
3036 get thrown away by the programmable completion code and recomputed
3038 (void)bash_ignore_filenames (m1);
3043 bash_dequote_text (text)
3049 qc = (text[0] == '"' || text[0] == '\'') ? text[0] : 0;
3050 dtxt = bash_dequote_filename ((char *)text, qc);
3053 #endif /* READLINE */