1 /* bashline.c -- Bash's interface to the readline library. */
3 /* Copyright (C) 1987-2011 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
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 Bash is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Bash. If not, see <http://www.gnu.org/licenses/>.
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"
55 #include "builtins/common.h"
57 #include <readline/rlconf.h>
58 #include <readline/readline.h>
59 #include <readline/history.h>
61 #include <glob/glob.h>
67 #if defined (PROGRAMMABLE_COMPLETION)
68 # include "pcomplete.h"
71 /* These should agree with the defines for emacs_mode and vi_mode in
72 rldefs.h, even though that's not a public readline header file. */
73 #ifndef EMACS_EDITING_MODE
74 # define NO_EDITING_MODE -1
75 # define EMACS_EDITING_MODE 1
76 # define VI_EDITING_MODE 0
79 #define RL_BOOLEAN_VARIABLE_VALUE(s) ((s)[0] == 'o' && (s)[1] == 'n' && (s)[2] == '\0')
81 #if defined (BRACE_COMPLETION)
82 extern int bash_brace_completion __P((int, int));
83 #endif /* BRACE_COMPLETION */
85 /* To avoid including curses.h/term.h/termcap.h and that whole mess. */
86 extern int tputs __P((const char *string, int nlines, int (*outx)(int)));
88 /* Forward declarations */
90 /* Functions bound to keys in Readline for Bash users. */
91 static int shell_expand_line __P((int, int));
92 static int display_shell_version __P((int, int));
93 static int operate_and_get_next __P((int, int));
95 static int bash_ignore_filenames __P((char **));
96 static int bash_ignore_everything __P((char **));
98 #if defined (BANG_HISTORY)
99 static char *history_expand_line_internal __P((char *));
100 static int history_expand_line __P((int, int));
101 static int tcsh_magic_space __P((int, int));
102 #endif /* BANG_HISTORY */
104 static int alias_expand_line __P((int, int));
106 #if defined (BANG_HISTORY) && defined (ALIAS)
107 static int history_and_alias_expand_line __P((int, int));
110 static int bash_forward_shellword __P((int, int));
111 static int bash_backward_shellword __P((int, int));
112 static int bash_kill_shellword __P((int, int));
113 static int bash_backward_kill_shellword __P((int, int));
115 /* Helper functions for Readline. */
116 static char *restore_tilde __P((char *, char *));
118 static char *bash_filename_rewrite_hook __P((char *, int));
119 static void bash_directory_expansion __P((char **));
120 static int bash_directory_completion_hook __P((char **));
121 static int filename_completion_ignore __P((char **));
122 static int bash_push_line __P((void));
124 static rl_icppfunc_t *save_directory_hook __P((void));
125 static void reset_directory_hook __P((rl_icppfunc_t *));
127 static void cleanup_expansion_error __P((void));
128 static void maybe_make_readline_line __P((char *));
129 static void set_up_new_line __P((char *));
131 static int check_redir __P((int));
132 static char **attempt_shell_completion __P((const char *, int, int));
133 static char *variable_completion_function __P((const char *, int));
134 static char *hostname_completion_function __P((const char *, int));
135 static char *command_subst_completion_function __P((const char *, int));
137 static void build_history_completion_array __P((void));
138 static char *history_completion_generator __P((const char *, int));
139 static int dynamic_complete_history __P((int, int));
140 static int bash_dabbrev_expand __P((int, int));
142 static void initialize_hostname_list __P((void));
143 static void add_host_name __P((char *));
144 static void snarf_hosts_from_file __P((char *));
145 static char **hostnames_matching __P((char *));
147 static void _ignore_completion_names __P((char **, sh_ignore_func_t *));
148 static int name_is_acceptable __P((const char *));
149 static int test_for_directory __P((const char *));
150 static int return_zero __P((const char *));
152 static char *bash_dequote_filename __P((char *, int));
153 static char *quote_word_break_chars __P((char *));
154 static char *bash_quote_filename __P((char *, int, char *));
156 static int putx __P((int));
157 static int bash_execute_unix_command __P((int, int));
158 static void init_unix_command_map __P((void));
159 static int isolate_sequence __P((char *, int, int, int *));
161 static int set_saved_history __P((void));
164 static int posix_edit_macros __P((int, int));
167 #if defined (PROGRAMMABLE_COMPLETION)
168 static int find_cmd_start __P((int));
169 static int find_cmd_end __P((int));
170 static char *find_cmd_name __P((int));
171 static char *prog_complete_return __P((const char *, int));
173 static char **prog_complete_matches;
176 /* Variables used here but defined in other files. */
177 #if defined (BANG_HISTORY)
178 extern int hist_verify;
181 extern int current_command_line_count, saved_command_line_count;
182 extern int last_command_exit_value;
183 extern int array_needs_making;
184 extern int posixly_correct, no_symbolic_links;
185 extern char *current_prompt_string, *ps1_prompt;
186 extern STRING_INT_ALIST word_token_alist[];
187 extern sh_builtin_func_t *last_shell_builtin, *this_shell_builtin;
189 /* SPECIFIC_COMPLETION_FUNCTIONS specifies that we have individual
190 completion functions which indicate what type of completion should be
191 done (at or before point) that can be bound to key sequences with
192 the readline library. */
193 #define SPECIFIC_COMPLETION_FUNCTIONS
195 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
196 static int bash_specific_completion __P((int, rl_compentry_func_t *));
198 static int bash_complete_filename_internal __P((int));
199 static int bash_complete_username_internal __P((int));
200 static int bash_complete_hostname_internal __P((int));
201 static int bash_complete_variable_internal __P((int));
202 static int bash_complete_command_internal __P((int));
204 static int bash_complete_filename __P((int, int));
205 static int bash_possible_filename_completions __P((int, int));
206 static int bash_complete_username __P((int, int));
207 static int bash_possible_username_completions __P((int, int));
208 static int bash_complete_hostname __P((int, int));
209 static int bash_possible_hostname_completions __P((int, int));
210 static int bash_complete_variable __P((int, int));
211 static int bash_possible_variable_completions __P((int, int));
212 static int bash_complete_command __P((int, int));
213 static int bash_possible_command_completions __P((int, int));
215 static char *glob_complete_word __P((const char *, int));
216 static int bash_glob_completion_internal __P((int));
217 static int bash_glob_complete_word __P((int, int));
218 static int bash_glob_expand_word __P((int, int));
219 static int bash_glob_list_expansions __P((int, int));
221 #endif /* SPECIFIC_COMPLETION_FUNCTIONS */
223 static int edit_and_execute_command __P((int, int, int, char *));
224 #if defined (VI_MODE)
225 static int vi_edit_and_execute_command __P((int, int));
226 static int bash_vi_complete __P((int, int));
228 static int emacs_edit_and_execute_command __P((int, int));
230 /* Non-zero once initalize_readline () has been called. */
231 int bash_readline_initialized = 0;
233 /* If non-zero, we do hostname completion, breaking words at `@' and
234 trying to complete the stuff after the `@' from our own internal
236 int perform_hostname_completion = 1;
238 /* If non-zero, we don't do command completion on an empty line. */
239 int no_empty_command_completion;
241 /* Set FORCE_FIGNORE if you want to honor FIGNORE even if it ignores the
242 only possible matches. Set to 0 if you want to match filenames if they
243 are the only possible matches, even if FIGNORE says to. */
244 int force_fignore = 1;
246 /* Perform spelling correction on directory names during word completion */
247 int dircomplete_spelling = 0;
249 /* Expand directory names during word/filename completion. */
250 int dircomplete_expand = 0;
251 int dircomplete_expand_relpath = 0;
253 static char *bash_completer_word_break_characters = " \t\n\"'@><=;|&(:";
254 static char *bash_nohostname_word_break_characters = " \t\n\"'><=;|&(:";
257 static const char *default_filename_quote_characters = " \t\n\\\"'@<>=;|&()#$`?*[!:{~"; /*}*/
258 static char *custom_filename_quote_characters = 0;
260 static rl_hook_func_t *old_rl_startup_hook = (rl_hook_func_t *)NULL;
262 static int dot_in_path = 0;
264 /* Set to non-zero when dabbrev-expand is running */
265 static int dabbrev_expand_active = 0;
267 /* What kind of quoting is performed by bash_quote_filename:
268 COMPLETE_DQUOTE = double-quoting the filename
269 COMPLETE_SQUOTE = single_quoting the filename
270 COMPLETE_BSQUOTE = backslash-quoting special chars in the filename
272 #define COMPLETE_DQUOTE 1
273 #define COMPLETE_SQUOTE 2
274 #define COMPLETE_BSQUOTE 3
275 static int completion_quoting_style = COMPLETE_BSQUOTE;
277 /* Flag values for the final argument to bash_default_completion */
278 #define DEFCOMP_CMDPOS 1
280 /* Change the readline VI-mode keymaps into or out of Posix.2 compliance.
281 Called when the shell is put into or out of `posix' mode. */
283 posix_readline_initialize (on_or_off)
287 rl_variable_bind ("comment-begin", "#");
288 #if defined (VI_MODE)
289 rl_bind_key_in_map (CTRL ('I'), on_or_off ? rl_insert : rl_complete, vi_insertion_keymap);
294 reset_completer_word_break_chars ()
296 rl_completer_word_break_characters = perform_hostname_completion ? savestring (bash_completer_word_break_characters) : savestring (bash_nohostname_word_break_characters);
299 /* When this function returns, rl_completer_word_break_characters points to
300 dynamically allocated memory. */
302 enable_hostname_completion (on_or_off)
306 char *at, *nv, *nval;
308 old_value = perform_hostname_completion;
312 perform_hostname_completion = 1;
313 rl_special_prefixes = "$@";
317 perform_hostname_completion = 0;
318 rl_special_prefixes = "$";
321 /* Now we need to figure out how to appropriately modify and assign
322 rl_completer_word_break_characters depending on whether we want
323 hostname completion on or off. */
325 /* If this is the first time this has been called
326 (bash_readline_initialized == 0), use the sames values as before, but
327 allocate new memory for rl_completer_word_break_characters. */
329 if (bash_readline_initialized == 0 &&
330 (rl_completer_word_break_characters == 0 ||
331 rl_completer_word_break_characters == rl_basic_word_break_characters))
334 rl_completer_word_break_characters = savestring (bash_completer_word_break_characters);
336 rl_completer_word_break_characters = savestring (bash_nohostname_word_break_characters);
340 /* See if we have anything to do. */
341 at = strchr (rl_completer_word_break_characters, '@');
342 if ((at == 0 && on_or_off == 0) || (at != 0 && on_or_off != 0))
345 /* We have something to do. Do it. */
346 nval = (char *)xmalloc (strlen (rl_completer_word_break_characters) + 1 + on_or_off);
350 /* Turn it off -- just remove `@' from word break chars. We want
351 to remove all occurrences of `@' from the char list, so we loop
352 rather than just copy the rest of the list over AT. */
353 for (nv = nval, at = rl_completer_word_break_characters; *at; )
363 strcpy (nval + 1, rl_completer_word_break_characters);
366 free (rl_completer_word_break_characters);
367 rl_completer_word_break_characters = nval;
373 /* Called once from parse.y if we are going to use readline. */
375 initialize_readline ()
377 rl_command_func_t *func;
380 if (bash_readline_initialized)
383 rl_terminal_name = get_string_value ("TERM");
385 rl_outstream = stderr;
387 /* Allow conditional parsing of the ~/.inputrc file. */
388 rl_readline_name = "Bash";
390 /* Add bindable names before calling rl_initialize so they may be
391 referenced in the various inputrc files. */
392 rl_add_defun ("shell-expand-line", shell_expand_line, -1);
394 rl_add_defun ("history-expand-line", history_expand_line, -1);
395 rl_add_defun ("magic-space", tcsh_magic_space, -1);
398 rl_add_defun ("shell-forward-word", bash_forward_shellword, -1);
399 rl_add_defun ("shell-backward-word", bash_backward_shellword, -1);
400 rl_add_defun ("shell-kill-word", bash_kill_shellword, -1);
401 rl_add_defun ("shell-backward-kill-word", bash_backward_kill_shellword, -1);
404 rl_add_defun ("alias-expand-line", alias_expand_line, -1);
406 rl_add_defun ("history-and-alias-expand-line", history_and_alias_expand_line, -1);
410 /* Backwards compatibility. */
411 rl_add_defun ("insert-last-argument", rl_yank_last_arg, -1);
413 rl_add_defun ("operate-and-get-next", operate_and_get_next, -1);
414 rl_add_defun ("display-shell-version", display_shell_version, -1);
415 rl_add_defun ("edit-and-execute-command", emacs_edit_and_execute_command, -1);
417 #if defined (BRACE_COMPLETION)
418 rl_add_defun ("complete-into-braces", bash_brace_completion, -1);
421 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
422 rl_add_defun ("complete-filename", bash_complete_filename, -1);
423 rl_add_defun ("possible-filename-completions", bash_possible_filename_completions, -1);
424 rl_add_defun ("complete-username", bash_complete_username, -1);
425 rl_add_defun ("possible-username-completions", bash_possible_username_completions, -1);
426 rl_add_defun ("complete-hostname", bash_complete_hostname, -1);
427 rl_add_defun ("possible-hostname-completions", bash_possible_hostname_completions, -1);
428 rl_add_defun ("complete-variable", bash_complete_variable, -1);
429 rl_add_defun ("possible-variable-completions", bash_possible_variable_completions, -1);
430 rl_add_defun ("complete-command", bash_complete_command, -1);
431 rl_add_defun ("possible-command-completions", bash_possible_command_completions, -1);
432 rl_add_defun ("glob-complete-word", bash_glob_complete_word, -1);
433 rl_add_defun ("glob-expand-word", bash_glob_expand_word, -1);
434 rl_add_defun ("glob-list-expansions", bash_glob_list_expansions, -1);
437 rl_add_defun ("dynamic-complete-history", dynamic_complete_history, -1);
438 rl_add_defun ("dabbrev-expand", bash_dabbrev_expand, -1);
440 /* Bind defaults before binding our custom shell keybindings. */
441 if (RL_ISSTATE(RL_STATE_INITIALIZED) == 0)
444 /* Bind up our special shell functions. */
445 rl_bind_key_if_unbound_in_map (CTRL('E'), shell_expand_line, emacs_meta_keymap);
448 rl_bind_key_if_unbound_in_map ('^', history_expand_line, emacs_meta_keymap);
451 rl_bind_key_if_unbound_in_map (CTRL ('O'), operate_and_get_next, emacs_standard_keymap);
452 rl_bind_key_if_unbound_in_map (CTRL ('V'), display_shell_version, emacs_ctlx_keymap);
454 /* In Bash, the user can switch editing modes with "set -o [vi emacs]",
455 so it is not necessary to allow C-M-j for context switching. Turn
456 off this occasionally confusing behaviour. */
459 func = rl_function_of_keyseq (kseq, emacs_meta_keymap, (int *)NULL);
460 if (func == rl_vi_editing_mode)
461 rl_unbind_key_in_map (CTRL('J'), emacs_meta_keymap);
463 func = rl_function_of_keyseq (kseq, emacs_meta_keymap, (int *)NULL);
464 if (func == rl_vi_editing_mode)
465 rl_unbind_key_in_map (CTRL('M'), emacs_meta_keymap);
466 #if defined (VI_MODE)
467 rl_unbind_key_in_map (CTRL('E'), vi_movement_keymap);
470 #if defined (BRACE_COMPLETION)
471 rl_bind_key_if_unbound_in_map ('{', bash_brace_completion, emacs_meta_keymap); /*}*/
472 #endif /* BRACE_COMPLETION */
474 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
475 rl_bind_key_if_unbound_in_map ('/', bash_complete_filename, emacs_meta_keymap);
476 rl_bind_key_if_unbound_in_map ('/', bash_possible_filename_completions, emacs_ctlx_keymap);
478 /* Have to jump through hoops here because there is a default binding for
479 M-~ (rl_tilde_expand) */
482 func = rl_function_of_keyseq (kseq, emacs_meta_keymap, (int *)NULL);
483 if (func == 0 || func == rl_tilde_expand)
484 rl_bind_keyseq_in_map (kseq, bash_complete_username, emacs_meta_keymap);
486 rl_bind_key_if_unbound_in_map ('~', bash_possible_username_completions, emacs_ctlx_keymap);
488 rl_bind_key_if_unbound_in_map ('@', bash_complete_hostname, emacs_meta_keymap);
489 rl_bind_key_if_unbound_in_map ('@', bash_possible_hostname_completions, emacs_ctlx_keymap);
491 rl_bind_key_if_unbound_in_map ('$', bash_complete_variable, emacs_meta_keymap);
492 rl_bind_key_if_unbound_in_map ('$', bash_possible_variable_completions, emacs_ctlx_keymap);
494 rl_bind_key_if_unbound_in_map ('!', bash_complete_command, emacs_meta_keymap);
495 rl_bind_key_if_unbound_in_map ('!', bash_possible_command_completions, emacs_ctlx_keymap);
497 rl_bind_key_if_unbound_in_map ('g', bash_glob_complete_word, emacs_meta_keymap);
498 rl_bind_key_if_unbound_in_map ('*', bash_glob_expand_word, emacs_ctlx_keymap);
499 rl_bind_key_if_unbound_in_map ('g', bash_glob_list_expansions, emacs_ctlx_keymap);
501 #endif /* SPECIFIC_COMPLETION_FUNCTIONS */
505 func = rl_function_of_keyseq (kseq, emacs_meta_keymap, (int *)NULL);
506 if (func == 0 || func == rl_tab_insert)
507 rl_bind_key_in_map (TAB, dynamic_complete_history, emacs_meta_keymap);
509 /* Tell the completer that we want a crack first. */
510 rl_attempted_completion_function = attempt_shell_completion;
512 /* Tell the completer that we might want to follow symbolic links or
513 do other expansion on directory names. */
514 set_directory_hook ();
516 rl_filename_rewrite_hook = bash_filename_rewrite_hook;
518 /* Tell the filename completer we want a chance to ignore some names. */
519 rl_ignore_some_completions_function = filename_completion_ignore;
521 /* Bind C-xC-e to invoke emacs and run result as commands. */
522 rl_bind_key_if_unbound_in_map (CTRL ('E'), emacs_edit_and_execute_command, emacs_ctlx_keymap);
523 #if defined (VI_MODE)
524 rl_bind_key_if_unbound_in_map ('v', vi_edit_and_execute_command, vi_movement_keymap);
526 rl_bind_key_if_unbound_in_map ('@', posix_edit_macros, vi_movement_keymap);
529 rl_bind_key_in_map ('\\', bash_vi_complete, vi_movement_keymap);
530 rl_bind_key_in_map ('*', bash_vi_complete, vi_movement_keymap);
531 rl_bind_key_in_map ('=', bash_vi_complete, vi_movement_keymap);
534 rl_completer_quote_characters = "'\"";
536 /* This sets rl_completer_word_break_characters and rl_special_prefixes
537 to the appropriate values, depending on whether or not hostname
538 completion is enabled. */
539 enable_hostname_completion (perform_hostname_completion);
541 /* characters that need to be quoted when appearing in filenames. */
542 rl_filename_quote_characters = default_filename_quote_characters;
544 rl_filename_quoting_function = bash_quote_filename;
545 rl_filename_dequoting_function = bash_dequote_filename;
546 rl_char_is_quoted_p = char_is_quoted;
549 /* This is superfluous and makes it impossible to use tab completion in
550 vi mode even when explicitly binding it in ~/.inputrc. sv_strict_posix()
551 should already have called posix_readline_initialize() when
552 posixly_correct was set. */
554 posix_readline_initialize (1);
557 bash_readline_initialized = 1;
561 bashline_reinitialize ()
563 bash_readline_initialized = 0;
566 /* On Sun systems at least, rl_attempted_completion_function can end up
567 getting set to NULL, and rl_completion_entry_function set to do command
568 word completion if Bash is interrupted while trying to complete a command
569 word. This just resets all the completion functions to the right thing.
570 It's called from throw_to_top_level(). */
575 rl_attempted_completion_function = attempt_shell_completion;
576 rl_completion_entry_function = NULL;
577 rl_ignore_some_completions_function = filename_completion_ignore;
578 rl_filename_quote_characters = default_filename_quote_characters;
580 set_directory_hook ();
583 /* Contains the line to push into readline. */
584 static char *push_to_readline = (char *)NULL;
586 /* Push the contents of push_to_readline into the
591 if (push_to_readline)
593 rl_insert_text (push_to_readline);
594 free (push_to_readline);
595 push_to_readline = (char *)NULL;
596 rl_startup_hook = old_rl_startup_hook;
601 /* Call this to set the initial text for the next line to read
607 FREE (push_to_readline);
609 push_to_readline = savestring (line);
610 old_rl_startup_hook = rl_startup_hook;
611 rl_startup_hook = bash_push_line;
617 display_shell_version (count, c)
621 show_shell_version (0);
622 putc ('\r', rl_outstream);
623 fflush (rl_outstream);
629 /* **************************************************************** */
633 /* **************************************************************** */
635 /* If the user requests hostname completion, then simply build a list
636 of hosts, and complete from that forever more, or at least until
637 HOSTFILE is unset. */
639 /* THIS SHOULD BE A STRINGLIST. */
640 /* The kept list of hostnames. */
641 static char **hostname_list = (char **)NULL;
643 /* The physical size of the above list. */
644 static int hostname_list_size;
646 /* The number of hostnames in the above list. */
647 static int hostname_list_length;
649 /* Whether or not HOSTNAME_LIST has been initialized. */
650 int hostname_list_initialized = 0;
652 /* Initialize the hostname completion table. */
654 initialize_hostname_list ()
658 temp = get_string_value ("HOSTFILE");
660 temp = get_string_value ("hostname_completion_file");
662 temp = DEFAULT_HOSTS_FILE;
664 snarf_hosts_from_file (temp);
667 hostname_list_initialized++;
670 /* Add NAME to the list of hosts. */
675 if (hostname_list_length + 2 > hostname_list_size)
677 hostname_list_size = (hostname_list_size + 32) - (hostname_list_size % 32);
678 hostname_list = strvec_resize (hostname_list, hostname_list_size);
681 hostname_list[hostname_list_length++] = savestring (name);
682 hostname_list[hostname_list_length] = (char *)NULL;
685 #define cr_whitespace(c) ((c) == '\r' || (c) == '\n' || whitespace(c))
688 snarf_hosts_from_file (filename)
692 char *temp, buffer[256], name[256];
693 register int i, start;
695 file = fopen (filename, "r");
699 while (temp = fgets (buffer, 255, file))
701 /* Skip to first character. */
702 for (i = 0; buffer[i] && cr_whitespace (buffer[i]); i++)
705 /* If comment or blank line, ignore. */
706 if (buffer[i] == '\0' || buffer[i] == '#')
709 /* If `preprocessor' directive, do the include. */
710 if (strncmp (buffer + i, "$include ", 9) == 0)
714 /* Find start of filename. */
715 for (incfile = buffer + i + 9; *incfile && whitespace (*incfile); incfile++)
718 /* Find end of filename. */
719 for (t = incfile; *t && cr_whitespace (*t) == 0; t++)
724 snarf_hosts_from_file (incfile);
728 /* Skip internet address if present. */
729 if (DIGIT (buffer[i]))
730 for (; buffer[i] && cr_whitespace (buffer[i]) == 0; i++);
732 /* Gobble up names. Each name is separated with whitespace. */
735 for (; cr_whitespace (buffer[i]); i++)
737 if (buffer[i] == '\0' || buffer[i] == '#')
740 /* Isolate the current word. */
741 for (start = i; buffer[i] && cr_whitespace (buffer[i]) == 0; i++)
745 strncpy (name, buffer + start, i - start);
746 name[i - start] = '\0';
747 add_host_name (name);
753 /* Return the hostname list. */
757 if (hostname_list_initialized == 0)
758 initialize_hostname_list ();
759 return (hostname_list);
763 clear_hostname_list ()
767 if (hostname_list_initialized == 0)
769 for (i = 0; i < hostname_list_length; i++)
770 free (hostname_list[i]);
771 hostname_list_length = hostname_list_initialized = 0;
774 /* Return a NULL terminated list of hostnames which begin with TEXT.
775 Initialize the hostname list the first time if neccessary.
776 The array is malloc ()'ed, but not the individual strings. */
778 hostnames_matching (text)
781 register int i, len, nmatch, rsize;
784 if (hostname_list_initialized == 0)
785 initialize_hostname_list ();
787 if (hostname_list_initialized == 0)
788 return ((char **)NULL);
790 /* Special case. If TEXT consists of nothing, then the whole list is
794 result = strvec_create (1 + hostname_list_length);
795 for (i = 0; i < hostname_list_length; i++)
796 result[i] = hostname_list[i];
797 result[i] = (char *)NULL;
801 /* Scan until found, or failure. */
803 result = (char **)NULL;
804 for (i = nmatch = rsize = 0; i < hostname_list_length; i++)
806 if (STREQN (text, hostname_list[i], len) == 0)
809 /* OK, it matches. Add it to the list. */
810 if (nmatch >= (rsize - 1))
812 rsize = (rsize + 16) - (rsize % 16);
813 result = strvec_resize (result, rsize);
816 result[nmatch++] = hostname_list[i];
819 result[nmatch] = (char *)NULL;
823 /* The equivalent of the Korn shell C-o operate-and-get-next-history-line
825 static int saved_history_line_to_use = -1;
830 if (saved_history_line_to_use >= 0)
831 rl_get_previous_history (history_length - saved_history_line_to_use, 0);
832 saved_history_line_to_use = -1;
833 rl_startup_hook = old_rl_startup_hook;
838 operate_and_get_next (count, c)
843 /* Accept the current line. */
846 /* Find the current line, and find the next line to use. */
847 where = where_history ();
849 if ((history_is_stifled () && (history_length >= history_max_entries)) ||
850 (where >= history_length - 1))
851 saved_history_line_to_use = where;
853 saved_history_line_to_use = where + 1;
855 old_rl_startup_hook = rl_startup_hook;
856 rl_startup_hook = set_saved_history;
861 /* This vi mode command causes VI_EDIT_COMMAND to be run on the current
862 command being entered (if no explicit argument is given), otherwise on
863 a command from the history file. */
865 #define VI_EDIT_COMMAND "fc -e \"${VISUAL:-${EDITOR:-vi}}\""
866 #define EMACS_EDIT_COMMAND "fc -e \"${VISUAL:-${EDITOR:-emacs}}\""
867 #define POSIX_VI_EDIT_COMMAND "fc -e vi"
870 edit_and_execute_command (count, c, editing_mode, edit_command)
871 int count, c, editing_mode;
874 char *command, *metaval;
875 int r, rrs, metaflag;
876 sh_parser_state_t ps;
878 rrs = rl_readline_state;
879 saved_command_line_count = current_command_line_count;
881 /* Accept the current line. */
886 command = (char *)xmalloc (strlen (edit_command) + 8);
887 sprintf (command, "%s %d", edit_command, count);
891 /* Take the command we were just editing, add it to the history file,
892 then call fc to operate on it. We have to add a dummy command to
893 the end of the history because fc ignores the last command (assumes
894 it's supposed to deal with the command before the `fc'). */
895 /* This breaks down when using command-oriented history and are not
896 finished with the command, so we should not ignore the last command */
898 bash_add_history (rl_line_buffer);
899 bash_add_history ("");
900 history_lines_this_session++;
902 command = savestring (edit_command);
905 metaval = rl_variable_value ("input-meta");
906 metaflag = RL_BOOLEAN_VARIABLE_VALUE (metaval);
908 /* Now, POSIX.1-2001 and SUSv3 say that the commands executed from the
909 temporary file should be placed into the history. We don't do that
911 if (rl_deprep_term_function)
912 (*rl_deprep_term_function) ();
913 save_parser_state (&ps);
914 r = parse_and_execute (command, (editing_mode == VI_EDITING_MODE) ? "v" : "C-xC-e", SEVAL_NOHIST);
915 restore_parser_state (&ps);
916 if (rl_prep_term_function)
917 (*rl_prep_term_function) (metaflag);
919 current_command_line_count = saved_command_line_count;
921 /* Now erase the contents of the current line and undo the effects of the
922 rl_accept_line() above. We don't even want to make the text we just
923 executed available for undoing. */
924 rl_line_buffer[0] = '\0'; /* XXX */
925 rl_point = rl_end = 0;
927 rl_readline_state = rrs;
929 rl_forced_update_display ();
934 #if defined (VI_MODE)
936 vi_edit_and_execute_command (count, c)
940 return (edit_and_execute_command (count, c, VI_EDITING_MODE, POSIX_VI_EDIT_COMMAND));
942 return (edit_and_execute_command (count, c, VI_EDITING_MODE, VI_EDIT_COMMAND));
947 emacs_edit_and_execute_command (count, c)
950 return (edit_and_execute_command (count, c, EMACS_EDITING_MODE, EMACS_EDIT_COMMAND));
955 posix_edit_macros (count, key)
959 char alias_name[3], *alias_value, *macro;
964 alias_name[2] = '\0';
966 alias_value = get_alias_value (alias_name);
967 if (alias_value && *alias_value)
969 macro = savestring (alias_value);
970 rl_push_macro_input (macro);
976 /* Bindable commands that move `shell-words': that is, sequences of
977 non-unquoted-metacharacters. */
979 #define WORDDELIM(c) (shellmeta(c) || shellblank(c))
982 bash_forward_shellword (count, key)
990 return (bash_backward_shellword (-count, key));
992 /* The tricky part of this is deciding whether or not the first character
993 we're on is an unquoted metacharacter. Not completely handled yet. */
994 /* XXX - need to test this stuff with backslash-escaped shell
995 metacharacters and unclosed single- and double-quoted strings. */
1008 /* Are we in a quoted string? If we are, move to the end of the quoted
1009 string and continue the outer loop. We only want quoted strings, not
1010 backslash-escaped characters, but char_is_quoted doesn't
1012 if (char_is_quoted (rl_line_buffer, p) && p > 0 && rl_line_buffer[p-1] != '\\')
1015 ADVANCE_CHAR (rl_line_buffer, slen, p);
1016 while (p < rl_end && char_is_quoted (rl_line_buffer, p));
1021 /* Rest of code assumes we are not in a quoted string. */
1022 /* Move forward until we hit a non-metacharacter. */
1023 while (p < rl_end && (c = rl_line_buffer[p]) && WORDDELIM (c))
1028 ADVANCE_CHAR (rl_line_buffer, slen, p);
1029 continue; /* straight back to loop, don't increment p */
1031 if (p < rl_end && rl_line_buffer[p])
1032 ADVANCE_CHAR (rl_line_buffer, slen, p);
1035 p = skip_to_delim (rl_line_buffer, ++p, "'", SD_NOJMP);
1038 p = skip_to_delim (rl_line_buffer, ++p, "\"", SD_NOJMP);
1046 if (rl_line_buffer[p] == 0 || p == rl_end)
1053 /* Now move forward until we hit a non-quoted metacharacter or EOL */
1054 while (p < rl_end && (c = rl_line_buffer[p]) && WORDDELIM (c) == 0)
1059 ADVANCE_CHAR (rl_line_buffer, slen, p);
1060 continue; /* straight back to loop, don't increment p */
1062 if (p < rl_end && rl_line_buffer[p])
1063 ADVANCE_CHAR (rl_line_buffer, slen, p);
1066 p = skip_to_delim (rl_line_buffer, ++p, "'", SD_NOJMP);
1069 p = skip_to_delim (rl_line_buffer, ++p, "\"", SD_NOJMP);
1077 if (p == rl_end || rl_line_buffer[p] == 0)
1091 bash_backward_shellword (count, key)
1099 return (bash_forward_shellword (-count, key));
1112 /* Move backward until we hit a non-metacharacter. */
1115 c = rl_line_buffer[p];
1116 if (WORDDELIM (c) && char_is_quoted (rl_line_buffer, p) == 0)
1117 BACKUP_CHAR (rl_line_buffer, slen, p);
1127 /* Now move backward until we hit a metacharacter or BOL. */
1130 c = rl_line_buffer[p];
1131 if (WORDDELIM (c) && char_is_quoted (rl_line_buffer, p) == 0)
1133 BACKUP_CHAR (rl_line_buffer, slen, p);
1144 bash_kill_shellword (count, key)
1150 return (bash_backward_kill_shellword (-count, key));
1153 bash_forward_shellword (count, key);
1156 rl_kill_text (p, rl_point);
1159 if (rl_editing_mode == 1) /* 1 == emacs_mode */
1166 bash_backward_kill_shellword (count, key)
1172 return (bash_kill_shellword (-count, key));
1175 bash_backward_shellword (count, key);
1178 rl_kill_text (p, rl_point);
1180 if (rl_editing_mode == 1) /* 1 == emacs_mode */
1187 /* **************************************************************** */
1189 /* How To Do Shell Completion */
1191 /* **************************************************************** */
1193 #define COMMAND_SEPARATORS ";|&{(`"
1200 register int this_char, prev_char;
1202 /* Handle the two character tokens `>&', `<&', and `>|'.
1203 We are not in a command position after one of these. */
1204 this_char = rl_line_buffer[ti];
1205 prev_char = rl_line_buffer[ti - 1];
1207 if ((this_char == '&' && (prev_char == '<' || prev_char == '>')) ||
1208 (this_char == '|' && prev_char == '>'))
1210 else if ((this_char == '{' && prev_char == '$') || /* } */
1211 (char_is_quoted (rl_line_buffer, ti)))
1216 #if defined (PROGRAMMABLE_COMPLETION)
1218 * XXX - because of the <= start test, and setting os = s+1, this can
1219 * potentially return os > start. This is probably not what we want to
1220 * happen, but fix later after 2.05a-release.
1223 find_cmd_start (start)
1229 while (((s = skip_to_delim (rl_line_buffer, os, COMMAND_SEPARATORS, SD_NOJMP|SD_NOSKIPCMD)) <= start) &&
1241 e = skip_to_delim (rl_line_buffer, end, COMMAND_SEPARATORS, SD_NOJMP);
1246 find_cmd_name (start)
1252 for (s = start; whitespace (rl_line_buffer[s]); s++)
1255 /* skip until a shell break character */
1256 e = skip_to_delim (rl_line_buffer, s, "()<>;&| \t\n", SD_NOJMP);
1258 name = substring (rl_line_buffer, s, e);
1264 prog_complete_return (text, matchnum)
1273 if (prog_complete_matches == 0 || prog_complete_matches[ind] == 0)
1274 return (char *)NULL;
1275 return (prog_complete_matches[ind++]);
1278 #endif /* PROGRAMMABLE_COMPLETION */
1280 /* Do some completion on TEXT. The indices of TEXT in RL_LINE_BUFFER are
1281 at START and END. Return an array of matches, or NULL if none. */
1283 attempt_shell_completion (text, start, end)
1287 int in_command_position, ti, saveti, qc, dflags;
1288 char **matches, *command_separator_chars;
1290 command_separator_chars = COMMAND_SEPARATORS;
1291 matches = (char **)NULL;
1292 rl_ignore_some_completions_function = filename_completion_ignore;
1294 rl_filename_quote_characters = default_filename_quote_characters;
1295 set_directory_hook ();
1297 /* Determine if this could be a command word. It is if it appears at
1298 the start of the line (ignoring preceding whitespace), or if it
1299 appears after a character that separates commands. It cannot be a
1300 command word if we aren't at the top-level prompt. */
1304 while ((ti > -1) && (whitespace (rl_line_buffer[ti])))
1308 /* If this is an open quote, maybe we're trying to complete a quoted
1310 if (ti >= 0 && (rl_line_buffer[ti] == '"' || rl_line_buffer[ti] == '\''))
1312 qc = rl_line_buffer[ti];
1314 while (ti > -1 && (whitespace (rl_line_buffer[ti])))
1319 in_command_position = 0;
1322 /* Only do command completion at the start of a line when we
1323 are prompting at the top level. */
1324 if (current_prompt_string == ps1_prompt)
1325 in_command_position++;
1327 else if (member (rl_line_buffer[ti], command_separator_chars))
1329 in_command_position++;
1331 if (check_redir (ti) == 1)
1332 in_command_position = 0;
1336 /* This still could be in command position. It is possible
1337 that all of the previous words on the line are variable
1341 /* Check that we haven't incorrectly flagged a closed command substitution
1342 as indicating we're in a command position. */
1343 if (in_command_position && ti >= 0 && rl_line_buffer[ti] == '`' &&
1344 *text != '`' && unclosed_pair (rl_line_buffer, end, "`") == 0)
1345 in_command_position = 0;
1347 /* Special handling for command substitution. If *TEXT is a backquote,
1348 it can be the start or end of an old-style command substitution, or
1349 unmatched. If it's unmatched, both calls to unclosed_pair will
1350 succeed. Don't bother if readline found a single quote and we are
1351 completing on the substring. */
1352 if (*text == '`' && rl_completion_quote_character != '\'' &&
1353 (in_command_position || (unclosed_pair (rl_line_buffer, start, "`") &&
1354 unclosed_pair (rl_line_buffer, end, "`"))))
1355 matches = rl_completion_matches (text, command_subst_completion_function);
1357 #if defined (PROGRAMMABLE_COMPLETION)
1358 /* Attempt programmable completion. */
1359 if (matches == 0 && (in_command_position == 0 || text[0] == '\0') &&
1360 prog_completion_enabled && (progcomp_size () > 0) &&
1361 current_prompt_string == ps1_prompt)
1366 /* XXX - don't free the members */
1367 if (prog_complete_matches)
1368 free (prog_complete_matches);
1369 prog_complete_matches = (char **)NULL;
1371 s = find_cmd_start (start);
1372 e = find_cmd_end (end);
1373 n = find_cmd_name (s);
1374 if (e == 0 && e == s && text[0] == '\0')
1375 prog_complete_matches = programmable_completions ("_EmptycmD_", text, s, e, &foundcs);
1376 else if (e > s && assignment (n, 0) == 0)
1377 prog_complete_matches = programmable_completions (n, text, s, e, &foundcs);
1381 /* XXX - if we found a COMPSPEC for the command, just return whatever
1382 the programmable completion code returns, and disable the default
1383 filename completion that readline will do unless the COPT_DEFAULT
1384 option has been set with the `-o default' option to complete or
1388 pcomp_set_readline_variables (foundcs, 1);
1389 /* Turn what the programmable completion code returns into what
1390 readline wants. I should have made compute_lcd_of_matches
1392 matches = rl_completion_matches (text, prog_complete_return);
1393 if ((foundcs & COPT_DEFAULT) == 0)
1394 rl_attempted_completion_over = 1; /* no default */
1395 if (matches || ((foundcs & COPT_BASHDEFAULT) == 0))
1404 if (in_command_position)
1405 dflags |= DEFCOMP_CMDPOS;
1406 matches = bash_default_completion (text, start, end, qc, dflags);
1413 bash_default_completion (text, start, end, qc, compflags)
1415 int start, end, qc, compflags;
1419 matches = (char **)NULL;
1421 /* New posix-style command substitution or variable name? */
1422 if (!matches && *text == '$')
1424 if (qc != '\'' && text[1] == '(') /* ) */
1425 matches = rl_completion_matches (text, command_subst_completion_function);
1427 matches = rl_completion_matches (text, variable_completion_function);
1430 /* If the word starts in `~', and there is no slash in the word, then
1431 try completing this word as a username. */
1432 if (matches == 0 && *text == '~' && mbschr (text, '/') == 0)
1433 matches = rl_completion_matches (text, rl_username_completion_function);
1435 /* Another one. Why not? If the word starts in '@', then look through
1436 the world of known hostnames for completion first. */
1437 if (matches == 0 && perform_hostname_completion && *text == '@')
1438 matches = rl_completion_matches (text, hostname_completion_function);
1440 /* And last, (but not least) if this word is in a command position, then
1441 complete over possible command names, including aliases, functions,
1442 and command names. */
1443 if (matches == 0 && (compflags & DEFCOMP_CMDPOS))
1445 /* If END == START and text[0] == 0, we are trying to complete an empty
1447 if (no_empty_command_completion && end == start && text[0] == '\0')
1449 matches = (char **)NULL;
1450 rl_ignore_some_completions_function = bash_ignore_everything;
1454 #define CMD_IS_DIR(x) (absolute_pathname(x) == 0 && absolute_program(x) == 0 && *(x) != '~' && test_for_directory (x))
1457 matches = rl_completion_matches (text, command_word_completion_function);
1459 /* If we are attempting command completion and nothing matches, we
1460 do not want readline to perform filename completion for us. We
1461 still want to be able to complete partial pathnames, so set the
1462 completion ignore function to something which will remove
1463 filenames and leave directories in the match list. */
1464 if (matches == (char **)NULL)
1465 rl_ignore_some_completions_function = bash_ignore_filenames;
1466 else if (matches[1] == 0 && CMD_IS_DIR(matches[0]) && dot_in_path == 0)
1467 /* If we found a single match, without looking in the current
1468 directory (because it's not in $PATH), but the found name is
1469 also a command in the current directory, suppress appending any
1470 terminating character, since it's ambiguous. */
1472 rl_completion_suppress_append = 1;
1473 rl_filename_completion_desired = 0;
1475 else if (matches[0] && matches[1] && STREQ (matches[0], matches[1]) && CMD_IS_DIR (matches[0]))
1476 /* There are multiple instances of the same match (duplicate
1477 completions haven't yet been removed). In this case, all of
1478 the matches will be the same, and the duplicate removal code
1479 will distill them all down to one. We turn on
1480 rl_completion_suppress_append for the same reason as above.
1481 Remember: we only care if there's eventually a single unique
1482 completion. If there are multiple completions this won't
1483 make a difference and the problem won't occur. */
1485 rl_completion_suppress_append = 1;
1486 rl_filename_completion_desired = 0;
1491 /* This could be a globbing pattern, so try to expand it using pathname
1493 if (!matches && glob_pattern_p (text))
1495 matches = rl_completion_matches (text, glob_complete_word);
1496 /* A glob expression that matches more than one filename is problematic.
1497 If we match more than one filename, punt. */
1498 if (matches && matches[1] && rl_completion_type == TAB)
1500 strvec_dispose (matches);
1501 matches = (char **)0;
1508 /* This is the function to call when the word to complete is in a position
1509 where a command word can be found. It grovels $PATH, looking for commands
1510 that match. It also scans aliases, function names, and the shell_builtin
1513 command_word_completion_function (hint_text, state)
1514 const char *hint_text;
1517 static char *hint = (char *)NULL;
1518 static char *path = (char *)NULL;
1519 static char *val = (char *)NULL;
1520 static char *filename_hint = (char *)NULL;
1521 static char *dequoted_hint = (char *)NULL;
1522 static char *directory_part = (char *)NULL;
1523 static char **glob_matches = (char **)NULL;
1524 static int path_index, hint_len, dequoted_len, istate, igncase;
1525 static int mapping_over, local_index, searching_path, hint_is_dir;
1526 static int old_glob_ignore_case, globpat;
1527 static SHELL_VAR **varlist = (SHELL_VAR **)NULL;
1529 static alias_t **alias_list = (alias_t **)NULL;
1533 /* We have to map over the possibilities for command words. If we have
1534 no state, then make one just for that purpose. */
1537 if (dequoted_hint && dequoted_hint != hint)
1538 free (dequoted_hint);
1542 mapping_over = searching_path = 0;
1543 hint_is_dir = CMD_IS_DIR (hint_text);
1546 temp = rl_variable_value ("completion-ignore-case");
1547 igncase = RL_BOOLEAN_VARIABLE_VALUE (temp);
1551 free (glob_matches);
1552 glob_matches = (char **)NULL;
1555 globpat = glob_pattern_p (hint_text);
1557 /* If this is an absolute program name, do not check it against
1558 aliases, reserved words, functions or builtins. We must check
1559 whether or not it is unique, and, if so, whether that filename
1561 if (globpat || absolute_program (hint_text))
1563 /* Perform tilde expansion on what's passed, so we don't end up
1564 passing filenames with tildes directly to stat(). */
1565 if (*hint_text == '~')
1567 hint = bash_tilde_expand (hint_text, 0);
1568 directory_part = savestring (hint_text);
1569 temp = strchr (directory_part, '/');
1574 free (directory_part);
1575 directory_part = (char *)NULL;
1579 hint = savestring (hint_text);
1581 dequoted_hint = hint;
1582 /* If readline's completer found a quote character somewhere, but
1583 didn't set the quote character, there must have been a quote
1584 character embedded in the filename. It can't be at the start of
1585 the filename, so we need to dequote the filename before we look
1586 in the file system for it. */
1587 if (rl_completion_found_quote && rl_completion_quote_character == 0)
1589 dequoted_hint = bash_dequote_filename (hint, 0);
1591 hint = dequoted_hint;
1593 dequoted_len = hint_len = strlen (hint);
1596 free (filename_hint);
1598 filename_hint = savestring (hint);
1609 if (dircomplete_expand && dot_or_dotdot (filename_hint))
1611 dircomplete_expand = 0;
1612 set_directory_hook ();
1613 dircomplete_expand = 1;
1620 dequoted_hint = hint = savestring (hint_text);
1621 dequoted_len = hint_len = strlen (hint);
1623 if (rl_completion_found_quote && rl_completion_quote_character == 0)
1625 dequoted_hint = bash_dequote_filename (hint, 0);
1626 dequoted_len = strlen (dequoted_hint);
1629 path = get_string_value ("PATH");
1630 path_index = dot_in_path = 0;
1632 /* Initialize the variables for each type of command word. */
1638 varlist = all_visible_functions ();
1644 alias_list = all_aliases ();
1648 /* mapping_over says what we are currently hacking. Note that every case
1649 in this list must fall through when there are no more possibilities. */
1651 switch (mapping_over)
1653 case 0: /* Aliases come first. */
1655 while (alias_list && alias_list[local_index])
1657 register char *alias;
1659 alias = alias_list[local_index++]->name;
1661 if (STREQN (alias, hint, hint_len))
1662 return (savestring (alias));
1668 case 1: /* Then shell reserved words. */
1670 while (word_token_alist[local_index].word)
1672 register char *reserved_word;
1674 reserved_word = word_token_alist[local_index++].word;
1676 if (STREQN (reserved_word, hint, hint_len))
1677 return (savestring (reserved_word));
1683 case 2: /* Then function names. */
1684 while (varlist && varlist[local_index])
1686 register char *varname;
1688 varname = varlist[local_index++]->name;
1690 if (STREQN (varname, hint, hint_len))
1691 return (savestring (varname));
1696 case 3: /* Then shell builtins. */
1697 for (; local_index < num_shell_builtins; local_index++)
1699 /* Ignore it if it doesn't have a function pointer or if it
1700 is not currently enabled. */
1701 if (!shell_builtins[local_index].function ||
1702 (shell_builtins[local_index].flags & BUILTIN_ENABLED) == 0)
1705 if (STREQN (shell_builtins[local_index].name, hint, hint_len))
1707 int i = local_index++;
1709 return (savestring (shell_builtins[i].name));
1717 /* Limited support for completing command words with globbing chars. Only
1718 a single match (multiple matches that end up reducing the number of
1719 characters in the common prefix are bad) will ever be returned on
1720 regular completion. */
1725 glob_ignore_case = igncase;
1726 glob_matches = shell_glob_filename (hint);
1727 glob_ignore_case = old_glob_ignore_case;
1729 if (GLOB_FAILED (glob_matches) || glob_matches == 0)
1731 glob_matches = (char **)NULL;
1732 return ((char *)NULL);
1737 if (glob_matches[1] && rl_completion_type == TAB) /* multiple matches are bad */
1738 return ((char *)NULL);
1741 while (val = glob_matches[local_index++])
1743 if (executable_or_directory (val))
1745 if (*hint_text == '~')
1747 temp = restore_tilde (val, directory_part);
1756 glob_ignore_case = old_glob_ignore_case;
1757 return ((char *)NULL);
1760 /* If the text passed is a directory in the current directory, return it
1761 as a possible match. Executables in directories in the current
1762 directory can be specified using relative pathnames and successfully
1763 executed even when `.' is not in $PATH. */
1766 hint_is_dir = 0; /* only return the hint text once */
1767 return (savestring (hint_text));
1770 /* Repeatedly call filename_completion_function while we have
1771 members of PATH left. Question: should we stat each file?
1772 Answer: we call executable_file () on each file. */
1775 istate = (val != (char *)NULL);
1781 /* Get the next directory from the path. If there is none, then we
1783 if (path == 0 || path[path_index] == 0 ||
1784 (current_path = extract_colon_unit (path, &path_index)) == 0)
1785 return ((char *)NULL);
1788 if (*current_path == 0)
1790 free (current_path);
1791 current_path = savestring (".");
1794 if (*current_path == '~')
1798 t = bash_tilde_expand (current_path, 0);
1799 free (current_path);
1803 if (current_path[0] == '.' && current_path[1] == '\0')
1807 free (filename_hint);
1809 filename_hint = sh_makepath (current_path, hint, 0);
1810 free (current_path); /* XXX */
1814 val = rl_filename_completion_function (filename_hint, istate);
1815 if (mapping_over == 4 && dircomplete_expand)
1816 set_directory_hook ();
1822 /* If the hint text is an absolute program, then don't bother
1823 searching through PATH. */
1824 if (absolute_program (hint))
1825 return ((char *)NULL);
1831 int match, freetemp;
1833 if (absolute_program (hint))
1836 match = strncmp (val, hint, hint_len) == 0;
1838 match = strncasecmp (val, hint, hint_len) == 0;
1840 /* If we performed tilde expansion, restore the original
1842 if (*hint_text == '~')
1843 temp = restore_tilde (val, directory_part);
1845 temp = savestring (val);
1850 temp = strrchr (val, '/');
1856 freetemp = match = strncmp (temp, hint, hint_len) == 0;
1858 freetemp = match = strncasecmp (temp, hint, hint_len) == 0;
1860 temp = savestring (temp);
1863 freetemp = match = 0;
1867 /* If we have found a match, and it is an executable file or a
1868 directory name, return it. */
1869 if (match && executable_or_directory (val))
1871 /* If we have found a match, and it is an executable file, return it.
1872 We don't return directory names when searching $PATH, since the
1873 bash execution code won't find executables in directories which
1874 appear in directories in $PATH when they're specified using
1875 relative pathnames. */
1876 if (match && (searching_path ? executable_file (val) : executable_or_directory (val)))
1880 val = ""; /* So it won't be NULL. */
1893 /* Completion inside an unterminated command substitution. */
1895 command_subst_completion_function (text, state)
1899 static char **matches = (char **)NULL;
1900 static const char *orig_start;
1901 static char *filename_text = (char *)NULL;
1902 static int cmd_index, start_len;
1908 free (filename_text);
1912 else if (*text == '$' && text[1] == '(') /* ) */
1914 /* If the text was quoted, suppress any quote character that the
1915 readline completion code would insert. */
1916 rl_completion_suppress_quote = 1;
1917 start_len = text - orig_start;
1918 filename_text = savestring (text);
1923 * At this point we can entertain the idea of re-parsing
1924 * `filename_text' into a (possibly incomplete) command name and
1925 * arguments, and doing completion based on that. This is
1926 * currently very rudimentary, but it is a small improvement.
1928 for (value = filename_text + strlen (filename_text) - 1; value > filename_text; value--)
1929 if (whitespace (*value) || member (*value, COMMAND_SEPARATORS))
1931 if (value <= filename_text)
1932 matches = rl_completion_matches (filename_text, command_word_completion_function);
1936 start_len += value - filename_text;
1937 if (whitespace (value[-1]))
1938 matches = rl_completion_matches (value, rl_filename_completion_function);
1940 matches = rl_completion_matches (value, command_word_completion_function);
1943 /* If there is more than one match, rl_completion_matches has already
1944 put the lcd in matches[0]. Skip over it. */
1945 cmd_index = matches && matches[0] && matches[1];
1947 /* If there's a single match and it's a directory, set the append char
1948 to the expected `/'. Otherwise, don't append anything. */
1949 if (matches && matches[0] && matches[1] == 0 && test_for_directory (matches[0]))
1950 rl_completion_append_character = '/';
1952 rl_completion_suppress_append = 1;
1955 if (!matches || !matches[cmd_index])
1957 rl_filename_quoting_desired = 0; /* disable quoting */
1958 return ((char *)NULL);
1962 value = (char *)xmalloc (1 + start_len + strlen (matches[cmd_index]));
1965 value[0] = *orig_start;
1967 strncpy (value, orig_start, start_len);
1969 strcpy (value + start_len, matches[cmd_index]);
1976 /* Okay, now we write the entry_function for variable completion. */
1978 variable_completion_function (text, state)
1982 static char **varlist = (char **)NULL;
1983 static int varlist_index;
1984 static char *varname = (char *)NULL;
1986 static int first_char, first_char_loc;
1994 first_char = text[0];
1996 if (first_char == '$')
1999 if (text[first_char_loc] == '{')
2002 varname = savestring (text + first_char_loc);
2004 namelen = strlen (varname);
2006 strvec_dispose (varlist);
2008 varlist = all_variables_matching_prefix (varname);
2012 if (!varlist || !varlist[varlist_index])
2014 return ((char *)NULL);
2020 value = (char *)xmalloc (4 + strlen (varlist[varlist_index]));
2024 value[0] = first_char;
2025 if (first_char_loc == 2)
2029 strcpy (value + first_char_loc, varlist[varlist_index]);
2030 if (first_char_loc == 2)
2031 strcat (value, "}");
2038 /* How about a completion function for hostnames? */
2040 hostname_completion_function (text, state)
2044 static char **list = (char **)NULL;
2045 static int list_index = 0;
2046 static int first_char, first_char_loc;
2048 /* If we don't have any state, make some. */
2053 list = (char **)NULL;
2058 if (first_char == '@')
2061 list = hostnames_matching ((char *)text+first_char_loc);
2065 if (list && list[list_index])
2069 t = (char *)xmalloc (2 + strlen (list[list_index]));
2071 strcpy (t + first_char_loc, list[list_index]);
2076 return ((char *)NULL);
2080 * A completion function for service names from /etc/services (or wherever).
2083 bash_servicename_completion_function (text, state)
2087 #if defined (__WIN32__) || defined (__OPENNT) || !defined (HAVE_GETSERVENT)
2088 return ((char *)NULL);
2090 static char *sname = (char *)NULL;
2091 static struct servent *srvent;
2092 static int snamelen, firstc;
2094 char **alist, *aentry;
2102 sname = savestring (text);
2103 snamelen = strlen (sname);
2107 while (srvent = getservent ())
2110 if (snamelen == 0 || (STREQN (sname, srvent->s_name, snamelen)))
2112 /* Not primary, check aliases */
2113 for (alist = srvent->s_aliases; *alist; alist++)
2116 if (STREQN (sname, aentry, snamelen))
2130 return ((char *)NULL);
2133 value = afound ? savestring (aentry) : savestring (srvent->s_name);
2139 * A completion function for group names from /etc/group (or wherever).
2142 bash_groupname_completion_function (text, state)
2146 #if defined (__WIN32__) || defined (__OPENNT) || !defined (HAVE_GRP_H)
2147 return ((char *)NULL);
2149 static char *gname = (char *)NULL;
2150 static struct group *grent;
2151 static int gnamelen;
2157 gname = savestring (text);
2158 gnamelen = strlen (gname);
2163 while (grent = getgrent ())
2165 if (gnamelen == 0 || (STREQN (gname, grent->gr_name, gnamelen)))
2172 return ((char *)NULL);
2175 value = savestring (grent->gr_name);
2180 /* Functions to perform history and alias expansions on the current line. */
2182 #if defined (BANG_HISTORY)
2183 /* Perform history expansion on the current line. If no history expansion
2184 is done, pre_process_line() returns what it was passed, so we need to
2185 allocate a new line here. */
2187 history_expand_line_internal (line)
2193 old_verify = hist_verify;
2195 new_line = pre_process_line (line, 0, 0);
2196 hist_verify = old_verify;
2198 return (new_line == line) ? savestring (line) : new_line;
2202 /* There was an error in expansion. Let the preprocessor print
2205 cleanup_expansion_error ()
2208 #if defined (BANG_HISTORY)
2211 old_verify = hist_verify;
2215 fprintf (rl_outstream, "\r\n");
2216 to_free = pre_process_line (rl_line_buffer, 1, 0);
2217 #if defined (BANG_HISTORY)
2218 hist_verify = old_verify;
2220 if (to_free != rl_line_buffer)
2222 putc ('\r', rl_outstream);
2223 rl_forced_update_display ();
2226 /* If NEW_LINE differs from what is in the readline line buffer, add an
2227 undo record to get from the readline line buffer contents to the new
2228 line and make NEW_LINE the current readline line. */
2230 maybe_make_readline_line (new_line)
2233 if (strcmp (new_line, rl_line_buffer) != 0)
2237 rl_add_undo (UNDO_BEGIN, 0, 0, 0);
2238 rl_delete_text (0, rl_point);
2239 rl_point = rl_end = rl_mark = 0;
2240 rl_insert_text (new_line);
2241 rl_add_undo (UNDO_END, 0, 0, 0);
2245 /* Make NEW_LINE be the current readline line. This frees NEW_LINE. */
2247 set_up_new_line (new_line)
2250 int old_point, at_end;
2252 old_point = rl_point;
2253 at_end = rl_point == rl_end;
2255 /* If the line was history and alias expanded, then make that
2256 be one thing to undo. */
2257 maybe_make_readline_line (new_line);
2260 /* Place rl_point where we think it should go. */
2263 else if (old_point < rl_end)
2265 rl_point = old_point;
2266 if (!whitespace (rl_line_buffer[rl_point]))
2267 rl_forward_word (1, 0);
2272 /* Expand aliases in the current readline line. */
2274 alias_expand_line (count, ignore)
2279 new_line = alias_expand (rl_line_buffer);
2283 set_up_new_line (new_line);
2288 cleanup_expansion_error ();
2294 #if defined (BANG_HISTORY)
2295 /* History expand the line. */
2297 history_expand_line (count, ignore)
2302 new_line = history_expand_line_internal (rl_line_buffer);
2306 set_up_new_line (new_line);
2311 cleanup_expansion_error ();
2316 /* Expand history substitutions in the current line and then insert a
2317 space (hopefully close to where we were before). */
2319 tcsh_magic_space (count, ignore)
2322 int dist_from_end, old_point;
2324 old_point = rl_point;
2325 dist_from_end = rl_end - rl_point;
2326 if (history_expand_line (count, ignore) == 0)
2328 /* Try a simple heuristic from Stephen Gildea <gildea@intouchsys.com>.
2329 This works if all expansions were before rl_point or if no expansions
2331 rl_point = (old_point == 0) ? old_point : rl_end - dist_from_end;
2338 #endif /* BANG_HISTORY */
2340 /* History and alias expand the line. */
2342 history_and_alias_expand_line (count, ignore)
2348 #if defined (BANG_HISTORY)
2349 new_line = history_expand_line_internal (rl_line_buffer);
2357 alias_line = alias_expand (new_line);
2359 new_line = alias_line;
2365 set_up_new_line (new_line);
2370 cleanup_expansion_error ();
2375 /* History and alias expand the line, then perform the shell word
2376 expansions by calling expand_string. This can't use set_up_new_line()
2377 because we want the variable expansions as a separate undo'able
2378 set of operations. */
2380 shell_expand_line (count, ignore)
2384 WORD_LIST *expanded_string;
2387 #if defined (BANG_HISTORY)
2388 new_line = history_expand_line_internal (rl_line_buffer);
2396 alias_line = alias_expand (new_line);
2398 new_line = alias_line;
2404 int old_point = rl_point;
2405 int at_end = rl_point == rl_end;
2407 /* If the line was history and alias expanded, then make that
2408 be one thing to undo. */
2409 maybe_make_readline_line (new_line);
2412 /* If there is variable expansion to perform, do that as a separate
2413 operation to be undone. */
2414 new_line = savestring (rl_line_buffer);
2415 expanded_string = expand_string (new_line, 0);
2417 if (expanded_string == 0)
2419 new_line = (char *)xmalloc (1);
2424 new_line = string_list (expanded_string);
2425 dispose_words (expanded_string);
2428 maybe_make_readline_line (new_line);
2431 /* Place rl_point where we think it should go. */
2434 else if (old_point < rl_end)
2436 rl_point = old_point;
2437 if (!whitespace (rl_line_buffer[rl_point]))
2438 rl_forward_word (1, 0);
2444 cleanup_expansion_error ();
2449 /* If FIGNORE is set, then don't match files with the given suffixes when
2450 completing filenames. If only one of the possibilities has an acceptable
2451 suffix, delete the others, else just return and let the completer
2452 signal an error. It is called by the completer when real
2453 completions are done on filenames by the completer's internal
2454 function, not for completion lists (M-?) and not on "other"
2455 completion types, such as hostnames or commands. */
2457 static struct ignorevar fignore =
2463 (sh_iv_item_func_t *) 0,
2467 _ignore_completion_names (names, name_func)
2469 sh_ignore_func_t *name_func;
2476 /* If there is only one completion, see if it is acceptable. If it is
2477 not, free it up. In any case, short-circuit and return. This is a
2478 special case because names[0] is not the prefix of the list of names
2479 if there is only one completion; it is the completion itself. */
2480 if (names[1] == (char *)0)
2483 if ((*name_func) (names[0]) == 0)
2486 names[0] = (char *)NULL;
2492 /* Allocate space for array to hold list of pointers to matching
2493 filenames. The pointers are copied back to NAMES when done. */
2494 for (nidx = 1; names[nidx]; nidx++)
2496 newnames = strvec_create (nidx + 1);
2498 if (force_fignore == 0)
2500 oldnames = strvec_create (nidx - 1);
2504 newnames[0] = names[0];
2505 for (idx = nidx = 1; names[idx]; idx++)
2507 if ((*name_func) (names[idx]))
2508 newnames[nidx++] = names[idx];
2509 else if (force_fignore == 0)
2510 oldnames[oidx++] = names[idx];
2515 newnames[nidx] = (char *)NULL;
2517 /* If none are acceptable then let the completer handle it. */
2523 names[0] = (char *)NULL;
2532 if (force_fignore == 0)
2535 free (oldnames[--oidx]);
2539 /* If only one is acceptable, copy it to names[0] and return. */
2543 names[0] = newnames[1];
2544 names[1] = (char *)NULL;
2549 /* Copy the acceptable names back to NAMES, set the new array end,
2551 for (nidx = 1; newnames[nidx]; nidx++)
2552 names[nidx] = newnames[nidx];
2553 names[nidx] = (char *)NULL;
2558 name_is_acceptable (name)
2564 for (nlen = strlen (name), p = fignore.ignores; p->val; p++)
2566 if (nlen > p->len && p->len > 0 && STREQ (p->val, &name[nlen - p->len]))
2575 ignore_dot_names (name)
2578 return (name[0] != '.');
2583 filename_completion_ignore (names)
2587 if (glob_dot_filenames == 0)
2588 _ignore_completion_names (names, ignore_dot_names);
2591 setup_ignore_patterns (&fignore);
2593 if (fignore.num_ignores == 0)
2596 _ignore_completion_names (names, name_is_acceptable);
2601 /* Return 1 if NAME is a directory. NAME undergoes tilde expansion. */
2603 test_for_directory (name)
2609 fn = bash_tilde_expand (name, 0);
2610 r = file_isdir (fn);
2616 /* Remove files from NAMES, leaving directories. */
2618 bash_ignore_filenames (names)
2621 _ignore_completion_names (names, test_for_directory);
2633 bash_ignore_everything (names)
2636 _ignore_completion_names (names, return_zero);
2640 /* Replace a tilde-prefix in VAL with a `~', assuming the user typed it. VAL
2641 is an expanded filename. DIRECTORY_PART is the tilde-prefix portion
2642 of the un-tilde-expanded version of VAL (what the user typed). */
2644 restore_tilde (val, directory_part)
2645 char *val, *directory_part;
2648 char *dh2, *expdir, *ret;
2652 /* We need to duplicate the expansions readline performs on the directory
2653 portion before passing it to our completion function. */
2654 dh2 = directory_part ? bash_dequote_filename (directory_part, 0) : 0;
2655 bash_directory_expansion (&dh2);
2658 expdir = bash_tilde_expand (directory_part, 0);
2659 xl = strlen (expdir);
2663 dh2 = unexpanded but dequoted tilde-prefix
2664 dl2 = length of tilde-prefix
2665 expdir = tilde-expanded tilde-prefix
2666 xl = length of expanded tilde-prefix
2667 l = length of remainder after tilde-prefix
2671 ret = (char *)xmalloc (dl2 + 2 + l);
2673 strcpy (ret + dl2, val + xl);
2679 /* Simulate the expansions that will be performed by
2680 rl_filename_completion_function. This must be called with the address of
2681 a pointer to malloc'd memory. */
2683 bash_directory_expansion (dirname)
2688 d = savestring (*dirname);
2690 if (rl_directory_rewrite_hook)
2691 (*rl_directory_rewrite_hook) (&d);
2692 else if (rl_directory_completion_hook && (*rl_directory_completion_hook) (&d))
2697 else if (rl_completion_found_quote)
2699 nd = bash_dequote_filename (d, rl_completion_quote_character);
2706 /* If necessary, rewrite directory entry */
2708 bash_filename_rewrite_hook (fname, fnlen)
2714 conv = fnx_fromfs (fname, fnlen);
2716 conv = savestring (conv);
2720 /* Functions to save and restore the appropriate directory hook */
2721 /* This is not static so the shopt code can call it */
2723 set_directory_hook ()
2725 if (dircomplete_expand)
2727 rl_directory_completion_hook = bash_directory_completion_hook;
2728 rl_directory_rewrite_hook = (rl_icppfunc_t *)0;
2732 rl_directory_rewrite_hook = bash_directory_completion_hook;
2733 rl_directory_completion_hook = (rl_icppfunc_t *)0;
2737 static rl_icppfunc_t *
2738 save_directory_hook ()
2742 if (dircomplete_expand)
2744 ret = rl_directory_completion_hook;
2745 rl_directory_completion_hook = (rl_icppfunc_t *)NULL;
2749 ret = rl_directory_rewrite_hook;
2750 rl_directory_rewrite_hook = (rl_icppfunc_t *)NULL;
2757 restore_directory_hook (hookf)
2758 rl_icppfunc_t *hookf;
2760 if (dircomplete_expand)
2761 rl_directory_completion_hook = hookf;
2763 rl_directory_rewrite_hook = hookf;
2766 /* Handle symbolic link references and other directory name
2767 expansions while hacking completion. This should return 1 if it modifies
2768 the DIRNAME argument, 0 otherwise. It should make sure not to modify
2769 DIRNAME if it returns 0. */
2771 bash_directory_completion_hook (dirname)
2774 char *local_dirname, *new_dirname, *t;
2775 int return_value, should_expand_dirname, nextch, closer;
2779 return_value = should_expand_dirname = nextch = closer = 0;
2780 local_dirname = *dirname;
2782 if (t = mbschr (local_dirname, '$'))
2784 should_expand_dirname = '$';
2786 /* Deliberately does not handle the deprecated $[...] arithmetic
2790 else if (nextch == '{')
2797 t = mbschr (local_dirname, '`');
2798 if (t && unclosed_pair (local_dirname, strlen (local_dirname), "`") == 0)
2799 should_expand_dirname = '`';
2802 #if defined (HAVE_LSTAT)
2803 if (should_expand_dirname && lstat (local_dirname, &sb) == 0)
2805 if (should_expand_dirname && stat (local_dirname, &sb) == 0)
2807 should_expand_dirname = 0;
2809 if (should_expand_dirname)
2811 new_dirname = savestring (local_dirname);
2812 wl = expand_prompt_string (new_dirname, 0, W_NOCOMSUB); /* does the right thing */
2815 *dirname = string_list (wl);
2816 /* Tell the completer to replace the directory name only if we
2817 actually expanded something. */
2818 return_value = STREQ (local_dirname, *dirname) == 0;
2819 free (local_dirname);
2822 local_dirname = *dirname;
2823 /* XXX - change rl_filename_quote_characters here based on
2824 should_expand_dirname/nextch/closer. This is the only place
2825 custom_filename_quote_characters is modified. */
2826 if (rl_filename_quote_characters && *rl_filename_quote_characters)
2829 i = strlen (default_filename_quote_characters);
2830 custom_filename_quote_characters = xrealloc (custom_filename_quote_characters, i+1);
2831 for (i = j = 0; c = default_filename_quote_characters[i]; i++)
2833 if (c == should_expand_dirname || c == nextch || c == closer)
2835 custom_filename_quote_characters[j++] = c;
2837 custom_filename_quote_characters[j] = '\0';
2838 rl_filename_quote_characters = custom_filename_quote_characters;
2844 free (local_dirname);
2845 *dirname = (char *)xmalloc (1);
2852 /* Dequote the filename even if we don't expand it. */
2853 new_dirname = bash_dequote_filename (local_dirname, rl_completion_quote_character);
2854 return_value = STREQ (local_dirname, new_dirname) == 0;
2855 free (local_dirname);
2856 local_dirname = *dirname = new_dirname;
2859 /* no_symbolic_links == 0 -> use (default) logical view of the file system.
2860 local_dirname[0] == '.' && local_dirname[1] == '/' means files in the
2861 current directory (./).
2862 local_dirname[0] == '.' && local_dirname[1] == 0 means relative pathnames
2863 in the current directory (e.g., lib/sh).
2864 XXX - should we do spelling correction on these? */
2866 /* This is test as it was in bash-4.2: skip relative pathnames in current
2867 directory. Change test to
2868 (local_dirname[0] != '.' || (local_dirname[1] && local_dirname[1] != '/'))
2869 if we want to skip paths beginning with ./ also. */
2870 if (no_symbolic_links == 0 && (local_dirname[0] != '.' || local_dirname[1]))
2872 char *temp1, *temp2;
2875 /* If we have a relative path
2876 (local_dirname[0] != '/' && local_dirname[0] != '.')
2877 that is canonical after appending it to the current directory, then
2880 strcmp (temp1, temp2) == 0
2881 after adding a slash to temp2 below. It should be safe to not
2884 t = get_working_directory ("symlink-hook");
2885 temp1 = make_absolute (local_dirname, t);
2887 temp2 = sh_canonpath (temp1, PATH_CHECKDOTDOT|PATH_CHECKEXISTS);
2889 /* Try spelling correction if initial canonicalization fails. */
2890 if (temp2 == 0 && dircomplete_spelling)
2892 temp2 = dirspell (temp1);
2897 temp2 = sh_canonpath (temp1, PATH_CHECKDOTDOT|PATH_CHECKEXISTS);
2898 return_value |= temp2 != 0;
2901 /* If we can't canonicalize, bail. */
2905 return return_value;
2907 len1 = strlen (temp1);
2908 if (temp1[len1 - 1] == '/')
2910 len2 = strlen (temp2);
2911 if (len2 > 2) /* don't append `/' to `/' or `//' */
2913 temp2 = (char *)xrealloc (temp2, len2 + 2);
2915 temp2[len2 + 1] = '\0';
2919 /* dircomplete_expand_relpath == 0 means we want to leave relative
2920 pathnames that are unchanged by canonicalization alone.
2921 *local_dirname != '/' && *local_dirname != '.' == relative pathname
2922 (consistent with general.c:absolute_pathname())
2923 temp1 == temp2 (after appending a slash to temp2) means the pathname
2924 is not changed by canonicalization as described above. */
2925 if (dircomplete_expand_relpath || ((local_dirname[0] != '/' && local_dirname[0] != '.') && STREQ (temp1, temp2) == 0))
2926 return_value |= STREQ (local_dirname, temp2) == 0;
2927 free (local_dirname);
2932 return (return_value);
2935 static char **history_completion_array = (char **)NULL;
2936 static int harry_size;
2937 static int harry_len;
2940 build_history_completion_array ()
2946 /* First, clear out the current dynamic history completion list. */
2949 strvec_dispose (history_completion_array);
2950 history_completion_array = (char **)NULL;
2955 /* Next, grovel each line of history, making each shell-sized token
2956 a separate entry in the history_completion_array. */
2957 hlist = history_list ();
2961 for (i = 0; hlist[i]; i++)
2963 for ( --i; i >= 0; i--)
2965 /* Separate each token, and place into an array. */
2966 tokens = history_tokenize (hlist[i]->line);
2968 for (j = 0; tokens && tokens[j]; j++)
2970 if (harry_len + 2 > harry_size)
2971 history_completion_array = strvec_resize (history_completion_array, harry_size += 10);
2973 history_completion_array[harry_len++] = tokens[j];
2974 history_completion_array[harry_len] = (char *)NULL;
2979 /* Sort the complete list of tokens. */
2980 if (dabbrev_expand_active == 0)
2981 qsort (history_completion_array, harry_len, sizeof (char *), (QSFUNC *)strvec_strcmp);
2986 history_completion_generator (hint_text, state)
2987 const char *hint_text;
2990 static int local_index, len;
2991 static const char *text;
2993 /* If this is the first call to the generator, then initialize the
2994 list of strings to complete over. */
2997 if (dabbrev_expand_active) /* This is kind of messy */
2998 rl_completion_suppress_append = 1;
3000 build_history_completion_array ();
3002 len = strlen (text);
3005 while (history_completion_array && history_completion_array[local_index])
3007 if (strncmp (text, history_completion_array[local_index++], len) == 0)
3008 return (savestring (history_completion_array[local_index - 1]));
3010 return ((char *)NULL);
3014 dynamic_complete_history (count, key)
3018 rl_compentry_func_t *orig_func;
3019 rl_completion_func_t *orig_attempt_func;
3020 rl_compignore_func_t *orig_ignore_func;
3022 orig_func = rl_completion_entry_function;
3023 orig_attempt_func = rl_attempted_completion_function;
3024 orig_ignore_func = rl_ignore_some_completions_function;
3026 rl_completion_entry_function = history_completion_generator;
3027 rl_attempted_completion_function = (rl_completion_func_t *)NULL;
3028 rl_ignore_some_completions_function = filename_completion_ignore;
3030 /* XXX - use rl_completion_mode here? */
3031 if (rl_last_func == dynamic_complete_history)
3032 r = rl_complete_internal ('?');
3034 r = rl_complete_internal (TAB);
3036 rl_completion_entry_function = orig_func;
3037 rl_attempted_completion_function = orig_attempt_func;
3038 rl_ignore_some_completions_function = orig_ignore_func;
3044 bash_dabbrev_expand (count, key)
3047 int r, orig_suppress, orig_sort;
3048 rl_compentry_func_t *orig_func;
3049 rl_completion_func_t *orig_attempt_func;
3050 rl_compignore_func_t *orig_ignore_func;
3052 orig_func = rl_menu_completion_entry_function;
3053 orig_attempt_func = rl_attempted_completion_function;
3054 orig_ignore_func = rl_ignore_some_completions_function;
3055 orig_suppress = rl_completion_suppress_append;
3056 orig_sort = rl_sort_completion_matches;
3058 rl_menu_completion_entry_function = history_completion_generator;
3059 rl_attempted_completion_function = (rl_completion_func_t *)NULL;
3060 rl_ignore_some_completions_function = filename_completion_ignore;
3061 rl_filename_completion_desired = 0;
3062 rl_completion_suppress_append = 1;
3063 rl_sort_completion_matches = 0;
3065 /* XXX - use rl_completion_mode here? */
3066 dabbrev_expand_active = 1;
3067 if (rl_last_func == bash_dabbrev_expand)
3068 rl_last_func = rl_menu_complete;
3069 r = rl_menu_complete (count, key);
3070 dabbrev_expand_active = 0;
3072 rl_last_func = bash_dabbrev_expand;
3073 rl_menu_completion_entry_function = orig_func;
3074 rl_attempted_completion_function = orig_attempt_func;
3075 rl_ignore_some_completions_function = orig_ignore_func;
3076 rl_completion_suppress_append = orig_suppress;
3077 rl_sort_completion_matches = orig_sort;
3082 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
3084 bash_complete_username (ignore, ignore2)
3085 int ignore, ignore2;
3087 return bash_complete_username_internal (rl_completion_mode (bash_complete_username));
3091 bash_possible_username_completions (ignore, ignore2)
3092 int ignore, ignore2;
3094 return bash_complete_username_internal ('?');
3098 bash_complete_username_internal (what_to_do)
3101 return bash_specific_completion (what_to_do, rl_username_completion_function);
3105 bash_complete_filename (ignore, ignore2)
3106 int ignore, ignore2;
3108 return bash_complete_filename_internal (rl_completion_mode (bash_complete_filename));
3112 bash_possible_filename_completions (ignore, ignore2)
3113 int ignore, ignore2;
3115 return bash_complete_filename_internal ('?');
3119 bash_complete_filename_internal (what_to_do)
3122 rl_compentry_func_t *orig_func;
3123 rl_completion_func_t *orig_attempt_func;
3124 rl_icppfunc_t *orig_dir_func;
3125 rl_compignore_func_t *orig_ignore_func;
3126 /*const*/ char *orig_rl_completer_word_break_characters;
3129 orig_func = rl_completion_entry_function;
3130 orig_attempt_func = rl_attempted_completion_function;
3131 orig_ignore_func = rl_ignore_some_completions_function;
3132 orig_rl_completer_word_break_characters = rl_completer_word_break_characters;
3134 orig_dir_func = save_directory_hook ();
3136 rl_completion_entry_function = rl_filename_completion_function;
3137 rl_attempted_completion_function = (rl_completion_func_t *)NULL;
3138 rl_ignore_some_completions_function = filename_completion_ignore;
3139 rl_completer_word_break_characters = " \t\n\"\'";
3141 r = rl_complete_internal (what_to_do);
3143 rl_completion_entry_function = orig_func;
3144 rl_attempted_completion_function = orig_attempt_func;
3145 rl_ignore_some_completions_function = orig_ignore_func;
3146 rl_completer_word_break_characters = orig_rl_completer_word_break_characters;
3148 restore_directory_hook (orig_dir_func);
3154 bash_complete_hostname (ignore, ignore2)
3155 int ignore, ignore2;
3157 return bash_complete_hostname_internal (rl_completion_mode (bash_complete_hostname));
3161 bash_possible_hostname_completions (ignore, ignore2)
3162 int ignore, ignore2;
3164 return bash_complete_hostname_internal ('?');
3168 bash_complete_variable (ignore, ignore2)
3169 int ignore, ignore2;
3171 return bash_complete_variable_internal (rl_completion_mode (bash_complete_variable));
3175 bash_possible_variable_completions (ignore, ignore2)
3176 int ignore, ignore2;
3178 return bash_complete_variable_internal ('?');
3182 bash_complete_command (ignore, ignore2)
3183 int ignore, ignore2;
3185 return bash_complete_command_internal (rl_completion_mode (bash_complete_command));
3189 bash_possible_command_completions (ignore, ignore2)
3190 int ignore, ignore2;
3192 return bash_complete_command_internal ('?');
3196 bash_complete_hostname_internal (what_to_do)
3199 return bash_specific_completion (what_to_do, hostname_completion_function);
3203 bash_complete_variable_internal (what_to_do)
3206 return bash_specific_completion (what_to_do, variable_completion_function);
3210 bash_complete_command_internal (what_to_do)
3213 return bash_specific_completion (what_to_do, command_word_completion_function);
3216 static char *globtext;
3217 static char *globorig;
3220 glob_complete_word (text, state)
3224 static char **matches = (char **)NULL;
3231 rl_filename_completion_desired = 1;
3233 if (globorig != globtext)
3237 ttext = bash_tilde_expand (text, 0);
3239 if (rl_explicit_arg)
3241 globorig = savestring (ttext);
3242 glen = strlen (ttext);
3243 globtext = (char *)xmalloc (glen + 2);
3244 strcpy (globtext, ttext);
3245 globtext[glen] = '*';
3246 globtext[glen+1] = '\0';
3249 globtext = globorig = savestring (ttext);
3254 matches = shell_glob_filename (globtext);
3255 if (GLOB_FAILED (matches))
3256 matches = (char **)NULL;
3260 ret = matches ? matches[ind] : (char *)NULL;
3266 bash_glob_completion_internal (what_to_do)
3269 return bash_specific_completion (what_to_do, glob_complete_word);
3272 /* A special quoting function so we don't end up quoting globbing characters
3273 in the word if there are no matches or multiple matches. */
3275 bash_glob_quote_filename (s, rtype, qcp)
3280 if (globorig && qcp && *qcp == '\0' && STREQ (s, globorig))
3281 return (savestring (s));
3283 return (bash_quote_filename (s, rtype, qcp));
3287 bash_glob_complete_word (count, key)
3291 rl_quote_func_t *orig_quoting_function;
3293 if (rl_editing_mode == EMACS_EDITING_MODE)
3294 rl_explicit_arg = 1; /* force `*' append */
3295 orig_quoting_function = rl_filename_quoting_function;
3296 rl_filename_quoting_function = bash_glob_quote_filename;
3298 r = bash_glob_completion_internal (rl_completion_mode (bash_glob_complete_word));
3300 rl_filename_quoting_function = orig_quoting_function;
3305 bash_glob_expand_word (count, key)
3308 return bash_glob_completion_internal ('*');
3312 bash_glob_list_expansions (count, key)
3315 return bash_glob_completion_internal ('?');
3319 bash_specific_completion (what_to_do, generator)
3321 rl_compentry_func_t *generator;
3323 rl_compentry_func_t *orig_func;
3324 rl_completion_func_t *orig_attempt_func;
3325 rl_compignore_func_t *orig_ignore_func;
3328 orig_func = rl_completion_entry_function;
3329 orig_attempt_func = rl_attempted_completion_function;
3330 orig_ignore_func = rl_ignore_some_completions_function;
3331 rl_completion_entry_function = generator;
3332 rl_attempted_completion_function = NULL;
3333 rl_ignore_some_completions_function = orig_ignore_func;
3335 r = rl_complete_internal (what_to_do);
3337 rl_completion_entry_function = orig_func;
3338 rl_attempted_completion_function = orig_attempt_func;
3339 rl_ignore_some_completions_function = orig_ignore_func;
3344 #endif /* SPECIFIC_COMPLETION_FUNCTIONS */
3346 #if defined (VI_MODE)
3347 /* Completion, from vi mode's point of view. This is a modified version of
3348 rl_vi_complete which uses the bash globbing code to implement what POSIX
3349 specifies, which is to append a `*' and attempt filename generation (which
3350 has the side effect of expanding any globbing characters in the word). */
3352 bash_vi_complete (count, key)
3355 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
3359 if ((rl_point < rl_end) && (!whitespace (rl_line_buffer[rl_point])))
3361 if (!whitespace (rl_line_buffer[rl_point + 1]))
3362 rl_vi_end_word (1, 'E');
3366 /* Find boundaries of current word, according to vi definition of a
3372 rl_vi_bWord (1, 'B');
3377 t = substring (rl_line_buffer, p, rl_point);
3380 if (t && glob_pattern_p (t) == 0)
3381 rl_explicit_arg = 1; /* XXX - force glob_complete_word to append `*' */
3384 if (key == '*') /* Expansion and replacement. */
3385 r = bash_glob_expand_word (count, key);
3386 else if (key == '=') /* List possible completions. */
3387 r = bash_glob_list_expansions (count, key);
3388 else if (key == '\\') /* Standard completion */
3389 r = bash_glob_complete_word (count, key);
3391 r = rl_complete (0, key);
3393 if (key == '*' || key == '\\')
3394 rl_vi_start_inserting (key, 1, 1);
3398 return rl_vi_complete (count, key);
3399 #endif /* !SPECIFIC_COMPLETION_FUNCTIONS */
3401 #endif /* VI_MODE */
3403 /* Filename quoting for completion. */
3404 /* A function to strip unquoted quote characters (single quotes, double
3405 quotes, and backslashes). It allows single quotes to appear
3406 within double quotes, and vice versa. It should be smarter. */
3408 bash_dequote_filename (text, quote_char)
3416 ret = (char *)xmalloc (l + 1);
3417 for (quoted = quote_char, p = text, r = ret; p && *p; p++)
3419 /* Allow backslash-escaped characters to pass through unscathed. */
3422 /* Backslashes are preserved within single quotes. */
3425 /* Backslashes are preserved within double quotes unless the
3426 character is one that is defined to be escaped */
3427 else if (quoted == '"' && ((sh_syntaxtab[p[1]] & CBSDQUOTE) == 0))
3432 return ret; /* XXX - was break; */
3436 if (quoted && *p == quoted)
3442 if (quoted == 0 && (*p == '\'' || *p == '"'))
3453 /* Quote characters that the readline completion code would treat as
3454 word break characters with backslashes. Pass backslash-quoted
3455 characters through without examination. */
3457 quote_word_break_chars (text)
3464 ret = (char *)xmalloc ((2 * l) + 1);
3465 for (s = text, r = ret; *s; s++)
3467 /* Pass backslash-quoted characters through, including the backslash. */
3476 /* OK, we have an unquoted character. Check its presence in
3477 rl_completer_word_break_characters. */
3478 if (mbschr (rl_completer_word_break_characters, *s))
3480 /* XXX -- check for standalone tildes here and backslash-quote them */
3481 if (s == text && *s == '~' && file_exists (text))
3489 /* Quote a filename using double quotes, single quotes, or backslashes
3490 depending on the value of completion_quoting_style. If we're
3491 completing using backslashes, we need to quote some additional
3492 characters (those that readline treats as word breaks), so we call
3493 quote_word_break_chars on the result. This returns newly-allocated
3496 bash_quote_filename (s, rtype, qcp)
3501 char *rtext, *mtext, *ret;
3504 rtext = (char *)NULL;
3506 /* If RTYPE == MULT_MATCH, it means that there is
3507 more than one match. In this case, we do not add
3508 the closing quote or attempt to perform tilde
3509 expansion. If RTYPE == SINGLE_MATCH, we try
3510 to perform tilde expansion, because single and double
3511 quotes inhibit tilde expansion by the shell. */
3513 cs = completion_quoting_style;
3514 /* Might need to modify the default completion style based on *qcp,
3515 since it's set to any user-provided opening quote. We also change
3516 to single-quoting if there is no user-provided opening quote and
3517 the word being completed contains newlines, since those are not
3518 quoted correctly using backslashes (a backslash-newline pair is
3519 special to the shell parser). */
3520 if (*qcp == '\0' && cs == COMPLETE_BSQUOTE && mbschr (s, '\n'))
3521 cs = COMPLETE_SQUOTE;
3522 else if (*qcp == '"')
3523 cs = COMPLETE_DQUOTE;
3524 else if (*qcp == '\'')
3525 cs = COMPLETE_SQUOTE;
3526 #if defined (BANG_HISTORY)
3527 else if (*qcp == '\0' && history_expansion && cs == COMPLETE_DQUOTE &&
3528 history_expansion_inhibited == 0 && mbschr (s, '!'))
3529 cs = COMPLETE_BSQUOTE;
3531 if (*qcp == '"' && history_expansion && cs == COMPLETE_DQUOTE &&
3532 history_expansion_inhibited == 0 && mbschr (s, '!'))
3534 cs = COMPLETE_BSQUOTE;
3539 /* Don't tilde-expand backslash-quoted filenames, since only single and
3540 double quotes inhibit tilde expansion. */
3542 if (mtext[0] == '~' && rtype == SINGLE_MATCH && cs != COMPLETE_BSQUOTE)
3543 mtext = bash_tilde_expand (s, 0);
3547 case COMPLETE_DQUOTE:
3548 rtext = sh_double_quote (mtext);
3550 case COMPLETE_SQUOTE:
3551 rtext = sh_single_quote (mtext);
3553 case COMPLETE_BSQUOTE:
3554 rtext = sh_backslash_quote (mtext);
3561 /* We may need to quote additional characters: those that readline treats
3562 as word breaks that are not quoted by backslash_quote. */
3563 if (rtext && cs == COMPLETE_BSQUOTE)
3565 mtext = quote_word_break_chars (rtext);
3570 /* Leave the opening quote intact. The readline completion code takes
3571 care of avoiding doubled opening quotes. */
3572 rlen = strlen (rtext);
3573 ret = (char *)xmalloc (rlen + 1);
3574 strcpy (ret, rtext);
3576 /* If there are multiple matches, cut off the closing quote. */
3577 if (rtype == MULT_MATCH && cs != COMPLETE_BSQUOTE)
3578 ret[rlen - 1] = '\0';
3583 /* Support for binding readline key sequences to Unix commands. */
3584 static Keymap cmd_xmap;
3592 x = putc (c, rl_outstream);
3597 bash_execute_unix_command (count, key)
3598 int count; /* ignored */
3601 Keymap ckmap; /* current keymap */
3602 Keymap xkmap; /* unix command executing keymap */
3605 sh_parser_state_t ps;
3606 char *cmd, *value, *l, *l1, *ce;
3608 char ibuf[INT_STRLEN_BOUND(int) + 1];
3610 /* First, we need to find the right command to execute. This is tricky,
3611 because we might have already indirected into another keymap. */
3612 ckmap = rl_get_keymap ();
3613 if (ckmap != rl_executing_keymap)
3615 /* bogus. we have to search. only handle one level of indirection. */
3616 for (i = 0; i < KEYMAP_SIZE; i++)
3618 if (ckmap[i].type == ISKMAP && (Keymap)ckmap[i].function == rl_executing_keymap)
3621 if (i < KEYMAP_SIZE)
3622 xkmap = (Keymap)cmd_xmap[i].function;
3626 internal_error (_("bash_execute_unix_command: cannot find keymap for command"));
3627 rl_forced_update_display ();
3634 cmd = (char *)xkmap[key].function;
3642 ce = rl_get_termcap ("ce");
3643 if (ce) /* clear current line */
3645 fprintf (rl_outstream, "\r");
3646 tputs (ce, 1, putx);
3647 fflush (rl_outstream);
3650 rl_crlf (); /* move to a new line */
3652 v = bind_variable ("READLINE_LINE", rl_line_buffer, 0);
3654 VSETATTR (v, att_exported);
3655 l = v ? value_cell (v) : 0;
3656 value = inttostr (rl_point, ibuf, sizeof (ibuf));
3657 v = bind_int_variable ("READLINE_POINT", value);
3659 VSETATTR (v, att_exported);
3660 array_needs_making = 1;
3662 save_parser_state (&ps);
3663 r = parse_and_execute (cmd, "bash_execute_unix_command", SEVAL_NOHIST|SEVAL_NOFREE);
3664 restore_parser_state (&ps);
3666 v = find_variable ("READLINE_LINE");
3667 l1 = v ? value_cell (v) : 0;
3669 maybe_make_readline_line (value_cell (v));
3670 v = find_variable ("READLINE_POINT");
3671 if (v && legal_number (value_cell (v), &mi))
3677 if (rl_point > rl_end)
3679 else if (rl_point < 0)
3684 unbind_variable ("READLINE_LINE");
3685 unbind_variable ("READLINE_POINT");
3686 array_needs_making = 1;
3688 /* and restore the readline buffer and display after command execution. */
3689 rl_forced_update_display ();
3694 init_unix_command_map ()
3696 cmd_xmap = rl_make_bare_keymap ();
3700 isolate_sequence (string, ind, need_dquote, startp)
3702 int ind, need_dquote, *startp;
3705 int c, passc, delim;
3707 for (i = ind; string[i] && whitespace (string[i]); i++)
3709 /* NEED_DQUOTE means that the first non-white character *must* be `"'. */
3710 if (need_dquote && string[i] != '"')
3712 builtin_error (_("%s: first non-whitespace character is not `\"'"), string);
3716 /* We can have delimited strings even if NEED_DQUOTE == 0, like the command
3717 string to bind the key sequence to. */
3718 delim = (string[i] == '"' || string[i] == '\'') ? string[i] : 0;
3721 *startp = delim ? ++i : i;
3723 for (passc = 0; c = string[i]; i++)
3739 if (delim && string[i] != delim)
3741 builtin_error (_("no closing `%c' in %s"), delim, string);
3749 bind_keyseq_to_unix_command (line)
3757 init_unix_command_map ();
3759 kmap = rl_get_keymap ();
3761 /* We duplicate some of the work done by rl_parse_and_bind here, but
3762 this code only has to handle `"keyseq": ["]command["]' and can
3763 generate an error for anything else. */
3764 i = isolate_sequence (line, 0, 1, &kstart);
3768 /* Create the key sequence string to pass to rl_generic_bind */
3769 kseq = substring (line, kstart, i);
3771 for ( ; line[i] && line[i] != ':'; i++)
3775 builtin_error (_("%s: missing colon separator"), line);
3779 i = isolate_sequence (line, i + 1, 0, &kstart);
3783 /* Create the value string containing the command to execute. */
3784 value = substring (line, kstart, i);
3786 /* Save the command to execute and the key sequence in the CMD_XMAP */
3787 rl_generic_bind (ISMACR, kseq, value, cmd_xmap);
3789 /* and bind the key sequence in the current keymap to a function that
3790 understands how to execute from CMD_XMAP */
3791 rl_bind_keyseq_in_map (kseq, bash_execute_unix_command, kmap);
3796 /* Used by the programmable completion code. Complete TEXT as a filename,
3797 but return only directories as matches. Dequotes the filename before
3798 attempting to find matches. */
3800 bash_directory_completion_matches (text)
3807 qc = rl_dispatching ? rl_completion_quote_character : 0;
3808 dfn = bash_dequote_filename ((char *)text, qc);
3809 m1 = rl_completion_matches (dfn, rl_filename_completion_function);
3812 if (m1 == 0 || m1[0] == 0)
3814 /* We don't bother recomputing the lcd of the matches, because it will just
3815 get thrown away by the programmable completion code and recomputed
3817 (void)bash_ignore_filenames (m1);
3822 bash_dequote_text (text)
3828 qc = (text[0] == '"' || text[0] == '\'') ? text[0] : 0;
3829 dtxt = bash_dequote_filename ((char *)text, qc);
3832 #endif /* READLINE */