1 /* bashline.c -- Bash's interface to the readline library. */
3 /* Copyright (C) 1987-2009 Free Software Foundation, Inc.
5 This file is part of GNU Bash, the Bourne Again SHell.
7 Bash is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 Bash is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Bash. If not, see <http://www.gnu.org/licenses/>.
23 #if defined (READLINE)
25 #include "bashtypes.h"
26 #include "posixstat.h"
28 #if defined (HAVE_UNISTD_H)
32 #if defined (HAVE_GRP_H)
36 #if defined (HAVE_NETDB_H)
41 #include "chartypes.h"
50 #include "execute_cmd.h"
55 #include "builtins/common.h"
57 #include <readline/rlconf.h>
58 #include <readline/readline.h>
59 #include <readline/history.h>
61 #include <glob/glob.h>
67 #if defined (PROGRAMMABLE_COMPLETION)
68 # include "pcomplete.h"
71 /* These should agree with the defines for emacs_mode and vi_mode in
72 rldefs.h, even though that's not a public readline header file. */
73 #ifndef EMACS_EDITING_MODE
74 # define NO_EDITING_MODE -1
75 # define EMACS_EDITING_MODE 1
76 # define VI_EDITING_MODE 0
79 #define RL_BOOLEAN_VARIABLE_VALUE(s) ((s)[0] == 'o' && (s)[1] == 'n' && (s)[2] == '\0')
81 #if defined (BRACE_COMPLETION)
82 extern int bash_brace_completion __P((int, int));
83 #endif /* BRACE_COMPLETION */
85 /* To avoid including curses.h/term.h/termcap.h and that whole mess. */
86 extern int tputs __P((const char *string, int nlines, int (*outx)(int)));
88 /* Forward declarations */
90 /* Functions bound to keys in Readline for Bash users. */
91 static int shell_expand_line __P((int, int));
92 static int display_shell_version __P((int, int));
93 static int operate_and_get_next __P((int, int));
95 static int bash_ignore_filenames __P((char **));
96 static int bash_ignore_everything __P((char **));
98 #if defined (BANG_HISTORY)
99 static char *history_expand_line_internal __P((char *));
100 static int history_expand_line __P((int, int));
101 static int tcsh_magic_space __P((int, int));
102 #endif /* BANG_HISTORY */
104 static int alias_expand_line __P((int, int));
106 #if defined (BANG_HISTORY) && defined (ALIAS)
107 static int history_and_alias_expand_line __P((int, int));
110 static int bash_forward_shellword __P((int, int));
111 static int bash_backward_shellword __P((int, int));
112 static int bash_kill_shellword __P((int, int));
113 static int bash_backward_kill_shellword __P((int, int));
115 /* Helper functions for Readline. */
116 static char *restore_tilde __P((char *, char *));
118 static char *bash_filename_rewrite_hook __P((char *, int));
119 static void bash_directory_expansion __P((char **));
120 static int bash_directory_completion_hook __P((char **));
121 static int filename_completion_ignore __P((char **));
122 static int bash_push_line __P((void));
124 static void cleanup_expansion_error __P((void));
125 static void maybe_make_readline_line __P((char *));
126 static void set_up_new_line __P((char *));
128 static int check_redir __P((int));
129 static char **attempt_shell_completion __P((const char *, int, int));
130 static char *variable_completion_function __P((const char *, int));
131 static char *hostname_completion_function __P((const char *, int));
132 static char *command_subst_completion_function __P((const char *, int));
134 static void build_history_completion_array __P((void));
135 static char *history_completion_generator __P((const char *, int));
136 static int dynamic_complete_history __P((int, int));
137 static int bash_dabbrev_expand __P((int, int));
139 static void initialize_hostname_list __P((void));
140 static void add_host_name __P((char *));
141 static void snarf_hosts_from_file __P((char *));
142 static char **hostnames_matching __P((char *));
144 static void _ignore_completion_names __P((char **, sh_ignore_func_t *));
145 static int name_is_acceptable __P((const char *));
146 static int test_for_directory __P((const char *));
147 static int return_zero __P((const char *));
149 static char *bash_dequote_filename __P((char *, int));
150 static char *quote_word_break_chars __P((char *));
151 static char *bash_quote_filename __P((char *, int, char *));
153 static int putx __P((int));
154 static int bash_execute_unix_command __P((int, int));
155 static void init_unix_command_map __P((void));
156 static int isolate_sequence __P((char *, int, int, int *));
158 static int set_saved_history __P((void));
161 static int posix_edit_macros __P((int, int));
164 #if defined (PROGRAMMABLE_COMPLETION)
165 static int find_cmd_start __P((int));
166 static int find_cmd_end __P((int));
167 static char *find_cmd_name __P((int));
168 static char *prog_complete_return __P((const char *, int));
170 static char **prog_complete_matches;
173 /* Variables used here but defined in other files. */
174 #if defined (BANG_HISTORY)
175 extern int hist_verify;
178 extern int current_command_line_count, last_command_exit_value;
179 extern int array_needs_making;
180 extern int posixly_correct, no_symbolic_links;
181 extern char *current_prompt_string, *ps1_prompt;
182 extern STRING_INT_ALIST word_token_alist[];
183 extern sh_builtin_func_t *last_shell_builtin, *this_shell_builtin;
185 /* SPECIFIC_COMPLETION_FUNCTIONS specifies that we have individual
186 completion functions which indicate what type of completion should be
187 done (at or before point) that can be bound to key sequences with
188 the readline library. */
189 #define SPECIFIC_COMPLETION_FUNCTIONS
191 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
192 static int bash_specific_completion __P((int, rl_compentry_func_t *));
194 static int bash_complete_filename_internal __P((int));
195 static int bash_complete_username_internal __P((int));
196 static int bash_complete_hostname_internal __P((int));
197 static int bash_complete_variable_internal __P((int));
198 static int bash_complete_command_internal __P((int));
200 static int bash_complete_filename __P((int, int));
201 static int bash_possible_filename_completions __P((int, int));
202 static int bash_complete_username __P((int, int));
203 static int bash_possible_username_completions __P((int, int));
204 static int bash_complete_hostname __P((int, int));
205 static int bash_possible_hostname_completions __P((int, int));
206 static int bash_complete_variable __P((int, int));
207 static int bash_possible_variable_completions __P((int, int));
208 static int bash_complete_command __P((int, int));
209 static int bash_possible_command_completions __P((int, int));
211 static char *glob_complete_word __P((const char *, int));
212 static int bash_glob_completion_internal __P((int));
213 static int bash_glob_complete_word __P((int, int));
214 static int bash_glob_expand_word __P((int, int));
215 static int bash_glob_list_expansions __P((int, int));
217 #endif /* SPECIFIC_COMPLETION_FUNCTIONS */
219 static int edit_and_execute_command __P((int, int, int, char *));
220 #if defined (VI_MODE)
221 static int vi_edit_and_execute_command __P((int, int));
222 static int bash_vi_complete __P((int, int));
224 static int emacs_edit_and_execute_command __P((int, int));
226 /* Non-zero once initalize_readline () has been called. */
227 int bash_readline_initialized = 0;
229 /* If non-zero, we do hostname completion, breaking words at `@' and
230 trying to complete the stuff after the `@' from our own internal
232 int perform_hostname_completion = 1;
234 /* If non-zero, we don't do command completion on an empty line. */
235 int no_empty_command_completion;
237 /* Set FORCE_FIGNORE if you want to honor FIGNORE even if it ignores the
238 only possible matches. Set to 0 if you want to match filenames if they
239 are the only possible matches, even if FIGNORE says to. */
240 int force_fignore = 1;
242 /* Perform spelling correction on directory names during word completion */
243 int dircomplete_spelling = 0;
245 static char *bash_completer_word_break_characters = " \t\n\"'@><=;|&(:";
246 static char *bash_nohostname_word_break_characters = " \t\n\"'><=;|&(:";
249 static rl_hook_func_t *old_rl_startup_hook = (rl_hook_func_t *)NULL;
251 static int dot_in_path = 0;
253 /* Set to non-zero when dabbrev-expand is running */
254 static int dabbrev_expand_active = 0;
256 /* What kind of quoting is performed by bash_quote_filename:
257 COMPLETE_DQUOTE = double-quoting the filename
258 COMPLETE_SQUOTE = single_quoting the filename
259 COMPLETE_BSQUOTE = backslash-quoting special chars in the filename
261 #define COMPLETE_DQUOTE 1
262 #define COMPLETE_SQUOTE 2
263 #define COMPLETE_BSQUOTE 3
264 static int completion_quoting_style = COMPLETE_BSQUOTE;
266 /* Flag values for the final argument to bash_default_completion */
267 #define DEFCOMP_CMDPOS 1
269 /* Change the readline VI-mode keymaps into or out of Posix.2 compliance.
270 Called when the shell is put into or out of `posix' mode. */
272 posix_readline_initialize (on_or_off)
276 rl_variable_bind ("comment-begin", "#");
277 #if defined (VI_MODE)
278 rl_bind_key_in_map (CTRL ('I'), on_or_off ? rl_insert : rl_complete, vi_insertion_keymap);
283 reset_completer_word_break_chars ()
285 rl_completer_word_break_characters = perform_hostname_completion ? savestring (bash_completer_word_break_characters) : savestring (bash_nohostname_word_break_characters);
288 /* When this function returns, rl_completer_word_break_characters points to
289 dynamically allocated memory. */
291 enable_hostname_completion (on_or_off)
295 char *at, *nv, *nval;
297 old_value = perform_hostname_completion;
301 perform_hostname_completion = 1;
302 rl_special_prefixes = "$@";
306 perform_hostname_completion = 0;
307 rl_special_prefixes = "$";
310 /* Now we need to figure out how to appropriately modify and assign
311 rl_completer_word_break_characters depending on whether we want
312 hostname completion on or off. */
314 /* If this is the first time this has been called
315 (bash_readline_initialized == 0), use the sames values as before, but
316 allocate new memory for rl_completer_word_break_characters. */
318 if (bash_readline_initialized == 0 &&
319 (rl_completer_word_break_characters == 0 ||
320 rl_completer_word_break_characters == rl_basic_word_break_characters))
323 rl_completer_word_break_characters = savestring (bash_completer_word_break_characters);
325 rl_completer_word_break_characters = savestring (bash_nohostname_word_break_characters);
329 /* See if we have anything to do. */
330 at = strchr (rl_completer_word_break_characters, '@');
331 if ((at == 0 && on_or_off == 0) || (at != 0 && on_or_off != 0))
334 /* We have something to do. Do it. */
335 nval = (char *)xmalloc (strlen (rl_completer_word_break_characters) + 1 + on_or_off);
339 /* Turn it off -- just remove `@' from word break chars. We want
340 to remove all occurrences of `@' from the char list, so we loop
341 rather than just copy the rest of the list over AT. */
342 for (nv = nval, at = rl_completer_word_break_characters; *at; )
352 strcpy (nval + 1, rl_completer_word_break_characters);
355 free (rl_completer_word_break_characters);
356 rl_completer_word_break_characters = nval;
362 /* Called once from parse.y if we are going to use readline. */
364 initialize_readline ()
366 rl_command_func_t *func;
369 if (bash_readline_initialized)
372 rl_terminal_name = get_string_value ("TERM");
374 rl_outstream = stderr;
376 /* Allow conditional parsing of the ~/.inputrc file. */
377 rl_readline_name = "Bash";
379 /* Add bindable names before calling rl_initialize so they may be
380 referenced in the various inputrc files. */
381 rl_add_defun ("shell-expand-line", shell_expand_line, -1);
383 rl_add_defun ("history-expand-line", history_expand_line, -1);
384 rl_add_defun ("magic-space", tcsh_magic_space, -1);
387 rl_add_defun ("shell-forward-word", bash_forward_shellword, -1);
388 rl_add_defun ("shell-backward-word", bash_backward_shellword, -1);
389 rl_add_defun ("shell-kill-word", bash_kill_shellword, -1);
390 rl_add_defun ("shell-backward-kill-word", bash_backward_kill_shellword, -1);
393 rl_add_defun ("alias-expand-line", alias_expand_line, -1);
395 rl_add_defun ("history-and-alias-expand-line", history_and_alias_expand_line, -1);
399 /* Backwards compatibility. */
400 rl_add_defun ("insert-last-argument", rl_yank_last_arg, -1);
402 rl_add_defun ("operate-and-get-next", operate_and_get_next, -1);
403 rl_add_defun ("display-shell-version", display_shell_version, -1);
404 rl_add_defun ("edit-and-execute-command", emacs_edit_and_execute_command, -1);
406 #if defined (BRACE_COMPLETION)
407 rl_add_defun ("complete-into-braces", bash_brace_completion, -1);
410 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
411 rl_add_defun ("complete-filename", bash_complete_filename, -1);
412 rl_add_defun ("possible-filename-completions", bash_possible_filename_completions, -1);
413 rl_add_defun ("complete-username", bash_complete_username, -1);
414 rl_add_defun ("possible-username-completions", bash_possible_username_completions, -1);
415 rl_add_defun ("complete-hostname", bash_complete_hostname, -1);
416 rl_add_defun ("possible-hostname-completions", bash_possible_hostname_completions, -1);
417 rl_add_defun ("complete-variable", bash_complete_variable, -1);
418 rl_add_defun ("possible-variable-completions", bash_possible_variable_completions, -1);
419 rl_add_defun ("complete-command", bash_complete_command, -1);
420 rl_add_defun ("possible-command-completions", bash_possible_command_completions, -1);
421 rl_add_defun ("glob-complete-word", bash_glob_complete_word, -1);
422 rl_add_defun ("glob-expand-word", bash_glob_expand_word, -1);
423 rl_add_defun ("glob-list-expansions", bash_glob_list_expansions, -1);
426 rl_add_defun ("dynamic-complete-history", dynamic_complete_history, -1);
427 rl_add_defun ("dabbrev-expand", bash_dabbrev_expand, -1);
429 /* Bind defaults before binding our custom shell keybindings. */
430 if (RL_ISSTATE(RL_STATE_INITIALIZED) == 0)
433 /* Bind up our special shell functions. */
434 rl_bind_key_if_unbound_in_map (CTRL('E'), shell_expand_line, emacs_meta_keymap);
437 rl_bind_key_if_unbound_in_map ('^', history_expand_line, emacs_meta_keymap);
440 rl_bind_key_if_unbound_in_map (CTRL ('O'), operate_and_get_next, emacs_standard_keymap);
441 rl_bind_key_if_unbound_in_map (CTRL ('V'), display_shell_version, emacs_ctlx_keymap);
443 /* In Bash, the user can switch editing modes with "set -o [vi emacs]",
444 so it is not necessary to allow C-M-j for context switching. Turn
445 off this occasionally confusing behaviour. */
448 func = rl_function_of_keyseq (kseq, emacs_meta_keymap, (int *)NULL);
449 if (func == rl_vi_editing_mode)
450 rl_unbind_key_in_map (CTRL('J'), emacs_meta_keymap);
452 func = rl_function_of_keyseq (kseq, emacs_meta_keymap, (int *)NULL);
453 if (func == rl_vi_editing_mode)
454 rl_unbind_key_in_map (CTRL('M'), emacs_meta_keymap);
455 #if defined (VI_MODE)
456 rl_unbind_key_in_map (CTRL('E'), vi_movement_keymap);
459 #if defined (BRACE_COMPLETION)
460 rl_bind_key_if_unbound_in_map ('{', bash_brace_completion, emacs_meta_keymap); /*}*/
461 #endif /* BRACE_COMPLETION */
463 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
464 rl_bind_key_if_unbound_in_map ('/', bash_complete_filename, emacs_meta_keymap);
465 rl_bind_key_if_unbound_in_map ('/', bash_possible_filename_completions, emacs_ctlx_keymap);
467 /* Have to jump through hoops here because there is a default binding for
468 M-~ (rl_tilde_expand) */
471 func = rl_function_of_keyseq (kseq, emacs_meta_keymap, (int *)NULL);
472 if (func == 0 || func == rl_tilde_expand)
473 rl_bind_keyseq_in_map (kseq, bash_complete_username, emacs_meta_keymap);
475 rl_bind_key_if_unbound_in_map ('~', bash_possible_username_completions, emacs_ctlx_keymap);
477 rl_bind_key_if_unbound_in_map ('@', bash_complete_hostname, emacs_meta_keymap);
478 rl_bind_key_if_unbound_in_map ('@', bash_possible_hostname_completions, emacs_ctlx_keymap);
480 rl_bind_key_if_unbound_in_map ('$', bash_complete_variable, emacs_meta_keymap);
481 rl_bind_key_if_unbound_in_map ('$', bash_possible_variable_completions, emacs_ctlx_keymap);
483 rl_bind_key_if_unbound_in_map ('!', bash_complete_command, emacs_meta_keymap);
484 rl_bind_key_if_unbound_in_map ('!', bash_possible_command_completions, emacs_ctlx_keymap);
486 rl_bind_key_if_unbound_in_map ('g', bash_glob_complete_word, emacs_meta_keymap);
487 rl_bind_key_if_unbound_in_map ('*', bash_glob_expand_word, emacs_ctlx_keymap);
488 rl_bind_key_if_unbound_in_map ('g', bash_glob_list_expansions, emacs_ctlx_keymap);
490 #endif /* SPECIFIC_COMPLETION_FUNCTIONS */
494 func = rl_function_of_keyseq (kseq, emacs_meta_keymap, (int *)NULL);
495 if (func == 0 || func == rl_tab_insert)
496 rl_bind_key_in_map (TAB, dynamic_complete_history, emacs_meta_keymap);
498 /* Tell the completer that we want a crack first. */
499 rl_attempted_completion_function = attempt_shell_completion;
501 /* Tell the completer that we might want to follow symbolic links or
502 do other expansion on directory names. */
503 rl_directory_completion_hook = bash_directory_completion_hook;
505 rl_filename_rewrite_hook = bash_filename_rewrite_hook;
507 /* Tell the filename completer we want a chance to ignore some names. */
508 rl_ignore_some_completions_function = filename_completion_ignore;
510 /* Bind C-xC-e to invoke emacs and run result as commands. */
511 rl_bind_key_if_unbound_in_map (CTRL ('E'), emacs_edit_and_execute_command, emacs_ctlx_keymap);
512 #if defined (VI_MODE)
513 rl_bind_key_if_unbound_in_map ('v', vi_edit_and_execute_command, vi_movement_keymap);
515 rl_bind_key_if_unbound_in_map ('@', posix_edit_macros, vi_movement_keymap);
518 rl_bind_key_in_map ('\\', bash_vi_complete, vi_movement_keymap);
519 rl_bind_key_in_map ('*', bash_vi_complete, vi_movement_keymap);
520 rl_bind_key_in_map ('=', bash_vi_complete, vi_movement_keymap);
523 rl_completer_quote_characters = "'\"";
525 /* This sets rl_completer_word_break_characters and rl_special_prefixes
526 to the appropriate values, depending on whether or not hostname
527 completion is enabled. */
528 enable_hostname_completion (perform_hostname_completion);
530 /* characters that need to be quoted when appearing in filenames. */
532 rl_filename_quote_characters = " \t\n\\\"'@<>=;|&()#$`?*[!:{"; /*}*/
534 rl_filename_quote_characters = " \t\n\\\"'@<>=;|&()#$`?*[!:{~"; /*}*/
536 rl_filename_quoting_function = bash_quote_filename;
537 rl_filename_dequoting_function = bash_dequote_filename;
538 rl_char_is_quoted_p = char_is_quoted;
541 /* This is superfluous and makes it impossible to use tab completion in
542 vi mode even when explicitly binding it in ~/.inputrc. sv_strict_posix()
543 should already have called posix_readline_initialize() when
544 posixly_correct was set. */
546 posix_readline_initialize (1);
549 bash_readline_initialized = 1;
553 bashline_reinitialize ()
555 bash_readline_initialized = 0;
558 /* On Sun systems at least, rl_attempted_completion_function can end up
559 getting set to NULL, and rl_completion_entry_function set to do command
560 word completion if Bash is interrupted while trying to complete a command
561 word. This just resets all the completion functions to the right thing.
562 It's called from throw_to_top_level(). */
567 rl_attempted_completion_function = attempt_shell_completion;
568 rl_completion_entry_function = NULL;
569 rl_directory_completion_hook = bash_directory_completion_hook;
570 rl_ignore_some_completions_function = filename_completion_ignore;
573 /* Contains the line to push into readline. */
574 static char *push_to_readline = (char *)NULL;
576 /* Push the contents of push_to_readline into the
581 if (push_to_readline)
583 rl_insert_text (push_to_readline);
584 free (push_to_readline);
585 push_to_readline = (char *)NULL;
586 rl_startup_hook = old_rl_startup_hook;
591 /* Call this to set the initial text for the next line to read
597 FREE (push_to_readline);
599 push_to_readline = savestring (line);
600 old_rl_startup_hook = rl_startup_hook;
601 rl_startup_hook = bash_push_line;
607 display_shell_version (count, c)
611 show_shell_version (0);
612 putc ('\r', rl_outstream);
613 fflush (rl_outstream);
619 /* **************************************************************** */
623 /* **************************************************************** */
625 /* If the user requests hostname completion, then simply build a list
626 of hosts, and complete from that forever more, or at least until
627 HOSTFILE is unset. */
629 /* THIS SHOULD BE A STRINGLIST. */
630 /* The kept list of hostnames. */
631 static char **hostname_list = (char **)NULL;
633 /* The physical size of the above list. */
634 static int hostname_list_size;
636 /* The number of hostnames in the above list. */
637 static int hostname_list_length;
639 /* Whether or not HOSTNAME_LIST has been initialized. */
640 int hostname_list_initialized = 0;
642 /* Initialize the hostname completion table. */
644 initialize_hostname_list ()
648 temp = get_string_value ("HOSTFILE");
650 temp = get_string_value ("hostname_completion_file");
652 temp = DEFAULT_HOSTS_FILE;
654 snarf_hosts_from_file (temp);
657 hostname_list_initialized++;
660 /* Add NAME to the list of hosts. */
665 if (hostname_list_length + 2 > hostname_list_size)
667 hostname_list_size = (hostname_list_size + 32) - (hostname_list_size % 32);
668 hostname_list = strvec_resize (hostname_list, hostname_list_size);
671 hostname_list[hostname_list_length++] = savestring (name);
672 hostname_list[hostname_list_length] = (char *)NULL;
675 #define cr_whitespace(c) ((c) == '\r' || (c) == '\n' || whitespace(c))
678 snarf_hosts_from_file (filename)
682 char *temp, buffer[256], name[256];
683 register int i, start;
685 file = fopen (filename, "r");
689 while (temp = fgets (buffer, 255, file))
691 /* Skip to first character. */
692 for (i = 0; buffer[i] && cr_whitespace (buffer[i]); i++)
695 /* If comment or blank line, ignore. */
696 if (buffer[i] == '\0' || buffer[i] == '#')
699 /* If `preprocessor' directive, do the include. */
700 if (strncmp (buffer + i, "$include ", 9) == 0)
704 /* Find start of filename. */
705 for (incfile = buffer + i + 9; *incfile && whitespace (*incfile); incfile++)
708 /* Find end of filename. */
709 for (t = incfile; *t && cr_whitespace (*t) == 0; t++)
714 snarf_hosts_from_file (incfile);
718 /* Skip internet address if present. */
719 if (DIGIT (buffer[i]))
720 for (; buffer[i] && cr_whitespace (buffer[i]) == 0; i++);
722 /* Gobble up names. Each name is separated with whitespace. */
725 for (; cr_whitespace (buffer[i]); i++)
727 if (buffer[i] == '\0' || buffer[i] == '#')
730 /* Isolate the current word. */
731 for (start = i; buffer[i] && cr_whitespace (buffer[i]) == 0; i++)
735 strncpy (name, buffer + start, i - start);
736 name[i - start] = '\0';
737 add_host_name (name);
743 /* Return the hostname list. */
747 if (hostname_list_initialized == 0)
748 initialize_hostname_list ();
749 return (hostname_list);
753 clear_hostname_list ()
757 if (hostname_list_initialized == 0)
759 for (i = 0; i < hostname_list_length; i++)
760 free (hostname_list[i]);
761 hostname_list_length = hostname_list_initialized = 0;
764 /* Return a NULL terminated list of hostnames which begin with TEXT.
765 Initialize the hostname list the first time if neccessary.
766 The array is malloc ()'ed, but not the individual strings. */
768 hostnames_matching (text)
771 register int i, len, nmatch, rsize;
774 if (hostname_list_initialized == 0)
775 initialize_hostname_list ();
777 if (hostname_list_initialized == 0)
778 return ((char **)NULL);
780 /* Special case. If TEXT consists of nothing, then the whole list is
784 result = strvec_create (1 + hostname_list_length);
785 for (i = 0; i < hostname_list_length; i++)
786 result[i] = hostname_list[i];
787 result[i] = (char *)NULL;
791 /* Scan until found, or failure. */
793 result = (char **)NULL;
794 for (i = nmatch = rsize = 0; i < hostname_list_length; i++)
796 if (STREQN (text, hostname_list[i], len) == 0)
799 /* OK, it matches. Add it to the list. */
800 if (nmatch >= (rsize - 1))
802 rsize = (rsize + 16) - (rsize % 16);
803 result = strvec_resize (result, rsize);
806 result[nmatch++] = hostname_list[i];
809 result[nmatch] = (char *)NULL;
813 /* The equivalent of the Korn shell C-o operate-and-get-next-history-line
815 static int saved_history_line_to_use = -1;
820 if (saved_history_line_to_use >= 0)
821 rl_get_previous_history (history_length - saved_history_line_to_use, 0);
822 saved_history_line_to_use = -1;
823 rl_startup_hook = old_rl_startup_hook;
828 operate_and_get_next (count, c)
833 /* Accept the current line. */
836 /* Find the current line, and find the next line to use. */
837 where = where_history ();
839 if ((history_is_stifled () && (history_length >= history_max_entries)) ||
840 (where >= history_length - 1))
841 saved_history_line_to_use = where;
843 saved_history_line_to_use = where + 1;
845 old_rl_startup_hook = rl_startup_hook;
846 rl_startup_hook = set_saved_history;
851 /* This vi mode command causes VI_EDIT_COMMAND to be run on the current
852 command being entered (if no explicit argument is given), otherwise on
853 a command from the history file. */
855 #define VI_EDIT_COMMAND "fc -e \"${VISUAL:-${EDITOR:-vi}}\""
856 #define EMACS_EDIT_COMMAND "fc -e \"${VISUAL:-${EDITOR:-emacs}}\""
857 #define POSIX_VI_EDIT_COMMAND "fc -e vi"
860 edit_and_execute_command (count, c, editing_mode, edit_command)
861 int count, c, editing_mode;
864 char *command, *metaval;
865 int r, cclc, rrs, metaflag;
867 rrs = rl_readline_state;
868 cclc = current_command_line_count;
870 /* Accept the current line. */
875 command = (char *)xmalloc (strlen (edit_command) + 8);
876 sprintf (command, "%s %d", edit_command, count);
880 /* Take the command we were just editing, add it to the history file,
881 then call fc to operate on it. We have to add a dummy command to
882 the end of the history because fc ignores the last command (assumes
883 it's supposed to deal with the command before the `fc'). */
885 bash_add_history (rl_line_buffer);
886 bash_add_history ("");
887 history_lines_this_session++;
889 command = savestring (edit_command);
892 metaval = rl_variable_value ("input-meta");
893 metaflag = RL_BOOLEAN_VARIABLE_VALUE (metaval);
895 /* Now, POSIX.1-2001 and SUSv3 say that the commands executed from the
896 temporary file should be placed into the history. We don't do that
898 if (rl_deprep_term_function)
899 (*rl_deprep_term_function) ();
900 r = parse_and_execute (command, (editing_mode == VI_EDITING_MODE) ? "v" : "C-xC-e", SEVAL_NOHIST);
901 if (rl_prep_term_function)
902 (*rl_prep_term_function) (metaflag);
904 current_command_line_count = cclc;
906 /* Now erase the contents of the current line and undo the effects of the
907 rl_accept_line() above. We don't even want to make the text we just
908 executed available for undoing. */
909 rl_line_buffer[0] = '\0'; /* XXX */
910 rl_point = rl_end = 0;
912 rl_readline_state = rrs;
914 rl_forced_update_display ();
919 #if defined (VI_MODE)
921 vi_edit_and_execute_command (count, c)
925 return (edit_and_execute_command (count, c, VI_EDITING_MODE, POSIX_VI_EDIT_COMMAND));
927 return (edit_and_execute_command (count, c, VI_EDITING_MODE, VI_EDIT_COMMAND));
932 emacs_edit_and_execute_command (count, c)
935 return (edit_and_execute_command (count, c, EMACS_EDITING_MODE, EMACS_EDIT_COMMAND));
940 posix_edit_macros (count, key)
944 char alias_name[3], *alias_value, *macro;
949 alias_name[2] = '\0';
951 alias_value = get_alias_value (alias_name);
952 if (alias_value && *alias_value)
954 macro = savestring (alias_value);
955 rl_push_macro_input (macro);
961 /* Bindable commands that move `shell-words': that is, sequences of
962 non-unquoted-metacharacters. */
964 #define WORDDELIM(c) (shellmeta(c) || shellblank(c))
967 bash_forward_shellword (count, key)
975 return (bash_backward_shellword (-count, key));
977 /* The tricky part of this is deciding whether or not the first character
978 we're on is an unquoted metacharacter. Not completely handled yet. */
979 /* XXX - need to test this stuff with backslash-escaped shell
980 metacharacters and unclosed single- and double-quoted strings. */
993 /* Move forward until we hit a non-metacharacter. */
994 while (p < rl_end && (c = rl_line_buffer[p]) && WORDDELIM (c))
999 ADVANCE_CHAR (rl_line_buffer, slen, p);
1000 continue; /* straight back to loop, don't increment p */
1002 if (p < rl_end && rl_line_buffer[p])
1003 ADVANCE_CHAR (rl_line_buffer, slen, p);
1006 p = skip_to_delim (rl_line_buffer, ++p, "'", SD_NOJMP);
1009 p = skip_to_delim (rl_line_buffer, ++p, "\"", SD_NOJMP);
1017 if (rl_line_buffer[p] == 0 || p == rl_end)
1024 /* Now move forward until we hit a non-quoted metacharacter or EOL */
1025 while (p < rl_end && (c = rl_line_buffer[p]) && WORDDELIM (c) == 0)
1030 ADVANCE_CHAR (rl_line_buffer, slen, p);
1031 continue; /* straight back to loop, don't increment p */
1033 if (p < rl_end && rl_line_buffer[p])
1034 ADVANCE_CHAR (rl_line_buffer, slen, p);
1037 p = skip_to_delim (rl_line_buffer, ++p, "'", SD_NOJMP);
1040 p = skip_to_delim (rl_line_buffer, ++p, "\"", SD_NOJMP);
1048 if (p == rl_end || rl_line_buffer[p] == 0)
1062 bash_backward_shellword (count, key)
1070 return (bash_forward_shellword (-count, key));
1083 /* Move backward until we hit a non-metacharacter. */
1086 c = rl_line_buffer[p];
1087 if (WORDDELIM (c) && char_is_quoted (rl_line_buffer, p) == 0)
1088 BACKUP_CHAR (rl_line_buffer, slen, p);
1098 /* Now move backward until we hit a metacharacter or BOL. */
1101 c = rl_line_buffer[p];
1102 if (WORDDELIM (c) && char_is_quoted (rl_line_buffer, p) == 0)
1104 BACKUP_CHAR (rl_line_buffer, slen, p);
1115 bash_kill_shellword (count, key)
1121 return (bash_backward_kill_shellword (-count, key));
1124 bash_forward_shellword (count, key);
1127 rl_kill_text (p, rl_point);
1130 if (rl_editing_mode == 1) /* 1 == emacs_mode */
1137 bash_backward_kill_shellword (count, key)
1143 return (bash_kill_shellword (-count, key));
1146 bash_backward_shellword (count, key);
1149 rl_kill_text (p, rl_point);
1151 if (rl_editing_mode == 1) /* 1 == emacs_mode */
1158 /* **************************************************************** */
1160 /* How To Do Shell Completion */
1162 /* **************************************************************** */
1164 #define COMMAND_SEPARATORS ";|&{(`"
1171 register int this_char, prev_char;
1173 /* Handle the two character tokens `>&', `<&', and `>|'.
1174 We are not in a command position after one of these. */
1175 this_char = rl_line_buffer[ti];
1176 prev_char = rl_line_buffer[ti - 1];
1178 if ((this_char == '&' && (prev_char == '<' || prev_char == '>')) ||
1179 (this_char == '|' && prev_char == '>'))
1181 else if ((this_char == '{' && prev_char == '$') || /* } */
1182 (char_is_quoted (rl_line_buffer, ti)))
1187 #if defined (PROGRAMMABLE_COMPLETION)
1189 * XXX - because of the <= start test, and setting os = s+1, this can
1190 * potentially return os > start. This is probably not what we want to
1191 * happen, but fix later after 2.05a-release.
1194 find_cmd_start (start)
1200 while (((s = skip_to_delim (rl_line_buffer, os, COMMAND_SEPARATORS, SD_NOJMP|SD_NOSKIPCMD)) <= start) &&
1212 e = skip_to_delim (rl_line_buffer, end, COMMAND_SEPARATORS, SD_NOJMP);
1217 find_cmd_name (start)
1223 for (s = start; whitespace (rl_line_buffer[s]); s++)
1226 /* skip until a shell break character */
1227 e = skip_to_delim (rl_line_buffer, s, "()<>;&| \t\n", SD_NOJMP);
1229 name = substring (rl_line_buffer, s, e);
1235 prog_complete_return (text, matchnum)
1244 if (prog_complete_matches == 0 || prog_complete_matches[ind] == 0)
1245 return (char *)NULL;
1246 return (prog_complete_matches[ind++]);
1249 #endif /* PROGRAMMABLE_COMPLETION */
1251 /* Do some completion on TEXT. The indices of TEXT in RL_LINE_BUFFER are
1252 at START and END. Return an array of matches, or NULL if none. */
1254 attempt_shell_completion (text, start, end)
1258 int in_command_position, ti, saveti, qc, dflags;
1259 char **matches, *command_separator_chars;
1261 command_separator_chars = COMMAND_SEPARATORS;
1262 matches = (char **)NULL;
1263 rl_ignore_some_completions_function = filename_completion_ignore;
1265 /* Determine if this could be a command word. It is if it appears at
1266 the start of the line (ignoring preceding whitespace), or if it
1267 appears after a character that separates commands. It cannot be a
1268 command word if we aren't at the top-level prompt. */
1272 while ((ti > -1) && (whitespace (rl_line_buffer[ti])))
1276 /* If this is an open quote, maybe we're trying to complete a quoted
1278 if (ti >= 0 && (rl_line_buffer[ti] == '"' || rl_line_buffer[ti] == '\''))
1280 qc = rl_line_buffer[ti];
1282 while (ti > -1 && (whitespace (rl_line_buffer[ti])))
1287 in_command_position = 0;
1290 /* Only do command completion at the start of a line when we
1291 are prompting at the top level. */
1292 if (current_prompt_string == ps1_prompt)
1293 in_command_position++;
1295 else if (member (rl_line_buffer[ti], command_separator_chars))
1297 in_command_position++;
1299 if (check_redir (ti) == 1)
1300 in_command_position = 0;
1304 /* This still could be in command position. It is possible
1305 that all of the previous words on the line are variable
1309 /* Check that we haven't incorrectly flagged a closed command substitution
1310 as indicating we're in a command position. */
1311 if (in_command_position && ti >= 0 && rl_line_buffer[ti] == '`' &&
1312 *text != '`' && unclosed_pair (rl_line_buffer, end, "`") == 0)
1313 in_command_position = 0;
1315 /* Special handling for command substitution. If *TEXT is a backquote,
1316 it can be the start or end of an old-style command substitution, or
1317 unmatched. If it's unmatched, both calls to unclosed_pair will
1318 succeed. Don't bother if readline found a single quote and we are
1319 completing on the substring. */
1320 if (*text == '`' && rl_completion_quote_character != '\'' &&
1321 (in_command_position || (unclosed_pair (rl_line_buffer, start, "`") &&
1322 unclosed_pair (rl_line_buffer, end, "`"))))
1323 matches = rl_completion_matches (text, command_subst_completion_function);
1325 #if defined (PROGRAMMABLE_COMPLETION)
1326 /* Attempt programmable completion. */
1327 if (matches == 0 && (in_command_position == 0 || text[0] == '\0') &&
1328 prog_completion_enabled && (progcomp_size () > 0) &&
1329 current_prompt_string == ps1_prompt)
1334 /* XXX - don't free the members */
1335 if (prog_complete_matches)
1336 free (prog_complete_matches);
1337 prog_complete_matches = (char **)NULL;
1339 s = find_cmd_start (start);
1340 e = find_cmd_end (end);
1341 n = find_cmd_name (s);
1342 if (e == 0 && e == s && text[0] == '\0')
1343 prog_complete_matches = programmable_completions ("_EmptycmD_", text, s, e, &foundcs);
1344 else if (e > s && assignment (n, 0) == 0)
1345 prog_complete_matches = programmable_completions (n, text, s, e, &foundcs);
1349 /* XXX - if we found a COMPSPEC for the command, just return whatever
1350 the programmable completion code returns, and disable the default
1351 filename completion that readline will do unless the COPT_DEFAULT
1352 option has been set with the `-o default' option to complete or
1356 pcomp_set_readline_variables (foundcs, 1);
1357 /* Turn what the programmable completion code returns into what
1358 readline wants. I should have made compute_lcd_of_matches
1360 matches = rl_completion_matches (text, prog_complete_return);
1361 if ((foundcs & COPT_DEFAULT) == 0)
1362 rl_attempted_completion_over = 1; /* no default */
1363 if (matches || ((foundcs & COPT_BASHDEFAULT) == 0))
1372 if (in_command_position)
1373 dflags |= DEFCOMP_CMDPOS;
1374 matches = bash_default_completion (text, start, end, qc, dflags);
1381 bash_default_completion (text, start, end, qc, compflags)
1383 int start, end, qc, compflags;
1387 matches = (char **)NULL;
1389 /* New posix-style command substitution or variable name? */
1390 if (!matches && *text == '$')
1392 if (qc != '\'' && text[1] == '(') /* ) */
1393 matches = rl_completion_matches (text, command_subst_completion_function);
1395 matches = rl_completion_matches (text, variable_completion_function);
1398 /* If the word starts in `~', and there is no slash in the word, then
1399 try completing this word as a username. */
1400 if (matches ==0 && *text == '~' && mbschr (text, '/') == 0)
1401 matches = rl_completion_matches (text, rl_username_completion_function);
1403 /* Another one. Why not? If the word starts in '@', then look through
1404 the world of known hostnames for completion first. */
1405 if (!matches && perform_hostname_completion && *text == '@')
1406 matches = rl_completion_matches (text, hostname_completion_function);
1408 /* And last, (but not least) if this word is in a command position, then
1409 complete over possible command names, including aliases, functions,
1410 and command names. */
1411 if (matches == 0 && (compflags & DEFCOMP_CMDPOS))
1413 /* If END == START and text[0] == 0, we are trying to complete an empty
1415 if (no_empty_command_completion && end == start && text[0] == '\0')
1417 matches = (char **)NULL;
1418 rl_ignore_some_completions_function = bash_ignore_everything;
1422 #define CMD_IS_DIR(x) (absolute_pathname(x) == 0 && absolute_program(x) == 0 && *(x) != '~' && test_for_directory (x))
1425 matches = rl_completion_matches (text, command_word_completion_function);
1427 /* If we are attempting command completion and nothing matches, we
1428 do not want readline to perform filename completion for us. We
1429 still want to be able to complete partial pathnames, so set the
1430 completion ignore function to something which will remove
1431 filenames and leave directories in the match list. */
1432 if (matches == (char **)NULL)
1433 rl_ignore_some_completions_function = bash_ignore_filenames;
1434 else if (matches[1] == 0 && CMD_IS_DIR(matches[0]) && dot_in_path == 0)
1435 /* If we found a single match, without looking in the current
1436 directory (because it's not in $PATH), but the found name is
1437 also a command in the current directory, suppress appending any
1438 terminating character, since it's ambiguous. */
1440 rl_completion_suppress_append = 1;
1441 rl_filename_completion_desired = 0;
1443 else if (matches[0] && matches[1] && STREQ (matches[0], matches[1]) && CMD_IS_DIR (matches[0]))
1444 /* There are multiple instances of the same match (duplicate
1445 completions haven't yet been removed). In this case, all of
1446 the matches will be the same, and the duplicate removal code
1447 will distill them all down to one. We turn on
1448 rl_completion_suppress_append for the same reason as above.
1449 Remember: we only care if there's eventually a single unique
1450 completion. If there are multiple completions this won't
1451 make a difference and the problem won't occur. */
1453 rl_completion_suppress_append = 1;
1454 rl_filename_completion_desired = 0;
1459 /* This could be a globbing pattern, so try to expand it using pathname
1461 if (!matches && glob_pattern_p (text))
1463 matches = rl_completion_matches (text, glob_complete_word);
1464 /* A glob expression that matches more than one filename is problematic.
1465 If we match more than one filename, punt. */
1466 if (matches && matches[1] && rl_completion_type == TAB)
1468 strvec_dispose (matches);
1469 matches = (char **)0;
1476 /* This is the function to call when the word to complete is in a position
1477 where a command word can be found. It grovels $PATH, looking for commands
1478 that match. It also scans aliases, function names, and the shell_builtin
1481 command_word_completion_function (hint_text, state)
1482 const char *hint_text;
1485 static char *hint = (char *)NULL;
1486 static char *path = (char *)NULL;
1487 static char *val = (char *)NULL;
1488 static char *filename_hint = (char *)NULL;
1489 static char *dequoted_hint = (char *)NULL;
1490 static char *directory_part = (char *)NULL;
1491 static char **glob_matches = (char **)NULL;
1492 static int path_index, hint_len, dequoted_len, istate, igncase;
1493 static int mapping_over, local_index, searching_path, hint_is_dir;
1494 static int old_glob_ignore_case, globpat;
1495 static SHELL_VAR **varlist = (SHELL_VAR **)NULL;
1497 static alias_t **alias_list = (alias_t **)NULL;
1501 /* We have to map over the possibilities for command words. If we have
1502 no state, then make one just for that purpose. */
1505 if (dequoted_hint && dequoted_hint != hint)
1506 free (dequoted_hint);
1510 mapping_over = searching_path = 0;
1511 hint_is_dir = CMD_IS_DIR (hint_text);
1514 temp = rl_variable_value ("completion-ignore-case");
1515 igncase = RL_BOOLEAN_VARIABLE_VALUE (temp);
1519 free (glob_matches);
1520 glob_matches = (char **)NULL;
1523 globpat = glob_pattern_p (hint_text);
1525 /* If this is an absolute program name, do not check it against
1526 aliases, reserved words, functions or builtins. We must check
1527 whether or not it is unique, and, if so, whether that filename
1529 if (globpat || absolute_program (hint_text))
1531 /* Perform tilde expansion on what's passed, so we don't end up
1532 passing filenames with tildes directly to stat(). */
1533 if (*hint_text == '~')
1535 hint = bash_tilde_expand (hint_text, 0);
1536 directory_part = savestring (hint_text);
1537 temp = strchr (directory_part, '/');
1542 free (directory_part);
1543 directory_part = (char *)NULL;
1547 hint = savestring (hint_text);
1549 dequoted_hint = hint;
1550 /* If readline's completer found a quote character somewhere, but
1551 didn't set the quote character, there must have been a quote
1552 character embedded in the filename. It can't be at the start of
1553 the filename, so we need to dequote the filename before we look
1554 in the file system for it. */
1555 if (rl_completion_found_quote && rl_completion_quote_character == 0)
1557 dequoted_hint = bash_dequote_filename (hint, 0);
1559 hint = dequoted_hint;
1561 dequoted_len = hint_len = strlen (hint);
1564 free (filename_hint);
1566 filename_hint = savestring (hint);
1582 dequoted_hint = hint = savestring (hint_text);
1583 dequoted_len = hint_len = strlen (hint);
1585 if (rl_completion_found_quote && rl_completion_quote_character == 0)
1587 dequoted_hint = bash_dequote_filename (hint, 0);
1588 dequoted_len = strlen (dequoted_hint);
1591 path = get_string_value ("PATH");
1592 path_index = dot_in_path = 0;
1594 /* Initialize the variables for each type of command word. */
1600 varlist = all_visible_functions ();
1606 alias_list = all_aliases ();
1610 /* mapping_over says what we are currently hacking. Note that every case
1611 in this list must fall through when there are no more possibilities. */
1613 switch (mapping_over)
1615 case 0: /* Aliases come first. */
1617 while (alias_list && alias_list[local_index])
1619 register char *alias;
1621 alias = alias_list[local_index++]->name;
1623 if (STREQN (alias, hint, hint_len))
1624 return (savestring (alias));
1630 case 1: /* Then shell reserved words. */
1632 while (word_token_alist[local_index].word)
1634 register char *reserved_word;
1636 reserved_word = word_token_alist[local_index++].word;
1638 if (STREQN (reserved_word, hint, hint_len))
1639 return (savestring (reserved_word));
1645 case 2: /* Then function names. */
1646 while (varlist && varlist[local_index])
1648 register char *varname;
1650 varname = varlist[local_index++]->name;
1652 if (STREQN (varname, hint, hint_len))
1653 return (savestring (varname));
1658 case 3: /* Then shell builtins. */
1659 for (; local_index < num_shell_builtins; local_index++)
1661 /* Ignore it if it doesn't have a function pointer or if it
1662 is not currently enabled. */
1663 if (!shell_builtins[local_index].function ||
1664 (shell_builtins[local_index].flags & BUILTIN_ENABLED) == 0)
1667 if (STREQN (shell_builtins[local_index].name, hint, hint_len))
1669 int i = local_index++;
1671 return (savestring (shell_builtins[i].name));
1679 /* Limited support for completing command words with globbing chars. Only
1680 a single match (multiple matches that end up reducing the number of
1681 characters in the common prefix are bad) will ever be returned on
1682 regular completion. */
1683 if (glob_pattern_p (hint))
1687 glob_ignore_case = igncase;
1688 glob_matches = shell_glob_filename (hint);
1689 glob_ignore_case = old_glob_ignore_case;
1691 if (GLOB_FAILED (glob_matches) || glob_matches == 0)
1693 glob_matches = (char **)NULL;
1694 return ((char *)NULL);
1699 if (glob_matches[1] && rl_completion_type == TAB) /* multiple matches are bad */
1700 return ((char *)NULL);
1703 while (val = glob_matches[local_index++])
1705 if (executable_or_directory (val))
1707 if (*hint_text == '~')
1709 temp = restore_tilde (val, directory_part);
1718 glob_ignore_case = old_glob_ignore_case;
1719 return ((char *)NULL);
1722 /* If the text passed is a directory in the current directory, return it
1723 as a possible match. Executables in directories in the current
1724 directory can be specified using relative pathnames and successfully
1725 executed even when `.' is not in $PATH. */
1728 hint_is_dir = 0; /* only return the hint text once */
1729 return (savestring (hint_text));
1732 /* Repeatedly call filename_completion_function while we have
1733 members of PATH left. Question: should we stat each file?
1734 Answer: we call executable_file () on each file. */
1737 istate = (val != (char *)NULL);
1743 /* Get the next directory from the path. If there is none, then we
1745 if (path == 0 || path[path_index] == 0 ||
1746 (current_path = extract_colon_unit (path, &path_index)) == 0)
1747 return ((char *)NULL);
1750 if (*current_path == 0)
1752 free (current_path);
1753 current_path = savestring (".");
1756 if (*current_path == '~')
1760 t = bash_tilde_expand (current_path, 0);
1761 free (current_path);
1765 if (current_path[0] == '.' && current_path[1] == '\0')
1769 free (filename_hint);
1771 filename_hint = sh_makepath (current_path, hint, 0);
1772 free (current_path); /* XXX */
1776 val = rl_filename_completion_function (filename_hint, istate);
1781 /* If the hint text is an absolute program, then don't bother
1782 searching through PATH. */
1783 if (absolute_program (hint))
1784 return ((char *)NULL);
1790 int match, freetemp;
1792 if (absolute_program (hint))
1795 match = strncmp (val, hint, hint_len) == 0;
1797 match = strncasecmp (val, hint, hint_len) == 0;
1799 /* If we performed tilde expansion, restore the original
1801 if (*hint_text == '~')
1802 temp = restore_tilde (val, directory_part);
1804 temp = savestring (val);
1809 temp = strrchr (val, '/');
1815 freetemp = match = strncmp (temp, hint, hint_len) == 0;
1817 freetemp = match = strncasecmp (temp, hint, hint_len) == 0;
1819 temp = savestring (temp);
1822 freetemp = match = 0;
1826 /* If we have found a match, and it is an executable file or a
1827 directory name, return it. */
1828 if (match && executable_or_directory (val))
1830 /* If we have found a match, and it is an executable file, return it.
1831 We don't return directory names when searching $PATH, since the
1832 bash execution code won't find executables in directories which
1833 appear in directories in $PATH when they're specified using
1834 relative pathnames. */
1835 if (match && (searching_path ? executable_file (val) : executable_or_directory (val)))
1839 val = ""; /* So it won't be NULL. */
1852 /* Completion inside an unterminated command substitution. */
1854 command_subst_completion_function (text, state)
1858 static char **matches = (char **)NULL;
1859 static const char *orig_start;
1860 static char *filename_text = (char *)NULL;
1861 static int cmd_index, start_len;
1867 free (filename_text);
1871 else if (*text == '$' && text[1] == '(') /* ) */
1873 /* If the text was quoted, suppress any quote character that the
1874 readline completion code would insert. */
1875 rl_completion_suppress_quote = 1;
1876 start_len = text - orig_start;
1877 filename_text = savestring (text);
1882 * At this point we can entertain the idea of re-parsing
1883 * `filename_text' into a (possibly incomplete) command name and
1884 * arguments, and doing completion based on that. This is
1885 * currently very rudimentary, but it is a small improvement.
1887 for (value = filename_text + strlen (filename_text) - 1; value > filename_text; value--)
1888 if (whitespace (*value) || member (*value, COMMAND_SEPARATORS))
1890 if (value <= filename_text)
1891 matches = rl_completion_matches (filename_text, command_word_completion_function);
1895 start_len += value - filename_text;
1896 if (whitespace (value[-1]))
1897 matches = rl_completion_matches (value, rl_filename_completion_function);
1899 matches = rl_completion_matches (value, command_word_completion_function);
1902 /* If there is more than one match, rl_completion_matches has already
1903 put the lcd in matches[0]. Skip over it. */
1904 cmd_index = matches && matches[0] && matches[1];
1906 /* If there's a single match and it's a directory, set the append char
1907 to the expected `/'. Otherwise, don't append anything. */
1908 if (matches && matches[0] && matches[1] == 0 && test_for_directory (matches[0]))
1909 rl_completion_append_character = '/';
1911 rl_completion_suppress_append = 1;
1914 if (!matches || !matches[cmd_index])
1916 rl_filename_quoting_desired = 0; /* disable quoting */
1917 return ((char *)NULL);
1921 value = (char *)xmalloc (1 + start_len + strlen (matches[cmd_index]));
1924 value[0] = *orig_start;
1926 strncpy (value, orig_start, start_len);
1928 strcpy (value + start_len, matches[cmd_index]);
1935 /* Okay, now we write the entry_function for variable completion. */
1937 variable_completion_function (text, state)
1941 static char **varlist = (char **)NULL;
1942 static int varlist_index;
1943 static char *varname = (char *)NULL;
1945 static int first_char, first_char_loc;
1953 first_char = text[0];
1955 if (first_char == '$')
1958 if (text[first_char_loc] == '{')
1961 varname = savestring (text + first_char_loc);
1963 namelen = strlen (varname);
1965 strvec_dispose (varlist);
1967 varlist = all_variables_matching_prefix (varname);
1971 if (!varlist || !varlist[varlist_index])
1973 return ((char *)NULL);
1979 value = (char *)xmalloc (4 + strlen (varlist[varlist_index]));
1983 value[0] = first_char;
1984 if (first_char_loc == 2)
1988 strcpy (value + first_char_loc, varlist[varlist_index]);
1989 if (first_char_loc == 2)
1990 strcat (value, "}");
1997 /* How about a completion function for hostnames? */
1999 hostname_completion_function (text, state)
2003 static char **list = (char **)NULL;
2004 static int list_index = 0;
2005 static int first_char, first_char_loc;
2007 /* If we don't have any state, make some. */
2012 list = (char **)NULL;
2017 if (first_char == '@')
2020 list = hostnames_matching ((char *)text+first_char_loc);
2024 if (list && list[list_index])
2028 t = (char *)xmalloc (2 + strlen (list[list_index]));
2030 strcpy (t + first_char_loc, list[list_index]);
2035 return ((char *)NULL);
2039 * A completion function for service names from /etc/services (or wherever).
2042 bash_servicename_completion_function (text, state)
2046 #if defined (__WIN32__) || defined (__OPENNT) || !defined (HAVE_GETSERVENT)
2047 return ((char *)NULL);
2049 static char *sname = (char *)NULL;
2050 static struct servent *srvent;
2051 static int snamelen, firstc;
2053 char **alist, *aentry;
2061 sname = savestring (text);
2062 snamelen = strlen (sname);
2066 while (srvent = getservent ())
2069 if (snamelen == 0 || (STREQN (sname, srvent->s_name, snamelen)))
2071 /* Not primary, check aliases */
2072 for (alist = srvent->s_aliases; *alist; alist++)
2075 if (STREQN (sname, aentry, snamelen))
2089 return ((char *)NULL);
2092 value = afound ? savestring (aentry) : savestring (srvent->s_name);
2098 * A completion function for group names from /etc/group (or wherever).
2101 bash_groupname_completion_function (text, state)
2105 #if defined (__WIN32__) || defined (__OPENNT) || !defined (HAVE_GRP_H)
2106 return ((char *)NULL);
2108 static char *gname = (char *)NULL;
2109 static struct group *grent;
2110 static int gnamelen;
2116 gname = savestring (text);
2117 gnamelen = strlen (gname);
2122 while (grent = getgrent ())
2124 if (gnamelen == 0 || (STREQN (gname, grent->gr_name, gnamelen)))
2131 return ((char *)NULL);
2134 value = savestring (grent->gr_name);
2139 /* Functions to perform history and alias expansions on the current line. */
2141 #if defined (BANG_HISTORY)
2142 /* Perform history expansion on the current line. If no history expansion
2143 is done, pre_process_line() returns what it was passed, so we need to
2144 allocate a new line here. */
2146 history_expand_line_internal (line)
2152 old_verify = hist_verify;
2154 new_line = pre_process_line (line, 0, 0);
2155 hist_verify = old_verify;
2157 return (new_line == line) ? savestring (line) : new_line;
2161 /* There was an error in expansion. Let the preprocessor print
2164 cleanup_expansion_error ()
2167 #if defined (BANG_HISTORY)
2170 old_verify = hist_verify;
2174 fprintf (rl_outstream, "\r\n");
2175 to_free = pre_process_line (rl_line_buffer, 1, 0);
2176 #if defined (BANG_HISTORY)
2177 hist_verify = old_verify;
2179 if (to_free != rl_line_buffer)
2181 putc ('\r', rl_outstream);
2182 rl_forced_update_display ();
2185 /* If NEW_LINE differs from what is in the readline line buffer, add an
2186 undo record to get from the readline line buffer contents to the new
2187 line and make NEW_LINE the current readline line. */
2189 maybe_make_readline_line (new_line)
2192 if (strcmp (new_line, rl_line_buffer) != 0)
2196 rl_add_undo (UNDO_BEGIN, 0, 0, 0);
2197 rl_delete_text (0, rl_point);
2198 rl_point = rl_end = rl_mark = 0;
2199 rl_insert_text (new_line);
2200 rl_add_undo (UNDO_END, 0, 0, 0);
2204 /* Make NEW_LINE be the current readline line. This frees NEW_LINE. */
2206 set_up_new_line (new_line)
2209 int old_point, at_end;
2211 old_point = rl_point;
2212 at_end = rl_point == rl_end;
2214 /* If the line was history and alias expanded, then make that
2215 be one thing to undo. */
2216 maybe_make_readline_line (new_line);
2219 /* Place rl_point where we think it should go. */
2222 else if (old_point < rl_end)
2224 rl_point = old_point;
2225 if (!whitespace (rl_line_buffer[rl_point]))
2226 rl_forward_word (1, 0);
2231 /* Expand aliases in the current readline line. */
2233 alias_expand_line (count, ignore)
2238 new_line = alias_expand (rl_line_buffer);
2242 set_up_new_line (new_line);
2247 cleanup_expansion_error ();
2253 #if defined (BANG_HISTORY)
2254 /* History expand the line. */
2256 history_expand_line (count, ignore)
2261 new_line = history_expand_line_internal (rl_line_buffer);
2265 set_up_new_line (new_line);
2270 cleanup_expansion_error ();
2275 /* Expand history substitutions in the current line and then insert a
2276 space (hopefully close to where we were before). */
2278 tcsh_magic_space (count, ignore)
2281 int dist_from_end, old_point;
2283 old_point = rl_point;
2284 dist_from_end = rl_end - rl_point;
2285 if (history_expand_line (count, ignore) == 0)
2287 /* Try a simple heuristic from Stephen Gildea <gildea@intouchsys.com>.
2288 This works if all expansions were before rl_point or if no expansions
2290 rl_point = (old_point == 0) ? old_point : rl_end - dist_from_end;
2297 #endif /* BANG_HISTORY */
2299 /* History and alias expand the line. */
2301 history_and_alias_expand_line (count, ignore)
2307 #if defined (BANG_HISTORY)
2308 new_line = history_expand_line_internal (rl_line_buffer);
2316 alias_line = alias_expand (new_line);
2318 new_line = alias_line;
2324 set_up_new_line (new_line);
2329 cleanup_expansion_error ();
2334 /* History and alias expand the line, then perform the shell word
2335 expansions by calling expand_string. This can't use set_up_new_line()
2336 because we want the variable expansions as a separate undo'able
2337 set of operations. */
2339 shell_expand_line (count, ignore)
2343 WORD_LIST *expanded_string;
2346 #if defined (BANG_HISTORY)
2347 new_line = history_expand_line_internal (rl_line_buffer);
2355 alias_line = alias_expand (new_line);
2357 new_line = alias_line;
2363 int old_point = rl_point;
2364 int at_end = rl_point == rl_end;
2366 /* If the line was history and alias expanded, then make that
2367 be one thing to undo. */
2368 maybe_make_readline_line (new_line);
2371 /* If there is variable expansion to perform, do that as a separate
2372 operation to be undone. */
2373 new_line = savestring (rl_line_buffer);
2374 expanded_string = expand_string (new_line, 0);
2376 if (expanded_string == 0)
2378 new_line = (char *)xmalloc (1);
2383 new_line = string_list (expanded_string);
2384 dispose_words (expanded_string);
2387 maybe_make_readline_line (new_line);
2390 /* Place rl_point where we think it should go. */
2393 else if (old_point < rl_end)
2395 rl_point = old_point;
2396 if (!whitespace (rl_line_buffer[rl_point]))
2397 rl_forward_word (1, 0);
2403 cleanup_expansion_error ();
2408 /* If FIGNORE is set, then don't match files with the given suffixes when
2409 completing filenames. If only one of the possibilities has an acceptable
2410 suffix, delete the others, else just return and let the completer
2411 signal an error. It is called by the completer when real
2412 completions are done on filenames by the completer's internal
2413 function, not for completion lists (M-?) and not on "other"
2414 completion types, such as hostnames or commands. */
2416 static struct ignorevar fignore =
2422 (sh_iv_item_func_t *) 0,
2426 _ignore_completion_names (names, name_func)
2428 sh_ignore_func_t *name_func;
2435 /* If there is only one completion, see if it is acceptable. If it is
2436 not, free it up. In any case, short-circuit and return. This is a
2437 special case because names[0] is not the prefix of the list of names
2438 if there is only one completion; it is the completion itself. */
2439 if (names[1] == (char *)0)
2442 if ((*name_func) (names[0]) == 0)
2445 names[0] = (char *)NULL;
2451 /* Allocate space for array to hold list of pointers to matching
2452 filenames. The pointers are copied back to NAMES when done. */
2453 for (nidx = 1; names[nidx]; nidx++)
2455 newnames = strvec_create (nidx + 1);
2457 if (force_fignore == 0)
2459 oldnames = strvec_create (nidx - 1);
2463 newnames[0] = names[0];
2464 for (idx = nidx = 1; names[idx]; idx++)
2466 if ((*name_func) (names[idx]))
2467 newnames[nidx++] = names[idx];
2468 else if (force_fignore == 0)
2469 oldnames[oidx++] = names[idx];
2474 newnames[nidx] = (char *)NULL;
2476 /* If none are acceptable then let the completer handle it. */
2482 names[0] = (char *)NULL;
2491 if (force_fignore == 0)
2494 free (oldnames[--oidx]);
2498 /* If only one is acceptable, copy it to names[0] and return. */
2502 names[0] = newnames[1];
2503 names[1] = (char *)NULL;
2508 /* Copy the acceptable names back to NAMES, set the new array end,
2510 for (nidx = 1; newnames[nidx]; nidx++)
2511 names[nidx] = newnames[nidx];
2512 names[nidx] = (char *)NULL;
2517 name_is_acceptable (name)
2523 for (nlen = strlen (name), p = fignore.ignores; p->val; p++)
2525 if (nlen > p->len && p->len > 0 && STREQ (p->val, &name[nlen - p->len]))
2534 ignore_dot_names (name)
2537 return (name[0] != '.');
2542 filename_completion_ignore (names)
2546 if (glob_dot_filenames == 0)
2547 _ignore_completion_names (names, ignore_dot_names);
2550 setup_ignore_patterns (&fignore);
2552 if (fignore.num_ignores == 0)
2555 _ignore_completion_names (names, name_is_acceptable);
2560 /* Return 1 if NAME is a directory. NAME undergoes tilde expansion. */
2562 test_for_directory (name)
2568 fn = bash_tilde_expand (name, 0);
2569 r = file_isdir (fn);
2575 /* Remove files from NAMES, leaving directories. */
2577 bash_ignore_filenames (names)
2580 _ignore_completion_names (names, test_for_directory);
2592 bash_ignore_everything (names)
2595 _ignore_completion_names (names, return_zero);
2599 /* Replace a tilde-prefix in VAL with a `~', assuming the user typed it. VAL
2600 is an expanded filename. DIRECTORY_PART is the tilde-prefix portion
2601 of the un-tilde-expanded version of VAL (what the user typed). */
2603 restore_tilde (val, directory_part)
2604 char *val, *directory_part;
2607 char *dh2, *expdir, *ret;
2611 /* We need to duplicate the expansions readline performs on the directory
2612 portion before passing it to our completion function. */
2613 dh2 = directory_part ? bash_dequote_filename (directory_part, 0) : 0;
2614 bash_directory_expansion (&dh2);
2617 expdir = bash_tilde_expand (directory_part, 0);
2618 xl = strlen (expdir);
2622 dh2 = unexpanded but dequoted tilde-prefix
2623 dl2 = length of tilde-prefix
2624 expdir = tilde-expanded tilde-prefix
2625 xl = length of expanded tilde-prefix
2626 l = length of remainder after tilde-prefix
2630 ret = (char *)xmalloc (dl2 + 2 + l);
2632 strcpy (ret + dl2, val + xl);
2638 /* Simulate the expansions that will be performed by
2639 rl_filename_completion_function. This must be called with the address of
2640 a pointer to malloc'd memory. */
2642 bash_directory_expansion (dirname)
2647 d = savestring (*dirname);
2649 if (rl_directory_rewrite_hook)
2650 (*rl_directory_rewrite_hook) (&d);
2652 if (rl_directory_completion_hook && (*rl_directory_completion_hook) (&d))
2657 else if (rl_completion_found_quote)
2659 nd = bash_dequote_filename (d, rl_completion_quote_character);
2666 /* If necessary, rewrite directory entry */
2668 bash_filename_rewrite_hook (fname, fnlen)
2674 conv = fnx_fromfs (fname, fnlen);
2676 conv = savestring (conv);
2680 /* Handle symbolic link references and other directory name
2681 expansions while hacking completion. */
2683 bash_directory_completion_hook (dirname)
2686 char *local_dirname, *new_dirname, *t;
2687 int return_value, should_expand_dirname;
2691 return_value = should_expand_dirname = 0;
2692 local_dirname = *dirname;
2694 if (mbschr (local_dirname, '$'))
2695 should_expand_dirname = 1;
2698 t = mbschr (local_dirname, '`');
2699 if (t && unclosed_pair (local_dirname, strlen (local_dirname), "`") == 0)
2700 should_expand_dirname = 1;
2703 #if defined (HAVE_LSTAT)
2704 if (should_expand_dirname && lstat (local_dirname, &sb) == 0)
2706 if (should_expand_dirname && stat (local_dirname, &sb) == 0)
2708 should_expand_dirname = 0;
2710 if (should_expand_dirname)
2712 new_dirname = savestring (local_dirname);
2713 wl = expand_prompt_string (new_dirname, 0, W_NOCOMSUB); /* does the right thing */
2716 *dirname = string_list (wl);
2717 /* Tell the completer to replace the directory name only if we
2718 actually expanded something. */
2719 return_value = STREQ (local_dirname, *dirname) == 0;
2720 free (local_dirname);
2723 local_dirname = *dirname;
2728 free (local_dirname);
2729 *dirname = (char *)xmalloc (1);
2736 /* Dequote the filename even if we don't expand it. */
2737 new_dirname = bash_dequote_filename (local_dirname, rl_completion_quote_character);
2738 free (local_dirname);
2739 local_dirname = *dirname = new_dirname;
2742 if (no_symbolic_links == 0 && (local_dirname[0] != '.' || local_dirname[1]))
2744 char *temp1, *temp2;
2747 t = get_working_directory ("symlink-hook");
2748 temp1 = make_absolute (local_dirname, t);
2750 temp2 = sh_canonpath (temp1, PATH_CHECKDOTDOT|PATH_CHECKEXISTS);
2752 /* Try spelling correction if initial canonicalization fails. */
2753 if (temp2 == 0 && dircomplete_spelling)
2755 temp2 = dirspell (temp1);
2760 temp2 = sh_canonpath (temp1, PATH_CHECKDOTDOT|PATH_CHECKEXISTS);
2761 return_value = temp2 != 0;
2764 /* If we can't canonicalize, bail. */
2770 len1 = strlen (temp1);
2771 if (temp1[len1 - 1] == '/')
2773 len2 = strlen (temp2);
2774 if (len2 > 2) /* don't append `/' to `/' or `//' */
2776 temp2 = (char *)xrealloc (temp2, len2 + 2);
2778 temp2[len2 + 1] = '\0';
2781 free (local_dirname);
2785 return (return_value);
2788 static char **history_completion_array = (char **)NULL;
2789 static int harry_size;
2790 static int harry_len;
2793 build_history_completion_array ()
2799 /* First, clear out the current dynamic history completion list. */
2802 strvec_dispose (history_completion_array);
2803 history_completion_array = (char **)NULL;
2808 /* Next, grovel each line of history, making each shell-sized token
2809 a separate entry in the history_completion_array. */
2810 hlist = history_list ();
2814 for (i = 0; hlist[i]; i++)
2816 for ( --i; i >= 0; i--)
2818 /* Separate each token, and place into an array. */
2819 tokens = history_tokenize (hlist[i]->line);
2821 for (j = 0; tokens && tokens[j]; j++)
2823 if (harry_len + 2 > harry_size)
2824 history_completion_array = strvec_resize (history_completion_array, harry_size += 10);
2826 history_completion_array[harry_len++] = tokens[j];
2827 history_completion_array[harry_len] = (char *)NULL;
2832 /* Sort the complete list of tokens. */
2833 if (dabbrev_expand_active == 0)
2834 qsort (history_completion_array, harry_len, sizeof (char *), (QSFUNC *)strvec_strcmp);
2839 history_completion_generator (hint_text, state)
2840 const char *hint_text;
2843 static int local_index, len;
2844 static const char *text;
2846 /* If this is the first call to the generator, then initialize the
2847 list of strings to complete over. */
2850 if (dabbrev_expand_active) /* This is kind of messy */
2851 rl_completion_suppress_append = 1;
2853 build_history_completion_array ();
2855 len = strlen (text);
2858 while (history_completion_array && history_completion_array[local_index])
2860 if (strncmp (text, history_completion_array[local_index++], len) == 0)
2861 return (savestring (history_completion_array[local_index - 1]));
2863 return ((char *)NULL);
2867 dynamic_complete_history (count, key)
2871 rl_compentry_func_t *orig_func;
2872 rl_completion_func_t *orig_attempt_func;
2874 orig_func = rl_completion_entry_function;
2875 orig_attempt_func = rl_attempted_completion_function;
2877 rl_completion_entry_function = history_completion_generator;
2878 rl_attempted_completion_function = (rl_completion_func_t *)NULL;
2880 /* XXX - use rl_completion_mode here? */
2881 if (rl_last_func == dynamic_complete_history)
2882 r = rl_complete_internal ('?');
2884 r = rl_complete_internal (TAB);
2886 rl_completion_entry_function = orig_func;
2887 rl_attempted_completion_function = orig_attempt_func;
2892 bash_dabbrev_expand (count, key)
2895 int r, orig_suppress, orig_sort;
2896 rl_compentry_func_t *orig_func;
2897 rl_completion_func_t *orig_attempt_func;
2899 orig_func = rl_menu_completion_entry_function;
2900 orig_attempt_func = rl_attempted_completion_function;
2901 orig_suppress = rl_completion_suppress_append;
2902 orig_sort = rl_sort_completion_matches;
2904 rl_menu_completion_entry_function = history_completion_generator;
2905 rl_attempted_completion_function = (rl_completion_func_t *)NULL;
2906 rl_filename_completion_desired = 0;
2907 rl_completion_suppress_append = 1;
2908 rl_sort_completion_matches = 0;
2910 /* XXX - use rl_completion_mode here? */
2911 dabbrev_expand_active = 1;
2912 if (rl_last_func == bash_dabbrev_expand)
2913 rl_last_func = rl_menu_complete;
2914 r = rl_menu_complete (count, key);
2915 dabbrev_expand_active = 0;
2917 rl_last_func = bash_dabbrev_expand;
2918 rl_menu_completion_entry_function = orig_func;
2919 rl_attempted_completion_function = orig_attempt_func;
2920 rl_completion_suppress_append = orig_suppress;
2921 rl_sort_completion_matches = orig_sort;
2926 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
2928 bash_complete_username (ignore, ignore2)
2929 int ignore, ignore2;
2931 return bash_complete_username_internal (rl_completion_mode (bash_complete_username));
2935 bash_possible_username_completions (ignore, ignore2)
2936 int ignore, ignore2;
2938 return bash_complete_username_internal ('?');
2942 bash_complete_username_internal (what_to_do)
2945 return bash_specific_completion (what_to_do, rl_username_completion_function);
2949 bash_complete_filename (ignore, ignore2)
2950 int ignore, ignore2;
2952 return bash_complete_filename_internal (rl_completion_mode (bash_complete_filename));
2956 bash_possible_filename_completions (ignore, ignore2)
2957 int ignore, ignore2;
2959 return bash_complete_filename_internal ('?');
2963 bash_complete_filename_internal (what_to_do)
2966 rl_compentry_func_t *orig_func;
2967 rl_completion_func_t *orig_attempt_func;
2968 rl_icppfunc_t *orig_dir_func;
2969 /*const*/ char *orig_rl_completer_word_break_characters;
2972 orig_func = rl_completion_entry_function;
2973 orig_attempt_func = rl_attempted_completion_function;
2974 orig_dir_func = rl_directory_completion_hook;
2975 orig_rl_completer_word_break_characters = rl_completer_word_break_characters;
2976 rl_completion_entry_function = rl_filename_completion_function;
2977 rl_attempted_completion_function = (rl_completion_func_t *)NULL;
2978 rl_directory_completion_hook = (rl_icppfunc_t *)NULL;
2979 rl_completer_word_break_characters = " \t\n\"\'";
2981 r = rl_complete_internal (what_to_do);
2983 rl_completion_entry_function = orig_func;
2984 rl_attempted_completion_function = orig_attempt_func;
2985 rl_directory_completion_hook = orig_dir_func;
2986 rl_completer_word_break_characters = orig_rl_completer_word_break_characters;
2992 bash_complete_hostname (ignore, ignore2)
2993 int ignore, ignore2;
2995 return bash_complete_hostname_internal (rl_completion_mode (bash_complete_hostname));
2999 bash_possible_hostname_completions (ignore, ignore2)
3000 int ignore, ignore2;
3002 return bash_complete_hostname_internal ('?');
3006 bash_complete_variable (ignore, ignore2)
3007 int ignore, ignore2;
3009 return bash_complete_variable_internal (rl_completion_mode (bash_complete_variable));
3013 bash_possible_variable_completions (ignore, ignore2)
3014 int ignore, ignore2;
3016 return bash_complete_variable_internal ('?');
3020 bash_complete_command (ignore, ignore2)
3021 int ignore, ignore2;
3023 return bash_complete_command_internal (rl_completion_mode (bash_complete_command));
3027 bash_possible_command_completions (ignore, ignore2)
3028 int ignore, ignore2;
3030 return bash_complete_command_internal ('?');
3034 bash_complete_hostname_internal (what_to_do)
3037 return bash_specific_completion (what_to_do, hostname_completion_function);
3041 bash_complete_variable_internal (what_to_do)
3044 return bash_specific_completion (what_to_do, variable_completion_function);
3048 bash_complete_command_internal (what_to_do)
3051 return bash_specific_completion (what_to_do, command_word_completion_function);
3054 static char *globtext;
3055 static char *globorig;
3058 glob_complete_word (text, state)
3062 static char **matches = (char **)NULL;
3069 rl_filename_completion_desired = 1;
3071 if (globorig != globtext)
3075 ttext = bash_tilde_expand (text, 0);
3077 if (rl_explicit_arg)
3079 globorig = savestring (ttext);
3080 glen = strlen (ttext);
3081 globtext = (char *)xmalloc (glen + 2);
3082 strcpy (globtext, ttext);
3083 globtext[glen] = '*';
3084 globtext[glen+1] = '\0';
3087 globtext = globorig = savestring (ttext);
3092 matches = shell_glob_filename (globtext);
3093 if (GLOB_FAILED (matches))
3094 matches = (char **)NULL;
3098 ret = matches ? matches[ind] : (char *)NULL;
3104 bash_glob_completion_internal (what_to_do)
3107 return bash_specific_completion (what_to_do, glob_complete_word);
3110 /* A special quoting function so we don't end up quoting globbing characters
3111 in the word if there are no matches or multiple matches. */
3113 bash_glob_quote_filename (s, rtype, qcp)
3118 if (globorig && qcp && *qcp == '\0' && STREQ (s, globorig))
3119 return (savestring (s));
3121 return (bash_quote_filename (s, rtype, qcp));
3125 bash_glob_complete_word (count, key)
3129 rl_quote_func_t *orig_quoting_function;
3131 if (rl_editing_mode == EMACS_EDITING_MODE)
3132 rl_explicit_arg = 1; /* force `*' append */
3133 orig_quoting_function = rl_filename_quoting_function;
3134 rl_filename_quoting_function = bash_glob_quote_filename;
3136 r = bash_glob_completion_internal (rl_completion_mode (bash_glob_complete_word));
3138 rl_filename_quoting_function = orig_quoting_function;
3143 bash_glob_expand_word (count, key)
3146 return bash_glob_completion_internal ('*');
3150 bash_glob_list_expansions (count, key)
3153 return bash_glob_completion_internal ('?');
3157 bash_specific_completion (what_to_do, generator)
3159 rl_compentry_func_t *generator;
3161 rl_compentry_func_t *orig_func;
3162 rl_completion_func_t *orig_attempt_func;
3165 orig_func = rl_completion_entry_function;
3166 orig_attempt_func = rl_attempted_completion_function;
3167 rl_completion_entry_function = generator;
3168 rl_attempted_completion_function = NULL;
3170 r = rl_complete_internal (what_to_do);
3172 rl_completion_entry_function = orig_func;
3173 rl_attempted_completion_function = orig_attempt_func;
3178 #endif /* SPECIFIC_COMPLETION_FUNCTIONS */
3180 #if defined (VI_MODE)
3181 /* Completion, from vi mode's point of view. This is a modified version of
3182 rl_vi_complete which uses the bash globbing code to implement what POSIX
3183 specifies, which is to append a `*' and attempt filename generation (which
3184 has the side effect of expanding any globbing characters in the word). */
3186 bash_vi_complete (count, key)
3189 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
3193 if ((rl_point < rl_end) && (!whitespace (rl_line_buffer[rl_point])))
3195 if (!whitespace (rl_line_buffer[rl_point + 1]))
3196 rl_vi_end_word (1, 'E');
3200 /* Find boundaries of current word, according to vi definition of a
3206 rl_vi_bWord (1, 'B');
3211 t = substring (rl_line_buffer, p, rl_point);
3214 if (t && glob_pattern_p (t) == 0)
3215 rl_explicit_arg = 1; /* XXX - force glob_complete_word to append `*' */
3218 if (key == '*') /* Expansion and replacement. */
3219 r = bash_glob_expand_word (count, key);
3220 else if (key == '=') /* List possible completions. */
3221 r = bash_glob_list_expansions (count, key);
3222 else if (key == '\\') /* Standard completion */
3223 r = bash_glob_complete_word (count, key);
3225 r = rl_complete (0, key);
3227 if (key == '*' || key == '\\')
3228 rl_vi_start_inserting (key, 1, 1);
3232 return rl_vi_complete (count, key);
3233 #endif /* !SPECIFIC_COMPLETION_FUNCTIONS */
3235 #endif /* VI_MODE */
3237 /* Filename quoting for completion. */
3238 /* A function to strip unquoted quote characters (single quotes, double
3239 quotes, and backslashes). It allows single quotes to appear
3240 within double quotes, and vice versa. It should be smarter. */
3242 bash_dequote_filename (text, quote_char)
3250 ret = (char *)xmalloc (l + 1);
3251 for (quoted = quote_char, p = text, r = ret; p && *p; p++)
3253 /* Allow backslash-escaped characters to pass through unscathed. */
3256 /* Backslashes are preserved within single quotes. */
3259 /* Backslashes are preserved within double quotes unless the
3260 character is one that is defined to be escaped */
3261 else if (quoted == '"' && ((sh_syntaxtab[p[1]] & CBSDQUOTE) == 0))
3266 return ret; /* XXX - was break; */
3270 if (quoted && *p == quoted)
3276 if (quoted == 0 && (*p == '\'' || *p == '"'))
3287 /* Quote characters that the readline completion code would treat as
3288 word break characters with backslashes. Pass backslash-quoted
3289 characters through without examination. */
3291 quote_word_break_chars (text)
3298 ret = (char *)xmalloc ((2 * l) + 1);
3299 for (s = text, r = ret; *s; s++)
3301 /* Pass backslash-quoted characters through, including the backslash. */
3310 /* OK, we have an unquoted character. Check its presence in
3311 rl_completer_word_break_characters. */
3312 if (mbschr (rl_completer_word_break_characters, *s))
3314 /* XXX -- check for standalone tildes here and backslash-quote them */
3315 if (s == text && *s == '~' && file_exists (text))
3323 /* Quote a filename using double quotes, single quotes, or backslashes
3324 depending on the value of completion_quoting_style. If we're
3325 completing using backslashes, we need to quote some additional
3326 characters (those that readline treats as word breaks), so we call
3327 quote_word_break_chars on the result. This returns newly-allocated
3330 bash_quote_filename (s, rtype, qcp)
3335 char *rtext, *mtext, *ret;
3338 rtext = (char *)NULL;
3340 /* If RTYPE == MULT_MATCH, it means that there is
3341 more than one match. In this case, we do not add
3342 the closing quote or attempt to perform tilde
3343 expansion. If RTYPE == SINGLE_MATCH, we try
3344 to perform tilde expansion, because single and double
3345 quotes inhibit tilde expansion by the shell. */
3347 cs = completion_quoting_style;
3348 /* Might need to modify the default completion style based on *qcp,
3349 since it's set to any user-provided opening quote. We also change
3350 to single-quoting if there is no user-provided opening quote and
3351 the word being completed contains newlines, since those are not
3352 quoted correctly using backslashes (a backslash-newline pair is
3353 special to the shell parser). */
3354 if (*qcp == '\0' && cs == COMPLETE_BSQUOTE && mbschr (s, '\n'))
3355 cs = COMPLETE_SQUOTE;
3356 else if (*qcp == '"')
3357 cs = COMPLETE_DQUOTE;
3358 else if (*qcp == '\'')
3359 cs = COMPLETE_SQUOTE;
3360 #if defined (BANG_HISTORY)
3361 else if (*qcp == '\0' && history_expansion && cs == COMPLETE_DQUOTE &&
3362 history_expansion_inhibited == 0 && mbschr (s, '!'))
3363 cs = COMPLETE_BSQUOTE;
3365 if (*qcp == '"' && history_expansion && cs == COMPLETE_DQUOTE &&
3366 history_expansion_inhibited == 0 && mbschr (s, '!'))
3368 cs = COMPLETE_BSQUOTE;
3373 /* Don't tilde-expand backslash-quoted filenames, since only single and
3374 double quotes inhibit tilde expansion. */
3376 if (mtext[0] == '~' && rtype == SINGLE_MATCH && cs != COMPLETE_BSQUOTE)
3377 mtext = bash_tilde_expand (s, 0);
3381 case COMPLETE_DQUOTE:
3382 rtext = sh_double_quote (mtext);
3384 case COMPLETE_SQUOTE:
3385 rtext = sh_single_quote (mtext);
3387 case COMPLETE_BSQUOTE:
3388 rtext = sh_backslash_quote (mtext);
3395 /* We may need to quote additional characters: those that readline treats
3396 as word breaks that are not quoted by backslash_quote. */
3397 if (rtext && cs == COMPLETE_BSQUOTE)
3399 mtext = quote_word_break_chars (rtext);
3404 /* Leave the opening quote intact. The readline completion code takes
3405 care of avoiding doubled opening quotes. */
3406 rlen = strlen (rtext);
3407 ret = (char *)xmalloc (rlen + 1);
3408 strcpy (ret, rtext);
3410 /* If there are multiple matches, cut off the closing quote. */
3411 if (rtype == MULT_MATCH && cs != COMPLETE_BSQUOTE)
3412 ret[rlen - 1] = '\0';
3417 /* Support for binding readline key sequences to Unix commands. */
3418 static Keymap cmd_xmap;
3424 putc (c, rl_outstream);
3428 bash_execute_unix_command (count, key)
3429 int count; /* ignored */
3432 Keymap ckmap; /* current keymap */
3433 Keymap xkmap; /* unix command executing keymap */
3436 sh_parser_state_t ps;
3437 char *cmd, *value, *l, *l1, *ce;
3439 char ibuf[INT_STRLEN_BOUND(int) + 1];
3441 /* First, we need to find the right command to execute. This is tricky,
3442 because we might have already indirected into another keymap. */
3443 ckmap = rl_get_keymap ();
3444 if (ckmap != rl_executing_keymap)
3446 /* bogus. we have to search. only handle one level of indirection. */
3447 for (i = 0; i < KEYMAP_SIZE; i++)
3449 if (ckmap[i].type == ISKMAP && (Keymap)ckmap[i].function == rl_executing_keymap)
3452 if (i < KEYMAP_SIZE)
3453 xkmap = (Keymap)cmd_xmap[i].function;
3457 internal_error (_("bash_execute_unix_command: cannot find keymap for command"));
3458 rl_forced_update_display ();
3465 cmd = (char *)xkmap[key].function;
3473 ce = rl_get_termcap ("ce");
3474 if (ce) /* clear current line */
3476 fprintf (rl_outstream, "\r");
3477 tputs (ce, 1, putx);
3478 fflush (rl_outstream);
3481 rl_crlf (); /* move to a new line */
3483 v = bind_variable ("READLINE_LINE", rl_line_buffer, 0);
3485 VSETATTR (v, att_exported);
3486 l = v ? value_cell (v) : 0;
3487 value = inttostr (rl_point, ibuf, sizeof (ibuf));
3488 v = bind_int_variable ("READLINE_POINT", value);
3490 VSETATTR (v, att_exported);
3491 array_needs_making = 1;
3493 save_parser_state (&ps);
3494 r = parse_and_execute (cmd, "bash_execute_unix_command", SEVAL_NOHIST|SEVAL_NOFREE);
3495 restore_parser_state (&ps);
3497 v = find_variable ("READLINE_LINE");
3498 l1 = v ? value_cell (v) : 0;
3500 maybe_make_readline_line (value_cell (v));
3501 v = find_variable ("READLINE_POINT");
3502 if (v && legal_number (value_cell (v), &mi))
3508 if (rl_point > rl_end)
3510 else if (rl_point < 0)
3515 unbind_variable ("READLINE_LINE");
3516 unbind_variable ("READLINE_POINT");
3517 array_needs_making = 1;
3519 /* and restore the readline buffer and display after command execution. */
3520 rl_forced_update_display ();
3525 init_unix_command_map ()
3527 cmd_xmap = rl_make_bare_keymap ();
3531 isolate_sequence (string, ind, need_dquote, startp)
3533 int ind, need_dquote, *startp;
3536 int c, passc, delim;
3538 for (i = ind; string[i] && whitespace (string[i]); i++)
3540 /* NEED_DQUOTE means that the first non-white character *must* be `"'. */
3541 if (need_dquote && string[i] != '"')
3543 builtin_error (_("%s: first non-whitespace character is not `\"'"), string);
3547 /* We can have delimited strings even if NEED_DQUOTE == 0, like the command
3548 string to bind the key sequence to. */
3549 delim = (string[i] == '"' || string[i] == '\'') ? string[i] : 0;
3552 *startp = delim ? ++i : i;
3554 for (passc = 0; c = string[i]; i++)
3570 if (delim && string[i] != delim)
3572 builtin_error (_("no closing `%c' in %s"), delim, string);
3580 bind_keyseq_to_unix_command (line)
3588 init_unix_command_map ();
3590 kmap = rl_get_keymap ();
3592 /* We duplicate some of the work done by rl_parse_and_bind here, but
3593 this code only has to handle `"keyseq": ["]command["]' and can
3594 generate an error for anything else. */
3595 i = isolate_sequence (line, 0, 1, &kstart);
3599 /* Create the key sequence string to pass to rl_generic_bind */
3600 kseq = substring (line, kstart, i);
3602 for ( ; line[i] && line[i] != ':'; i++)
3606 builtin_error (_("%s: missing colon separator"), line);
3610 i = isolate_sequence (line, i + 1, 0, &kstart);
3614 /* Create the value string containing the command to execute. */
3615 value = substring (line, kstart, i);
3617 /* Save the command to execute and the key sequence in the CMD_XMAP */
3618 rl_generic_bind (ISMACR, kseq, value, cmd_xmap);
3620 /* and bind the key sequence in the current keymap to a function that
3621 understands how to execute from CMD_XMAP */
3622 rl_bind_keyseq_in_map (kseq, bash_execute_unix_command, kmap);
3627 /* Used by the programmable completion code. Complete TEXT as a filename,
3628 but return only directories as matches. Dequotes the filename before
3629 attempting to find matches. */
3631 bash_directory_completion_matches (text)
3638 qc = rl_dispatching ? rl_completion_quote_character : 0;
3639 dfn = bash_dequote_filename ((char *)text, qc);
3640 m1 = rl_completion_matches (dfn, rl_filename_completion_function);
3643 if (m1 == 0 || m1[0] == 0)
3645 /* We don't bother recomputing the lcd of the matches, because it will just
3646 get thrown away by the programmable completion code and recomputed
3648 (void)bash_ignore_filenames (m1);
3653 bash_dequote_text (text)
3659 qc = (text[0] == '"' || text[0] == '\'') ? text[0] : 0;
3660 dtxt = bash_dequote_filename ((char *)text, qc);
3663 #endif /* READLINE */