1 /* bashline.c -- Bash's interface to the readline library. */
3 /* Copyright (C) 1987-2024 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"
61 #if defined (HAVE_MBSTR_H) && defined (HAVE_MBSCHR)
62 # include <mbstr.h> /* mbschr */
65 #include "builtins/common.h"
66 #include "builtins/builtext.h" /* for read_builtin */
68 #include <readline/rlconf.h>
69 #include <readline/readline.h>
70 #include <readline/history.h>
71 #include <readline/rlmbutil.h>
73 #include <glob/glob.h>
79 #if defined (PROGRAMMABLE_COMPLETION)
80 # include "pcomplete.h"
83 /* These should agree with the defines for emacs_mode and vi_mode in
84 rldefs.h, even though that's not a public readline header file. */
85 #ifndef EMACS_EDITING_MODE
86 # define NO_EDITING_MODE -1
87 # define EMACS_EDITING_MODE 1
88 # define VI_EDITING_MODE 0
91 /* Copied from rldefs.h, since that's not a public readline header file. */
92 #ifndef FUNCTION_TO_KEYMAP
95 # define FUNCTION_TO_KEYMAP(map, key) (Keymap)((int)map[key].function)
96 # define KEYMAP_TO_FUNCTION(data) (rl_command_func_t *)((int)(data))
98 # define FUNCTION_TO_KEYMAP(map, key) (Keymap)(map[key].function)
99 # define KEYMAP_TO_FUNCTION(data) (rl_command_func_t *)(data)
104 #define RL_BOOLEAN_VARIABLE_VALUE(s) ((s)[0] == 'o' && (s)[1] == 'n' && (s)[2] == '\0')
106 #if defined (BRACE_COMPLETION)
107 extern int bash_brace_completion (int, int);
108 #endif /* BRACE_COMPLETION */
110 /* To avoid including curses.h/term.h/termcap.h and that whole mess. */
112 extern int tputs (const char *string
, int nlines
, void (*outx
)(int));
114 extern int tputs (const char *string
, int nlines
, int (*outx
)(int));
117 /* Forward declarations */
119 /* Functions bound to keys in Readline for Bash users. */
120 static int shell_expand_line (int, int);
121 static int display_shell_version (int, int);
123 static int bash_ignore_filenames (char **);
124 static int bash_ignore_everything (char **);
125 static int bash_progcomp_ignore_filenames (char **);
127 #if defined (BANG_HISTORY)
128 static char *history_expand_line_internal (char *);
129 static int history_expand_line (int, int);
130 static int tcsh_magic_space (int, int);
131 #endif /* BANG_HISTORY */
133 static int alias_expand_line (int, int);
135 #if defined (BANG_HISTORY) && defined (ALIAS)
136 static int history_and_alias_expand_line (int, int);
139 static int bash_forward_shellword (int, int);
140 static int bash_backward_shellword (int, int);
141 static int bash_kill_shellword (int, int);
142 static int bash_backward_kill_shellword (int, int);
143 static int bash_transpose_shellwords (int, int);
145 static int bash_spell_correct_shellword (int, int);
147 /* Helper functions for Readline. */
148 static char *restore_tilde (const char *, char *);
149 static char *maybe_restore_tilde (char *, char *);
151 static char *bash_filename_rewrite_hook (char *, int);
153 static void bash_directory_expansion (char **);
154 static char *bash_expand_filename (char *);
155 static int bash_filename_stat_hook (char **);
156 static int bash_command_name_stat_hook (char **);
157 static int bash_directory_completion_hook (char **);
158 static int filename_completion_ignore (char **);
159 static int bash_push_line (void);
161 static int executable_completion (const char *, int);
163 static rl_icppfunc_t
*save_directory_hook (void);
164 static void restore_directory_hook (rl_icppfunc_t
);
166 static int directory_exists (const char *, int);
168 static void cleanup_expansion_error (void);
169 static void maybe_make_readline_line (const char *);
170 static void set_up_new_line (char *);
172 static int check_redir (int);
173 static char **attempt_shell_completion (const char *, int, int);
174 static char *variable_completion_function (const char *, int);
175 static char *hostname_completion_function (const char *, int);
176 static char *command_subst_completion_function (const char *, int);
178 static void build_history_completion_array (void);
179 static char *history_completion_generator (const char *, int);
180 static int dynamic_complete_history (int, int);
181 static int bash_dabbrev_expand (int, int);
183 static void initialize_hostname_list (void);
184 static void add_host_name (const char *);
185 static void snarf_hosts_from_file (const char *);
186 static char **hostnames_matching (const char *);
188 static void _ignore_completion_names (char **, sh_ignore_func_t
*);
189 static int name_is_acceptable (const char *);
190 static int test_for_directory (const char *);
191 static int test_for_canon_directory (const char *);
192 static int return_zero (const char *);
194 static char *bash_dequote_filename (char *, int);
195 static char *quote_word_break_chars (char *);
196 static int bash_check_expchar (char *, int, int *, int *);
197 static void set_filename_quote_chars (int, int, int);
198 static void set_filename_bstab (const char *);
199 static char *bash_quote_filename (char *, int, char *);
202 static void putx (int);
204 static int putx (int);
206 static int readline_get_char_offset (int);
207 static void readline_set_char_offset (int, int *);
209 static Keymap
get_cmd_xmap_from_edit_mode (void);
210 static Keymap
get_cmd_xmap_from_keymap (Keymap
);
212 static void init_unix_command_map (void);
213 static int isolate_sequence (char *, int, int, int *);
215 static int set_saved_history (void);
218 static int posix_edit_macros (int, int);
221 static int bash_event_hook (void);
223 #if defined (PROGRAMMABLE_COMPLETION)
224 static int find_cmd_start (int);
225 static int find_cmd_end (int);
226 static char *find_cmd_name (int, int *, int *);
227 static char *prog_complete_return (const char *, int);
229 static char **prog_complete_matches
;
232 extern int no_symbolic_links
;
233 extern STRING_INT_ALIST word_token_alist
[];
234 extern sh_timer
*read_timeout
;
236 /* SPECIFIC_COMPLETION_FUNCTIONS specifies that we have individual
237 completion functions which indicate what type of completion should be
238 done (at or before point) that can be bound to key sequences with
239 the readline library. */
240 #define SPECIFIC_COMPLETION_FUNCTIONS
242 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
243 static int bash_specific_completion (int, rl_compentry_func_t
*);
245 static int bash_complete_filename_internal (int);
246 static int bash_complete_username_internal (int);
247 static int bash_complete_hostname_internal (int);
248 static int bash_complete_variable_internal (int);
249 static int bash_complete_command_internal (int);
251 static int bash_complete_filename (int, int);
252 static int bash_possible_filename_completions (int, int);
253 static int bash_complete_username (int, int);
254 static int bash_possible_username_completions (int, int);
255 static int bash_complete_hostname (int, int);
256 static int bash_possible_hostname_completions (int, int);
257 static int bash_complete_variable (int, int);
258 static int bash_possible_variable_completions (int, int);
259 static int bash_complete_command (int, int);
260 static int bash_possible_command_completions (int, int);
262 static int completion_glob_pattern (const char *);
263 static char *glob_complete_word (const char *, int);
264 static int bash_glob_completion_internal (int);
265 static int bash_glob_complete_word (int, int);
266 static int bash_glob_expand_word (int, int);
267 static int bash_glob_list_expansions (int, int);
269 #endif /* SPECIFIC_COMPLETION_FUNCTIONS */
271 static int edit_and_execute_command (int, int, int, const char *);
272 #if defined (VI_MODE)
273 static int vi_edit_and_execute_command (int, int);
274 static int bash_vi_complete (int, int);
276 static int emacs_edit_and_execute_command (int, int);
278 /* Non-zero once initialize_readline () has been called. */
279 int bash_readline_initialized
= 0;
281 /* If non-zero, we do hostname completion, breaking words at `@' and
282 trying to complete the stuff after the `@' from our own internal
284 int perform_hostname_completion
= 1;
286 /* If non-zero, we don't do command completion on an empty line. */
287 int no_empty_command_completion
;
289 /* Set FORCE_FIGNORE if you want to honor FIGNORE even if it ignores the
290 only possible matches. Set to 0 if you want to match filenames if they
291 are the only possible matches, even if FIGNORE says to. */
292 int force_fignore
= 1;
294 /* Perform spelling correction on directory names during word completion */
295 int dircomplete_spelling
= 0;
297 /* Expand directory names during word/filename completion. */
298 #if DIRCOMPLETE_EXPAND_DEFAULT
299 int dircomplete_expand
= 1;
300 int dircomplete_expand_relpath
= 1;
302 int dircomplete_expand
= 0;
303 int dircomplete_expand_relpath
= 0;
306 /* When non-zero, perform `normal' shell quoting on completed filenames
307 even when the completed name contains a directory name with a shell
308 variable reference, so dollar signs in a filename get quoted appropriately.
309 Set to zero to remove dollar sign (and braces or parens as needed) from
310 the set of characters that will be quoted. */
311 int complete_fullquote
= 1;
313 static char *bash_completer_word_break_characters
= " \t\n\"'@><=;|&(:";
314 static char *bash_nohostname_word_break_characters
= " \t\n\"'><=;|&(:";
317 static const char *default_filename_quote_characters
= " \t\n\\\"'@<>=;|&()#$`?*[!:{~"; /*}*/
318 static char *custom_filename_quote_characters
= 0;
319 static char filename_bstab
[256];
321 static rl_hook_func_t
*old_rl_startup_hook
= (rl_hook_func_t
*)NULL
;
323 static int dot_in_path
= 0;
325 /* Set to non-zero when dabbrev-expand is running */
326 static int dabbrev_expand_active
= 0;
328 /* What kind of quoting is performed by bash_quote_filename:
329 COMPLETE_DQUOTE = double-quoting the filename
330 COMPLETE_SQUOTE = single_quoting the filename
331 COMPLETE_BSQUOTE = backslash-quoting special chars in the filename
332 COMPLETE_DQUOTE2 = double-quote filename, but leave $ and ` unquoted
334 #define COMPLETE_DQUOTE 1
335 #define COMPLETE_SQUOTE 2
336 #define COMPLETE_BSQUOTE 3
337 #define COMPLETE_DQUOTE2 4
339 static int completion_quoting_style
= COMPLETE_BSQUOTE
;
341 /* Flag values for the final argument to bash_default_completion */
342 #define DEFCOMP_CMDPOS 1
344 static rl_command_func_t
*vi_tab_binding
= rl_complete
;
346 /* Change the readline VI-mode keymaps into or out of Posix.2 compliance.
347 Called when the shell is put into or out of `posix' mode. */
349 posix_readline_initialize (int on_or_off
)
351 static char kseq
[2] = { CTRL ('I'), 0 }; /* TAB */
354 rl_variable_bind ("comment-begin", "#");
355 #if defined (VI_MODE)
358 vi_tab_binding
= rl_function_of_keyseq (kseq
, vi_insertion_keymap
, (int *)NULL
);
359 rl_bind_key_in_map (CTRL ('I'), rl_insert
, vi_insertion_keymap
);
363 if (rl_function_of_keyseq (kseq
, vi_insertion_keymap
, (int *)NULL
) == rl_insert
)
364 rl_bind_key_in_map (CTRL ('I'), vi_tab_binding
, vi_insertion_keymap
);
370 reset_completer_word_break_chars (void)
372 rl_completer_word_break_characters
= perform_hostname_completion
? savestring (bash_completer_word_break_characters
) : savestring (bash_nohostname_word_break_characters
);
375 /* When this function returns, rl_completer_word_break_characters points to
376 dynamically allocated memory. */
378 enable_hostname_completion (int on_or_off
)
384 old_value
= perform_hostname_completion
;
388 perform_hostname_completion
= 1;
389 rl_special_prefixes
= "$@";
393 perform_hostname_completion
= 0;
394 rl_special_prefixes
= "$";
397 /* Now we need to figure out how to appropriately modify and assign
398 rl_completer_word_break_characters depending on whether we want
399 hostname completion on or off. */
401 /* If this is the first time this has been called
402 (bash_readline_initialized == 0), use the sames values as before, but
403 allocate new memory for rl_completer_word_break_characters. */
405 if (bash_readline_initialized
== 0 &&
406 (rl_completer_word_break_characters
== 0 ||
407 rl_completer_word_break_characters
== rl_basic_word_break_characters
))
410 rl_completer_word_break_characters
= savestring (bash_completer_word_break_characters
);
412 rl_completer_word_break_characters
= savestring (bash_nohostname_word_break_characters
);
416 /* See if we have anything to do. */
417 at
= strchr (rl_completer_word_break_characters
, '@');
418 if ((at
== 0 && on_or_off
== 0) || (at
!= 0 && on_or_off
!= 0))
421 /* We have something to do. Do it. */
422 nval
= (char *)xmalloc (strlen (rl_completer_word_break_characters
) + 1 + on_or_off
);
426 /* Turn it off -- just remove `@' from word break chars. We want
427 to remove all occurrences of `@' from the char list, so we loop
428 rather than just copy the rest of the list over AT. */
429 for (nv
= nval
, at
= rl_completer_word_break_characters
; *at
; )
439 strcpy (nval
+ 1, rl_completer_word_break_characters
);
442 free ((void *)rl_completer_word_break_characters
);
443 rl_completer_word_break_characters
= nval
;
449 /* Called once from parse.y if we are going to use readline. */
451 initialize_readline (void)
453 rl_command_func_t
*func
;
456 if (bash_readline_initialized
)
459 rl_terminal_name
= get_string_value ("TERM");
461 rl_outstream
= stderr
;
463 /* Allow conditional parsing of the ~/.inputrc file. */
464 rl_readline_name
= "Bash";
466 /* Add bindable names before calling rl_initialize so they may be
467 referenced in the various inputrc files. */
468 rl_add_defun ("shell-expand-line", shell_expand_line
, -1);
470 rl_add_defun ("history-expand-line", history_expand_line
, -1);
471 rl_add_defun ("magic-space", tcsh_magic_space
, -1);
474 rl_add_defun ("shell-forward-word", bash_forward_shellword
, -1);
475 rl_add_defun ("shell-backward-word", bash_backward_shellword
, -1);
476 rl_add_defun ("shell-kill-word", bash_kill_shellword
, -1);
477 rl_add_defun ("shell-backward-kill-word", bash_backward_kill_shellword
, -1);
478 rl_add_defun ("shell-transpose-words", bash_transpose_shellwords
, -1);
480 rl_add_defun ("spell-correct-word", bash_spell_correct_shellword
, -1);
481 rl_bind_key_if_unbound_in_map ('s', bash_spell_correct_shellword
, emacs_ctlx_keymap
);
484 rl_add_defun ("alias-expand-line", alias_expand_line
, -1);
486 rl_add_defun ("history-and-alias-expand-line", history_and_alias_expand_line
, -1);
490 /* Backwards compatibility. */
491 rl_add_defun ("insert-last-argument", rl_yank_last_arg
, -1);
493 rl_add_defun ("display-shell-version", display_shell_version
, -1);
494 rl_add_defun ("edit-and-execute-command", emacs_edit_and_execute_command
, -1);
495 #if defined (VI_MODE)
496 rl_add_defun ("vi-edit-and-execute-command", vi_edit_and_execute_command
, -1);
499 #if defined (BRACE_COMPLETION)
500 rl_add_defun ("complete-into-braces", bash_brace_completion
, -1);
503 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
504 rl_add_defun ("complete-filename", bash_complete_filename
, -1);
505 rl_add_defun ("possible-filename-completions", bash_possible_filename_completions
, -1);
506 rl_add_defun ("complete-username", bash_complete_username
, -1);
507 rl_add_defun ("possible-username-completions", bash_possible_username_completions
, -1);
508 rl_add_defun ("complete-hostname", bash_complete_hostname
, -1);
509 rl_add_defun ("possible-hostname-completions", bash_possible_hostname_completions
, -1);
510 rl_add_defun ("complete-variable", bash_complete_variable
, -1);
511 rl_add_defun ("possible-variable-completions", bash_possible_variable_completions
, -1);
512 rl_add_defun ("complete-command", bash_complete_command
, -1);
513 rl_add_defun ("possible-command-completions", bash_possible_command_completions
, -1);
514 rl_add_defun ("glob-complete-word", bash_glob_complete_word
, -1);
515 rl_add_defun ("glob-expand-word", bash_glob_expand_word
, -1);
516 rl_add_defun ("glob-list-expansions", bash_glob_list_expansions
, -1);
519 rl_add_defun ("dynamic-complete-history", dynamic_complete_history
, -1);
520 rl_add_defun ("dabbrev-expand", bash_dabbrev_expand
, -1);
522 /* Bind defaults before binding our custom shell keybindings. */
523 if (RL_ISSTATE(RL_STATE_INITIALIZED
) == 0)
526 /* Bind up our special shell functions. */
527 rl_bind_key_if_unbound_in_map (CTRL('E'), shell_expand_line
, emacs_meta_keymap
);
530 rl_bind_key_if_unbound_in_map ('^', history_expand_line
, emacs_meta_keymap
);
533 rl_bind_key_if_unbound_in_map (CTRL ('V'), display_shell_version
, emacs_ctlx_keymap
);
535 /* In Bash, the user can switch editing modes with "set -o [vi emacs]",
536 so it is not necessary to allow C-M-j for context switching. Turn
537 off this occasionally confusing behaviour. */
540 func
= rl_function_of_keyseq (kseq
, emacs_meta_keymap
, (int *)NULL
);
541 if (func
== rl_vi_editing_mode
)
542 rl_unbind_key_in_map (CTRL('J'), emacs_meta_keymap
);
544 func
= rl_function_of_keyseq (kseq
, emacs_meta_keymap
, (int *)NULL
);
545 if (func
== rl_vi_editing_mode
)
546 rl_unbind_key_in_map (CTRL('M'), emacs_meta_keymap
);
547 #if defined (VI_MODE)
549 func
= rl_function_of_keyseq (kseq
, vi_movement_keymap
, (int *)NULL
);
550 if (func
== rl_emacs_editing_mode
)
551 rl_unbind_key_in_map (CTRL('E'), vi_movement_keymap
);
554 #if defined (BRACE_COMPLETION)
555 rl_bind_key_if_unbound_in_map ('{', bash_brace_completion
, emacs_meta_keymap
); /*}*/
556 #endif /* BRACE_COMPLETION */
558 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
559 rl_bind_key_if_unbound_in_map ('/', bash_complete_filename
, emacs_meta_keymap
);
560 rl_bind_key_if_unbound_in_map ('/', bash_possible_filename_completions
, emacs_ctlx_keymap
);
562 /* Have to jump through hoops here because there is a default binding for
563 M-~ (rl_tilde_expand) */
566 func
= rl_function_of_keyseq (kseq
, emacs_meta_keymap
, (int *)NULL
);
567 if (func
== 0 || func
== rl_tilde_expand
)
568 rl_bind_keyseq_in_map (kseq
, bash_complete_username
, emacs_meta_keymap
);
570 rl_bind_key_if_unbound_in_map ('~', bash_possible_username_completions
, emacs_ctlx_keymap
);
572 rl_bind_key_if_unbound_in_map ('@', bash_complete_hostname
, emacs_meta_keymap
);
573 rl_bind_key_if_unbound_in_map ('@', bash_possible_hostname_completions
, emacs_ctlx_keymap
);
575 rl_bind_key_if_unbound_in_map ('$', bash_complete_variable
, emacs_meta_keymap
);
576 rl_bind_key_if_unbound_in_map ('$', bash_possible_variable_completions
, emacs_ctlx_keymap
);
578 rl_bind_key_if_unbound_in_map ('!', bash_complete_command
, emacs_meta_keymap
);
579 rl_bind_key_if_unbound_in_map ('!', bash_possible_command_completions
, emacs_ctlx_keymap
);
581 rl_bind_key_if_unbound_in_map ('g', bash_glob_complete_word
, emacs_meta_keymap
);
582 rl_bind_key_if_unbound_in_map ('*', bash_glob_expand_word
, emacs_ctlx_keymap
);
583 rl_bind_key_if_unbound_in_map ('g', bash_glob_list_expansions
, emacs_ctlx_keymap
);
585 #endif /* SPECIFIC_COMPLETION_FUNCTIONS */
589 func
= rl_function_of_keyseq (kseq
, emacs_meta_keymap
, (int *)NULL
);
590 if (func
== 0 || func
== rl_tab_insert
)
591 rl_bind_key_in_map (TAB
, dynamic_complete_history
, emacs_meta_keymap
);
593 /* Tell the completer that we want a crack first. */
594 rl_attempted_completion_function
= attempt_shell_completion
;
596 bashline_set_filename_hooks ();
598 /* Tell the filename completer we want a chance to ignore some names. */
599 rl_ignore_some_completions_function
= filename_completion_ignore
;
601 /* Bind C-xC-e to invoke emacs and run result as commands. */
602 rl_bind_key_if_unbound_in_map (CTRL ('E'), emacs_edit_and_execute_command
, emacs_ctlx_keymap
);
603 #if defined (VI_MODE)
604 rl_bind_key_if_unbound_in_map ('v', vi_edit_and_execute_command
, vi_movement_keymap
);
606 rl_bind_key_if_unbound_in_map ('@', posix_edit_macros
, vi_movement_keymap
);
609 rl_add_defun ("bash-vi-complete", bash_vi_complete
, -1);
610 rl_bind_key_in_map ('\\', bash_vi_complete
, vi_movement_keymap
);
611 rl_bind_key_in_map ('*', bash_vi_complete
, vi_movement_keymap
);
612 rl_bind_key_in_map ('=', bash_vi_complete
, vi_movement_keymap
);
615 rl_completer_quote_characters
= "'\"";
617 /* This sets rl_completer_word_break_characters and rl_special_prefixes
618 to the appropriate values, depending on whether or not hostname
619 completion is enabled. */
620 enable_hostname_completion (perform_hostname_completion
);
622 /* characters that need to be quoted when appearing in filenames. */
623 rl_filename_quote_characters
= default_filename_quote_characters
;
624 set_filename_bstab (rl_filename_quote_characters
);
626 rl_filename_quoting_function
= bash_quote_filename
;
627 rl_filename_dequoting_function
= bash_dequote_filename
;
628 rl_char_is_quoted_p
= char_is_quoted
;
630 /* Add some default bindings for the "shellwords" functions, roughly
631 parallelling the default word bindings in emacs mode. */
632 rl_bind_key_if_unbound_in_map (CTRL('B'), bash_backward_shellword
, emacs_meta_keymap
);
633 rl_bind_key_if_unbound_in_map (CTRL('D'), bash_kill_shellword
, emacs_meta_keymap
);
634 rl_bind_key_if_unbound_in_map (CTRL('F'), bash_forward_shellword
, emacs_meta_keymap
);
635 rl_bind_key_if_unbound_in_map (CTRL('T'), bash_transpose_shellwords
, emacs_meta_keymap
);
638 /* This is superfluous and makes it impossible to use tab completion in
639 vi mode even when explicitly binding it in ~/.inputrc. sv_strict_posix()
640 should already have called posix_readline_initialize() when
641 posixly_correct was set. */
643 posix_readline_initialize (1);
646 bash_readline_initialized
= 1;
650 bashline_reinitialize (void)
652 bash_readline_initialized
= 0;
656 bashline_set_event_hook (void)
658 rl_signal_event_hook
= bash_event_hook
;
662 bashline_reset_event_hook (void)
664 rl_signal_event_hook
= 0;
667 /* On Sun systems at least, rl_attempted_completion_function can end up
668 getting set to NULL, and rl_completion_entry_function set to do command
669 word completion if Bash is interrupted while trying to complete a command
670 word. This just resets all the completion functions to the right thing.
671 It's called from throw_to_top_level(). */
673 bashline_reset (void)
676 rl_attempted_completion_function
= attempt_shell_completion
;
677 rl_completion_entry_function
= NULL
;
678 rl_ignore_some_completions_function
= filename_completion_ignore
;
680 complete_fullquote
= 1;
681 rl_filename_quote_characters
= default_filename_quote_characters
;
682 set_filename_bstab (rl_filename_quote_characters
);
684 rl_filename_quoting_function
= bash_quote_filename
;
686 bashline_set_filename_hooks ();
688 bashline_reset_event_hook ();
690 rl_sort_completion_matches
= 1;
693 /* Contains the line to push into readline. */
694 static char *push_to_readline
= (char *)NULL
;
696 /* Push the contents of push_to_readline into the
699 bash_push_line (void)
701 if (push_to_readline
)
703 rl_insert_text (push_to_readline
);
704 free (push_to_readline
);
705 push_to_readline
= (char *)NULL
;
706 rl_startup_hook
= old_rl_startup_hook
;
711 /* Call this to set the initial text for the next line to read
714 bash_re_edit (const char *line
)
716 FREE (push_to_readline
);
718 push_to_readline
= savestring (line
);
719 old_rl_startup_hook
= rl_startup_hook
;
720 rl_startup_hook
= bash_push_line
;
726 display_shell_version (int count
, int c
)
729 show_shell_version (0);
730 putc ('\r', rl_outstream
);
731 fflush (rl_outstream
);
737 /* **************************************************************** */
741 /* **************************************************************** */
743 /* If the user requests hostname completion, then simply build a list
744 of hosts, and complete from that forever more, or at least until
745 HOSTFILE is unset. */
747 /* THIS SHOULD BE A STRINGLIST. */
748 /* The kept list of hostnames. */
749 static char **hostname_list
= (char **)NULL
;
751 /* The physical size of the above list. */
752 static size_t hostname_list_size
;
754 /* The number of hostnames in the above list. */
755 static size_t hostname_list_length
;
757 /* Whether or not HOSTNAME_LIST has been initialized. */
758 int hostname_list_initialized
= 0;
760 /* Initialize the hostname completion table. */
762 initialize_hostname_list (void)
766 temp
= get_string_value ("HOSTFILE");
768 temp
= get_string_value ("hostname_completion_file");
770 temp
= DEFAULT_HOSTS_FILE
;
772 snarf_hosts_from_file (temp
);
775 hostname_list_initialized
++;
778 /* Add NAME to the list of hosts. */
780 add_host_name (const char *name
)
782 if (hostname_list_length
+ 2 > hostname_list_size
)
784 hostname_list_size
= (hostname_list_size
+ 32) - (hostname_list_size
% 32);
785 hostname_list
= strvec_resize (hostname_list
, hostname_list_size
);
788 hostname_list
[hostname_list_length
++] = savestring (name
);
789 hostname_list
[hostname_list_length
] = (char *)NULL
;
792 #define cr_whitespace(c) ((c) == '\r' || (c) == '\n' || whitespace(c))
795 snarf_hosts_from_file (const char *filename
)
798 char *temp
, buffer
[256], name
[256];
799 register int i
, start
;
802 file
= fopen (filename
, "rt");
804 file
= fopen (filename
, "r");
809 while (temp
= fgets (buffer
, 255, file
))
811 /* Skip to first character. */
812 for (i
= 0; buffer
[i
] && cr_whitespace (buffer
[i
]); i
++)
815 /* If comment or blank line, ignore. */
816 if (buffer
[i
] == '\0' || buffer
[i
] == '#')
819 /* If `preprocessor' directive, do the include. */
820 if (strncmp (buffer
+ i
, "$include ", 9) == 0)
824 /* Find start of filename. */
825 for (incfile
= buffer
+ i
+ 9; *incfile
&& whitespace (*incfile
); incfile
++)
828 /* Find end of filename. */
829 for (t
= incfile
; *t
&& cr_whitespace (*t
) == 0; t
++)
834 snarf_hosts_from_file (incfile
);
838 /* Skip internet address if present. */
839 if (DIGIT (buffer
[i
]))
840 for (; buffer
[i
] && cr_whitespace (buffer
[i
]) == 0; i
++);
842 /* Gobble up names. Each name is separated with whitespace. */
845 for (; cr_whitespace (buffer
[i
]); i
++)
847 if (buffer
[i
] == '\0' || buffer
[i
] == '#')
850 /* Isolate the current word. */
851 for (start
= i
; buffer
[i
] && cr_whitespace (buffer
[i
]) == 0; i
++)
855 strncpy (name
, buffer
+ start
, i
- start
);
856 name
[i
- start
] = '\0';
857 add_host_name (name
);
863 /* Return the hostname list. */
865 get_hostname_list (void)
867 if (hostname_list_initialized
== 0)
868 initialize_hostname_list ();
869 return (hostname_list
);
873 clear_hostname_list (void)
877 if (hostname_list_initialized
== 0)
879 for (i
= 0; i
< hostname_list_length
; i
++)
880 free (hostname_list
[i
]);
881 hostname_list_length
= hostname_list_initialized
= 0;
884 /* Return a NULL terminated list of hostnames which begin with TEXT.
885 Initialize the hostname list the first time if necessary.
886 The array is malloc ()'ed, but not the individual strings. */
888 hostnames_matching (const char *text
)
894 if (hostname_list_initialized
== 0)
895 initialize_hostname_list ();
897 if (hostname_list_initialized
== 0)
898 return ((char **)NULL
);
900 /* Special case. If TEXT consists of nothing, then the whole list is
904 result
= strvec_create (1 + hostname_list_length
);
905 for (i
= 0; i
< hostname_list_length
; i
++)
906 result
[i
] = hostname_list
[i
];
907 result
[i
] = (char *)NULL
;
911 /* Scan until found, or failure. */
913 result
= (char **)NULL
;
914 for (i
= nmatch
= rsize
= 0; i
< hostname_list_length
; i
++)
916 if (STREQN (text
, hostname_list
[i
], len
) == 0)
919 /* OK, it matches. Add it to the list. */
920 if (nmatch
+ 1 >= rsize
)
922 rsize
= (rsize
+ 16) - (rsize
% 16);
923 result
= strvec_resize (result
, rsize
);
926 result
[nmatch
++] = hostname_list
[i
];
929 result
[nmatch
] = (char *)NULL
;
933 /* This vi mode command causes VI_EDIT_COMMAND to be run on the current
934 command being entered (if no explicit argument is given), otherwise on
935 a command from the history file. */
937 #define VI_EDIT_COMMAND "fc -e \"${VISUAL:-${EDITOR:-vi}}\""
938 #define EMACS_EDIT_COMMAND "fc -e \"${VISUAL:-${EDITOR:-emacs}}\""
939 #define POSIX_VI_EDIT_COMMAND "fc -e vi"
942 edit_and_execute_command (int count
, int c
, int editing_mode
, const char *edit_command
)
944 char *command
, *metaval
;
945 int r
, rrs
, metaflag
;
946 sh_parser_state_t ps
;
948 rrs
= rl_readline_state
;
949 saved_command_line_count
= current_command_line_count
;
951 /* Accept the current line. */
957 /* 32 exceeds strlen (itos (INTMAX_MAX)) (19) */
958 clen
= strlen (edit_command
) + 32;
959 command
= (char *)xmalloc (clen
);
960 snprintf (command
, clen
, "%s %d", edit_command
, count
);
964 /* Take the command we were just editing, add it to the history file,
965 then call fc to operate on it. We have to add a dummy command to
966 the end of the history because fc ignores the last command (assumes
967 it's supposed to deal with the command before the `fc'). */
968 /* This breaks down when using command-oriented history and are not
969 finished with the command, so we should not ignore the last command */
971 current_command_line_count
++; /* for rl_newline above */
972 bash_add_history (rl_line_buffer
);
973 current_command_line_count
= 0; /* for dummy history entry */
974 bash_add_history ("");
975 history_lines_this_session
++;
977 command
= savestring (edit_command
);
980 metaval
= rl_variable_value ("input-meta");
981 metaflag
= RL_BOOLEAN_VARIABLE_VALUE (metaval
);
983 if (rl_deprep_term_function
)
984 (*rl_deprep_term_function
) ();
986 save_parser_state (&ps
);
987 r
= parse_and_execute (command
, (editing_mode
== VI_EDITING_MODE
) ? "v" : "C-xC-e", SEVAL_NOHIST
);
988 restore_parser_state (&ps
);
990 /* if some kind of reset_parser was called, undo it. */
991 reset_readahead_token ();
993 if (rl_prep_term_function
)
994 (*rl_prep_term_function
) (metaflag
);
997 current_command_line_count
= saved_command_line_count
;
999 /* Now erase the contents of the current line and undo the effects of the
1000 rl_accept_line() above. We don't even want to make the text we just
1001 executed available for undoing. */
1002 rl_line_buffer
[0] = '\0'; /* XXX */
1003 rl_point
= rl_end
= 0;
1005 rl_readline_state
= rrs
;
1007 #if defined (VI_MODE)
1008 if (editing_mode
== VI_EDITING_MODE
)
1009 rl_vi_insertion_mode (1, c
);
1012 rl_forced_update_display ();
1017 #if defined (VI_MODE)
1019 vi_edit_and_execute_command (int count
, int key
)
1021 if (posixly_correct
)
1022 return (edit_and_execute_command (count
, key
, VI_EDITING_MODE
, POSIX_VI_EDIT_COMMAND
));
1024 return (edit_and_execute_command (count
, key
, VI_EDITING_MODE
, VI_EDIT_COMMAND
));
1026 #endif /* VI_MODE */
1029 emacs_edit_and_execute_command (int count
, int key
)
1031 return (edit_and_execute_command (count
, key
, EMACS_EDITING_MODE
, EMACS_EDIT_COMMAND
));
1036 posix_edit_macros (int count
, int key
)
1039 char alias_name
[3], *alias_value
, *macro
;
1044 alias_name
[0] = '_';
1046 alias_name
[2] = '\0';
1048 alias_value
= get_alias_value (alias_name
);
1049 if (alias_value
&& *alias_value
)
1051 macro
= savestring (alias_value
);
1052 rl_push_macro_input (macro
);
1058 /* Bindable commands that move `shell-words': that is, sequences of
1059 non-unquoted-metacharacters. */
1061 #define WORDDELIM(c) (shellmeta(c) || shellblank(c))
1064 bash_forward_shellword (int count
, int key
)
1071 return (bash_backward_shellword (-count
, key
));
1073 /* The tricky part of this is deciding whether or not the first character
1074 we're on is an unquoted metacharacter. Not completely handled yet. */
1075 /* XXX - need to test this stuff with backslash-escaped shell
1076 metacharacters and unclosed single- and double-quoted strings. */
1089 /* Are we in a quoted string? If we are, move to the end of the quoted
1090 string and continue the outer loop. We only want quoted strings, not
1091 backslash-escaped characters, but char_is_quoted doesn't
1093 if (char_is_quoted (rl_line_buffer
, p
) && p
> 0 && rl_line_buffer
[p
-1] != '\\')
1096 ADVANCE_CHAR (rl_line_buffer
, slen
, p
);
1097 while (p
< rl_end
&& char_is_quoted (rl_line_buffer
, p
));
1102 /* Rest of code assumes we are not in a quoted string. */
1103 /* Move forward until we hit a non-metacharacter. */
1104 while (p
< rl_end
&& (c
= rl_line_buffer
[p
]) && WORDDELIM (c
))
1109 ADVANCE_CHAR (rl_line_buffer
, slen
, p
);
1110 continue; /* straight back to loop, don't increment p */
1112 if (p
< rl_end
&& rl_line_buffer
[p
])
1113 ADVANCE_CHAR (rl_line_buffer
, slen
, p
);
1116 p
= skip_to_delim (rl_line_buffer
, ++p
, "'", SD_NOJMP
);
1119 p
= skip_to_delim (rl_line_buffer
, ++p
, "\"", SD_NOJMP
);
1127 if (rl_line_buffer
[p
] == 0 || p
== rl_end
)
1134 /* Now move forward until we hit a non-quoted metacharacter or EOL */
1135 while (p
< rl_end
&& (c
= rl_line_buffer
[p
]) && WORDDELIM (c
) == 0)
1140 ADVANCE_CHAR (rl_line_buffer
, slen
, p
);
1141 continue; /* straight back to loop, don't increment p */
1143 if (p
< rl_end
&& rl_line_buffer
[p
])
1144 ADVANCE_CHAR (rl_line_buffer
, slen
, p
);
1147 p
= skip_to_delim (rl_line_buffer
, ++p
, "'", SD_NOJMP
);
1150 p
= skip_to_delim (rl_line_buffer
, ++p
, "\"", SD_NOJMP
);
1158 if (p
== rl_end
|| rl_line_buffer
[p
] == 0)
1172 bash_backward_shellword (int count
, int key
)
1179 return (bash_forward_shellword (-count
, key
));
1192 /* Move backward until we hit a non-metacharacter. We want to deal
1193 with the characters before point, so we move off a word if we're
1194 at its first character. */
1195 BACKUP_CHAR (rl_line_buffer
, slen
, p
);
1198 c
= rl_line_buffer
[p
];
1199 if (WORDDELIM (c
) == 0 || char_is_quoted (rl_line_buffer
, p
))
1201 BACKUP_CHAR (rl_line_buffer
, slen
, p
);
1210 /* Now move backward until we hit a metacharacter or BOL. Leave point
1211 at the start of the shellword or at BOL. */
1215 c
= rl_line_buffer
[p
];
1216 if (WORDDELIM (c
) && char_is_quoted (rl_line_buffer
, p
) == 0)
1222 BACKUP_CHAR (rl_line_buffer
, slen
, p
);
1233 bash_kill_shellword (int count
, int key
)
1238 return (bash_backward_kill_shellword (-count
, key
));
1241 bash_forward_shellword (count
, key
);
1244 rl_kill_text (p
, rl_point
);
1247 if (rl_editing_mode
== EMACS_EDITING_MODE
) /* 1 == emacs_mode */
1254 bash_backward_kill_shellword (int count
, int key
)
1259 return (bash_kill_shellword (-count
, key
));
1262 bash_backward_shellword (count
, key
);
1265 rl_kill_text (p
, rl_point
);
1267 if (rl_editing_mode
== EMACS_EDITING_MODE
) /* 1 == emacs_mode */
1274 bash_transpose_shellwords (int count
, int key
)
1276 char *word1
, *word2
;
1277 int w1_beg
, w1_end
, w2_beg
, w2_end
;
1278 int orig_point
= rl_point
;
1283 /* Find the two shell words. */
1284 bash_forward_shellword (count
, key
);
1286 bash_backward_shellword (1, key
);
1288 bash_backward_shellword (count
, key
);
1290 bash_forward_shellword (1, key
);
1293 /* check that there really are two words. */
1294 if ((w1_beg
== w2_beg
) || (w2_beg
< w1_end
))
1297 rl_point
= orig_point
;
1301 /* Get the text of the words. */
1302 word1
= rl_copy_text (w1_beg
, w1_end
);
1303 word2
= rl_copy_text (w2_beg
, w2_end
);
1305 /* We are about to do many insertions and deletions. Remember them
1306 as one operation. */
1307 rl_begin_undo_group ();
1309 /* Do the stuff at word2 first, so that we don't have to worry
1310 about word1 moving. */
1312 rl_delete_text (w2_beg
, w2_end
);
1313 rl_insert_text (word1
);
1316 rl_delete_text (w1_beg
, w1_end
);
1317 rl_insert_text (word2
);
1319 /* This is exactly correct since the text before this point has not
1320 changed in length. */
1323 /* I think that does it. */
1324 rl_end_undo_group ();
1331 /* Directory name spelling correction on the current word (not shellword).
1332 COUNT > 1 is not exactly correct yet. */
1334 bash_spell_correct_shellword (int count
, int key
)
1337 char *text
, *newdir
;
1341 bash_backward_shellword (1, key
);
1343 bash_forward_shellword (1, key
);
1349 text
= rl_copy_text (wbeg
, wend
);
1350 if (text
== 0 || *text
== 0)
1353 newdir
= dirspell (text
);
1356 rl_begin_undo_group ();
1357 rl_delete_text (wbeg
, wend
);
1360 rl_insert_text (newdir
);
1362 rl_end_undo_group ();
1368 if (rl_point
>= rl_end
)
1374 bash_forward_shellword (1, key
); /* XXX */
1380 /* **************************************************************** */
1382 /* How To Do Shell Completion */
1384 /* **************************************************************** */
1386 #define COMMAND_SEPARATORS ";|&{(`"
1388 #define COMMAND_SEPARATORS_PLUS_WS ";|&{(` \t"
1391 /* check for redirections and other character combinations that are not
1392 command separators */
1394 check_redir (int ti
)
1396 int this_char
, prev_char
, next_char
;
1398 /* Handle the two character tokens `>&', `<&', and `>|'.
1399 We are not in a command position after one of these. */
1400 this_char
= rl_line_buffer
[ti
];
1401 prev_char
= (ti
> 0) ? rl_line_buffer
[ti
- 1] : 0;
1402 next_char
= (ti
< rl_end
) ? rl_line_buffer
[ti
+ 1] : 0;
1404 if ((this_char
== '&' && (prev_char
== '<' || prev_char
== '>')) ||
1405 (this_char
== '|' && prev_char
== '>'))
1407 else if (this_char
== '{' && prev_char
== '$' && FUNSUB_CHAR (next_char
) == 0) /*}*/
1410 else if (this_char
== '(' && prev_char
== '$') /*)*/
1412 else if (this_char
== '(' && prev_char
== '<') /*)*/
1414 #if defined (EXTENDED_GLOB)
1415 else if (extended_glob
&& this_char
== '(' && prev_char
== '!') /*)*/
1419 else if (char_is_quoted (rl_line_buffer
, ti
))
1424 #if defined (PROGRAMMABLE_COMPLETION)
1426 * XXX - because of the <= start test, and setting os = s+1, this can
1427 * potentially return os > start. This is probably not what we want to
1428 * happen, but fix later after 2.05a-release.
1431 find_cmd_start (int start
)
1433 register int s
, os
, ns
;
1436 /* Flags == SD_NOJMP only because we want to skip over command substitutions
1437 in assignment statements. Have to test whether this affects `standalone'
1438 command substitutions as individual words. */
1439 while (((s
= skip_to_delim (rl_line_buffer
, os
, COMMAND_SEPARATORS
, SD_NOJMP
|SD_COMPLETE
/*|SD_NOSKIPCMD*/)) <= start
) &&
1442 /* Handle >| token crudely; treat as > not | */
1443 if (s
> 0 && rl_line_buffer
[s
] == '|' && rl_line_buffer
[s
-1] == '>')
1445 ns
= skip_to_delim (rl_line_buffer
, s
+1, COMMAND_SEPARATORS
, SD_NOJMP
|SD_COMPLETE
/*|SD_NOSKIPCMD*/);
1446 if (ns
> start
|| rl_line_buffer
[ns
] == 0)
1451 /* The only reserved word in COMMAND_SEPARATORS is `{', so handle that
1452 specially, making sure it's in a spot acceptable for reserved words */
1453 if (s
>= os
&& rl_line_buffer
[s
] == '{')
1455 int pc
, nc
; /* index of previous non-whitespace, next char */
1456 for (pc
= (s
> os
) ? s
- 1 : os
; pc
> os
&& whitespace(rl_line_buffer
[pc
]); pc
--)
1458 nc
= rl_line_buffer
[s
+1];
1459 /* must be preceded by a command separator or be the first non-
1460 whitespace character since the last command separator, and
1461 followed by a shell break character (not another `{') to be a reserved word. */
1462 if ((pc
> os
&& (rl_line_buffer
[s
-1] == '{' || strchr (COMMAND_SEPARATORS
, rl_line_buffer
[pc
]) == 0)) ||
1463 (shellbreak(nc
) == 0)) /* }} */
1465 /* Not a reserved word, look for another delim */
1466 ns
= skip_to_delim (rl_line_buffer
, s
+1, COMMAND_SEPARATORS
, SD_NOJMP
|SD_COMPLETE
/*|SD_NOSKIPCMD*/);
1467 if (ns
> start
|| rl_line_buffer
[ns
] == 0)
1479 find_cmd_end (int end
)
1483 e
= skip_to_delim (rl_line_buffer
, end
, COMMAND_SEPARATORS
, SD_NOJMP
|SD_COMPLETE
);
1488 find_cmd_name (int start
, int *sp
, int *ep
)
1493 for (s
= start
; whitespace (rl_line_buffer
[s
]); s
++)
1496 /* skip until a shell break character */
1497 e
= skip_to_delim (rl_line_buffer
, s
, "()<>;&| \t\n", SD_NOJMP
|SD_COMPLETE
);
1499 name
= substring (rl_line_buffer
, s
, e
);
1510 prog_complete_return (const char *text
, int matchnum
)
1517 if (prog_complete_matches
== 0 || prog_complete_matches
[ind
] == 0)
1518 return (char *)NULL
;
1519 return (prog_complete_matches
[ind
++]);
1522 #endif /* PROGRAMMABLE_COMPLETION */
1524 /* Try and catch completion attempts that are syntax errors or otherwise
1527 invalid_completion (const char *text
, int ind
)
1531 /* If we don't catch these here, the next clause will */
1532 if (ind
> 0 && rl_line_buffer
[ind
] == '(' && /*)*/
1533 member (rl_line_buffer
[ind
-1], "$<>"))
1537 while (pind
> 0 && whitespace (rl_line_buffer
[pind
]))
1539 /* If we have only whitespace preceding a paren, it's valid */
1540 if (ind
>= 0 && pind
<= 0 && rl_line_buffer
[ind
] == '(') /*)*/
1542 /* Flag the invalid completions, which are mostly syntax errors */
1543 if (ind
> 0 && rl_line_buffer
[ind
] == '(' && /*)*/
1544 member (rl_line_buffer
[pind
], COMMAND_SEPARATORS
) == 0)
1550 /* Do some completion on TEXT. The indices of TEXT in RL_LINE_BUFFER are
1551 at START and END. Return an array of matches, or NULL if none. */
1553 attempt_shell_completion (const char *text
, int start
, int end
)
1555 int in_command_position
, ti
, qc
, dflags
;
1556 char **matches
, *command_separator_chars
;
1557 #if defined (PROGRAMMABLE_COMPLETION)
1558 int have_progcomps
, was_assignment
;
1559 COMPSPEC
*iw_compspec
;
1562 command_separator_chars
= COMMAND_SEPARATORS
;
1563 matches
= (char **)NULL
;
1564 rl_ignore_some_completions_function
= filename_completion_ignore
;
1566 complete_fullquote
= 1; /* full filename quoting by default */
1567 rl_filename_quote_characters
= default_filename_quote_characters
;
1568 set_filename_bstab (rl_filename_quote_characters
);
1569 bashline_set_filename_hooks ();
1571 rl_sort_completion_matches
= 1; /* sort by default */
1573 /* Determine if this could be a command word. It is if it appears at
1574 the start of the line (ignoring preceding whitespace), or if it
1575 appears after a character that separates commands. It cannot be a
1576 command word if we aren't at the top-level prompt. */
1580 while ((ti
> -1) && (whitespace (rl_line_buffer
[ti
])))
1584 /* If this is an open quote, maybe we're trying to complete a quoted
1586 if (ti
>= 0 && (rl_line_buffer
[ti
] == '"' || rl_line_buffer
[ti
] == '\''))
1588 qc
= rl_line_buffer
[ti
];
1590 while (ti
> -1 && (whitespace (rl_line_buffer
[ti
])))
1595 in_command_position
= 0;
1598 /* Only do command completion at the start of a line when we
1599 are prompting at the top level. */
1600 if (current_prompt_string
== ps1_prompt
)
1601 in_command_position
++;
1602 else if (parser_in_command_position ())
1603 in_command_position
++;
1605 else if (member (rl_line_buffer
[ti
], command_separator_chars
))
1607 in_command_position
++;
1609 if (check_redir (ti
) == 1)
1610 in_command_position
= -1; /* sentinel that we're not the first word on the line */
1614 /* This still could be in command position. It is possible
1615 that all of the previous words on the line are variable
1619 if (in_command_position
> 0 && invalid_completion (text
, ti
))
1621 rl_attempted_completion_over
= 1;
1622 return ((char **)NULL
);
1625 /* Check that we haven't incorrectly flagged a closed command substitution
1626 as indicating we're in a command position. */
1627 if (in_command_position
> 0 && ti
>= 0 && rl_line_buffer
[ti
] == '`' &&
1628 *text
!= '`' && unclosed_pair (rl_line_buffer
, end
, "`") == 0)
1629 in_command_position
= -1; /* not following a command separator */
1631 /* Special handling for command substitution. If *TEXT is a backquote,
1632 it can be the start or end of an old-style command substitution, or
1633 unmatched. If it's unmatched, both calls to unclosed_pair will
1634 succeed. Don't bother if readline found a single quote and we are
1635 completing on the substring. */
1636 if (*text
== '`' && rl_completion_quote_character
!= '\'' &&
1637 (in_command_position
> 0 || (unclosed_pair (rl_line_buffer
, start
, "`") &&
1638 unclosed_pair (rl_line_buffer
, end
, "`"))))
1639 matches
= rl_completion_matches (text
, command_subst_completion_function
);
1641 #if defined (PROGRAMMABLE_COMPLETION)
1642 /* Attempt programmable completion. */
1643 have_progcomps
= prog_completion_enabled
&& (progcomp_size () > 0);
1644 iw_compspec
= progcomp_search (INITIALWORD
);
1646 (in_command_position
== 0 || text
[0] == '\0' || (in_command_position
> 0 && iw_compspec
)) &&
1647 current_prompt_string
== ps1_prompt
)
1649 int s
, e
, s1
, e1
, os
, foundcs
;
1652 /* XXX - don't free the members */
1653 if (prog_complete_matches
)
1654 free (prog_complete_matches
);
1655 prog_complete_matches
= (char **)NULL
;
1660 s
= find_cmd_start (os
);
1661 e
= find_cmd_end (end
);
1664 /* Don't read past the end of rl_line_buffer */
1670 /* Or past point if point is within an assignment statement */
1671 else if (was_assignment
&& s
> rl_point
)
1678 s
= s1
= start
; e
= e1
= end
; /* reset */
1680 /* Skip over assignment statements preceding a command name. If we
1681 don't find a command name at all, we can perform command name
1682 completion. If we find a partial command name, we should perform
1683 command name completion on it. */
1685 n
= find_cmd_name (s
, &s1
, &e1
);
1688 while (was_assignment
= assignment (n
, 0));
1689 s
= s1
; /* reset to index where name begins */
1691 /* s == index of where command name begins (reset above)
1692 e == end of current command, may be end of line
1693 s1 = index of where command name begins
1694 e1 == index of where command name ends
1695 start == index of where word to be completed begins
1696 end == index of where word to be completed ends
1697 if (s == start) we are doing command word completion for sure
1698 if (e1 == end) we are at the end of the command name and completing it */
1699 if (start
== 0 && end
== 0 && e
!= 0 && e1
< rl_end
&& text
[0] == '\0') /* beginning of non-empty line */
1701 else if (start
== end
&& start
== s1
&& e
!= 0 && e1
> end
) /* beginning of command name, leading whitespace */
1703 else if (start
== 0 && start
== end
&& start
< s1
&& e
!= 0 && e1
> end
&& text
[0] == '\0' && have_progcomps
) /* no command name, leading whitespace only */
1704 prog_complete_matches
= programmable_completions (EMPTYCMD
, text
, s
, e
, &foundcs
);
1705 else if (e
== 0 && e
== s
&& text
[0] == '\0' && have_progcomps
) /* beginning of empty line */
1706 prog_complete_matches
= programmable_completions (EMPTYCMD
, text
, s
, e
, &foundcs
);
1707 else if (start
== end
&& text
[0] == '\0' && s1
> start
&& whitespace (rl_line_buffer
[start
]))
1708 foundcs
= 0; /* whitespace before command name */
1709 else if (e
> s
&& was_assignment
== 0 && e1
== end
&& rl_line_buffer
[e
] == 0 && whitespace (rl_line_buffer
[e
-1]) == 0)
1711 /* not assignment statement, but still want to perform command
1712 completion if we are composing command word. */
1714 in_command_position
= s
== start
&& STREQ (n
, text
); /* XXX */
1716 else if (e
> s
&& was_assignment
== 0 && have_progcomps
)
1718 prog_complete_matches
= programmable_completions (n
, text
, s
, e
, &foundcs
);
1719 /* command completion if programmable completion fails */
1720 /* If we have a completion for the initial word, we can prefer that */
1721 in_command_position
= s
== start
&& (iw_compspec
|| STREQ (n
, text
)); /* XXX */
1722 if (iw_compspec
&& in_command_position
)
1725 /* empty command name following command separator */
1726 else if (s
>= e
&& n
[0] == '\0' && text
[0] == '\0' && start
> 0 &&
1727 was_assignment
== 0 && member (rl_line_buffer
[start
-1], COMMAND_SEPARATORS
))
1730 in_command_position
= 1;
1732 else if (s
>= e
&& n
[0] == '\0' && text
[0] == '\0' && start
> 0)
1734 foundcs
= 0; /* empty command name following optional assignments */
1735 in_command_position
+= was_assignment
;
1737 else if (s
== start
&& e
== end
&& STREQ (n
, text
) && start
> 0)
1739 foundcs
= 0; /* partial command name following assignments */
1740 in_command_position
= 1;
1745 /* If we have defined a compspec for the initial (command) word, call
1746 it and process the results like any other programmable completion. */
1747 if (in_command_position
&& have_progcomps
&& foundcs
== 0 && iw_compspec
)
1749 /* Do some sanity checking on S and E. Room for more here. */
1754 prog_complete_matches
= programmable_completions (INITIALWORD
, text
, s
, e
, &foundcs
);
1758 /* XXX - if we found a COMPSPEC for the command, just return whatever
1759 the programmable completion code returns, and disable the default
1760 filename completion that readline will do unless the COPT_DEFAULT
1761 option has been set with the `-o default' option to complete or
1765 pcomp_set_readline_variables (foundcs
, 1);
1766 /* Turn what the programmable completion code returns into what
1767 readline wants. I should have made compute_lcd_of_matches
1769 matches
= rl_completion_matches (text
, prog_complete_return
);
1770 if ((foundcs
& COPT_DEFAULT
) == 0)
1771 rl_attempted_completion_over
= 1; /* no default */
1772 if (matches
|| ((foundcs
& COPT_BASHDEFAULT
) == 0))
1781 if (in_command_position
> 0)
1782 dflags
|= DEFCOMP_CMDPOS
;
1783 matches
= bash_default_completion (text
, start
, end
, qc
, dflags
);
1790 bash_default_completion (const char *text
, int start
, int end
, int qc
, int compflags
)
1794 matches
= (char **)NULL
;
1796 /* New posix-style command substitution or variable name? */
1799 if (qc
!= '\'' && text
[1] == '(') /* ) */
1800 matches
= rl_completion_matches (text
, command_subst_completion_function
);
1801 else if (qc
!= '\'' && text
[1] == '{' && FUNSUB_CHAR (text
[2])) /* } */
1802 matches
= rl_completion_matches (text
, command_subst_completion_function
);
1805 matches
= rl_completion_matches (text
, variable_completion_function
);
1806 /* If a single match, see if it expands to a directory name and append
1807 a slash if it does. This requires us to expand the variable name,
1808 so we don't want to display errors if the variable is unset. This
1809 can happen with dynamic variables whose value has never been
1811 if (matches
&& matches
[0] && matches
[1] == 0)
1813 t
= savestring (matches
[0]);
1814 bash_filename_stat_hook (&t
);
1815 /* doesn't use test_for_directory because that performs tilde
1818 rl_completion_append_character
= '/';
1824 /* If the word starts in `~', and there is no slash in the word, then
1825 try completing this word as a username. */
1826 if (matches
== 0 && *text
== '~' && mbschr (text
, '/') == 0)
1827 matches
= rl_completion_matches (text
, rl_username_completion_function
);
1829 /* Another one. Why not? If the word starts in '@', then look through
1830 the world of known hostnames for completion first. */
1831 if (matches
== 0 && perform_hostname_completion
&& *text
== '@')
1832 matches
= rl_completion_matches (text
, hostname_completion_function
);
1834 /* And last, (but not least) if this word is in a command position, then
1835 complete over possible command names, including aliases, functions,
1836 and command names. */
1837 if (matches
== 0 && (compflags
& DEFCOMP_CMDPOS
))
1839 /* If END == START and text[0] == 0, we are trying to complete an empty
1841 if (no_empty_command_completion
&& end
== start
&& text
[0] == '\0')
1843 matches
= (char **)NULL
;
1844 rl_ignore_some_completions_function
= bash_ignore_everything
;
1848 #define CMD_IS_DIR(x) (absolute_pathname(x) == 0 && absolute_program(x) == 0 && *(x) != '~' && test_for_directory (x))
1851 matches
= rl_completion_matches (text
, command_word_completion_function
);
1853 /* If we are attempting command completion and nothing matches, we
1854 do not want readline to perform filename completion for us. We
1855 still want to be able to complete partial pathnames, so set the
1856 completion ignore function to something which will remove
1857 filenames and leave directories in the match list. */
1858 if (matches
== (char **)NULL
)
1859 rl_ignore_some_completions_function
= bash_ignore_filenames
;
1860 else if (matches
[1] == 0 && CMD_IS_DIR(matches
[0]) && dot_in_path
== 0)
1861 /* If we found a single match, without looking in the current
1862 directory (because it's not in $PATH), but the found name is
1863 also a command in the current directory, suppress appending any
1864 terminating character, since it's ambiguous. */
1866 rl_completion_suppress_append
= 1;
1867 rl_filename_completion_desired
= 0;
1870 else if (matches
[0] && matches
[1] && STREQ (matches
[0], matches
[1]) &&
1871 matches
[2] && STREQ (matches
[1], matches
[2]) && CMD_IS_DIR (matches
[0]))
1873 else if (matches
[0] && matches
[1] && STREQ (matches
[0], matches
[1]) && CMD_IS_DIR (matches
[0]))
1875 /* There are multiple instances of the same match (duplicate
1876 completions haven't yet been removed). In this case, all of
1877 the matches will be the same, and the duplicate removal code
1878 will distill them all down to one. We turn on
1879 rl_completion_suppress_append for the same reason as above.
1880 Remember: we only care if there's eventually a single unique
1881 completion. If there are multiple completions this won't
1882 make a difference and the problem won't occur. */
1884 rl_completion_suppress_append
= 1;
1885 rl_filename_completion_desired
= 0;
1890 /* This could be a globbing pattern, so try to expand it using pathname
1892 if (!matches
&& completion_glob_pattern (text
))
1894 matches
= rl_completion_matches (text
, glob_complete_word
);
1895 /* A glob expression that matches more than one filename is problematic.
1896 If we match more than one filename, punt. */
1897 if (matches
&& matches
[1] && rl_completion_type
== TAB
)
1899 strvec_dispose (matches
);
1900 matches
= (char **)0;
1902 else if (matches
&& matches
[1] && rl_completion_type
== '!')
1904 rl_completion_suppress_append
= 1;
1905 rl_filename_completion_desired
= 0;
1913 bash_command_name_stat_hook (char **name
)
1915 char *cname
, *result
;
1917 /* If it's not something we're going to look up in $PATH, just call the
1918 normal filename stat hook. */
1919 if (absolute_program (*name
))
1920 return (bash_filename_stat_hook (name
));
1923 /* XXX - we could do something here with converting aliases, builtins,
1924 and functions into something that came out as executable, but we don't. */
1925 result
= search_for_command (cname
, 0);
1936 executable_completion (const char *filename
, int searching_path
)
1941 /* This gets an unquoted filename, so we need to quote special characters
1942 in the filename before the completion hook gets it. */
1944 f
= bash_quote_filename ((char *)filename
, SINGLE_MATCH
, &c
);
1945 bash_directory_completion_hook (&f
);
1947 r
= searching_path
? executable_file (f
) : executable_or_directory (f
);
1952 /* This is the function to call when the word to complete is in a position
1953 where a command word can be found. It grovels $PATH, looking for commands
1954 that match. It also scans aliases, function names, and the shell_builtin
1957 command_word_completion_function (const char *hint_text
, int state
)
1959 static char *hint
= (char *)NULL
;
1960 static char *path
= (char *)NULL
;
1961 static char *val
= (char *)NULL
;
1962 static char *filename_hint
= (char *)NULL
;
1963 static char *fnhint
= (char *)NULL
;
1964 static char *dequoted_hint
= (char *)NULL
;
1965 static char *directory_part
= (char *)NULL
;
1966 static char **glob_matches
= (char **)NULL
;
1967 static int path_index
, istate
, igncase
;
1968 static size_t hint_len
;
1969 static int mapping_over
, local_index
, searching_path
, hint_is_dir
;
1970 static int old_glob_ignore_case
, globpat
;
1971 static SHELL_VAR
**varlist
= (SHELL_VAR
**)NULL
;
1973 static alias_t
**alias_list
= (alias_t
**)NULL
;
1977 /* We have to map over the possibilities for command words. If we have
1978 no state, then make one just for that purpose. */
1981 rl_filename_stat_hook
= bash_command_name_stat_hook
;
1983 if (dequoted_hint
&& dequoted_hint
!= hint
)
1984 free (dequoted_hint
);
1987 dequoted_hint
= hint
= (char *)NULL
;
1989 mapping_over
= searching_path
= 0;
1990 hint_is_dir
= CMD_IS_DIR (hint_text
);
1993 temp
= rl_variable_value ("completion-ignore-case");
1994 igncase
= RL_BOOLEAN_VARIABLE_VALUE (temp
);
1996 old_glob_ignore_case
= glob_ignore_case
;
2000 free (glob_matches
);
2001 glob_matches
= (char **)NULL
;
2004 globpat
= completion_glob_pattern (hint_text
);
2006 /* If this is an absolute program name, do not check it against
2007 aliases, reserved words, functions or builtins. We must check
2008 whether or not it is unique, and, if so, whether that filename
2010 if (globpat
|| absolute_program (hint_text
))
2012 /* Perform tilde expansion on what's passed, so we don't end up
2013 passing filenames with tildes directly to stat(). The rest of
2014 the shell doesn't do variable expansion on the word following
2015 the tilde, so we don't do it here even if direxpand is set. */
2016 if (*hint_text
== '~')
2018 hint
= bash_tilde_expand (hint_text
, 0);
2019 directory_part
= savestring (hint_text
);
2020 temp
= strchr (directory_part
, '/');
2025 free (directory_part
);
2026 directory_part
= (char *)NULL
;
2029 else if (dircomplete_expand
)
2031 hint
= savestring (hint_text
);
2032 bash_directory_completion_hook (&hint
);
2035 hint
= savestring (hint_text
);
2037 dequoted_hint
= hint
;
2038 /* If readline's completer found a quote character somewhere, but
2039 didn't set the quote character, there must have been a quote
2040 character embedded in the filename. It can't be at the start of
2041 the filename, so we need to dequote the filename before we look
2042 in the file system for it. */
2043 if (rl_completion_found_quote
&& rl_completion_quote_character
== 0)
2045 dequoted_hint
= bash_dequote_filename (hint
, 0);
2047 hint
= dequoted_hint
;
2049 hint_len
= strlen (hint
);
2052 free (filename_hint
);
2054 fnhint
= filename_hint
= savestring (hint
);
2065 if (dircomplete_expand
&& path_dot_or_dotdot (filename_hint
))
2067 dircomplete_expand
= 0;
2068 set_directory_hook ();
2069 dircomplete_expand
= 1;
2076 dequoted_hint
= hint
= savestring (hint_text
);
2077 hint_len
= strlen (hint
);
2079 if (rl_completion_found_quote
&& rl_completion_quote_character
== 0)
2080 dequoted_hint
= bash_dequote_filename (hint
, 0);
2082 path
= path_value ("PATH", 0);
2083 path_index
= dot_in_path
= 0;
2085 /* Initialize the variables for each type of command word. */
2091 varlist
= all_visible_functions ();
2097 alias_list
= all_aliases ();
2101 /* mapping_over says what we are currently hacking. Note that every case
2102 in this list must fall through when there are no more possibilities. */
2104 switch (mapping_over
)
2106 case 0: /* Aliases come first. */
2108 while (alias_list
&& alias_list
[local_index
])
2110 register char *alias
;
2112 alias
= alias_list
[local_index
++]->name
;
2114 if (igncase
== 0 && (STREQN (alias
, hint
, hint_len
)))
2115 return (savestring (alias
));
2116 else if (igncase
&& strncasecmp (alias
, hint
, hint_len
) == 0)
2117 return (savestring (alias
));
2123 case 1: /* Then shell reserved words. */
2125 while (word_token_alist
[local_index
].word
)
2127 register char *reserved_word
;
2129 reserved_word
= word_token_alist
[local_index
++].word
;
2131 if (STREQN (reserved_word
, hint
, hint_len
))
2132 return (savestring (reserved_word
));
2138 case 2: /* Then function names. */
2139 while (varlist
&& varlist
[local_index
])
2141 register char *varname
;
2143 varname
= varlist
[local_index
++]->name
;
2145 /* Honor completion-ignore-case for shell function names. */
2146 if (igncase
== 0 && (STREQN (varname
, hint
, hint_len
)))
2147 return (savestring (varname
));
2148 else if (igncase
&& strncasecmp (varname
, hint
, hint_len
) == 0)
2149 return (savestring (varname
));
2154 case 3: /* Then shell builtins. */
2155 for (; local_index
< num_shell_builtins
; local_index
++)
2157 /* Ignore it if it doesn't have a function pointer or if it
2158 is not currently enabled. */
2159 if (!shell_builtins
[local_index
].function
||
2160 (shell_builtins
[local_index
].flags
& BUILTIN_ENABLED
) == 0)
2163 if (STREQN (shell_builtins
[local_index
].name
, hint
, hint_len
))
2165 int i
= local_index
++;
2167 return (savestring (shell_builtins
[i
].name
));
2175 /* Limited support for completing command words with globbing chars. Only
2176 a single match (multiple matches that end up reducing the number of
2177 characters in the common prefix are bad) will ever be returned on
2178 regular completion. */
2183 rl_filename_completion_desired
= 1;
2185 glob_ignore_case
= igncase
;
2186 glob_matches
= shell_glob_filename (hint
, 0);
2187 glob_ignore_case
= old_glob_ignore_case
;
2189 if (GLOB_FAILED (glob_matches
) || glob_matches
== 0)
2191 glob_matches
= (char **)NULL
;
2192 return ((char *)NULL
);
2197 if (glob_matches
[1] && rl_completion_type
== TAB
) /* multiple matches are bad */
2199 strvec_dispose (glob_matches
);
2200 glob_matches
= (char **)NULL
;
2201 return ((char *)NULL
);
2205 while (val
= glob_matches
[local_index
++])
2207 if (executable_or_directory (val
))
2209 if (*hint_text
== '~' && directory_part
)
2211 temp
= maybe_restore_tilde (val
, directory_part
);
2220 glob_ignore_case
= old_glob_ignore_case
;
2221 return ((char *)NULL
);
2224 /* If the text passed is a directory in the current directory, return it
2225 as a possible match. Executables in directories in the current
2226 directory can be specified using relative pathnames and successfully
2227 executed even when `.' is not in $PATH. */
2230 hint_is_dir
= 0; /* only return the hint text once */
2231 return (savestring (hint_text
));
2234 /* Repeatedly call filename_completion_function while we have
2235 members of PATH left. Question: should we stat each file?
2236 Answer: we call executable_file () on each file. */
2239 istate
= (val
!= (char *)NULL
);
2245 /* Get the next directory from the path. If there is none, then we
2247 if (path
== 0 || path
[path_index
] == 0 ||
2248 (current_path
= extract_colon_unit (path
, &path_index
)) == 0)
2249 return ((char *)NULL
);
2252 if (*current_path
== 0)
2254 free (current_path
);
2255 current_path
= savestring (".");
2258 if (*current_path
== '~')
2262 t
= bash_tilde_expand (current_path
, 0);
2263 free (current_path
);
2267 if (current_path
[0] == '.' && current_path
[1] == '\0')
2270 if (fnhint
&& fnhint
!= filename_hint
)
2273 free (filename_hint
);
2274 fnhint
= filename_hint
= (char *)NULL
;
2276 filename_hint
= sh_makepath (current_path
, hint
, 0);
2277 /* Need a quoted version (though it doesn't matter much in most
2278 cases) because rl_filename_completion_function dequotes the
2279 filename it gets, assuming that it's been quoted as part of
2280 the input line buffer. */
2281 if (strpbrk (filename_hint
, "\"'\\"))
2282 fnhint
= sh_backslash_quote (filename_hint
, filename_bstab
, 0);
2284 fnhint
= filename_hint
;
2285 free (current_path
); /* XXX */
2289 val
= rl_filename_completion_function (fnhint
, istate
);
2290 if (mapping_over
== 4 && dircomplete_expand
)
2291 set_directory_hook ();
2297 /* If the hint text is an absolute program, then don't bother
2298 searching through PATH. */
2299 if (absolute_program (hint
))
2300 return ((char *)NULL
);
2306 int match
, freetemp
;
2308 if (absolute_program (hint
))
2312 match
= strncmp (val
, hint
, hint_len
) == 0;
2314 match
= strncasecmp (val
, hint
, hint_len
) == 0;
2316 /* Why duplicate the comparison rl_filename_completion_function
2317 already performs? */
2321 /* If we performed tilde expansion, restore the original
2323 if (*hint_text
== '~')
2324 temp
= maybe_restore_tilde (val
, directory_part
);
2326 temp
= savestring (val
);
2331 temp
= strrchr (val
, '/');
2337 freetemp
= match
= strncmp (temp
, hint
, hint_len
) == 0;
2339 freetemp
= match
= strncasecmp (temp
, hint
, hint_len
) == 0;
2341 temp
= savestring (temp
);
2344 freetemp
= match
= 0;
2347 /* If we have found a match, and it is an executable file, return it.
2348 We don't return directory names when searching $PATH, since the
2349 bash execution code won't find executables in directories which
2350 appear in directories in $PATH when they're specified using
2351 relative pathnames. */
2353 /* If we're not searching $PATH and we have a relative pathname, we
2354 need to re-canonicalize it before testing whether or not it's an
2355 executable or a directory so the shell treats .. relative to $PWD
2356 according to the physical/logical option. The shell already
2357 canonicalizes the directory name in order to tell readline where
2358 to look, so not doing it here will be inconsistent. */
2359 /* XXX -- currently not used -- will introduce more inconsistency,
2360 since shell does not canonicalize ../foo before passing it to
2362 if (match
&& searching_path
== 0 && *val
== '.')
2366 t
= get_working_directory ("command-word-completion");
2367 t1
= make_absolute (val
, t
);
2369 cval
= sh_canonpath (t1
, PATH_CHECKDOTDOT
|PATH_CHECKEXISTS
);
2376 if (match
&& executable_completion ((searching_path
? val
: cval
), searching_path
))
2381 val
= ""; /* So it won't be NULL. */
2396 /* Completion inside an unterminated command substitution. */
2398 command_subst_completion_function (const char *text
, int state
)
2400 static char **matches
= (char **)NULL
;
2401 static const char *orig_start
;
2402 static char *filename_text
= (char *)NULL
;
2403 static int cmd_index
, start_len
;
2409 free (filename_text
);
2413 else if (*text
== '$' && text
[1] == '(') /* ) */
2415 else if (*text
== '$' && text
[1] == '{' && FUNSUB_CHAR (text
[2])) /*}*/
2416 text
+= 3; /* nofork command substitution */
2417 /* If the text was quoted, suppress any quote character that the
2418 readline completion code would insert. */
2419 rl_completion_suppress_quote
= 1;
2420 start_len
= text
- orig_start
;
2421 filename_text
= savestring (text
);
2425 matches
= (char **)NULL
;
2429 * At this point we can entertain the idea of re-parsing
2430 * `filename_text' into a (possibly incomplete) command name and
2431 * arguments, and doing completion based on that. This is
2432 * currently very rudimentary, but it is a small improvement.
2434 for (value
= filename_text
+ strlen (filename_text
) - 1; value
> filename_text
; value
--)
2435 if (whitespace (*value
) || member (*value
, COMMAND_SEPARATORS
))
2437 if (value
<= filename_text
)
2438 matches
= rl_completion_matches (filename_text
, command_word_completion_function
);
2442 start_len
+= value
- filename_text
;
2443 if (whitespace (value
[-1]))
2444 matches
= rl_completion_matches (value
, rl_filename_completion_function
);
2446 matches
= rl_completion_matches (value
, command_word_completion_function
);
2449 /* If there is more than one match, rl_completion_matches has already
2450 put the lcd in matches[0]. Skip over it. */
2451 cmd_index
= matches
&& matches
[0] && matches
[1];
2453 /* If there's a single match and it's a directory, set the append char
2454 to the expected `/'. Otherwise, don't append anything. */
2455 if (matches
&& matches
[0] && matches
[1] == 0 && test_for_directory (matches
[0]))
2456 rl_completion_append_character
= '/';
2458 rl_completion_suppress_append
= 1;
2461 if (matches
== 0 || matches
[cmd_index
] == 0)
2463 rl_filename_quoting_desired
= 0; /* disable quoting */
2464 return ((char *)NULL
);
2468 value
= (char *)xmalloc (1 + start_len
+ strlen (matches
[cmd_index
]));
2471 value
[0] = *orig_start
;
2473 strncpy (value
, orig_start
, start_len
);
2475 strcpy (value
+ start_len
, matches
[cmd_index
]);
2482 /* Okay, now we write the entry_function for variable completion. */
2484 variable_completion_function (const char *text
, int state
)
2486 static char **varlist
= (char **)NULL
;
2487 static int varlist_index
;
2488 static char *varname
= (char *)NULL
;
2489 static int first_char
, first_char_loc
;
2497 first_char
= text
[0];
2499 if (first_char
== '$')
2502 if (text
[first_char_loc
] == '{')
2505 varname
= savestring (text
+ first_char_loc
);
2508 strvec_dispose (varlist
);
2510 varlist
= all_variables_matching_prefix (varname
);
2514 if (!varlist
|| !varlist
[varlist_index
])
2516 return ((char *)NULL
);
2522 value
= (char *)xmalloc (4 + strlen (varlist
[varlist_index
]));
2526 value
[0] = first_char
;
2527 if (first_char_loc
== 2)
2531 strcpy (value
+ first_char_loc
, varlist
[varlist_index
]);
2532 if (first_char_loc
== 2)
2533 strcat (value
, "}");
2540 /* How about a completion function for hostnames? */
2542 hostname_completion_function (const char *text
, int state
)
2544 static char **list
= (char **)NULL
;
2545 static int list_index
= 0;
2546 static int first_char
, first_char_loc
;
2548 /* If we don't have any state, make some. */
2553 list
= (char **)NULL
;
2558 if (first_char
== '@')
2561 list
= hostnames_matching ((char *)text
+first_char_loc
);
2565 if (list
&& list
[list_index
])
2569 t
= (char *)xmalloc (2 + strlen (list
[list_index
]));
2571 strcpy (t
+ first_char_loc
, list
[list_index
]);
2576 return ((char *)NULL
);
2580 * A completion function for service names from /etc/services (or wherever).
2583 bash_servicename_completion_function (const char *text
, int state
)
2585 #if defined (__WIN32__) || defined (__OPENNT) || !defined (HAVE_GETSERVENT)
2586 return ((char *)NULL
);
2588 static char *sname
= (char *)NULL
;
2589 static struct servent
*srvent
;
2590 static size_t snamelen
;
2592 char **alist
, *aentry
;
2599 sname
= savestring (text
);
2600 snamelen
= strlen (sname
);
2604 while (srvent
= getservent ())
2607 if (snamelen
== 0 || (STREQN (sname
, srvent
->s_name
, snamelen
)))
2609 /* Not primary, check aliases */
2610 for (alist
= srvent
->s_aliases
; *alist
; alist
++)
2613 if (STREQN (sname
, aentry
, snamelen
))
2627 return ((char *)NULL
);
2630 value
= afound
? savestring (aentry
) : savestring (srvent
->s_name
);
2636 * A completion function for group names from /etc/group (or wherever).
2639 bash_groupname_completion_function (const char *text
, int state
)
2641 #if defined (__WIN32__) || defined (__OPENNT) || !defined (HAVE_GRP_H)
2642 return ((char *)NULL
);
2644 static char *gname
= (char *)NULL
;
2645 static struct group
*grent
;
2646 static size_t gnamelen
;
2652 gname
= savestring (text
);
2653 gnamelen
= strlen (gname
);
2658 while (grent
= getgrent ())
2660 if (gnamelen
== 0 || (STREQN (gname
, grent
->gr_name
, gnamelen
)))
2667 return ((char *)NULL
);
2670 value
= savestring (grent
->gr_name
);
2675 /* Functions to perform history and alias expansions on the current line. */
2677 #if defined (BANG_HISTORY)
2678 /* Perform history expansion on the current line. If no history expansion
2679 is done, pre_process_line() returns what it was passed, so we need to
2680 allocate a new line here. */
2682 history_expand_line_internal (char *line
)
2687 old_verify
= hist_verify
;
2689 new_line
= pre_process_line (line
, 0, 0);
2690 hist_verify
= old_verify
;
2692 return (new_line
== line
) ? savestring (line
) : new_line
;
2696 /* There was an error in expansion. Let the preprocessor print
2699 cleanup_expansion_error (void)
2702 #if defined (BANG_HISTORY)
2705 old_verify
= hist_verify
;
2709 fprintf (rl_outstream
, "\r\n");
2710 to_free
= pre_process_line (rl_line_buffer
, 1, 0);
2711 #if defined (BANG_HISTORY)
2712 hist_verify
= old_verify
;
2714 if (to_free
!= rl_line_buffer
)
2716 putc ('\r', rl_outstream
);
2717 rl_forced_update_display ();
2720 /* If NEW_LINE differs from what is in the readline line buffer, add an
2721 undo record to get from the readline line buffer contents to the new
2722 line and make NEW_LINE the current readline line. */
2724 maybe_make_readline_line (const char *new_line
)
2726 if (new_line
&& strcmp (new_line
, rl_line_buffer
) != 0)
2730 rl_add_undo (UNDO_BEGIN
, 0, 0, 0);
2731 rl_delete_text (0, rl_point
);
2732 rl_point
= rl_end
= rl_mark
= 0;
2733 rl_insert_text (new_line
);
2734 rl_add_undo (UNDO_END
, 0, 0, 0);
2738 /* Make NEW_LINE be the current readline line. This frees NEW_LINE. We use
2739 several heuristics to decide where to put rl_point. */
2742 set_up_new_line (char *new_line
)
2745 int old_point
, old_end
, dist
, nb
;
2748 /* If we didn't expand anything, don't change anything. */
2749 if (STREQ (new_line
, rl_line_buffer
))
2755 old_point
= rl_point
;
2757 dist
= rl_end
- rl_point
;
2758 nb
= rl_end
- old_end
;
2760 /* If the line was history and alias expanded, then make that
2761 be one thing to undo. */
2762 maybe_make_readline_line (new_line
);
2765 /* Place rl_point where we think it should go. */
2768 else if (old_point
== 0)
2770 /* this is what the old code did, but separate it out so we can treat
2773 if (!whitespace (rl_line_buffer
[rl_point
]))
2774 rl_forward_word (1, 0);
2776 else if (rl_point
< old_point
+nb
)
2778 /* let's assume that this means the new point is within the changed region */
2779 rl_point
= old_point
;
2780 if (!whitespace (rl_line_buffer
[rl_point
]))
2781 rl_forward_word (1, 0);
2784 rl_point
= rl_end
- dist
; /* try to put point the same distance from end */
2788 else if (rl_point
> rl_end
)
2790 rl_mark
= 0; /* XXX */
2794 /* Expand aliases in the current readline line. */
2796 alias_expand_line (int count
, int ignore
)
2800 new_line
= alias_expand (rl_line_buffer
);
2804 set_up_new_line (new_line
);
2809 cleanup_expansion_error ();
2815 #if defined (BANG_HISTORY)
2816 /* History expand the line. */
2818 history_expand_line (int count
, int ignore
)
2822 new_line
= history_expand_line_internal (rl_line_buffer
);
2826 set_up_new_line (new_line
);
2831 cleanup_expansion_error ();
2836 /* Expand history substitutions in the current line and then insert a
2837 space (hopefully close to where we were before). */
2839 tcsh_magic_space (int count
, int ignore
)
2841 int dist_from_end
, old_point
;
2843 old_point
= rl_point
;
2844 dist_from_end
= rl_end
- rl_point
;
2845 if (history_expand_line (count
, ignore
) == 0)
2847 /* Try a simple heuristic from Stephen Gildea <gildea@intouchsys.com>.
2848 This works if all expansions were before rl_point or if no expansions
2850 rl_point
= (old_point
== 0) ? old_point
: rl_end
- dist_from_end
;
2857 #endif /* BANG_HISTORY */
2859 /* History and alias expand the line. */
2861 history_and_alias_expand_line (int count
, int ignore
)
2866 #if defined (BANG_HISTORY)
2867 new_line
= history_expand_line_internal (rl_line_buffer
);
2875 alias_line
= alias_expand (new_line
);
2877 new_line
= alias_line
;
2883 set_up_new_line (new_line
);
2888 cleanup_expansion_error ();
2893 /* History and alias expand the line, then perform the shell word
2894 expansions by calling expand_string. This can't use set_up_new_line()
2895 because we want the variable expansions as a separate undo'able
2896 set of operations. */
2898 shell_expand_line (int count
, int ignore
)
2901 WORD_LIST
*expanded_string
;
2905 #if defined (BANG_HISTORY)
2906 new_line
= history_expand_line_internal (rl_line_buffer
);
2909 t
= expand_string_dollar_quote (new_line
? new_line
: rl_line_buffer
, 0);
2918 alias_line
= alias_expand (new_line
);
2920 new_line
= alias_line
;
2926 int old_point
= rl_point
;
2927 int at_end
= rl_point
== rl_end
;
2929 /* If the line was history and alias expanded, then make that
2930 be one thing to undo. */
2931 maybe_make_readline_line (new_line
);
2934 /* If there is variable expansion to perform, do that as a separate
2935 operation to be undone. */
2938 w
= alloc_word_desc ();
2939 w
->word
= savestring (rl_line_buffer
);
2940 w
->flags
= rl_explicit_arg
? (W_NOPROCSUB
|W_NOCOMSUB
) : 0;
2941 expanded_string
= expand_word (w
, rl_explicit_arg
? Q_HERE_DOCUMENT
: 0);
2944 new_line
= savestring (rl_line_buffer
);
2945 expanded_string
= expand_string (new_line
, 0);
2949 if (expanded_string
== 0)
2951 new_line
= (char *)xmalloc (1);
2956 new_line
= string_list (expanded_string
);
2957 dispose_words (expanded_string
);
2960 maybe_make_readline_line (new_line
);
2963 /* Place rl_point where we think it should go. */
2966 else if (old_point
< rl_end
)
2968 rl_point
= old_point
;
2969 if (!whitespace (rl_line_buffer
[rl_point
]))
2970 rl_forward_word (1, 0);
2976 cleanup_expansion_error ();
2981 /* If FIGNORE is set, then don't match files with the given suffixes when
2982 completing filenames. If only one of the possibilities has an acceptable
2983 suffix, delete the others, else just return and let the completer
2984 signal an error. It is called by the completer when real
2985 completions are done on filenames by the completer's internal
2986 function, not for completion lists (M-?) and not on "other"
2987 completion types, such as hostnames or commands. */
2989 static struct ignorevar fignore
=
2995 (sh_iv_item_func_t
*) 0,
2999 _ignore_completion_names (char **names
, sh_ignore_func_t
*name_func
)
3006 /* If there is only one completion, see if it is acceptable. If it is
3007 not, free it up. In any case, short-circuit and return. This is a
3008 special case because names[0] is not the prefix of the list of names
3009 if there is only one completion; it is the completion itself. */
3010 if (names
[1] == (char *)0)
3013 if ((*name_func
) (names
[0]) == 0)
3016 names
[0] = (char *)NULL
;
3022 /* Allocate space for array to hold list of pointers to matching
3023 filenames. The pointers are copied back to NAMES when done. */
3024 for (nidx
= 1; names
[nidx
]; nidx
++)
3026 newnames
= strvec_create (nidx
+ 1);
3028 if (force_fignore
== 0)
3030 oldnames
= strvec_create (nidx
- 1);
3034 newnames
[0] = names
[0];
3035 for (idx
= nidx
= 1; names
[idx
]; idx
++)
3037 if ((*name_func
) (names
[idx
]))
3038 newnames
[nidx
++] = names
[idx
];
3039 else if (force_fignore
== 0)
3040 oldnames
[oidx
++] = names
[idx
];
3045 newnames
[nidx
] = (char *)NULL
;
3047 /* If none are acceptable then let the completer handle it. */
3053 names
[0] = (char *)NULL
;
3062 if (force_fignore
== 0)
3065 free (oldnames
[--oidx
]);
3069 /* If only one is acceptable, copy it to names[0] and return. */
3073 names
[0] = newnames
[1];
3074 names
[1] = (char *)NULL
;
3079 /* Copy the acceptable names back to NAMES, set the new array end,
3081 for (nidx
= 1; newnames
[nidx
]; nidx
++)
3082 names
[nidx
] = newnames
[nidx
];
3083 names
[nidx
] = (char *)NULL
;
3088 name_is_acceptable (const char *name
)
3093 for (nlen
= strlen (name
), p
= fignore
.ignores
; p
->val
; p
++)
3095 if (nlen
>= p
->len
&& p
->len
> 0 && STREQ (p
->val
, &name
[nlen
- p
->len
]))
3104 ignore_dot_names (const char *name
)
3106 return (name
[0] != '.');
3111 filename_completion_ignore (char **names
)
3114 if (glob_dot_filenames
== 0)
3115 _ignore_completion_names (names
, ignore_dot_names
);
3118 setup_ignore_patterns (&fignore
);
3120 if (fignore
.num_ignores
== 0)
3123 _ignore_completion_names (names
, name_is_acceptable
);
3128 /* Return 1 if NAME is a directory. NAME undergoes tilde expansion. */
3130 test_for_directory (const char *name
)
3135 fn
= bash_tilde_expand (name
, 0);
3138 /* stat("//server") can only be successful as a directory, but can take
3139 seconds to time out on failure. It is much faster to assume that
3140 "//server" is a valid name than it is to wait for a stat, even if it
3141 gives false positives on bad names. */
3142 if (fn
[0] == '/' && fn
[1] == '/' && ! strchr (&fn
[2], '/'))
3149 r
= file_isdir (fn
);
3156 test_for_canon_directory (const char *name
)
3161 fn
= (*name
== '~') ? bash_tilde_expand (name
, 0) : savestring (name
);
3162 bash_filename_stat_hook (&fn
);
3163 r
= file_isdir (fn
);
3169 /* Remove files from NAMES, leaving directories. */
3171 bash_ignore_filenames (char **names
)
3173 _ignore_completion_names (names
, test_for_directory
);
3178 bash_progcomp_ignore_filenames (char **names
)
3180 _ignore_completion_names (names
, test_for_canon_directory
);
3185 return_zero (const char *name
)
3191 bash_ignore_everything (char **names
)
3193 _ignore_completion_names (names
, return_zero
);
3197 /* Replace a tilde-prefix in VAL with a `~', assuming the user typed it. VAL
3198 is an expanded filename. DIRECTORY_PART is the tilde-prefix portion
3199 of the un-tilde-expanded version of VAL (what the user typed). */
3201 restore_tilde (const char *val
, char *directory_part
)
3203 size_t l
, vl
, dl2
, xl
;
3204 char *dh2
, *expdir
, *ret
, *v
;
3208 /* We need to duplicate the expansions readline performs on the directory
3209 portion before passing it to our completion function. */
3210 dh2
= directory_part
? bash_dequote_filename (directory_part
, 0) : 0;
3211 bash_directory_expansion (&dh2
);
3214 expdir
= bash_tilde_expand (directory_part
, 0);
3215 xl
= strlen (expdir
);
3216 if (*directory_part
== '~' && STREQ (directory_part
, expdir
))
3218 /* tilde expansion failed, so what should we return? we use what the
3220 v
= mbschr (val
, '/');
3222 ret
= (char *)xmalloc (xl
+ vl
+ 2);
3223 strcpy (ret
, directory_part
);
3225 strcpy (ret
+ xl
, v
);
3235 dh2 = unexpanded but dequoted tilde-prefix
3236 dl2 = length of tilde-prefix
3237 expdir = tilde-expanded tilde-prefix
3238 xl = length of expanded tilde-prefix
3239 l = length of remainder after tilde-prefix
3245 return (savestring (val
)); /* XXX - just punt */
3248 ret
= (char *)xmalloc (dl2
+ 2 + l
);
3250 strcpy (ret
+ dl2
, val
+ xl
);
3257 maybe_restore_tilde (char *val
, char *directory_part
)
3259 rl_icppfunc_t
*save
;
3262 save
= (dircomplete_expand
== 0) ? save_directory_hook () : (rl_icppfunc_t
*)0;
3263 ret
= restore_tilde (val
, directory_part
);
3265 restore_directory_hook (save
);
3269 /* Simulate the expansions that will be performed by
3270 rl_filename_completion_function. This must be called with the address of
3271 a pointer to malloc'd memory. */
3273 bash_directory_expansion (char **dirname
)
3277 d
= savestring (*dirname
);
3279 if ((rl_directory_rewrite_hook
) && (*rl_directory_rewrite_hook
) (&d
))
3284 else if (rl_directory_completion_hook
&& (*rl_directory_completion_hook
) (&d
))
3289 else if (rl_completion_found_quote
)
3291 nd
= bash_dequote_filename (d
, rl_completion_quote_character
);
3300 /* If necessary, rewrite directory entry */
3302 bash_filename_rewrite_hook (char *fname
, int fnlen
)
3306 conv
= fnx_fromfs (fname
, fnlen
);
3308 conv
= savestring (conv
);
3312 /* Functions to save and restore the appropriate directory hook */
3313 /* This is not static so the shopt code can call it */
3315 set_directory_hook (void)
3317 if (dircomplete_expand
)
3319 rl_directory_completion_hook
= bash_directory_completion_hook
;
3320 rl_directory_rewrite_hook
= (rl_icppfunc_t
*)0;
3324 rl_directory_rewrite_hook
= bash_directory_completion_hook
;
3325 rl_directory_completion_hook
= (rl_icppfunc_t
*)0;
3329 static rl_icppfunc_t
*
3330 save_directory_hook (void)
3334 if (dircomplete_expand
)
3336 ret
= rl_directory_completion_hook
;
3337 rl_directory_completion_hook
= (rl_icppfunc_t
*)NULL
;
3341 ret
= rl_directory_rewrite_hook
;
3342 rl_directory_rewrite_hook
= (rl_icppfunc_t
*)NULL
;
3349 restore_directory_hook (rl_icppfunc_t
*hookf
)
3351 if (dircomplete_expand
)
3352 rl_directory_completion_hook
= hookf
;
3354 rl_directory_rewrite_hook
= hookf
;
3357 /* Set the readline hooks that affect how directories and filenames are
3358 converted. Extern so other parts of the shell can use. */
3360 bashline_set_filename_hooks (void)
3362 /* Tell the completer that we might want to follow symbolic links or
3363 do other expansion on directory names. */
3364 set_directory_hook ();
3366 rl_filename_rewrite_hook
= bash_filename_rewrite_hook
;
3367 rl_completion_rewrite_hook
= bash_filename_rewrite_hook
;
3368 rl_filename_stat_hook
= bash_filename_stat_hook
;
3371 /* Check whether not DIRNAME, with any trailing slash removed, exists. If
3372 SHOULD_DEQUOTE is non-zero, we dequote the directory name first. */
3374 directory_exists (const char *dirname
, int should_dequote
)
3380 /* We save the string and chop the trailing slash because stat/lstat behave
3381 inconsistently if one is present. */
3382 new_dirname
= should_dequote
? bash_dequote_filename ((char *)dirname
, rl_completion_quote_character
) : savestring (dirname
);
3383 dirlen
= STRLEN (new_dirname
);
3384 if (new_dirname
[dirlen
- 1] == '/')
3385 new_dirname
[dirlen
- 1] = '\0';
3386 #if defined (HAVE_LSTAT)
3387 r
= lstat (new_dirname
, &sb
) == 0;
3389 r
= stat (new_dirname
, &sb
) == 0;
3396 bash_expand_filename (char *filename
)
3402 newname
= savestring (filename
);
3403 /* no error messages, and expand_prompt_string doesn't longjmp so we don't
3404 have to worry about restoring this setting. */
3405 global_nounset
= unbound_vars_is_error
;
3406 unbound_vars_is_error
= 0;
3407 wl
= expand_prompt_string (newname
, 0, W_NOCOMSUB
|W_NOPROCSUB
|W_COMPLETE
); /* does the right thing */
3408 unbound_vars_is_error
= global_nounset
;
3415 newname
= string_list (wl
);
3417 if (newname
&& *newname
&& STREQ (newname
, filename
))
3426 /* Expand a filename before the readline completion code passes it to stat(2).
3427 The filename will already have had tilde expansion performed. */
3429 bash_filename_stat_hook (char **dirname
)
3431 char *local_dirname
, *new_dirname
, *t
;
3432 int should_expand_dirname
, return_value
;
3436 local_dirname
= *dirname
;
3437 should_expand_dirname
= return_value
= 0;
3438 if (t
= mbschr (local_dirname
, '$'))
3439 should_expand_dirname
= '$';
3440 else if (t
= mbschr (local_dirname
, '`')) /* XXX */
3441 should_expand_dirname
= '`';
3443 if (should_expand_dirname
&& directory_exists (local_dirname
, 0))
3444 should_expand_dirname
= 0;
3446 if (should_expand_dirname
)
3448 new_dirname
= savestring (local_dirname
);
3449 /* no error messages, and expand_prompt_string doesn't longjmp so we don't
3450 have to worry about restoring this setting. */
3451 global_nounset
= unbound_vars_is_error
;
3452 unbound_vars_is_error
= 0;
3453 wl
= expand_prompt_string (new_dirname
, 0, W_NOCOMSUB
|W_NOPROCSUB
|W_COMPLETE
); /* does the right thing */
3454 unbound_vars_is_error
= global_nounset
;
3458 new_dirname
= string_list (wl
);
3459 /* Tell the completer we actually expanded something and change
3460 *dirname only if we expanded to something non-null -- stat
3461 behaves unpredictably when passed null or empty strings */
3462 if (new_dirname
&& *new_dirname
)
3464 free (local_dirname
); /* XXX */
3465 local_dirname
= *dirname
= new_dirname
;
3466 return_value
= STREQ (local_dirname
, *dirname
) == 0;
3476 /* This is very similar to the code in bash_directory_completion_hook below,
3477 but without spelling correction and not worrying about whether or not
3478 we change relative pathnames. */
3479 if (no_symbolic_links
== 0 && (local_dirname
[0] != '.' || local_dirname
[1]))
3481 char *temp1
, *temp2
;
3483 t
= get_working_directory ("symlink-hook");
3484 temp1
= make_absolute (local_dirname
, t
);
3486 temp2
= sh_canonpath (temp1
, PATH_CHECKDOTDOT
|PATH_CHECKEXISTS
);
3488 /* If we can't canonicalize, bail. */
3492 return return_value
;
3495 free (local_dirname
);
3500 return (return_value
);
3503 /* Handle symbolic link references and other directory name
3504 expansions while hacking completion. This should return 1 if it modifies
3505 the DIRNAME argument, 0 otherwise. It should make sure not to modify
3506 DIRNAME if it returns 0. */
3508 bash_directory_completion_hook (char **dirname
)
3510 char *local_dirname
, *new_dirname
, *t
;
3511 int return_value
, should_expand_dirname
, nextch
, closer
;
3514 return_value
= should_expand_dirname
= nextch
= closer
= 0;
3515 local_dirname
= *dirname
;
3517 should_expand_dirname
= bash_check_expchar (local_dirname
, 1, &nextch
, &closer
);
3519 if (should_expand_dirname
&& directory_exists (local_dirname
, 1))
3520 should_expand_dirname
= 0;
3522 if (should_expand_dirname
)
3524 new_dirname
= savestring (local_dirname
);
3525 wl
= expand_prompt_string (new_dirname
, 0, W_NOCOMSUB
|W_NOPROCSUB
|W_COMPLETE
); /* does the right thing */
3528 *dirname
= string_list (wl
);
3529 /* Tell the completer to replace the directory name only if we
3530 actually expanded something. */
3531 return_value
= STREQ (local_dirname
, *dirname
) == 0;
3532 free (local_dirname
);
3535 local_dirname
= *dirname
;
3537 set_filename_quote_chars (should_expand_dirname
, nextch
, closer
);
3542 free (local_dirname
);
3543 *dirname
= (char *)xmalloc (1);
3550 /* Dequote the filename even if we don't expand it. */
3551 new_dirname
= bash_dequote_filename (local_dirname
, rl_completion_quote_character
);
3552 return_value
= STREQ (local_dirname
, new_dirname
) == 0;
3553 free (local_dirname
);
3554 local_dirname
= *dirname
= new_dirname
;
3557 /* no_symbolic_links == 0 -> use (default) logical view of the file system.
3558 local_dirname[0] == '.' && local_dirname[1] == '/' means files in the
3559 current directory (./).
3560 local_dirname[0] == '.' && local_dirname[1] == 0 means relative pathnames
3561 in the current directory (e.g., lib/sh).
3562 XXX - should we do spelling correction on these? */
3564 /* This is test as it was in bash-4.2: skip relative pathnames in current
3565 directory. Change test to
3566 (local_dirname[0] != '.' || (local_dirname[1] && local_dirname[1] != '/'))
3567 if we want to skip paths beginning with ./ also. */
3568 if (no_symbolic_links
== 0 && (local_dirname
[0] != '.' || local_dirname
[1]))
3570 char *temp1
, *temp2
;
3573 /* If we have a relative path
3574 (local_dirname[0] != '/' && local_dirname[0] != '.')
3575 that is canonical after appending it to the current directory, then
3578 strcmp (temp1, temp2) == 0
3579 after adding a slash to temp2 below. It should be safe to not
3582 t
= get_working_directory ("symlink-hook");
3583 temp1
= make_absolute (local_dirname
, t
);
3585 temp2
= sh_canonpath (temp1
, PATH_CHECKDOTDOT
|PATH_CHECKEXISTS
);
3587 /* Try spelling correction if initial canonicalization fails. Make
3588 sure we are set to replace the directory name with the results so
3589 subsequent directory checks don't fail. */
3590 if (temp2
== 0 && dircomplete_spelling
&& dircomplete_expand
)
3594 temp2
= dirspell (temp1
);
3595 l2
= STRLEN (temp2
);
3596 /* Don't take matches if they are shorter than the original path */
3597 if (temp2
&& l2
< strlen (temp1
) && STREQN (temp1
, temp2
, l2
))
3606 temp2
= sh_canonpath (temp1
, PATH_CHECKDOTDOT
|PATH_CHECKEXISTS
);
3607 return_value
|= temp2
!= 0;
3610 /* If we can't canonicalize, bail. */
3614 return return_value
;
3616 len1
= strlen (temp1
);
3617 if (temp1
[len1
- 1] == '/')
3619 len2
= strlen (temp2
);
3620 if (len2
> 2) /* don't append `/' to `/' or `//' */
3622 temp2
= (char *)xrealloc (temp2
, len2
+ 2);
3624 temp2
[len2
+ 1] = '\0';
3628 /* dircomplete_expand_relpath == 0 means we want to leave relative
3629 pathnames that are unchanged by canonicalization alone.
3630 *local_dirname != '/' && *local_dirname != '.' == relative pathname
3631 (consistent with general.c:absolute_pathname())
3632 temp1 == temp2 (after appending a slash to temp2) means the pathname
3633 is not changed by canonicalization as described above. */
3634 if (dircomplete_expand_relpath
|| ((local_dirname
[0] != '/' && local_dirname
[0] != '.') && STREQ (temp1
, temp2
) == 0))
3635 return_value
|= STREQ (local_dirname
, temp2
) == 0;
3636 free (local_dirname
);
3641 return (return_value
);
3644 static char **history_completion_array
= (char **)NULL
;
3645 static size_t harry_size
;
3646 static size_t harry_len
;
3649 build_history_completion_array (void)
3655 /* First, clear out the current dynamic history completion list. */
3658 strvec_dispose (history_completion_array
);
3659 history_completion_array
= (char **)NULL
;
3664 /* Next, grovel each line of history, making each shell-sized token
3665 a separate entry in the history_completion_array. */
3666 hlist
= history_list ();
3670 for (i
= 0; hlist
[i
]; i
++)
3672 for ( --i
; i
>= 0; i
--)
3674 /* Separate each token, and place into an array. */
3675 tokens
= history_tokenize (hlist
[i
]->line
);
3677 for (j
= 0; tokens
&& tokens
[j
]; j
++)
3679 if (harry_len
+ 2 > harry_size
)
3680 history_completion_array
= strvec_resize (history_completion_array
, harry_size
+= 10);
3682 history_completion_array
[harry_len
++] = tokens
[j
];
3683 history_completion_array
[harry_len
] = (char *)NULL
;
3688 /* Sort the complete list of tokens. */
3689 if (dabbrev_expand_active
== 0)
3690 qsort (history_completion_array
, harry_len
, sizeof (char *), (QSFUNC
*)strvec_strcmp
);
3695 history_completion_generator (const char *hint_text
, int state
)
3697 static int local_index
;
3699 static const char *text
;
3701 /* If this is the first call to the generator, then initialize the
3702 list of strings to complete over. */
3705 if (dabbrev_expand_active
) /* This is kind of messy */
3706 rl_completion_suppress_append
= 1;
3708 build_history_completion_array ();
3710 len
= strlen (text
);
3713 while (history_completion_array
&& history_completion_array
[local_index
])
3715 /* XXX - should this use completion-ignore-case? */
3716 if (strncmp (text
, history_completion_array
[local_index
++], len
) == 0)
3717 return (savestring (history_completion_array
[local_index
- 1]));
3719 return ((char *)NULL
);
3723 dynamic_complete_history (int count
, int key
)
3726 rl_compentry_func_t
*orig_func
;
3727 rl_completion_func_t
*orig_attempt_func
;
3728 rl_compignore_func_t
*orig_ignore_func
;
3730 orig_func
= rl_completion_entry_function
;
3731 orig_attempt_func
= rl_attempted_completion_function
;
3732 orig_ignore_func
= rl_ignore_some_completions_function
;
3734 rl_completion_entry_function
= history_completion_generator
;
3735 rl_attempted_completion_function
= (rl_completion_func_t
*)NULL
;
3736 rl_ignore_some_completions_function
= filename_completion_ignore
;
3738 /* XXX - use rl_completion_mode here? */
3739 if (rl_last_func
== dynamic_complete_history
)
3740 r
= rl_complete_internal ('?');
3742 r
= rl_complete_internal (TAB
);
3744 rl_completion_entry_function
= orig_func
;
3745 rl_attempted_completion_function
= orig_attempt_func
;
3746 rl_ignore_some_completions_function
= orig_ignore_func
;
3752 bash_dabbrev_expand (int count
, int key
)
3754 int r
, orig_suppress
, orig_sort
;
3755 rl_compentry_func_t
*orig_func
;
3756 rl_completion_func_t
*orig_attempt_func
;
3757 rl_compignore_func_t
*orig_ignore_func
;
3759 orig_func
= rl_menu_completion_entry_function
;
3760 orig_attempt_func
= rl_attempted_completion_function
;
3761 orig_ignore_func
= rl_ignore_some_completions_function
;
3762 orig_suppress
= rl_completion_suppress_append
;
3763 orig_sort
= rl_sort_completion_matches
;
3765 rl_menu_completion_entry_function
= history_completion_generator
;
3766 rl_attempted_completion_function
= (rl_completion_func_t
*)NULL
;
3767 rl_ignore_some_completions_function
= filename_completion_ignore
;
3768 rl_filename_completion_desired
= 0;
3769 rl_completion_suppress_append
= 1;
3770 rl_sort_completion_matches
= 0;
3772 /* XXX - use rl_completion_mode here? */
3773 dabbrev_expand_active
= 1;
3774 if (rl_last_func
== bash_dabbrev_expand
)
3775 rl_last_func
= rl_menu_complete
;
3776 r
= rl_menu_complete (count
, key
);
3777 dabbrev_expand_active
= 0;
3779 rl_last_func
= bash_dabbrev_expand
;
3780 rl_menu_completion_entry_function
= orig_func
;
3781 rl_attempted_completion_function
= orig_attempt_func
;
3782 rl_ignore_some_completions_function
= orig_ignore_func
;
3783 rl_completion_suppress_append
= orig_suppress
;
3784 rl_sort_completion_matches
= orig_sort
;
3789 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
3791 bash_complete_username (int ignore
, int ignore2
)
3793 return bash_complete_username_internal (rl_completion_mode (bash_complete_username
));
3797 bash_possible_username_completions (int ignore
, int ignore2
)
3799 return bash_complete_username_internal ('?');
3803 bash_complete_username_internal (int what_to_do
)
3805 return bash_specific_completion (what_to_do
, rl_username_completion_function
);
3809 bash_complete_filename (int ignore
, int ignore2
)
3811 return bash_complete_filename_internal (rl_completion_mode (bash_complete_filename
));
3815 bash_possible_filename_completions (int ignore
, int ignore2
)
3817 return bash_complete_filename_internal ('?');
3821 bash_complete_filename_internal (int what_to_do
)
3823 rl_compentry_func_t
*orig_func
;
3824 rl_completion_func_t
*orig_attempt_func
;
3825 rl_icppfunc_t
*orig_dir_func
;
3826 rl_compignore_func_t
*orig_ignore_func
;
3827 const char *orig_rl_completer_word_break_characters
;
3830 orig_func
= rl_completion_entry_function
;
3831 orig_attempt_func
= rl_attempted_completion_function
;
3832 orig_ignore_func
= rl_ignore_some_completions_function
;
3833 orig_rl_completer_word_break_characters
= rl_completer_word_break_characters
;
3835 orig_dir_func
= save_directory_hook ();
3837 rl_completion_entry_function
= rl_filename_completion_function
;
3838 rl_attempted_completion_function
= (rl_completion_func_t
*)NULL
;
3839 rl_ignore_some_completions_function
= filename_completion_ignore
;
3840 rl_completer_word_break_characters
= " \t\n\"\'";
3842 r
= rl_complete_internal (what_to_do
);
3844 rl_completion_entry_function
= orig_func
;
3845 rl_attempted_completion_function
= orig_attempt_func
;
3846 rl_ignore_some_completions_function
= orig_ignore_func
;
3847 rl_completer_word_break_characters
= orig_rl_completer_word_break_characters
;
3849 restore_directory_hook (orig_dir_func
);
3855 bash_complete_hostname (int ignore
, int ignore2
)
3857 return bash_complete_hostname_internal (rl_completion_mode (bash_complete_hostname
));
3861 bash_possible_hostname_completions (int ignore
, int ignore2
)
3863 return bash_complete_hostname_internal ('?');
3867 bash_complete_variable (int ignore
, int ignore2
)
3869 return bash_complete_variable_internal (rl_completion_mode (bash_complete_variable
));
3873 bash_possible_variable_completions (int ignore
, int ignore2
)
3875 return bash_complete_variable_internal ('?');
3879 bash_complete_command (int ignore
, int ignore2
)
3881 return bash_complete_command_internal (rl_completion_mode (bash_complete_command
));
3885 bash_possible_command_completions (int ignore
, int ignore2
)
3887 return bash_complete_command_internal ('?');
3891 bash_complete_hostname_internal (int what_to_do
)
3893 return bash_specific_completion (what_to_do
, hostname_completion_function
);
3897 bash_complete_variable_internal (int what_to_do
)
3899 return bash_specific_completion (what_to_do
, variable_completion_function
);
3903 bash_complete_command_internal (int what_to_do
)
3905 return bash_specific_completion (what_to_do
, command_word_completion_function
);
3909 completion_glob_pattern (const char *string
)
3911 return (glob_pattern_p (string
) == 1);
3914 static char *globtext
;
3915 static char *globorig
;
3918 glob_complete_word (const char *text
, int state
)
3920 static char **matches
= (char **)NULL
;
3927 rl_filename_completion_desired
= 1;
3929 matches
= (char **)NULL
;
3930 if (globorig
!= globtext
)
3933 globorig
= globtext
= (char *)NULL
;
3935 ttext
= bash_tilde_expand (text
, 0);
3937 if (rl_explicit_arg
)
3939 globorig
= savestring (ttext
);
3940 glen
= strlen (ttext
);
3941 globtext
= (char *)xmalloc (glen
+ 2);
3942 strcpy (globtext
, ttext
);
3943 globtext
[glen
] = '*';
3944 globtext
[glen
+1] = '\0';
3947 globtext
= globorig
= savestring (ttext
);
3952 matches
= shell_glob_filename (globtext
, 0);
3953 if (GLOB_FAILED (matches
))
3954 matches
= (char **)NULL
;
3958 ret
= matches
? matches
[ind
] : (char *)NULL
;
3964 bash_glob_completion_internal (int what_to_do
)
3966 return bash_specific_completion (what_to_do
, glob_complete_word
);
3969 /* A special quoting function so we don't end up quoting globbing characters
3970 in the word if there are no matches or multiple matches. */
3972 bash_glob_quote_filename (char *s
, int rtype
, char *qcp
)
3974 if (globorig
&& qcp
&& *qcp
== '\0' && STREQ (s
, globorig
))
3975 return (savestring (s
));
3977 return (bash_quote_filename (s
, rtype
, qcp
));
3981 bash_glob_complete_word (int count
, int key
)
3984 rl_quote_func_t
*orig_quoting_function
;
3986 if (rl_editing_mode
== EMACS_EDITING_MODE
)
3987 rl_explicit_arg
= 1; /* force `*' append */
3988 orig_quoting_function
= rl_filename_quoting_function
;
3989 rl_filename_quoting_function
= bash_glob_quote_filename
;
3991 r
= bash_glob_completion_internal (rl_completion_mode (bash_glob_complete_word
));
3993 rl_filename_quoting_function
= orig_quoting_function
;
3998 bash_glob_expand_word (int count
, int key
)
4000 return bash_glob_completion_internal ('*');
4004 bash_glob_list_expansions (int count
, int key
)
4006 return bash_glob_completion_internal ('?');
4010 bash_specific_completion (int what_to_do
, rl_compentry_func_t
*generator
)
4012 rl_compentry_func_t
*orig_func
;
4013 rl_completion_func_t
*orig_attempt_func
;
4014 rl_compignore_func_t
*orig_ignore_func
;
4017 orig_func
= rl_completion_entry_function
;
4018 orig_attempt_func
= rl_attempted_completion_function
;
4019 orig_ignore_func
= rl_ignore_some_completions_function
;
4020 rl_completion_entry_function
= generator
;
4021 rl_attempted_completion_function
= NULL
;
4022 rl_ignore_some_completions_function
= orig_ignore_func
;
4024 r
= rl_complete_internal (what_to_do
);
4026 rl_completion_entry_function
= orig_func
;
4027 rl_attempted_completion_function
= orig_attempt_func
;
4028 rl_ignore_some_completions_function
= orig_ignore_func
;
4033 #endif /* SPECIFIC_COMPLETION_FUNCTIONS */
4035 #if defined (VI_MODE)
4036 /* This does pretty much what _rl_vi_advance_point does. */
4038 vi_advance_point (void)
4044 if (rl_point
< rl_end
)
4045 #if defined (HANDLE_MULTIBYTE)
4047 if (locale_mb_cur_max
== 1)
4052 ADVANCE_CHAR (rl_line_buffer
, rl_end
, rl_point
);
4053 if (point
== rl_point
|| rl_point
> rl_end
)
4063 /* Completion, from vi mode's point of view. This is a modified version of
4064 rl_vi_complete which uses the bash globbing code to implement what POSIX
4065 specifies, which is to optinally append a `*' and attempt filename
4066 generation (which has the side effect of expanding any globbing characters
4069 bash_vi_complete (int count
, int key
)
4071 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
4075 if ((rl_point
< rl_end
) && (!whitespace (rl_line_buffer
[rl_point
])))
4077 if (!whitespace (rl_line_buffer
[rl_point
+ 1]))
4078 rl_vi_end_word (1, 'E');
4079 vi_advance_point ();
4082 /* Find boundaries of current word, according to vi definition of a
4088 rl_vi_bWord (1, 'B');
4093 t
= substring (rl_line_buffer
, p
, rl_point
);
4096 if (t
&& completion_glob_pattern (t
) == 0)
4097 rl_explicit_arg
= 1; /* XXX - force glob_complete_word to append `*' */
4100 if (key
== '*') /* Expansion and replacement. */
4101 r
= bash_glob_expand_word (count
, key
);
4102 else if (key
== '=') /* List possible completions. */
4103 r
= bash_glob_list_expansions (count
, key
);
4104 else if (key
== '\\') /* Standard completion */
4105 r
= bash_glob_complete_word (count
, key
);
4107 r
= rl_complete (0, key
);
4109 if (key
== '*' || key
== '\\')
4110 rl_vi_start_inserting (key
, 1, 1);
4114 return rl_vi_complete (count
, key
);
4115 #endif /* !SPECIFIC_COMPLETION_FUNCTIONS */
4117 #endif /* VI_MODE */
4119 /* Filename quoting for completion. */
4120 /* A function to strip unquoted quote characters (single quotes, double
4121 quotes, and backslashes). It allows single quotes to appear
4122 within double quotes, and vice versa. It should be smarter. */
4124 bash_dequote_filename (char *text
, int quote_char
)
4131 ret
= (char *)xmalloc (l
+ 1);
4132 for (quoted
= quote_char
, p
= text
, r
= ret
; p
&& *p
; p
++)
4134 /* Allow backslash-escaped characters to pass through unscathed. Backslashes
4135 aren't special in single quotes. */
4136 if (quoted
!= '\'' && *p
== '\\')
4138 /* Backslashes are preserved within double quotes unless the
4139 character is one that is defined to be escaped */
4140 if (quoted
== '"' && ((sh_syntaxtab
[(unsigned char)p
[1]] & CBSDQUOTE
) == 0))
4145 return ret
; /* XXX - was break; */
4149 if (quoted
&& *p
== quoted
)
4155 if (quoted
== 0 && (*p
== '\'' || *p
== '"'))
4166 /* Quote characters that the readline completion code would treat as
4167 word break characters with backslashes. Pass backslash-quoted
4168 characters through without examination. */
4170 quote_word_break_chars (char *text
)
4176 ret
= (char *)xmalloc ((2 * l
) + 1);
4177 for (s
= text
, r
= ret
; *s
; s
++)
4179 /* Pass backslash-quoted characters through, including the backslash. */
4188 /* OK, we have an unquoted character. Check its presence in
4189 rl_completer_word_break_characters. */
4190 if (mbschr (rl_completer_word_break_characters
, *s
))
4192 /* XXX -- check for standalone tildes here and backslash-quote them */
4193 if (s
== text
&& *s
== '~' && file_exists (text
))
4201 /* Return a character in DIRNAME that will cause shell expansion to be
4202 performed. If NEXTP is non-null, *NEXTP gets the expansion character that
4203 follows RET (e.g., '{' or `(' for `$'). If CLOSERP is non-null, *CLOSERP
4204 gets the character that should close <RET><NEXTP>. If NEED_CLOSER is non-
4205 zero, any expansion pair that isn't closed causes this function to
4206 return 0, which indicates that we didn't find an expansion character. It's
4207 used in case DIRNAME is going to be expanded. If DIRNAME is just going to
4208 be quoted, NEED_CLOSER will be 0. */
4210 bash_check_expchar (char *dirname
, int need_closer
, int *nextp
, int *closerp
)
4216 if (t
= mbschr (dirname
, '$'))
4220 /* Deliberately does not handle the deprecated $[...] arithmetic
4229 if (c
&& need_closer
) /* XXX */
4234 delims
[0] = c
; delims
[1] = 0;
4235 p
= skip_to_delim (t
, 1, delims
, SD_NOJMP
|SD_COMPLETE
);
4240 else if (dirname
[0] == '~')
4244 t
= mbschr (dirname
, '`');
4247 if (need_closer
== 0)
4249 else if (unclosed_pair (dirname
, strlen (dirname
), "`") == 0)
4262 /* Make sure EXPCHAR and, if non-zero, NEXTCH and CLOSER are not in the set
4263 of characters to be backslash-escaped. This is the only place
4264 custom_filename_quote_characters is modified. */
4266 set_filename_quote_chars (int expchar
, int nextch
, int closer
)
4271 if (rl_filename_quote_characters
&& *rl_filename_quote_characters
)
4273 i
= strlen (default_filename_quote_characters
);
4274 custom_filename_quote_characters
= xrealloc (custom_filename_quote_characters
, i
+1);
4275 for (i
= j
= 0; c
= default_filename_quote_characters
[i
]; i
++)
4277 if (c
== expchar
|| c
== nextch
|| c
== closer
)
4279 custom_filename_quote_characters
[j
++] = c
;
4281 custom_filename_quote_characters
[j
] = '\0';
4282 rl_filename_quote_characters
= custom_filename_quote_characters
;
4283 set_filename_bstab (rl_filename_quote_characters
);
4287 /* Use characters in STRING to populate the table of characters that should
4288 be backslash-quoted. The table will be used for sh_backslash_quote from
4291 set_filename_bstab (const char *string
)
4295 memset (filename_bstab
, 0, sizeof (filename_bstab
));
4296 for (s
= string
; s
&& *s
; s
++)
4297 filename_bstab
[(unsigned char)*s
] = 1;
4300 /* Quote a filename using double quotes, single quotes, or backslashes
4301 depending on the value of completion_quoting_style. If we're
4302 completing using backslashes, we need to quote some additional
4303 characters (those that readline treats as word breaks), so we call
4304 quote_word_break_chars on the result. This returns newly-allocated
4307 bash_quote_filename (char *s
, int rtype
, char *qcp
)
4309 char *rtext
, *mtext
, *ret
;
4311 int cs
, expchar
, nextch
, closer
;
4313 rtext
= (char *)NULL
;
4315 /* If RTYPE == MULT_MATCH, it means that there is
4316 more than one match. In this case, we do not add
4317 the closing quote or attempt to perform tilde
4318 expansion. If RTYPE == SINGLE_MATCH, we try
4319 to perform tilde expansion, because single and double
4320 quotes inhibit tilde expansion by the shell. */
4322 cs
= completion_quoting_style
;
4323 /* Might need to modify the default completion style based on *qcp,
4324 since it's set to any user-provided opening quote. We also change
4325 to single-quoting if there is no user-provided opening quote and
4326 the word being completed contains newlines, since those are not
4327 quoted correctly using backslashes (a backslash-newline pair is
4328 special to the shell parser). */
4329 expchar
= nextch
= closer
= 0;
4330 if (*qcp
== '\0' && cs
== COMPLETE_BSQUOTE
&& dircomplete_expand
== 0 &&
4331 (expchar
= bash_check_expchar (s
, 0, &nextch
, &closer
)) &&
4332 file_exists (s
) == 0)
4334 /* If it looks like the name is subject to expansion, see if we want to
4336 if (expchar
== '$' || expchar
== '`')
4339 newname
= bash_expand_filename (s
);
4340 if (newname
&& strpbrk (newname
, rl_filename_quote_characters
))
4341 cs
= COMPLETE_DQUOTE2
;
4345 /* Usually this will have been set by bash_directory_completion_hook,
4346 but there are cases where it will not be. */
4347 if (rl_filename_quote_characters
!= custom_filename_quote_characters
)
4348 set_filename_quote_chars (expchar
, nextch
, closer
);
4349 complete_fullquote
= 0;
4351 else if (*qcp
== '\0' && cs
== COMPLETE_BSQUOTE
&& mbschr (s
, '\n'))
4352 cs
= COMPLETE_SQUOTE
;
4353 else if (*qcp
== '"')
4355 if ((expchar
= bash_check_expchar (s
, 0, &nextch
, &closer
)) == '$' || expchar
== '`')
4356 cs
= COMPLETE_DQUOTE2
;
4358 cs
= COMPLETE_DQUOTE
;
4360 else if (*qcp
== '\'')
4361 cs
= COMPLETE_SQUOTE
;
4362 #if defined (BANG_HISTORY)
4363 else if (*qcp
== '\0' && history_expansion
&& cs
== COMPLETE_DQUOTE
&&
4364 history_expansion_inhibited
== 0 && mbschr (s
, '!'))
4365 cs
= COMPLETE_BSQUOTE
;
4367 if (*qcp
== '"' && history_expansion
&& cs
== COMPLETE_DQUOTE
&&
4368 history_expansion_inhibited
== 0 && mbschr (s
, '!'))
4370 cs
= COMPLETE_BSQUOTE
;
4375 /* Don't tilde-expand backslash-quoted filenames, since only single and
4376 double quotes inhibit tilde expansion. */
4378 if (mtext
[0] == '~' && rtype
== SINGLE_MATCH
&& cs
!= COMPLETE_BSQUOTE
)
4379 mtext
= bash_tilde_expand (s
, 0);
4383 case COMPLETE_DQUOTE2
:
4384 rtext
= sh_mkdoublequoted (mtext
, strlen (mtext
), 1); /* For now */
4386 case COMPLETE_DQUOTE
:
4387 rtext
= sh_double_quote (mtext
);
4389 case COMPLETE_SQUOTE
:
4390 rtext
= sh_single_quote (mtext
);
4392 case COMPLETE_BSQUOTE
:
4393 rtext
= sh_backslash_quote (mtext
, complete_fullquote
? 0 : filename_bstab
, 0);
4400 /* We may need to quote additional characters: those that readline treats
4401 as word breaks that are not quoted by backslash_quote. */
4402 /* XXX - test complete_fullquote here? */
4403 if (rtext
&& cs
== COMPLETE_BSQUOTE
&& rl_completer_word_break_characters
)
4405 mtext
= quote_word_break_chars (rtext
);
4410 /* Leave the opening quote intact. The readline completion code takes
4411 care of avoiding doubled opening quotes. */
4414 rlen
= strlen (rtext
);
4415 ret
= (char *)xmalloc (rlen
+ 1);
4416 strcpy (ret
, rtext
);
4420 ret
= (char *)xmalloc (rlen
= 1);
4424 /* If there are multiple matches, cut off the closing quote. */
4425 if (rtype
== MULT_MATCH
&& cs
!= COMPLETE_BSQUOTE
)
4426 ret
[rlen
- 1] = '\0';
4431 /* Support for binding readline key sequences to Unix commands. Each editing
4432 mode has a separate Unix command keymap. */
4434 static Keymap emacs_std_cmd_xmap
;
4435 #if defined (VI_MODE)
4436 static Keymap vi_insert_cmd_xmap
;
4437 static Keymap vi_movement_cmd_xmap
;
4448 x
= putc (c
, rl_outstream
);
4455 readline_get_char_offset (int ind
)
4460 #if defined (HANDLE_MULTIBYTE)
4461 if (locale_mb_cur_max
> 1)
4463 old_ch
= rl_line_buffer
[ind
];
4464 rl_line_buffer
[ind
] = '\0';
4465 r
= MB_STRLEN (rl_line_buffer
);
4466 rl_line_buffer
[ind
] = old_ch
;
4473 readline_set_char_offset (int ind
, int *varp
)
4479 #if defined (HANDLE_MULTIBYTE)
4480 if (i
> 0 && locale_mb_cur_max
> 1)
4481 i
= _rl_find_next_mbchar (rl_line_buffer
, 0, i
, 0); /* XXX */
4494 uw_restore_parser_state (void *ps
)
4496 restore_parser_state (ps
);
4500 uw_rl_set_signals (void *ignore
)
4506 unbind_readline_variables (void)
4508 check_unbind_variable ("READLINE_LINE");
4509 check_unbind_variable ("READLINE_POINT");
4510 check_unbind_variable ("READLINE_MARK");
4511 check_unbind_variable ("READLINE_ARGUMENT");
4512 array_needs_making
= 1;
4516 uw_unbind_readline_variables (void *ignore
)
4518 unbind_readline_variables ();
4522 bash_execute_unix_command (int count
, int key
)
4527 sh_parser_state_t ps
;
4528 char *cmd
, *value
, *ce
;
4530 char ibuf
[INT_STRLEN_BOUND(int) + 1];
4535 kseq
= rl_executing_keyseq
;
4536 kslen
= rl_key_sequence_length
;
4538 /* If we have a numeric argument, chop it off the front of the key sequence */
4539 if (count
!= 1 || rl_explicit_arg
)
4541 i
= rl_trim_arg_from_keyseq (rl_executing_keyseq
, rl_key_sequence_length
, rl_get_keymap ());
4544 kseq
= rl_executing_keyseq
+ i
;
4545 kslen
= rl_key_sequence_length
- i
;
4549 /* First, we need to find the right command to execute. This is tricky,
4550 because we might have already indirected into another keymap, so we
4551 have to walk cmd_xmap using the entire key sequence. */
4552 cmd_xmap
= get_cmd_xmap_from_keymap (rl_get_keymap ());
4553 cmd
= (char *)rl_function_of_keyseq_len (kseq
, kslen
, cmd_xmap
, &type
);
4555 if (type
== ISKMAP
&& (type
= ((Keymap
) cmd
)[ANYOTHERKEY
].type
) == ISMACR
)
4556 cmd
= (char*)((Keymap
) cmd
)[ANYOTHERKEY
].function
;
4558 if (cmd
== 0 || type
!= ISMACR
)
4561 internal_error (_("bash_execute_unix_command: cannot find keymap for command"));
4562 rl_forced_update_display ();
4566 ce
= rl_get_termcap ("ce");
4567 if (ce
) /* clear current line */
4569 rl_clear_visible_line ();
4570 fflush (rl_outstream
);
4573 rl_crlf (); /* move to a new line */
4575 v
= bind_variable ("READLINE_LINE", rl_line_buffer
, 0);
4577 VSETATTR (v
, att_exported
);
4579 i
= readline_get_char_offset (rl_point
);
4580 value
= inttostr (i
, ibuf
, sizeof (ibuf
));
4581 v
= bind_int_variable ("READLINE_POINT", value
, 0);
4583 VSETATTR (v
, att_exported
);
4585 i
= readline_get_char_offset (rl_mark
);
4586 value
= inttostr (i
, ibuf
, sizeof (ibuf
));
4587 v
= bind_int_variable ("READLINE_MARK", value
, 0);
4589 VSETATTR (v
, att_exported
);
4591 if (count
!= 1 || rl_explicit_arg
)
4593 value
= inttostr (count
, ibuf
, sizeof (ibuf
));
4594 v
= bind_int_variable ("READLINE_ARGUMENT", value
, 0);
4596 VSETATTR (v
, att_exported
);
4598 array_needs_making
= 1;
4600 begin_unwind_frame ("execute-unix-command");
4601 save_parser_state (&ps
);
4602 rl_clear_signals ();
4603 add_unwind_protect (uw_unbind_readline_variables
, 0);
4604 add_unwind_protect (uw_restore_parser_state
, &ps
);
4605 add_unwind_protect (uw_rl_set_signals
, 0);
4606 r
= parse_and_execute (savestring (cmd
), "bash_execute_unix_command", SEVAL_NOHIST
);
4608 restore_parser_state (&ps
);
4610 v
= find_variable ("READLINE_LINE");
4611 maybe_make_readline_line (v
? value_cell (v
) : 0);
4613 v
= find_variable ("READLINE_POINT");
4614 if (v
&& valid_number (value_cell (v
), &mi
))
4615 readline_set_char_offset (mi
, &rl_point
);
4617 v
= find_variable ("READLINE_MARK");
4618 if (v
&& valid_number (value_cell (v
), &mi
))
4619 readline_set_char_offset (mi
, &rl_mark
);
4621 unbind_readline_variables ();
4622 discard_unwind_frame ("execute-unix-command");
4624 /* and restore the readline buffer and display after command execution. */
4625 /* If we clear the last line of the prompt above, redraw only that last
4626 line. If the command returns 124, we redraw unconditionally as in
4627 previous versions. */
4629 rl_redraw_prompt_last_line ();
4631 rl_forced_update_display ();
4636 /* This only has to handle macros/shell commandsfrom print_unix_command_map */
4638 print_unix_command (const char *kseq
, const char *value
, int readable
, const char *prefix
)
4641 fprintf (rl_outstream
, "\"%s%s\" \"%s\"\n", prefix
? prefix
: "", kseq
, value
? value
: "");
4643 fprintf (rl_outstream
, "%s%s outputs %s\n", prefix
? prefix
: "", kseq
, value
? value
: "");
4647 print_unix_command_map (void)
4649 Keymap save
, cmd_xmap
;
4650 rl_macro_print_func_t
*old_printer
;
4652 save
= rl_get_keymap ();
4653 cmd_xmap
= get_cmd_xmap_from_keymap (save
);
4654 rl_set_keymap (cmd_xmap
);
4655 old_printer
= rl_macro_display_hook
;
4656 rl_macro_display_hook
= print_unix_command
;
4657 rl_macro_dumper (1);
4658 rl_macro_display_hook
= old_printer
;
4659 rl_set_keymap (save
);
4664 init_unix_command_map (void)
4666 emacs_std_cmd_xmap
= rl_make_bare_keymap ();
4668 emacs_std_cmd_xmap
[CTRL('X')].type
= ISKMAP
;
4669 emacs_std_cmd_xmap
[CTRL('X')].function
= KEYMAP_TO_FUNCTION (rl_make_bare_keymap ());
4670 emacs_std_cmd_xmap
[ESC
].type
= ISKMAP
;
4671 emacs_std_cmd_xmap
[ESC
].function
= KEYMAP_TO_FUNCTION (rl_make_bare_keymap ());
4673 #if defined (VI_MODE)
4674 vi_insert_cmd_xmap
= rl_make_bare_keymap ();
4675 vi_movement_cmd_xmap
= rl_make_bare_keymap ();
4680 get_cmd_xmap_from_edit_mode (void)
4682 if (emacs_std_cmd_xmap
== 0)
4683 init_unix_command_map ();
4685 switch (rl_editing_mode
)
4687 case EMACS_EDITING_MODE
:
4688 return emacs_std_cmd_xmap
;
4689 #if defined (VI_MODE)
4690 case VI_EDITING_MODE
:
4691 return (get_cmd_xmap_from_keymap (rl_get_keymap ()));
4694 return (Keymap
)NULL
;
4699 get_cmd_xmap_from_keymap (Keymap kmap
)
4701 if (emacs_std_cmd_xmap
== 0)
4702 init_unix_command_map ();
4704 if (kmap
== emacs_standard_keymap
)
4705 return emacs_std_cmd_xmap
;
4706 else if (kmap
== emacs_meta_keymap
)
4707 return (FUNCTION_TO_KEYMAP (emacs_std_cmd_xmap
, ESC
));
4708 else if (kmap
== emacs_ctlx_keymap
)
4709 return (FUNCTION_TO_KEYMAP (emacs_std_cmd_xmap
, CTRL('X')));
4710 #if defined (VI_MODE)
4711 else if (kmap
== vi_insertion_keymap
)
4712 return vi_insert_cmd_xmap
;
4713 else if (kmap
== vi_movement_keymap
)
4714 return vi_movement_cmd_xmap
;
4717 return (Keymap
)NULL
;
4721 isolate_sequence (char *string
, int ind
, int need_dquote
, int *startp
)
4724 int c
, passc
, delim
;
4726 for (i
= ind
; string
[i
] && whitespace (string
[i
]); i
++)
4728 /* NEED_DQUOTE means that the first non-white character *must* be `"'. */
4729 if (need_dquote
&& string
[i
] != '"')
4731 builtin_error (_("%s: first non-whitespace character is not `\"'"), string
);
4735 /* We can have delimited strings even if NEED_DQUOTE == 0, like the command
4736 string to bind the key sequence to. */
4737 delim
= (string
[i
] == '"' || string
[i
] == '\'') ? string
[i
] : 0;
4740 *startp
= delim
? ++i
: i
;
4742 for (passc
= 0; c
= string
[i
]; i
++)
4758 if (delim
&& string
[i
] != delim
)
4760 builtin_error (_("no closing `%c' in %s"), delim
, string
);
4768 bind_keyseq_to_unix_command (char *line
)
4770 Keymap kmap
, cmd_xmap
;
4772 int i
, kstart
, translate
;
4774 kmap
= rl_get_keymap ();
4776 /* We duplicate some of the work done by rl_parse_and_bind here, but
4777 this code only has to handle `"keyseq"[:][ \t]+["]command["]' and can
4778 generate an error for anything else. */
4779 i
= isolate_sequence (line
, 0, 1, &kstart
);
4783 /* Create the key sequence string to pass to rl_generic_bind */
4784 kseq
= substring (line
, kstart
, i
);
4786 /* Allow colon or whitespace to separate the key sequence and command string. */
4787 for ( ; line
[i
] && line
[i
] != ':' && whitespace (line
[i
]) == 0; i
++)
4789 if (line
[i
] != ':' && whitespace (line
[i
]) == 0)
4791 builtin_error (_("%s: missing separator"), line
);
4796 /* If we have a whitespace separator we're going to call rl_macro_bind so
4797 we get the readline-translated version of the value (backslash-escapes
4799 translate
= line
[i
] != ':';
4801 /* Kind of tricky. If we use whitespace as a delimiter, we can backslash-
4802 quote double quotes and have them preserved in the value. However, we
4803 still want to be able to auto-detect quoted strings and only require
4804 them with whitespace delimiters. */
4805 i
= isolate_sequence (line
, i
+ 1, translate
, &kstart
);
4812 /* Create the value string containing the command to execute. */
4813 value
= substring (line
, kstart
, i
);
4815 /* Save the command to execute and the key sequence in the CMD_XMAP */
4816 cmd_xmap
= get_cmd_xmap_from_keymap (kmap
);
4818 rl_macro_bind (kseq
, value
, cmd_xmap
);
4820 rl_generic_bind (ISMACR
, kseq
, value
, cmd_xmap
);
4822 /* and bind the key sequence in the current keymap to a function that
4823 understands how to execute from CMD_XMAP */
4824 rl_bind_keyseq_in_map (kseq
, bash_execute_unix_command
, kmap
);
4831 unbind_unix_command (char *kseq
)
4835 cmd_xmap
= get_cmd_xmap_from_keymap (rl_get_keymap ());
4836 if (rl_bind_keyseq_in_map (kseq
, (rl_command_func_t
*)NULL
, cmd_xmap
) != 0)
4838 builtin_error (_("`%s': cannot unbind in command keymap"), kseq
);
4844 /* Used by the programmable completion code. Complete TEXT as a filename,
4845 but return only directories as matches. Dequotes the filename before
4846 attempting to find matches. */
4848 bash_directory_completion_matches (const char *text
)
4854 qc
= rl_dispatching
? rl_completion_quote_character
: 0;
4855 /* If rl_completion_found_quote != 0, rl_completion_matches will call the
4856 filename dequoting function, causing the directory name to be dequoted
4858 if (rl_dispatching
&& rl_completion_found_quote
== 0)
4859 dfn
= bash_dequote_filename ((char *)text
, qc
);
4862 m1
= rl_completion_matches (dfn
, rl_filename_completion_function
);
4866 if (m1
== 0 || m1
[0] == 0)
4868 /* We don't bother recomputing the lcd of the matches, because it will just
4869 get thrown away by the programmable completion code and recomputed
4871 (void)bash_progcomp_ignore_filenames (m1
);
4876 bash_dequote_text (const char *text
)
4881 qc
= (text
[0] == '"' || text
[0] == '\'') ? text
[0] : 0;
4882 dtxt
= bash_dequote_filename ((char *)text
, qc
);
4886 /* This event hook is designed to be called after readline receives a signal
4887 that interrupts read(2). It gives reasonable responsiveness to interrupts
4888 and fatal signals without executing too much code in a signal handler
4891 bash_event_hook (void)
4895 /* XXX - see if we need to do anything here if sigterm_received == 1,
4896 we probably don't want to reset the event hook since we will not be
4897 jumping to the top level */
4898 if (sigterm_received
)
4900 /* RESET_SIGTERM; */
4905 if (terminating_signal
)
4906 sig
= terminating_signal
;
4907 else if (interrupt_state
)
4909 else if (read_timeout
&& read_timeout
->alrmflag
)
4911 else if (RL_ISSTATE (RL_STATE_TIMEOUT
)) /* just in case */
4915 read_timeout
->alrmflag
= 1;
4918 sig
= first_pending_trap ();
4920 /* If we're going to longjmp to top_level, make sure we clean up readline.
4921 check_signals will call QUIT, which will eventually longjmp to top_level,
4922 calling run_interrupt_trap along the way. The check against read_timeout
4923 is so we can clean up the read builtin's state. */
4924 if (terminating_signal
|| interrupt_state
|| (read_timeout
&& read_timeout
->alrmflag
))
4925 rl_cleanup_after_signal ();
4926 bashline_reset_event_hook ();
4928 RL_UNSETSTATE (RL_STATE_TIMEOUT
); /* XXX */
4930 /* posix mode SIGINT during read -e. We only get here if SIGINT is trapped. */
4931 if (posixly_correct
&& this_shell_builtin
== read_builtin
&& sig
== SIGINT
)
4933 last_command_exit_value
= 128|SIGINT
;
4934 throw_to_top_level ();
4937 check_signals_and_traps (); /* XXX */
4941 #endif /* READLINE */