1 /* bashline.c -- Bash's interface to the readline library. */
3 /* Copyright (C) 1987-2019 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)
43 #include "chartypes.h"
53 #include "execute_cmd.h"
60 #if defined (HAVE_MBSTR_H) && defined (HAVE_MBSCHR)
61 # include <mbstr.h> /* mbschr */
64 #include "builtins/common.h"
66 #include <readline/rlconf.h>
67 #include <readline/readline.h>
68 #include <readline/history.h>
69 #include <readline/rlmbutil.h>
71 #include <glob/glob.h>
77 #if defined (PROGRAMMABLE_COMPLETION)
78 # include "pcomplete.h"
81 /* These should agree with the defines for emacs_mode and vi_mode in
82 rldefs.h, even though that's not a public readline header file. */
83 #ifndef EMACS_EDITING_MODE
84 # define NO_EDITING_MODE -1
85 # define EMACS_EDITING_MODE 1
86 # define VI_EDITING_MODE 0
89 #define RL_BOOLEAN_VARIABLE_VALUE(s) ((s)[0] == 'o' && (s)[1] == 'n' && (s)[2] == '\0')
91 #if defined (BRACE_COMPLETION)
92 extern int bash_brace_completion
__P((int, int));
93 #endif /* BRACE_COMPLETION */
95 /* To avoid including curses.h/term.h/termcap.h and that whole mess. */
97 extern int tputs
__P((const char *string
, int nlines
, void (*outx
)(int)));
99 extern int tputs
__P((const char *string
, int nlines
, int (*outx
)(int)));
102 /* Forward declarations */
104 /* Functions bound to keys in Readline for Bash users. */
105 static int shell_expand_line
__P((int, int));
106 static int display_shell_version
__P((int, int));
107 static int operate_and_get_next
__P((int, int));
109 static int bash_ignore_filenames
__P((char **));
110 static int bash_ignore_everything
__P((char **));
111 static int bash_progcomp_ignore_filenames
__P((char **));
113 #if defined (BANG_HISTORY)
114 static char *history_expand_line_internal
__P((char *));
115 static int history_expand_line
__P((int, int));
116 static int tcsh_magic_space
__P((int, int));
117 #endif /* BANG_HISTORY */
119 static int alias_expand_line
__P((int, int));
121 #if defined (BANG_HISTORY) && defined (ALIAS)
122 static int history_and_alias_expand_line
__P((int, int));
125 static int bash_forward_shellword
__P((int, int));
126 static int bash_backward_shellword
__P((int, int));
127 static int bash_kill_shellword
__P((int, int));
128 static int bash_backward_kill_shellword
__P((int, int));
130 /* Helper functions for Readline. */
131 static char *restore_tilde
__P((char *, char *));
132 static char *maybe_restore_tilde
__P((char *, char *));
134 static char *bash_filename_rewrite_hook
__P((char *, int));
136 static void bash_directory_expansion
__P((char **));
137 static int bash_filename_stat_hook
__P((char **));
138 static int bash_command_name_stat_hook
__P((char **));
139 static int bash_directory_completion_hook
__P((char **));
140 static int filename_completion_ignore
__P((char **));
141 static int bash_push_line
__P((void));
143 static int executable_completion
__P((const char *, int));
145 static rl_icppfunc_t
*save_directory_hook
__P((void));
146 static void restore_directory_hook
__P((rl_icppfunc_t
));
148 static int directory_exists
__P((const char *, int));
150 static void cleanup_expansion_error
__P((void));
151 static void maybe_make_readline_line
__P((char *));
152 static void set_up_new_line
__P((char *));
154 static int check_redir
__P((int));
155 static char **attempt_shell_completion
__P((const char *, int, int));
156 static char *variable_completion_function
__P((const char *, int));
157 static char *hostname_completion_function
__P((const char *, int));
158 static char *command_subst_completion_function
__P((const char *, int));
160 static void build_history_completion_array
__P((void));
161 static char *history_completion_generator
__P((const char *, int));
162 static int dynamic_complete_history
__P((int, int));
163 static int bash_dabbrev_expand
__P((int, int));
165 static void initialize_hostname_list
__P((void));
166 static void add_host_name
__P((char *));
167 static void snarf_hosts_from_file
__P((char *));
168 static char **hostnames_matching
__P((char *));
170 static void _ignore_completion_names
__P((char **, sh_ignore_func_t
*));
171 static int name_is_acceptable
__P((const char *));
172 static int test_for_directory
__P((const char *));
173 static int test_for_canon_directory
__P((const char *));
174 static int return_zero
__P((const char *));
176 static char *bash_dequote_filename
__P((char *, int));
177 static char *quote_word_break_chars
__P((char *));
178 static void set_filename_bstab
__P((const char *));
179 static char *bash_quote_filename
__P((char *, int, char *));
182 static void putx
__P((int));
184 static int putx
__P((int));
186 static int bash_execute_unix_command
__P((int, int));
187 static void init_unix_command_map
__P((void));
188 static int isolate_sequence
__P((char *, int, int, int *));
190 static int set_saved_history
__P((void));
193 static int posix_edit_macros
__P((int, int));
196 static int bash_event_hook
__P((void));
198 #if defined (PROGRAMMABLE_COMPLETION)
199 static int find_cmd_start
__P((int));
200 static int find_cmd_end
__P((int));
201 static char *find_cmd_name
__P((int, int *, int *));
202 static char *prog_complete_return
__P((const char *, int));
204 static char **prog_complete_matches
;
207 extern int no_symbolic_links
;
208 extern STRING_INT_ALIST word_token_alist
[];
210 /* SPECIFIC_COMPLETION_FUNCTIONS specifies that we have individual
211 completion functions which indicate what type of completion should be
212 done (at or before point) that can be bound to key sequences with
213 the readline library. */
214 #define SPECIFIC_COMPLETION_FUNCTIONS
216 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
217 static int bash_specific_completion
__P((int, rl_compentry_func_t
*));
219 static int bash_complete_filename_internal
__P((int));
220 static int bash_complete_username_internal
__P((int));
221 static int bash_complete_hostname_internal
__P((int));
222 static int bash_complete_variable_internal
__P((int));
223 static int bash_complete_command_internal
__P((int));
225 static int bash_complete_filename
__P((int, int));
226 static int bash_possible_filename_completions
__P((int, int));
227 static int bash_complete_username
__P((int, int));
228 static int bash_possible_username_completions
__P((int, int));
229 static int bash_complete_hostname
__P((int, int));
230 static int bash_possible_hostname_completions
__P((int, int));
231 static int bash_complete_variable
__P((int, int));
232 static int bash_possible_variable_completions
__P((int, int));
233 static int bash_complete_command
__P((int, int));
234 static int bash_possible_command_completions
__P((int, int));
236 static int completion_glob_pattern
__P((char *));
237 static char *glob_complete_word
__P((const char *, int));
238 static int bash_glob_completion_internal
__P((int));
239 static int bash_glob_complete_word
__P((int, int));
240 static int bash_glob_expand_word
__P((int, int));
241 static int bash_glob_list_expansions
__P((int, int));
243 #endif /* SPECIFIC_COMPLETION_FUNCTIONS */
245 static int edit_and_execute_command
__P((int, int, int, char *));
246 #if defined (VI_MODE)
247 static int vi_edit_and_execute_command
__P((int, int));
248 static int bash_vi_complete
__P((int, int));
250 static int emacs_edit_and_execute_command
__P((int, int));
252 /* Non-zero once initalize_readline () has been called. */
253 int bash_readline_initialized
= 0;
255 /* If non-zero, we do hostname completion, breaking words at `@' and
256 trying to complete the stuff after the `@' from our own internal
258 int perform_hostname_completion
= 1;
260 /* If non-zero, we don't do command completion on an empty line. */
261 int no_empty_command_completion
;
263 /* Set FORCE_FIGNORE if you want to honor FIGNORE even if it ignores the
264 only possible matches. Set to 0 if you want to match filenames if they
265 are the only possible matches, even if FIGNORE says to. */
266 int force_fignore
= 1;
268 /* Perform spelling correction on directory names during word completion */
269 int dircomplete_spelling
= 0;
271 /* Expand directory names during word/filename completion. */
272 #if DIRCOMPLETE_EXPAND_DEFAULT
273 int dircomplete_expand
= 1;
274 int dircomplete_expand_relpath
= 1;
276 int dircomplete_expand
= 0;
277 int dircomplete_expand_relpath
= 0;
280 /* When non-zero, perform `normal' shell quoting on completed filenames
281 even when the completed name contains a directory name with a shell
282 variable referene, so dollar signs in a filename get quoted appropriately.
283 Set to zero to remove dollar sign (and braces or parens as needed) from
284 the set of characters that will be quoted. */
285 int complete_fullquote
= 1;
287 static char *bash_completer_word_break_characters
= " \t\n\"'@><=;|&(:";
288 static char *bash_nohostname_word_break_characters
= " \t\n\"'><=;|&(:";
291 static const char *default_filename_quote_characters
= " \t\n\\\"'@<>=;|&()#$`?*[!:{~"; /*}*/
292 static char *custom_filename_quote_characters
= 0;
293 static char filename_bstab
[256];
295 static rl_hook_func_t
*old_rl_startup_hook
= (rl_hook_func_t
*)NULL
;
297 static int dot_in_path
= 0;
299 /* Set to non-zero when dabbrev-expand is running */
300 static int dabbrev_expand_active
= 0;
302 /* What kind of quoting is performed by bash_quote_filename:
303 COMPLETE_DQUOTE = double-quoting the filename
304 COMPLETE_SQUOTE = single_quoting the filename
305 COMPLETE_BSQUOTE = backslash-quoting special chars in the filename
307 #define COMPLETE_DQUOTE 1
308 #define COMPLETE_SQUOTE 2
309 #define COMPLETE_BSQUOTE 3
310 static int completion_quoting_style
= COMPLETE_BSQUOTE
;
312 /* Flag values for the final argument to bash_default_completion */
313 #define DEFCOMP_CMDPOS 1
315 static rl_command_func_t
*vi_tab_binding
= rl_complete
;
317 /* Change the readline VI-mode keymaps into or out of Posix.2 compliance.
318 Called when the shell is put into or out of `posix' mode. */
320 posix_readline_initialize (on_or_off
)
323 static char kseq
[2] = { CTRL ('I'), 0 }; /* TAB */
326 rl_variable_bind ("comment-begin", "#");
327 #if defined (VI_MODE)
330 vi_tab_binding
= rl_function_of_keyseq (kseq
, vi_insertion_keymap
, (int *)NULL
);
331 rl_bind_key_in_map (CTRL ('I'), rl_insert
, vi_insertion_keymap
);
335 if (rl_function_of_keyseq (kseq
, vi_insertion_keymap
, (int *)NULL
) == rl_insert
)
336 rl_bind_key_in_map (CTRL ('I'), vi_tab_binding
, vi_insertion_keymap
);
342 reset_completer_word_break_chars ()
344 rl_completer_word_break_characters
= perform_hostname_completion
? savestring (bash_completer_word_break_characters
) : savestring (bash_nohostname_word_break_characters
);
347 /* When this function returns, rl_completer_word_break_characters points to
348 dynamically allocated memory. */
350 enable_hostname_completion (on_or_off
)
354 char *at
, *nv
, *nval
;
356 old_value
= perform_hostname_completion
;
360 perform_hostname_completion
= 1;
361 rl_special_prefixes
= "$@";
365 perform_hostname_completion
= 0;
366 rl_special_prefixes
= "$";
369 /* Now we need to figure out how to appropriately modify and assign
370 rl_completer_word_break_characters depending on whether we want
371 hostname completion on or off. */
373 /* If this is the first time this has been called
374 (bash_readline_initialized == 0), use the sames values as before, but
375 allocate new memory for rl_completer_word_break_characters. */
377 if (bash_readline_initialized
== 0 &&
378 (rl_completer_word_break_characters
== 0 ||
379 rl_completer_word_break_characters
== rl_basic_word_break_characters
))
382 rl_completer_word_break_characters
= savestring (bash_completer_word_break_characters
);
384 rl_completer_word_break_characters
= savestring (bash_nohostname_word_break_characters
);
388 /* See if we have anything to do. */
389 at
= strchr (rl_completer_word_break_characters
, '@');
390 if ((at
== 0 && on_or_off
== 0) || (at
!= 0 && on_or_off
!= 0))
393 /* We have something to do. Do it. */
394 nval
= (char *)xmalloc (strlen (rl_completer_word_break_characters
) + 1 + on_or_off
);
398 /* Turn it off -- just remove `@' from word break chars. We want
399 to remove all occurrences of `@' from the char list, so we loop
400 rather than just copy the rest of the list over AT. */
401 for (nv
= nval
, at
= rl_completer_word_break_characters
; *at
; )
411 strcpy (nval
+ 1, rl_completer_word_break_characters
);
414 free (rl_completer_word_break_characters
);
415 rl_completer_word_break_characters
= nval
;
421 /* Called once from parse.y if we are going to use readline. */
423 initialize_readline ()
425 rl_command_func_t
*func
;
428 if (bash_readline_initialized
)
431 rl_terminal_name
= get_string_value ("TERM");
433 rl_outstream
= stderr
;
435 /* Allow conditional parsing of the ~/.inputrc file. */
436 rl_readline_name
= "Bash";
438 /* Add bindable names before calling rl_initialize so they may be
439 referenced in the various inputrc files. */
440 rl_add_defun ("shell-expand-line", shell_expand_line
, -1);
442 rl_add_defun ("history-expand-line", history_expand_line
, -1);
443 rl_add_defun ("magic-space", tcsh_magic_space
, -1);
446 rl_add_defun ("shell-forward-word", bash_forward_shellword
, -1);
447 rl_add_defun ("shell-backward-word", bash_backward_shellword
, -1);
448 rl_add_defun ("shell-kill-word", bash_kill_shellword
, -1);
449 rl_add_defun ("shell-backward-kill-word", bash_backward_kill_shellword
, -1);
452 rl_add_defun ("alias-expand-line", alias_expand_line
, -1);
454 rl_add_defun ("history-and-alias-expand-line", history_and_alias_expand_line
, -1);
458 /* Backwards compatibility. */
459 rl_add_defun ("insert-last-argument", rl_yank_last_arg
, -1);
461 rl_add_defun ("operate-and-get-next", operate_and_get_next
, -1);
462 rl_add_defun ("display-shell-version", display_shell_version
, -1);
463 rl_add_defun ("edit-and-execute-command", emacs_edit_and_execute_command
, -1);
465 #if defined (BRACE_COMPLETION)
466 rl_add_defun ("complete-into-braces", bash_brace_completion
, -1);
469 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
470 rl_add_defun ("complete-filename", bash_complete_filename
, -1);
471 rl_add_defun ("possible-filename-completions", bash_possible_filename_completions
, -1);
472 rl_add_defun ("complete-username", bash_complete_username
, -1);
473 rl_add_defun ("possible-username-completions", bash_possible_username_completions
, -1);
474 rl_add_defun ("complete-hostname", bash_complete_hostname
, -1);
475 rl_add_defun ("possible-hostname-completions", bash_possible_hostname_completions
, -1);
476 rl_add_defun ("complete-variable", bash_complete_variable
, -1);
477 rl_add_defun ("possible-variable-completions", bash_possible_variable_completions
, -1);
478 rl_add_defun ("complete-command", bash_complete_command
, -1);
479 rl_add_defun ("possible-command-completions", bash_possible_command_completions
, -1);
480 rl_add_defun ("glob-complete-word", bash_glob_complete_word
, -1);
481 rl_add_defun ("glob-expand-word", bash_glob_expand_word
, -1);
482 rl_add_defun ("glob-list-expansions", bash_glob_list_expansions
, -1);
485 rl_add_defun ("dynamic-complete-history", dynamic_complete_history
, -1);
486 rl_add_defun ("dabbrev-expand", bash_dabbrev_expand
, -1);
488 /* Bind defaults before binding our custom shell keybindings. */
489 if (RL_ISSTATE(RL_STATE_INITIALIZED
) == 0)
492 /* Bind up our special shell functions. */
493 rl_bind_key_if_unbound_in_map (CTRL('E'), shell_expand_line
, emacs_meta_keymap
);
496 rl_bind_key_if_unbound_in_map ('^', history_expand_line
, emacs_meta_keymap
);
499 rl_bind_key_if_unbound_in_map (CTRL ('O'), operate_and_get_next
, emacs_standard_keymap
);
500 rl_bind_key_if_unbound_in_map (CTRL ('V'), display_shell_version
, emacs_ctlx_keymap
);
502 /* In Bash, the user can switch editing modes with "set -o [vi emacs]",
503 so it is not necessary to allow C-M-j for context switching. Turn
504 off this occasionally confusing behaviour. */
507 func
= rl_function_of_keyseq (kseq
, emacs_meta_keymap
, (int *)NULL
);
508 if (func
== rl_vi_editing_mode
)
509 rl_unbind_key_in_map (CTRL('J'), emacs_meta_keymap
);
511 func
= rl_function_of_keyseq (kseq
, emacs_meta_keymap
, (int *)NULL
);
512 if (func
== rl_vi_editing_mode
)
513 rl_unbind_key_in_map (CTRL('M'), emacs_meta_keymap
);
514 #if defined (VI_MODE)
516 func
= rl_function_of_keyseq (kseq
, vi_movement_keymap
, (int *)NULL
);
517 if (func
== rl_emacs_editing_mode
)
518 rl_unbind_key_in_map (CTRL('E'), vi_movement_keymap
);
521 #if defined (BRACE_COMPLETION)
522 rl_bind_key_if_unbound_in_map ('{', bash_brace_completion
, emacs_meta_keymap
); /*}*/
523 #endif /* BRACE_COMPLETION */
525 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
526 rl_bind_key_if_unbound_in_map ('/', bash_complete_filename
, emacs_meta_keymap
);
527 rl_bind_key_if_unbound_in_map ('/', bash_possible_filename_completions
, emacs_ctlx_keymap
);
529 /* Have to jump through hoops here because there is a default binding for
530 M-~ (rl_tilde_expand) */
533 func
= rl_function_of_keyseq (kseq
, emacs_meta_keymap
, (int *)NULL
);
534 if (func
== 0 || func
== rl_tilde_expand
)
535 rl_bind_keyseq_in_map (kseq
, bash_complete_username
, emacs_meta_keymap
);
537 rl_bind_key_if_unbound_in_map ('~', bash_possible_username_completions
, emacs_ctlx_keymap
);
539 rl_bind_key_if_unbound_in_map ('@', bash_complete_hostname
, emacs_meta_keymap
);
540 rl_bind_key_if_unbound_in_map ('@', bash_possible_hostname_completions
, emacs_ctlx_keymap
);
542 rl_bind_key_if_unbound_in_map ('$', bash_complete_variable
, emacs_meta_keymap
);
543 rl_bind_key_if_unbound_in_map ('$', bash_possible_variable_completions
, emacs_ctlx_keymap
);
545 rl_bind_key_if_unbound_in_map ('!', bash_complete_command
, emacs_meta_keymap
);
546 rl_bind_key_if_unbound_in_map ('!', bash_possible_command_completions
, emacs_ctlx_keymap
);
548 rl_bind_key_if_unbound_in_map ('g', bash_glob_complete_word
, emacs_meta_keymap
);
549 rl_bind_key_if_unbound_in_map ('*', bash_glob_expand_word
, emacs_ctlx_keymap
);
550 rl_bind_key_if_unbound_in_map ('g', bash_glob_list_expansions
, emacs_ctlx_keymap
);
552 #endif /* SPECIFIC_COMPLETION_FUNCTIONS */
556 func
= rl_function_of_keyseq (kseq
, emacs_meta_keymap
, (int *)NULL
);
557 if (func
== 0 || func
== rl_tab_insert
)
558 rl_bind_key_in_map (TAB
, dynamic_complete_history
, emacs_meta_keymap
);
560 /* Tell the completer that we want a crack first. */
561 rl_attempted_completion_function
= attempt_shell_completion
;
563 /* Tell the completer that we might want to follow symbolic links or
564 do other expansion on directory names. */
565 set_directory_hook ();
567 rl_filename_rewrite_hook
= bash_filename_rewrite_hook
;
569 rl_filename_stat_hook
= bash_filename_stat_hook
;
571 /* Tell the filename completer we want a chance to ignore some names. */
572 rl_ignore_some_completions_function
= filename_completion_ignore
;
574 /* Bind C-xC-e to invoke emacs and run result as commands. */
575 rl_bind_key_if_unbound_in_map (CTRL ('E'), emacs_edit_and_execute_command
, emacs_ctlx_keymap
);
576 #if defined (VI_MODE)
577 rl_bind_key_if_unbound_in_map ('v', vi_edit_and_execute_command
, vi_movement_keymap
);
579 rl_bind_key_if_unbound_in_map ('@', posix_edit_macros
, vi_movement_keymap
);
582 rl_bind_key_in_map ('\\', bash_vi_complete
, vi_movement_keymap
);
583 rl_bind_key_in_map ('*', bash_vi_complete
, vi_movement_keymap
);
584 rl_bind_key_in_map ('=', bash_vi_complete
, vi_movement_keymap
);
587 rl_completer_quote_characters
= "'\"";
589 /* This sets rl_completer_word_break_characters and rl_special_prefixes
590 to the appropriate values, depending on whether or not hostname
591 completion is enabled. */
592 enable_hostname_completion (perform_hostname_completion
);
594 /* characters that need to be quoted when appearing in filenames. */
595 rl_filename_quote_characters
= default_filename_quote_characters
;
596 set_filename_bstab (rl_filename_quote_characters
);
598 rl_filename_quoting_function
= bash_quote_filename
;
599 rl_filename_dequoting_function
= bash_dequote_filename
;
600 rl_char_is_quoted_p
= char_is_quoted
;
603 /* This is superfluous and makes it impossible to use tab completion in
604 vi mode even when explicitly binding it in ~/.inputrc. sv_strict_posix()
605 should already have called posix_readline_initialize() when
606 posixly_correct was set. */
608 posix_readline_initialize (1);
611 bash_readline_initialized
= 1;
615 bashline_reinitialize ()
617 bash_readline_initialized
= 0;
621 bashline_set_event_hook ()
623 rl_signal_event_hook
= bash_event_hook
;
627 bashline_reset_event_hook ()
629 rl_signal_event_hook
= 0;
632 /* On Sun systems at least, rl_attempted_completion_function can end up
633 getting set to NULL, and rl_completion_entry_function set to do command
634 word completion if Bash is interrupted while trying to complete a command
635 word. This just resets all the completion functions to the right thing.
636 It's called from throw_to_top_level(). */
641 rl_attempted_completion_function
= attempt_shell_completion
;
642 rl_completion_entry_function
= NULL
;
643 rl_ignore_some_completions_function
= filename_completion_ignore
;
644 rl_filename_quote_characters
= default_filename_quote_characters
;
645 set_filename_bstab (rl_filename_quote_characters
);
647 set_directory_hook ();
648 rl_filename_stat_hook
= bash_filename_stat_hook
;
650 bashline_reset_event_hook ();
652 rl_sort_completion_matches
= 1;
655 /* Contains the line to push into readline. */
656 static char *push_to_readline
= (char *)NULL
;
658 /* Push the contents of push_to_readline into the
663 if (push_to_readline
)
665 rl_insert_text (push_to_readline
);
666 free (push_to_readline
);
667 push_to_readline
= (char *)NULL
;
668 rl_startup_hook
= old_rl_startup_hook
;
673 /* Call this to set the initial text for the next line to read
679 FREE (push_to_readline
);
681 push_to_readline
= savestring (line
);
682 old_rl_startup_hook
= rl_startup_hook
;
683 rl_startup_hook
= bash_push_line
;
689 display_shell_version (count
, c
)
693 show_shell_version (0);
694 putc ('\r', rl_outstream
);
695 fflush (rl_outstream
);
701 /* **************************************************************** */
705 /* **************************************************************** */
707 /* If the user requests hostname completion, then simply build a list
708 of hosts, and complete from that forever more, or at least until
709 HOSTFILE is unset. */
711 /* THIS SHOULD BE A STRINGLIST. */
712 /* The kept list of hostnames. */
713 static char **hostname_list
= (char **)NULL
;
715 /* The physical size of the above list. */
716 static int hostname_list_size
;
718 /* The number of hostnames in the above list. */
719 static int hostname_list_length
;
721 /* Whether or not HOSTNAME_LIST has been initialized. */
722 int hostname_list_initialized
= 0;
724 /* Initialize the hostname completion table. */
726 initialize_hostname_list ()
730 temp
= get_string_value ("HOSTFILE");
732 temp
= get_string_value ("hostname_completion_file");
734 temp
= DEFAULT_HOSTS_FILE
;
736 snarf_hosts_from_file (temp
);
739 hostname_list_initialized
++;
742 /* Add NAME to the list of hosts. */
747 if (hostname_list_length
+ 2 > hostname_list_size
)
749 hostname_list_size
= (hostname_list_size
+ 32) - (hostname_list_size
% 32);
750 hostname_list
= strvec_resize (hostname_list
, hostname_list_size
);
753 hostname_list
[hostname_list_length
++] = savestring (name
);
754 hostname_list
[hostname_list_length
] = (char *)NULL
;
757 #define cr_whitespace(c) ((c) == '\r' || (c) == '\n' || whitespace(c))
760 snarf_hosts_from_file (filename
)
764 char *temp
, buffer
[256], name
[256];
765 register int i
, start
;
767 file
= fopen (filename
, "r");
771 while (temp
= fgets (buffer
, 255, file
))
773 /* Skip to first character. */
774 for (i
= 0; buffer
[i
] && cr_whitespace (buffer
[i
]); i
++)
777 /* If comment or blank line, ignore. */
778 if (buffer
[i
] == '\0' || buffer
[i
] == '#')
781 /* If `preprocessor' directive, do the include. */
782 if (strncmp (buffer
+ i
, "$include ", 9) == 0)
786 /* Find start of filename. */
787 for (incfile
= buffer
+ i
+ 9; *incfile
&& whitespace (*incfile
); incfile
++)
790 /* Find end of filename. */
791 for (t
= incfile
; *t
&& cr_whitespace (*t
) == 0; t
++)
796 snarf_hosts_from_file (incfile
);
800 /* Skip internet address if present. */
801 if (DIGIT (buffer
[i
]))
802 for (; buffer
[i
] && cr_whitespace (buffer
[i
]) == 0; i
++);
804 /* Gobble up names. Each name is separated with whitespace. */
807 for (; cr_whitespace (buffer
[i
]); i
++)
809 if (buffer
[i
] == '\0' || buffer
[i
] == '#')
812 /* Isolate the current word. */
813 for (start
= i
; buffer
[i
] && cr_whitespace (buffer
[i
]) == 0; i
++)
817 strncpy (name
, buffer
+ start
, i
- start
);
818 name
[i
- start
] = '\0';
819 add_host_name (name
);
825 /* Return the hostname list. */
829 if (hostname_list_initialized
== 0)
830 initialize_hostname_list ();
831 return (hostname_list
);
835 clear_hostname_list ()
839 if (hostname_list_initialized
== 0)
841 for (i
= 0; i
< hostname_list_length
; i
++)
842 free (hostname_list
[i
]);
843 hostname_list_length
= hostname_list_initialized
= 0;
846 /* Return a NULL terminated list of hostnames which begin with TEXT.
847 Initialize the hostname list the first time if necessary.
848 The array is malloc ()'ed, but not the individual strings. */
850 hostnames_matching (text
)
853 register int i
, len
, nmatch
, rsize
;
856 if (hostname_list_initialized
== 0)
857 initialize_hostname_list ();
859 if (hostname_list_initialized
== 0)
860 return ((char **)NULL
);
862 /* Special case. If TEXT consists of nothing, then the whole list is
866 result
= strvec_create (1 + hostname_list_length
);
867 for (i
= 0; i
< hostname_list_length
; i
++)
868 result
[i
] = hostname_list
[i
];
869 result
[i
] = (char *)NULL
;
873 /* Scan until found, or failure. */
875 result
= (char **)NULL
;
876 for (i
= nmatch
= rsize
= 0; i
< hostname_list_length
; i
++)
878 if (STREQN (text
, hostname_list
[i
], len
) == 0)
881 /* OK, it matches. Add it to the list. */
882 if (nmatch
>= (rsize
- 1))
884 rsize
= (rsize
+ 16) - (rsize
% 16);
885 result
= strvec_resize (result
, rsize
);
888 result
[nmatch
++] = hostname_list
[i
];
891 result
[nmatch
] = (char *)NULL
;
895 /* The equivalent of the Korn shell C-o operate-and-get-next-history-line
897 static int saved_history_line_to_use
= -1;
898 static int last_saved_history_line
= -1;
900 #define HISTORY_FULL() (history_is_stifled () && history_length >= history_max_entries)
905 /* XXX - compensate for assumption that history was `shuffled' if it was
907 if (HISTORY_FULL () &&
908 hist_last_line_added
== 0 &&
909 saved_history_line_to_use
< history_length
- 1)
910 saved_history_line_to_use
++;
912 if (saved_history_line_to_use
>= 0)
914 rl_get_previous_history (history_length
- saved_history_line_to_use
, 0);
915 last_saved_history_line
= saved_history_line_to_use
;
917 saved_history_line_to_use
= -1;
918 rl_startup_hook
= old_rl_startup_hook
;
923 operate_and_get_next (count
, c
)
928 /* Accept the current line. */
931 /* Find the current line, and find the next line to use. */
932 where
= rl_explicit_arg
? count
: where_history ();
934 if (HISTORY_FULL () || (where
>= history_length
- 1) || rl_explicit_arg
)
935 saved_history_line_to_use
= where
;
937 saved_history_line_to_use
= where
+ 1;
939 old_rl_startup_hook
= rl_startup_hook
;
940 rl_startup_hook
= set_saved_history
;
945 /* This vi mode command causes VI_EDIT_COMMAND to be run on the current
946 command being entered (if no explicit argument is given), otherwise on
947 a command from the history file. */
949 #define VI_EDIT_COMMAND "fc -e \"${VISUAL:-${EDITOR:-vi}}\""
950 #define EMACS_EDIT_COMMAND "fc -e \"${VISUAL:-${EDITOR:-emacs}}\""
951 #define POSIX_VI_EDIT_COMMAND "fc -e vi"
954 edit_and_execute_command (count
, c
, editing_mode
, edit_command
)
955 int count
, c
, editing_mode
;
958 char *command
, *metaval
;
959 int r
, rrs
, metaflag
;
960 sh_parser_state_t ps
;
962 rrs
= rl_readline_state
;
963 saved_command_line_count
= current_command_line_count
;
965 /* Accept the current line. */
970 command
= (char *)xmalloc (strlen (edit_command
) + 8);
971 sprintf (command
, "%s %d", edit_command
, count
);
975 /* Take the command we were just editing, add it to the history file,
976 then call fc to operate on it. We have to add a dummy command to
977 the end of the history because fc ignores the last command (assumes
978 it's supposed to deal with the command before the `fc'). */
979 /* This breaks down when using command-oriented history and are not
980 finished with the command, so we should not ignore the last command */
982 current_command_line_count
++; /* for rl_newline above */
983 bash_add_history (rl_line_buffer
);
984 current_command_line_count
= 0; /* for dummy history entry */
985 bash_add_history ("");
986 history_lines_this_session
++;
988 command
= savestring (edit_command
);
991 metaval
= rl_variable_value ("input-meta");
992 metaflag
= RL_BOOLEAN_VARIABLE_VALUE (metaval
);
994 if (rl_deprep_term_function
)
995 (*rl_deprep_term_function
) ();
996 save_parser_state (&ps
);
997 r
= parse_and_execute (command
, (editing_mode
== VI_EDITING_MODE
) ? "v" : "C-xC-e", SEVAL_NOHIST
);
998 restore_parser_state (&ps
);
999 if (rl_prep_term_function
)
1000 (*rl_prep_term_function
) (metaflag
);
1002 current_command_line_count
= saved_command_line_count
;
1004 /* Now erase the contents of the current line and undo the effects of the
1005 rl_accept_line() above. We don't even want to make the text we just
1006 executed available for undoing. */
1007 rl_line_buffer
[0] = '\0'; /* XXX */
1008 rl_point
= rl_end
= 0;
1010 rl_readline_state
= rrs
;
1012 #if defined (VI_MODE)
1013 if (editing_mode
== VI_EDITING_MODE
)
1014 rl_vi_insertion_mode (1, c
);
1017 rl_forced_update_display ();
1022 #if defined (VI_MODE)
1024 vi_edit_and_execute_command (count
, c
)
1027 if (posixly_correct
)
1028 return (edit_and_execute_command (count
, c
, VI_EDITING_MODE
, POSIX_VI_EDIT_COMMAND
));
1030 return (edit_and_execute_command (count
, c
, VI_EDITING_MODE
, VI_EDIT_COMMAND
));
1032 #endif /* VI_MODE */
1035 emacs_edit_and_execute_command (count
, c
)
1038 return (edit_and_execute_command (count
, c
, EMACS_EDITING_MODE
, EMACS_EDIT_COMMAND
));
1043 posix_edit_macros (count
, key
)
1047 char alias_name
[3], *alias_value
, *macro
;
1050 alias_name
[0] = '_';
1052 alias_name
[2] = '\0';
1054 alias_value
= get_alias_value (alias_name
);
1055 if (alias_value
&& *alias_value
)
1057 macro
= savestring (alias_value
);
1058 rl_push_macro_input (macro
);
1064 /* Bindable commands that move `shell-words': that is, sequences of
1065 non-unquoted-metacharacters. */
1067 #define WORDDELIM(c) (shellmeta(c) || shellblank(c))
1070 bash_forward_shellword (count
, key
)
1078 return (bash_backward_shellword (-count
, key
));
1080 /* The tricky part of this is deciding whether or not the first character
1081 we're on is an unquoted metacharacter. Not completely handled yet. */
1082 /* XXX - need to test this stuff with backslash-escaped shell
1083 metacharacters and unclosed single- and double-quoted strings. */
1096 /* Are we in a quoted string? If we are, move to the end of the quoted
1097 string and continue the outer loop. We only want quoted strings, not
1098 backslash-escaped characters, but char_is_quoted doesn't
1100 if (char_is_quoted (rl_line_buffer
, p
) && p
> 0 && rl_line_buffer
[p
-1] != '\\')
1103 ADVANCE_CHAR (rl_line_buffer
, slen
, p
);
1104 while (p
< rl_end
&& char_is_quoted (rl_line_buffer
, p
));
1109 /* Rest of code assumes we are not in a quoted string. */
1110 /* Move forward until we hit a non-metacharacter. */
1111 while (p
< rl_end
&& (c
= rl_line_buffer
[p
]) && WORDDELIM (c
))
1116 ADVANCE_CHAR (rl_line_buffer
, slen
, p
);
1117 continue; /* straight back to loop, don't increment p */
1119 if (p
< rl_end
&& rl_line_buffer
[p
])
1120 ADVANCE_CHAR (rl_line_buffer
, slen
, p
);
1123 p
= skip_to_delim (rl_line_buffer
, ++p
, "'", SD_NOJMP
);
1126 p
= skip_to_delim (rl_line_buffer
, ++p
, "\"", SD_NOJMP
);
1134 if (rl_line_buffer
[p
] == 0 || p
== rl_end
)
1141 /* Now move forward until we hit a non-quoted metacharacter or EOL */
1142 while (p
< rl_end
&& (c
= rl_line_buffer
[p
]) && WORDDELIM (c
) == 0)
1147 ADVANCE_CHAR (rl_line_buffer
, slen
, p
);
1148 continue; /* straight back to loop, don't increment p */
1150 if (p
< rl_end
&& rl_line_buffer
[p
])
1151 ADVANCE_CHAR (rl_line_buffer
, slen
, p
);
1154 p
= skip_to_delim (rl_line_buffer
, ++p
, "'", SD_NOJMP
);
1157 p
= skip_to_delim (rl_line_buffer
, ++p
, "\"", SD_NOJMP
);
1165 if (p
== rl_end
|| rl_line_buffer
[p
] == 0)
1179 bash_backward_shellword (count
, key
)
1187 return (bash_forward_shellword (-count
, key
));
1192 if (p
== rl_end
&& p
> 0)
1203 /* Move backward until we hit a non-metacharacter. */
1206 c
= rl_line_buffer
[p
];
1207 if (WORDDELIM (c
) == 0 || char_is_quoted (rl_line_buffer
, p
))
1209 BACKUP_CHAR (rl_line_buffer
, slen
, p
);
1218 /* Now move backward until we hit a metacharacter or BOL. */
1221 c
= rl_line_buffer
[p
];
1222 if (WORDDELIM (c
) && char_is_quoted (rl_line_buffer
, p
) == 0)
1224 BACKUP_CHAR (rl_line_buffer
, slen
, p
);
1235 bash_kill_shellword (count
, key
)
1241 return (bash_backward_kill_shellword (-count
, key
));
1244 bash_forward_shellword (count
, key
);
1247 rl_kill_text (p
, rl_point
);
1250 if (rl_editing_mode
== EMACS_EDITING_MODE
) /* 1 == emacs_mode */
1257 bash_backward_kill_shellword (count
, key
)
1263 return (bash_kill_shellword (-count
, key
));
1266 bash_backward_shellword (count
, key
);
1269 rl_kill_text (p
, rl_point
);
1271 if (rl_editing_mode
== EMACS_EDITING_MODE
) /* 1 == emacs_mode */
1278 /* **************************************************************** */
1280 /* How To Do Shell Completion */
1282 /* **************************************************************** */
1284 #define COMMAND_SEPARATORS ";|&{(`"
1286 #define COMMAND_SEPARATORS_PLUS_WS ";|&{(` \t"
1289 /* check for redirections and other character combinations that are not
1290 command separators */
1295 register int this_char
, prev_char
;
1297 /* Handle the two character tokens `>&', `<&', and `>|'.
1298 We are not in a command position after one of these. */
1299 this_char
= rl_line_buffer
[ti
];
1300 prev_char
= (ti
> 0) ? rl_line_buffer
[ti
- 1] : 0;
1302 if ((this_char
== '&' && (prev_char
== '<' || prev_char
== '>')) ||
1303 (this_char
== '|' && prev_char
== '>'))
1305 else if (this_char
== '{' && prev_char
== '$') /*}*/
1308 else if (this_char
== '(' && prev_char
== '$') /*)*/
1310 else if (this_char
== '(' && prev_char
== '<') /*)*/
1312 #if defined (EXTENDED_GLOB)
1313 else if (extended_glob
&& this_char
== '(' && prev_char
== '!') /*)*/
1317 else if (char_is_quoted (rl_line_buffer
, ti
))
1322 #if defined (PROGRAMMABLE_COMPLETION)
1324 * XXX - because of the <= start test, and setting os = s+1, this can
1325 * potentially return os > start. This is probably not what we want to
1326 * happen, but fix later after 2.05a-release.
1329 find_cmd_start (start
)
1332 register int s
, os
, ns
;
1335 /* Flags == SD_NOJMP only because we want to skip over command substitutions
1336 in assignment statements. Have to test whether this affects `standalone'
1337 command substitutions as individual words. */
1338 while (((s
= skip_to_delim (rl_line_buffer
, os
, COMMAND_SEPARATORS
, SD_NOJMP
|SD_COMPLETE
/*|SD_NOSKIPCMD*/)) <= start
) &&
1341 /* Handle >| token crudely; treat as > not | */
1342 if (rl_line_buffer
[s
] == '|' && rl_line_buffer
[s
-1] == '>')
1344 ns
= skip_to_delim (rl_line_buffer
, s
+1, COMMAND_SEPARATORS
, SD_NOJMP
|SD_COMPLETE
/*|SD_NOSKIPCMD*/);
1345 if (ns
> start
|| rl_line_buffer
[ns
] == 0)
1361 e
= skip_to_delim (rl_line_buffer
, end
, COMMAND_SEPARATORS
, SD_NOJMP
|SD_COMPLETE
);
1366 find_cmd_name (start
, sp
, ep
)
1373 for (s
= start
; whitespace (rl_line_buffer
[s
]); s
++)
1376 /* skip until a shell break character */
1377 e
= skip_to_delim (rl_line_buffer
, s
, "()<>;&| \t\n", SD_NOJMP
|SD_COMPLETE
);
1379 name
= substring (rl_line_buffer
, s
, e
);
1390 prog_complete_return (text
, matchnum
)
1399 if (prog_complete_matches
== 0 || prog_complete_matches
[ind
] == 0)
1400 return (char *)NULL
;
1401 return (prog_complete_matches
[ind
++]);
1404 #endif /* PROGRAMMABLE_COMPLETION */
1406 /* Try and catch completion attempts that are syntax errors or otherwise
1409 invalid_completion (text
, ind
)
1415 /* If we don't catch these here, the next clause will */
1416 if (ind
> 0 && rl_line_buffer
[ind
] == '(' && /*)*/
1417 member (rl_line_buffer
[ind
-1], "$<>"))
1421 while (pind
> 0 && whitespace (rl_line_buffer
[pind
]))
1423 /* If we have only whitespace preceding a paren, it's valid */
1424 if (ind
>= 0 && pind
<= 0 && rl_line_buffer
[ind
] == '(') /*)*/
1426 /* Flag the invalid completions, which are mostly syntax errors */
1427 if (ind
> 0 && rl_line_buffer
[ind
] == '(' && /*)*/
1428 member (rl_line_buffer
[pind
], COMMAND_SEPARATORS
) == 0)
1434 /* Do some completion on TEXT. The indices of TEXT in RL_LINE_BUFFER are
1435 at START and END. Return an array of matches, or NULL if none. */
1437 attempt_shell_completion (text
, start
, end
)
1441 int in_command_position
, ti
, qc
, dflags
;
1442 char **matches
, *command_separator_chars
;
1443 #if defined (PROGRAMMABLE_COMPLETION)
1444 int have_progcomps
, was_assignment
;
1445 COMPSPEC
*iw_compspec
;
1448 command_separator_chars
= COMMAND_SEPARATORS
;
1449 matches
= (char **)NULL
;
1450 rl_ignore_some_completions_function
= filename_completion_ignore
;
1452 rl_filename_quote_characters
= default_filename_quote_characters
;
1453 set_filename_bstab (rl_filename_quote_characters
);
1454 set_directory_hook ();
1455 rl_filename_stat_hook
= bash_filename_stat_hook
;
1457 rl_sort_completion_matches
= 1; /* sort by default */
1459 /* Determine if this could be a command word. It is if it appears at
1460 the start of the line (ignoring preceding whitespace), or if it
1461 appears after a character that separates commands. It cannot be a
1462 command word if we aren't at the top-level prompt. */
1466 while ((ti
> -1) && (whitespace (rl_line_buffer
[ti
])))
1470 /* If this is an open quote, maybe we're trying to complete a quoted
1472 if (ti
>= 0 && (rl_line_buffer
[ti
] == '"' || rl_line_buffer
[ti
] == '\''))
1474 qc
= rl_line_buffer
[ti
];
1476 while (ti
> -1 && (whitespace (rl_line_buffer
[ti
])))
1481 in_command_position
= 0;
1484 /* Only do command completion at the start of a line when we
1485 are prompting at the top level. */
1486 if (current_prompt_string
== ps1_prompt
)
1487 in_command_position
++;
1488 else if (parser_in_command_position ())
1489 in_command_position
++;
1491 else if (member (rl_line_buffer
[ti
], command_separator_chars
))
1493 in_command_position
++;
1495 if (check_redir (ti
) == 1)
1496 in_command_position
= 0;
1500 /* This still could be in command position. It is possible
1501 that all of the previous words on the line are variable
1505 if (in_command_position
&& invalid_completion (text
, ti
))
1507 rl_attempted_completion_over
= 1;
1508 return ((char **)NULL
);
1511 /* Check that we haven't incorrectly flagged a closed command substitution
1512 as indicating we're in a command position. */
1513 if (in_command_position
&& ti
>= 0 && rl_line_buffer
[ti
] == '`' &&
1514 *text
!= '`' && unclosed_pair (rl_line_buffer
, end
, "`") == 0)
1515 in_command_position
= 0;
1517 /* Special handling for command substitution. If *TEXT is a backquote,
1518 it can be the start or end of an old-style command substitution, or
1519 unmatched. If it's unmatched, both calls to unclosed_pair will
1520 succeed. Don't bother if readline found a single quote and we are
1521 completing on the substring. */
1522 if (*text
== '`' && rl_completion_quote_character
!= '\'' &&
1523 (in_command_position
|| (unclosed_pair (rl_line_buffer
, start
, "`") &&
1524 unclosed_pair (rl_line_buffer
, end
, "`"))))
1525 matches
= rl_completion_matches (text
, command_subst_completion_function
);
1527 #if defined (PROGRAMMABLE_COMPLETION)
1528 /* Attempt programmable completion. */
1529 have_progcomps
= prog_completion_enabled
&& (progcomp_size () > 0);
1530 iw_compspec
= progcomp_search (INITIALWORD
);
1532 (in_command_position
== 0 || text
[0] == '\0' || (in_command_position
&& iw_compspec
)) &&
1533 current_prompt_string
== ps1_prompt
)
1535 int s
, e
, s1
, e1
, os
, foundcs
;
1538 /* XXX - don't free the members */
1539 if (prog_complete_matches
)
1540 free (prog_complete_matches
);
1541 prog_complete_matches
= (char **)NULL
;
1546 s
= find_cmd_start (os
);
1547 e
= find_cmd_end (end
);
1550 /* Don't read past the end of rl_line_buffer */
1556 /* Or past point if point is within an assignment statement */
1557 else if (was_assignment
&& s
> rl_point
)
1562 /* Skip over assignment statements preceding a command name. If we
1563 don't find a command name at all, we can perform command name
1564 completion. If we find a partial command name, we should perform
1565 command name completion on it. */
1567 n
= find_cmd_name (s
, &s1
, &e1
);
1570 while (was_assignment
= assignment (n
, 0));
1571 s
= s1
; /* reset to index where name begins */
1573 /* s == index of where command name begins (reset above)
1574 e == end of current command, may be end of line
1575 s1 = index of where command name begins
1576 e1 == index of where command name ends
1577 start == index of where word to be completed begins
1578 end == index of where word to be completed ends
1579 if (s == start) we are doing command word completion for sure
1580 if (e1 == end) we are at the end of the command name and completing it */
1581 if (start
== 0 && end
== 0 && e
!= 0 && text
[0] == '\0') /* beginning of non-empty line */
1583 else if (start
== end
&& start
== s1
&& e
!= 0 && e1
> end
) /* beginning of command name, leading whitespace */
1585 else if (e
== 0 && e
== s
&& text
[0] == '\0' && have_progcomps
) /* beginning of empty line */
1586 prog_complete_matches
= programmable_completions (EMPTYCMD
, text
, s
, e
, &foundcs
);
1587 else if (start
== end
&& text
[0] == '\0' && s1
> start
&& whitespace (rl_line_buffer
[start
]))
1588 foundcs
= 0; /* whitespace before command name */
1589 else if (e
> s
&& was_assignment
== 0 && e1
== end
&& rl_line_buffer
[e
] == 0 && whitespace (rl_line_buffer
[e
-1]) == 0)
1591 /* not assignment statement, but still want to perform command
1592 completion if we are composing command word. */
1594 in_command_position
= s
== start
&& STREQ (n
, text
); /* XXX */
1596 else if (e
> s
&& was_assignment
== 0 && have_progcomps
)
1598 prog_complete_matches
= programmable_completions (n
, text
, s
, e
, &foundcs
);
1599 /* command completion if programmable completion fails */
1600 /* If we have a completion for the initial word, we can prefer that */
1601 in_command_position
= s
== start
&& (iw_compspec
|| STREQ (n
, text
)); /* XXX */
1602 if (iw_compspec
&& in_command_position
)
1605 /* empty command name following command separator */
1606 else if (s
>= e
&& n
[0] == '\0' && text
[0] == '\0' && start
> 0 &&
1607 was_assignment
== 0 && member (rl_line_buffer
[start
-1], COMMAND_SEPARATORS
))
1610 in_command_position
= 1;
1612 else if (s
>= e
&& n
[0] == '\0' && text
[0] == '\0' && start
> 0)
1614 foundcs
= 0; /* empty command name following optional assignments */
1615 in_command_position
+= was_assignment
;
1617 else if (s
== start
&& e
== end
&& STREQ (n
, text
) && start
> 0)
1619 foundcs
= 0; /* partial command name following assignments */
1620 in_command_position
= 1;
1625 /* If we have defined a compspec for the initial (command) word, call
1626 it and process the results like any other programmable completion. */
1627 if (in_command_position
&& have_progcomps
&& foundcs
== 0 && iw_compspec
)
1628 prog_complete_matches
= programmable_completions (INITIALWORD
, text
, s
, e
, &foundcs
);
1631 /* XXX - if we found a COMPSPEC for the command, just return whatever
1632 the programmable completion code returns, and disable the default
1633 filename completion that readline will do unless the COPT_DEFAULT
1634 option has been set with the `-o default' option to complete or
1638 pcomp_set_readline_variables (foundcs
, 1);
1639 /* Turn what the programmable completion code returns into what
1640 readline wants. I should have made compute_lcd_of_matches
1642 matches
= rl_completion_matches (text
, prog_complete_return
);
1643 if ((foundcs
& COPT_DEFAULT
) == 0)
1644 rl_attempted_completion_over
= 1; /* no default */
1645 if (matches
|| ((foundcs
& COPT_BASHDEFAULT
) == 0))
1654 if (in_command_position
)
1655 dflags
|= DEFCOMP_CMDPOS
;
1656 matches
= bash_default_completion (text
, start
, end
, qc
, dflags
);
1663 bash_default_completion (text
, start
, end
, qc
, compflags
)
1665 int start
, end
, qc
, compflags
;
1669 matches
= (char **)NULL
;
1671 /* New posix-style command substitution or variable name? */
1674 if (qc
!= '\'' && text
[1] == '(') /* ) */
1675 matches
= rl_completion_matches (text
, command_subst_completion_function
);
1678 matches
= rl_completion_matches (text
, variable_completion_function
);
1679 /* If a single match, see if it expands to a directory name and append
1680 a slash if it does. This requires us to expand the variable name,
1681 so we don't want to display errors if the variable is unset. This
1682 can happen with dynamic variables whose value has never been
1684 if (matches
&& matches
[0] && matches
[1] == 0)
1686 t
= savestring (matches
[0]);
1687 bash_filename_stat_hook (&t
);
1688 /* doesn't use test_for_directory because that performs tilde
1691 rl_completion_append_character
= '/';
1697 /* If the word starts in `~', and there is no slash in the word, then
1698 try completing this word as a username. */
1699 if (matches
== 0 && *text
== '~' && mbschr (text
, '/') == 0)
1700 matches
= rl_completion_matches (text
, rl_username_completion_function
);
1702 /* Another one. Why not? If the word starts in '@', then look through
1703 the world of known hostnames for completion first. */
1704 if (matches
== 0 && perform_hostname_completion
&& *text
== '@')
1705 matches
= rl_completion_matches (text
, hostname_completion_function
);
1707 /* And last, (but not least) if this word is in a command position, then
1708 complete over possible command names, including aliases, functions,
1709 and command names. */
1710 if (matches
== 0 && (compflags
& DEFCOMP_CMDPOS
))
1712 /* If END == START and text[0] == 0, we are trying to complete an empty
1714 if (no_empty_command_completion
&& end
== start
&& text
[0] == '\0')
1716 matches
= (char **)NULL
;
1717 rl_ignore_some_completions_function
= bash_ignore_everything
;
1721 #define CMD_IS_DIR(x) (absolute_pathname(x) == 0 && absolute_program(x) == 0 && *(x) != '~' && test_for_directory (x))
1724 matches
= rl_completion_matches (text
, command_word_completion_function
);
1726 /* If we are attempting command completion and nothing matches, we
1727 do not want readline to perform filename completion for us. We
1728 still want to be able to complete partial pathnames, so set the
1729 completion ignore function to something which will remove
1730 filenames and leave directories in the match list. */
1731 if (matches
== (char **)NULL
)
1732 rl_ignore_some_completions_function
= bash_ignore_filenames
;
1733 else if (matches
[1] == 0 && CMD_IS_DIR(matches
[0]) && dot_in_path
== 0)
1734 /* If we found a single match, without looking in the current
1735 directory (because it's not in $PATH), but the found name is
1736 also a command in the current directory, suppress appending any
1737 terminating character, since it's ambiguous. */
1739 rl_completion_suppress_append
= 1;
1740 rl_filename_completion_desired
= 0;
1742 else if (matches
[0] && matches
[1] && STREQ (matches
[0], matches
[1]) && CMD_IS_DIR (matches
[0]))
1743 /* There are multiple instances of the same match (duplicate
1744 completions haven't yet been removed). In this case, all of
1745 the matches will be the same, and the duplicate removal code
1746 will distill them all down to one. We turn on
1747 rl_completion_suppress_append for the same reason as above.
1748 Remember: we only care if there's eventually a single unique
1749 completion. If there are multiple completions this won't
1750 make a difference and the problem won't occur. */
1752 rl_completion_suppress_append
= 1;
1753 rl_filename_completion_desired
= 0;
1758 /* This could be a globbing pattern, so try to expand it using pathname
1760 if (!matches
&& completion_glob_pattern ((char *)text
))
1762 matches
= rl_completion_matches (text
, glob_complete_word
);
1763 /* A glob expression that matches more than one filename is problematic.
1764 If we match more than one filename, punt. */
1765 if (matches
&& matches
[1] && rl_completion_type
== TAB
)
1767 strvec_dispose (matches
);
1768 matches
= (char **)0;
1770 else if (matches
&& matches
[1] && rl_completion_type
== '!')
1772 rl_completion_suppress_append
= 1;
1773 rl_filename_completion_desired
= 0;
1781 bash_command_name_stat_hook (name
)
1784 char *cname
, *result
;
1786 /* If it's not something we're going to look up in $PATH, just call the
1787 normal filename stat hook. */
1788 if (absolute_program (*name
))
1789 return (bash_filename_stat_hook (name
));
1792 /* XXX - we could do something here with converting aliases, builtins,
1793 and functions into something that came out as executable, but we don't. */
1794 result
= search_for_command (cname
, 0);
1804 executable_completion (filename
, searching_path
)
1805 const char *filename
;
1811 f
= savestring (filename
);
1812 bash_directory_completion_hook (&f
);
1814 r
= searching_path
? executable_file (f
) : executable_or_directory (f
);
1819 /* This is the function to call when the word to complete is in a position
1820 where a command word can be found. It grovels $PATH, looking for commands
1821 that match. It also scans aliases, function names, and the shell_builtin
1824 command_word_completion_function (hint_text
, state
)
1825 const char *hint_text
;
1828 static char *hint
= (char *)NULL
;
1829 static char *path
= (char *)NULL
;
1830 static char *val
= (char *)NULL
;
1831 static char *filename_hint
= (char *)NULL
;
1832 static char *fnhint
= (char *)NULL
;
1833 static char *dequoted_hint
= (char *)NULL
;
1834 static char *directory_part
= (char *)NULL
;
1835 static char **glob_matches
= (char **)NULL
;
1836 static int path_index
, hint_len
, istate
, igncase
;
1837 static int mapping_over
, local_index
, searching_path
, hint_is_dir
;
1838 static int old_glob_ignore_case
, globpat
;
1839 static SHELL_VAR
**varlist
= (SHELL_VAR
**)NULL
;
1841 static alias_t
**alias_list
= (alias_t
**)NULL
;
1845 /* We have to map over the possibilities for command words. If we have
1846 no state, then make one just for that purpose. */
1849 rl_filename_stat_hook
= bash_command_name_stat_hook
;
1851 if (dequoted_hint
&& dequoted_hint
!= hint
)
1852 free (dequoted_hint
);
1856 mapping_over
= searching_path
= 0;
1857 hint_is_dir
= CMD_IS_DIR (hint_text
);
1860 temp
= rl_variable_value ("completion-ignore-case");
1861 igncase
= RL_BOOLEAN_VARIABLE_VALUE (temp
);
1865 free (glob_matches
);
1866 glob_matches
= (char **)NULL
;
1869 globpat
= completion_glob_pattern ((char *)hint_text
);
1871 /* If this is an absolute program name, do not check it against
1872 aliases, reserved words, functions or builtins. We must check
1873 whether or not it is unique, and, if so, whether that filename
1875 if (globpat
|| absolute_program (hint_text
))
1877 /* Perform tilde expansion on what's passed, so we don't end up
1878 passing filenames with tildes directly to stat(). The rest of
1879 the shell doesn't do variable expansion on the word following
1880 the tilde, so we don't do it here even if direxpand is set. */
1881 if (*hint_text
== '~')
1883 hint
= bash_tilde_expand (hint_text
, 0);
1884 directory_part
= savestring (hint_text
);
1885 temp
= strchr (directory_part
, '/');
1890 free (directory_part
);
1891 directory_part
= (char *)NULL
;
1894 else if (dircomplete_expand
)
1896 hint
= savestring (hint_text
);
1897 bash_directory_completion_hook (&hint
);
1900 hint
= savestring (hint_text
);
1902 dequoted_hint
= hint
;
1903 /* If readline's completer found a quote character somewhere, but
1904 didn't set the quote character, there must have been a quote
1905 character embedded in the filename. It can't be at the start of
1906 the filename, so we need to dequote the filename before we look
1907 in the file system for it. */
1908 if (rl_completion_found_quote
&& rl_completion_quote_character
== 0)
1910 dequoted_hint
= bash_dequote_filename (hint
, 0);
1912 hint
= dequoted_hint
;
1914 hint_len
= strlen (hint
);
1917 free (filename_hint
);
1919 fnhint
= filename_hint
= savestring (hint
);
1930 if (dircomplete_expand
&& path_dot_or_dotdot (filename_hint
))
1932 dircomplete_expand
= 0;
1933 set_directory_hook ();
1934 dircomplete_expand
= 1;
1941 dequoted_hint
= hint
= savestring (hint_text
);
1942 hint_len
= strlen (hint
);
1944 if (rl_completion_found_quote
&& rl_completion_quote_character
== 0)
1945 dequoted_hint
= bash_dequote_filename (hint
, 0);
1947 path
= get_string_value ("PATH");
1948 path_index
= dot_in_path
= 0;
1950 /* Initialize the variables for each type of command word. */
1956 varlist
= all_visible_functions ();
1962 alias_list
= all_aliases ();
1966 /* mapping_over says what we are currently hacking. Note that every case
1967 in this list must fall through when there are no more possibilities. */
1969 switch (mapping_over
)
1971 case 0: /* Aliases come first. */
1973 while (alias_list
&& alias_list
[local_index
])
1975 register char *alias
;
1977 alias
= alias_list
[local_index
++]->name
;
1979 if (igncase
== 0 && (STREQN (alias
, hint
, hint_len
)))
1980 return (savestring (alias
));
1981 else if (igncase
&& strncasecmp (alias
, hint
, hint_len
) == 0)
1982 return (savestring (alias
));
1988 case 1: /* Then shell reserved words. */
1990 while (word_token_alist
[local_index
].word
)
1992 register char *reserved_word
;
1994 reserved_word
= word_token_alist
[local_index
++].word
;
1996 if (STREQN (reserved_word
, hint
, hint_len
))
1997 return (savestring (reserved_word
));
2003 case 2: /* Then function names. */
2004 while (varlist
&& varlist
[local_index
])
2006 register char *varname
;
2008 varname
= varlist
[local_index
++]->name
;
2010 /* Honor completion-ignore-case for shell function names. */
2011 if (igncase
== 0 && (STREQN (varname
, hint
, hint_len
)))
2012 return (savestring (varname
));
2013 else if (igncase
&& strncasecmp (varname
, hint
, hint_len
) == 0)
2014 return (savestring (varname
));
2019 case 3: /* Then shell builtins. */
2020 for (; local_index
< num_shell_builtins
; local_index
++)
2022 /* Ignore it if it doesn't have a function pointer or if it
2023 is not currently enabled. */
2024 if (!shell_builtins
[local_index
].function
||
2025 (shell_builtins
[local_index
].flags
& BUILTIN_ENABLED
) == 0)
2028 if (STREQN (shell_builtins
[local_index
].name
, hint
, hint_len
))
2030 int i
= local_index
++;
2032 return (savestring (shell_builtins
[i
].name
));
2040 /* Limited support for completing command words with globbing chars. Only
2041 a single match (multiple matches that end up reducing the number of
2042 characters in the common prefix are bad) will ever be returned on
2043 regular completion. */
2048 glob_ignore_case
= igncase
;
2049 glob_matches
= shell_glob_filename (hint
);
2050 glob_ignore_case
= old_glob_ignore_case
;
2052 if (GLOB_FAILED (glob_matches
) || glob_matches
== 0)
2054 glob_matches
= (char **)NULL
;
2055 return ((char *)NULL
);
2060 if (glob_matches
[1] && rl_completion_type
== TAB
) /* multiple matches are bad */
2061 return ((char *)NULL
);
2064 while (val
= glob_matches
[local_index
++])
2066 if (executable_or_directory (val
))
2068 if (*hint_text
== '~' && directory_part
)
2070 temp
= maybe_restore_tilde (val
, directory_part
);
2079 glob_ignore_case
= old_glob_ignore_case
;
2080 return ((char *)NULL
);
2083 /* If the text passed is a directory in the current directory, return it
2084 as a possible match. Executables in directories in the current
2085 directory can be specified using relative pathnames and successfully
2086 executed even when `.' is not in $PATH. */
2089 hint_is_dir
= 0; /* only return the hint text once */
2090 return (savestring (hint_text
));
2093 /* Repeatedly call filename_completion_function while we have
2094 members of PATH left. Question: should we stat each file?
2095 Answer: we call executable_file () on each file. */
2098 istate
= (val
!= (char *)NULL
);
2104 /* Get the next directory from the path. If there is none, then we
2106 if (path
== 0 || path
[path_index
] == 0 ||
2107 (current_path
= extract_colon_unit (path
, &path_index
)) == 0)
2108 return ((char *)NULL
);
2111 if (*current_path
== 0)
2113 free (current_path
);
2114 current_path
= savestring (".");
2117 if (*current_path
== '~')
2121 t
= bash_tilde_expand (current_path
, 0);
2122 free (current_path
);
2126 if (current_path
[0] == '.' && current_path
[1] == '\0')
2129 if (fnhint
&& fnhint
!= filename_hint
)
2132 free (filename_hint
);
2134 filename_hint
= sh_makepath (current_path
, hint
, 0);
2135 /* Need a quoted version (though it doesn't matter much in most
2136 cases) because rl_filename_completion_function dequotes the
2137 filename it gets, assuming that it's been quoted as part of
2138 the input line buffer. */
2139 if (strpbrk (filename_hint
, "\"'\\"))
2140 fnhint
= sh_backslash_quote (filename_hint
, filename_bstab
, 0);
2142 fnhint
= filename_hint
;
2143 free (current_path
); /* XXX */
2147 val
= rl_filename_completion_function (fnhint
, istate
);
2148 if (mapping_over
== 4 && dircomplete_expand
)
2149 set_directory_hook ();
2155 /* If the hint text is an absolute program, then don't bother
2156 searching through PATH. */
2157 if (absolute_program (hint
))
2158 return ((char *)NULL
);
2164 int match
, freetemp
;
2166 if (absolute_program (hint
))
2169 match
= strncmp (val
, hint
, hint_len
) == 0;
2171 match
= strncasecmp (val
, hint
, hint_len
) == 0;
2173 /* If we performed tilde expansion, restore the original
2175 if (*hint_text
== '~')
2176 temp
= maybe_restore_tilde (val
, directory_part
);
2178 temp
= savestring (val
);
2183 temp
= strrchr (val
, '/');
2189 freetemp
= match
= strncmp (temp
, hint
, hint_len
) == 0;
2191 freetemp
= match
= strncasecmp (temp
, hint
, hint_len
) == 0;
2193 temp
= savestring (temp
);
2196 freetemp
= match
= 0;
2199 /* If we have found a match, and it is an executable file, return it.
2200 We don't return directory names when searching $PATH, since the
2201 bash execution code won't find executables in directories which
2202 appear in directories in $PATH when they're specified using
2203 relative pathnames. */
2205 /* If we're not searching $PATH and we have a relative pathname, we
2206 need to re-canonicalize it before testing whether or not it's an
2207 executable or a directory so the shell treats .. relative to $PWD
2208 according to the physical/logical option. The shell already
2209 canonicalizes the directory name in order to tell readline where
2210 to look, so not doing it here will be inconsistent. */
2211 /* XXX -- currently not used -- will introduce more inconsistency,
2212 since shell does not canonicalize ../foo before passing it to
2214 if (match
&& searching_path
== 0 && *val
== '.')
2218 t
= get_working_directory ("command-word-completion");
2219 t1
= make_absolute (val
, t
);
2221 cval
= sh_canonpath (t1
, PATH_CHECKDOTDOT
|PATH_CHECKEXISTS
);
2227 if (match
&& executable_completion ((searching_path
? val
: cval
), searching_path
))
2232 val
= ""; /* So it won't be NULL. */
2247 /* Completion inside an unterminated command substitution. */
2249 command_subst_completion_function (text
, state
)
2253 static char **matches
= (char **)NULL
;
2254 static const char *orig_start
;
2255 static char *filename_text
= (char *)NULL
;
2256 static int cmd_index
, start_len
;
2262 free (filename_text
);
2266 else if (*text
== '$' && text
[1] == '(') /* ) */
2268 /* If the text was quoted, suppress any quote character that the
2269 readline completion code would insert. */
2270 rl_completion_suppress_quote
= 1;
2271 start_len
= text
- orig_start
;
2272 filename_text
= savestring (text
);
2277 * At this point we can entertain the idea of re-parsing
2278 * `filename_text' into a (possibly incomplete) command name and
2279 * arguments, and doing completion based on that. This is
2280 * currently very rudimentary, but it is a small improvement.
2282 for (value
= filename_text
+ strlen (filename_text
) - 1; value
> filename_text
; value
--)
2283 if (whitespace (*value
) || member (*value
, COMMAND_SEPARATORS
))
2285 if (value
<= filename_text
)
2286 matches
= rl_completion_matches (filename_text
, command_word_completion_function
);
2290 start_len
+= value
- filename_text
;
2291 if (whitespace (value
[-1]))
2292 matches
= rl_completion_matches (value
, rl_filename_completion_function
);
2294 matches
= rl_completion_matches (value
, command_word_completion_function
);
2297 /* If there is more than one match, rl_completion_matches has already
2298 put the lcd in matches[0]. Skip over it. */
2299 cmd_index
= matches
&& matches
[0] && matches
[1];
2301 /* If there's a single match and it's a directory, set the append char
2302 to the expected `/'. Otherwise, don't append anything. */
2303 if (matches
&& matches
[0] && matches
[1] == 0 && test_for_directory (matches
[0]))
2304 rl_completion_append_character
= '/';
2306 rl_completion_suppress_append
= 1;
2309 if (matches
== 0 || matches
[cmd_index
] == 0)
2311 rl_filename_quoting_desired
= 0; /* disable quoting */
2312 return ((char *)NULL
);
2316 value
= (char *)xmalloc (1 + start_len
+ strlen (matches
[cmd_index
]));
2319 value
[0] = *orig_start
;
2321 strncpy (value
, orig_start
, start_len
);
2323 strcpy (value
+ start_len
, matches
[cmd_index
]);
2330 /* Okay, now we write the entry_function for variable completion. */
2332 variable_completion_function (text
, state
)
2336 static char **varlist
= (char **)NULL
;
2337 static int varlist_index
;
2338 static char *varname
= (char *)NULL
;
2339 static int first_char
, first_char_loc
;
2347 first_char
= text
[0];
2349 if (first_char
== '$')
2352 if (text
[first_char_loc
] == '{')
2355 varname
= savestring (text
+ first_char_loc
);
2358 strvec_dispose (varlist
);
2360 varlist
= all_variables_matching_prefix (varname
);
2364 if (!varlist
|| !varlist
[varlist_index
])
2366 return ((char *)NULL
);
2372 value
= (char *)xmalloc (4 + strlen (varlist
[varlist_index
]));
2376 value
[0] = first_char
;
2377 if (first_char_loc
== 2)
2381 strcpy (value
+ first_char_loc
, varlist
[varlist_index
]);
2382 if (first_char_loc
== 2)
2383 strcat (value
, "}");
2390 /* How about a completion function for hostnames? */
2392 hostname_completion_function (text
, state
)
2396 static char **list
= (char **)NULL
;
2397 static int list_index
= 0;
2398 static int first_char
, first_char_loc
;
2400 /* If we don't have any state, make some. */
2405 list
= (char **)NULL
;
2410 if (first_char
== '@')
2413 list
= hostnames_matching ((char *)text
+first_char_loc
);
2417 if (list
&& list
[list_index
])
2421 t
= (char *)xmalloc (2 + strlen (list
[list_index
]));
2423 strcpy (t
+ first_char_loc
, list
[list_index
]);
2428 return ((char *)NULL
);
2432 * A completion function for service names from /etc/services (or wherever).
2435 bash_servicename_completion_function (text
, state
)
2439 #if defined (__WIN32__) || defined (__OPENNT) || !defined (HAVE_GETSERVENT)
2440 return ((char *)NULL
);
2442 static char *sname
= (char *)NULL
;
2443 static struct servent
*srvent
;
2444 static int snamelen
;
2446 char **alist
, *aentry
;
2453 sname
= savestring (text
);
2454 snamelen
= strlen (sname
);
2458 while (srvent
= getservent ())
2461 if (snamelen
== 0 || (STREQN (sname
, srvent
->s_name
, snamelen
)))
2463 /* Not primary, check aliases */
2464 for (alist
= srvent
->s_aliases
; *alist
; alist
++)
2467 if (STREQN (sname
, aentry
, snamelen
))
2481 return ((char *)NULL
);
2484 value
= afound
? savestring (aentry
) : savestring (srvent
->s_name
);
2490 * A completion function for group names from /etc/group (or wherever).
2493 bash_groupname_completion_function (text
, state
)
2497 #if defined (__WIN32__) || defined (__OPENNT) || !defined (HAVE_GRP_H)
2498 return ((char *)NULL
);
2500 static char *gname
= (char *)NULL
;
2501 static struct group
*grent
;
2502 static int gnamelen
;
2508 gname
= savestring (text
);
2509 gnamelen
= strlen (gname
);
2514 while (grent
= getgrent ())
2516 if (gnamelen
== 0 || (STREQN (gname
, grent
->gr_name
, gnamelen
)))
2523 return ((char *)NULL
);
2526 value
= savestring (grent
->gr_name
);
2531 /* Functions to perform history and alias expansions on the current line. */
2533 #if defined (BANG_HISTORY)
2534 /* Perform history expansion on the current line. If no history expansion
2535 is done, pre_process_line() returns what it was passed, so we need to
2536 allocate a new line here. */
2538 history_expand_line_internal (line
)
2544 old_verify
= hist_verify
;
2546 new_line
= pre_process_line (line
, 0, 0);
2547 hist_verify
= old_verify
;
2549 return (new_line
== line
) ? savestring (line
) : new_line
;
2553 /* There was an error in expansion. Let the preprocessor print
2556 cleanup_expansion_error ()
2559 #if defined (BANG_HISTORY)
2562 old_verify
= hist_verify
;
2566 fprintf (rl_outstream
, "\r\n");
2567 to_free
= pre_process_line (rl_line_buffer
, 1, 0);
2568 #if defined (BANG_HISTORY)
2569 hist_verify
= old_verify
;
2571 if (to_free
!= rl_line_buffer
)
2573 putc ('\r', rl_outstream
);
2574 rl_forced_update_display ();
2577 /* If NEW_LINE differs from what is in the readline line buffer, add an
2578 undo record to get from the readline line buffer contents to the new
2579 line and make NEW_LINE the current readline line. */
2581 maybe_make_readline_line (new_line
)
2584 if (new_line
&& strcmp (new_line
, rl_line_buffer
) != 0)
2588 rl_add_undo (UNDO_BEGIN
, 0, 0, 0);
2589 rl_delete_text (0, rl_point
);
2590 rl_point
= rl_end
= rl_mark
= 0;
2591 rl_insert_text (new_line
);
2592 rl_add_undo (UNDO_END
, 0, 0, 0);
2596 /* Make NEW_LINE be the current readline line. This frees NEW_LINE. */
2598 set_up_new_line (new_line
)
2601 int old_point
, at_end
;
2603 old_point
= rl_point
;
2604 at_end
= rl_point
== rl_end
;
2606 /* If the line was history and alias expanded, then make that
2607 be one thing to undo. */
2608 maybe_make_readline_line (new_line
);
2611 /* Place rl_point where we think it should go. */
2614 else if (old_point
< rl_end
)
2616 rl_point
= old_point
;
2617 if (!whitespace (rl_line_buffer
[rl_point
]))
2618 rl_forward_word (1, 0);
2623 /* Expand aliases in the current readline line. */
2625 alias_expand_line (count
, ignore
)
2630 new_line
= alias_expand (rl_line_buffer
);
2634 set_up_new_line (new_line
);
2639 cleanup_expansion_error ();
2645 #if defined (BANG_HISTORY)
2646 /* History expand the line. */
2648 history_expand_line (count
, ignore
)
2653 new_line
= history_expand_line_internal (rl_line_buffer
);
2657 set_up_new_line (new_line
);
2662 cleanup_expansion_error ();
2667 /* Expand history substitutions in the current line and then insert a
2668 space (hopefully close to where we were before). */
2670 tcsh_magic_space (count
, ignore
)
2673 int dist_from_end
, old_point
;
2675 old_point
= rl_point
;
2676 dist_from_end
= rl_end
- rl_point
;
2677 if (history_expand_line (count
, ignore
) == 0)
2679 /* Try a simple heuristic from Stephen Gildea <gildea@intouchsys.com>.
2680 This works if all expansions were before rl_point or if no expansions
2682 rl_point
= (old_point
== 0) ? old_point
: rl_end
- dist_from_end
;
2689 #endif /* BANG_HISTORY */
2691 /* History and alias expand the line. */
2693 history_and_alias_expand_line (count
, ignore
)
2699 #if defined (BANG_HISTORY)
2700 new_line
= history_expand_line_internal (rl_line_buffer
);
2708 alias_line
= alias_expand (new_line
);
2710 new_line
= alias_line
;
2716 set_up_new_line (new_line
);
2721 cleanup_expansion_error ();
2726 /* History and alias expand the line, then perform the shell word
2727 expansions by calling expand_string. This can't use set_up_new_line()
2728 because we want the variable expansions as a separate undo'able
2729 set of operations. */
2731 shell_expand_line (count
, ignore
)
2735 WORD_LIST
*expanded_string
;
2739 #if defined (BANG_HISTORY)
2740 new_line
= history_expand_line_internal (rl_line_buffer
);
2748 alias_line
= alias_expand (new_line
);
2750 new_line
= alias_line
;
2756 int old_point
= rl_point
;
2757 int at_end
= rl_point
== rl_end
;
2759 /* If the line was history and alias expanded, then make that
2760 be one thing to undo. */
2761 maybe_make_readline_line (new_line
);
2764 /* If there is variable expansion to perform, do that as a separate
2765 operation to be undone. */
2768 w
= alloc_word_desc ();
2769 w
->word
= savestring (rl_line_buffer
);
2770 w
->flags
= rl_explicit_arg
? (W_NOPROCSUB
|W_NOCOMSUB
) : 0;
2771 expanded_string
= expand_word (w
, rl_explicit_arg
? Q_HERE_DOCUMENT
: 0);
2774 new_line
= savestring (rl_line_buffer
);
2775 expanded_string
= expand_string (new_line
, 0);
2779 if (expanded_string
== 0)
2781 new_line
= (char *)xmalloc (1);
2786 new_line
= string_list (expanded_string
);
2787 dispose_words (expanded_string
);
2790 maybe_make_readline_line (new_line
);
2793 /* Place rl_point where we think it should go. */
2796 else if (old_point
< rl_end
)
2798 rl_point
= old_point
;
2799 if (!whitespace (rl_line_buffer
[rl_point
]))
2800 rl_forward_word (1, 0);
2806 cleanup_expansion_error ();
2811 /* If FIGNORE is set, then don't match files with the given suffixes when
2812 completing filenames. If only one of the possibilities has an acceptable
2813 suffix, delete the others, else just return and let the completer
2814 signal an error. It is called by the completer when real
2815 completions are done on filenames by the completer's internal
2816 function, not for completion lists (M-?) and not on "other"
2817 completion types, such as hostnames or commands. */
2819 static struct ignorevar fignore
=
2825 (sh_iv_item_func_t
*) 0,
2829 _ignore_completion_names (names
, name_func
)
2831 sh_ignore_func_t
*name_func
;
2838 /* If there is only one completion, see if it is acceptable. If it is
2839 not, free it up. In any case, short-circuit and return. This is a
2840 special case because names[0] is not the prefix of the list of names
2841 if there is only one completion; it is the completion itself. */
2842 if (names
[1] == (char *)0)
2845 if ((*name_func
) (names
[0]) == 0)
2848 names
[0] = (char *)NULL
;
2854 /* Allocate space for array to hold list of pointers to matching
2855 filenames. The pointers are copied back to NAMES when done. */
2856 for (nidx
= 1; names
[nidx
]; nidx
++)
2858 newnames
= strvec_create (nidx
+ 1);
2860 if (force_fignore
== 0)
2862 oldnames
= strvec_create (nidx
- 1);
2866 newnames
[0] = names
[0];
2867 for (idx
= nidx
= 1; names
[idx
]; idx
++)
2869 if ((*name_func
) (names
[idx
]))
2870 newnames
[nidx
++] = names
[idx
];
2871 else if (force_fignore
== 0)
2872 oldnames
[oidx
++] = names
[idx
];
2877 newnames
[nidx
] = (char *)NULL
;
2879 /* If none are acceptable then let the completer handle it. */
2885 names
[0] = (char *)NULL
;
2894 if (force_fignore
== 0)
2897 free (oldnames
[--oidx
]);
2901 /* If only one is acceptable, copy it to names[0] and return. */
2905 names
[0] = newnames
[1];
2906 names
[1] = (char *)NULL
;
2911 /* Copy the acceptable names back to NAMES, set the new array end,
2913 for (nidx
= 1; newnames
[nidx
]; nidx
++)
2914 names
[nidx
] = newnames
[nidx
];
2915 names
[nidx
] = (char *)NULL
;
2920 name_is_acceptable (name
)
2926 for (nlen
= strlen (name
), p
= fignore
.ignores
; p
->val
; p
++)
2928 if (nlen
> p
->len
&& p
->len
> 0 && STREQ (p
->val
, &name
[nlen
- p
->len
]))
2937 ignore_dot_names (name
)
2940 return (name
[0] != '.');
2945 filename_completion_ignore (names
)
2949 if (glob_dot_filenames
== 0)
2950 _ignore_completion_names (names
, ignore_dot_names
);
2953 setup_ignore_patterns (&fignore
);
2955 if (fignore
.num_ignores
== 0)
2958 _ignore_completion_names (names
, name_is_acceptable
);
2963 /* Return 1 if NAME is a directory. NAME undergoes tilde expansion. */
2965 test_for_directory (name
)
2971 fn
= bash_tilde_expand (name
, 0);
2972 r
= file_isdir (fn
);
2979 test_for_canon_directory (name
)
2985 fn
= (*name
== '~') ? bash_tilde_expand (name
, 0) : savestring (name
);
2986 bash_filename_stat_hook (&fn
);
2987 r
= file_isdir (fn
);
2993 /* Remove files from NAMES, leaving directories. */
2995 bash_ignore_filenames (names
)
2998 _ignore_completion_names (names
, test_for_directory
);
3003 bash_progcomp_ignore_filenames (names
)
3006 _ignore_completion_names (names
, test_for_canon_directory
);
3018 bash_ignore_everything (names
)
3021 _ignore_completion_names (names
, return_zero
);
3025 /* Replace a tilde-prefix in VAL with a `~', assuming the user typed it. VAL
3026 is an expanded filename. DIRECTORY_PART is the tilde-prefix portion
3027 of the un-tilde-expanded version of VAL (what the user typed). */
3029 restore_tilde (val
, directory_part
)
3030 char *val
, *directory_part
;
3033 char *dh2
, *expdir
, *ret
, *v
;
3037 /* We need to duplicate the expansions readline performs on the directory
3038 portion before passing it to our completion function. */
3039 dh2
= directory_part
? bash_dequote_filename (directory_part
, 0) : 0;
3040 bash_directory_expansion (&dh2
);
3043 expdir
= bash_tilde_expand (directory_part
, 0);
3044 xl
= strlen (expdir
);
3045 if (*directory_part
== '~' && STREQ (directory_part
, expdir
))
3047 /* tilde expansion failed, so what should we return? we use what the
3049 v
= mbschr (val
, '/');
3051 ret
= (char *)xmalloc (xl
+ vl
+ 2);
3052 strcpy (ret
, directory_part
);
3054 strcpy (ret
+ xl
, v
);
3064 dh2 = unexpanded but dequoted tilde-prefix
3065 dl2 = length of tilde-prefix
3066 expdir = tilde-expanded tilde-prefix
3067 xl = length of expanded tilde-prefix
3068 l = length of remainder after tilde-prefix
3074 return (savestring (val
)); /* XXX - just punt */
3077 ret
= (char *)xmalloc (dl2
+ 2 + l
);
3079 strcpy (ret
+ dl2
, val
+ xl
);
3086 maybe_restore_tilde (val
, directory_part
)
3087 char *val
, *directory_part
;
3089 rl_icppfunc_t
*save
;
3092 save
= (dircomplete_expand
== 0) ? save_directory_hook () : (rl_icppfunc_t
*)0;
3093 ret
= restore_tilde (val
, directory_part
);
3095 restore_directory_hook (save
);
3099 /* Simulate the expansions that will be performed by
3100 rl_filename_completion_function. This must be called with the address of
3101 a pointer to malloc'd memory. */
3103 bash_directory_expansion (dirname
)
3108 d
= savestring (*dirname
);
3110 if ((rl_directory_rewrite_hook
) && (*rl_directory_rewrite_hook
) (&d
))
3115 else if (rl_directory_completion_hook
&& (*rl_directory_completion_hook
) (&d
))
3120 else if (rl_completion_found_quote
)
3122 nd
= bash_dequote_filename (d
, rl_completion_quote_character
);
3129 /* If necessary, rewrite directory entry */
3131 bash_filename_rewrite_hook (fname
, fnlen
)
3137 conv
= fnx_fromfs (fname
, fnlen
);
3139 conv
= savestring (conv
);
3143 /* Functions to save and restore the appropriate directory hook */
3144 /* This is not static so the shopt code can call it */
3146 set_directory_hook ()
3148 if (dircomplete_expand
)
3150 rl_directory_completion_hook
= bash_directory_completion_hook
;
3151 rl_directory_rewrite_hook
= (rl_icppfunc_t
*)0;
3155 rl_directory_rewrite_hook
= bash_directory_completion_hook
;
3156 rl_directory_completion_hook
= (rl_icppfunc_t
*)0;
3160 static rl_icppfunc_t
*
3161 save_directory_hook ()
3165 if (dircomplete_expand
)
3167 ret
= rl_directory_completion_hook
;
3168 rl_directory_completion_hook
= (rl_icppfunc_t
*)NULL
;
3172 ret
= rl_directory_rewrite_hook
;
3173 rl_directory_rewrite_hook
= (rl_icppfunc_t
*)NULL
;
3180 restore_directory_hook (hookf
)
3181 rl_icppfunc_t
*hookf
;
3183 if (dircomplete_expand
)
3184 rl_directory_completion_hook
= hookf
;
3186 rl_directory_rewrite_hook
= hookf
;
3189 /* Check whether not DIRNAME, with any trailing slash removed, exists. If
3190 SHOULD_DEQUOTE is non-zero, we dequote the directory name first. */
3192 directory_exists (dirname
, should_dequote
)
3193 const char *dirname
;
3200 /* We save the string and chop the trailing slash because stat/lstat behave
3201 inconsistently if one is present. */
3202 new_dirname
= should_dequote
? bash_dequote_filename ((char *)dirname
, rl_completion_quote_character
) : savestring (dirname
);
3203 dirlen
= STRLEN (new_dirname
);
3204 if (new_dirname
[dirlen
- 1] == '/')
3205 new_dirname
[dirlen
- 1] = '\0';
3206 #if defined (HAVE_LSTAT)
3207 r
= lstat (new_dirname
, &sb
) == 0;
3209 r
= stat (new_dirname
, &sb
) == 0;
3215 /* Expand a filename before the readline completion code passes it to stat(2).
3216 The filename will already have had tilde expansion performed. */
3218 bash_filename_stat_hook (dirname
)
3221 char *local_dirname
, *new_dirname
, *t
;
3222 int should_expand_dirname
, return_value
;
3226 local_dirname
= *dirname
;
3227 should_expand_dirname
= return_value
= 0;
3228 if (t
= mbschr (local_dirname
, '$'))
3229 should_expand_dirname
= '$';
3230 else if (t
= mbschr (local_dirname
, '`')) /* XXX */
3231 should_expand_dirname
= '`';
3233 if (should_expand_dirname
&& directory_exists (local_dirname
, 0))
3234 should_expand_dirname
= 0;
3236 if (should_expand_dirname
)
3238 new_dirname
= savestring (local_dirname
);
3239 /* no error messages, and expand_prompt_string doesn't longjmp so we don't
3240 have to worry about restoring this setting. */
3241 global_nounset
= unbound_vars_is_error
;
3242 unbound_vars_is_error
= 0;
3243 wl
= expand_prompt_string (new_dirname
, 0, W_NOCOMSUB
|W_NOPROCSUB
|W_COMPLETE
); /* does the right thing */
3244 unbound_vars_is_error
= global_nounset
;
3248 new_dirname
= string_list (wl
);
3249 /* Tell the completer we actually expanded something and change
3250 *dirname only if we expanded to something non-null -- stat
3251 behaves unpredictably when passed null or empty strings */
3252 if (new_dirname
&& *new_dirname
)
3254 free (local_dirname
); /* XXX */
3255 local_dirname
= *dirname
= new_dirname
;
3256 return_value
= STREQ (local_dirname
, *dirname
) == 0;
3266 /* This is very similar to the code in bash_directory_completion_hook below,
3267 but without spelling correction and not worrying about whether or not
3268 we change relative pathnames. */
3269 if (no_symbolic_links
== 0 && (local_dirname
[0] != '.' || local_dirname
[1]))
3271 char *temp1
, *temp2
;
3273 t
= get_working_directory ("symlink-hook");
3274 temp1
= make_absolute (local_dirname
, t
);
3276 temp2
= sh_canonpath (temp1
, PATH_CHECKDOTDOT
|PATH_CHECKEXISTS
);
3278 /* If we can't canonicalize, bail. */
3282 return return_value
;
3285 free (local_dirname
);
3290 return (return_value
);
3293 /* Handle symbolic link references and other directory name
3294 expansions while hacking completion. This should return 1 if it modifies
3295 the DIRNAME argument, 0 otherwise. It should make sure not to modify
3296 DIRNAME if it returns 0. */
3298 bash_directory_completion_hook (dirname
)
3301 char *local_dirname
, *new_dirname
, *t
;
3302 int return_value
, should_expand_dirname
, nextch
, closer
;
3305 return_value
= should_expand_dirname
= nextch
= closer
= 0;
3306 local_dirname
= *dirname
;
3308 if (t
= mbschr (local_dirname
, '$'))
3310 should_expand_dirname
= '$';
3312 /* Deliberately does not handle the deprecated $[...] arithmetic
3316 else if (nextch
== '{')
3326 delims
[0] = closer
; delims
[1] = 0;
3327 p
= skip_to_delim (t
, 1, delims
, SD_NOJMP
|SD_COMPLETE
);
3329 should_expand_dirname
= 0;
3332 else if (local_dirname
[0] == '~')
3333 should_expand_dirname
= '~';
3336 t
= mbschr (local_dirname
, '`');
3337 if (t
&& unclosed_pair (local_dirname
, strlen (local_dirname
), "`") == 0)
3338 should_expand_dirname
= '`';
3341 if (should_expand_dirname
&& directory_exists (local_dirname
, 1))
3342 should_expand_dirname
= 0;
3344 if (should_expand_dirname
)
3346 new_dirname
= savestring (local_dirname
);
3347 wl
= expand_prompt_string (new_dirname
, 0, W_NOCOMSUB
|W_NOPROCSUB
|W_COMPLETE
); /* does the right thing */
3350 *dirname
= string_list (wl
);
3351 /* Tell the completer to replace the directory name only if we
3352 actually expanded something. */
3353 return_value
= STREQ (local_dirname
, *dirname
) == 0;
3354 free (local_dirname
);
3357 local_dirname
= *dirname
;
3358 /* XXX - change rl_filename_quote_characters here based on
3359 should_expand_dirname/nextch/closer. This is the only place
3360 custom_filename_quote_characters is modified. */
3361 if (rl_filename_quote_characters
&& *rl_filename_quote_characters
)
3364 i
= strlen (default_filename_quote_characters
);
3365 custom_filename_quote_characters
= xrealloc (custom_filename_quote_characters
, i
+1);
3366 for (i
= j
= 0; c
= default_filename_quote_characters
[i
]; i
++)
3368 if (c
== should_expand_dirname
|| c
== nextch
|| c
== closer
)
3370 custom_filename_quote_characters
[j
++] = c
;
3372 custom_filename_quote_characters
[j
] = '\0';
3373 rl_filename_quote_characters
= custom_filename_quote_characters
;
3374 set_filename_bstab (rl_filename_quote_characters
);
3380 free (local_dirname
);
3381 *dirname
= (char *)xmalloc (1);
3388 /* Dequote the filename even if we don't expand it. */
3389 new_dirname
= bash_dequote_filename (local_dirname
, rl_completion_quote_character
);
3390 return_value
= STREQ (local_dirname
, new_dirname
) == 0;
3391 free (local_dirname
);
3392 local_dirname
= *dirname
= new_dirname
;
3395 /* no_symbolic_links == 0 -> use (default) logical view of the file system.
3396 local_dirname[0] == '.' && local_dirname[1] == '/' means files in the
3397 current directory (./).
3398 local_dirname[0] == '.' && local_dirname[1] == 0 means relative pathnames
3399 in the current directory (e.g., lib/sh).
3400 XXX - should we do spelling correction on these? */
3402 /* This is test as it was in bash-4.2: skip relative pathnames in current
3403 directory. Change test to
3404 (local_dirname[0] != '.' || (local_dirname[1] && local_dirname[1] != '/'))
3405 if we want to skip paths beginning with ./ also. */
3406 if (no_symbolic_links
== 0 && (local_dirname
[0] != '.' || local_dirname
[1]))
3408 char *temp1
, *temp2
;
3411 /* If we have a relative path
3412 (local_dirname[0] != '/' && local_dirname[0] != '.')
3413 that is canonical after appending it to the current directory, then
3416 strcmp (temp1, temp2) == 0
3417 after adding a slash to temp2 below. It should be safe to not
3420 t
= get_working_directory ("symlink-hook");
3421 temp1
= make_absolute (local_dirname
, t
);
3423 temp2
= sh_canonpath (temp1
, PATH_CHECKDOTDOT
|PATH_CHECKEXISTS
);
3425 /* Try spelling correction if initial canonicalization fails. Make
3426 sure we are set to replace the directory name with the results so
3427 subsequent directory checks don't fail. */
3428 if (temp2
== 0 && dircomplete_spelling
&& dircomplete_expand
)
3430 temp2
= dirspell (temp1
);
3435 temp2
= sh_canonpath (temp1
, PATH_CHECKDOTDOT
|PATH_CHECKEXISTS
);
3436 return_value
|= temp2
!= 0;
3439 /* If we can't canonicalize, bail. */
3443 return return_value
;
3445 len1
= strlen (temp1
);
3446 if (temp1
[len1
- 1] == '/')
3448 len2
= strlen (temp2
);
3449 if (len2
> 2) /* don't append `/' to `/' or `//' */
3451 temp2
= (char *)xrealloc (temp2
, len2
+ 2);
3453 temp2
[len2
+ 1] = '\0';
3457 /* dircomplete_expand_relpath == 0 means we want to leave relative
3458 pathnames that are unchanged by canonicalization alone.
3459 *local_dirname != '/' && *local_dirname != '.' == relative pathname
3460 (consistent with general.c:absolute_pathname())
3461 temp1 == temp2 (after appending a slash to temp2) means the pathname
3462 is not changed by canonicalization as described above. */
3463 if (dircomplete_expand_relpath
|| ((local_dirname
[0] != '/' && local_dirname
[0] != '.') && STREQ (temp1
, temp2
) == 0))
3464 return_value
|= STREQ (local_dirname
, temp2
) == 0;
3465 free (local_dirname
);
3470 return (return_value
);
3473 static char **history_completion_array
= (char **)NULL
;
3474 static int harry_size
;
3475 static int harry_len
;
3478 build_history_completion_array ()
3484 /* First, clear out the current dynamic history completion list. */
3487 strvec_dispose (history_completion_array
);
3488 history_completion_array
= (char **)NULL
;
3493 /* Next, grovel each line of history, making each shell-sized token
3494 a separate entry in the history_completion_array. */
3495 hlist
= history_list ();
3499 for (i
= 0; hlist
[i
]; i
++)
3501 for ( --i
; i
>= 0; i
--)
3503 /* Separate each token, and place into an array. */
3504 tokens
= history_tokenize (hlist
[i
]->line
);
3506 for (j
= 0; tokens
&& tokens
[j
]; j
++)
3508 if (harry_len
+ 2 > harry_size
)
3509 history_completion_array
= strvec_resize (history_completion_array
, harry_size
+= 10);
3511 history_completion_array
[harry_len
++] = tokens
[j
];
3512 history_completion_array
[harry_len
] = (char *)NULL
;
3517 /* Sort the complete list of tokens. */
3518 if (dabbrev_expand_active
== 0)
3519 qsort (history_completion_array
, harry_len
, sizeof (char *), (QSFUNC
*)strvec_strcmp
);
3524 history_completion_generator (hint_text
, state
)
3525 const char *hint_text
;
3528 static int local_index
, len
;
3529 static const char *text
;
3531 /* If this is the first call to the generator, then initialize the
3532 list of strings to complete over. */
3535 if (dabbrev_expand_active
) /* This is kind of messy */
3536 rl_completion_suppress_append
= 1;
3538 build_history_completion_array ();
3540 len
= strlen (text
);
3543 while (history_completion_array
&& history_completion_array
[local_index
])
3545 /* XXX - should this use completion-ignore-case? */
3546 if (strncmp (text
, history_completion_array
[local_index
++], len
) == 0)
3547 return (savestring (history_completion_array
[local_index
- 1]));
3549 return ((char *)NULL
);
3553 dynamic_complete_history (count
, key
)
3557 rl_compentry_func_t
*orig_func
;
3558 rl_completion_func_t
*orig_attempt_func
;
3559 rl_compignore_func_t
*orig_ignore_func
;
3561 orig_func
= rl_completion_entry_function
;
3562 orig_attempt_func
= rl_attempted_completion_function
;
3563 orig_ignore_func
= rl_ignore_some_completions_function
;
3565 rl_completion_entry_function
= history_completion_generator
;
3566 rl_attempted_completion_function
= (rl_completion_func_t
*)NULL
;
3567 rl_ignore_some_completions_function
= filename_completion_ignore
;
3569 /* XXX - use rl_completion_mode here? */
3570 if (rl_last_func
== dynamic_complete_history
)
3571 r
= rl_complete_internal ('?');
3573 r
= rl_complete_internal (TAB
);
3575 rl_completion_entry_function
= orig_func
;
3576 rl_attempted_completion_function
= orig_attempt_func
;
3577 rl_ignore_some_completions_function
= orig_ignore_func
;
3583 bash_dabbrev_expand (count
, key
)
3586 int r
, orig_suppress
, orig_sort
;
3587 rl_compentry_func_t
*orig_func
;
3588 rl_completion_func_t
*orig_attempt_func
;
3589 rl_compignore_func_t
*orig_ignore_func
;
3591 orig_func
= rl_menu_completion_entry_function
;
3592 orig_attempt_func
= rl_attempted_completion_function
;
3593 orig_ignore_func
= rl_ignore_some_completions_function
;
3594 orig_suppress
= rl_completion_suppress_append
;
3595 orig_sort
= rl_sort_completion_matches
;
3597 rl_menu_completion_entry_function
= history_completion_generator
;
3598 rl_attempted_completion_function
= (rl_completion_func_t
*)NULL
;
3599 rl_ignore_some_completions_function
= filename_completion_ignore
;
3600 rl_filename_completion_desired
= 0;
3601 rl_completion_suppress_append
= 1;
3602 rl_sort_completion_matches
= 0;
3604 /* XXX - use rl_completion_mode here? */
3605 dabbrev_expand_active
= 1;
3606 if (rl_last_func
== bash_dabbrev_expand
)
3607 rl_last_func
= rl_menu_complete
;
3608 r
= rl_menu_complete (count
, key
);
3609 dabbrev_expand_active
= 0;
3611 rl_last_func
= bash_dabbrev_expand
;
3612 rl_menu_completion_entry_function
= orig_func
;
3613 rl_attempted_completion_function
= orig_attempt_func
;
3614 rl_ignore_some_completions_function
= orig_ignore_func
;
3615 rl_completion_suppress_append
= orig_suppress
;
3616 rl_sort_completion_matches
= orig_sort
;
3621 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
3623 bash_complete_username (ignore
, ignore2
)
3624 int ignore
, ignore2
;
3626 return bash_complete_username_internal (rl_completion_mode (bash_complete_username
));
3630 bash_possible_username_completions (ignore
, ignore2
)
3631 int ignore
, ignore2
;
3633 return bash_complete_username_internal ('?');
3637 bash_complete_username_internal (what_to_do
)
3640 return bash_specific_completion (what_to_do
, rl_username_completion_function
);
3644 bash_complete_filename (ignore
, ignore2
)
3645 int ignore
, ignore2
;
3647 return bash_complete_filename_internal (rl_completion_mode (bash_complete_filename
));
3651 bash_possible_filename_completions (ignore
, ignore2
)
3652 int ignore
, ignore2
;
3654 return bash_complete_filename_internal ('?');
3658 bash_complete_filename_internal (what_to_do
)
3661 rl_compentry_func_t
*orig_func
;
3662 rl_completion_func_t
*orig_attempt_func
;
3663 rl_icppfunc_t
*orig_dir_func
;
3664 rl_compignore_func_t
*orig_ignore_func
;
3665 /*const*/ char *orig_rl_completer_word_break_characters
;
3668 orig_func
= rl_completion_entry_function
;
3669 orig_attempt_func
= rl_attempted_completion_function
;
3670 orig_ignore_func
= rl_ignore_some_completions_function
;
3671 orig_rl_completer_word_break_characters
= rl_completer_word_break_characters
;
3673 orig_dir_func
= save_directory_hook ();
3675 rl_completion_entry_function
= rl_filename_completion_function
;
3676 rl_attempted_completion_function
= (rl_completion_func_t
*)NULL
;
3677 rl_ignore_some_completions_function
= filename_completion_ignore
;
3678 rl_completer_word_break_characters
= " \t\n\"\'";
3680 r
= rl_complete_internal (what_to_do
);
3682 rl_completion_entry_function
= orig_func
;
3683 rl_attempted_completion_function
= orig_attempt_func
;
3684 rl_ignore_some_completions_function
= orig_ignore_func
;
3685 rl_completer_word_break_characters
= orig_rl_completer_word_break_characters
;
3687 restore_directory_hook (orig_dir_func
);
3693 bash_complete_hostname (ignore
, ignore2
)
3694 int ignore
, ignore2
;
3696 return bash_complete_hostname_internal (rl_completion_mode (bash_complete_hostname
));
3700 bash_possible_hostname_completions (ignore
, ignore2
)
3701 int ignore
, ignore2
;
3703 return bash_complete_hostname_internal ('?');
3707 bash_complete_variable (ignore
, ignore2
)
3708 int ignore
, ignore2
;
3710 return bash_complete_variable_internal (rl_completion_mode (bash_complete_variable
));
3714 bash_possible_variable_completions (ignore
, ignore2
)
3715 int ignore
, ignore2
;
3717 return bash_complete_variable_internal ('?');
3721 bash_complete_command (ignore
, ignore2
)
3722 int ignore
, ignore2
;
3724 return bash_complete_command_internal (rl_completion_mode (bash_complete_command
));
3728 bash_possible_command_completions (ignore
, ignore2
)
3729 int ignore
, ignore2
;
3731 return bash_complete_command_internal ('?');
3735 bash_complete_hostname_internal (what_to_do
)
3738 return bash_specific_completion (what_to_do
, hostname_completion_function
);
3742 bash_complete_variable_internal (what_to_do
)
3745 return bash_specific_completion (what_to_do
, variable_completion_function
);
3749 bash_complete_command_internal (what_to_do
)
3752 return bash_specific_completion (what_to_do
, command_word_completion_function
);
3756 completion_glob_pattern (string
)
3766 send
= string
+ strlen (string
);
3768 while (c
= *string
++)
3788 if (*string
== '(') /*)*/
3797 /* Advance one fewer byte than an entire multibyte character to
3798 account for the auto-increment in the loop above. */
3799 #ifdef HANDLE_MULTIBYTE
3801 ADVANCE_CHAR_P (string
, send
- string
);
3804 ADVANCE_CHAR_P (string
, send
- string
);
3810 static char *globtext
;
3811 static char *globorig
;
3814 glob_complete_word (text
, state
)
3818 static char **matches
= (char **)NULL
;
3825 rl_filename_completion_desired
= 1;
3827 if (globorig
!= globtext
)
3831 ttext
= bash_tilde_expand (text
, 0);
3833 if (rl_explicit_arg
)
3835 globorig
= savestring (ttext
);
3836 glen
= strlen (ttext
);
3837 globtext
= (char *)xmalloc (glen
+ 2);
3838 strcpy (globtext
, ttext
);
3839 globtext
[glen
] = '*';
3840 globtext
[glen
+1] = '\0';
3843 globtext
= globorig
= savestring (ttext
);
3848 matches
= shell_glob_filename (globtext
);
3849 if (GLOB_FAILED (matches
))
3850 matches
= (char **)NULL
;
3854 ret
= matches
? matches
[ind
] : (char *)NULL
;
3860 bash_glob_completion_internal (what_to_do
)
3863 return bash_specific_completion (what_to_do
, glob_complete_word
);
3866 /* A special quoting function so we don't end up quoting globbing characters
3867 in the word if there are no matches or multiple matches. */
3869 bash_glob_quote_filename (s
, rtype
, qcp
)
3874 if (globorig
&& qcp
&& *qcp
== '\0' && STREQ (s
, globorig
))
3875 return (savestring (s
));
3877 return (bash_quote_filename (s
, rtype
, qcp
));
3881 bash_glob_complete_word (count
, key
)
3885 rl_quote_func_t
*orig_quoting_function
;
3887 if (rl_editing_mode
== EMACS_EDITING_MODE
)
3888 rl_explicit_arg
= 1; /* force `*' append */
3889 orig_quoting_function
= rl_filename_quoting_function
;
3890 rl_filename_quoting_function
= bash_glob_quote_filename
;
3892 r
= bash_glob_completion_internal (rl_completion_mode (bash_glob_complete_word
));
3894 rl_filename_quoting_function
= orig_quoting_function
;
3899 bash_glob_expand_word (count
, key
)
3902 return bash_glob_completion_internal ('*');
3906 bash_glob_list_expansions (count
, key
)
3909 return bash_glob_completion_internal ('?');
3913 bash_specific_completion (what_to_do
, generator
)
3915 rl_compentry_func_t
*generator
;
3917 rl_compentry_func_t
*orig_func
;
3918 rl_completion_func_t
*orig_attempt_func
;
3919 rl_compignore_func_t
*orig_ignore_func
;
3922 orig_func
= rl_completion_entry_function
;
3923 orig_attempt_func
= rl_attempted_completion_function
;
3924 orig_ignore_func
= rl_ignore_some_completions_function
;
3925 rl_completion_entry_function
= generator
;
3926 rl_attempted_completion_function
= NULL
;
3927 rl_ignore_some_completions_function
= orig_ignore_func
;
3929 r
= rl_complete_internal (what_to_do
);
3931 rl_completion_entry_function
= orig_func
;
3932 rl_attempted_completion_function
= orig_attempt_func
;
3933 rl_ignore_some_completions_function
= orig_ignore_func
;
3938 #endif /* SPECIFIC_COMPLETION_FUNCTIONS */
3940 #if defined (VI_MODE)
3941 /* Completion, from vi mode's point of view. This is a modified version of
3942 rl_vi_complete which uses the bash globbing code to implement what POSIX
3943 specifies, which is to append a `*' and attempt filename generation (which
3944 has the side effect of expanding any globbing characters in the word). */
3946 bash_vi_complete (count
, key
)
3949 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
3953 if ((rl_point
< rl_end
) && (!whitespace (rl_line_buffer
[rl_point
])))
3955 if (!whitespace (rl_line_buffer
[rl_point
+ 1]))
3956 rl_vi_end_word (1, 'E');
3960 /* Find boundaries of current word, according to vi definition of a
3966 rl_vi_bWord (1, 'B');
3971 t
= substring (rl_line_buffer
, p
, rl_point
);
3974 if (t
&& completion_glob_pattern (t
) == 0)
3975 rl_explicit_arg
= 1; /* XXX - force glob_complete_word to append `*' */
3978 if (key
== '*') /* Expansion and replacement. */
3979 r
= bash_glob_expand_word (count
, key
);
3980 else if (key
== '=') /* List possible completions. */
3981 r
= bash_glob_list_expansions (count
, key
);
3982 else if (key
== '\\') /* Standard completion */
3983 r
= bash_glob_complete_word (count
, key
);
3985 r
= rl_complete (0, key
);
3987 if (key
== '*' || key
== '\\')
3988 rl_vi_start_inserting (key
, 1, 1);
3992 return rl_vi_complete (count
, key
);
3993 #endif /* !SPECIFIC_COMPLETION_FUNCTIONS */
3995 #endif /* VI_MODE */
3997 /* Filename quoting for completion. */
3998 /* A function to strip unquoted quote characters (single quotes, double
3999 quotes, and backslashes). It allows single quotes to appear
4000 within double quotes, and vice versa. It should be smarter. */
4002 bash_dequote_filename (text
, quote_char
)
4010 ret
= (char *)xmalloc (l
+ 1);
4011 for (quoted
= quote_char
, p
= text
, r
= ret
; p
&& *p
; p
++)
4013 /* Allow backslash-escaped characters to pass through unscathed. */
4016 /* Backslashes are preserved within single quotes. */
4019 /* Backslashes are preserved within double quotes unless the
4020 character is one that is defined to be escaped */
4021 else if (quoted
== '"' && ((sh_syntaxtab
[(unsigned char)p
[1]] & CBSDQUOTE
) == 0))
4026 return ret
; /* XXX - was break; */
4030 if (quoted
&& *p
== quoted
)
4036 if (quoted
== 0 && (*p
== '\'' || *p
== '"'))
4047 /* Quote characters that the readline completion code would treat as
4048 word break characters with backslashes. Pass backslash-quoted
4049 characters through without examination. */
4051 quote_word_break_chars (text
)
4058 ret
= (char *)xmalloc ((2 * l
) + 1);
4059 for (s
= text
, r
= ret
; *s
; s
++)
4061 /* Pass backslash-quoted characters through, including the backslash. */
4070 /* OK, we have an unquoted character. Check its presence in
4071 rl_completer_word_break_characters. */
4072 if (mbschr (rl_completer_word_break_characters
, *s
))
4074 /* XXX -- check for standalone tildes here and backslash-quote them */
4075 if (s
== text
&& *s
== '~' && file_exists (text
))
4083 /* Use characters in STRING to populate the table of characters that should
4084 be backslash-quoted. The table will be used for sh_backslash_quote from
4087 set_filename_bstab (string
)
4092 memset (filename_bstab
, 0, sizeof (filename_bstab
));
4093 for (s
= string
; s
&& *s
; s
++)
4094 filename_bstab
[*s
] = 1;
4097 /* Quote a filename using double quotes, single quotes, or backslashes
4098 depending on the value of completion_quoting_style. If we're
4099 completing using backslashes, we need to quote some additional
4100 characters (those that readline treats as word breaks), so we call
4101 quote_word_break_chars on the result. This returns newly-allocated
4104 bash_quote_filename (s
, rtype
, qcp
)
4109 char *rtext
, *mtext
, *ret
;
4112 rtext
= (char *)NULL
;
4114 /* If RTYPE == MULT_MATCH, it means that there is
4115 more than one match. In this case, we do not add
4116 the closing quote or attempt to perform tilde
4117 expansion. If RTYPE == SINGLE_MATCH, we try
4118 to perform tilde expansion, because single and double
4119 quotes inhibit tilde expansion by the shell. */
4121 cs
= completion_quoting_style
;
4122 /* Might need to modify the default completion style based on *qcp,
4123 since it's set to any user-provided opening quote. We also change
4124 to single-quoting if there is no user-provided opening quote and
4125 the word being completed contains newlines, since those are not
4126 quoted correctly using backslashes (a backslash-newline pair is
4127 special to the shell parser). */
4128 if (*qcp
== '\0' && cs
== COMPLETE_BSQUOTE
&& mbschr (s
, '\n'))
4129 cs
= COMPLETE_SQUOTE
;
4130 else if (*qcp
== '"')
4131 cs
= COMPLETE_DQUOTE
;
4132 else if (*qcp
== '\'')
4133 cs
= COMPLETE_SQUOTE
;
4134 #if defined (BANG_HISTORY)
4135 else if (*qcp
== '\0' && history_expansion
&& cs
== COMPLETE_DQUOTE
&&
4136 history_expansion_inhibited
== 0 && mbschr (s
, '!'))
4137 cs
= COMPLETE_BSQUOTE
;
4139 if (*qcp
== '"' && history_expansion
&& cs
== COMPLETE_DQUOTE
&&
4140 history_expansion_inhibited
== 0 && mbschr (s
, '!'))
4142 cs
= COMPLETE_BSQUOTE
;
4147 /* Don't tilde-expand backslash-quoted filenames, since only single and
4148 double quotes inhibit tilde expansion. */
4150 if (mtext
[0] == '~' && rtype
== SINGLE_MATCH
&& cs
!= COMPLETE_BSQUOTE
)
4151 mtext
= bash_tilde_expand (s
, 0);
4155 case COMPLETE_DQUOTE
:
4156 rtext
= sh_double_quote (mtext
);
4158 case COMPLETE_SQUOTE
:
4159 rtext
= sh_single_quote (mtext
);
4161 case COMPLETE_BSQUOTE
:
4162 rtext
= sh_backslash_quote (mtext
, complete_fullquote
? 0 : filename_bstab
, 0);
4169 /* We may need to quote additional characters: those that readline treats
4170 as word breaks that are not quoted by backslash_quote. */
4171 if (rtext
&& cs
== COMPLETE_BSQUOTE
)
4173 mtext
= quote_word_break_chars (rtext
);
4178 /* Leave the opening quote intact. The readline completion code takes
4179 care of avoiding doubled opening quotes. */
4182 rlen
= strlen (rtext
);
4183 ret
= (char *)xmalloc (rlen
+ 1);
4184 strcpy (ret
, rtext
);
4188 ret
= (char *)xmalloc (rlen
= 1);
4192 /* If there are multiple matches, cut off the closing quote. */
4193 if (rtype
== MULT_MATCH
&& cs
!= COMPLETE_BSQUOTE
)
4194 ret
[rlen
- 1] = '\0';
4199 /* Support for binding readline key sequences to Unix commands. */
4200 static Keymap cmd_xmap
;
4211 x
= putc (c
, rl_outstream
);
4218 bash_execute_unix_command (count
, key
)
4219 int count
; /* ignored */
4225 sh_parser_state_t ps
;
4226 char *cmd
, *value
, *ce
, old_ch
;
4228 char ibuf
[INT_STRLEN_BOUND(int) + 1];
4230 /* First, we need to find the right command to execute. This is tricky,
4231 because we might have already indirected into another keymap, so we
4232 have to walk cmd_xmap using the entire key sequence. */
4233 cmd
= (char *)rl_function_of_keyseq_len (rl_executing_keyseq
, rl_key_sequence_length
, cmd_xmap
, &type
);
4235 if (cmd
== 0 || type
!= ISMACR
)
4238 internal_error (_("bash_execute_unix_command: cannot find keymap for command"));
4239 rl_forced_update_display ();
4243 ce
= rl_get_termcap ("ce");
4244 if (ce
) /* clear current line */
4247 fprintf (rl_outstream
, "\r");
4248 tputs (ce
, 1, putx
);
4250 rl_clear_visible_line ();
4252 fflush (rl_outstream
);
4255 rl_crlf (); /* move to a new line */
4257 v
= bind_variable ("READLINE_LINE", rl_line_buffer
, 0);
4259 VSETATTR (v
, att_exported
);
4261 #if defined (HANDLE_MULTIBYTE)
4264 old_ch
= rl_line_buffer
[rl_point
];
4265 rl_line_buffer
[rl_point
] = '\0';
4266 i
= MB_STRLEN (rl_line_buffer
);
4267 rl_line_buffer
[rl_point
] = old_ch
;
4270 value
= inttostr (i
, ibuf
, sizeof (ibuf
));
4271 v
= bind_int_variable ("READLINE_POINT", value
, 0);
4273 VSETATTR (v
, att_exported
);
4274 array_needs_making
= 1;
4276 save_parser_state (&ps
);
4277 r
= parse_and_execute (savestring (cmd
), "bash_execute_unix_command", SEVAL_NOHIST
|SEVAL_NOFREE
);
4278 restore_parser_state (&ps
);
4280 v
= find_variable ("READLINE_LINE");
4281 maybe_make_readline_line (v
? value_cell (v
) : 0);
4283 v
= find_variable ("READLINE_POINT");
4284 if (v
&& legal_number (value_cell (v
), &mi
))
4287 #if defined (HANDLE_MULTIBYTE)
4288 if (i
> 0 && MB_CUR_MAX
> 1)
4289 i
= _rl_find_next_mbchar (rl_line_buffer
, 0, i
, 0);
4294 if (rl_point
> rl_end
)
4296 else if (rl_point
< 0)
4301 check_unbind_variable ("READLINE_LINE");
4302 check_unbind_variable ("READLINE_POINT");
4303 array_needs_making
= 1;
4305 /* and restore the readline buffer and display after command execution. */
4306 /* If we clear the last line of the prompt above, redraw only that last
4307 line. If the command returns 124, we redraw unconditionally as in
4308 previous versions. */
4310 rl_redraw_prompt_last_line ();
4312 rl_forced_update_display ();
4318 print_unix_command_map ()
4322 save
= rl_get_keymap ();
4323 rl_set_keymap (cmd_xmap
);
4324 rl_macro_dumper (1);
4325 rl_set_keymap (save
);
4330 init_unix_command_map ()
4332 cmd_xmap
= rl_make_bare_keymap ();
4336 isolate_sequence (string
, ind
, need_dquote
, startp
)
4338 int ind
, need_dquote
, *startp
;
4341 int c
, passc
, delim
;
4343 for (i
= ind
; string
[i
] && whitespace (string
[i
]); i
++)
4345 /* NEED_DQUOTE means that the first non-white character *must* be `"'. */
4346 if (need_dquote
&& string
[i
] != '"')
4348 builtin_error (_("%s: first non-whitespace character is not `\"'"), string
);
4352 /* We can have delimited strings even if NEED_DQUOTE == 0, like the command
4353 string to bind the key sequence to. */
4354 delim
= (string
[i
] == '"' || string
[i
] == '\'') ? string
[i
] : 0;
4357 *startp
= delim
? ++i
: i
;
4359 for (passc
= 0; c
= string
[i
]; i
++)
4375 if (delim
&& string
[i
] != delim
)
4377 builtin_error (_("no closing `%c' in %s"), delim
, string
);
4385 bind_keyseq_to_unix_command (line
)
4393 init_unix_command_map ();
4395 kmap
= rl_get_keymap ();
4397 /* We duplicate some of the work done by rl_parse_and_bind here, but
4398 this code only has to handle `"keyseq": ["]command["]' and can
4399 generate an error for anything else. */
4400 i
= isolate_sequence (line
, 0, 1, &kstart
);
4404 /* Create the key sequence string to pass to rl_generic_bind */
4405 kseq
= substring (line
, kstart
, i
);
4407 for ( ; line
[i
] && line
[i
] != ':'; i
++)
4411 builtin_error (_("%s: missing colon separator"), line
);
4416 i
= isolate_sequence (line
, i
+ 1, 0, &kstart
);
4423 /* Create the value string containing the command to execute. */
4424 value
= substring (line
, kstart
, i
);
4426 /* Save the command to execute and the key sequence in the CMD_XMAP */
4427 rl_generic_bind (ISMACR
, kseq
, value
, cmd_xmap
);
4429 /* and bind the key sequence in the current keymap to a function that
4430 understands how to execute from CMD_XMAP */
4431 rl_bind_keyseq_in_map (kseq
, bash_execute_unix_command
, kmap
);
4437 /* Used by the programmable completion code. Complete TEXT as a filename,
4438 but return only directories as matches. Dequotes the filename before
4439 attempting to find matches. */
4441 bash_directory_completion_matches (text
)
4448 qc
= rl_dispatching
? rl_completion_quote_character
: 0;
4449 /* If rl_completion_found_quote != 0, rl_completion_matches will call the
4450 filename dequoting function, causing the directory name to be dequoted
4452 if (rl_dispatching
&& rl_completion_found_quote
== 0)
4453 dfn
= bash_dequote_filename ((char *)text
, qc
);
4456 m1
= rl_completion_matches (dfn
, rl_filename_completion_function
);
4460 if (m1
== 0 || m1
[0] == 0)
4462 /* We don't bother recomputing the lcd of the matches, because it will just
4463 get thrown away by the programmable completion code and recomputed
4465 (void)bash_progcomp_ignore_filenames (m1
);
4470 bash_dequote_text (text
)
4476 qc
= (text
[0] == '"' || text
[0] == '\'') ? text
[0] : 0;
4477 dtxt
= bash_dequote_filename ((char *)text
, qc
);
4481 /* This event hook is designed to be called after readline receives a signal
4482 that interrupts read(2). It gives reasonable responsiveness to interrupts
4483 and fatal signals without executing too much code in a signal handler
4488 /* If we're going to longjmp to top_level, make sure we clean up readline.
4489 check_signals will call QUIT, which will eventually longjmp to top_level,
4490 calling run_interrupt_trap along the way. The check for sigalrm_seen is
4491 to clean up the read builtin's state. */
4492 if (terminating_signal
|| interrupt_state
|| sigalrm_seen
)
4493 rl_cleanup_after_signal ();
4494 bashline_reset_event_hook ();
4495 check_signals_and_traps (); /* XXX */
4499 #endif /* READLINE */