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
;
801 file
= fopen (filename
, "r");
805 while (temp
= fgets (buffer
, 255, file
))
807 /* Skip to first character. */
808 for (i
= 0; buffer
[i
] && cr_whitespace (buffer
[i
]); i
++)
811 /* If comment or blank line, ignore. */
812 if (buffer
[i
] == '\0' || buffer
[i
] == '#')
815 /* If `preprocessor' directive, do the include. */
816 if (strncmp (buffer
+ i
, "$include ", 9) == 0)
820 /* Find start of filename. */
821 for (incfile
= buffer
+ i
+ 9; *incfile
&& whitespace (*incfile
); incfile
++)
824 /* Find end of filename. */
825 for (t
= incfile
; *t
&& cr_whitespace (*t
) == 0; t
++)
830 snarf_hosts_from_file (incfile
);
834 /* Skip internet address if present. */
835 if (DIGIT (buffer
[i
]))
836 for (; buffer
[i
] && cr_whitespace (buffer
[i
]) == 0; i
++);
838 /* Gobble up names. Each name is separated with whitespace. */
841 for (; cr_whitespace (buffer
[i
]); i
++)
843 if (buffer
[i
] == '\0' || buffer
[i
] == '#')
846 /* Isolate the current word. */
847 for (start
= i
; buffer
[i
] && cr_whitespace (buffer
[i
]) == 0; i
++)
851 strncpy (name
, buffer
+ start
, i
- start
);
852 name
[i
- start
] = '\0';
853 add_host_name (name
);
859 /* Return the hostname list. */
861 get_hostname_list (void)
863 if (hostname_list_initialized
== 0)
864 initialize_hostname_list ();
865 return (hostname_list
);
869 clear_hostname_list (void)
873 if (hostname_list_initialized
== 0)
875 for (i
= 0; i
< hostname_list_length
; i
++)
876 free (hostname_list
[i
]);
877 hostname_list_length
= hostname_list_initialized
= 0;
880 /* Return a NULL terminated list of hostnames which begin with TEXT.
881 Initialize the hostname list the first time if necessary.
882 The array is malloc ()'ed, but not the individual strings. */
884 hostnames_matching (const char *text
)
890 if (hostname_list_initialized
== 0)
891 initialize_hostname_list ();
893 if (hostname_list_initialized
== 0)
894 return ((char **)NULL
);
896 /* Special case. If TEXT consists of nothing, then the whole list is
900 result
= strvec_create (1 + hostname_list_length
);
901 for (i
= 0; i
< hostname_list_length
; i
++)
902 result
[i
] = hostname_list
[i
];
903 result
[i
] = (char *)NULL
;
907 /* Scan until found, or failure. */
909 result
= (char **)NULL
;
910 for (i
= nmatch
= rsize
= 0; i
< hostname_list_length
; i
++)
912 if (STREQN (text
, hostname_list
[i
], len
) == 0)
915 /* OK, it matches. Add it to the list. */
916 if (nmatch
+ 1 >= rsize
)
918 rsize
= (rsize
+ 16) - (rsize
% 16);
919 result
= strvec_resize (result
, rsize
);
922 result
[nmatch
++] = hostname_list
[i
];
925 result
[nmatch
] = (char *)NULL
;
929 /* This vi mode command causes VI_EDIT_COMMAND to be run on the current
930 command being entered (if no explicit argument is given), otherwise on
931 a command from the history file. */
933 #define VI_EDIT_COMMAND "fc -e \"${VISUAL:-${EDITOR:-vi}}\""
934 #define EMACS_EDIT_COMMAND "fc -e \"${VISUAL:-${EDITOR:-emacs}}\""
935 #define POSIX_VI_EDIT_COMMAND "fc -e vi"
938 edit_and_execute_command (int count
, int c
, int editing_mode
, const char *edit_command
)
940 char *command
, *metaval
;
941 int r
, rrs
, metaflag
;
942 sh_parser_state_t ps
;
944 rrs
= rl_readline_state
;
945 saved_command_line_count
= current_command_line_count
;
947 /* Accept the current line. */
952 command
= (char *)xmalloc (strlen (edit_command
) + 8);
953 sprintf (command
, "%s %d", edit_command
, count
);
957 /* Take the command we were just editing, add it to the history file,
958 then call fc to operate on it. We have to add a dummy command to
959 the end of the history because fc ignores the last command (assumes
960 it's supposed to deal with the command before the `fc'). */
961 /* This breaks down when using command-oriented history and are not
962 finished with the command, so we should not ignore the last command */
964 current_command_line_count
++; /* for rl_newline above */
965 bash_add_history (rl_line_buffer
);
966 current_command_line_count
= 0; /* for dummy history entry */
967 bash_add_history ("");
968 history_lines_this_session
++;
970 command
= savestring (edit_command
);
973 metaval
= rl_variable_value ("input-meta");
974 metaflag
= RL_BOOLEAN_VARIABLE_VALUE (metaval
);
976 if (rl_deprep_term_function
)
977 (*rl_deprep_term_function
) ();
979 save_parser_state (&ps
);
980 r
= parse_and_execute (command
, (editing_mode
== VI_EDITING_MODE
) ? "v" : "C-xC-e", SEVAL_NOHIST
);
981 restore_parser_state (&ps
);
983 /* if some kind of reset_parser was called, undo it. */
984 reset_readahead_token ();
986 if (rl_prep_term_function
)
987 (*rl_prep_term_function
) (metaflag
);
990 current_command_line_count
= saved_command_line_count
;
992 /* Now erase the contents of the current line and undo the effects of the
993 rl_accept_line() above. We don't even want to make the text we just
994 executed available for undoing. */
995 rl_line_buffer
[0] = '\0'; /* XXX */
996 rl_point
= rl_end
= 0;
998 rl_readline_state
= rrs
;
1000 #if defined (VI_MODE)
1001 if (editing_mode
== VI_EDITING_MODE
)
1002 rl_vi_insertion_mode (1, c
);
1005 rl_forced_update_display ();
1010 #if defined (VI_MODE)
1012 vi_edit_and_execute_command (int count
, int key
)
1014 if (posixly_correct
)
1015 return (edit_and_execute_command (count
, key
, VI_EDITING_MODE
, POSIX_VI_EDIT_COMMAND
));
1017 return (edit_and_execute_command (count
, key
, VI_EDITING_MODE
, VI_EDIT_COMMAND
));
1019 #endif /* VI_MODE */
1022 emacs_edit_and_execute_command (int count
, int key
)
1024 return (edit_and_execute_command (count
, key
, EMACS_EDITING_MODE
, EMACS_EDIT_COMMAND
));
1029 posix_edit_macros (int count
, int key
)
1032 char alias_name
[3], *alias_value
, *macro
;
1037 alias_name
[0] = '_';
1039 alias_name
[2] = '\0';
1041 alias_value
= get_alias_value (alias_name
);
1042 if (alias_value
&& *alias_value
)
1044 macro
= savestring (alias_value
);
1045 rl_push_macro_input (macro
);
1051 /* Bindable commands that move `shell-words': that is, sequences of
1052 non-unquoted-metacharacters. */
1054 #define WORDDELIM(c) (shellmeta(c) || shellblank(c))
1057 bash_forward_shellword (int count
, int key
)
1064 return (bash_backward_shellword (-count
, key
));
1066 /* The tricky part of this is deciding whether or not the first character
1067 we're on is an unquoted metacharacter. Not completely handled yet. */
1068 /* XXX - need to test this stuff with backslash-escaped shell
1069 metacharacters and unclosed single- and double-quoted strings. */
1082 /* Are we in a quoted string? If we are, move to the end of the quoted
1083 string and continue the outer loop. We only want quoted strings, not
1084 backslash-escaped characters, but char_is_quoted doesn't
1086 if (char_is_quoted (rl_line_buffer
, p
) && p
> 0 && rl_line_buffer
[p
-1] != '\\')
1089 ADVANCE_CHAR (rl_line_buffer
, slen
, p
);
1090 while (p
< rl_end
&& char_is_quoted (rl_line_buffer
, p
));
1095 /* Rest of code assumes we are not in a quoted string. */
1096 /* Move forward until we hit a non-metacharacter. */
1097 while (p
< rl_end
&& (c
= rl_line_buffer
[p
]) && WORDDELIM (c
))
1102 ADVANCE_CHAR (rl_line_buffer
, slen
, p
);
1103 continue; /* straight back to loop, don't increment p */
1105 if (p
< rl_end
&& rl_line_buffer
[p
])
1106 ADVANCE_CHAR (rl_line_buffer
, slen
, p
);
1109 p
= skip_to_delim (rl_line_buffer
, ++p
, "'", SD_NOJMP
);
1112 p
= skip_to_delim (rl_line_buffer
, ++p
, "\"", SD_NOJMP
);
1120 if (rl_line_buffer
[p
] == 0 || p
== rl_end
)
1127 /* Now move forward until we hit a non-quoted metacharacter or EOL */
1128 while (p
< rl_end
&& (c
= rl_line_buffer
[p
]) && WORDDELIM (c
) == 0)
1133 ADVANCE_CHAR (rl_line_buffer
, slen
, p
);
1134 continue; /* straight back to loop, don't increment p */
1136 if (p
< rl_end
&& rl_line_buffer
[p
])
1137 ADVANCE_CHAR (rl_line_buffer
, slen
, p
);
1140 p
= skip_to_delim (rl_line_buffer
, ++p
, "'", SD_NOJMP
);
1143 p
= skip_to_delim (rl_line_buffer
, ++p
, "\"", SD_NOJMP
);
1151 if (p
== rl_end
|| rl_line_buffer
[p
] == 0)
1165 bash_backward_shellword (int count
, int key
)
1172 return (bash_forward_shellword (-count
, key
));
1185 /* Move backward until we hit a non-metacharacter. We want to deal
1186 with the characters before point, so we move off a word if we're
1187 at its first character. */
1188 BACKUP_CHAR (rl_line_buffer
, slen
, p
);
1191 c
= rl_line_buffer
[p
];
1192 if (WORDDELIM (c
) == 0 || char_is_quoted (rl_line_buffer
, p
))
1194 BACKUP_CHAR (rl_line_buffer
, slen
, p
);
1203 /* Now move backward until we hit a metacharacter or BOL. Leave point
1204 at the start of the shellword or at BOL. */
1208 c
= rl_line_buffer
[p
];
1209 if (WORDDELIM (c
) && char_is_quoted (rl_line_buffer
, p
) == 0)
1215 BACKUP_CHAR (rl_line_buffer
, slen
, p
);
1226 bash_kill_shellword (int count
, int key
)
1231 return (bash_backward_kill_shellword (-count
, key
));
1234 bash_forward_shellword (count
, key
);
1237 rl_kill_text (p
, rl_point
);
1240 if (rl_editing_mode
== EMACS_EDITING_MODE
) /* 1 == emacs_mode */
1247 bash_backward_kill_shellword (int count
, int key
)
1252 return (bash_kill_shellword (-count
, key
));
1255 bash_backward_shellword (count
, key
);
1258 rl_kill_text (p
, rl_point
);
1260 if (rl_editing_mode
== EMACS_EDITING_MODE
) /* 1 == emacs_mode */
1267 bash_transpose_shellwords (int count
, int key
)
1269 char *word1
, *word2
;
1270 int w1_beg
, w1_end
, w2_beg
, w2_end
;
1271 int orig_point
= rl_point
;
1276 /* Find the two shell words. */
1277 bash_forward_shellword (count
, key
);
1279 bash_backward_shellword (1, key
);
1281 bash_backward_shellword (count
, key
);
1283 bash_forward_shellword (1, key
);
1286 /* check that there really are two words. */
1287 if ((w1_beg
== w2_beg
) || (w2_beg
< w1_end
))
1290 rl_point
= orig_point
;
1294 /* Get the text of the words. */
1295 word1
= rl_copy_text (w1_beg
, w1_end
);
1296 word2
= rl_copy_text (w2_beg
, w2_end
);
1298 /* We are about to do many insertions and deletions. Remember them
1299 as one operation. */
1300 rl_begin_undo_group ();
1302 /* Do the stuff at word2 first, so that we don't have to worry
1303 about word1 moving. */
1305 rl_delete_text (w2_beg
, w2_end
);
1306 rl_insert_text (word1
);
1309 rl_delete_text (w1_beg
, w1_end
);
1310 rl_insert_text (word2
);
1312 /* This is exactly correct since the text before this point has not
1313 changed in length. */
1316 /* I think that does it. */
1317 rl_end_undo_group ();
1324 /* Directory name spelling correction on the current word (not shellword).
1325 COUNT > 1 is not exactly correct yet. */
1327 bash_spell_correct_shellword (int count
, int key
)
1330 char *text
, *newdir
;
1334 bash_backward_shellword (1, key
);
1336 bash_forward_shellword (1, key
);
1342 text
= rl_copy_text (wbeg
, wend
);
1343 if (text
== 0 || *text
== 0)
1346 newdir
= dirspell (text
);
1349 rl_begin_undo_group ();
1350 rl_delete_text (wbeg
, wend
);
1353 rl_insert_text (newdir
);
1355 rl_end_undo_group ();
1361 if (rl_point
>= rl_end
)
1367 bash_forward_shellword (1, key
); /* XXX */
1373 /* **************************************************************** */
1375 /* How To Do Shell Completion */
1377 /* **************************************************************** */
1379 #define COMMAND_SEPARATORS ";|&{(`"
1381 #define COMMAND_SEPARATORS_PLUS_WS ";|&{(` \t"
1384 /* check for redirections and other character combinations that are not
1385 command separators */
1387 check_redir (int ti
)
1389 int this_char
, prev_char
, next_char
;
1391 /* Handle the two character tokens `>&', `<&', and `>|'.
1392 We are not in a command position after one of these. */
1393 this_char
= rl_line_buffer
[ti
];
1394 prev_char
= (ti
> 0) ? rl_line_buffer
[ti
- 1] : 0;
1395 next_char
= (ti
< rl_end
) ? rl_line_buffer
[ti
+ 1] : 0;
1397 if ((this_char
== '&' && (prev_char
== '<' || prev_char
== '>')) ||
1398 (this_char
== '|' && prev_char
== '>'))
1400 else if (this_char
== '{' && prev_char
== '$' && FUNSUB_CHAR (next_char
) == 0) /*}*/
1403 else if (this_char
== '(' && prev_char
== '$') /*)*/
1405 else if (this_char
== '(' && prev_char
== '<') /*)*/
1407 #if defined (EXTENDED_GLOB)
1408 else if (extended_glob
&& this_char
== '(' && prev_char
== '!') /*)*/
1412 else if (char_is_quoted (rl_line_buffer
, ti
))
1417 #if defined (PROGRAMMABLE_COMPLETION)
1419 * XXX - because of the <= start test, and setting os = s+1, this can
1420 * potentially return os > start. This is probably not what we want to
1421 * happen, but fix later after 2.05a-release.
1424 find_cmd_start (int start
)
1426 register int s
, os
, ns
;
1429 /* Flags == SD_NOJMP only because we want to skip over command substitutions
1430 in assignment statements. Have to test whether this affects `standalone'
1431 command substitutions as individual words. */
1432 while (((s
= skip_to_delim (rl_line_buffer
, os
, COMMAND_SEPARATORS
, SD_NOJMP
|SD_COMPLETE
/*|SD_NOSKIPCMD*/)) <= start
) &&
1435 /* Handle >| token crudely; treat as > not | */
1436 if (s
> 0 && rl_line_buffer
[s
] == '|' && rl_line_buffer
[s
-1] == '>')
1438 ns
= skip_to_delim (rl_line_buffer
, s
+1, COMMAND_SEPARATORS
, SD_NOJMP
|SD_COMPLETE
/*|SD_NOSKIPCMD*/);
1439 if (ns
> start
|| rl_line_buffer
[ns
] == 0)
1444 /* The only reserved word in COMMAND_SEPARATORS is `{', so handle that
1445 specially, making sure it's in a spot acceptable for reserved words */
1446 if (s
>= os
&& rl_line_buffer
[s
] == '{')
1448 int pc
, nc
; /* index of previous non-whitespace, next char */
1449 for (pc
= (s
> os
) ? s
- 1 : os
; pc
> os
&& whitespace(rl_line_buffer
[pc
]); pc
--)
1451 nc
= rl_line_buffer
[s
+1];
1452 /* must be preceded by a command separator or be the first non-
1453 whitespace character since the last command separator, and
1454 followed by a shell break character (not another `{') to be a reserved word. */
1455 if ((pc
> os
&& (rl_line_buffer
[s
-1] == '{' || strchr (COMMAND_SEPARATORS
, rl_line_buffer
[pc
]) == 0)) ||
1456 (shellbreak(nc
) == 0)) /* }} */
1458 /* Not a reserved word, look for another delim */
1459 ns
= skip_to_delim (rl_line_buffer
, s
+1, COMMAND_SEPARATORS
, SD_NOJMP
|SD_COMPLETE
/*|SD_NOSKIPCMD*/);
1460 if (ns
> start
|| rl_line_buffer
[ns
] == 0)
1472 find_cmd_end (int end
)
1476 e
= skip_to_delim (rl_line_buffer
, end
, COMMAND_SEPARATORS
, SD_NOJMP
|SD_COMPLETE
);
1481 find_cmd_name (int start
, int *sp
, int *ep
)
1486 for (s
= start
; whitespace (rl_line_buffer
[s
]); s
++)
1489 /* skip until a shell break character */
1490 e
= skip_to_delim (rl_line_buffer
, s
, "()<>;&| \t\n", SD_NOJMP
|SD_COMPLETE
);
1492 name
= substring (rl_line_buffer
, s
, e
);
1503 prog_complete_return (const char *text
, int matchnum
)
1510 if (prog_complete_matches
== 0 || prog_complete_matches
[ind
] == 0)
1511 return (char *)NULL
;
1512 return (prog_complete_matches
[ind
++]);
1515 #endif /* PROGRAMMABLE_COMPLETION */
1517 /* Try and catch completion attempts that are syntax errors or otherwise
1520 invalid_completion (const char *text
, int ind
)
1524 /* If we don't catch these here, the next clause will */
1525 if (ind
> 0 && rl_line_buffer
[ind
] == '(' && /*)*/
1526 member (rl_line_buffer
[ind
-1], "$<>"))
1530 while (pind
> 0 && whitespace (rl_line_buffer
[pind
]))
1532 /* If we have only whitespace preceding a paren, it's valid */
1533 if (ind
>= 0 && pind
<= 0 && rl_line_buffer
[ind
] == '(') /*)*/
1535 /* Flag the invalid completions, which are mostly syntax errors */
1536 if (ind
> 0 && rl_line_buffer
[ind
] == '(' && /*)*/
1537 member (rl_line_buffer
[pind
], COMMAND_SEPARATORS
) == 0)
1543 /* Do some completion on TEXT. The indices of TEXT in RL_LINE_BUFFER are
1544 at START and END. Return an array of matches, or NULL if none. */
1546 attempt_shell_completion (const char *text
, int start
, int end
)
1548 int in_command_position
, ti
, qc
, dflags
;
1549 char **matches
, *command_separator_chars
;
1550 #if defined (PROGRAMMABLE_COMPLETION)
1551 int have_progcomps
, was_assignment
;
1552 COMPSPEC
*iw_compspec
;
1555 command_separator_chars
= COMMAND_SEPARATORS
;
1556 matches
= (char **)NULL
;
1557 rl_ignore_some_completions_function
= filename_completion_ignore
;
1559 complete_fullquote
= 1; /* full filename quoting by default */
1560 rl_filename_quote_characters
= default_filename_quote_characters
;
1561 set_filename_bstab (rl_filename_quote_characters
);
1562 bashline_set_filename_hooks ();
1564 rl_sort_completion_matches
= 1; /* sort by default */
1566 /* Determine if this could be a command word. It is if it appears at
1567 the start of the line (ignoring preceding whitespace), or if it
1568 appears after a character that separates commands. It cannot be a
1569 command word if we aren't at the top-level prompt. */
1573 while ((ti
> -1) && (whitespace (rl_line_buffer
[ti
])))
1577 /* If this is an open quote, maybe we're trying to complete a quoted
1579 if (ti
>= 0 && (rl_line_buffer
[ti
] == '"' || rl_line_buffer
[ti
] == '\''))
1581 qc
= rl_line_buffer
[ti
];
1583 while (ti
> -1 && (whitespace (rl_line_buffer
[ti
])))
1588 in_command_position
= 0;
1591 /* Only do command completion at the start of a line when we
1592 are prompting at the top level. */
1593 if (current_prompt_string
== ps1_prompt
)
1594 in_command_position
++;
1595 else if (parser_in_command_position ())
1596 in_command_position
++;
1598 else if (member (rl_line_buffer
[ti
], command_separator_chars
))
1600 in_command_position
++;
1602 if (check_redir (ti
) == 1)
1603 in_command_position
= -1; /* sentinel that we're not the first word on the line */
1607 /* This still could be in command position. It is possible
1608 that all of the previous words on the line are variable
1612 if (in_command_position
> 0 && invalid_completion (text
, ti
))
1614 rl_attempted_completion_over
= 1;
1615 return ((char **)NULL
);
1618 /* Check that we haven't incorrectly flagged a closed command substitution
1619 as indicating we're in a command position. */
1620 if (in_command_position
> 0 && ti
>= 0 && rl_line_buffer
[ti
] == '`' &&
1621 *text
!= '`' && unclosed_pair (rl_line_buffer
, end
, "`") == 0)
1622 in_command_position
= -1; /* not following a command separator */
1624 /* Special handling for command substitution. If *TEXT is a backquote,
1625 it can be the start or end of an old-style command substitution, or
1626 unmatched. If it's unmatched, both calls to unclosed_pair will
1627 succeed. Don't bother if readline found a single quote and we are
1628 completing on the substring. */
1629 if (*text
== '`' && rl_completion_quote_character
!= '\'' &&
1630 (in_command_position
> 0 || (unclosed_pair (rl_line_buffer
, start
, "`") &&
1631 unclosed_pair (rl_line_buffer
, end
, "`"))))
1632 matches
= rl_completion_matches (text
, command_subst_completion_function
);
1634 #if defined (PROGRAMMABLE_COMPLETION)
1635 /* Attempt programmable completion. */
1636 have_progcomps
= prog_completion_enabled
&& (progcomp_size () > 0);
1637 iw_compspec
= progcomp_search (INITIALWORD
);
1639 (in_command_position
== 0 || text
[0] == '\0' || (in_command_position
> 0 && iw_compspec
)) &&
1640 current_prompt_string
== ps1_prompt
)
1642 int s
, e
, s1
, e1
, os
, foundcs
;
1645 /* XXX - don't free the members */
1646 if (prog_complete_matches
)
1647 free (prog_complete_matches
);
1648 prog_complete_matches
= (char **)NULL
;
1653 s
= find_cmd_start (os
);
1654 e
= find_cmd_end (end
);
1657 /* Don't read past the end of rl_line_buffer */
1663 /* Or past point if point is within an assignment statement */
1664 else if (was_assignment
&& s
> rl_point
)
1671 s
= s1
= start
; e
= e1
= end
; /* reset */
1673 /* Skip over assignment statements preceding a command name. If we
1674 don't find a command name at all, we can perform command name
1675 completion. If we find a partial command name, we should perform
1676 command name completion on it. */
1678 n
= find_cmd_name (s
, &s1
, &e1
);
1681 while (was_assignment
= assignment (n
, 0));
1682 s
= s1
; /* reset to index where name begins */
1684 /* s == index of where command name begins (reset above)
1685 e == end of current command, may be end of line
1686 s1 = index of where command name begins
1687 e1 == index of where command name ends
1688 start == index of where word to be completed begins
1689 end == index of where word to be completed ends
1690 if (s == start) we are doing command word completion for sure
1691 if (e1 == end) we are at the end of the command name and completing it */
1692 if (start
== 0 && end
== 0 && e
!= 0 && e1
< rl_end
&& text
[0] == '\0') /* beginning of non-empty line */
1694 else if (start
== end
&& start
== s1
&& e
!= 0 && e1
> end
) /* beginning of command name, leading whitespace */
1696 else if (start
== 0 && start
== end
&& start
< s1
&& e
!= 0 && e1
> end
&& text
[0] == '\0' && have_progcomps
) /* no command name, leading whitespace only */
1697 prog_complete_matches
= programmable_completions (EMPTYCMD
, text
, s
, e
, &foundcs
);
1698 else if (e
== 0 && e
== s
&& text
[0] == '\0' && have_progcomps
) /* beginning of empty line */
1699 prog_complete_matches
= programmable_completions (EMPTYCMD
, text
, s
, e
, &foundcs
);
1700 else if (start
== end
&& text
[0] == '\0' && s1
> start
&& whitespace (rl_line_buffer
[start
]))
1701 foundcs
= 0; /* whitespace before command name */
1702 else if (e
> s
&& was_assignment
== 0 && e1
== end
&& rl_line_buffer
[e
] == 0 && whitespace (rl_line_buffer
[e
-1]) == 0)
1704 /* not assignment statement, but still want to perform command
1705 completion if we are composing command word. */
1707 in_command_position
= s
== start
&& STREQ (n
, text
); /* XXX */
1709 else if (e
> s
&& was_assignment
== 0 && have_progcomps
)
1711 prog_complete_matches
= programmable_completions (n
, text
, s
, e
, &foundcs
);
1712 /* command completion if programmable completion fails */
1713 /* If we have a completion for the initial word, we can prefer that */
1714 in_command_position
= s
== start
&& (iw_compspec
|| STREQ (n
, text
)); /* XXX */
1715 if (iw_compspec
&& in_command_position
)
1718 /* empty command name following command separator */
1719 else if (s
>= e
&& n
[0] == '\0' && text
[0] == '\0' && start
> 0 &&
1720 was_assignment
== 0 && member (rl_line_buffer
[start
-1], COMMAND_SEPARATORS
))
1723 in_command_position
= 1;
1725 else if (s
>= e
&& n
[0] == '\0' && text
[0] == '\0' && start
> 0)
1727 foundcs
= 0; /* empty command name following optional assignments */
1728 in_command_position
+= was_assignment
;
1730 else if (s
== start
&& e
== end
&& STREQ (n
, text
) && start
> 0)
1732 foundcs
= 0; /* partial command name following assignments */
1733 in_command_position
= 1;
1738 /* If we have defined a compspec for the initial (command) word, call
1739 it and process the results like any other programmable completion. */
1740 if (in_command_position
&& have_progcomps
&& foundcs
== 0 && iw_compspec
)
1742 /* Do some sanity checking on S and E. Room for more here. */
1747 prog_complete_matches
= programmable_completions (INITIALWORD
, text
, s
, e
, &foundcs
);
1751 /* XXX - if we found a COMPSPEC for the command, just return whatever
1752 the programmable completion code returns, and disable the default
1753 filename completion that readline will do unless the COPT_DEFAULT
1754 option has been set with the `-o default' option to complete or
1758 pcomp_set_readline_variables (foundcs
, 1);
1759 /* Turn what the programmable completion code returns into what
1760 readline wants. I should have made compute_lcd_of_matches
1762 matches
= rl_completion_matches (text
, prog_complete_return
);
1763 if ((foundcs
& COPT_DEFAULT
) == 0)
1764 rl_attempted_completion_over
= 1; /* no default */
1765 if (matches
|| ((foundcs
& COPT_BASHDEFAULT
) == 0))
1774 if (in_command_position
> 0)
1775 dflags
|= DEFCOMP_CMDPOS
;
1776 matches
= bash_default_completion (text
, start
, end
, qc
, dflags
);
1783 bash_default_completion (const char *text
, int start
, int end
, int qc
, int compflags
)
1787 matches
= (char **)NULL
;
1789 /* New posix-style command substitution or variable name? */
1792 if (qc
!= '\'' && text
[1] == '(') /* ) */
1793 matches
= rl_completion_matches (text
, command_subst_completion_function
);
1794 else if (qc
!= '\'' && text
[1] == '{' && FUNSUB_CHAR (text
[2])) /* } */
1795 matches
= rl_completion_matches (text
, command_subst_completion_function
);
1798 matches
= rl_completion_matches (text
, variable_completion_function
);
1799 /* If a single match, see if it expands to a directory name and append
1800 a slash if it does. This requires us to expand the variable name,
1801 so we don't want to display errors if the variable is unset. This
1802 can happen with dynamic variables whose value has never been
1804 if (matches
&& matches
[0] && matches
[1] == 0)
1806 t
= savestring (matches
[0]);
1807 bash_filename_stat_hook (&t
);
1808 /* doesn't use test_for_directory because that performs tilde
1811 rl_completion_append_character
= '/';
1817 /* If the word starts in `~', and there is no slash in the word, then
1818 try completing this word as a username. */
1819 if (matches
== 0 && *text
== '~' && mbschr (text
, '/') == 0)
1820 matches
= rl_completion_matches (text
, rl_username_completion_function
);
1822 /* Another one. Why not? If the word starts in '@', then look through
1823 the world of known hostnames for completion first. */
1824 if (matches
== 0 && perform_hostname_completion
&& *text
== '@')
1825 matches
= rl_completion_matches (text
, hostname_completion_function
);
1827 /* And last, (but not least) if this word is in a command position, then
1828 complete over possible command names, including aliases, functions,
1829 and command names. */
1830 if (matches
== 0 && (compflags
& DEFCOMP_CMDPOS
))
1832 /* If END == START and text[0] == 0, we are trying to complete an empty
1834 if (no_empty_command_completion
&& end
== start
&& text
[0] == '\0')
1836 matches
= (char **)NULL
;
1837 rl_ignore_some_completions_function
= bash_ignore_everything
;
1841 #define CMD_IS_DIR(x) (absolute_pathname(x) == 0 && absolute_program(x) == 0 && *(x) != '~' && test_for_directory (x))
1844 matches
= rl_completion_matches (text
, command_word_completion_function
);
1846 /* If we are attempting command completion and nothing matches, we
1847 do not want readline to perform filename completion for us. We
1848 still want to be able to complete partial pathnames, so set the
1849 completion ignore function to something which will remove
1850 filenames and leave directories in the match list. */
1851 if (matches
== (char **)NULL
)
1852 rl_ignore_some_completions_function
= bash_ignore_filenames
;
1853 else if (matches
[1] == 0 && CMD_IS_DIR(matches
[0]) && dot_in_path
== 0)
1854 /* If we found a single match, without looking in the current
1855 directory (because it's not in $PATH), but the found name is
1856 also a command in the current directory, suppress appending any
1857 terminating character, since it's ambiguous. */
1859 rl_completion_suppress_append
= 1;
1860 rl_filename_completion_desired
= 0;
1863 else if (matches
[0] && matches
[1] && STREQ (matches
[0], matches
[1]) &&
1864 matches
[2] && STREQ (matches
[1], matches
[2]) && CMD_IS_DIR (matches
[0]))
1866 else if (matches
[0] && matches
[1] && STREQ (matches
[0], matches
[1]) && CMD_IS_DIR (matches
[0]))
1868 /* There are multiple instances of the same match (duplicate
1869 completions haven't yet been removed). In this case, all of
1870 the matches will be the same, and the duplicate removal code
1871 will distill them all down to one. We turn on
1872 rl_completion_suppress_append for the same reason as above.
1873 Remember: we only care if there's eventually a single unique
1874 completion. If there are multiple completions this won't
1875 make a difference and the problem won't occur. */
1877 rl_completion_suppress_append
= 1;
1878 rl_filename_completion_desired
= 0;
1883 /* This could be a globbing pattern, so try to expand it using pathname
1885 if (!matches
&& completion_glob_pattern (text
))
1887 matches
= rl_completion_matches (text
, glob_complete_word
);
1888 /* A glob expression that matches more than one filename is problematic.
1889 If we match more than one filename, punt. */
1890 if (matches
&& matches
[1] && rl_completion_type
== TAB
)
1892 strvec_dispose (matches
);
1893 matches
= (char **)0;
1895 else if (matches
&& matches
[1] && rl_completion_type
== '!')
1897 rl_completion_suppress_append
= 1;
1898 rl_filename_completion_desired
= 0;
1906 bash_command_name_stat_hook (char **name
)
1908 char *cname
, *result
;
1910 /* If it's not something we're going to look up in $PATH, just call the
1911 normal filename stat hook. */
1912 if (absolute_program (*name
))
1913 return (bash_filename_stat_hook (name
));
1916 /* XXX - we could do something here with converting aliases, builtins,
1917 and functions into something that came out as executable, but we don't. */
1918 result
= search_for_command (cname
, 0);
1929 executable_completion (const char *filename
, int searching_path
)
1934 /* This gets an unquoted filename, so we need to quote special characters
1935 in the filename before the completion hook gets it. */
1937 f
= bash_quote_filename ((char *)filename
, SINGLE_MATCH
, &c
);
1938 bash_directory_completion_hook (&f
);
1940 r
= searching_path
? executable_file (f
) : executable_or_directory (f
);
1945 /* This is the function to call when the word to complete is in a position
1946 where a command word can be found. It grovels $PATH, looking for commands
1947 that match. It also scans aliases, function names, and the shell_builtin
1950 command_word_completion_function (const char *hint_text
, int state
)
1952 static char *hint
= (char *)NULL
;
1953 static char *path
= (char *)NULL
;
1954 static char *val
= (char *)NULL
;
1955 static char *filename_hint
= (char *)NULL
;
1956 static char *fnhint
= (char *)NULL
;
1957 static char *dequoted_hint
= (char *)NULL
;
1958 static char *directory_part
= (char *)NULL
;
1959 static char **glob_matches
= (char **)NULL
;
1960 static int path_index
, istate
, igncase
;
1961 static size_t hint_len
;
1962 static int mapping_over
, local_index
, searching_path
, hint_is_dir
;
1963 static int old_glob_ignore_case
, globpat
;
1964 static SHELL_VAR
**varlist
= (SHELL_VAR
**)NULL
;
1966 static alias_t
**alias_list
= (alias_t
**)NULL
;
1970 /* We have to map over the possibilities for command words. If we have
1971 no state, then make one just for that purpose. */
1974 rl_filename_stat_hook
= bash_command_name_stat_hook
;
1976 if (dequoted_hint
&& dequoted_hint
!= hint
)
1977 free (dequoted_hint
);
1980 dequoted_hint
= hint
= (char *)NULL
;
1982 mapping_over
= searching_path
= 0;
1983 hint_is_dir
= CMD_IS_DIR (hint_text
);
1986 temp
= rl_variable_value ("completion-ignore-case");
1987 igncase
= RL_BOOLEAN_VARIABLE_VALUE (temp
);
1989 old_glob_ignore_case
= glob_ignore_case
;
1993 free (glob_matches
);
1994 glob_matches
= (char **)NULL
;
1997 globpat
= completion_glob_pattern (hint_text
);
1999 /* If this is an absolute program name, do not check it against
2000 aliases, reserved words, functions or builtins. We must check
2001 whether or not it is unique, and, if so, whether that filename
2003 if (globpat
|| absolute_program (hint_text
))
2005 /* Perform tilde expansion on what's passed, so we don't end up
2006 passing filenames with tildes directly to stat(). The rest of
2007 the shell doesn't do variable expansion on the word following
2008 the tilde, so we don't do it here even if direxpand is set. */
2009 if (*hint_text
== '~')
2011 hint
= bash_tilde_expand (hint_text
, 0);
2012 directory_part
= savestring (hint_text
);
2013 temp
= strchr (directory_part
, '/');
2018 free (directory_part
);
2019 directory_part
= (char *)NULL
;
2022 else if (dircomplete_expand
)
2024 hint
= savestring (hint_text
);
2025 bash_directory_completion_hook (&hint
);
2028 hint
= savestring (hint_text
);
2030 dequoted_hint
= hint
;
2031 /* If readline's completer found a quote character somewhere, but
2032 didn't set the quote character, there must have been a quote
2033 character embedded in the filename. It can't be at the start of
2034 the filename, so we need to dequote the filename before we look
2035 in the file system for it. */
2036 if (rl_completion_found_quote
&& rl_completion_quote_character
== 0)
2038 dequoted_hint
= bash_dequote_filename (hint
, 0);
2040 hint
= dequoted_hint
;
2042 hint_len
= strlen (hint
);
2045 free (filename_hint
);
2047 fnhint
= filename_hint
= savestring (hint
);
2058 if (dircomplete_expand
&& path_dot_or_dotdot (filename_hint
))
2060 dircomplete_expand
= 0;
2061 set_directory_hook ();
2062 dircomplete_expand
= 1;
2069 dequoted_hint
= hint
= savestring (hint_text
);
2070 hint_len
= strlen (hint
);
2072 if (rl_completion_found_quote
&& rl_completion_quote_character
== 0)
2073 dequoted_hint
= bash_dequote_filename (hint
, 0);
2075 path
= path_value ("PATH", 0);
2076 path_index
= dot_in_path
= 0;
2078 /* Initialize the variables for each type of command word. */
2084 varlist
= all_visible_functions ();
2090 alias_list
= all_aliases ();
2094 /* mapping_over says what we are currently hacking. Note that every case
2095 in this list must fall through when there are no more possibilities. */
2097 switch (mapping_over
)
2099 case 0: /* Aliases come first. */
2101 while (alias_list
&& alias_list
[local_index
])
2103 register char *alias
;
2105 alias
= alias_list
[local_index
++]->name
;
2107 if (igncase
== 0 && (STREQN (alias
, hint
, hint_len
)))
2108 return (savestring (alias
));
2109 else if (igncase
&& strncasecmp (alias
, hint
, hint_len
) == 0)
2110 return (savestring (alias
));
2116 case 1: /* Then shell reserved words. */
2118 while (word_token_alist
[local_index
].word
)
2120 register char *reserved_word
;
2122 reserved_word
= word_token_alist
[local_index
++].word
;
2124 if (STREQN (reserved_word
, hint
, hint_len
))
2125 return (savestring (reserved_word
));
2131 case 2: /* Then function names. */
2132 while (varlist
&& varlist
[local_index
])
2134 register char *varname
;
2136 varname
= varlist
[local_index
++]->name
;
2138 /* Honor completion-ignore-case for shell function names. */
2139 if (igncase
== 0 && (STREQN (varname
, hint
, hint_len
)))
2140 return (savestring (varname
));
2141 else if (igncase
&& strncasecmp (varname
, hint
, hint_len
) == 0)
2142 return (savestring (varname
));
2147 case 3: /* Then shell builtins. */
2148 for (; local_index
< num_shell_builtins
; local_index
++)
2150 /* Ignore it if it doesn't have a function pointer or if it
2151 is not currently enabled. */
2152 if (!shell_builtins
[local_index
].function
||
2153 (shell_builtins
[local_index
].flags
& BUILTIN_ENABLED
) == 0)
2156 if (STREQN (shell_builtins
[local_index
].name
, hint
, hint_len
))
2158 int i
= local_index
++;
2160 return (savestring (shell_builtins
[i
].name
));
2168 /* Limited support for completing command words with globbing chars. Only
2169 a single match (multiple matches that end up reducing the number of
2170 characters in the common prefix are bad) will ever be returned on
2171 regular completion. */
2176 rl_filename_completion_desired
= 1;
2178 glob_ignore_case
= igncase
;
2179 glob_matches
= shell_glob_filename (hint
, 0);
2180 glob_ignore_case
= old_glob_ignore_case
;
2182 if (GLOB_FAILED (glob_matches
) || glob_matches
== 0)
2184 glob_matches
= (char **)NULL
;
2185 return ((char *)NULL
);
2190 if (glob_matches
[1] && rl_completion_type
== TAB
) /* multiple matches are bad */
2192 strvec_dispose (glob_matches
);
2193 glob_matches
= (char **)NULL
;
2194 return ((char *)NULL
);
2198 while (val
= glob_matches
[local_index
++])
2200 if (executable_or_directory (val
))
2202 if (*hint_text
== '~' && directory_part
)
2204 temp
= maybe_restore_tilde (val
, directory_part
);
2213 glob_ignore_case
= old_glob_ignore_case
;
2214 return ((char *)NULL
);
2217 /* If the text passed is a directory in the current directory, return it
2218 as a possible match. Executables in directories in the current
2219 directory can be specified using relative pathnames and successfully
2220 executed even when `.' is not in $PATH. */
2223 hint_is_dir
= 0; /* only return the hint text once */
2224 return (savestring (hint_text
));
2227 /* Repeatedly call filename_completion_function while we have
2228 members of PATH left. Question: should we stat each file?
2229 Answer: we call executable_file () on each file. */
2232 istate
= (val
!= (char *)NULL
);
2238 /* Get the next directory from the path. If there is none, then we
2240 if (path
== 0 || path
[path_index
] == 0 ||
2241 (current_path
= extract_colon_unit (path
, &path_index
)) == 0)
2242 return ((char *)NULL
);
2245 if (*current_path
== 0)
2247 free (current_path
);
2248 current_path
= savestring (".");
2251 if (*current_path
== '~')
2255 t
= bash_tilde_expand (current_path
, 0);
2256 free (current_path
);
2260 if (current_path
[0] == '.' && current_path
[1] == '\0')
2263 if (fnhint
&& fnhint
!= filename_hint
)
2266 free (filename_hint
);
2267 fnhint
= filename_hint
= (char *)NULL
;
2269 filename_hint
= sh_makepath (current_path
, hint
, 0);
2270 /* Need a quoted version (though it doesn't matter much in most
2271 cases) because rl_filename_completion_function dequotes the
2272 filename it gets, assuming that it's been quoted as part of
2273 the input line buffer. */
2274 if (strpbrk (filename_hint
, "\"'\\"))
2275 fnhint
= sh_backslash_quote (filename_hint
, filename_bstab
, 0);
2277 fnhint
= filename_hint
;
2278 free (current_path
); /* XXX */
2282 val
= rl_filename_completion_function (fnhint
, istate
);
2283 if (mapping_over
== 4 && dircomplete_expand
)
2284 set_directory_hook ();
2290 /* If the hint text is an absolute program, then don't bother
2291 searching through PATH. */
2292 if (absolute_program (hint
))
2293 return ((char *)NULL
);
2299 int match
, freetemp
;
2301 if (absolute_program (hint
))
2305 match
= strncmp (val
, hint
, hint_len
) == 0;
2307 match
= strncasecmp (val
, hint
, hint_len
) == 0;
2309 /* Why duplicate the comparison rl_filename_completion_function
2310 already performs? */
2314 /* If we performed tilde expansion, restore the original
2316 if (*hint_text
== '~')
2317 temp
= maybe_restore_tilde (val
, directory_part
);
2319 temp
= savestring (val
);
2324 temp
= strrchr (val
, '/');
2330 freetemp
= match
= strncmp (temp
, hint
, hint_len
) == 0;
2332 freetemp
= match
= strncasecmp (temp
, hint
, hint_len
) == 0;
2334 temp
= savestring (temp
);
2337 freetemp
= match
= 0;
2340 /* If we have found a match, and it is an executable file, return it.
2341 We don't return directory names when searching $PATH, since the
2342 bash execution code won't find executables in directories which
2343 appear in directories in $PATH when they're specified using
2344 relative pathnames. */
2346 /* If we're not searching $PATH and we have a relative pathname, we
2347 need to re-canonicalize it before testing whether or not it's an
2348 executable or a directory so the shell treats .. relative to $PWD
2349 according to the physical/logical option. The shell already
2350 canonicalizes the directory name in order to tell readline where
2351 to look, so not doing it here will be inconsistent. */
2352 /* XXX -- currently not used -- will introduce more inconsistency,
2353 since shell does not canonicalize ../foo before passing it to
2355 if (match
&& searching_path
== 0 && *val
== '.')
2359 t
= get_working_directory ("command-word-completion");
2360 t1
= make_absolute (val
, t
);
2362 cval
= sh_canonpath (t1
, PATH_CHECKDOTDOT
|PATH_CHECKEXISTS
);
2369 if (match
&& executable_completion ((searching_path
? val
: cval
), searching_path
))
2374 val
= ""; /* So it won't be NULL. */
2389 /* Completion inside an unterminated command substitution. */
2391 command_subst_completion_function (const char *text
, int state
)
2393 static char **matches
= (char **)NULL
;
2394 static const char *orig_start
;
2395 static char *filename_text
= (char *)NULL
;
2396 static int cmd_index
, start_len
;
2402 free (filename_text
);
2406 else if (*text
== '$' && text
[1] == '(') /* ) */
2408 else if (*text
== '$' && text
[1] == '{' && FUNSUB_CHAR (text
[2])) /*}*/
2409 text
+= 3; /* nofork command substitution */
2410 /* If the text was quoted, suppress any quote character that the
2411 readline completion code would insert. */
2412 rl_completion_suppress_quote
= 1;
2413 start_len
= text
- orig_start
;
2414 filename_text
= savestring (text
);
2418 matches
= (char **)NULL
;
2422 * At this point we can entertain the idea of re-parsing
2423 * `filename_text' into a (possibly incomplete) command name and
2424 * arguments, and doing completion based on that. This is
2425 * currently very rudimentary, but it is a small improvement.
2427 for (value
= filename_text
+ strlen (filename_text
) - 1; value
> filename_text
; value
--)
2428 if (whitespace (*value
) || member (*value
, COMMAND_SEPARATORS
))
2430 if (value
<= filename_text
)
2431 matches
= rl_completion_matches (filename_text
, command_word_completion_function
);
2435 start_len
+= value
- filename_text
;
2436 if (whitespace (value
[-1]))
2437 matches
= rl_completion_matches (value
, rl_filename_completion_function
);
2439 matches
= rl_completion_matches (value
, command_word_completion_function
);
2442 /* If there is more than one match, rl_completion_matches has already
2443 put the lcd in matches[0]. Skip over it. */
2444 cmd_index
= matches
&& matches
[0] && matches
[1];
2446 /* If there's a single match and it's a directory, set the append char
2447 to the expected `/'. Otherwise, don't append anything. */
2448 if (matches
&& matches
[0] && matches
[1] == 0 && test_for_directory (matches
[0]))
2449 rl_completion_append_character
= '/';
2451 rl_completion_suppress_append
= 1;
2454 if (matches
== 0 || matches
[cmd_index
] == 0)
2456 rl_filename_quoting_desired
= 0; /* disable quoting */
2457 return ((char *)NULL
);
2461 value
= (char *)xmalloc (1 + start_len
+ strlen (matches
[cmd_index
]));
2464 value
[0] = *orig_start
;
2466 strncpy (value
, orig_start
, start_len
);
2468 strcpy (value
+ start_len
, matches
[cmd_index
]);
2475 /* Okay, now we write the entry_function for variable completion. */
2477 variable_completion_function (const char *text
, int state
)
2479 static char **varlist
= (char **)NULL
;
2480 static int varlist_index
;
2481 static char *varname
= (char *)NULL
;
2482 static int first_char
, first_char_loc
;
2490 first_char
= text
[0];
2492 if (first_char
== '$')
2495 if (text
[first_char_loc
] == '{')
2498 varname
= savestring (text
+ first_char_loc
);
2501 strvec_dispose (varlist
);
2503 varlist
= all_variables_matching_prefix (varname
);
2507 if (!varlist
|| !varlist
[varlist_index
])
2509 return ((char *)NULL
);
2515 value
= (char *)xmalloc (4 + strlen (varlist
[varlist_index
]));
2519 value
[0] = first_char
;
2520 if (first_char_loc
== 2)
2524 strcpy (value
+ first_char_loc
, varlist
[varlist_index
]);
2525 if (first_char_loc
== 2)
2526 strcat (value
, "}");
2533 /* How about a completion function for hostnames? */
2535 hostname_completion_function (const char *text
, int state
)
2537 static char **list
= (char **)NULL
;
2538 static int list_index
= 0;
2539 static int first_char
, first_char_loc
;
2541 /* If we don't have any state, make some. */
2546 list
= (char **)NULL
;
2551 if (first_char
== '@')
2554 list
= hostnames_matching ((char *)text
+first_char_loc
);
2558 if (list
&& list
[list_index
])
2562 t
= (char *)xmalloc (2 + strlen (list
[list_index
]));
2564 strcpy (t
+ first_char_loc
, list
[list_index
]);
2569 return ((char *)NULL
);
2573 * A completion function for service names from /etc/services (or wherever).
2576 bash_servicename_completion_function (const char *text
, int state
)
2578 #if defined (__WIN32__) || defined (__OPENNT) || !defined (HAVE_GETSERVENT)
2579 return ((char *)NULL
);
2581 static char *sname
= (char *)NULL
;
2582 static struct servent
*srvent
;
2583 static size_t snamelen
;
2585 char **alist
, *aentry
;
2592 sname
= savestring (text
);
2593 snamelen
= strlen (sname
);
2597 while (srvent
= getservent ())
2600 if (snamelen
== 0 || (STREQN (sname
, srvent
->s_name
, snamelen
)))
2602 /* Not primary, check aliases */
2603 for (alist
= srvent
->s_aliases
; *alist
; alist
++)
2606 if (STREQN (sname
, aentry
, snamelen
))
2620 return ((char *)NULL
);
2623 value
= afound
? savestring (aentry
) : savestring (srvent
->s_name
);
2629 * A completion function for group names from /etc/group (or wherever).
2632 bash_groupname_completion_function (const char *text
, int state
)
2634 #if defined (__WIN32__) || defined (__OPENNT) || !defined (HAVE_GRP_H)
2635 return ((char *)NULL
);
2637 static char *gname
= (char *)NULL
;
2638 static struct group
*grent
;
2639 static size_t gnamelen
;
2645 gname
= savestring (text
);
2646 gnamelen
= strlen (gname
);
2651 while (grent
= getgrent ())
2653 if (gnamelen
== 0 || (STREQN (gname
, grent
->gr_name
, gnamelen
)))
2660 return ((char *)NULL
);
2663 value
= savestring (grent
->gr_name
);
2668 /* Functions to perform history and alias expansions on the current line. */
2670 #if defined (BANG_HISTORY)
2671 /* Perform history expansion on the current line. If no history expansion
2672 is done, pre_process_line() returns what it was passed, so we need to
2673 allocate a new line here. */
2675 history_expand_line_internal (char *line
)
2680 old_verify
= hist_verify
;
2682 new_line
= pre_process_line (line
, 0, 0);
2683 hist_verify
= old_verify
;
2685 return (new_line
== line
) ? savestring (line
) : new_line
;
2689 /* There was an error in expansion. Let the preprocessor print
2692 cleanup_expansion_error (void)
2695 #if defined (BANG_HISTORY)
2698 old_verify
= hist_verify
;
2702 fprintf (rl_outstream
, "\r\n");
2703 to_free
= pre_process_line (rl_line_buffer
, 1, 0);
2704 #if defined (BANG_HISTORY)
2705 hist_verify
= old_verify
;
2707 if (to_free
!= rl_line_buffer
)
2709 putc ('\r', rl_outstream
);
2710 rl_forced_update_display ();
2713 /* If NEW_LINE differs from what is in the readline line buffer, add an
2714 undo record to get from the readline line buffer contents to the new
2715 line and make NEW_LINE the current readline line. */
2717 maybe_make_readline_line (const char *new_line
)
2719 if (new_line
&& strcmp (new_line
, rl_line_buffer
) != 0)
2723 rl_add_undo (UNDO_BEGIN
, 0, 0, 0);
2724 rl_delete_text (0, rl_point
);
2725 rl_point
= rl_end
= rl_mark
= 0;
2726 rl_insert_text (new_line
);
2727 rl_add_undo (UNDO_END
, 0, 0, 0);
2731 /* Make NEW_LINE be the current readline line. This frees NEW_LINE. We use
2732 several heuristics to decide where to put rl_point. */
2735 set_up_new_line (char *new_line
)
2738 int old_point
, old_end
, dist
, nb
;
2741 /* If we didn't expand anything, don't change anything. */
2742 if (STREQ (new_line
, rl_line_buffer
))
2748 old_point
= rl_point
;
2750 dist
= rl_end
- rl_point
;
2751 nb
= rl_end
- old_end
;
2753 /* If the line was history and alias expanded, then make that
2754 be one thing to undo. */
2755 maybe_make_readline_line (new_line
);
2758 /* Place rl_point where we think it should go. */
2761 else if (old_point
== 0)
2763 /* this is what the old code did, but separate it out so we can treat
2766 if (!whitespace (rl_line_buffer
[rl_point
]))
2767 rl_forward_word (1, 0);
2769 else if (rl_point
< old_point
+nb
)
2771 /* let's assume that this means the new point is within the changed region */
2772 rl_point
= old_point
;
2773 if (!whitespace (rl_line_buffer
[rl_point
]))
2774 rl_forward_word (1, 0);
2777 rl_point
= rl_end
- dist
; /* try to put point the same distance from end */
2781 else if (rl_point
> rl_end
)
2783 rl_mark
= 0; /* XXX */
2787 /* Expand aliases in the current readline line. */
2789 alias_expand_line (int count
, int ignore
)
2793 new_line
= alias_expand (rl_line_buffer
);
2797 set_up_new_line (new_line
);
2802 cleanup_expansion_error ();
2808 #if defined (BANG_HISTORY)
2809 /* History expand the line. */
2811 history_expand_line (int count
, int ignore
)
2815 new_line
= history_expand_line_internal (rl_line_buffer
);
2819 set_up_new_line (new_line
);
2824 cleanup_expansion_error ();
2829 /* Expand history substitutions in the current line and then insert a
2830 space (hopefully close to where we were before). */
2832 tcsh_magic_space (int count
, int ignore
)
2834 int dist_from_end
, old_point
;
2836 old_point
= rl_point
;
2837 dist_from_end
= rl_end
- rl_point
;
2838 if (history_expand_line (count
, ignore
) == 0)
2840 /* Try a simple heuristic from Stephen Gildea <gildea@intouchsys.com>.
2841 This works if all expansions were before rl_point or if no expansions
2843 rl_point
= (old_point
== 0) ? old_point
: rl_end
- dist_from_end
;
2850 #endif /* BANG_HISTORY */
2852 /* History and alias expand the line. */
2854 history_and_alias_expand_line (int count
, int ignore
)
2859 #if defined (BANG_HISTORY)
2860 new_line
= history_expand_line_internal (rl_line_buffer
);
2868 alias_line
= alias_expand (new_line
);
2870 new_line
= alias_line
;
2876 set_up_new_line (new_line
);
2881 cleanup_expansion_error ();
2886 /* History and alias expand the line, then perform the shell word
2887 expansions by calling expand_string. This can't use set_up_new_line()
2888 because we want the variable expansions as a separate undo'able
2889 set of operations. */
2891 shell_expand_line (int count
, int ignore
)
2894 WORD_LIST
*expanded_string
;
2898 #if defined (BANG_HISTORY)
2899 new_line
= history_expand_line_internal (rl_line_buffer
);
2902 t
= expand_string_dollar_quote (new_line
? new_line
: rl_line_buffer
, 0);
2911 alias_line
= alias_expand (new_line
);
2913 new_line
= alias_line
;
2919 int old_point
= rl_point
;
2920 int at_end
= rl_point
== rl_end
;
2922 /* If the line was history and alias expanded, then make that
2923 be one thing to undo. */
2924 maybe_make_readline_line (new_line
);
2927 /* If there is variable expansion to perform, do that as a separate
2928 operation to be undone. */
2931 w
= alloc_word_desc ();
2932 w
->word
= savestring (rl_line_buffer
);
2933 w
->flags
= rl_explicit_arg
? (W_NOPROCSUB
|W_NOCOMSUB
) : 0;
2934 expanded_string
= expand_word (w
, rl_explicit_arg
? Q_HERE_DOCUMENT
: 0);
2937 new_line
= savestring (rl_line_buffer
);
2938 expanded_string
= expand_string (new_line
, 0);
2942 if (expanded_string
== 0)
2944 new_line
= (char *)xmalloc (1);
2949 new_line
= string_list (expanded_string
);
2950 dispose_words (expanded_string
);
2953 maybe_make_readline_line (new_line
);
2956 /* Place rl_point where we think it should go. */
2959 else if (old_point
< rl_end
)
2961 rl_point
= old_point
;
2962 if (!whitespace (rl_line_buffer
[rl_point
]))
2963 rl_forward_word (1, 0);
2969 cleanup_expansion_error ();
2974 /* If FIGNORE is set, then don't match files with the given suffixes when
2975 completing filenames. If only one of the possibilities has an acceptable
2976 suffix, delete the others, else just return and let the completer
2977 signal an error. It is called by the completer when real
2978 completions are done on filenames by the completer's internal
2979 function, not for completion lists (M-?) and not on "other"
2980 completion types, such as hostnames or commands. */
2982 static struct ignorevar fignore
=
2988 (sh_iv_item_func_t
*) 0,
2992 _ignore_completion_names (char **names
, sh_ignore_func_t
*name_func
)
2999 /* If there is only one completion, see if it is acceptable. If it is
3000 not, free it up. In any case, short-circuit and return. This is a
3001 special case because names[0] is not the prefix of the list of names
3002 if there is only one completion; it is the completion itself. */
3003 if (names
[1] == (char *)0)
3006 if ((*name_func
) (names
[0]) == 0)
3009 names
[0] = (char *)NULL
;
3015 /* Allocate space for array to hold list of pointers to matching
3016 filenames. The pointers are copied back to NAMES when done. */
3017 for (nidx
= 1; names
[nidx
]; nidx
++)
3019 newnames
= strvec_create (nidx
+ 1);
3021 if (force_fignore
== 0)
3023 oldnames
= strvec_create (nidx
- 1);
3027 newnames
[0] = names
[0];
3028 for (idx
= nidx
= 1; names
[idx
]; idx
++)
3030 if ((*name_func
) (names
[idx
]))
3031 newnames
[nidx
++] = names
[idx
];
3032 else if (force_fignore
== 0)
3033 oldnames
[oidx
++] = names
[idx
];
3038 newnames
[nidx
] = (char *)NULL
;
3040 /* If none are acceptable then let the completer handle it. */
3046 names
[0] = (char *)NULL
;
3055 if (force_fignore
== 0)
3058 free (oldnames
[--oidx
]);
3062 /* If only one is acceptable, copy it to names[0] and return. */
3066 names
[0] = newnames
[1];
3067 names
[1] = (char *)NULL
;
3072 /* Copy the acceptable names back to NAMES, set the new array end,
3074 for (nidx
= 1; newnames
[nidx
]; nidx
++)
3075 names
[nidx
] = newnames
[nidx
];
3076 names
[nidx
] = (char *)NULL
;
3081 name_is_acceptable (const char *name
)
3086 for (nlen
= strlen (name
), p
= fignore
.ignores
; p
->val
; p
++)
3088 if (nlen
>= p
->len
&& p
->len
> 0 && STREQ (p
->val
, &name
[nlen
- p
->len
]))
3097 ignore_dot_names (const char *name
)
3099 return (name
[0] != '.');
3104 filename_completion_ignore (char **names
)
3107 if (glob_dot_filenames
== 0)
3108 _ignore_completion_names (names
, ignore_dot_names
);
3111 setup_ignore_patterns (&fignore
);
3113 if (fignore
.num_ignores
== 0)
3116 _ignore_completion_names (names
, name_is_acceptable
);
3121 /* Return 1 if NAME is a directory. NAME undergoes tilde expansion. */
3123 test_for_directory (const char *name
)
3128 fn
= bash_tilde_expand (name
, 0);
3129 r
= file_isdir (fn
);
3136 test_for_canon_directory (const char *name
)
3141 fn
= (*name
== '~') ? bash_tilde_expand (name
, 0) : savestring (name
);
3142 bash_filename_stat_hook (&fn
);
3143 r
= file_isdir (fn
);
3149 /* Remove files from NAMES, leaving directories. */
3151 bash_ignore_filenames (char **names
)
3153 _ignore_completion_names (names
, test_for_directory
);
3158 bash_progcomp_ignore_filenames (char **names
)
3160 _ignore_completion_names (names
, test_for_canon_directory
);
3165 return_zero (const char *name
)
3171 bash_ignore_everything (char **names
)
3173 _ignore_completion_names (names
, return_zero
);
3177 /* Replace a tilde-prefix in VAL with a `~', assuming the user typed it. VAL
3178 is an expanded filename. DIRECTORY_PART is the tilde-prefix portion
3179 of the un-tilde-expanded version of VAL (what the user typed). */
3181 restore_tilde (const char *val
, char *directory_part
)
3183 size_t l
, vl
, dl2
, xl
;
3184 char *dh2
, *expdir
, *ret
, *v
;
3188 /* We need to duplicate the expansions readline performs on the directory
3189 portion before passing it to our completion function. */
3190 dh2
= directory_part
? bash_dequote_filename (directory_part
, 0) : 0;
3191 bash_directory_expansion (&dh2
);
3194 expdir
= bash_tilde_expand (directory_part
, 0);
3195 xl
= strlen (expdir
);
3196 if (*directory_part
== '~' && STREQ (directory_part
, expdir
))
3198 /* tilde expansion failed, so what should we return? we use what the
3200 v
= mbschr (val
, '/');
3202 ret
= (char *)xmalloc (xl
+ vl
+ 2);
3203 strcpy (ret
, directory_part
);
3205 strcpy (ret
+ xl
, v
);
3215 dh2 = unexpanded but dequoted tilde-prefix
3216 dl2 = length of tilde-prefix
3217 expdir = tilde-expanded tilde-prefix
3218 xl = length of expanded tilde-prefix
3219 l = length of remainder after tilde-prefix
3225 return (savestring (val
)); /* XXX - just punt */
3228 ret
= (char *)xmalloc (dl2
+ 2 + l
);
3230 strcpy (ret
+ dl2
, val
+ xl
);
3237 maybe_restore_tilde (char *val
, char *directory_part
)
3239 rl_icppfunc_t
*save
;
3242 save
= (dircomplete_expand
== 0) ? save_directory_hook () : (rl_icppfunc_t
*)0;
3243 ret
= restore_tilde (val
, directory_part
);
3245 restore_directory_hook (save
);
3249 /* Simulate the expansions that will be performed by
3250 rl_filename_completion_function. This must be called with the address of
3251 a pointer to malloc'd memory. */
3253 bash_directory_expansion (char **dirname
)
3257 d
= savestring (*dirname
);
3259 if ((rl_directory_rewrite_hook
) && (*rl_directory_rewrite_hook
) (&d
))
3264 else if (rl_directory_completion_hook
&& (*rl_directory_completion_hook
) (&d
))
3269 else if (rl_completion_found_quote
)
3271 nd
= bash_dequote_filename (d
, rl_completion_quote_character
);
3280 /* If necessary, rewrite directory entry */
3282 bash_filename_rewrite_hook (char *fname
, int fnlen
)
3286 conv
= fnx_fromfs (fname
, fnlen
);
3288 conv
= savestring (conv
);
3292 /* Functions to save and restore the appropriate directory hook */
3293 /* This is not static so the shopt code can call it */
3295 set_directory_hook (void)
3297 if (dircomplete_expand
)
3299 rl_directory_completion_hook
= bash_directory_completion_hook
;
3300 rl_directory_rewrite_hook
= (rl_icppfunc_t
*)0;
3304 rl_directory_rewrite_hook
= bash_directory_completion_hook
;
3305 rl_directory_completion_hook
= (rl_icppfunc_t
*)0;
3309 static rl_icppfunc_t
*
3310 save_directory_hook (void)
3314 if (dircomplete_expand
)
3316 ret
= rl_directory_completion_hook
;
3317 rl_directory_completion_hook
= (rl_icppfunc_t
*)NULL
;
3321 ret
= rl_directory_rewrite_hook
;
3322 rl_directory_rewrite_hook
= (rl_icppfunc_t
*)NULL
;
3329 restore_directory_hook (rl_icppfunc_t
*hookf
)
3331 if (dircomplete_expand
)
3332 rl_directory_completion_hook
= hookf
;
3334 rl_directory_rewrite_hook
= hookf
;
3337 /* Set the readline hooks that affect how directories and filenames are
3338 converted. Extern so other parts of the shell can use. */
3340 bashline_set_filename_hooks (void)
3342 /* Tell the completer that we might want to follow symbolic links or
3343 do other expansion on directory names. */
3344 set_directory_hook ();
3346 rl_filename_rewrite_hook
= bash_filename_rewrite_hook
;
3347 rl_completion_rewrite_hook
= bash_filename_rewrite_hook
;
3348 rl_filename_stat_hook
= bash_filename_stat_hook
;
3351 /* Check whether not DIRNAME, with any trailing slash removed, exists. If
3352 SHOULD_DEQUOTE is non-zero, we dequote the directory name first. */
3354 directory_exists (const char *dirname
, int should_dequote
)
3360 /* We save the string and chop the trailing slash because stat/lstat behave
3361 inconsistently if one is present. */
3362 new_dirname
= should_dequote
? bash_dequote_filename ((char *)dirname
, rl_completion_quote_character
) : savestring (dirname
);
3363 dirlen
= STRLEN (new_dirname
);
3364 if (new_dirname
[dirlen
- 1] == '/')
3365 new_dirname
[dirlen
- 1] = '\0';
3366 #if defined (HAVE_LSTAT)
3367 r
= lstat (new_dirname
, &sb
) == 0;
3369 r
= stat (new_dirname
, &sb
) == 0;
3376 bash_expand_filename (char *filename
)
3382 newname
= savestring (filename
);
3383 /* no error messages, and expand_prompt_string doesn't longjmp so we don't
3384 have to worry about restoring this setting. */
3385 global_nounset
= unbound_vars_is_error
;
3386 unbound_vars_is_error
= 0;
3387 wl
= expand_prompt_string (newname
, 0, W_NOCOMSUB
|W_NOPROCSUB
|W_COMPLETE
); /* does the right thing */
3388 unbound_vars_is_error
= global_nounset
;
3395 newname
= string_list (wl
);
3397 if (newname
&& *newname
&& STREQ (newname
, filename
))
3406 /* Expand a filename before the readline completion code passes it to stat(2).
3407 The filename will already have had tilde expansion performed. */
3409 bash_filename_stat_hook (char **dirname
)
3411 char *local_dirname
, *new_dirname
, *t
;
3412 int should_expand_dirname
, return_value
;
3416 local_dirname
= *dirname
;
3417 should_expand_dirname
= return_value
= 0;
3418 if (t
= mbschr (local_dirname
, '$'))
3419 should_expand_dirname
= '$';
3420 else if (t
= mbschr (local_dirname
, '`')) /* XXX */
3421 should_expand_dirname
= '`';
3423 if (should_expand_dirname
&& directory_exists (local_dirname
, 0))
3424 should_expand_dirname
= 0;
3426 if (should_expand_dirname
)
3428 new_dirname
= savestring (local_dirname
);
3429 /* no error messages, and expand_prompt_string doesn't longjmp so we don't
3430 have to worry about restoring this setting. */
3431 global_nounset
= unbound_vars_is_error
;
3432 unbound_vars_is_error
= 0;
3433 wl
= expand_prompt_string (new_dirname
, 0, W_NOCOMSUB
|W_NOPROCSUB
|W_COMPLETE
); /* does the right thing */
3434 unbound_vars_is_error
= global_nounset
;
3438 new_dirname
= string_list (wl
);
3439 /* Tell the completer we actually expanded something and change
3440 *dirname only if we expanded to something non-null -- stat
3441 behaves unpredictably when passed null or empty strings */
3442 if (new_dirname
&& *new_dirname
)
3444 free (local_dirname
); /* XXX */
3445 local_dirname
= *dirname
= new_dirname
;
3446 return_value
= STREQ (local_dirname
, *dirname
) == 0;
3456 /* This is very similar to the code in bash_directory_completion_hook below,
3457 but without spelling correction and not worrying about whether or not
3458 we change relative pathnames. */
3459 if (no_symbolic_links
== 0 && (local_dirname
[0] != '.' || local_dirname
[1]))
3461 char *temp1
, *temp2
;
3463 t
= get_working_directory ("symlink-hook");
3464 temp1
= make_absolute (local_dirname
, t
);
3466 temp2
= sh_canonpath (temp1
, PATH_CHECKDOTDOT
|PATH_CHECKEXISTS
);
3468 /* If we can't canonicalize, bail. */
3472 return return_value
;
3475 free (local_dirname
);
3480 return (return_value
);
3483 /* Handle symbolic link references and other directory name
3484 expansions while hacking completion. This should return 1 if it modifies
3485 the DIRNAME argument, 0 otherwise. It should make sure not to modify
3486 DIRNAME if it returns 0. */
3488 bash_directory_completion_hook (char **dirname
)
3490 char *local_dirname
, *new_dirname
, *t
;
3491 int return_value
, should_expand_dirname
, nextch
, closer
;
3494 return_value
= should_expand_dirname
= nextch
= closer
= 0;
3495 local_dirname
= *dirname
;
3497 should_expand_dirname
= bash_check_expchar (local_dirname
, 1, &nextch
, &closer
);
3499 if (should_expand_dirname
&& directory_exists (local_dirname
, 1))
3500 should_expand_dirname
= 0;
3502 if (should_expand_dirname
)
3504 new_dirname
= savestring (local_dirname
);
3505 wl
= expand_prompt_string (new_dirname
, 0, W_NOCOMSUB
|W_NOPROCSUB
|W_COMPLETE
); /* does the right thing */
3508 *dirname
= string_list (wl
);
3509 /* Tell the completer to replace the directory name only if we
3510 actually expanded something. */
3511 return_value
= STREQ (local_dirname
, *dirname
) == 0;
3512 free (local_dirname
);
3515 local_dirname
= *dirname
;
3517 set_filename_quote_chars (should_expand_dirname
, nextch
, closer
);
3522 free (local_dirname
);
3523 *dirname
= (char *)xmalloc (1);
3530 /* Dequote the filename even if we don't expand it. */
3531 new_dirname
= bash_dequote_filename (local_dirname
, rl_completion_quote_character
);
3532 return_value
= STREQ (local_dirname
, new_dirname
) == 0;
3533 free (local_dirname
);
3534 local_dirname
= *dirname
= new_dirname
;
3537 /* no_symbolic_links == 0 -> use (default) logical view of the file system.
3538 local_dirname[0] == '.' && local_dirname[1] == '/' means files in the
3539 current directory (./).
3540 local_dirname[0] == '.' && local_dirname[1] == 0 means relative pathnames
3541 in the current directory (e.g., lib/sh).
3542 XXX - should we do spelling correction on these? */
3544 /* This is test as it was in bash-4.2: skip relative pathnames in current
3545 directory. Change test to
3546 (local_dirname[0] != '.' || (local_dirname[1] && local_dirname[1] != '/'))
3547 if we want to skip paths beginning with ./ also. */
3548 if (no_symbolic_links
== 0 && (local_dirname
[0] != '.' || local_dirname
[1]))
3550 char *temp1
, *temp2
;
3553 /* If we have a relative path
3554 (local_dirname[0] != '/' && local_dirname[0] != '.')
3555 that is canonical after appending it to the current directory, then
3558 strcmp (temp1, temp2) == 0
3559 after adding a slash to temp2 below. It should be safe to not
3562 t
= get_working_directory ("symlink-hook");
3563 temp1
= make_absolute (local_dirname
, t
);
3565 temp2
= sh_canonpath (temp1
, PATH_CHECKDOTDOT
|PATH_CHECKEXISTS
);
3567 /* Try spelling correction if initial canonicalization fails. Make
3568 sure we are set to replace the directory name with the results so
3569 subsequent directory checks don't fail. */
3570 if (temp2
== 0 && dircomplete_spelling
&& dircomplete_expand
)
3574 temp2
= dirspell (temp1
);
3575 l2
= STRLEN (temp2
);
3576 /* Don't take matches if they are shorter than the original path */
3577 if (temp2
&& l2
< strlen (temp1
) && STREQN (temp1
, temp2
, l2
))
3586 temp2
= sh_canonpath (temp1
, PATH_CHECKDOTDOT
|PATH_CHECKEXISTS
);
3587 return_value
|= temp2
!= 0;
3590 /* If we can't canonicalize, bail. */
3594 return return_value
;
3596 len1
= strlen (temp1
);
3597 if (temp1
[len1
- 1] == '/')
3599 len2
= strlen (temp2
);
3600 if (len2
> 2) /* don't append `/' to `/' or `//' */
3602 temp2
= (char *)xrealloc (temp2
, len2
+ 2);
3604 temp2
[len2
+ 1] = '\0';
3608 /* dircomplete_expand_relpath == 0 means we want to leave relative
3609 pathnames that are unchanged by canonicalization alone.
3610 *local_dirname != '/' && *local_dirname != '.' == relative pathname
3611 (consistent with general.c:absolute_pathname())
3612 temp1 == temp2 (after appending a slash to temp2) means the pathname
3613 is not changed by canonicalization as described above. */
3614 if (dircomplete_expand_relpath
|| ((local_dirname
[0] != '/' && local_dirname
[0] != '.') && STREQ (temp1
, temp2
) == 0))
3615 return_value
|= STREQ (local_dirname
, temp2
) == 0;
3616 free (local_dirname
);
3621 return (return_value
);
3624 static char **history_completion_array
= (char **)NULL
;
3625 static size_t harry_size
;
3626 static size_t harry_len
;
3629 build_history_completion_array (void)
3635 /* First, clear out the current dynamic history completion list. */
3638 strvec_dispose (history_completion_array
);
3639 history_completion_array
= (char **)NULL
;
3644 /* Next, grovel each line of history, making each shell-sized token
3645 a separate entry in the history_completion_array. */
3646 hlist
= history_list ();
3650 for (i
= 0; hlist
[i
]; i
++)
3652 for ( --i
; i
>= 0; i
--)
3654 /* Separate each token, and place into an array. */
3655 tokens
= history_tokenize (hlist
[i
]->line
);
3657 for (j
= 0; tokens
&& tokens
[j
]; j
++)
3659 if (harry_len
+ 2 > harry_size
)
3660 history_completion_array
= strvec_resize (history_completion_array
, harry_size
+= 10);
3662 history_completion_array
[harry_len
++] = tokens
[j
];
3663 history_completion_array
[harry_len
] = (char *)NULL
;
3668 /* Sort the complete list of tokens. */
3669 if (dabbrev_expand_active
== 0)
3670 qsort (history_completion_array
, harry_len
, sizeof (char *), (QSFUNC
*)strvec_strcmp
);
3675 history_completion_generator (const char *hint_text
, int state
)
3677 static int local_index
;
3679 static const char *text
;
3681 /* If this is the first call to the generator, then initialize the
3682 list of strings to complete over. */
3685 if (dabbrev_expand_active
) /* This is kind of messy */
3686 rl_completion_suppress_append
= 1;
3688 build_history_completion_array ();
3690 len
= strlen (text
);
3693 while (history_completion_array
&& history_completion_array
[local_index
])
3695 /* XXX - should this use completion-ignore-case? */
3696 if (strncmp (text
, history_completion_array
[local_index
++], len
) == 0)
3697 return (savestring (history_completion_array
[local_index
- 1]));
3699 return ((char *)NULL
);
3703 dynamic_complete_history (int count
, int key
)
3706 rl_compentry_func_t
*orig_func
;
3707 rl_completion_func_t
*orig_attempt_func
;
3708 rl_compignore_func_t
*orig_ignore_func
;
3710 orig_func
= rl_completion_entry_function
;
3711 orig_attempt_func
= rl_attempted_completion_function
;
3712 orig_ignore_func
= rl_ignore_some_completions_function
;
3714 rl_completion_entry_function
= history_completion_generator
;
3715 rl_attempted_completion_function
= (rl_completion_func_t
*)NULL
;
3716 rl_ignore_some_completions_function
= filename_completion_ignore
;
3718 /* XXX - use rl_completion_mode here? */
3719 if (rl_last_func
== dynamic_complete_history
)
3720 r
= rl_complete_internal ('?');
3722 r
= rl_complete_internal (TAB
);
3724 rl_completion_entry_function
= orig_func
;
3725 rl_attempted_completion_function
= orig_attempt_func
;
3726 rl_ignore_some_completions_function
= orig_ignore_func
;
3732 bash_dabbrev_expand (int count
, int key
)
3734 int r
, orig_suppress
, orig_sort
;
3735 rl_compentry_func_t
*orig_func
;
3736 rl_completion_func_t
*orig_attempt_func
;
3737 rl_compignore_func_t
*orig_ignore_func
;
3739 orig_func
= rl_menu_completion_entry_function
;
3740 orig_attempt_func
= rl_attempted_completion_function
;
3741 orig_ignore_func
= rl_ignore_some_completions_function
;
3742 orig_suppress
= rl_completion_suppress_append
;
3743 orig_sort
= rl_sort_completion_matches
;
3745 rl_menu_completion_entry_function
= history_completion_generator
;
3746 rl_attempted_completion_function
= (rl_completion_func_t
*)NULL
;
3747 rl_ignore_some_completions_function
= filename_completion_ignore
;
3748 rl_filename_completion_desired
= 0;
3749 rl_completion_suppress_append
= 1;
3750 rl_sort_completion_matches
= 0;
3752 /* XXX - use rl_completion_mode here? */
3753 dabbrev_expand_active
= 1;
3754 if (rl_last_func
== bash_dabbrev_expand
)
3755 rl_last_func
= rl_menu_complete
;
3756 r
= rl_menu_complete (count
, key
);
3757 dabbrev_expand_active
= 0;
3759 rl_last_func
= bash_dabbrev_expand
;
3760 rl_menu_completion_entry_function
= orig_func
;
3761 rl_attempted_completion_function
= orig_attempt_func
;
3762 rl_ignore_some_completions_function
= orig_ignore_func
;
3763 rl_completion_suppress_append
= orig_suppress
;
3764 rl_sort_completion_matches
= orig_sort
;
3769 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
3771 bash_complete_username (int ignore
, int ignore2
)
3773 return bash_complete_username_internal (rl_completion_mode (bash_complete_username
));
3777 bash_possible_username_completions (int ignore
, int ignore2
)
3779 return bash_complete_username_internal ('?');
3783 bash_complete_username_internal (int what_to_do
)
3785 return bash_specific_completion (what_to_do
, rl_username_completion_function
);
3789 bash_complete_filename (int ignore
, int ignore2
)
3791 return bash_complete_filename_internal (rl_completion_mode (bash_complete_filename
));
3795 bash_possible_filename_completions (int ignore
, int ignore2
)
3797 return bash_complete_filename_internal ('?');
3801 bash_complete_filename_internal (int what_to_do
)
3803 rl_compentry_func_t
*orig_func
;
3804 rl_completion_func_t
*orig_attempt_func
;
3805 rl_icppfunc_t
*orig_dir_func
;
3806 rl_compignore_func_t
*orig_ignore_func
;
3807 const char *orig_rl_completer_word_break_characters
;
3810 orig_func
= rl_completion_entry_function
;
3811 orig_attempt_func
= rl_attempted_completion_function
;
3812 orig_ignore_func
= rl_ignore_some_completions_function
;
3813 orig_rl_completer_word_break_characters
= rl_completer_word_break_characters
;
3815 orig_dir_func
= save_directory_hook ();
3817 rl_completion_entry_function
= rl_filename_completion_function
;
3818 rl_attempted_completion_function
= (rl_completion_func_t
*)NULL
;
3819 rl_ignore_some_completions_function
= filename_completion_ignore
;
3820 rl_completer_word_break_characters
= " \t\n\"\'";
3822 r
= rl_complete_internal (what_to_do
);
3824 rl_completion_entry_function
= orig_func
;
3825 rl_attempted_completion_function
= orig_attempt_func
;
3826 rl_ignore_some_completions_function
= orig_ignore_func
;
3827 rl_completer_word_break_characters
= orig_rl_completer_word_break_characters
;
3829 restore_directory_hook (orig_dir_func
);
3835 bash_complete_hostname (int ignore
, int ignore2
)
3837 return bash_complete_hostname_internal (rl_completion_mode (bash_complete_hostname
));
3841 bash_possible_hostname_completions (int ignore
, int ignore2
)
3843 return bash_complete_hostname_internal ('?');
3847 bash_complete_variable (int ignore
, int ignore2
)
3849 return bash_complete_variable_internal (rl_completion_mode (bash_complete_variable
));
3853 bash_possible_variable_completions (int ignore
, int ignore2
)
3855 return bash_complete_variable_internal ('?');
3859 bash_complete_command (int ignore
, int ignore2
)
3861 return bash_complete_command_internal (rl_completion_mode (bash_complete_command
));
3865 bash_possible_command_completions (int ignore
, int ignore2
)
3867 return bash_complete_command_internal ('?');
3871 bash_complete_hostname_internal (int what_to_do
)
3873 return bash_specific_completion (what_to_do
, hostname_completion_function
);
3877 bash_complete_variable_internal (int what_to_do
)
3879 return bash_specific_completion (what_to_do
, variable_completion_function
);
3883 bash_complete_command_internal (int what_to_do
)
3885 return bash_specific_completion (what_to_do
, command_word_completion_function
);
3889 completion_glob_pattern (const char *string
)
3891 return (glob_pattern_p (string
) == 1);
3894 static char *globtext
;
3895 static char *globorig
;
3898 glob_complete_word (const char *text
, int state
)
3900 static char **matches
= (char **)NULL
;
3907 rl_filename_completion_desired
= 1;
3909 matches
= (char **)NULL
;
3910 if (globorig
!= globtext
)
3913 globorig
= globtext
= (char *)NULL
;
3915 ttext
= bash_tilde_expand (text
, 0);
3917 if (rl_explicit_arg
)
3919 globorig
= savestring (ttext
);
3920 glen
= strlen (ttext
);
3921 globtext
= (char *)xmalloc (glen
+ 2);
3922 strcpy (globtext
, ttext
);
3923 globtext
[glen
] = '*';
3924 globtext
[glen
+1] = '\0';
3927 globtext
= globorig
= savestring (ttext
);
3932 matches
= shell_glob_filename (globtext
, 0);
3933 if (GLOB_FAILED (matches
))
3934 matches
= (char **)NULL
;
3938 ret
= matches
? matches
[ind
] : (char *)NULL
;
3944 bash_glob_completion_internal (int what_to_do
)
3946 return bash_specific_completion (what_to_do
, glob_complete_word
);
3949 /* A special quoting function so we don't end up quoting globbing characters
3950 in the word if there are no matches or multiple matches. */
3952 bash_glob_quote_filename (char *s
, int rtype
, char *qcp
)
3954 if (globorig
&& qcp
&& *qcp
== '\0' && STREQ (s
, globorig
))
3955 return (savestring (s
));
3957 return (bash_quote_filename (s
, rtype
, qcp
));
3961 bash_glob_complete_word (int count
, int key
)
3964 rl_quote_func_t
*orig_quoting_function
;
3966 if (rl_editing_mode
== EMACS_EDITING_MODE
)
3967 rl_explicit_arg
= 1; /* force `*' append */
3968 orig_quoting_function
= rl_filename_quoting_function
;
3969 rl_filename_quoting_function
= bash_glob_quote_filename
;
3971 r
= bash_glob_completion_internal (rl_completion_mode (bash_glob_complete_word
));
3973 rl_filename_quoting_function
= orig_quoting_function
;
3978 bash_glob_expand_word (int count
, int key
)
3980 return bash_glob_completion_internal ('*');
3984 bash_glob_list_expansions (int count
, int key
)
3986 return bash_glob_completion_internal ('?');
3990 bash_specific_completion (int what_to_do
, rl_compentry_func_t
*generator
)
3992 rl_compentry_func_t
*orig_func
;
3993 rl_completion_func_t
*orig_attempt_func
;
3994 rl_compignore_func_t
*orig_ignore_func
;
3997 orig_func
= rl_completion_entry_function
;
3998 orig_attempt_func
= rl_attempted_completion_function
;
3999 orig_ignore_func
= rl_ignore_some_completions_function
;
4000 rl_completion_entry_function
= generator
;
4001 rl_attempted_completion_function
= NULL
;
4002 rl_ignore_some_completions_function
= orig_ignore_func
;
4004 r
= rl_complete_internal (what_to_do
);
4006 rl_completion_entry_function
= orig_func
;
4007 rl_attempted_completion_function
= orig_attempt_func
;
4008 rl_ignore_some_completions_function
= orig_ignore_func
;
4013 #endif /* SPECIFIC_COMPLETION_FUNCTIONS */
4015 #if defined (VI_MODE)
4016 /* This does pretty much what _rl_vi_advance_point does. */
4018 vi_advance_point (void)
4024 if (rl_point
< rl_end
)
4025 #if defined (HANDLE_MULTIBYTE)
4027 if (locale_mb_cur_max
== 1)
4032 ADVANCE_CHAR (rl_line_buffer
, rl_end
, rl_point
);
4033 if (point
== rl_point
|| rl_point
> rl_end
)
4043 /* Completion, from vi mode's point of view. This is a modified version of
4044 rl_vi_complete which uses the bash globbing code to implement what POSIX
4045 specifies, which is to optinally append a `*' and attempt filename
4046 generation (which has the side effect of expanding any globbing characters
4049 bash_vi_complete (int count
, int key
)
4051 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
4055 if ((rl_point
< rl_end
) && (!whitespace (rl_line_buffer
[rl_point
])))
4057 if (!whitespace (rl_line_buffer
[rl_point
+ 1]))
4058 rl_vi_end_word (1, 'E');
4059 vi_advance_point ();
4062 /* Find boundaries of current word, according to vi definition of a
4068 rl_vi_bWord (1, 'B');
4073 t
= substring (rl_line_buffer
, p
, rl_point
);
4076 if (t
&& completion_glob_pattern (t
) == 0)
4077 rl_explicit_arg
= 1; /* XXX - force glob_complete_word to append `*' */
4080 if (key
== '*') /* Expansion and replacement. */
4081 r
= bash_glob_expand_word (count
, key
);
4082 else if (key
== '=') /* List possible completions. */
4083 r
= bash_glob_list_expansions (count
, key
);
4084 else if (key
== '\\') /* Standard completion */
4085 r
= bash_glob_complete_word (count
, key
);
4087 r
= rl_complete (0, key
);
4089 if (key
== '*' || key
== '\\')
4090 rl_vi_start_inserting (key
, 1, 1);
4094 return rl_vi_complete (count
, key
);
4095 #endif /* !SPECIFIC_COMPLETION_FUNCTIONS */
4097 #endif /* VI_MODE */
4099 /* Filename quoting for completion. */
4100 /* A function to strip unquoted quote characters (single quotes, double
4101 quotes, and backslashes). It allows single quotes to appear
4102 within double quotes, and vice versa. It should be smarter. */
4104 bash_dequote_filename (char *text
, int quote_char
)
4111 ret
= (char *)xmalloc (l
+ 1);
4112 for (quoted
= quote_char
, p
= text
, r
= ret
; p
&& *p
; p
++)
4114 /* Allow backslash-escaped characters to pass through unscathed. Backslashes
4115 aren't special in single quotes. */
4116 if (quoted
!= '\'' && *p
== '\\')
4118 /* Backslashes are preserved within double quotes unless the
4119 character is one that is defined to be escaped */
4120 if (quoted
== '"' && ((sh_syntaxtab
[(unsigned char)p
[1]] & CBSDQUOTE
) == 0))
4125 return ret
; /* XXX - was break; */
4129 if (quoted
&& *p
== quoted
)
4135 if (quoted
== 0 && (*p
== '\'' || *p
== '"'))
4146 /* Quote characters that the readline completion code would treat as
4147 word break characters with backslashes. Pass backslash-quoted
4148 characters through without examination. */
4150 quote_word_break_chars (char *text
)
4156 ret
= (char *)xmalloc ((2 * l
) + 1);
4157 for (s
= text
, r
= ret
; *s
; s
++)
4159 /* Pass backslash-quoted characters through, including the backslash. */
4168 /* OK, we have an unquoted character. Check its presence in
4169 rl_completer_word_break_characters. */
4170 if (mbschr (rl_completer_word_break_characters
, *s
))
4172 /* XXX -- check for standalone tildes here and backslash-quote them */
4173 if (s
== text
&& *s
== '~' && file_exists (text
))
4181 /* Return a character in DIRNAME that will cause shell expansion to be
4182 performed. If NEXTP is non-null, *NEXTP gets the expansion character that
4183 follows RET (e.g., '{' or `(' for `$'). If CLOSERP is non-null, *CLOSERP
4184 gets the character that should close <RET><NEXTP>. If NEED_CLOSER is non-
4185 zero, any expansion pair that isn't closed causes this function to
4186 return 0, which indicates that we didn't find an expansion character. It's
4187 used in case DIRNAME is going to be expanded. If DIRNAME is just going to
4188 be quoted, NEED_CLOSER will be 0. */
4190 bash_check_expchar (char *dirname
, int need_closer
, int *nextp
, int *closerp
)
4196 if (t
= mbschr (dirname
, '$'))
4200 /* Deliberately does not handle the deprecated $[...] arithmetic
4209 if (c
&& need_closer
) /* XXX */
4214 delims
[0] = c
; delims
[1] = 0;
4215 p
= skip_to_delim (t
, 1, delims
, SD_NOJMP
|SD_COMPLETE
);
4220 else if (dirname
[0] == '~')
4224 t
= mbschr (dirname
, '`');
4227 if (need_closer
== 0)
4229 else if (unclosed_pair (dirname
, strlen (dirname
), "`") == 0)
4242 /* Make sure EXPCHAR and, if non-zero, NEXTCH and CLOSER are not in the set
4243 of characters to be backslash-escaped. This is the only place
4244 custom_filename_quote_characters is modified. */
4246 set_filename_quote_chars (int expchar
, int nextch
, int closer
)
4251 if (rl_filename_quote_characters
&& *rl_filename_quote_characters
)
4253 i
= strlen (default_filename_quote_characters
);
4254 custom_filename_quote_characters
= xrealloc (custom_filename_quote_characters
, i
+1);
4255 for (i
= j
= 0; c
= default_filename_quote_characters
[i
]; i
++)
4257 if (c
== expchar
|| c
== nextch
|| c
== closer
)
4259 custom_filename_quote_characters
[j
++] = c
;
4261 custom_filename_quote_characters
[j
] = '\0';
4262 rl_filename_quote_characters
= custom_filename_quote_characters
;
4263 set_filename_bstab (rl_filename_quote_characters
);
4267 /* Use characters in STRING to populate the table of characters that should
4268 be backslash-quoted. The table will be used for sh_backslash_quote from
4271 set_filename_bstab (const char *string
)
4275 memset (filename_bstab
, 0, sizeof (filename_bstab
));
4276 for (s
= string
; s
&& *s
; s
++)
4277 filename_bstab
[(unsigned char)*s
] = 1;
4280 /* Quote a filename using double quotes, single quotes, or backslashes
4281 depending on the value of completion_quoting_style. If we're
4282 completing using backslashes, we need to quote some additional
4283 characters (those that readline treats as word breaks), so we call
4284 quote_word_break_chars on the result. This returns newly-allocated
4287 bash_quote_filename (char *s
, int rtype
, char *qcp
)
4289 char *rtext
, *mtext
, *ret
;
4291 int cs
, expchar
, nextch
, closer
;
4293 rtext
= (char *)NULL
;
4295 /* If RTYPE == MULT_MATCH, it means that there is
4296 more than one match. In this case, we do not add
4297 the closing quote or attempt to perform tilde
4298 expansion. If RTYPE == SINGLE_MATCH, we try
4299 to perform tilde expansion, because single and double
4300 quotes inhibit tilde expansion by the shell. */
4302 cs
= completion_quoting_style
;
4303 /* Might need to modify the default completion style based on *qcp,
4304 since it's set to any user-provided opening quote. We also change
4305 to single-quoting if there is no user-provided opening quote and
4306 the word being completed contains newlines, since those are not
4307 quoted correctly using backslashes (a backslash-newline pair is
4308 special to the shell parser). */
4309 expchar
= nextch
= closer
= 0;
4310 if (*qcp
== '\0' && cs
== COMPLETE_BSQUOTE
&& dircomplete_expand
== 0 &&
4311 (expchar
= bash_check_expchar (s
, 0, &nextch
, &closer
)) &&
4312 file_exists (s
) == 0)
4314 /* If it looks like the name is subject to expansion, see if we want to
4316 if (expchar
== '$' || expchar
== '`')
4319 newname
= bash_expand_filename (s
);
4320 if (newname
&& strpbrk (newname
, rl_filename_quote_characters
))
4321 cs
= COMPLETE_DQUOTE2
;
4325 /* Usually this will have been set by bash_directory_completion_hook,
4326 but there are cases where it will not be. */
4327 if (rl_filename_quote_characters
!= custom_filename_quote_characters
)
4328 set_filename_quote_chars (expchar
, nextch
, closer
);
4329 complete_fullquote
= 0;
4331 else if (*qcp
== '\0' && cs
== COMPLETE_BSQUOTE
&& mbschr (s
, '\n'))
4332 cs
= COMPLETE_SQUOTE
;
4333 else if (*qcp
== '"')
4335 if ((expchar
= bash_check_expchar (s
, 0, &nextch
, &closer
)) == '$' || expchar
== '`')
4336 cs
= COMPLETE_DQUOTE2
;
4338 cs
= COMPLETE_DQUOTE
;
4340 else if (*qcp
== '\'')
4341 cs
= COMPLETE_SQUOTE
;
4342 #if defined (BANG_HISTORY)
4343 else if (*qcp
== '\0' && history_expansion
&& cs
== COMPLETE_DQUOTE
&&
4344 history_expansion_inhibited
== 0 && mbschr (s
, '!'))
4345 cs
= COMPLETE_BSQUOTE
;
4347 if (*qcp
== '"' && history_expansion
&& cs
== COMPLETE_DQUOTE
&&
4348 history_expansion_inhibited
== 0 && mbschr (s
, '!'))
4350 cs
= COMPLETE_BSQUOTE
;
4355 /* Don't tilde-expand backslash-quoted filenames, since only single and
4356 double quotes inhibit tilde expansion. */
4358 if (mtext
[0] == '~' && rtype
== SINGLE_MATCH
&& cs
!= COMPLETE_BSQUOTE
)
4359 mtext
= bash_tilde_expand (s
, 0);
4363 case COMPLETE_DQUOTE2
:
4364 rtext
= sh_mkdoublequoted (mtext
, strlen (mtext
), 1); /* For now */
4366 case COMPLETE_DQUOTE
:
4367 rtext
= sh_double_quote (mtext
);
4369 case COMPLETE_SQUOTE
:
4370 rtext
= sh_single_quote (mtext
);
4372 case COMPLETE_BSQUOTE
:
4373 rtext
= sh_backslash_quote (mtext
, complete_fullquote
? 0 : filename_bstab
, 0);
4380 /* We may need to quote additional characters: those that readline treats
4381 as word breaks that are not quoted by backslash_quote. */
4382 /* XXX - test complete_fullquote here? */
4383 if (rtext
&& cs
== COMPLETE_BSQUOTE
&& rl_completer_word_break_characters
)
4385 mtext
= quote_word_break_chars (rtext
);
4390 /* Leave the opening quote intact. The readline completion code takes
4391 care of avoiding doubled opening quotes. */
4394 rlen
= strlen (rtext
);
4395 ret
= (char *)xmalloc (rlen
+ 1);
4396 strcpy (ret
, rtext
);
4400 ret
= (char *)xmalloc (rlen
= 1);
4404 /* If there are multiple matches, cut off the closing quote. */
4405 if (rtype
== MULT_MATCH
&& cs
!= COMPLETE_BSQUOTE
)
4406 ret
[rlen
- 1] = '\0';
4411 /* Support for binding readline key sequences to Unix commands. Each editing
4412 mode has a separate Unix command keymap. */
4414 static Keymap emacs_std_cmd_xmap
;
4415 #if defined (VI_MODE)
4416 static Keymap vi_insert_cmd_xmap
;
4417 static Keymap vi_movement_cmd_xmap
;
4428 x
= putc (c
, rl_outstream
);
4435 readline_get_char_offset (int ind
)
4440 #if defined (HANDLE_MULTIBYTE)
4441 if (locale_mb_cur_max
> 1)
4443 old_ch
= rl_line_buffer
[ind
];
4444 rl_line_buffer
[ind
] = '\0';
4445 r
= MB_STRLEN (rl_line_buffer
);
4446 rl_line_buffer
[ind
] = old_ch
;
4453 readline_set_char_offset (int ind
, int *varp
)
4459 #if defined (HANDLE_MULTIBYTE)
4460 if (i
> 0 && locale_mb_cur_max
> 1)
4461 i
= _rl_find_next_mbchar (rl_line_buffer
, 0, i
, 0); /* XXX */
4474 uw_restore_parser_state (void *ps
)
4476 restore_parser_state (ps
);
4480 uw_rl_set_signals (void *ignore
)
4486 unbind_readline_variables (void)
4488 check_unbind_variable ("READLINE_LINE");
4489 check_unbind_variable ("READLINE_POINT");
4490 check_unbind_variable ("READLINE_MARK");
4491 check_unbind_variable ("READLINE_ARGUMENT");
4492 array_needs_making
= 1;
4496 uw_unbind_readline_variables (void *ignore
)
4498 unbind_readline_variables ();
4502 bash_execute_unix_command (int count
, int key
)
4507 sh_parser_state_t ps
;
4508 char *cmd
, *value
, *ce
;
4510 char ibuf
[INT_STRLEN_BOUND(int) + 1];
4515 kseq
= rl_executing_keyseq
;
4516 kslen
= rl_key_sequence_length
;
4518 /* If we have a numeric argument, chop it off the front of the key sequence */
4519 if (count
!= 1 || rl_explicit_arg
)
4521 i
= rl_trim_arg_from_keyseq (rl_executing_keyseq
, rl_key_sequence_length
, rl_get_keymap ());
4524 kseq
= rl_executing_keyseq
+ i
;
4525 kslen
= rl_key_sequence_length
- i
;
4529 /* First, we need to find the right command to execute. This is tricky,
4530 because we might have already indirected into another keymap, so we
4531 have to walk cmd_xmap using the entire key sequence. */
4532 cmd_xmap
= get_cmd_xmap_from_keymap (rl_get_keymap ());
4533 cmd
= (char *)rl_function_of_keyseq_len (kseq
, kslen
, cmd_xmap
, &type
);
4535 if (type
== ISKMAP
&& (type
= ((Keymap
) cmd
)[ANYOTHERKEY
].type
) == ISMACR
)
4536 cmd
= (char*)((Keymap
) cmd
)[ANYOTHERKEY
].function
;
4538 if (cmd
== 0 || type
!= ISMACR
)
4541 internal_error (_("bash_execute_unix_command: cannot find keymap for command"));
4542 rl_forced_update_display ();
4546 ce
= rl_get_termcap ("ce");
4547 if (ce
) /* clear current line */
4549 rl_clear_visible_line ();
4550 fflush (rl_outstream
);
4553 rl_crlf (); /* move to a new line */
4555 v
= bind_variable ("READLINE_LINE", rl_line_buffer
, 0);
4557 VSETATTR (v
, att_exported
);
4559 i
= readline_get_char_offset (rl_point
);
4560 value
= inttostr (i
, ibuf
, sizeof (ibuf
));
4561 v
= bind_int_variable ("READLINE_POINT", value
, 0);
4563 VSETATTR (v
, att_exported
);
4565 i
= readline_get_char_offset (rl_mark
);
4566 value
= inttostr (i
, ibuf
, sizeof (ibuf
));
4567 v
= bind_int_variable ("READLINE_MARK", value
, 0);
4569 VSETATTR (v
, att_exported
);
4571 if (count
!= 1 || rl_explicit_arg
)
4573 value
= inttostr (count
, ibuf
, sizeof (ibuf
));
4574 v
= bind_int_variable ("READLINE_ARGUMENT", value
, 0);
4576 VSETATTR (v
, att_exported
);
4578 array_needs_making
= 1;
4580 begin_unwind_frame ("execute-unix-command");
4581 save_parser_state (&ps
);
4582 rl_clear_signals ();
4583 add_unwind_protect (uw_unbind_readline_variables
, 0);
4584 add_unwind_protect (uw_restore_parser_state
, &ps
);
4585 add_unwind_protect (uw_rl_set_signals
, 0);
4586 r
= parse_and_execute (savestring (cmd
), "bash_execute_unix_command", SEVAL_NOHIST
);
4588 restore_parser_state (&ps
);
4590 v
= find_variable ("READLINE_LINE");
4591 maybe_make_readline_line (v
? value_cell (v
) : 0);
4593 v
= find_variable ("READLINE_POINT");
4594 if (v
&& valid_number (value_cell (v
), &mi
))
4595 readline_set_char_offset (mi
, &rl_point
);
4597 v
= find_variable ("READLINE_MARK");
4598 if (v
&& valid_number (value_cell (v
), &mi
))
4599 readline_set_char_offset (mi
, &rl_mark
);
4601 unbind_readline_variables ();
4602 discard_unwind_frame ("execute-unix-command");
4604 /* and restore the readline buffer and display after command execution. */
4605 /* If we clear the last line of the prompt above, redraw only that last
4606 line. If the command returns 124, we redraw unconditionally as in
4607 previous versions. */
4609 rl_redraw_prompt_last_line ();
4611 rl_forced_update_display ();
4616 /* This only has to handle macros/shell commandsfrom print_unix_command_map */
4618 print_unix_command (const char *kseq
, const char *value
, int readable
, const char *prefix
)
4621 fprintf (rl_outstream
, "\"%s%s\" \"%s\"\n", prefix
? prefix
: "", kseq
, value
? value
: "");
4623 fprintf (rl_outstream
, "%s%s outputs %s\n", prefix
? prefix
: "", kseq
, value
? value
: "");
4627 print_unix_command_map (void)
4629 Keymap save
, cmd_xmap
;
4630 rl_macro_print_func_t
*old_printer
;
4632 save
= rl_get_keymap ();
4633 cmd_xmap
= get_cmd_xmap_from_keymap (save
);
4634 rl_set_keymap (cmd_xmap
);
4635 old_printer
= rl_macro_display_hook
;
4636 rl_macro_display_hook
= print_unix_command
;
4637 rl_macro_dumper (1);
4638 rl_macro_display_hook
= old_printer
;
4639 rl_set_keymap (save
);
4644 init_unix_command_map (void)
4646 emacs_std_cmd_xmap
= rl_make_bare_keymap ();
4648 emacs_std_cmd_xmap
[CTRL('X')].type
= ISKMAP
;
4649 emacs_std_cmd_xmap
[CTRL('X')].function
= KEYMAP_TO_FUNCTION (rl_make_bare_keymap ());
4650 emacs_std_cmd_xmap
[ESC
].type
= ISKMAP
;
4651 emacs_std_cmd_xmap
[ESC
].function
= KEYMAP_TO_FUNCTION (rl_make_bare_keymap ());
4653 #if defined (VI_MODE)
4654 vi_insert_cmd_xmap
= rl_make_bare_keymap ();
4655 vi_movement_cmd_xmap
= rl_make_bare_keymap ();
4660 get_cmd_xmap_from_edit_mode (void)
4662 if (emacs_std_cmd_xmap
== 0)
4663 init_unix_command_map ();
4665 switch (rl_editing_mode
)
4667 case EMACS_EDITING_MODE
:
4668 return emacs_std_cmd_xmap
;
4669 #if defined (VI_MODE)
4670 case VI_EDITING_MODE
:
4671 return (get_cmd_xmap_from_keymap (rl_get_keymap ()));
4674 return (Keymap
)NULL
;
4679 get_cmd_xmap_from_keymap (Keymap kmap
)
4681 if (emacs_std_cmd_xmap
== 0)
4682 init_unix_command_map ();
4684 if (kmap
== emacs_standard_keymap
)
4685 return emacs_std_cmd_xmap
;
4686 else if (kmap
== emacs_meta_keymap
)
4687 return (FUNCTION_TO_KEYMAP (emacs_std_cmd_xmap
, ESC
));
4688 else if (kmap
== emacs_ctlx_keymap
)
4689 return (FUNCTION_TO_KEYMAP (emacs_std_cmd_xmap
, CTRL('X')));
4690 #if defined (VI_MODE)
4691 else if (kmap
== vi_insertion_keymap
)
4692 return vi_insert_cmd_xmap
;
4693 else if (kmap
== vi_movement_keymap
)
4694 return vi_movement_cmd_xmap
;
4697 return (Keymap
)NULL
;
4701 isolate_sequence (char *string
, int ind
, int need_dquote
, int *startp
)
4704 int c
, passc
, delim
;
4706 for (i
= ind
; string
[i
] && whitespace (string
[i
]); i
++)
4708 /* NEED_DQUOTE means that the first non-white character *must* be `"'. */
4709 if (need_dquote
&& string
[i
] != '"')
4711 builtin_error (_("%s: first non-whitespace character is not `\"'"), string
);
4715 /* We can have delimited strings even if NEED_DQUOTE == 0, like the command
4716 string to bind the key sequence to. */
4717 delim
= (string
[i
] == '"' || string
[i
] == '\'') ? string
[i
] : 0;
4720 *startp
= delim
? ++i
: i
;
4722 for (passc
= 0; c
= string
[i
]; i
++)
4738 if (delim
&& string
[i
] != delim
)
4740 builtin_error (_("no closing `%c' in %s"), delim
, string
);
4748 bind_keyseq_to_unix_command (char *line
)
4750 Keymap kmap
, cmd_xmap
;
4752 int i
, kstart
, translate
;
4754 kmap
= rl_get_keymap ();
4756 /* We duplicate some of the work done by rl_parse_and_bind here, but
4757 this code only has to handle `"keyseq"[:][ \t]+["]command["]' and can
4758 generate an error for anything else. */
4759 i
= isolate_sequence (line
, 0, 1, &kstart
);
4763 /* Create the key sequence string to pass to rl_generic_bind */
4764 kseq
= substring (line
, kstart
, i
);
4766 /* Allow colon or whitespace to separate the key sequence and command string. */
4767 for ( ; line
[i
] && line
[i
] != ':' && whitespace (line
[i
]) == 0; i
++)
4769 if (line
[i
] != ':' && whitespace (line
[i
]) == 0)
4771 builtin_error (_("%s: missing separator"), line
);
4776 /* If we have a whitespace separator we're going to call rl_macro_bind so
4777 we get the readline-translated version of the value (backslash-escapes
4779 translate
= line
[i
] != ':';
4781 /* Kind of tricky. If we use whitespace as a delimiter, we can backslash-
4782 quote double quotes and have them preserved in the value. However, we
4783 still want to be able to auto-detect quoted strings and only require
4784 them with whitespace delimiters. */
4785 i
= isolate_sequence (line
, i
+ 1, translate
, &kstart
);
4792 /* Create the value string containing the command to execute. */
4793 value
= substring (line
, kstart
, i
);
4795 /* Save the command to execute and the key sequence in the CMD_XMAP */
4796 cmd_xmap
= get_cmd_xmap_from_keymap (kmap
);
4798 rl_macro_bind (kseq
, value
, cmd_xmap
);
4800 rl_generic_bind (ISMACR
, kseq
, value
, cmd_xmap
);
4802 /* and bind the key sequence in the current keymap to a function that
4803 understands how to execute from CMD_XMAP */
4804 rl_bind_keyseq_in_map (kseq
, bash_execute_unix_command
, kmap
);
4811 unbind_unix_command (char *kseq
)
4815 cmd_xmap
= get_cmd_xmap_from_keymap (rl_get_keymap ());
4816 if (rl_bind_keyseq_in_map (kseq
, (rl_command_func_t
*)NULL
, cmd_xmap
) != 0)
4818 builtin_error (_("`%s': cannot unbind in command keymap"), kseq
);
4824 /* Used by the programmable completion code. Complete TEXT as a filename,
4825 but return only directories as matches. Dequotes the filename before
4826 attempting to find matches. */
4828 bash_directory_completion_matches (const char *text
)
4834 qc
= rl_dispatching
? rl_completion_quote_character
: 0;
4835 /* If rl_completion_found_quote != 0, rl_completion_matches will call the
4836 filename dequoting function, causing the directory name to be dequoted
4838 if (rl_dispatching
&& rl_completion_found_quote
== 0)
4839 dfn
= bash_dequote_filename ((char *)text
, qc
);
4842 m1
= rl_completion_matches (dfn
, rl_filename_completion_function
);
4846 if (m1
== 0 || m1
[0] == 0)
4848 /* We don't bother recomputing the lcd of the matches, because it will just
4849 get thrown away by the programmable completion code and recomputed
4851 (void)bash_progcomp_ignore_filenames (m1
);
4856 bash_dequote_text (const char *text
)
4861 qc
= (text
[0] == '"' || text
[0] == '\'') ? text
[0] : 0;
4862 dtxt
= bash_dequote_filename ((char *)text
, qc
);
4866 /* This event hook is designed to be called after readline receives a signal
4867 that interrupts read(2). It gives reasonable responsiveness to interrupts
4868 and fatal signals without executing too much code in a signal handler
4871 bash_event_hook (void)
4875 /* XXX - see if we need to do anything here if sigterm_received == 1,
4876 we probably don't want to reset the event hook since we will not be
4877 jumping to the top level */
4878 if (sigterm_received
)
4880 /* RESET_SIGTERM; */
4885 if (terminating_signal
)
4886 sig
= terminating_signal
;
4887 else if (interrupt_state
)
4889 else if (read_timeout
&& read_timeout
->alrmflag
)
4891 else if (RL_ISSTATE (RL_STATE_TIMEOUT
)) /* just in case */
4895 read_timeout
->alrmflag
= 1;
4898 sig
= first_pending_trap ();
4900 /* If we're going to longjmp to top_level, make sure we clean up readline.
4901 check_signals will call QUIT, which will eventually longjmp to top_level,
4902 calling run_interrupt_trap along the way. The check against read_timeout
4903 is so we can clean up the read builtin's state. */
4904 if (terminating_signal
|| interrupt_state
|| (read_timeout
&& read_timeout
->alrmflag
))
4905 rl_cleanup_after_signal ();
4906 bashline_reset_event_hook ();
4908 RL_UNSETSTATE (RL_STATE_TIMEOUT
); /* XXX */
4910 /* posix mode SIGINT during read -e. We only get here if SIGINT is trapped. */
4911 if (posixly_correct
&& this_shell_builtin
== read_builtin
&& sig
== SIGINT
)
4913 last_command_exit_value
= 128|SIGINT
;
4914 throw_to_top_level ();
4917 check_signals_and_traps (); /* XXX */
4921 #endif /* READLINE */