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_expansion __P((char **));
104 static int bash_directory_completion_hook __P((char **));
105 static int filename_completion_ignore __P((char **));
106 static int bash_push_line __P((void));
108 static void cleanup_expansion_error __P((void));
109 static void maybe_make_readline_line __P((char *));
110 static void set_up_new_line __P((char *));
112 static int check_redir __P((int));
113 static char **attempt_shell_completion __P((const char *, int, int));
114 static char *variable_completion_function __P((const char *, int));
115 static char *hostname_completion_function __P((const char *, int));
116 static char *command_subst_completion_function __P((const char *, int));
118 static void build_history_completion_array __P((void));
119 static char *history_completion_generator __P((const char *, int));
120 static int dynamic_complete_history __P((int, int));
122 static void initialize_hostname_list __P((void));
123 static void add_host_name __P((char *));
124 static void snarf_hosts_from_file __P((char *));
125 static char **hostnames_matching __P((char *));
127 static void _ignore_completion_names __P((char **, sh_ignore_func_t *));
128 static int name_is_acceptable __P((const char *));
129 static int test_for_directory __P((const char *));
130 static int return_zero __P((const char *));
132 static char *bash_dequote_filename __P((char *, int));
133 static char *quote_word_break_chars __P((char *));
134 static char *bash_quote_filename __P((char *, int, char *));
136 static int bash_execute_unix_command __P((int, int));
137 static void init_unix_command_map __P((void));
138 static int isolate_sequence __P((char *, int, int, int *));
140 static int set_saved_history __P((void));
143 static int posix_edit_macros __P((int, int));
146 #if defined (PROGRAMMABLE_COMPLETION)
147 static int find_cmd_start __P((int));
148 static int find_cmd_end __P((int));
149 static char *find_cmd_name __P((int));
150 static char *prog_complete_return __P((const char *, int));
152 static char **prog_complete_matches;
155 /* Variables used here but defined in other files. */
156 #if defined (BANG_HISTORY)
157 extern int hist_verify;
160 extern int current_command_line_count, last_command_exit_value;
161 extern int posixly_correct, no_symbolic_links;
162 extern char *current_prompt_string, *ps1_prompt;
163 extern STRING_INT_ALIST word_token_alist[];
164 extern sh_builtin_func_t *last_shell_builtin, *this_shell_builtin;
166 /* SPECIFIC_COMPLETION_FUNCTIONS specifies that we have individual
167 completion functions which indicate what type of completion should be
168 done (at or before point) that can be bound to key sequences with
169 the readline library. */
170 #define SPECIFIC_COMPLETION_FUNCTIONS
172 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
173 static int bash_specific_completion __P((int, rl_compentry_func_t *));
175 static int bash_complete_filename_internal __P((int));
176 static int bash_complete_username_internal __P((int));
177 static int bash_complete_hostname_internal __P((int));
178 static int bash_complete_variable_internal __P((int));
179 static int bash_complete_command_internal __P((int));
181 static int bash_complete_filename __P((int, int));
182 static int bash_possible_filename_completions __P((int, int));
183 static int bash_complete_username __P((int, int));
184 static int bash_possible_username_completions __P((int, int));
185 static int bash_complete_hostname __P((int, int));
186 static int bash_possible_hostname_completions __P((int, int));
187 static int bash_complete_variable __P((int, int));
188 static int bash_possible_variable_completions __P((int, int));
189 static int bash_complete_command __P((int, int));
190 static int bash_possible_command_completions __P((int, int));
192 static char *glob_complete_word __P((const char *, int));
193 static int bash_glob_completion_internal __P((int));
194 static int bash_glob_complete_word __P((int, int));
195 static int bash_glob_expand_word __P((int, int));
196 static int bash_glob_list_expansions __P((int, int));
198 #endif /* SPECIFIC_COMPLETION_FUNCTIONS */
200 static int edit_and_execute_command __P((int, int, int, char *));
201 #if defined (VI_MODE)
202 static int vi_edit_and_execute_command __P((int, int));
203 static int bash_vi_complete __P((int, int));
205 static int emacs_edit_and_execute_command __P((int, int));
207 /* Non-zero once initalize_readline () has been called. */
208 int bash_readline_initialized = 0;
210 /* If non-zero, we do hostname completion, breaking words at `@' and
211 trying to complete the stuff after the `@' from our own internal
213 int perform_hostname_completion = 1;
215 /* If non-zero, we don't do command completion on an empty line. */
216 int no_empty_command_completion;
218 /* Set FORCE_FIGNORE if you want to honor FIGNORE even if it ignores the
219 only possible matches. Set to 0 if you want to match filenames if they
220 are the only possible matches, even if FIGNORE says to. */
221 int force_fignore = 1;
223 static char *bash_completer_word_break_characters = " \t\n\"'@><=;|&(:";
224 static char *bash_nohostname_word_break_characters = " \t\n\"'><=;|&(:";
227 static rl_hook_func_t *old_rl_startup_hook = (rl_hook_func_t *)NULL;
229 /* What kind of quoting is performed by bash_quote_filename:
230 COMPLETE_DQUOTE = double-quoting the filename
231 COMPLETE_SQUOTE = single_quoting the filename
232 COMPLETE_BSQUOTE = backslash-quoting special chars in the filename
234 #define COMPLETE_DQUOTE 1
235 #define COMPLETE_SQUOTE 2
236 #define COMPLETE_BSQUOTE 3
237 static int completion_quoting_style = COMPLETE_BSQUOTE;
239 /* Change the readline VI-mode keymaps into or out of Posix.2 compliance.
240 Called when the shell is put into or out of `posix' mode. */
242 posix_readline_initialize (on_or_off)
246 rl_variable_bind ("comment-begin", "#");
247 #if defined (VI_MODE)
248 rl_bind_key_in_map (CTRL ('I'), on_or_off ? rl_insert : rl_complete, vi_insertion_keymap);
252 /* When this function returns, rl_completer_word_break_characters points to
253 dynamically allocated memory. */
255 enable_hostname_completion (on_or_off)
259 char *at, *nv, *nval;
261 old_value = perform_hostname_completion;
265 perform_hostname_completion = 1;
266 rl_special_prefixes = "$@";
270 perform_hostname_completion = 0;
271 rl_special_prefixes = "$";
274 /* Now we need to figure out how to appropriately modify and assign
275 rl_completer_word_break_characters depending on whether we want
276 hostname completion on or off. */
278 /* If this is the first time this has been called
279 (bash_readline_initialized == 0), use the sames values as before, but
280 allocate new memory for rl_completer_word_break_characters. */
282 if (bash_readline_initialized == 0 &&
283 (rl_completer_word_break_characters == 0 ||
284 rl_completer_word_break_characters == rl_basic_word_break_characters))
287 rl_completer_word_break_characters = savestring (bash_completer_word_break_characters);
289 rl_completer_word_break_characters = savestring (bash_nohostname_word_break_characters);
293 /* See if we have anything to do. */
294 at = strchr (rl_completer_word_break_characters, '@');
295 if ((at == 0 && on_or_off == 0) || (at != 0 && on_or_off != 0))
298 /* We have something to do. Do it. */
299 nval = (char *)xmalloc (strlen (rl_completer_word_break_characters) + 1 + on_or_off);
303 /* Turn it off -- just remove `@' from word break chars. We want
304 to remove all occurrences of `@' from the char list, so we loop
305 rather than just copy the rest of the list over AT. */
306 for (nv = nval, at = rl_completer_word_break_characters; *at; )
316 strcpy (nval + 1, rl_completer_word_break_characters);
319 free (rl_completer_word_break_characters);
320 rl_completer_word_break_characters = nval;
326 /* Called once from parse.y if we are going to use readline. */
328 initialize_readline ()
330 rl_command_func_t *func;
333 if (bash_readline_initialized)
336 rl_terminal_name = get_string_value ("TERM");
338 rl_outstream = stderr;
340 /* Allow conditional parsing of the ~/.inputrc file. */
341 rl_readline_name = "Bash";
343 /* Add bindable names before calling rl_initialize so they may be
344 referenced in the various inputrc files. */
345 rl_add_defun ("shell-expand-line", shell_expand_line, -1);
347 rl_add_defun ("history-expand-line", history_expand_line, -1);
348 rl_add_defun ("magic-space", tcsh_magic_space, -1);
352 rl_add_defun ("alias-expand-line", alias_expand_line, -1);
354 rl_add_defun ("history-and-alias-expand-line", history_and_alias_expand_line, -1);
358 /* Backwards compatibility. */
359 rl_add_defun ("insert-last-argument", rl_yank_last_arg, -1);
361 rl_add_defun ("operate-and-get-next", operate_and_get_next, -1);
362 rl_add_defun ("display-shell-version", display_shell_version, -1);
363 rl_add_defun ("edit-and-execute-command", emacs_edit_and_execute_command, -1);
365 #if defined (BRACE_COMPLETION)
366 rl_add_defun ("complete-into-braces", bash_brace_completion, -1);
369 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
370 rl_add_defun ("complete-filename", bash_complete_filename, -1);
371 rl_add_defun ("possible-filename-completions", bash_possible_filename_completions, -1);
372 rl_add_defun ("complete-username", bash_complete_username, -1);
373 rl_add_defun ("possible-username-completions", bash_possible_username_completions, -1);
374 rl_add_defun ("complete-hostname", bash_complete_hostname, -1);
375 rl_add_defun ("possible-hostname-completions", bash_possible_hostname_completions, -1);
376 rl_add_defun ("complete-variable", bash_complete_variable, -1);
377 rl_add_defun ("possible-variable-completions", bash_possible_variable_completions, -1);
378 rl_add_defun ("complete-command", bash_complete_command, -1);
379 rl_add_defun ("possible-command-completions", bash_possible_command_completions, -1);
380 rl_add_defun ("glob-complete-word", bash_glob_complete_word, -1);
381 rl_add_defun ("glob-expand-word", bash_glob_expand_word, -1);
382 rl_add_defun ("glob-list-expansions", bash_glob_list_expansions, -1);
385 rl_add_defun ("dynamic-complete-history", dynamic_complete_history, -1);
387 /* Bind defaults before binding our custom shell keybindings. */
388 if (RL_ISSTATE(RL_STATE_INITIALIZED) == 0)
391 /* Bind up our special shell functions. */
392 rl_bind_key_if_unbound_in_map (CTRL('E'), shell_expand_line, emacs_meta_keymap);
395 rl_bind_key_if_unbound_in_map ('^', history_expand_line, emacs_meta_keymap);
398 rl_bind_key_if_unbound_in_map (CTRL ('O'), operate_and_get_next, emacs_standard_keymap);
399 rl_bind_key_if_unbound_in_map (CTRL ('V'), display_shell_version, emacs_ctlx_keymap);
401 /* In Bash, the user can switch editing modes with "set -o [vi emacs]",
402 so it is not necessary to allow C-M-j for context switching. Turn
403 off this occasionally confusing behaviour. */
406 func = rl_function_of_keyseq (kseq, emacs_meta_keymap, (int *)NULL);
407 if (func == rl_vi_editing_mode)
408 rl_unbind_key_in_map (CTRL('J'), emacs_meta_keymap);
410 func = rl_function_of_keyseq (kseq, emacs_meta_keymap, (int *)NULL);
411 if (func == rl_vi_editing_mode)
412 rl_unbind_key_in_map (CTRL('M'), emacs_meta_keymap);
413 #if defined (VI_MODE)
414 rl_unbind_key_in_map (CTRL('E'), vi_movement_keymap);
417 #if defined (BRACE_COMPLETION)
418 rl_bind_key_if_unbound_in_map ('{', bash_brace_completion, emacs_meta_keymap); /*}*/
419 #endif /* BRACE_COMPLETION */
421 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
422 rl_bind_key_if_unbound_in_map ('/', bash_complete_filename, emacs_meta_keymap);
423 rl_bind_key_if_unbound_in_map ('/', bash_possible_filename_completions, emacs_ctlx_keymap);
425 /* Have to jump through hoops here because there is a default binding for
426 M-~ (rl_tilde_expand) */
429 func = rl_function_of_keyseq (kseq, emacs_meta_keymap, (int *)NULL);
430 if (func == 0 || func == rl_tilde_expand)
431 rl_bind_keyseq_in_map (kseq, bash_complete_username, emacs_meta_keymap);
433 rl_bind_key_if_unbound_in_map ('~', bash_possible_username_completions, emacs_ctlx_keymap);
435 rl_bind_key_if_unbound_in_map ('@', bash_complete_hostname, emacs_meta_keymap);
436 rl_bind_key_if_unbound_in_map ('@', bash_possible_hostname_completions, emacs_ctlx_keymap);
438 rl_bind_key_if_unbound_in_map ('$', bash_complete_variable, emacs_meta_keymap);
439 rl_bind_key_if_unbound_in_map ('$', bash_possible_variable_completions, emacs_ctlx_keymap);
441 rl_bind_key_if_unbound_in_map ('!', bash_complete_command, emacs_meta_keymap);
442 rl_bind_key_if_unbound_in_map ('!', bash_possible_command_completions, emacs_ctlx_keymap);
444 rl_bind_key_if_unbound_in_map ('g', bash_glob_complete_word, emacs_meta_keymap);
445 rl_bind_key_if_unbound_in_map ('*', bash_glob_expand_word, emacs_ctlx_keymap);
446 rl_bind_key_if_unbound_in_map ('g', bash_glob_list_expansions, emacs_ctlx_keymap);
448 #endif /* SPECIFIC_COMPLETION_FUNCTIONS */
450 rl_bind_key_if_unbound_in_map (TAB, dynamic_complete_history, emacs_meta_keymap);
452 /* Tell the completer that we want a crack first. */
453 rl_attempted_completion_function = attempt_shell_completion;
455 /* Tell the completer that we might want to follow symbolic links or
456 do other expansion on directory names. */
457 rl_directory_completion_hook = bash_directory_completion_hook;
459 /* Tell the filename completer we want a chance to ignore some names. */
460 rl_ignore_some_completions_function = filename_completion_ignore;
462 /* Bind C-xC-e to invoke emacs and run result as commands. */
463 rl_bind_key_if_unbound_in_map (CTRL ('E'), emacs_edit_and_execute_command, emacs_ctlx_keymap);
464 #if defined (VI_MODE)
465 rl_bind_key_if_unbound_in_map ('v', vi_edit_and_execute_command, vi_movement_keymap);
467 rl_bind_key_if_unbound_in_map ('@', posix_edit_macros, 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);
472 rl_bind_key_in_map ('=', bash_vi_complete, vi_movement_keymap);
475 rl_completer_quote_characters = "'\"";
477 /* This sets rl_completer_word_break_characters and rl_special_prefixes
478 to the appropriate values, depending on whether or not hostname
479 completion is enabled. */
480 enable_hostname_completion (perform_hostname_completion);
482 /* characters that need to be quoted when appearing in filenames. */
483 rl_filename_quote_characters = " \t\n\\\"'@<>=;|&()#$`?*[!:{"; /*}*/
484 rl_filename_quoting_function = bash_quote_filename;
485 rl_filename_dequoting_function = bash_dequote_filename;
486 rl_char_is_quoted_p = char_is_quoted;
489 /* This is superfluous and makes it impossible to use tab completion in
490 vi mode even when explicitly binding it in ~/.inputrc. sv_strict_posix()
491 should already have called posix_readline_initialize() when
492 posixly_correct was set. */
494 posix_readline_initialize (1);
497 bash_readline_initialized = 1;
500 /* On Sun systems at least, rl_attempted_completion_function can end up
501 getting set to NULL, and rl_completion_entry_function set to do command
502 word completion if Bash is interrupted while trying to complete a command
503 word. This just resets all the completion functions to the right thing.
504 It's called from throw_to_top_level(). */
506 bashline_reinitialize ()
509 rl_attempted_completion_function = attempt_shell_completion;
510 rl_completion_entry_function = NULL;
511 rl_directory_completion_hook = bash_directory_completion_hook;
512 rl_ignore_some_completions_function = filename_completion_ignore;
515 /* Contains the line to push into readline. */
516 static char *push_to_readline = (char *)NULL;
518 /* Push the contents of push_to_readline into the
523 if (push_to_readline)
525 rl_insert_text (push_to_readline);
526 free (push_to_readline);
527 push_to_readline = (char *)NULL;
528 rl_startup_hook = old_rl_startup_hook;
533 /* Call this to set the initial text for the next line to read
539 FREE (push_to_readline);
541 push_to_readline = savestring (line);
542 old_rl_startup_hook = rl_startup_hook;
543 rl_startup_hook = bash_push_line;
549 display_shell_version (count, c)
553 show_shell_version (0);
554 putc ('\r', rl_outstream);
555 fflush (rl_outstream);
561 /* **************************************************************** */
565 /* **************************************************************** */
567 /* If the user requests hostname completion, then simply build a list
568 of hosts, and complete from that forever more, or at least until
569 HOSTFILE is unset. */
571 /* THIS SHOULD BE A STRINGLIST. */
572 /* The kept list of hostnames. */
573 static char **hostname_list = (char **)NULL;
575 /* The physical size of the above list. */
576 static int hostname_list_size;
578 /* The number of hostnames in the above list. */
579 static int hostname_list_length;
581 /* Whether or not HOSTNAME_LIST has been initialized. */
582 int hostname_list_initialized = 0;
584 /* Initialize the hostname completion table. */
586 initialize_hostname_list ()
590 temp = get_string_value ("HOSTFILE");
592 temp = get_string_value ("hostname_completion_file");
594 temp = DEFAULT_HOSTS_FILE;
596 snarf_hosts_from_file (temp);
599 hostname_list_initialized++;
602 /* Add NAME to the list of hosts. */
607 if (hostname_list_length + 2 > hostname_list_size)
609 hostname_list_size = (hostname_list_size + 32) - (hostname_list_size % 32);
610 hostname_list = strvec_resize (hostname_list, hostname_list_size);
613 hostname_list[hostname_list_length++] = savestring (name);
614 hostname_list[hostname_list_length] = (char *)NULL;
617 #define cr_whitespace(c) ((c) == '\r' || (c) == '\n' || whitespace(c))
620 snarf_hosts_from_file (filename)
624 char *temp, buffer[256], name[256];
625 register int i, start;
627 file = fopen (filename, "r");
631 while (temp = fgets (buffer, 255, file))
633 /* Skip to first character. */
634 for (i = 0; buffer[i] && cr_whitespace (buffer[i]); i++)
637 /* If comment or blank line, ignore. */
638 if (buffer[i] == '\0' || buffer[i] == '#')
641 /* If `preprocessor' directive, do the include. */
642 if (strncmp (buffer + i, "$include ", 9) == 0)
646 /* Find start of filename. */
647 for (incfile = buffer + i + 9; *incfile && whitespace (*incfile); incfile++)
650 /* Find end of filename. */
651 for (t = incfile; *t && cr_whitespace (*t) == 0; t++)
656 snarf_hosts_from_file (incfile);
660 /* Skip internet address if present. */
661 if (DIGIT (buffer[i]))
662 for (; buffer[i] && cr_whitespace (buffer[i]) == 0; i++);
664 /* Gobble up names. Each name is separated with whitespace. */
667 for (; cr_whitespace (buffer[i]); i++)
669 if (buffer[i] == '\0' || buffer[i] == '#')
672 /* Isolate the current word. */
673 for (start = i; buffer[i] && cr_whitespace (buffer[i]) == 0; i++)
677 strncpy (name, buffer + start, i - start);
678 name[i - start] = '\0';
679 add_host_name (name);
685 /* Return the hostname list. */
689 if (hostname_list_initialized == 0)
690 initialize_hostname_list ();
691 return (hostname_list);
695 clear_hostname_list ()
699 if (hostname_list_initialized == 0)
701 for (i = 0; i < hostname_list_length; i++)
702 free (hostname_list[i]);
703 hostname_list_length = 0;
706 /* Return a NULL terminated list of hostnames which begin with TEXT.
707 Initialize the hostname list the first time if neccessary.
708 The array is malloc ()'ed, but not the individual strings. */
710 hostnames_matching (text)
713 register int i, len, nmatch, rsize;
716 if (hostname_list_initialized == 0)
717 initialize_hostname_list ();
719 if (hostname_list_initialized == 0)
720 return ((char **)NULL);
722 /* Special case. If TEXT consists of nothing, then the whole list is
726 result = strvec_create (1 + hostname_list_length);
727 for (i = 0; i < hostname_list_length; i++)
728 result[i] = hostname_list[i];
729 result[i] = (char *)NULL;
733 /* Scan until found, or failure. */
735 result = (char **)NULL;
736 for (i = nmatch = rsize = 0; i < hostname_list_length; i++)
738 if (STREQN (text, hostname_list[i], len) == 0)
741 /* OK, it matches. Add it to the list. */
742 if (nmatch >= (rsize - 1))
744 rsize = (rsize + 16) - (rsize % 16);
745 result = strvec_resize (result, rsize);
748 result[nmatch++] = hostname_list[i];
751 result[nmatch] = (char *)NULL;
755 /* The equivalent of the Korn shell C-o operate-and-get-next-history-line
757 static int saved_history_line_to_use = -1;
762 if (saved_history_line_to_use >= 0)
763 rl_get_previous_history (history_length - saved_history_line_to_use, 0);
764 saved_history_line_to_use = -1;
765 rl_startup_hook = old_rl_startup_hook;
770 operate_and_get_next (count, c)
775 /* Accept the current line. */
778 /* Find the current line, and find the next line to use. */
779 where = where_history ();
781 if ((history_is_stifled () && (history_length >= history_max_entries)) ||
782 (where >= history_length - 1))
783 saved_history_line_to_use = where;
785 saved_history_line_to_use = where + 1;
787 old_rl_startup_hook = rl_startup_hook;
788 rl_startup_hook = set_saved_history;
793 /* This vi mode command causes VI_EDIT_COMMAND to be run on the current
794 command being entered (if no explicit argument is given), otherwise on
795 a command from the history file. */
797 #define VI_EDIT_COMMAND "fc -e \"${VISUAL:-${EDITOR:-vi}}\""
798 #define EMACS_EDIT_COMMAND "fc -e \"${VISUAL:-${EDITOR:-emacs}}\""
801 edit_and_execute_command (count, c, editing_mode, edit_command)
802 int count, c, editing_mode;
808 rrs = rl_readline_state;
809 cclc = current_command_line_count;
811 /* Accept the current line. */
816 command = (char *)xmalloc (strlen (edit_command) + 8);
817 sprintf (command, "%s %d", edit_command, count);
821 /* Take the command we were just editing, add it to the history file,
822 then call fc to operate on it. We have to add a dummy command to
823 the end of the history because fc ignores the last command (assumes
824 it's supposed to deal with the command before the `fc'). */
826 bash_add_history (rl_line_buffer);
827 bash_add_history ("");
828 history_lines_this_session++;
830 command = savestring (edit_command);
833 /* Now, POSIX.1-2001 and SUSv3 say that the commands executed from the
834 temporary file should be placed into the history. We don't do that
836 r = parse_and_execute (command, (editing_mode == VI_EDITING_MODE) ? "v" : "C-xC-e", SEVAL_NOHIST);
838 current_command_line_count = cclc;
840 /* Now erase the contents of the current line and undo the effects of the
841 rl_accept_line() above. We don't even want to make the text we just
842 executed available for undoing. */
843 rl_line_buffer[0] = '\0'; /* XXX */
844 rl_point = rl_end = 0;
846 rl_readline_state = rrs;
848 rl_forced_update_display ();
853 #if defined (VI_MODE)
855 vi_edit_and_execute_command (count, c)
858 return (edit_and_execute_command (count, c, VI_EDITING_MODE, VI_EDIT_COMMAND));
863 emacs_edit_and_execute_command (count, c)
866 return (edit_and_execute_command (count, c, EMACS_EDITING_MODE, EMACS_EDIT_COMMAND));
871 posix_edit_macros (count, key)
875 char alias_name[3], *alias_value, *macro;
880 alias_name[2] = '\0';
882 alias_value = get_alias_value (alias_name);
883 if (alias_value && *alias_value)
885 macro = savestring (alias_value);
886 rl_push_macro_input (macro);
892 /* **************************************************************** */
894 /* How To Do Shell Completion */
896 /* **************************************************************** */
898 #define COMMAND_SEPARATORS ";|&{(`"
905 register int this_char, prev_char;
907 /* Handle the two character tokens `>&', `<&', and `>|'.
908 We are not in a command position after one of these. */
909 this_char = rl_line_buffer[ti];
910 prev_char = rl_line_buffer[ti - 1];
912 if ((this_char == '&' && (prev_char == '<' || prev_char == '>')) ||
913 (this_char == '|' && prev_char == '>'))
915 else if ((this_char == '{' && prev_char == '$') || /* } */
916 (char_is_quoted (rl_line_buffer, ti)))
921 #if defined (PROGRAMMABLE_COMPLETION)
923 * XXX - because of the <= start test, and setting os = s+1, this can
924 * potentially return os > start. This is probably not what we want to
925 * happen, but fix later after 2.05a-release.
928 find_cmd_start (start)
934 while (((s = skip_to_delim (rl_line_buffer, os, COMMAND_SEPARATORS)) <= start) &&
946 e = skip_to_delim (rl_line_buffer, end, COMMAND_SEPARATORS);
951 find_cmd_name (start)
957 for (s = start; whitespace (rl_line_buffer[s]); s++)
960 /* skip until a shell break character */
961 e = skip_to_delim (rl_line_buffer, s, "()<>;&| \t\n");
963 name = substring (rl_line_buffer, s, e);
969 prog_complete_return (text, matchnum)
978 if (prog_complete_matches == 0 || prog_complete_matches[ind] == 0)
980 return (prog_complete_matches[ind++]);
983 #endif /* PROGRAMMABLE_COMPLETION */
985 /* Do some completion on TEXT. The indices of TEXT in RL_LINE_BUFFER are
986 at START and END. Return an array of matches, or NULL if none. */
988 attempt_shell_completion (text, start, end)
992 int in_command_position, ti, saveti, qc;
993 char **matches, *command_separator_chars;
995 command_separator_chars = COMMAND_SEPARATORS;
996 matches = (char **)NULL;
997 rl_ignore_some_completions_function = filename_completion_ignore;
999 /* Determine if this could be a command word. It is if it appears at
1000 the start of the line (ignoring preceding whitespace), or if it
1001 appears after a character that separates commands. It cannot be a
1002 command word if we aren't at the top-level prompt. */
1006 while ((ti > -1) && (whitespace (rl_line_buffer[ti])))
1010 /* If this is an open quote, maybe we're trying to complete a quoted
1012 if (ti >= 0 && (rl_line_buffer[ti] == '"' || rl_line_buffer[ti] == '\''))
1014 qc = rl_line_buffer[ti];
1016 while (ti > -1 && (whitespace (rl_line_buffer[ti])))
1021 in_command_position = 0;
1024 /* Only do command completion at the start of a line when we
1025 are prompting at the top level. */
1026 if (current_prompt_string == ps1_prompt)
1027 in_command_position++;
1029 else if (member (rl_line_buffer[ti], command_separator_chars))
1031 in_command_position++;
1033 if (check_redir (ti) == 1)
1034 in_command_position = 0;
1038 /* This still could be in command position. It is possible
1039 that all of the previous words on the line are variable
1043 /* Check that we haven't incorrectly flagged a closed command substitution
1044 as indicating we're in a command position. */
1045 if (in_command_position && ti >= 0 && rl_line_buffer[ti] == '`' &&
1046 *text != '`' && unclosed_pair (rl_line_buffer, end, "`") == 0)
1047 in_command_position = 0;
1049 /* Special handling for command substitution. If *TEXT is a backquote,
1050 it can be the start or end of an old-style command substitution, or
1051 unmatched. If it's unmatched, both calls to unclosed_pair will
1054 (in_command_position || (unclosed_pair (rl_line_buffer, start, "`") &&
1055 unclosed_pair (rl_line_buffer, end, "`"))))
1056 matches = rl_completion_matches (text, command_subst_completion_function);
1058 #if defined (PROGRAMMABLE_COMPLETION)
1059 /* Attempt programmable completion. */
1060 if (!matches && in_command_position == 0 && prog_completion_enabled &&
1061 (progcomp_size () > 0) && current_prompt_string == ps1_prompt)
1066 /* XXX - don't free the members */
1067 if (prog_complete_matches)
1068 free (prog_complete_matches);
1069 prog_complete_matches = (char **)NULL;
1071 s = find_cmd_start (start);
1072 e = find_cmd_end (end);
1073 n = find_cmd_name (s);
1075 prog_complete_matches = programmable_completions (n, text, s, e, &foundcs);
1079 /* XXX - if we found a COMPSPEC for the command, just return whatever
1080 the programmable completion code returns, and disable the default
1081 filename completion that readline will do unless the COPT_DEFAULT
1082 option has been set with the `-o default' option to complete. */
1085 /* If the user specified that the compspec returns filenames, make
1086 sure that readline knows it. */
1087 if (foundcs & COPT_FILENAMES)
1088 rl_filename_completion_desired = 1;
1089 /* If the user doesn't want a space appended, tell readline. */
1090 if (foundcs & COPT_NOSPACE)
1091 rl_completion_suppress_append = 1;
1092 /* Turn what the programmable completion code returns into what
1093 readline wants. I should have made compute_lcd_of_matches
1095 matches = rl_completion_matches (text, prog_complete_return);
1096 if ((foundcs & COPT_DEFAULT) == 0)
1097 rl_attempted_completion_over = 1; /* no default */
1098 if (matches || ((foundcs & COPT_BASHDEFAULT) == 0))
1105 matches = bash_default_completion (text, start, end, qc, in_command_position);
1111 bash_default_completion (text, start, end, qc, in_command_position)
1113 int start, end, qc, in_command_position;
1117 matches = (char **)NULL;
1119 /* New posix-style command substitution or variable name? */
1120 if (!matches && *text == '$')
1122 if (qc != '\'' && text[1] == '(') /* ) */
1123 matches = rl_completion_matches (text, command_subst_completion_function);
1125 matches = rl_completion_matches (text, variable_completion_function);
1128 /* If the word starts in `~', and there is no slash in the word, then
1129 try completing this word as a username. */
1130 if (!matches && *text == '~' && !xstrchr (text, '/'))
1131 matches = rl_completion_matches (text, rl_username_completion_function);
1133 /* Another one. Why not? If the word starts in '@', then look through
1134 the world of known hostnames for completion first. */
1135 if (!matches && perform_hostname_completion && *text == '@')
1136 matches = rl_completion_matches (text, hostname_completion_function);
1138 /* And last, (but not least) if this word is in a command position, then
1139 complete over possible command names, including aliases, functions,
1140 and command names. */
1141 if (!matches && in_command_position)
1143 if (start == 0 && end == 0 && text[0] == '\0' && no_empty_command_completion)
1145 matches = (char **)NULL;
1146 rl_ignore_some_completions_function = bash_ignore_everything;
1150 #define CMD_IS_DIR(x) (absolute_pathname(x) == 0 && absolute_program(x) == 0 && *(x) != '~' && test_for_directory (x))
1152 matches = rl_completion_matches (text, command_word_completion_function);
1154 /* If we are attempting command completion and nothing matches, we
1155 do not want readline to perform filename completion for us. We
1156 still want to be able to complete partial pathnames, so set the
1157 completion ignore function to something which will remove
1158 filenames and leave directories in the match list. */
1159 if (matches == (char **)NULL)
1160 rl_ignore_some_completions_function = bash_ignore_filenames;
1162 else if (matches[1] == 0 && CMD_IS_DIR(matches[0]))
1163 /* Turn off rl_filename_completion_desired so readline doesn't
1164 append a slash if there is a directory with the same name
1165 in the current directory, or other filename-specific things.
1166 If the name begins with a slash, we're either completing a
1167 full pathname or a directory pathname, and readline won't be
1168 looking in the current directory anyway, so there's no
1170 rl_filename_completion_desired = 0;
1171 else if (matches[0] && matches[1] && STREQ (matches[0], matches[1]) && CMD_IS_DIR (matches[0]))
1172 /* There are multiple instances of the same match (duplicate
1173 completions haven't yet been removed). In this case, all of
1174 the matches will be the same, and the duplicate removal code
1175 will distill them all down to one. We turn off
1176 rl_filename_completion_desired for the same reason as above.
1177 Remember: we only care if there's eventually a single unique
1178 completion. If there are multiple completions this won't
1179 make a difference and the problem won't occur. */
1180 rl_filename_completion_desired = 0;
1185 /* This could be a globbing pattern, so try to expand it using pathname
1187 if (!matches && glob_pattern_p (text))
1189 matches = rl_completion_matches (text, glob_complete_word);
1190 /* A glob expression that matches more than one filename is problematic.
1191 If we match more than one filename, punt. */
1192 if (matches && matches[1] && rl_completion_type == TAB)
1194 strvec_dispose (matches);
1195 matches = (char **)0;
1202 /* This is the function to call when the word to complete is in a position
1203 where a command word can be found. It grovels $PATH, looking for commands
1204 that match. It also scans aliases, function names, and the shell_builtin
1207 command_word_completion_function (hint_text, state)
1208 const char *hint_text;
1211 static char *hint = (char *)NULL;
1212 static char *path = (char *)NULL;
1213 static char *val = (char *)NULL;
1214 static char *filename_hint = (char *)NULL;
1215 static int path_index, hint_len, istate;
1216 static int mapping_over, local_index;
1217 static SHELL_VAR **varlist = (SHELL_VAR **)NULL;
1219 static alias_t **alias_list = (alias_t **)NULL;
1222 /* We have to map over the possibilities for command words. If we have
1223 no state, then make one just for that purpose. */
1232 /* If this is an absolute program name, do not check it against
1233 aliases, reserved words, functions or builtins. We must check
1234 whether or not it is unique, and, if so, whether that filename
1236 if (absolute_program (hint_text))
1238 /* Perform tilde expansion on what's passed, so we don't end up
1239 passing filenames with tildes directly to stat(). */
1240 if (*hint_text == '~')
1241 hint = bash_tilde_expand (hint_text, 0);
1243 hint = savestring (hint_text);
1244 hint_len = strlen (hint);
1247 free (filename_hint);
1248 filename_hint = savestring (hint);
1255 hint = savestring (hint_text);
1256 hint_len = strlen (hint);
1258 path = get_string_value ("PATH");
1261 /* Initialize the variables for each type of command word. */
1267 varlist = all_visible_functions ();
1273 alias_list = all_aliases ();
1277 /* mapping_over says what we are currently hacking. Note that every case
1278 in this list must fall through when there are no more possibilities. */
1280 switch (mapping_over)
1282 case 0: /* Aliases come first. */
1284 while (alias_list && alias_list[local_index])
1286 register char *alias;
1288 alias = alias_list[local_index++]->name;
1290 if (STREQN (alias, hint, hint_len))
1291 return (savestring (alias));
1297 case 1: /* Then shell reserved words. */
1299 while (word_token_alist[local_index].word)
1301 register char *reserved_word;
1303 reserved_word = word_token_alist[local_index++].word;
1305 if (STREQN (reserved_word, hint, hint_len))
1306 return (savestring (reserved_word));
1312 case 2: /* Then function names. */
1313 while (varlist && varlist[local_index])
1315 register char *varname;
1317 varname = varlist[local_index++]->name;
1319 if (STREQN (varname, hint, hint_len))
1320 return (savestring (varname));
1325 case 3: /* Then shell builtins. */
1326 for (; local_index < num_shell_builtins; local_index++)
1328 /* Ignore it if it doesn't have a function pointer or if it
1329 is not currently enabled. */
1330 if (!shell_builtins[local_index].function ||
1331 (shell_builtins[local_index].flags & BUILTIN_ENABLED) == 0)
1334 if (STREQN (shell_builtins[local_index].name, hint, hint_len))
1336 int i = local_index++;
1338 return (savestring (shell_builtins[i].name));
1345 /* Repeatedly call filename_completion_function while we have
1346 members of PATH left. Question: should we stat each file?
1347 Answer: we call executable_file () on each file. */
1350 istate = (val != (char *)NULL);
1356 /* Get the next directory from the path. If there is none, then we
1358 if (!path || !path[path_index] ||
1359 (current_path = extract_colon_unit (path, &path_index)) == 0)
1360 return ((char *)NULL);
1362 if (*current_path == 0)
1364 free (current_path);
1365 current_path = savestring (".");
1368 if (*current_path == '~')
1372 t = bash_tilde_expand (current_path, 0);
1373 free (current_path);
1378 free (filename_hint);
1380 filename_hint = sh_makepath (current_path, hint, 0);
1382 free (current_path);
1386 val = rl_filename_completion_function (filename_hint, istate);
1391 /* If the hint text is an absolute program, then don't bother
1392 searching through PATH. */
1393 if (absolute_program (hint))
1394 return ((char *)NULL);
1400 int match, freetemp;
1403 if (absolute_program (hint))
1405 match = strncmp (val, hint, hint_len) == 0;
1406 /* If we performed tilde expansion, restore the original
1408 if (*hint_text == '~')
1413 tl = strlen (hint_text);
1415 l = vl - hint_len; /* # of chars added */
1417 rd = savestring (filename_hint);
1418 bash_directory_expansion (&rd);
1420 l = vl - dl; /* # of chars added */
1423 temp = (char *)xmalloc (l + 2 + tl);
1424 strcpy (temp, hint_text);
1425 strcpy (temp + tl, val + vl - l);
1428 temp = savestring (val);
1433 temp = strrchr (val, '/');
1438 freetemp = match = strncmp (temp, hint, hint_len) == 0;
1440 temp = savestring (temp);
1443 freetemp = match = 0;
1446 /* If we have found a match, and it is an executable file or a
1447 directory name, return it. */
1448 if (match && executable_or_directory (val))
1451 val = ""; /* So it won't be NULL. */
1464 /* Completion inside an unterminated command substitution. */
1466 command_subst_completion_function (text, state)
1470 static char **matches = (char **)NULL;
1471 static const char *orig_start;
1472 static char *filename_text = (char *)NULL;
1473 static int cmd_index, start_len;
1479 free (filename_text);
1483 else if (*text == '$' && text[1] == '(') /* ) */
1485 /* If the text was quoted, suppress any quote character that the
1486 readline completion code would insert. */
1487 rl_completion_suppress_quote = 1;
1488 start_len = text - orig_start;
1489 filename_text = savestring (text);
1494 * At this point we can entertain the idea of re-parsing
1495 * `filename_text' into a (possibly incomplete) command name and
1496 * arguments, and doing completion based on that. This is
1497 * currently very rudimentary, but it is a small improvement.
1499 for (value = filename_text + strlen (filename_text) - 1; value > filename_text; value--)
1500 if (whitespace (*value) || member (*value, COMMAND_SEPARATORS))
1502 if (value <= filename_text)
1503 matches = rl_completion_matches (filename_text, command_word_completion_function);
1507 start_len += value - filename_text;
1508 if (whitespace (value[-1]))
1509 matches = rl_completion_matches (value, rl_filename_completion_function);
1511 matches = rl_completion_matches (value, command_word_completion_function);
1514 /* If there is more than one match, rl_completion_matches has already
1515 put the lcd in matches[0]. Skip over it. */
1516 cmd_index = matches && matches[0] && matches[1];
1519 if (!matches || !matches[cmd_index])
1521 rl_filename_quoting_desired = 0; /* disable quoting */
1522 return ((char *)NULL);
1526 value = (char *)xmalloc (1 + start_len + strlen (matches[cmd_index]));
1529 value[0] = *orig_start;
1531 strncpy (value, orig_start, start_len);
1533 strcpy (value + start_len, matches[cmd_index]);
1540 /* Okay, now we write the entry_function for variable completion. */
1542 variable_completion_function (text, state)
1546 static char **varlist = (char **)NULL;
1547 static int varlist_index;
1548 static char *varname = (char *)NULL;
1550 static int first_char, first_char_loc;
1558 first_char = text[0];
1560 if (first_char == '$')
1563 if (text[first_char_loc] == '{')
1566 varname = savestring (text + first_char_loc);
1568 namelen = strlen (varname);
1570 strvec_dispose (varlist);
1572 varlist = all_variables_matching_prefix (varname);
1576 if (!varlist || !varlist[varlist_index])
1578 return ((char *)NULL);
1584 value = (char *)xmalloc (4 + strlen (varlist[varlist_index]));
1588 value[0] = first_char;
1589 if (first_char_loc == 2)
1593 strcpy (value + first_char_loc, varlist[varlist_index]);
1594 if (first_char_loc == 2)
1595 strcat (value, "}");
1602 /* How about a completion function for hostnames? */
1604 hostname_completion_function (text, state)
1608 static char **list = (char **)NULL;
1609 static int list_index = 0;
1610 static int first_char, first_char_loc;
1612 /* If we don't have any state, make some. */
1617 list = (char **)NULL;
1622 if (first_char == '@')
1625 list = hostnames_matching ((char *)text+first_char_loc);
1629 if (list && list[list_index])
1633 t = (char *)xmalloc (2 + strlen (list[list_index]));
1635 strcpy (t + first_char_loc, list[list_index]);
1640 return ((char *)NULL);
1644 * A completion function for service names from /etc/services (or wherever).
1647 bash_servicename_completion_function (text, state)
1651 #if defined (__WIN32__) || defined (__OPENNT) || !defined (HAVE_GETSERVENT)
1652 return ((char *)NULL);
1654 static char *sname = (char *)NULL;
1655 static struct servent *srvent;
1656 static int snamelen, firstc;
1658 char **alist, *aentry;
1666 sname = savestring (text);
1667 snamelen = strlen (sname);
1671 while (srvent = getservent ())
1674 if (snamelen == 0 || (STREQN (sname, srvent->s_name, snamelen)))
1676 /* Not primary, check aliases */
1677 for (alist = srvent->s_aliases; aentry = *alist; alist++)
1679 if (STREQN (sname, aentry, snamelen))
1693 return ((char *)NULL);
1696 value = afound ? savestring (aentry) : savestring (srvent->s_name);
1702 * A completion function for group names from /etc/group (or wherever).
1705 bash_groupname_completion_function (text, state)
1709 #if defined (__WIN32__) || defined (__OPENNT) || !defined (HAVE_GRP_H)
1710 return ((char *)NULL);
1712 static char *gname = (char *)NULL;
1713 static struct group *grent;
1714 static int gnamelen;
1720 gname = savestring (text);
1721 gnamelen = strlen (gname);
1726 while (grent = getgrent ())
1728 if (gnamelen == 0 || (STREQN (gname, grent->gr_name, gnamelen)))
1735 return ((char *)NULL);
1738 value = savestring (grent->gr_name);
1743 /* Functions to perform history and alias expansions on the current line. */
1745 #if defined (BANG_HISTORY)
1746 /* Perform history expansion on the current line. If no history expansion
1747 is done, pre_process_line() returns what it was passed, so we need to
1748 allocate a new line here. */
1750 history_expand_line_internal (line)
1756 old_verify = hist_verify;
1758 new_line = pre_process_line (line, 0, 0);
1759 hist_verify = old_verify;
1761 return (new_line == line) ? savestring (line) : new_line;
1765 /* There was an error in expansion. Let the preprocessor print
1768 cleanup_expansion_error ()
1771 #if defined (BANG_HISTORY)
1774 old_verify = hist_verify;
1778 fprintf (rl_outstream, "\r\n");
1779 to_free = pre_process_line (rl_line_buffer, 1, 0);
1780 #if defined (BANG_HISTORY)
1781 hist_verify = old_verify;
1783 if (to_free != rl_line_buffer)
1785 putc ('\r', rl_outstream);
1786 rl_forced_update_display ();
1789 /* If NEW_LINE differs from what is in the readline line buffer, add an
1790 undo record to get from the readline line buffer contents to the new
1791 line and make NEW_LINE the current readline line. */
1793 maybe_make_readline_line (new_line)
1796 if (strcmp (new_line, rl_line_buffer) != 0)
1800 rl_add_undo (UNDO_BEGIN, 0, 0, 0);
1801 rl_delete_text (0, rl_point);
1802 rl_point = rl_end = rl_mark = 0;
1803 rl_insert_text (new_line);
1804 rl_add_undo (UNDO_END, 0, 0, 0);
1808 /* Make NEW_LINE be the current readline line. This frees NEW_LINE. */
1810 set_up_new_line (new_line)
1813 int old_point, at_end;
1815 old_point = rl_point;
1816 at_end = rl_point == rl_end;
1818 /* If the line was history and alias expanded, then make that
1819 be one thing to undo. */
1820 maybe_make_readline_line (new_line);
1823 /* Place rl_point where we think it should go. */
1826 else if (old_point < rl_end)
1828 rl_point = old_point;
1829 if (!whitespace (rl_line_buffer[rl_point]))
1830 rl_forward_word (1, 0);
1835 /* Expand aliases in the current readline line. */
1837 alias_expand_line (count, ignore)
1842 new_line = alias_expand (rl_line_buffer);
1846 set_up_new_line (new_line);
1851 cleanup_expansion_error ();
1857 #if defined (BANG_HISTORY)
1858 /* History expand the line. */
1860 history_expand_line (count, ignore)
1865 new_line = history_expand_line_internal (rl_line_buffer);
1869 set_up_new_line (new_line);
1874 cleanup_expansion_error ();
1879 /* Expand history substitutions in the current line and then insert a
1880 space (hopefully close to where we were before). */
1882 tcsh_magic_space (count, ignore)
1885 int dist_from_end, old_point;
1887 old_point = rl_point;
1888 dist_from_end = rl_end - rl_point;
1889 if (history_expand_line (count, ignore) == 0)
1891 /* Try a simple heuristic from Stephen Gildea <gildea@intouchsys.com>.
1892 This works if all expansions were before rl_point or if no expansions
1894 rl_point = (old_point == 0) ? old_point : rl_end - dist_from_end;
1903 /* History and alias expand the line. */
1905 history_and_alias_expand_line (count, ignore)
1910 new_line = history_expand_line_internal (rl_line_buffer);
1917 alias_line = alias_expand (new_line);
1919 new_line = alias_line;
1925 set_up_new_line (new_line);
1930 cleanup_expansion_error ();
1935 /* History and alias expand the line, then perform the shell word
1936 expansions by calling expand_string. This can't use set_up_new_line()
1937 because we want the variable expansions as a separate undo'able
1938 set of operations. */
1940 shell_expand_line (count, ignore)
1944 WORD_LIST *expanded_string;
1946 new_line = history_expand_line_internal (rl_line_buffer);
1953 alias_line = alias_expand (new_line);
1955 new_line = alias_line;
1961 int old_point = rl_point;
1962 int at_end = rl_point == rl_end;
1964 /* If the line was history and alias expanded, then make that
1965 be one thing to undo. */
1966 maybe_make_readline_line (new_line);
1969 /* If there is variable expansion to perform, do that as a separate
1970 operation to be undone. */
1971 new_line = savestring (rl_line_buffer);
1972 expanded_string = expand_string (new_line, 0);
1974 if (expanded_string == 0)
1976 new_line = (char *)xmalloc (1);
1981 new_line = string_list (expanded_string);
1982 dispose_words (expanded_string);
1985 maybe_make_readline_line (new_line);
1988 /* Place rl_point where we think it should go. */
1991 else if (old_point < rl_end)
1993 rl_point = old_point;
1994 if (!whitespace (rl_line_buffer[rl_point]))
1995 rl_forward_word (1, 0);
2001 cleanup_expansion_error ();
2006 /* If FIGNORE is set, then don't match files with the given suffixes when
2007 completing filenames. If only one of the possibilities has an acceptable
2008 suffix, delete the others, else just return and let the completer
2009 signal an error. It is called by the completer when real
2010 completions are done on filenames by the completer's internal
2011 function, not for completion lists (M-?) and not on "other"
2012 completion types, such as hostnames or commands. */
2014 static struct ignorevar fignore =
2020 (sh_iv_item_func_t *) 0,
2024 _ignore_completion_names (names, name_func)
2026 sh_ignore_func_t *name_func;
2033 /* If there is only one completion, see if it is acceptable. If it is
2034 not, free it up. In any case, short-circuit and return. This is a
2035 special case because names[0] is not the prefix of the list of names
2036 if there is only one completion; it is the completion itself. */
2037 if (names[1] == (char *)0)
2040 if ((*name_func) (names[0]) == 0)
2043 names[0] = (char *)NULL;
2049 /* Allocate space for array to hold list of pointers to matching
2050 filenames. The pointers are copied back to NAMES when done. */
2051 for (nidx = 1; names[nidx]; nidx++)
2053 newnames = strvec_create (nidx + 1);
2055 if (force_fignore == 0)
2057 oldnames = strvec_create (nidx - 1);
2061 newnames[0] = names[0];
2062 for (idx = nidx = 1; names[idx]; idx++)
2064 if ((*name_func) (names[idx]))
2065 newnames[nidx++] = names[idx];
2066 else if (force_fignore == 0)
2067 oldnames[oidx++] = names[idx];
2072 newnames[nidx] = (char *)NULL;
2074 /* If none are acceptable then let the completer handle it. */
2080 names[0] = (char *)NULL;
2089 if (force_fignore == 0)
2092 free (oldnames[--oidx]);
2096 /* If only one is acceptable, copy it to names[0] and return. */
2100 names[0] = newnames[1];
2101 names[1] = (char *)NULL;
2106 /* Copy the acceptable names back to NAMES, set the new array end,
2108 for (nidx = 1; newnames[nidx]; nidx++)
2109 names[nidx] = newnames[nidx];
2110 names[nidx] = (char *)NULL;
2115 name_is_acceptable (name)
2121 for (nlen = strlen (name), p = fignore.ignores; p->val; p++)
2123 if (nlen > p->len && p->len > 0 && STREQ (p->val, &name[nlen - p->len]))
2132 ignore_dot_names (name)
2135 return (name[0] != '.');
2140 filename_completion_ignore (names)
2144 if (glob_dot_filenames == 0)
2145 _ignore_completion_names (names, ignore_dot_names);
2148 setup_ignore_patterns (&fignore);
2150 if (fignore.num_ignores == 0)
2153 _ignore_completion_names (names, name_is_acceptable);
2158 /* Return 1 if NAME is a directory. */
2160 test_for_directory (name)
2166 fn = bash_tilde_expand (name, 0);
2167 if (stat (fn, &finfo) != 0)
2173 return (S_ISDIR (finfo.st_mode));
2176 /* Remove files from NAMES, leaving directories. */
2178 bash_ignore_filenames (names)
2181 _ignore_completion_names (names, test_for_directory);
2193 bash_ignore_everything (names)
2196 _ignore_completion_names (names, return_zero);
2200 /* Simulate the expansions that will be performed by
2201 rl_filename_completion_function. This must be called with the address of
2202 a pointer to malloc'd memory. */
2204 bash_directory_expansion (dirname)
2209 d = savestring (*dirname);
2211 if (rl_directory_rewrite_hook)
2212 (*rl_directory_rewrite_hook) (&d);
2214 if (rl_directory_completion_hook && (*rl_directory_completion_hook) (&d))
2221 /* Handle symbolic link references and other directory name
2222 expansions while hacking completion. */
2224 bash_directory_completion_hook (dirname)
2227 char *local_dirname, *new_dirname, *t;
2228 int return_value, should_expand_dirname;
2232 return_value = should_expand_dirname = 0;
2233 local_dirname = *dirname;
2236 should_expand_dirname = xstrchr (local_dirname, '$') || xstrchr (local_dirname, '`');
2238 if (xstrchr (local_dirname, '$'))
2239 should_expand_dirname = 1;
2242 t = xstrchr (local_dirname, '`');
2243 if (t && unclosed_pair (local_dirname, strlen (local_dirname), "`") == 0)
2244 should_expand_dirname = 1;
2248 #if defined (HAVE_LSTAT)
2249 if (should_expand_dirname && lstat (local_dirname, &sb) == 0)
2251 if (should_expand_dirname && stat (local_dirname, &sb) == 0)
2253 should_expand_dirname = 0;
2255 if (should_expand_dirname)
2257 new_dirname = savestring (local_dirname);
2258 wl = expand_prompt_string (new_dirname, 0); /* does the right thing */
2261 *dirname = string_list (wl);
2262 /* Tell the completer to replace the directory name only if we
2263 actually expanded something. */
2264 return_value = STREQ (local_dirname, *dirname) == 0;
2265 free (local_dirname);
2268 local_dirname = *dirname;
2273 free (local_dirname);
2274 *dirname = (char *)xmalloc (1);
2280 if (!no_symbolic_links && (local_dirname[0] != '.' || local_dirname[1]))
2282 char *temp1, *temp2;
2285 t = get_working_directory ("symlink-hook");
2286 temp1 = make_absolute (local_dirname, t);
2288 temp2 = sh_canonpath (temp1, PATH_CHECKDOTDOT|PATH_CHECKEXISTS);
2289 /* If we can't canonicalize, bail. */
2295 len1 = strlen (temp1);
2296 if (temp1[len1 - 1] == '/')
2298 len2 = strlen (temp2);
2299 temp2 = (char *)xrealloc (temp2, len2 + 2);
2301 temp2[len2 + 1] = '\0';
2303 free (local_dirname);
2307 return (return_value);
2310 static char **history_completion_array = (char **)NULL;
2311 static int harry_size;
2312 static int harry_len;
2315 build_history_completion_array ()
2321 /* First, clear out the current dynamic history completion list. */
2324 strvec_dispose (history_completion_array);
2325 history_completion_array = (char **)NULL;
2330 /* Next, grovel each line of history, making each shell-sized token
2331 a separate entry in the history_completion_array. */
2332 hlist = history_list ();
2336 for (i = 0; hlist[i]; i++)
2338 /* Separate each token, and place into an array. */
2339 tokens = history_tokenize (hlist[i]->line);
2341 for (j = 0; tokens && tokens[j]; j++)
2343 if (harry_len + 2 > harry_size)
2344 history_completion_array = strvec_resize (history_completion_array, harry_size += 10);
2346 history_completion_array[harry_len++] = tokens[j];
2347 history_completion_array[harry_len] = (char *)NULL;
2352 /* Sort the complete list of tokens. */
2353 qsort (history_completion_array, harry_len, sizeof (char *), (QSFUNC *)strvec_strcmp);
2358 history_completion_generator (hint_text, state)
2359 const char *hint_text;
2362 static int local_index, len;
2363 static const char *text;
2365 /* If this is the first call to the generator, then initialize the
2366 list of strings to complete over. */
2370 build_history_completion_array ();
2372 len = strlen (text);
2375 while (history_completion_array && history_completion_array[local_index])
2377 if (strncmp (text, history_completion_array[local_index++], len) == 0)
2378 return (savestring (history_completion_array[local_index - 1]));
2380 return ((char *)NULL);
2384 dynamic_complete_history (count, key)
2389 rl_compentry_func_t *orig_func;
2390 rl_completion_func_t *orig_attempt_func;
2392 orig_func = rl_completion_entry_function;
2393 orig_attempt_func = rl_attempted_completion_function;
2394 rl_completion_entry_function = history_completion_generator;
2395 rl_attempted_completion_function = (rl_completion_func_t *)NULL;
2397 /* XXX - use rl_completion_mode here? */
2398 if (rl_last_func == dynamic_complete_history)
2399 r = rl_complete_internal ('?');
2401 r = rl_complete_internal (TAB);
2403 rl_completion_entry_function = orig_func;
2404 rl_attempted_completion_function = orig_attempt_func;
2408 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
2410 bash_complete_username (ignore, ignore2)
2411 int ignore, ignore2;
2413 return bash_complete_username_internal (rl_completion_mode (bash_complete_username));
2417 bash_possible_username_completions (ignore, ignore2)
2418 int ignore, ignore2;
2420 return bash_complete_username_internal ('?');
2424 bash_complete_username_internal (what_to_do)
2427 return bash_specific_completion (what_to_do, rl_username_completion_function);
2431 bash_complete_filename (ignore, ignore2)
2432 int ignore, ignore2;
2434 return bash_complete_filename_internal (rl_completion_mode (bash_complete_filename));
2438 bash_possible_filename_completions (ignore, ignore2)
2439 int ignore, ignore2;
2441 return bash_complete_filename_internal ('?');
2445 bash_complete_filename_internal (what_to_do)
2448 rl_compentry_func_t *orig_func;
2449 rl_completion_func_t *orig_attempt_func;
2450 rl_icppfunc_t *orig_dir_func;
2451 /*const*/ char *orig_rl_completer_word_break_characters;
2454 orig_func = rl_completion_entry_function;
2455 orig_attempt_func = rl_attempted_completion_function;
2456 orig_dir_func = rl_directory_completion_hook;
2457 orig_rl_completer_word_break_characters = rl_completer_word_break_characters;
2458 rl_completion_entry_function = rl_filename_completion_function;
2459 rl_attempted_completion_function = (rl_completion_func_t *)NULL;
2460 rl_directory_completion_hook = (rl_icppfunc_t *)NULL;
2461 rl_completer_word_break_characters = " \t\n\"\'";
2463 r = rl_complete_internal (what_to_do);
2465 rl_completion_entry_function = orig_func;
2466 rl_attempted_completion_function = orig_attempt_func;
2467 rl_directory_completion_hook = orig_dir_func;
2468 rl_completer_word_break_characters = orig_rl_completer_word_break_characters;
2474 bash_complete_hostname (ignore, ignore2)
2475 int ignore, ignore2;
2477 return bash_complete_hostname_internal (rl_completion_mode (bash_complete_hostname));
2481 bash_possible_hostname_completions (ignore, ignore2)
2482 int ignore, ignore2;
2484 return bash_complete_hostname_internal ('?');
2488 bash_complete_variable (ignore, ignore2)
2489 int ignore, ignore2;
2491 return bash_complete_variable_internal (rl_completion_mode (bash_complete_variable));
2495 bash_possible_variable_completions (ignore, ignore2)
2496 int ignore, ignore2;
2498 return bash_complete_variable_internal ('?');
2502 bash_complete_command (ignore, ignore2)
2503 int ignore, ignore2;
2505 return bash_complete_command_internal (rl_completion_mode (bash_complete_command));
2509 bash_possible_command_completions (ignore, ignore2)
2510 int ignore, ignore2;
2512 return bash_complete_command_internal ('?');
2516 bash_complete_hostname_internal (what_to_do)
2519 return bash_specific_completion (what_to_do, hostname_completion_function);
2523 bash_complete_variable_internal (what_to_do)
2526 return bash_specific_completion (what_to_do, variable_completion_function);
2530 bash_complete_command_internal (what_to_do)
2533 return bash_specific_completion (what_to_do, command_word_completion_function);
2536 static char *globtext;
2537 static char *globorig;
2540 glob_complete_word (text, state)
2544 static char **matches = (char **)NULL;
2551 rl_filename_completion_desired = 1;
2553 if (globorig != globtext)
2557 ttext = bash_tilde_expand (text, 0);
2559 if (rl_explicit_arg)
2561 globorig = savestring (ttext);
2562 glen = strlen (ttext);
2563 globtext = (char *)xmalloc (glen + 2);
2564 strcpy (globtext, ttext);
2565 globtext[glen] = '*';
2566 globtext[glen+1] = '\0';
2569 globtext = globorig = savestring (ttext);
2574 matches = shell_glob_filename (globtext);
2575 if (GLOB_FAILED (matches))
2576 matches = (char **)NULL;
2580 ret = matches ? matches[ind] : (char *)NULL;
2586 bash_glob_completion_internal (what_to_do)
2589 return bash_specific_completion (what_to_do, glob_complete_word);
2592 /* A special quoting function so we don't end up quoting globbing characters
2593 in the word if there are no matches or multiple matches. */
2595 bash_glob_quote_filename (s, rtype, qcp)
2600 if (globorig && qcp && *qcp == '\0' && STREQ (s, globorig))
2601 return (savestring (s));
2603 return (bash_quote_filename (s, rtype, qcp));
2607 bash_glob_complete_word (count, key)
2611 rl_quote_func_t *orig_quoting_function;
2613 if (rl_editing_mode == EMACS_EDITING_MODE)
2614 rl_explicit_arg = 1; /* force `*' append */
2615 orig_quoting_function = rl_filename_quoting_function;
2616 rl_filename_quoting_function = bash_glob_quote_filename;
2618 r = bash_glob_completion_internal (rl_completion_mode (bash_glob_complete_word));
2620 rl_filename_quoting_function = orig_quoting_function;
2625 bash_glob_expand_word (count, key)
2628 return bash_glob_completion_internal ('*');
2632 bash_glob_list_expansions (count, key)
2635 return bash_glob_completion_internal ('?');
2639 bash_specific_completion (what_to_do, generator)
2641 rl_compentry_func_t *generator;
2643 rl_compentry_func_t *orig_func;
2644 rl_completion_func_t *orig_attempt_func;
2647 orig_func = rl_completion_entry_function;
2648 orig_attempt_func = rl_attempted_completion_function;
2649 rl_completion_entry_function = generator;
2650 rl_attempted_completion_function = NULL;
2652 r = rl_complete_internal (what_to_do);
2654 rl_completion_entry_function = orig_func;
2655 rl_attempted_completion_function = orig_attempt_func;
2660 #endif /* SPECIFIC_COMPLETION_FUNCTIONS */
2662 #if defined (VI_MODE)
2663 /* Completion, from vi mode's point of view. This is a modified version of
2664 rl_vi_complete which uses the bash globbing code to implement what POSIX
2665 specifies, which is to append a `*' and attempt filename generation (which
2666 has the side effect of expanding any globbing characters in the word). */
2668 bash_vi_complete (count, key)
2671 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
2675 if ((rl_point < rl_end) && (!whitespace (rl_line_buffer[rl_point])))
2677 if (!whitespace (rl_line_buffer[rl_point + 1]))
2678 rl_vi_end_word (1, 'E');
2682 /* Find boundaries of current word, according to vi definition of a
2688 rl_vi_bWord (1, 'B');
2693 t = substring (rl_line_buffer, p, rl_point);
2696 if (t && glob_pattern_p (t) == 0)
2697 rl_explicit_arg = 1; /* XXX - force glob_complete_word to append `*' */
2700 if (key == '*') /* Expansion and replacement. */
2701 r = bash_glob_expand_word (count, key);
2702 else if (key == '=') /* List possible completions. */
2703 r = bash_glob_list_expansions (count, key);
2704 else if (key == '\\') /* Standard completion */
2705 r = bash_glob_complete_word (count, key);
2707 r = rl_complete (0, key);
2709 if (key == '*' || key == '\\')
2710 rl_vi_start_inserting (key, 1, 1);
2714 return rl_vi_complete (count, key);
2715 #endif /* !SPECIFIC_COMPLETION_FUNCTIONS */
2717 #endif /* VI_MODE */
2719 /* Filename quoting for completion. */
2720 /* A function to strip unquoted quote characters (single quotes, double
2721 quotes, and backslashes). It allows single quotes to appear
2722 within double quotes, and vice versa. It should be smarter. */
2724 bash_dequote_filename (text, quote_char)
2732 ret = (char *)xmalloc (l + 1);
2733 for (quoted = quote_char, p = text, r = ret; p && *p; p++)
2735 /* Allow backslash-quoted characters to pass through unscathed. */
2744 if (quoted && *p == quoted)
2750 if (quoted == 0 && (*p == '\'' || *p == '"'))
2761 /* Quote characters that the readline completion code would treat as
2762 word break characters with backslashes. Pass backslash-quoted
2763 characters through without examination. */
2765 quote_word_break_chars (text)
2772 ret = (char *)xmalloc ((2 * l) + 1);
2773 for (s = text, r = ret; *s; s++)
2775 /* Pass backslash-quoted characters through, including the backslash. */
2784 /* OK, we have an unquoted character. Check its presence in
2785 rl_completer_word_break_characters. */
2786 if (xstrchr (rl_completer_word_break_characters, *s))
2794 /* Quote a filename using double quotes, single quotes, or backslashes
2795 depending on the value of completion_quoting_style. If we're
2796 completing using backslashes, we need to quote some additional
2797 characters (those that readline treats as word breaks), so we call
2798 quote_word_break_chars on the result. This returns newly-allocated
2801 bash_quote_filename (s, rtype, qcp)
2806 char *rtext, *mtext, *ret;
2809 rtext = (char *)NULL;
2811 /* If RTYPE == MULT_MATCH, it means that there is
2812 more than one match. In this case, we do not add
2813 the closing quote or attempt to perform tilde
2814 expansion. If RTYPE == SINGLE_MATCH, we try
2815 to perform tilde expansion, because single and double
2816 quotes inhibit tilde expansion by the shell. */
2819 if (mtext[0] == '~' && rtype == SINGLE_MATCH)
2820 mtext = bash_tilde_expand (s, 0);
2822 cs = completion_quoting_style;
2823 /* Might need to modify the default completion style based on *qcp,
2824 since it's set to any user-provided opening quote. We also change
2825 to single-quoting if there is no user-provided opening quote and
2826 the word being completed contains newlines, since those are not
2827 quoted correctly using backslashes (a backslash-newline pair is
2828 special to the shell parser). */
2829 if (*qcp == '\0' && cs == COMPLETE_BSQUOTE && xstrchr (mtext, '\n'))
2830 cs = COMPLETE_SQUOTE;
2831 else if (*qcp == '"')
2832 cs = COMPLETE_DQUOTE;
2833 else if (*qcp == '\'')
2834 cs = COMPLETE_SQUOTE;
2835 #if defined (BANG_HISTORY)
2836 else if (*qcp == '\0' && history_expansion && cs == COMPLETE_DQUOTE &&
2837 history_expansion_inhibited == 0 && xstrchr (mtext, '!'))
2838 cs = COMPLETE_BSQUOTE;
2840 if (*qcp == '"' && history_expansion && cs == COMPLETE_DQUOTE &&
2841 history_expansion_inhibited == 0 && xstrchr (mtext, '!'))
2843 cs = COMPLETE_BSQUOTE;
2850 case COMPLETE_DQUOTE:
2851 rtext = sh_double_quote (mtext);
2853 case COMPLETE_SQUOTE:
2854 rtext = sh_single_quote (mtext);
2856 case COMPLETE_BSQUOTE:
2857 rtext = sh_backslash_quote (mtext);
2864 /* We may need to quote additional characters: those that readline treats
2865 as word breaks that are not quoted by backslash_quote. */
2866 if (rtext && cs == COMPLETE_BSQUOTE)
2868 mtext = quote_word_break_chars (rtext);
2873 /* Leave the opening quote intact. The readline completion code takes
2874 care of avoiding doubled opening quotes. */
2875 rlen = strlen (rtext);
2876 ret = (char *)xmalloc (rlen + 1);
2877 strcpy (ret, rtext);
2879 /* If there are multiple matches, cut off the closing quote. */
2880 if (rtype == MULT_MATCH && cs != COMPLETE_BSQUOTE)
2881 ret[rlen - 1] = '\0';
2886 /* Support for binding readline key sequences to Unix commands. */
2887 static Keymap cmd_xmap;
2890 bash_execute_unix_command (count, key)
2891 int count; /* ignored */
2894 Keymap ckmap; /* current keymap */
2895 Keymap xkmap; /* unix command executing keymap */
2898 sh_parser_state_t ps;
2900 /* First, we need to find the right command to execute. This is tricky,
2901 because we might have already indirected into another keymap. */
2902 ckmap = rl_get_keymap ();
2903 if (ckmap != rl_executing_keymap)
2905 /* bogus. we have to search. only handle one level of indirection. */
2906 for (i = 0; i < KEYMAP_SIZE; i++)
2908 if (ckmap[i].type == ISKMAP && (Keymap)ckmap[i].function == rl_executing_keymap)
2911 if (i < KEYMAP_SIZE)
2912 xkmap = (Keymap)cmd_xmap[i].function;
2916 internal_error (_("bash_execute_unix_command: cannot find keymap for command"));
2917 rl_forced_update_display ();
2924 cmd = (char *)xkmap[key].function;
2932 rl_crlf (); /* move to a new line */
2934 save_parser_state (&ps);
2936 cmd = savestring (cmd);
2937 parse_and_execute (cmd, "bash_execute_unix_command", SEVAL_NOHIST);
2939 restore_parser_state (&ps);
2941 /* and restore the readline buffer and display after command execution. */
2942 rl_forced_update_display ();
2947 init_unix_command_map ()
2949 cmd_xmap = rl_make_bare_keymap ();
2953 isolate_sequence (string, ind, need_dquote, startp)
2955 int ind, need_dquote, *startp;
2958 int c, passc, delim;
2960 for (i = ind; string[i] && whitespace (string[i]); i++)
2962 /* NEED_DQUOTE means that the first non-white character *must* be `"'. */
2963 if (need_dquote && string[i] != '"')
2965 builtin_error (_("%s: first non-whitespace character is not `\"'"), string);
2969 /* We can have delimited strings even if NEED_DQUOTE == 0, like the command
2970 string to bind the key sequence to. */
2971 delim = (string[i] == '"' || string[i] == '\'') ? string[i] : 0;
2974 *startp = delim ? ++i : i;
2976 for (passc = 0; c = string[i]; i++)
2992 if (delim && string[i] != delim)
2994 builtin_error (_("no closing `%c' in %s"), delim, string);
3002 bind_keyseq_to_unix_command (line)
3010 init_unix_command_map ();
3012 kmap = rl_get_keymap ();
3014 /* We duplicate some of the work done by rl_parse_and_bind here, but
3015 this code only has to handle `"keyseq": ["]command["]' and can
3016 generate an error for anything else. */
3017 i = isolate_sequence (line, 0, 1, &kstart);
3021 /* Create the key sequence string to pass to rl_generic_bind */
3022 kseq = substring (line, kstart, i);
3024 for ( ; line[i] && line[i] != ':'; i++)
3028 builtin_error (_("%s: missing colon separator"), line);
3032 i = isolate_sequence (line, i + 1, 0, &kstart);
3036 /* Create the value string containing the command to execute. */
3037 value = substring (line, kstart, i);
3039 /* Save the command to execute and the key sequence in the CMD_XMAP */
3040 rl_generic_bind (ISMACR, kseq, value, cmd_xmap);
3042 /* and bind the key sequence in the current keymap to a function that
3043 understands how to execute from CMD_XMAP */
3044 rl_bind_keyseq_in_map (kseq, bash_execute_unix_command, kmap);
3049 /* Used by the programmable completion code. Complete TEXT as a filename,
3050 but return only directories as matches. Dequotes the filename before
3051 attempting to find matches. */
3053 bash_directory_completion_matches (text)
3061 qc = (text[0] == '"' || text[0] == '\'') ? text[0] : 0;
3063 qc = rl_dispatching ? rl_completion_quote_character : 0;
3065 dfn = bash_dequote_filename ((char *)text, qc);
3066 m1 = rl_completion_matches (dfn, rl_filename_completion_function);
3069 if (m1 == 0 || m1[0] == 0)
3071 /* We don't bother recomputing the lcd of the matches, because it will just
3072 get thrown away by the programmable completion code and recomputed
3074 (void)bash_ignore_filenames (m1);
3079 bash_dequote_text (text)
3085 qc = (text[0] == '"' || text[0] == '\'') ? text[0] : 0;
3086 dtxt = bash_dequote_filename ((char *)text, qc);
3089 #endif /* READLINE */