init version.
[bush.git] / src / bushline.c
blobc057518a1b2353505bbbc9f5e1c159d995855be5
1 /* bushline.c -- Bush's interface to the readline library. */
3 /* Copyright (C) 1987-2020 Free Software Foundation, Inc.
5 This file is part of GNU Bush, the Bourne Again SHell.
7 Bush 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 Bush 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 Bush. If not, see <http://www.gnu.org/licenses/>.
21 #include "config.h"
23 #if defined (READLINE)
25 #include "bushtypes.h"
26 #include "posixstat.h"
28 #if defined (HAVE_UNISTD_H)
29 # include <unistd.h>
30 #endif
32 #if defined (HAVE_GRP_H)
33 # include <grp.h>
34 #endif
36 #if defined (HAVE_NETDB_H)
37 # include <netdb.h>
38 #endif
40 #include <signal.h>
42 #include <stdio.h>
43 #include "chartypes.h"
44 #include "bushansi.h"
45 #include "bushintl.h"
47 #include "shell.h"
48 #include "input.h"
49 #include "parser.h"
50 #include "builtins.h"
51 #include "bushhist.h"
52 #include "bushline.h"
53 #include "execute_cmd.h"
54 #include "findcmd.h"
55 #include "pathexp.h"
56 #include "shmbutil.h"
57 #include "trap.h"
58 #include "flags.h"
60 #if defined (HAVE_MBSTR_H) && defined (HAVE_MBSCHR)
61 # include <mbstr.h> /* mbschr */
62 #endif
64 #include "builtins/common.h"
65 #include "builtins/builtext.h" /* for read_builtin */
67 #include <readline/rlconf.h>
68 #include <readline/readline.h>
69 #include <readline/history.h>
70 #include <readline/rlmbutil.h>
72 #include <glob/glob.h>
74 #if defined (ALIAS)
75 # include "alias.h"
76 #endif
78 #if defined (PROGRAMMABLE_COMPLETION)
79 # include "pcomplete.h"
80 #endif
82 /* These should agree with the defines for emacs_mode and vi_mode in
83 rldefs.h, even though that's not a public readline header file. */
84 #ifndef EMACS_EDITING_MODE
85 # define NO_EDITING_MODE -1
86 # define EMACS_EDITING_MODE 1
87 # define VI_EDITING_MODE 0
88 #endif
90 /* Copied from rldefs.h, since that's not a public readline header file. */
91 #ifndef FUNCTION_TO_KEYMAP
93 #if defined (CRAY)
94 # define FUNCTION_TO_KEYMAP(map, key) (Keymap)((int)map[key].function)
95 # define KEYMAP_TO_FUNCTION(data) (rl_command_func_t *)((int)(data))
96 #else
97 # define FUNCTION_TO_KEYMAP(map, key) (Keymap)(map[key].function)
98 # define KEYMAP_TO_FUNCTION(data) (rl_command_func_t *)(data)
99 #endif
101 #endif
103 #define RL_BOOLEAN_VARIABLE_VALUE(s) ((s)[0] == 'o' && (s)[1] == 'n' && (s)[2] == '\0')
105 #if defined (BRACE_COMPLETION)
106 extern int bush_brace_completion PARAMS((int, int));
107 #endif /* BRACE_COMPLETION */
109 /* To avoid including curses.h/term.h/termcap.h and that whole mess. */
110 #ifdef _MINIX
111 extern int tputs PARAMS((const char *string, int nlines, void (*outx)(int)));
112 #else
113 extern int tputs PARAMS((const char *string, int nlines, int (*outx)(int)));
114 #endif
116 /* Forward declarations */
118 /* Functions bound to keys in Readline for Bush users. */
119 static int shell_expand_line PARAMS((int, int));
120 static int display_shell_version PARAMS((int, int));
122 static int bush_ignore_filenames PARAMS((char **));
123 static int bush_ignore_everything PARAMS((char **));
124 static int bush_progcomp_ignore_filenames PARAMS((char **));
126 #if defined (BANG_HISTORY)
127 static char *history_expand_line_internal PARAMS((char *));
128 static int history_expand_line PARAMS((int, int));
129 static int tcsh_magic_space PARAMS((int, int));
130 #endif /* BANG_HISTORY */
131 #ifdef ALIAS
132 static int alias_expand_line PARAMS((int, int));
133 #endif
134 #if defined (BANG_HISTORY) && defined (ALIAS)
135 static int history_and_alias_expand_line PARAMS((int, int));
136 #endif
138 static int bush_forward_shellword PARAMS((int, int));
139 static int bush_backward_shellword PARAMS((int, int));
140 static int bush_kill_shellword PARAMS((int, int));
141 static int bush_backward_kill_shellword PARAMS((int, int));
142 static int bush_transpose_shellwords PARAMS((int, int));
144 /* Helper functions for Readline. */
145 static char *restore_tilde PARAMS((char *, char *));
146 static char *maybe_restore_tilde PARAMS((char *, char *));
148 static char *bush_filename_rewrite_hook PARAMS((char *, int));
150 static void bush_directory_expansion PARAMS((char **));
151 static int bush_filename_stat_hook PARAMS((char **));
152 static int bush_command_name_stat_hook PARAMS((char **));
153 static int bush_directory_completion_hook PARAMS((char **));
154 static int filename_completion_ignore PARAMS((char **));
155 static int bush_push_line PARAMS((void));
157 static int executable_completion PARAMS((const char *, int));
159 static rl_icppfunc_t *save_directory_hook PARAMS((void));
160 static void restore_directory_hook PARAMS((rl_icppfunc_t));
162 static int directory_exists PARAMS((const char *, int));
164 static void cleanup_expansion_error PARAMS((void));
165 static void maybe_make_readline_line PARAMS((char *));
166 static void set_up_new_line PARAMS((char *));
168 static int check_redir PARAMS((int));
169 static char **attempt_shell_completion PARAMS((const char *, int, int));
170 static char *variable_completion_function PARAMS((const char *, int));
171 static char *hostname_completion_function PARAMS((const char *, int));
172 static char *command_subst_completion_function PARAMS((const char *, int));
174 static void build_history_completion_array PARAMS((void));
175 static char *history_completion_generator PARAMS((const char *, int));
176 static int dynamic_complete_history PARAMS((int, int));
177 static int bush_dabbrev_expand PARAMS((int, int));
179 static void initialize_hostname_list PARAMS((void));
180 static void add_host_name PARAMS((char *));
181 static void snarf_hosts_from_file PARAMS((char *));
182 static char **hostnames_matching PARAMS((char *));
184 static void _ignore_completion_names PARAMS((char **, sh_ignore_func_t *));
185 static int name_is_acceptable PARAMS((const char *));
186 static int test_for_directory PARAMS((const char *));
187 static int test_for_canon_directory PARAMS((const char *));
188 static int return_zero PARAMS((const char *));
190 static char *bush_dequote_filename PARAMS((char *, int));
191 static char *quote_word_break_chars PARAMS((char *));
192 static void set_filename_bstab PARAMS((const char *));
193 static char *bush_quote_filename PARAMS((char *, int, char *));
195 #ifdef _MINIX
196 static void putx PARAMS((int));
197 #else
198 static int putx PARAMS((int));
199 #endif
200 static int readline_get_char_offset PARAMS((int));
201 static void readline_set_char_offset PARAMS((int, int *));
203 static Keymap get_cmd_xmap_from_edit_mode PARAMS((void));
204 static Keymap get_cmd_xmap_from_keymap PARAMS((Keymap));
206 static void init_unix_command_map PARAMS((void));
207 static int isolate_sequence PARAMS((char *, int, int, int *));
209 static int set_saved_history PARAMS((void));
211 #if defined (ALIAS)
212 static int posix_edit_macros PARAMS((int, int));
213 #endif
215 static int bush_event_hook PARAMS((void));
217 #if defined (PROGRAMMABLE_COMPLETION)
218 static int find_cmd_start PARAMS((int));
219 static int find_cmd_end PARAMS((int));
220 static char *find_cmd_name PARAMS((int, int *, int *));
221 static char *prog_complete_return PARAMS((const char *, int));
223 static char **prog_complete_matches;
224 #endif
226 extern int no_symbolic_links;
227 extern STRING_INT_ALIST word_token_alist[];
229 /* SPECIFIC_COMPLETION_FUNCTIONS specifies that we have individual
230 completion functions which indicate what type of completion should be
231 done (at or before point) that can be bound to key sequences with
232 the readline library. */
233 #define SPECIFIC_COMPLETION_FUNCTIONS
235 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
236 static int bush_specific_completion PARAMS((int, rl_compentry_func_t *));
238 static int bush_complete_filename_internal PARAMS((int));
239 static int bush_complete_username_internal PARAMS((int));
240 static int bush_complete_hostname_internal PARAMS((int));
241 static int bush_complete_variable_internal PARAMS((int));
242 static int bush_complete_command_internal PARAMS((int));
244 static int bush_complete_filename PARAMS((int, int));
245 static int bush_possible_filename_completions PARAMS((int, int));
246 static int bush_complete_username PARAMS((int, int));
247 static int bush_possible_username_completions PARAMS((int, int));
248 static int bush_complete_hostname PARAMS((int, int));
249 static int bush_possible_hostname_completions PARAMS((int, int));
250 static int bush_complete_variable PARAMS((int, int));
251 static int bush_possible_variable_completions PARAMS((int, int));
252 static int bush_complete_command PARAMS((int, int));
253 static int bush_possible_command_completions PARAMS((int, int));
255 static int completion_glob_pattern PARAMS((char *));
256 static char *glob_complete_word PARAMS((const char *, int));
257 static int bush_glob_completion_internal PARAMS((int));
258 static int bush_glob_complete_word PARAMS((int, int));
259 static int bush_glob_expand_word PARAMS((int, int));
260 static int bush_glob_list_expansions PARAMS((int, int));
262 #endif /* SPECIFIC_COMPLETION_FUNCTIONS */
264 static int edit_and_execute_command PARAMS((int, int, int, char *));
265 #if defined (VI_MODE)
266 static int vi_edit_and_execute_command PARAMS((int, int));
267 static int bush_vi_complete PARAMS((int, int));
268 #endif
269 static int emacs_edit_and_execute_command PARAMS((int, int));
271 /* Non-zero once initialize_readline () has been called. */
272 int bush_readline_initialized = 0;
274 /* If non-zero, we do hostname completion, breaking words at `@' and
275 trying to complete the stuff after the `@' from our own internal
276 host list. */
277 int perform_hostname_completion = 1;
279 /* If non-zero, we don't do command completion on an empty line. */
280 int no_empty_command_completion;
282 /* Set FORCE_FIGNORE if you want to honor FIGNORE even if it ignores the
283 only possible matches. Set to 0 if you want to match filenames if they
284 are the only possible matches, even if FIGNORE says to. */
285 int force_fignore = 1;
287 /* Perform spelling correction on directory names during word completion */
288 int dircomplete_spelling = 0;
290 /* Expand directory names during word/filename completion. */
291 #if DIRCOMPLETE_EXPAND_DEFAULT
292 int dircomplete_expand = 1;
293 int dircomplete_expand_relpath = 1;
294 #else
295 int dircomplete_expand = 0;
296 int dircomplete_expand_relpath = 0;
297 #endif
299 /* When non-zero, perform `normal' shell quoting on completed filenames
300 even when the completed name contains a directory name with a shell
301 variable reference, so dollar signs in a filename get quoted appropriately.
302 Set to zero to remove dollar sign (and braces or parens as needed) from
303 the set of characters that will be quoted. */
304 int complete_fullquote = 1;
306 static char *bush_completer_word_break_characters = " \t\n\"'@><=;|&(:";
307 static char *bush_nohostname_word_break_characters = " \t\n\"'><=;|&(:";
308 /* )) */
310 static const char *default_filename_quote_characters = " \t\n\\\"'@<>=;|&()#$`?*[!:{~"; /*}*/
311 static char *custom_filename_quote_characters = 0;
312 static char filename_bstab[256];
314 static rl_hook_func_t *old_rl_startup_hook = (rl_hook_func_t *)NULL;
316 static int dot_in_path = 0;
318 /* Set to non-zero when dabbrev-expand is running */
319 static int dabbrev_expand_active = 0;
321 /* What kind of quoting is performed by bush_quote_filename:
322 COMPLETE_DQUOTE = double-quoting the filename
323 COMPLETE_SQUOTE = single_quoting the filename
324 COMPLETE_BSQUOTE = backslash-quoting special chars in the filename
326 #define COMPLETE_DQUOTE 1
327 #define COMPLETE_SQUOTE 2
328 #define COMPLETE_BSQUOTE 3
329 static int completion_quoting_style = COMPLETE_BSQUOTE;
331 /* Flag values for the final argument to bush_default_completion */
332 #define DEFCOMP_CMDPOS 1
334 static rl_command_func_t *vi_tab_binding = rl_complete;
336 /* Change the readline VI-mode keymaps into or out of Posix.2 compliance.
337 Called when the shell is put into or out of `posix' mode. */
338 void
339 posix_readline_initialize (on_or_off)
340 int on_or_off;
342 static char kseq[2] = { CTRL ('I'), 0 }; /* TAB */
344 if (on_or_off)
345 rl_variable_bind ("comment-begin", "#");
346 #if defined (VI_MODE)
347 if (on_or_off)
349 vi_tab_binding = rl_function_of_keyseq (kseq, vi_insertion_keymap, (int *)NULL);
350 rl_bind_key_in_map (CTRL ('I'), rl_insert, vi_insertion_keymap);
352 else
354 if (rl_function_of_keyseq (kseq, vi_insertion_keymap, (int *)NULL) == rl_insert)
355 rl_bind_key_in_map (CTRL ('I'), vi_tab_binding, vi_insertion_keymap);
357 #endif
360 void
361 reset_completer_word_break_chars ()
363 rl_completer_word_break_characters = perform_hostname_completion ? savestring (bush_completer_word_break_characters) : savestring (bush_nohostname_word_break_characters);
366 /* When this function returns, rl_completer_word_break_characters points to
367 dynamically allocated memory. */
369 enable_hostname_completion (on_or_off)
370 int on_or_off;
372 int old_value;
373 char *at, *nv, *nval;
375 old_value = perform_hostname_completion;
377 if (on_or_off)
379 perform_hostname_completion = 1;
380 rl_special_prefixes = "$@";
382 else
384 perform_hostname_completion = 0;
385 rl_special_prefixes = "$";
388 /* Now we need to figure out how to appropriately modify and assign
389 rl_completer_word_break_characters depending on whether we want
390 hostname completion on or off. */
392 /* If this is the first time this has been called
393 (bush_readline_initialized == 0), use the sames values as before, but
394 allocate new memory for rl_completer_word_break_characters. */
396 if (bush_readline_initialized == 0 &&
397 (rl_completer_word_break_characters == 0 ||
398 rl_completer_word_break_characters == rl_basic_word_break_characters))
400 if (on_or_off)
401 rl_completer_word_break_characters = savestring (bush_completer_word_break_characters);
402 else
403 rl_completer_word_break_characters = savestring (bush_nohostname_word_break_characters);
405 else
407 /* See if we have anything to do. */
408 at = strchr (rl_completer_word_break_characters, '@');
409 if ((at == 0 && on_or_off == 0) || (at != 0 && on_or_off != 0))
410 return old_value;
412 /* We have something to do. Do it. */
413 nval = (char *)xmalloc (strlen (rl_completer_word_break_characters) + 1 + on_or_off);
415 if (on_or_off == 0)
417 /* Turn it off -- just remove `@' from word break chars. We want
418 to remove all occurrences of `@' from the char list, so we loop
419 rather than just copy the rest of the list over AT. */
420 for (nv = nval, at = rl_completer_word_break_characters; *at; )
421 if (*at != '@')
422 *nv++ = *at++;
423 else
424 at++;
425 *nv = '\0';
427 else
429 nval[0] = '@';
430 strcpy (nval + 1, rl_completer_word_break_characters);
433 free (rl_completer_word_break_characters);
434 rl_completer_word_break_characters = nval;
437 return (old_value);
440 /* Called once from parse.y if we are going to use readline. */
441 void
442 initialize_readline ()
444 rl_command_func_t *func;
445 char kseq[2];
447 if (bush_readline_initialized)
448 return;
450 rl_terminal_name = get_string_value ("TERM");
451 rl_instream = stdin;
452 rl_outstream = stderr;
454 /* Allow conditional parsing of the ~/.inputrc file. */
455 rl_readline_name = "Bush";
457 /* Add bindable names before calling rl_initialize so they may be
458 referenced in the various inputrc files. */
459 rl_add_defun ("shell-expand-line", shell_expand_line, -1);
460 #ifdef BANG_HISTORY
461 rl_add_defun ("history-expand-line", history_expand_line, -1);
462 rl_add_defun ("magic-space", tcsh_magic_space, -1);
463 #endif
465 rl_add_defun ("shell-forward-word", bush_forward_shellword, -1);
466 rl_add_defun ("shell-backward-word", bush_backward_shellword, -1);
467 rl_add_defun ("shell-kill-word", bush_kill_shellword, -1);
468 rl_add_defun ("shell-backward-kill-word", bush_backward_kill_shellword, -1);
469 rl_add_defun ("shell-transpose-words", bush_transpose_shellwords, -1);
471 #ifdef ALIAS
472 rl_add_defun ("alias-expand-line", alias_expand_line, -1);
473 # ifdef BANG_HISTORY
474 rl_add_defun ("history-and-alias-expand-line", history_and_alias_expand_line, -1);
475 # endif
476 #endif
478 /* Backwards compatibility. */
479 rl_add_defun ("insert-last-argument", rl_yank_last_arg, -1);
481 rl_add_defun ("display-shell-version", display_shell_version, -1);
482 rl_add_defun ("edit-and-execute-command", emacs_edit_and_execute_command, -1);
484 #if defined (BRACE_COMPLETION)
485 rl_add_defun ("complete-into-braces", bush_brace_completion, -1);
486 #endif
488 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
489 rl_add_defun ("complete-filename", bush_complete_filename, -1);
490 rl_add_defun ("possible-filename-completions", bush_possible_filename_completions, -1);
491 rl_add_defun ("complete-username", bush_complete_username, -1);
492 rl_add_defun ("possible-username-completions", bush_possible_username_completions, -1);
493 rl_add_defun ("complete-hostname", bush_complete_hostname, -1);
494 rl_add_defun ("possible-hostname-completions", bush_possible_hostname_completions, -1);
495 rl_add_defun ("complete-variable", bush_complete_variable, -1);
496 rl_add_defun ("possible-variable-completions", bush_possible_variable_completions, -1);
497 rl_add_defun ("complete-command", bush_complete_command, -1);
498 rl_add_defun ("possible-command-completions", bush_possible_command_completions, -1);
499 rl_add_defun ("glob-complete-word", bush_glob_complete_word, -1);
500 rl_add_defun ("glob-expand-word", bush_glob_expand_word, -1);
501 rl_add_defun ("glob-list-expansions", bush_glob_list_expansions, -1);
502 #endif
504 rl_add_defun ("dynamic-complete-history", dynamic_complete_history, -1);
505 rl_add_defun ("dabbrev-expand", bush_dabbrev_expand, -1);
507 /* Bind defaults before binding our custom shell keybindings. */
508 if (RL_ISSTATE(RL_STATE_INITIALIZED) == 0)
509 rl_initialize ();
511 /* Bind up our special shell functions. */
512 rl_bind_key_if_unbound_in_map (CTRL('E'), shell_expand_line, emacs_meta_keymap);
514 #ifdef BANG_HISTORY
515 rl_bind_key_if_unbound_in_map ('^', history_expand_line, emacs_meta_keymap);
516 #endif
518 rl_bind_key_if_unbound_in_map (CTRL ('V'), display_shell_version, emacs_ctlx_keymap);
520 /* In Bush, the user can switch editing modes with "set -o [vi emacs]",
521 so it is not necessary to allow C-M-j for context switching. Turn
522 off this occasionally confusing behaviour. */
523 kseq[0] = CTRL('J');
524 kseq[1] = '\0';
525 func = rl_function_of_keyseq (kseq, emacs_meta_keymap, (int *)NULL);
526 if (func == rl_vi_editing_mode)
527 rl_unbind_key_in_map (CTRL('J'), emacs_meta_keymap);
528 kseq[0] = CTRL('M');
529 func = rl_function_of_keyseq (kseq, emacs_meta_keymap, (int *)NULL);
530 if (func == rl_vi_editing_mode)
531 rl_unbind_key_in_map (CTRL('M'), emacs_meta_keymap);
532 #if defined (VI_MODE)
533 kseq[0] = CTRL('E');
534 func = rl_function_of_keyseq (kseq, vi_movement_keymap, (int *)NULL);
535 if (func == rl_emacs_editing_mode)
536 rl_unbind_key_in_map (CTRL('E'), vi_movement_keymap);
537 #endif
539 #if defined (BRACE_COMPLETION)
540 rl_bind_key_if_unbound_in_map ('{', bush_brace_completion, emacs_meta_keymap); /*}*/
541 #endif /* BRACE_COMPLETION */
543 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
544 rl_bind_key_if_unbound_in_map ('/', bush_complete_filename, emacs_meta_keymap);
545 rl_bind_key_if_unbound_in_map ('/', bush_possible_filename_completions, emacs_ctlx_keymap);
547 /* Have to jump through hoops here because there is a default binding for
548 M-~ (rl_tilde_expand) */
549 kseq[0] = '~';
550 kseq[1] = '\0';
551 func = rl_function_of_keyseq (kseq, emacs_meta_keymap, (int *)NULL);
552 if (func == 0 || func == rl_tilde_expand)
553 rl_bind_keyseq_in_map (kseq, bush_complete_username, emacs_meta_keymap);
555 rl_bind_key_if_unbound_in_map ('~', bush_possible_username_completions, emacs_ctlx_keymap);
557 rl_bind_key_if_unbound_in_map ('@', bush_complete_hostname, emacs_meta_keymap);
558 rl_bind_key_if_unbound_in_map ('@', bush_possible_hostname_completions, emacs_ctlx_keymap);
560 rl_bind_key_if_unbound_in_map ('$', bush_complete_variable, emacs_meta_keymap);
561 rl_bind_key_if_unbound_in_map ('$', bush_possible_variable_completions, emacs_ctlx_keymap);
563 rl_bind_key_if_unbound_in_map ('!', bush_complete_command, emacs_meta_keymap);
564 rl_bind_key_if_unbound_in_map ('!', bush_possible_command_completions, emacs_ctlx_keymap);
566 rl_bind_key_if_unbound_in_map ('g', bush_glob_complete_word, emacs_meta_keymap);
567 rl_bind_key_if_unbound_in_map ('*', bush_glob_expand_word, emacs_ctlx_keymap);
568 rl_bind_key_if_unbound_in_map ('g', bush_glob_list_expansions, emacs_ctlx_keymap);
570 #endif /* SPECIFIC_COMPLETION_FUNCTIONS */
572 kseq[0] = TAB;
573 kseq[1] = '\0';
574 func = rl_function_of_keyseq (kseq, emacs_meta_keymap, (int *)NULL);
575 if (func == 0 || func == rl_tab_insert)
576 rl_bind_key_in_map (TAB, dynamic_complete_history, emacs_meta_keymap);
578 /* Tell the completer that we want a crack first. */
579 rl_attempted_completion_function = attempt_shell_completion;
581 /* Tell the completer that we might want to follow symbolic links or
582 do other expansion on directory names. */
583 set_directory_hook ();
585 rl_filename_rewrite_hook = bush_filename_rewrite_hook;
587 rl_filename_stat_hook = bush_filename_stat_hook;
589 /* Tell the filename completer we want a chance to ignore some names. */
590 rl_ignore_some_completions_function = filename_completion_ignore;
592 /* Bind C-xC-e to invoke emacs and run result as commands. */
593 rl_bind_key_if_unbound_in_map (CTRL ('E'), emacs_edit_and_execute_command, emacs_ctlx_keymap);
594 #if defined (VI_MODE)
595 rl_bind_key_if_unbound_in_map ('v', vi_edit_and_execute_command, vi_movement_keymap);
596 # if defined (ALIAS)
597 rl_bind_key_if_unbound_in_map ('@', posix_edit_macros, vi_movement_keymap);
598 # endif
600 rl_bind_key_in_map ('\\', bush_vi_complete, vi_movement_keymap);
601 rl_bind_key_in_map ('*', bush_vi_complete, vi_movement_keymap);
602 rl_bind_key_in_map ('=', bush_vi_complete, vi_movement_keymap);
603 #endif
605 rl_completer_quote_characters = "'\"";
607 /* This sets rl_completer_word_break_characters and rl_special_prefixes
608 to the appropriate values, depending on whether or not hostname
609 completion is enabled. */
610 enable_hostname_completion (perform_hostname_completion);
612 /* characters that need to be quoted when appearing in filenames. */
613 rl_filename_quote_characters = default_filename_quote_characters;
614 set_filename_bstab (rl_filename_quote_characters);
616 rl_filename_quoting_function = bush_quote_filename;
617 rl_filename_dequoting_function = bush_dequote_filename;
618 rl_char_is_quoted_p = char_is_quoted;
620 /* Add some default bindings for the "shellwords" functions, roughly
621 parallelling the default word bindings in emacs mode. */
622 rl_bind_key_if_unbound_in_map (CTRL('B'), bush_backward_shellword, emacs_meta_keymap);
623 rl_bind_key_if_unbound_in_map (CTRL('D'), bush_kill_shellword, emacs_meta_keymap);
624 rl_bind_key_if_unbound_in_map (CTRL('F'), bush_forward_shellword, emacs_meta_keymap);
625 rl_bind_key_if_unbound_in_map (CTRL('T'), bush_transpose_shellwords, emacs_meta_keymap);
627 #if 0
628 /* This is superfluous and makes it impossible to use tab completion in
629 vi mode even when explicitly binding it in ~/.inputrc. sv_strict_posix()
630 should already have called posix_readline_initialize() when
631 posixly_correct was set. */
632 if (posixly_correct)
633 posix_readline_initialize (1);
634 #endif
636 bush_readline_initialized = 1;
639 void
640 bushline_reinitialize ()
642 bush_readline_initialized = 0;
645 void
646 bushline_set_event_hook ()
648 rl_signal_event_hook = bush_event_hook;
651 void
652 bushline_reset_event_hook ()
654 rl_signal_event_hook = 0;
657 /* On Sun systems at least, rl_attempted_completion_function can end up
658 getting set to NULL, and rl_completion_entry_function set to do command
659 word completion if Bush is interrupted while trying to complete a command
660 word. This just resets all the completion functions to the right thing.
661 It's called from throw_to_top_level(). */
662 void
663 bushline_reset ()
665 tilde_initialize ();
666 rl_attempted_completion_function = attempt_shell_completion;
667 rl_completion_entry_function = NULL;
668 rl_ignore_some_completions_function = filename_completion_ignore;
669 rl_filename_quote_characters = default_filename_quote_characters;
670 set_filename_bstab (rl_filename_quote_characters);
672 set_directory_hook ();
673 rl_filename_stat_hook = bush_filename_stat_hook;
675 bushline_reset_event_hook ();
677 rl_sort_completion_matches = 1;
680 /* Contains the line to push into readline. */
681 static char *push_to_readline = (char *)NULL;
683 /* Push the contents of push_to_readline into the
684 readline buffer. */
685 static int
686 bush_push_line ()
688 if (push_to_readline)
690 rl_insert_text (push_to_readline);
691 free (push_to_readline);
692 push_to_readline = (char *)NULL;
693 rl_startup_hook = old_rl_startup_hook;
695 return 0;
698 /* Call this to set the initial text for the next line to read
699 from readline. */
701 bush_re_edit (line)
702 char *line;
704 FREE (push_to_readline);
706 push_to_readline = savestring (line);
707 old_rl_startup_hook = rl_startup_hook;
708 rl_startup_hook = bush_push_line;
710 return (0);
713 static int
714 display_shell_version (count, c)
715 int count, c;
717 rl_crlf ();
718 show_shell_version (0);
719 putc ('\r', rl_outstream);
720 fflush (rl_outstream);
721 rl_on_new_line ();
722 rl_redisplay ();
723 return 0;
726 /* **************************************************************** */
727 /* */
728 /* Readline Stuff */
729 /* */
730 /* **************************************************************** */
732 /* If the user requests hostname completion, then simply build a list
733 of hosts, and complete from that forever more, or at least until
734 HOSTFILE is unset. */
736 /* THIS SHOULD BE A STRINGLIST. */
737 /* The kept list of hostnames. */
738 static char **hostname_list = (char **)NULL;
740 /* The physical size of the above list. */
741 static int hostname_list_size;
743 /* The number of hostnames in the above list. */
744 static int hostname_list_length;
746 /* Whether or not HOSTNAME_LIST has been initialized. */
747 int hostname_list_initialized = 0;
749 /* Initialize the hostname completion table. */
750 static void
751 initialize_hostname_list ()
753 char *temp;
755 temp = get_string_value ("HOSTFILE");
756 if (temp == 0)
757 temp = get_string_value ("hostname_completion_file");
758 if (temp == 0)
759 temp = DEFAULT_HOSTS_FILE;
761 snarf_hosts_from_file (temp);
763 if (hostname_list)
764 hostname_list_initialized++;
767 /* Add NAME to the list of hosts. */
768 static void
769 add_host_name (name)
770 char *name;
772 if (hostname_list_length + 2 > hostname_list_size)
774 hostname_list_size = (hostname_list_size + 32) - (hostname_list_size % 32);
775 hostname_list = strvec_resize (hostname_list, hostname_list_size);
778 hostname_list[hostname_list_length++] = savestring (name);
779 hostname_list[hostname_list_length] = (char *)NULL;
782 #define cr_whitespace(c) ((c) == '\r' || (c) == '\n' || whitespace(c))
784 static void
785 snarf_hosts_from_file (filename)
786 char *filename;
788 FILE *file;
789 char *temp, buffer[256], name[256];
790 register int i, start;
792 file = fopen (filename, "r");
793 if (file == 0)
794 return;
796 while (temp = fgets (buffer, 255, file))
798 /* Skip to first character. */
799 for (i = 0; buffer[i] && cr_whitespace (buffer[i]); i++)
802 /* If comment or blank line, ignore. */
803 if (buffer[i] == '\0' || buffer[i] == '#')
804 continue;
806 /* If `preprocessor' directive, do the include. */
807 if (strncmp (buffer + i, "$include ", 9) == 0)
809 char *incfile, *t;
811 /* Find start of filename. */
812 for (incfile = buffer + i + 9; *incfile && whitespace (*incfile); incfile++)
815 /* Find end of filename. */
816 for (t = incfile; *t && cr_whitespace (*t) == 0; t++)
819 *t = '\0';
821 snarf_hosts_from_file (incfile);
822 continue;
825 /* Skip internet address if present. */
826 if (DIGIT (buffer[i]))
827 for (; buffer[i] && cr_whitespace (buffer[i]) == 0; i++);
829 /* Gobble up names. Each name is separated with whitespace. */
830 while (buffer[i])
832 for (; cr_whitespace (buffer[i]); i++)
834 if (buffer[i] == '\0' || buffer[i] == '#')
835 break;
837 /* Isolate the current word. */
838 for (start = i; buffer[i] && cr_whitespace (buffer[i]) == 0; i++)
840 if (i == start)
841 continue;
842 strncpy (name, buffer + start, i - start);
843 name[i - start] = '\0';
844 add_host_name (name);
847 fclose (file);
850 /* Return the hostname list. */
851 char **
852 get_hostname_list ()
854 if (hostname_list_initialized == 0)
855 initialize_hostname_list ();
856 return (hostname_list);
859 void
860 clear_hostname_list ()
862 register int i;
864 if (hostname_list_initialized == 0)
865 return;
866 for (i = 0; i < hostname_list_length; i++)
867 free (hostname_list[i]);
868 hostname_list_length = hostname_list_initialized = 0;
871 /* Return a NULL terminated list of hostnames which begin with TEXT.
872 Initialize the hostname list the first time if necessary.
873 The array is malloc ()'ed, but not the individual strings. */
874 static char **
875 hostnames_matching (text)
876 char *text;
878 register int i, len, nmatch, rsize;
879 char **result;
881 if (hostname_list_initialized == 0)
882 initialize_hostname_list ();
884 if (hostname_list_initialized == 0)
885 return ((char **)NULL);
887 /* Special case. If TEXT consists of nothing, then the whole list is
888 what is desired. */
889 if (*text == '\0')
891 result = strvec_create (1 + hostname_list_length);
892 for (i = 0; i < hostname_list_length; i++)
893 result[i] = hostname_list[i];
894 result[i] = (char *)NULL;
895 return (result);
898 /* Scan until found, or failure. */
899 len = strlen (text);
900 result = (char **)NULL;
901 for (i = nmatch = rsize = 0; i < hostname_list_length; i++)
903 if (STREQN (text, hostname_list[i], len) == 0)
904 continue;
906 /* OK, it matches. Add it to the list. */
907 if (nmatch >= (rsize - 1))
909 rsize = (rsize + 16) - (rsize % 16);
910 result = strvec_resize (result, rsize);
913 result[nmatch++] = hostname_list[i];
915 if (nmatch)
916 result[nmatch] = (char *)NULL;
917 return (result);
920 /* This vi mode command causes VI_EDIT_COMMAND to be run on the current
921 command being entered (if no explicit argument is given), otherwise on
922 a command from the history file. */
924 #define VI_EDIT_COMMAND "fc -e \"${VISUAL:-${EDITOR:-vi}}\""
925 #define EMACS_EDIT_COMMAND "fc -e \"${VISUAL:-${EDITOR:-emacs}}\""
926 #define POSIX_VI_EDIT_COMMAND "fc -e vi"
928 static int
929 edit_and_execute_command (count, c, editing_mode, edit_command)
930 int count, c, editing_mode;
931 char *edit_command;
933 char *command, *metaval;
934 int r, rrs, metaflag;
935 sh_parser_state_t ps;
937 rrs = rl_readline_state;
938 saved_command_line_count = current_command_line_count;
940 /* Accept the current line. */
941 rl_newline (1, c);
943 if (rl_explicit_arg)
945 command = (char *)xmalloc (strlen (edit_command) + 8);
946 sprintf (command, "%s %d", edit_command, count);
948 else
950 /* Take the command we were just editing, add it to the history file,
951 then call fc to operate on it. We have to add a dummy command to
952 the end of the history because fc ignores the last command (assumes
953 it's supposed to deal with the command before the `fc'). */
954 /* This breaks down when using command-oriented history and are not
955 finished with the command, so we should not ignore the last command */
956 using_history ();
957 current_command_line_count++; /* for rl_newline above */
958 bush_add_history (rl_line_buffer);
959 current_command_line_count = 0; /* for dummy history entry */
960 bush_add_history ("");
961 history_lines_this_session++;
962 using_history ();
963 command = savestring (edit_command);
966 metaval = rl_variable_value ("input-meta");
967 metaflag = RL_BOOLEAN_VARIABLE_VALUE (metaval);
969 if (rl_deprep_term_function)
970 (*rl_deprep_term_function) ();
971 rl_clear_signals ();
972 save_parser_state (&ps);
973 r = parse_and_execute (command, (editing_mode == VI_EDITING_MODE) ? "v" : "C-xC-e", SEVAL_NOHIST);
974 restore_parser_state (&ps);
976 /* if some kind of reset_parser was called, undo it. */
977 reset_readahead_token ();
979 if (rl_prep_term_function)
980 (*rl_prep_term_function) (metaflag);
981 rl_set_signals ();
983 current_command_line_count = saved_command_line_count;
985 /* Now erase the contents of the current line and undo the effects of the
986 rl_accept_line() above. We don't even want to make the text we just
987 executed available for undoing. */
988 rl_line_buffer[0] = '\0'; /* XXX */
989 rl_point = rl_end = 0;
990 rl_done = 0;
991 rl_readline_state = rrs;
993 #if defined (VI_MODE)
994 if (editing_mode == VI_EDITING_MODE)
995 rl_vi_insertion_mode (1, c);
996 #endif
998 rl_forced_update_display ();
1000 return r;
1003 #if defined (VI_MODE)
1004 static int
1005 vi_edit_and_execute_command (count, c)
1006 int count, c;
1008 if (posixly_correct)
1009 return (edit_and_execute_command (count, c, VI_EDITING_MODE, POSIX_VI_EDIT_COMMAND));
1010 else
1011 return (edit_and_execute_command (count, c, VI_EDITING_MODE, VI_EDIT_COMMAND));
1013 #endif /* VI_MODE */
1015 static int
1016 emacs_edit_and_execute_command (count, c)
1017 int count, c;
1019 return (edit_and_execute_command (count, c, EMACS_EDITING_MODE, EMACS_EDIT_COMMAND));
1022 #if defined (ALIAS)
1023 static int
1024 posix_edit_macros (count, key)
1025 int count, key;
1027 int c;
1028 char alias_name[3], *alias_value, *macro;
1030 c = rl_read_key ();
1031 alias_name[0] = '_';
1032 alias_name[1] = c;
1033 alias_name[2] = '\0';
1035 alias_value = get_alias_value (alias_name);
1036 if (alias_value && *alias_value)
1038 macro = savestring (alias_value);
1039 rl_push_macro_input (macro);
1041 return 0;
1043 #endif
1045 /* Bindable commands that move `shell-words': that is, sequences of
1046 non-unquoted-metacharacters. */
1048 #define WORDDELIM(c) (shellmeta(c) || shellblank(c))
1050 static int
1051 bush_forward_shellword (count, key)
1052 int count, key;
1054 size_t slen;
1055 int c, p;
1056 DECLARE_MBSTATE;
1058 if (count < 0)
1059 return (bush_backward_shellword (-count, key));
1061 /* The tricky part of this is deciding whether or not the first character
1062 we're on is an unquoted metacharacter. Not completely handled yet. */
1063 /* XXX - need to test this stuff with backslash-escaped shell
1064 metacharacters and unclosed single- and double-quoted strings. */
1066 p = rl_point;
1067 slen = rl_end;
1069 while (count)
1071 if (p == rl_end)
1073 rl_point = rl_end;
1074 return 0;
1077 /* Are we in a quoted string? If we are, move to the end of the quoted
1078 string and continue the outer loop. We only want quoted strings, not
1079 backslash-escaped characters, but char_is_quoted doesn't
1080 differentiate. */
1081 if (char_is_quoted (rl_line_buffer, p) && p > 0 && rl_line_buffer[p-1] != '\\')
1084 ADVANCE_CHAR (rl_line_buffer, slen, p);
1085 while (p < rl_end && char_is_quoted (rl_line_buffer, p));
1086 count--;
1087 continue;
1090 /* Rest of code assumes we are not in a quoted string. */
1091 /* Move forward until we hit a non-metacharacter. */
1092 while (p < rl_end && (c = rl_line_buffer[p]) && WORDDELIM (c))
1094 switch (c)
1096 default:
1097 ADVANCE_CHAR (rl_line_buffer, slen, p);
1098 continue; /* straight back to loop, don't increment p */
1099 case '\\':
1100 if (p < rl_end && rl_line_buffer[p])
1101 ADVANCE_CHAR (rl_line_buffer, slen, p);
1102 break;
1103 case '\'':
1104 p = skip_to_delim (rl_line_buffer, ++p, "'", SD_NOJMP);
1105 break;
1106 case '"':
1107 p = skip_to_delim (rl_line_buffer, ++p, "\"", SD_NOJMP);
1108 break;
1111 if (p < rl_end)
1112 p++;
1115 if (rl_line_buffer[p] == 0 || p == rl_end)
1117 rl_point = rl_end;
1118 rl_ding ();
1119 return 0;
1122 /* Now move forward until we hit a non-quoted metacharacter or EOL */
1123 while (p < rl_end && (c = rl_line_buffer[p]) && WORDDELIM (c) == 0)
1125 switch (c)
1127 default:
1128 ADVANCE_CHAR (rl_line_buffer, slen, p);
1129 continue; /* straight back to loop, don't increment p */
1130 case '\\':
1131 if (p < rl_end && rl_line_buffer[p])
1132 ADVANCE_CHAR (rl_line_buffer, slen, p);
1133 break;
1134 case '\'':
1135 p = skip_to_delim (rl_line_buffer, ++p, "'", SD_NOJMP);
1136 break;
1137 case '"':
1138 p = skip_to_delim (rl_line_buffer, ++p, "\"", SD_NOJMP);
1139 break;
1142 if (p < rl_end)
1143 p++;
1146 if (p == rl_end || rl_line_buffer[p] == 0)
1148 rl_point = rl_end;
1149 return (0);
1152 count--;
1155 rl_point = p;
1156 return (0);
1159 static int
1160 bush_backward_shellword (count, key)
1161 int count, key;
1163 size_t slen;
1164 int c, p, prev_p;
1165 DECLARE_MBSTATE;
1167 if (count < 0)
1168 return (bush_forward_shellword (-count, key));
1170 p = rl_point;
1171 slen = rl_end;
1173 while (count)
1175 if (p == 0)
1177 rl_point = 0;
1178 return 0;
1181 /* Move backward until we hit a non-metacharacter. We want to deal
1182 with the characters before point, so we move off a word if we're
1183 at its first character. */
1184 BACKUP_CHAR (rl_line_buffer, slen, p);
1185 while (p > 0)
1187 c = rl_line_buffer[p];
1188 if (WORDDELIM (c) == 0 || char_is_quoted (rl_line_buffer, p))
1189 break;
1190 BACKUP_CHAR (rl_line_buffer, slen, p);
1193 if (p == 0)
1195 rl_point = 0;
1196 return 0;
1199 /* Now move backward until we hit a metacharacter or BOL. Leave point
1200 at the start of the shellword or at BOL. */
1201 prev_p = p;
1202 while (p > 0)
1204 c = rl_line_buffer[p];
1205 if (WORDDELIM (c) && char_is_quoted (rl_line_buffer, p) == 0)
1207 p = prev_p;
1208 break;
1210 prev_p = p;
1211 BACKUP_CHAR (rl_line_buffer, slen, p);
1214 count--;
1217 rl_point = p;
1218 return 0;
1221 static int
1222 bush_kill_shellword (count, key)
1223 int count, key;
1225 int p;
1227 if (count < 0)
1228 return (bush_backward_kill_shellword (-count, key));
1230 p = rl_point;
1231 bush_forward_shellword (count, key);
1233 if (rl_point != p)
1234 rl_kill_text (p, rl_point);
1236 rl_point = p;
1237 if (rl_editing_mode == EMACS_EDITING_MODE) /* 1 == emacs_mode */
1238 rl_mark = rl_point;
1240 return 0;
1243 static int
1244 bush_backward_kill_shellword (count, key)
1245 int count, key;
1247 int p;
1249 if (count < 0)
1250 return (bush_kill_shellword (-count, key));
1252 p = rl_point;
1253 bush_backward_shellword (count, key);
1255 if (rl_point != p)
1256 rl_kill_text (p, rl_point);
1258 if (rl_editing_mode == EMACS_EDITING_MODE) /* 1 == emacs_mode */
1259 rl_mark = rl_point;
1261 return 0;
1264 static int
1265 bush_transpose_shellwords (count, key)
1266 int count, key;
1268 char *word1, *word2;
1269 int w1_beg, w1_end, w2_beg, w2_end;
1270 int orig_point = rl_point;
1272 if (count == 0)
1273 return 0;
1275 /* Find the two shell words. */
1276 bush_forward_shellword (count, key);
1277 w2_end = rl_point;
1278 bush_backward_shellword (1, key);
1279 w2_beg = rl_point;
1280 bush_backward_shellword (count, key);
1281 w1_beg = rl_point;
1282 bush_forward_shellword (1, key);
1283 w1_end = rl_point;
1285 /* check that there really are two words. */
1286 if ((w1_beg == w2_beg) || (w2_beg < w1_end))
1288 rl_ding ();
1289 rl_point = orig_point;
1290 return 1;
1293 /* Get the text of the words. */
1294 word1 = rl_copy_text (w1_beg, w1_end);
1295 word2 = rl_copy_text (w2_beg, w2_end);
1297 /* We are about to do many insertions and deletions. Remember them
1298 as one operation. */
1299 rl_begin_undo_group ();
1301 /* Do the stuff at word2 first, so that we don't have to worry
1302 about word1 moving. */
1303 rl_point = w2_beg;
1304 rl_delete_text (w2_beg, w2_end);
1305 rl_insert_text (word1);
1307 rl_point = w1_beg;
1308 rl_delete_text (w1_beg, w1_end);
1309 rl_insert_text (word2);
1311 /* This is exactly correct since the text before this point has not
1312 changed in length. */
1313 rl_point = w2_end;
1315 /* I think that does it. */
1316 rl_end_undo_group ();
1317 xfree (word1);
1318 xfree (word2);
1320 return 0;
1323 /* **************************************************************** */
1324 /* */
1325 /* How To Do Shell Completion */
1326 /* */
1327 /* **************************************************************** */
1329 #define COMMAND_SEPARATORS ";|&{(`"
1330 /* )} */
1331 #define COMMAND_SEPARATORS_PLUS_WS ";|&{(` \t"
1332 /* )} */
1334 /* check for redirections and other character combinations that are not
1335 command separators */
1336 static int
1337 check_redir (ti)
1338 int ti;
1340 register int this_char, prev_char;
1342 /* Handle the two character tokens `>&', `<&', and `>|'.
1343 We are not in a command position after one of these. */
1344 this_char = rl_line_buffer[ti];
1345 prev_char = (ti > 0) ? rl_line_buffer[ti - 1] : 0;
1347 if ((this_char == '&' && (prev_char == '<' || prev_char == '>')) ||
1348 (this_char == '|' && prev_char == '>'))
1349 return (1);
1350 else if (this_char == '{' && prev_char == '$') /*}*/
1351 return (1);
1352 #if 0 /* Not yet */
1353 else if (this_char == '(' && prev_char == '$') /*)*/
1354 return (1);
1355 else if (this_char == '(' && prev_char == '<') /*)*/
1356 return (1);
1357 #if defined (EXTENDED_GLOB)
1358 else if (extended_glob && this_char == '(' && prev_char == '!') /*)*/
1359 return (1);
1360 #endif
1361 #endif
1362 else if (char_is_quoted (rl_line_buffer, ti))
1363 return (1);
1364 return (0);
1367 #if defined (PROGRAMMABLE_COMPLETION)
1369 * XXX - because of the <= start test, and setting os = s+1, this can
1370 * potentially return os > start. This is probably not what we want to
1371 * happen, but fix later after 2.05a-release.
1373 static int
1374 find_cmd_start (start)
1375 int start;
1377 register int s, os, ns;
1379 os = 0;
1380 /* Flags == SD_NOJMP only because we want to skip over command substitutions
1381 in assignment statements. Have to test whether this affects `standalone'
1382 command substitutions as individual words. */
1383 while (((s = skip_to_delim (rl_line_buffer, os, COMMAND_SEPARATORS, SD_NOJMP|SD_COMPLETE/*|SD_NOSKIPCMD*/)) <= start) &&
1384 rl_line_buffer[s])
1386 /* Handle >| token crudely; treat as > not | */
1387 if (s > 0 && rl_line_buffer[s] == '|' && rl_line_buffer[s-1] == '>')
1389 ns = skip_to_delim (rl_line_buffer, s+1, COMMAND_SEPARATORS, SD_NOJMP|SD_COMPLETE/*|SD_NOSKIPCMD*/);
1390 if (ns > start || rl_line_buffer[ns] == 0)
1391 return os;
1392 os = ns+1;
1393 continue;
1395 /* The only reserved word in COMMAND_SEPARATORS is `{', so handle that
1396 specially, making sure it's in a spot acceptable for reserved words */
1397 if (s >= os && rl_line_buffer[s] == '{')
1399 int pc, nc; /* index of previous non-whitespace, next char */
1400 for (pc = (s > os) ? s - 1 : os; pc > os && whitespace(rl_line_buffer[pc]); pc--)
1402 nc = rl_line_buffer[s+1];
1403 /* must be preceded by a command separator or be the first non-
1404 whitespace character since the last command separator, and
1405 followed by a shell break character (not another `{') to be a reserved word. */
1406 if ((pc > os && (rl_line_buffer[s-1] == '{' || strchr (COMMAND_SEPARATORS, rl_line_buffer[pc]) == 0)) ||
1407 (shellbreak(nc) == 0)) /* }} */
1409 /* Not a reserved word, look for another delim */
1410 ns = skip_to_delim (rl_line_buffer, s+1, COMMAND_SEPARATORS, SD_NOJMP|SD_COMPLETE/*|SD_NOSKIPCMD*/);
1411 if (ns > start || rl_line_buffer[ns] == 0)
1412 return os;
1413 os = ns+1;
1414 continue;
1417 os = s+1;
1419 return os;
1422 static int
1423 find_cmd_end (end)
1424 int end;
1426 register int e;
1428 e = skip_to_delim (rl_line_buffer, end, COMMAND_SEPARATORS, SD_NOJMP|SD_COMPLETE);
1429 return e;
1432 static char *
1433 find_cmd_name (start, sp, ep)
1434 int start;
1435 int *sp, *ep;
1437 char *name;
1438 register int s, e;
1440 for (s = start; whitespace (rl_line_buffer[s]); s++)
1443 /* skip until a shell break character */
1444 e = skip_to_delim (rl_line_buffer, s, "()<>;&| \t\n", SD_NOJMP|SD_COMPLETE);
1446 name = substring (rl_line_buffer, s, e);
1448 if (sp)
1449 *sp = s;
1450 if (ep)
1451 *ep = e;
1453 return (name);
1456 static char *
1457 prog_complete_return (text, matchnum)
1458 const char *text;
1459 int matchnum;
1461 static int ind;
1463 if (matchnum == 0)
1464 ind = 0;
1466 if (prog_complete_matches == 0 || prog_complete_matches[ind] == 0)
1467 return (char *)NULL;
1468 return (prog_complete_matches[ind++]);
1471 #endif /* PROGRAMMABLE_COMPLETION */
1473 /* Try and catch completion attempts that are syntax errors or otherwise
1474 invalid. */
1475 static int
1476 invalid_completion (text, ind)
1477 const char *text;
1478 int ind;
1480 int pind;
1482 /* If we don't catch these here, the next clause will */
1483 if (ind > 0 && rl_line_buffer[ind] == '(' && /*)*/
1484 member (rl_line_buffer[ind-1], "$<>"))
1485 return 0;
1487 pind = ind - 1;
1488 while (pind > 0 && whitespace (rl_line_buffer[pind]))
1489 pind--;
1490 /* If we have only whitespace preceding a paren, it's valid */
1491 if (ind >= 0 && pind <= 0 && rl_line_buffer[ind] == '(') /*)*/
1492 return 0;
1493 /* Flag the invalid completions, which are mostly syntax errors */
1494 if (ind > 0 && rl_line_buffer[ind] == '(' && /*)*/
1495 member (rl_line_buffer[pind], COMMAND_SEPARATORS) == 0)
1496 return 1;
1498 return 0;
1501 /* Do some completion on TEXT. The indices of TEXT in RL_LINE_BUFFER are
1502 at START and END. Return an array of matches, or NULL if none. */
1503 static char **
1504 attempt_shell_completion (text, start, end)
1505 const char *text;
1506 int start, end;
1508 int in_command_position, ti, qc, dflags;
1509 char **matches, *command_separator_chars;
1510 #if defined (PROGRAMMABLE_COMPLETION)
1511 int have_progcomps, was_assignment;
1512 COMPSPEC *iw_compspec;
1513 #endif
1515 command_separator_chars = COMMAND_SEPARATORS;
1516 matches = (char **)NULL;
1517 rl_ignore_some_completions_function = filename_completion_ignore;
1519 rl_filename_quote_characters = default_filename_quote_characters;
1520 set_filename_bstab (rl_filename_quote_characters);
1521 set_directory_hook ();
1522 rl_filename_stat_hook = bush_filename_stat_hook;
1524 rl_sort_completion_matches = 1; /* sort by default */
1526 /* Determine if this could be a command word. It is if it appears at
1527 the start of the line (ignoring preceding whitespace), or if it
1528 appears after a character that separates commands. It cannot be a
1529 command word if we aren't at the top-level prompt. */
1530 ti = start - 1;
1531 qc = -1;
1533 while ((ti > -1) && (whitespace (rl_line_buffer[ti])))
1534 ti--;
1536 #if 1
1537 /* If this is an open quote, maybe we're trying to complete a quoted
1538 command name. */
1539 if (ti >= 0 && (rl_line_buffer[ti] == '"' || rl_line_buffer[ti] == '\''))
1541 qc = rl_line_buffer[ti];
1542 ti--;
1543 while (ti > -1 && (whitespace (rl_line_buffer[ti])))
1544 ti--;
1546 #endif
1548 in_command_position = 0;
1549 if (ti < 0)
1551 /* Only do command completion at the start of a line when we
1552 are prompting at the top level. */
1553 if (current_prompt_string == ps1_prompt)
1554 in_command_position++;
1555 else if (parser_in_command_position ())
1556 in_command_position++;
1558 else if (member (rl_line_buffer[ti], command_separator_chars))
1560 in_command_position++;
1562 if (check_redir (ti) == 1)
1563 in_command_position = 0;
1565 else
1567 /* This still could be in command position. It is possible
1568 that all of the previous words on the line are variable
1569 assignments. */
1572 if (in_command_position && invalid_completion (text, ti))
1574 rl_attempted_completion_over = 1;
1575 return ((char **)NULL);
1578 /* Check that we haven't incorrectly flagged a closed command substitution
1579 as indicating we're in a command position. */
1580 if (in_command_position && ti >= 0 && rl_line_buffer[ti] == '`' &&
1581 *text != '`' && unclosed_pair (rl_line_buffer, end, "`") == 0)
1582 in_command_position = 0;
1584 /* Special handling for command substitution. If *TEXT is a backquote,
1585 it can be the start or end of an old-style command substitution, or
1586 unmatched. If it's unmatched, both calls to unclosed_pair will
1587 succeed. Don't bother if readline found a single quote and we are
1588 completing on the substring. */
1589 if (*text == '`' && rl_completion_quote_character != '\'' &&
1590 (in_command_position || (unclosed_pair (rl_line_buffer, start, "`") &&
1591 unclosed_pair (rl_line_buffer, end, "`"))))
1592 matches = rl_completion_matches (text, command_subst_completion_function);
1594 #if defined (PROGRAMMABLE_COMPLETION)
1595 /* Attempt programmable completion. */
1596 have_progcomps = prog_completion_enabled && (progcomp_size () > 0);
1597 iw_compspec = progcomp_search (INITIALWORD);
1598 if (matches == 0 &&
1599 (in_command_position == 0 || text[0] == '\0' || (in_command_position && iw_compspec)) &&
1600 current_prompt_string == ps1_prompt)
1602 int s, e, s1, e1, os, foundcs;
1603 char *n;
1605 /* XXX - don't free the members */
1606 if (prog_complete_matches)
1607 free (prog_complete_matches);
1608 prog_complete_matches = (char **)NULL;
1610 os = start;
1611 n = 0;
1612 was_assignment = 0;
1613 s = find_cmd_start (os);
1614 e = find_cmd_end (end);
1617 /* Don't read past the end of rl_line_buffer */
1618 if (s > rl_end)
1620 s1 = s = e1;
1621 break;
1623 /* Or past point if point is within an assignment statement */
1624 else if (was_assignment && s > rl_point)
1626 s1 = s = e1;
1627 break;
1629 /* Skip over assignment statements preceding a command name. If we
1630 don't find a command name at all, we can perform command name
1631 completion. If we find a partial command name, we should perform
1632 command name completion on it. */
1633 FREE (n);
1634 n = find_cmd_name (s, &s1, &e1);
1635 s = e1 + 1;
1637 while (was_assignment = assignment (n, 0));
1638 s = s1; /* reset to index where name begins */
1640 /* s == index of where command name begins (reset above)
1641 e == end of current command, may be end of line
1642 s1 = index of where command name begins
1643 e1 == index of where command name ends
1644 start == index of where word to be completed begins
1645 end == index of where word to be completed ends
1646 if (s == start) we are doing command word completion for sure
1647 if (e1 == end) we are at the end of the command name and completing it */
1648 if (start == 0 && end == 0 && e != 0 && text[0] == '\0') /* beginning of non-empty line */
1649 foundcs = 0;
1650 else if (start == end && start == s1 && e != 0 && e1 > end) /* beginning of command name, leading whitespace */
1651 foundcs = 0;
1652 else if (e == 0 && e == s && text[0] == '\0' && have_progcomps) /* beginning of empty line */
1653 prog_complete_matches = programmable_completions (EMPTYCMD, text, s, e, &foundcs);
1654 else if (start == end && text[0] == '\0' && s1 > start && whitespace (rl_line_buffer[start]))
1655 foundcs = 0; /* whitespace before command name */
1656 else if (e > s && was_assignment == 0 && e1 == end && rl_line_buffer[e] == 0 && whitespace (rl_line_buffer[e-1]) == 0)
1658 /* not assignment statement, but still want to perform command
1659 completion if we are composing command word. */
1660 foundcs = 0;
1661 in_command_position = s == start && STREQ (n, text); /* XXX */
1663 else if (e > s && was_assignment == 0 && have_progcomps)
1665 prog_complete_matches = programmable_completions (n, text, s, e, &foundcs);
1666 /* command completion if programmable completion fails */
1667 /* If we have a completion for the initial word, we can prefer that */
1668 in_command_position = s == start && (iw_compspec || STREQ (n, text)); /* XXX */
1669 if (iw_compspec && in_command_position)
1670 foundcs = 0;
1672 /* empty command name following command separator */
1673 else if (s >= e && n[0] == '\0' && text[0] == '\0' && start > 0 &&
1674 was_assignment == 0 && member (rl_line_buffer[start-1], COMMAND_SEPARATORS))
1676 foundcs = 0;
1677 in_command_position = 1;
1679 else if (s >= e && n[0] == '\0' && text[0] == '\0' && start > 0)
1681 foundcs = 0; /* empty command name following optional assignments */
1682 in_command_position += was_assignment;
1684 else if (s == start && e == end && STREQ (n, text) && start > 0)
1686 foundcs = 0; /* partial command name following assignments */
1687 in_command_position = 1;
1689 else
1690 foundcs = 0;
1692 /* If we have defined a compspec for the initial (command) word, call
1693 it and process the results like any other programmable completion. */
1694 if (in_command_position && have_progcomps && foundcs == 0 && iw_compspec)
1695 prog_complete_matches = programmable_completions (INITIALWORD, text, s, e, &foundcs);
1697 FREE (n);
1698 /* XXX - if we found a COMPSPEC for the command, just return whatever
1699 the programmable completion code returns, and disable the default
1700 filename completion that readline will do unless the COPT_DEFAULT
1701 option has been set with the `-o default' option to complete or
1702 compopt. */
1703 if (foundcs)
1705 pcomp_set_readline_variables (foundcs, 1);
1706 /* Turn what the programmable completion code returns into what
1707 readline wants. I should have made compute_lcd_of_matches
1708 external... */
1709 matches = rl_completion_matches (text, prog_complete_return);
1710 if ((foundcs & COPT_DEFAULT) == 0)
1711 rl_attempted_completion_over = 1; /* no default */
1712 if (matches || ((foundcs & COPT_BUSHDEFAULT) == 0))
1713 return (matches);
1716 #endif
1718 if (matches == 0)
1720 dflags = 0;
1721 if (in_command_position)
1722 dflags |= DEFCOMP_CMDPOS;
1723 matches = bush_default_completion (text, start, end, qc, dflags);
1726 return matches;
1729 char **
1730 bush_default_completion (text, start, end, qc, compflags)
1731 const char *text;
1732 int start, end, qc, compflags;
1734 char **matches, *t;
1736 matches = (char **)NULL;
1738 /* New posix-style command substitution or variable name? */
1739 if (*text == '$')
1741 if (qc != '\'' && text[1] == '(') /* ) */
1742 matches = rl_completion_matches (text, command_subst_completion_function);
1743 else
1745 matches = rl_completion_matches (text, variable_completion_function);
1746 /* If a single match, see if it expands to a directory name and append
1747 a slash if it does. This requires us to expand the variable name,
1748 so we don't want to display errors if the variable is unset. This
1749 can happen with dynamic variables whose value has never been
1750 requested. */
1751 if (matches && matches[0] && matches[1] == 0)
1753 t = savestring (matches[0]);
1754 bush_filename_stat_hook (&t);
1755 /* doesn't use test_for_directory because that performs tilde
1756 expansion */
1757 if (file_isdir (t))
1758 rl_completion_append_character = '/';
1759 free (t);
1764 /* If the word starts in `~', and there is no slash in the word, then
1765 try completing this word as a username. */
1766 if (matches == 0 && *text == '~' && mbschr (text, '/') == 0)
1767 matches = rl_completion_matches (text, rl_username_completion_function);
1769 /* Another one. Why not? If the word starts in '@', then look through
1770 the world of known hostnames for completion first. */
1771 if (matches == 0 && perform_hostname_completion && *text == '@')
1772 matches = rl_completion_matches (text, hostname_completion_function);
1774 /* And last, (but not least) if this word is in a command position, then
1775 complete over possible command names, including aliases, functions,
1776 and command names. */
1777 if (matches == 0 && (compflags & DEFCOMP_CMDPOS))
1779 /* If END == START and text[0] == 0, we are trying to complete an empty
1780 command word. */
1781 if (no_empty_command_completion && end == start && text[0] == '\0')
1783 matches = (char **)NULL;
1784 rl_ignore_some_completions_function = bush_ignore_everything;
1786 else
1788 #define CMD_IS_DIR(x) (absolute_pathname(x) == 0 && absolute_program(x) == 0 && *(x) != '~' && test_for_directory (x))
1790 dot_in_path = 0;
1791 matches = rl_completion_matches (text, command_word_completion_function);
1793 /* If we are attempting command completion and nothing matches, we
1794 do not want readline to perform filename completion for us. We
1795 still want to be able to complete partial pathnames, so set the
1796 completion ignore function to something which will remove
1797 filenames and leave directories in the match list. */
1798 if (matches == (char **)NULL)
1799 rl_ignore_some_completions_function = bush_ignore_filenames;
1800 else if (matches[1] == 0 && CMD_IS_DIR(matches[0]) && dot_in_path == 0)
1801 /* If we found a single match, without looking in the current
1802 directory (because it's not in $PATH), but the found name is
1803 also a command in the current directory, suppress appending any
1804 terminating character, since it's ambiguous. */
1806 rl_completion_suppress_append = 1;
1807 rl_filename_completion_desired = 0;
1809 else if (matches[0] && matches[1] && STREQ (matches[0], matches[1]) && CMD_IS_DIR (matches[0]))
1810 /* There are multiple instances of the same match (duplicate
1811 completions haven't yet been removed). In this case, all of
1812 the matches will be the same, and the duplicate removal code
1813 will distill them all down to one. We turn on
1814 rl_completion_suppress_append for the same reason as above.
1815 Remember: we only care if there's eventually a single unique
1816 completion. If there are multiple completions this won't
1817 make a difference and the problem won't occur. */
1819 rl_completion_suppress_append = 1;
1820 rl_filename_completion_desired = 0;
1825 /* This could be a globbing pattern, so try to expand it using pathname
1826 expansion. */
1827 if (!matches && completion_glob_pattern ((char *)text))
1829 matches = rl_completion_matches (text, glob_complete_word);
1830 /* A glob expression that matches more than one filename is problematic.
1831 If we match more than one filename, punt. */
1832 if (matches && matches[1] && rl_completion_type == TAB)
1834 strvec_dispose (matches);
1835 matches = (char **)0;
1837 else if (matches && matches[1] && rl_completion_type == '!')
1839 rl_completion_suppress_append = 1;
1840 rl_filename_completion_desired = 0;
1844 return (matches);
1847 static int
1848 bush_command_name_stat_hook (name)
1849 char **name;
1851 char *cname, *result;
1853 /* If it's not something we're going to look up in $PATH, just call the
1854 normal filename stat hook. */
1855 if (absolute_program (*name))
1856 return (bush_filename_stat_hook (name));
1858 cname = *name;
1859 /* XXX - we could do something here with converting aliases, builtins,
1860 and functions into something that came out as executable, but we don't. */
1861 result = search_for_command (cname, 0);
1862 if (result)
1864 *name = result;
1865 return 1;
1867 return 0;
1870 static int
1871 executable_completion (filename, searching_path)
1872 const char *filename;
1873 int searching_path;
1875 char *f;
1876 int r;
1878 f = savestring (filename);
1879 bush_directory_completion_hook (&f);
1881 r = searching_path ? executable_file (f) : executable_or_directory (f);
1882 free (f);
1883 return r;
1886 /* This is the function to call when the word to complete is in a position
1887 where a command word can be found. It grovels $PATH, looking for commands
1888 that match. It also scans aliases, function names, and the shell_builtin
1889 table. */
1890 char *
1891 command_word_completion_function (hint_text, state)
1892 const char *hint_text;
1893 int state;
1895 static char *hint = (char *)NULL;
1896 static char *path = (char *)NULL;
1897 static char *val = (char *)NULL;
1898 static char *filename_hint = (char *)NULL;
1899 static char *fnhint = (char *)NULL;
1900 static char *dequoted_hint = (char *)NULL;
1901 static char *directory_part = (char *)NULL;
1902 static char **glob_matches = (char **)NULL;
1903 static int path_index, hint_len, istate, igncase;
1904 static int mapping_over, local_index, searching_path, hint_is_dir;
1905 static int old_glob_ignore_case, globpat;
1906 static SHELL_VAR **varlist = (SHELL_VAR **)NULL;
1907 #if defined (ALIAS)
1908 static alias_t **alias_list = (alias_t **)NULL;
1909 #endif /* ALIAS */
1910 char *temp, *cval;
1912 /* We have to map over the possibilities for command words. If we have
1913 no state, then make one just for that purpose. */
1914 if (state == 0)
1916 rl_filename_stat_hook = bush_command_name_stat_hook;
1918 if (dequoted_hint && dequoted_hint != hint)
1919 free (dequoted_hint);
1920 if (hint)
1921 free (hint);
1923 mapping_over = searching_path = 0;
1924 hint_is_dir = CMD_IS_DIR (hint_text);
1925 val = (char *)NULL;
1927 temp = rl_variable_value ("completion-ignore-case");
1928 igncase = RL_BOOLEAN_VARIABLE_VALUE (temp);
1930 if (glob_matches)
1932 free (glob_matches);
1933 glob_matches = (char **)NULL;
1936 globpat = completion_glob_pattern ((char *)hint_text);
1938 /* If this is an absolute program name, do not check it against
1939 aliases, reserved words, functions or builtins. We must check
1940 whether or not it is unique, and, if so, whether that filename
1941 is executable. */
1942 if (globpat || absolute_program (hint_text))
1944 /* Perform tilde expansion on what's passed, so we don't end up
1945 passing filenames with tildes directly to stat(). The rest of
1946 the shell doesn't do variable expansion on the word following
1947 the tilde, so we don't do it here even if direxpand is set. */
1948 if (*hint_text == '~')
1950 hint = bush_tilde_expand (hint_text, 0);
1951 directory_part = savestring (hint_text);
1952 temp = strchr (directory_part, '/');
1953 if (temp)
1954 *temp = 0;
1955 else
1957 free (directory_part);
1958 directory_part = (char *)NULL;
1961 else if (dircomplete_expand)
1963 hint = savestring (hint_text);
1964 bush_directory_completion_hook (&hint);
1966 else
1967 hint = savestring (hint_text);
1969 dequoted_hint = hint;
1970 /* If readline's completer found a quote character somewhere, but
1971 didn't set the quote character, there must have been a quote
1972 character embedded in the filename. It can't be at the start of
1973 the filename, so we need to dequote the filename before we look
1974 in the file system for it. */
1975 if (rl_completion_found_quote && rl_completion_quote_character == 0)
1977 dequoted_hint = bush_dequote_filename (hint, 0);
1978 free (hint);
1979 hint = dequoted_hint;
1981 hint_len = strlen (hint);
1983 if (filename_hint)
1984 free (filename_hint);
1986 fnhint = filename_hint = savestring (hint);
1988 istate = 0;
1990 if (globpat)
1992 mapping_over = 5;
1993 goto globword;
1995 else
1997 if (dircomplete_expand && path_dot_or_dotdot (filename_hint))
1999 dircomplete_expand = 0;
2000 set_directory_hook ();
2001 dircomplete_expand = 1;
2003 mapping_over = 4;
2004 goto inner;
2008 dequoted_hint = hint = savestring (hint_text);
2009 hint_len = strlen (hint);
2011 if (rl_completion_found_quote && rl_completion_quote_character == 0)
2012 dequoted_hint = bush_dequote_filename (hint, 0);
2014 path = get_string_value ("PATH");
2015 path_index = dot_in_path = 0;
2017 /* Initialize the variables for each type of command word. */
2018 local_index = 0;
2020 if (varlist)
2021 free (varlist);
2023 varlist = all_visible_functions ();
2025 #if defined (ALIAS)
2026 if (alias_list)
2027 free (alias_list);
2029 alias_list = all_aliases ();
2030 #endif /* ALIAS */
2033 /* mapping_over says what we are currently hacking. Note that every case
2034 in this list must fall through when there are no more possibilities. */
2036 switch (mapping_over)
2038 case 0: /* Aliases come first. */
2039 #if defined (ALIAS)
2040 while (alias_list && alias_list[local_index])
2042 register char *alias;
2044 alias = alias_list[local_index++]->name;
2046 if (igncase == 0 && (STREQN (alias, hint, hint_len)))
2047 return (savestring (alias));
2048 else if (igncase && strncasecmp (alias, hint, hint_len) == 0)
2049 return (savestring (alias));
2051 #endif /* ALIAS */
2052 local_index = 0;
2053 mapping_over++;
2055 case 1: /* Then shell reserved words. */
2057 while (word_token_alist[local_index].word)
2059 register char *reserved_word;
2061 reserved_word = word_token_alist[local_index++].word;
2063 if (STREQN (reserved_word, hint, hint_len))
2064 return (savestring (reserved_word));
2066 local_index = 0;
2067 mapping_over++;
2070 case 2: /* Then function names. */
2071 while (varlist && varlist[local_index])
2073 register char *varname;
2075 varname = varlist[local_index++]->name;
2077 /* Honor completion-ignore-case for shell function names. */
2078 if (igncase == 0 && (STREQN (varname, hint, hint_len)))
2079 return (savestring (varname));
2080 else if (igncase && strncasecmp (varname, hint, hint_len) == 0)
2081 return (savestring (varname));
2083 local_index = 0;
2084 mapping_over++;
2086 case 3: /* Then shell builtins. */
2087 for (; local_index < num_shell_builtins; local_index++)
2089 /* Ignore it if it doesn't have a function pointer or if it
2090 is not currently enabled. */
2091 if (!shell_builtins[local_index].function ||
2092 (shell_builtins[local_index].flags & BUILTIN_ENABLED) == 0)
2093 continue;
2095 if (STREQN (shell_builtins[local_index].name, hint, hint_len))
2097 int i = local_index++;
2099 return (savestring (shell_builtins[i].name));
2102 local_index = 0;
2103 mapping_over++;
2106 globword:
2107 /* Limited support for completing command words with globbing chars. Only
2108 a single match (multiple matches that end up reducing the number of
2109 characters in the common prefix are bad) will ever be returned on
2110 regular completion. */
2111 if (globpat)
2113 if (state == 0)
2115 glob_ignore_case = igncase;
2116 glob_matches = shell_glob_filename (hint, 0);
2117 glob_ignore_case = old_glob_ignore_case;
2119 if (GLOB_FAILED (glob_matches) || glob_matches == 0)
2121 glob_matches = (char **)NULL;
2122 return ((char *)NULL);
2125 local_index = 0;
2127 if (glob_matches[1] && rl_completion_type == TAB) /* multiple matches are bad */
2128 return ((char *)NULL);
2131 while (val = glob_matches[local_index++])
2133 if (executable_or_directory (val))
2135 if (*hint_text == '~' && directory_part)
2137 temp = maybe_restore_tilde (val, directory_part);
2138 free (val);
2139 val = temp;
2141 return (val);
2143 free (val);
2146 glob_ignore_case = old_glob_ignore_case;
2147 return ((char *)NULL);
2150 /* If the text passed is a directory in the current directory, return it
2151 as a possible match. Executables in directories in the current
2152 directory can be specified using relative pathnames and successfully
2153 executed even when `.' is not in $PATH. */
2154 if (hint_is_dir)
2156 hint_is_dir = 0; /* only return the hint text once */
2157 return (savestring (hint_text));
2160 /* Repeatedly call filename_completion_function while we have
2161 members of PATH left. Question: should we stat each file?
2162 Answer: we call executable_file () on each file. */
2163 outer:
2165 istate = (val != (char *)NULL);
2167 if (istate == 0)
2169 char *current_path;
2171 /* Get the next directory from the path. If there is none, then we
2172 are all done. */
2173 if (path == 0 || path[path_index] == 0 ||
2174 (current_path = extract_colon_unit (path, &path_index)) == 0)
2175 return ((char *)NULL);
2177 searching_path = 1;
2178 if (*current_path == 0)
2180 free (current_path);
2181 current_path = savestring (".");
2184 if (*current_path == '~')
2186 char *t;
2188 t = bush_tilde_expand (current_path, 0);
2189 free (current_path);
2190 current_path = t;
2193 if (current_path[0] == '.' && current_path[1] == '\0')
2194 dot_in_path = 1;
2196 if (fnhint && fnhint != filename_hint)
2197 free (fnhint);
2198 if (filename_hint)
2199 free (filename_hint);
2201 filename_hint = sh_makepath (current_path, hint, 0);
2202 /* Need a quoted version (though it doesn't matter much in most
2203 cases) because rl_filename_completion_function dequotes the
2204 filename it gets, assuming that it's been quoted as part of
2205 the input line buffer. */
2206 if (strpbrk (filename_hint, "\"'\\"))
2207 fnhint = sh_backslash_quote (filename_hint, filename_bstab, 0);
2208 else
2209 fnhint = filename_hint;
2210 free (current_path); /* XXX */
2213 inner:
2214 val = rl_filename_completion_function (fnhint, istate);
2215 if (mapping_over == 4 && dircomplete_expand)
2216 set_directory_hook ();
2218 istate = 1;
2220 if (val == 0)
2222 /* If the hint text is an absolute program, then don't bother
2223 searching through PATH. */
2224 if (absolute_program (hint))
2225 return ((char *)NULL);
2227 goto outer;
2229 else
2231 int match, freetemp;
2233 if (absolute_program (hint))
2235 if (igncase == 0)
2236 match = strncmp (val, hint, hint_len) == 0;
2237 else
2238 match = strncasecmp (val, hint, hint_len) == 0;
2240 /* If we performed tilde expansion, restore the original
2241 filename. */
2242 if (*hint_text == '~')
2243 temp = maybe_restore_tilde (val, directory_part);
2244 else
2245 temp = savestring (val);
2246 freetemp = 1;
2248 else
2250 temp = strrchr (val, '/');
2252 if (temp)
2254 temp++;
2255 if (igncase == 0)
2256 freetemp = match = strncmp (temp, hint, hint_len) == 0;
2257 else
2258 freetemp = match = strncasecmp (temp, hint, hint_len) == 0;
2259 if (match)
2260 temp = savestring (temp);
2262 else
2263 freetemp = match = 0;
2266 /* If we have found a match, and it is an executable file, return it.
2267 We don't return directory names when searching $PATH, since the
2268 bush execution code won't find executables in directories which
2269 appear in directories in $PATH when they're specified using
2270 relative pathnames. */
2271 #if 0
2272 /* If we're not searching $PATH and we have a relative pathname, we
2273 need to re-canonicalize it before testing whether or not it's an
2274 executable or a directory so the shell treats .. relative to $PWD
2275 according to the physical/logical option. The shell already
2276 canonicalizes the directory name in order to tell readline where
2277 to look, so not doing it here will be inconsistent. */
2278 /* XXX -- currently not used -- will introduce more inconsistency,
2279 since shell does not canonicalize ../foo before passing it to
2280 shell_execve(). */
2281 if (match && searching_path == 0 && *val == '.')
2283 char *t, *t1;
2285 t = get_working_directory ("command-word-completion");
2286 t1 = make_absolute (val, t);
2287 free (t);
2288 cval = sh_canonpath (t1, PATH_CHECKDOTDOT|PATH_CHECKEXISTS);
2290 else
2291 #endif
2292 cval = val;
2294 if (match && executable_completion ((searching_path ? val : cval), searching_path))
2296 if (cval != val)
2297 free (cval);
2298 free (val);
2299 val = ""; /* So it won't be NULL. */
2300 return (temp);
2302 else
2304 if (freetemp)
2305 free (temp);
2306 if (cval != val)
2307 free (cval);
2308 free (val);
2309 goto inner;
2314 /* Completion inside an unterminated command substitution. */
2315 static char *
2316 command_subst_completion_function (text, state)
2317 const char *text;
2318 int state;
2320 static char **matches = (char **)NULL;
2321 static const char *orig_start;
2322 static char *filename_text = (char *)NULL;
2323 static int cmd_index, start_len;
2324 char *value;
2326 if (state == 0)
2328 if (filename_text)
2329 free (filename_text);
2330 orig_start = text;
2331 if (*text == '`')
2332 text++;
2333 else if (*text == '$' && text[1] == '(') /* ) */
2334 text += 2;
2335 /* If the text was quoted, suppress any quote character that the
2336 readline completion code would insert. */
2337 rl_completion_suppress_quote = 1;
2338 start_len = text - orig_start;
2339 filename_text = savestring (text);
2340 if (matches)
2341 free (matches);
2344 * At this point we can entertain the idea of re-parsing
2345 * `filename_text' into a (possibly incomplete) command name and
2346 * arguments, and doing completion based on that. This is
2347 * currently very rudimentary, but it is a small improvement.
2349 for (value = filename_text + strlen (filename_text) - 1; value > filename_text; value--)
2350 if (whitespace (*value) || member (*value, COMMAND_SEPARATORS))
2351 break;
2352 if (value <= filename_text)
2353 matches = rl_completion_matches (filename_text, command_word_completion_function);
2354 else
2356 value++;
2357 start_len += value - filename_text;
2358 if (whitespace (value[-1]))
2359 matches = rl_completion_matches (value, rl_filename_completion_function);
2360 else
2361 matches = rl_completion_matches (value, command_word_completion_function);
2364 /* If there is more than one match, rl_completion_matches has already
2365 put the lcd in matches[0]. Skip over it. */
2366 cmd_index = matches && matches[0] && matches[1];
2368 /* If there's a single match and it's a directory, set the append char
2369 to the expected `/'. Otherwise, don't append anything. */
2370 if (matches && matches[0] && matches[1] == 0 && test_for_directory (matches[0]))
2371 rl_completion_append_character = '/';
2372 else
2373 rl_completion_suppress_append = 1;
2376 if (matches == 0 || matches[cmd_index] == 0)
2378 rl_filename_quoting_desired = 0; /* disable quoting */
2379 return ((char *)NULL);
2381 else
2383 value = (char *)xmalloc (1 + start_len + strlen (matches[cmd_index]));
2385 if (start_len == 1)
2386 value[0] = *orig_start;
2387 else
2388 strncpy (value, orig_start, start_len);
2390 strcpy (value + start_len, matches[cmd_index]);
2392 cmd_index++;
2393 return (value);
2397 /* Okay, now we write the entry_function for variable completion. */
2398 static char *
2399 variable_completion_function (text, state)
2400 const char *text;
2401 int state;
2403 static char **varlist = (char **)NULL;
2404 static int varlist_index;
2405 static char *varname = (char *)NULL;
2406 static int first_char, first_char_loc;
2408 if (!state)
2410 if (varname)
2411 free (varname);
2413 first_char_loc = 0;
2414 first_char = text[0];
2416 if (first_char == '$')
2417 first_char_loc++;
2419 if (text[first_char_loc] == '{')
2420 first_char_loc++;
2422 varname = savestring (text + first_char_loc);
2424 if (varlist)
2425 strvec_dispose (varlist);
2427 varlist = all_variables_matching_prefix (varname);
2428 varlist_index = 0;
2431 if (!varlist || !varlist[varlist_index])
2433 return ((char *)NULL);
2435 else
2437 char *value;
2439 value = (char *)xmalloc (4 + strlen (varlist[varlist_index]));
2441 if (first_char_loc)
2443 value[0] = first_char;
2444 if (first_char_loc == 2)
2445 value[1] = '{';
2448 strcpy (value + first_char_loc, varlist[varlist_index]);
2449 if (first_char_loc == 2)
2450 strcat (value, "}");
2452 varlist_index++;
2453 return (value);
2457 /* How about a completion function for hostnames? */
2458 static char *
2459 hostname_completion_function (text, state)
2460 const char *text;
2461 int state;
2463 static char **list = (char **)NULL;
2464 static int list_index = 0;
2465 static int first_char, first_char_loc;
2467 /* If we don't have any state, make some. */
2468 if (state == 0)
2470 FREE (list);
2472 list = (char **)NULL;
2474 first_char_loc = 0;
2475 first_char = *text;
2477 if (first_char == '@')
2478 first_char_loc++;
2480 list = hostnames_matching ((char *)text+first_char_loc);
2481 list_index = 0;
2484 if (list && list[list_index])
2486 char *t;
2488 t = (char *)xmalloc (2 + strlen (list[list_index]));
2489 *t = first_char;
2490 strcpy (t + first_char_loc, list[list_index]);
2491 list_index++;
2492 return (t);
2495 return ((char *)NULL);
2499 * A completion function for service names from /etc/services (or wherever).
2501 char *
2502 bush_servicename_completion_function (text, state)
2503 const char *text;
2504 int state;
2506 #if defined (__WIN32__) || defined (__OPENNT) || !defined (HAVE_GETSERVENT)
2507 return ((char *)NULL);
2508 #else
2509 static char *sname = (char *)NULL;
2510 static struct servent *srvent;
2511 static int snamelen;
2512 char *value;
2513 char **alist, *aentry;
2514 int afound;
2516 if (state == 0)
2518 FREE (sname);
2520 sname = savestring (text);
2521 snamelen = strlen (sname);
2522 setservent (0);
2525 while (srvent = getservent ())
2527 afound = 0;
2528 if (snamelen == 0 || (STREQN (sname, srvent->s_name, snamelen)))
2529 break;
2530 /* Not primary, check aliases */
2531 for (alist = srvent->s_aliases; *alist; alist++)
2533 aentry = *alist;
2534 if (STREQN (sname, aentry, snamelen))
2536 afound = 1;
2537 break;
2541 if (afound)
2542 break;
2545 if (srvent == 0)
2547 endservent ();
2548 return ((char *)NULL);
2551 value = afound ? savestring (aentry) : savestring (srvent->s_name);
2552 return value;
2553 #endif
2557 * A completion function for group names from /etc/group (or wherever).
2559 char *
2560 bush_groupname_completion_function (text, state)
2561 const char *text;
2562 int state;
2564 #if defined (__WIN32__) || defined (__OPENNT) || !defined (HAVE_GRP_H)
2565 return ((char *)NULL);
2566 #else
2567 static char *gname = (char *)NULL;
2568 static struct group *grent;
2569 static int gnamelen;
2570 char *value;
2572 if (state == 0)
2574 FREE (gname);
2575 gname = savestring (text);
2576 gnamelen = strlen (gname);
2578 setgrent ();
2581 while (grent = getgrent ())
2583 if (gnamelen == 0 || (STREQN (gname, grent->gr_name, gnamelen)))
2584 break;
2587 if (grent == 0)
2589 endgrent ();
2590 return ((char *)NULL);
2593 value = savestring (grent->gr_name);
2594 return (value);
2595 #endif
2598 /* Functions to perform history and alias expansions on the current line. */
2600 #if defined (BANG_HISTORY)
2601 /* Perform history expansion on the current line. If no history expansion
2602 is done, pre_process_line() returns what it was passed, so we need to
2603 allocate a new line here. */
2604 static char *
2605 history_expand_line_internal (line)
2606 char *line;
2608 char *new_line;
2609 int old_verify;
2611 old_verify = hist_verify;
2612 hist_verify = 0;
2613 new_line = pre_process_line (line, 0, 0);
2614 hist_verify = old_verify;
2616 return (new_line == line) ? savestring (line) : new_line;
2618 #endif
2620 /* There was an error in expansion. Let the preprocessor print
2621 the error here. */
2622 static void
2623 cleanup_expansion_error ()
2625 char *to_free;
2626 #if defined (BANG_HISTORY)
2627 int old_verify;
2629 old_verify = hist_verify;
2630 hist_verify = 0;
2631 #endif
2633 fprintf (rl_outstream, "\r\n");
2634 to_free = pre_process_line (rl_line_buffer, 1, 0);
2635 #if defined (BANG_HISTORY)
2636 hist_verify = old_verify;
2637 #endif
2638 if (to_free != rl_line_buffer)
2639 FREE (to_free);
2640 putc ('\r', rl_outstream);
2641 rl_forced_update_display ();
2644 /* If NEW_LINE differs from what is in the readline line buffer, add an
2645 undo record to get from the readline line buffer contents to the new
2646 line and make NEW_LINE the current readline line. */
2647 static void
2648 maybe_make_readline_line (new_line)
2649 char *new_line;
2651 if (new_line && strcmp (new_line, rl_line_buffer) != 0)
2653 rl_point = rl_end;
2655 rl_add_undo (UNDO_BEGIN, 0, 0, 0);
2656 rl_delete_text (0, rl_point);
2657 rl_point = rl_end = rl_mark = 0;
2658 rl_insert_text (new_line);
2659 rl_add_undo (UNDO_END, 0, 0, 0);
2663 /* Make NEW_LINE be the current readline line. This frees NEW_LINE. */
2664 static void
2665 set_up_new_line (new_line)
2666 char *new_line;
2668 int old_point, at_end;
2670 old_point = rl_point;
2671 at_end = rl_point == rl_end;
2673 /* If the line was history and alias expanded, then make that
2674 be one thing to undo. */
2675 maybe_make_readline_line (new_line);
2676 free (new_line);
2678 /* Place rl_point where we think it should go. */
2679 if (at_end)
2680 rl_point = rl_end;
2681 else if (old_point < rl_end)
2683 rl_point = old_point;
2684 if (!whitespace (rl_line_buffer[rl_point]))
2685 rl_forward_word (1, 0);
2689 #if defined (ALIAS)
2690 /* Expand aliases in the current readline line. */
2691 static int
2692 alias_expand_line (count, ignore)
2693 int count, ignore;
2695 char *new_line;
2697 new_line = alias_expand (rl_line_buffer);
2699 if (new_line)
2701 set_up_new_line (new_line);
2702 return (0);
2704 else
2706 cleanup_expansion_error ();
2707 return (1);
2710 #endif
2712 #if defined (BANG_HISTORY)
2713 /* History expand the line. */
2714 static int
2715 history_expand_line (count, ignore)
2716 int count, ignore;
2718 char *new_line;
2720 new_line = history_expand_line_internal (rl_line_buffer);
2722 if (new_line)
2724 set_up_new_line (new_line);
2725 return (0);
2727 else
2729 cleanup_expansion_error ();
2730 return (1);
2734 /* Expand history substitutions in the current line and then insert a
2735 space (hopefully close to where we were before). */
2736 static int
2737 tcsh_magic_space (count, ignore)
2738 int count, ignore;
2740 int dist_from_end, old_point;
2742 old_point = rl_point;
2743 dist_from_end = rl_end - rl_point;
2744 if (history_expand_line (count, ignore) == 0)
2746 /* Try a simple heuristic from Stephen Gildea <gildea@intouchsys.com>.
2747 This works if all expansions were before rl_point or if no expansions
2748 were performed. */
2749 rl_point = (old_point == 0) ? old_point : rl_end - dist_from_end;
2750 rl_insert (1, ' ');
2751 return (0);
2753 else
2754 return (1);
2756 #endif /* BANG_HISTORY */
2758 /* History and alias expand the line. */
2759 static int
2760 history_and_alias_expand_line (count, ignore)
2761 int count, ignore;
2763 char *new_line;
2765 new_line = 0;
2766 #if defined (BANG_HISTORY)
2767 new_line = history_expand_line_internal (rl_line_buffer);
2768 #endif
2770 #if defined (ALIAS)
2771 if (new_line)
2773 char *alias_line;
2775 alias_line = alias_expand (new_line);
2776 free (new_line);
2777 new_line = alias_line;
2779 #endif /* ALIAS */
2781 if (new_line)
2783 set_up_new_line (new_line);
2784 return (0);
2786 else
2788 cleanup_expansion_error ();
2789 return (1);
2793 /* History and alias expand the line, then perform the shell word
2794 expansions by calling expand_string. This can't use set_up_new_line()
2795 because we want the variable expansions as a separate undo'able
2796 set of operations. */
2797 static int
2798 shell_expand_line (count, ignore)
2799 int count, ignore;
2801 char *new_line;
2802 WORD_LIST *expanded_string;
2803 WORD_DESC *w;
2805 new_line = 0;
2806 #if defined (BANG_HISTORY)
2807 new_line = history_expand_line_internal (rl_line_buffer);
2808 #endif
2810 #if defined (ALIAS)
2811 if (new_line)
2813 char *alias_line;
2815 alias_line = alias_expand (new_line);
2816 free (new_line);
2817 new_line = alias_line;
2819 #endif /* ALIAS */
2821 if (new_line)
2823 int old_point = rl_point;
2824 int at_end = rl_point == rl_end;
2826 /* If the line was history and alias expanded, then make that
2827 be one thing to undo. */
2828 maybe_make_readline_line (new_line);
2829 free (new_line);
2831 /* If there is variable expansion to perform, do that as a separate
2832 operation to be undone. */
2834 #if 1
2835 w = alloc_word_desc ();
2836 w->word = savestring (rl_line_buffer);
2837 w->flags = rl_explicit_arg ? (W_NOPROCSUB|W_NOCOMSUB) : 0;
2838 expanded_string = expand_word (w, rl_explicit_arg ? Q_HERE_DOCUMENT : 0);
2839 dispose_word (w);
2840 #else
2841 new_line = savestring (rl_line_buffer);
2842 expanded_string = expand_string (new_line, 0);
2843 FREE (new_line);
2844 #endif
2846 if (expanded_string == 0)
2848 new_line = (char *)xmalloc (1);
2849 new_line[0] = '\0';
2851 else
2853 new_line = string_list (expanded_string);
2854 dispose_words (expanded_string);
2857 maybe_make_readline_line (new_line);
2858 free (new_line);
2860 /* Place rl_point where we think it should go. */
2861 if (at_end)
2862 rl_point = rl_end;
2863 else if (old_point < rl_end)
2865 rl_point = old_point;
2866 if (!whitespace (rl_line_buffer[rl_point]))
2867 rl_forward_word (1, 0);
2869 return 0;
2871 else
2873 cleanup_expansion_error ();
2874 return 1;
2878 /* If FIGNORE is set, then don't match files with the given suffixes when
2879 completing filenames. If only one of the possibilities has an acceptable
2880 suffix, delete the others, else just return and let the completer
2881 signal an error. It is called by the completer when real
2882 completions are done on filenames by the completer's internal
2883 function, not for completion lists (M-?) and not on "other"
2884 completion types, such as hostnames or commands. */
2886 static struct ignorevar fignore =
2888 "FIGNORE",
2889 (struct ign *)0,
2891 (char *)0,
2892 (sh_iv_item_func_t *) 0,
2895 static void
2896 _ignore_completion_names (names, name_func)
2897 char **names;
2898 sh_ignore_func_t *name_func;
2900 char **newnames;
2901 int idx, nidx;
2902 char **oldnames;
2903 int oidx;
2905 /* If there is only one completion, see if it is acceptable. If it is
2906 not, free it up. In any case, short-circuit and return. This is a
2907 special case because names[0] is not the prefix of the list of names
2908 if there is only one completion; it is the completion itself. */
2909 if (names[1] == (char *)0)
2911 if (force_fignore)
2912 if ((*name_func) (names[0]) == 0)
2914 free (names[0]);
2915 names[0] = (char *)NULL;
2918 return;
2921 /* Allocate space for array to hold list of pointers to matching
2922 filenames. The pointers are copied back to NAMES when done. */
2923 for (nidx = 1; names[nidx]; nidx++)
2925 newnames = strvec_create (nidx + 1);
2927 if (force_fignore == 0)
2929 oldnames = strvec_create (nidx - 1);
2930 oidx = 0;
2933 newnames[0] = names[0];
2934 for (idx = nidx = 1; names[idx]; idx++)
2936 if ((*name_func) (names[idx]))
2937 newnames[nidx++] = names[idx];
2938 else if (force_fignore == 0)
2939 oldnames[oidx++] = names[idx];
2940 else
2941 free (names[idx]);
2944 newnames[nidx] = (char *)NULL;
2946 /* If none are acceptable then let the completer handle it. */
2947 if (nidx == 1)
2949 if (force_fignore)
2951 free (names[0]);
2952 names[0] = (char *)NULL;
2954 else
2955 free (oldnames);
2957 free (newnames);
2958 return;
2961 if (force_fignore == 0)
2963 while (oidx)
2964 free (oldnames[--oidx]);
2965 free (oldnames);
2968 /* If only one is acceptable, copy it to names[0] and return. */
2969 if (nidx == 2)
2971 free (names[0]);
2972 names[0] = newnames[1];
2973 names[1] = (char *)NULL;
2974 free (newnames);
2975 return;
2978 /* Copy the acceptable names back to NAMES, set the new array end,
2979 and return. */
2980 for (nidx = 1; newnames[nidx]; nidx++)
2981 names[nidx] = newnames[nidx];
2982 names[nidx] = (char *)NULL;
2983 free (newnames);
2986 static int
2987 name_is_acceptable (name)
2988 const char *name;
2990 struct ign *p;
2991 int nlen;
2993 for (nlen = strlen (name), p = fignore.ignores; p->val; p++)
2995 if (nlen > p->len && p->len > 0 && STREQ (p->val, &name[nlen - p->len]))
2996 return (0);
2999 return (1);
3002 #if 0
3003 static int
3004 ignore_dot_names (name)
3005 char *name;
3007 return (name[0] != '.');
3009 #endif
3011 static int
3012 filename_completion_ignore (names)
3013 char **names;
3015 #if 0
3016 if (glob_dot_filenames == 0)
3017 _ignore_completion_names (names, ignore_dot_names);
3018 #endif
3020 setup_ignore_patterns (&fignore);
3022 if (fignore.num_ignores == 0)
3023 return 0;
3025 _ignore_completion_names (names, name_is_acceptable);
3027 return 0;
3030 /* Return 1 if NAME is a directory. NAME undergoes tilde expansion. */
3031 static int
3032 test_for_directory (name)
3033 const char *name;
3035 char *fn;
3036 int r;
3038 fn = bush_tilde_expand (name, 0);
3039 r = file_isdir (fn);
3040 free (fn);
3042 return (r);
3045 static int
3046 test_for_canon_directory (name)
3047 const char *name;
3049 char *fn;
3050 int r;
3052 fn = (*name == '~') ? bush_tilde_expand (name, 0) : savestring (name);
3053 bush_filename_stat_hook (&fn);
3054 r = file_isdir (fn);
3055 free (fn);
3057 return (r);
3060 /* Remove files from NAMES, leaving directories. */
3061 static int
3062 bush_ignore_filenames (names)
3063 char **names;
3065 _ignore_completion_names (names, test_for_directory);
3066 return 0;
3069 static int
3070 bush_progcomp_ignore_filenames (names)
3071 char **names;
3073 _ignore_completion_names (names, test_for_canon_directory);
3074 return 0;
3077 static int
3078 return_zero (name)
3079 const char *name;
3081 return 0;
3084 static int
3085 bush_ignore_everything (names)
3086 char **names;
3088 _ignore_completion_names (names, return_zero);
3089 return 0;
3092 /* Replace a tilde-prefix in VAL with a `~', assuming the user typed it. VAL
3093 is an expanded filename. DIRECTORY_PART is the tilde-prefix portion
3094 of the un-tilde-expanded version of VAL (what the user typed). */
3095 static char *
3096 restore_tilde (val, directory_part)
3097 char *val, *directory_part;
3099 int l, vl, dl2, xl;
3100 char *dh2, *expdir, *ret, *v;
3102 vl = strlen (val);
3104 /* We need to duplicate the expansions readline performs on the directory
3105 portion before passing it to our completion function. */
3106 dh2 = directory_part ? bush_dequote_filename (directory_part, 0) : 0;
3107 bush_directory_expansion (&dh2);
3108 dl2 = strlen (dh2);
3110 expdir = bush_tilde_expand (directory_part, 0);
3111 xl = strlen (expdir);
3112 if (*directory_part == '~' && STREQ (directory_part, expdir))
3114 /* tilde expansion failed, so what should we return? we use what the
3115 user typed. */
3116 v = mbschr (val, '/');
3117 vl = STRLEN (v);
3118 ret = (char *)xmalloc (xl + vl + 2);
3119 strcpy (ret, directory_part);
3120 if (v && *v)
3121 strcpy (ret + xl, v);
3123 free (dh2);
3124 free (expdir);
3126 return ret;
3128 free (expdir);
3131 dh2 = unexpanded but dequoted tilde-prefix
3132 dl2 = length of tilde-prefix
3133 expdir = tilde-expanded tilde-prefix
3134 xl = length of expanded tilde-prefix
3135 l = length of remainder after tilde-prefix
3137 l = (vl - xl) + 1;
3138 if (l <= 0)
3140 free (dh2);
3141 return (savestring (val)); /* XXX - just punt */
3144 ret = (char *)xmalloc (dl2 + 2 + l);
3145 strcpy (ret, dh2);
3146 strcpy (ret + dl2, val + xl);
3148 free (dh2);
3149 return (ret);
3152 static char *
3153 maybe_restore_tilde (val, directory_part)
3154 char *val, *directory_part;
3156 rl_icppfunc_t *save;
3157 char *ret;
3159 save = (dircomplete_expand == 0) ? save_directory_hook () : (rl_icppfunc_t *)0;
3160 ret = restore_tilde (val, directory_part);
3161 if (save)
3162 restore_directory_hook (save);
3163 return ret;
3166 /* Simulate the expansions that will be performed by
3167 rl_filename_completion_function. This must be called with the address of
3168 a pointer to malloc'd memory. */
3169 static void
3170 bush_directory_expansion (dirname)
3171 char **dirname;
3173 char *d, *nd;
3175 d = savestring (*dirname);
3177 if ((rl_directory_rewrite_hook) && (*rl_directory_rewrite_hook) (&d))
3179 free (*dirname);
3180 *dirname = d;
3182 else if (rl_directory_completion_hook && (*rl_directory_completion_hook) (&d))
3184 free (*dirname);
3185 *dirname = d;
3187 else if (rl_completion_found_quote)
3189 nd = bush_dequote_filename (d, rl_completion_quote_character);
3190 free (*dirname);
3191 free (d);
3192 *dirname = nd;
3196 /* If necessary, rewrite directory entry */
3197 static char *
3198 bush_filename_rewrite_hook (fname, fnlen)
3199 char *fname;
3200 int fnlen;
3202 char *conv;
3204 conv = fnx_fromfs (fname, fnlen);
3205 if (conv != fname)
3206 conv = savestring (conv);
3207 return conv;
3210 /* Functions to save and restore the appropriate directory hook */
3211 /* This is not static so the shopt code can call it */
3212 void
3213 set_directory_hook ()
3215 if (dircomplete_expand)
3217 rl_directory_completion_hook = bush_directory_completion_hook;
3218 rl_directory_rewrite_hook = (rl_icppfunc_t *)0;
3220 else
3222 rl_directory_rewrite_hook = bush_directory_completion_hook;
3223 rl_directory_completion_hook = (rl_icppfunc_t *)0;
3227 static rl_icppfunc_t *
3228 save_directory_hook ()
3230 rl_icppfunc_t *ret;
3232 if (dircomplete_expand)
3234 ret = rl_directory_completion_hook;
3235 rl_directory_completion_hook = (rl_icppfunc_t *)NULL;
3237 else
3239 ret = rl_directory_rewrite_hook;
3240 rl_directory_rewrite_hook = (rl_icppfunc_t *)NULL;
3243 return ret;
3246 static void
3247 restore_directory_hook (hookf)
3248 rl_icppfunc_t *hookf;
3250 if (dircomplete_expand)
3251 rl_directory_completion_hook = hookf;
3252 else
3253 rl_directory_rewrite_hook = hookf;
3256 /* Check whether not DIRNAME, with any trailing slash removed, exists. If
3257 SHOULD_DEQUOTE is non-zero, we dequote the directory name first. */
3258 static int
3259 directory_exists (dirname, should_dequote)
3260 const char *dirname;
3261 int should_dequote;
3263 char *new_dirname;
3264 int dirlen, r;
3265 struct stat sb;
3267 /* We save the string and chop the trailing slash because stat/lstat behave
3268 inconsistently if one is present. */
3269 new_dirname = should_dequote ? bush_dequote_filename ((char *)dirname, rl_completion_quote_character) : savestring (dirname);
3270 dirlen = STRLEN (new_dirname);
3271 if (new_dirname[dirlen - 1] == '/')
3272 new_dirname[dirlen - 1] = '\0';
3273 #if defined (HAVE_LSTAT)
3274 r = lstat (new_dirname, &sb) == 0;
3275 #else
3276 r = stat (new_dirname, &sb) == 0;
3277 #endif
3278 free (new_dirname);
3279 return (r);
3282 /* Expand a filename before the readline completion code passes it to stat(2).
3283 The filename will already have had tilde expansion performed. */
3284 static int
3285 bush_filename_stat_hook (dirname)
3286 char **dirname;
3288 char *local_dirname, *new_dirname, *t;
3289 int should_expand_dirname, return_value;
3290 int global_nounset;
3291 WORD_LIST *wl;
3293 local_dirname = *dirname;
3294 should_expand_dirname = return_value = 0;
3295 if (t = mbschr (local_dirname, '$'))
3296 should_expand_dirname = '$';
3297 else if (t = mbschr (local_dirname, '`')) /* XXX */
3298 should_expand_dirname = '`';
3300 if (should_expand_dirname && directory_exists (local_dirname, 0))
3301 should_expand_dirname = 0;
3303 if (should_expand_dirname)
3305 new_dirname = savestring (local_dirname);
3306 /* no error messages, and expand_prompt_string doesn't longjmp so we don't
3307 have to worry about restoring this setting. */
3308 global_nounset = unbound_vars_is_error;
3309 unbound_vars_is_error = 0;
3310 wl = expand_prompt_string (new_dirname, 0, W_NOCOMSUB|W_NOPROCSUB|W_COMPLETE); /* does the right thing */
3311 unbound_vars_is_error = global_nounset;
3312 if (wl)
3314 free (new_dirname);
3315 new_dirname = string_list (wl);
3316 /* Tell the completer we actually expanded something and change
3317 *dirname only if we expanded to something non-null -- stat
3318 behaves unpredictably when passed null or empty strings */
3319 if (new_dirname && *new_dirname)
3321 free (local_dirname); /* XXX */
3322 local_dirname = *dirname = new_dirname;
3323 return_value = STREQ (local_dirname, *dirname) == 0;
3325 else
3326 free (new_dirname);
3327 dispose_words (wl);
3329 else
3330 free (new_dirname);
3333 /* This is very similar to the code in bush_directory_completion_hook below,
3334 but without spelling correction and not worrying about whether or not
3335 we change relative pathnames. */
3336 if (no_symbolic_links == 0 && (local_dirname[0] != '.' || local_dirname[1]))
3338 char *temp1, *temp2;
3340 t = get_working_directory ("symlink-hook");
3341 temp1 = make_absolute (local_dirname, t);
3342 free (t);
3343 temp2 = sh_canonpath (temp1, PATH_CHECKDOTDOT|PATH_CHECKEXISTS);
3345 /* If we can't canonicalize, bail. */
3346 if (temp2 == 0)
3348 free (temp1);
3349 return return_value;
3352 free (local_dirname);
3353 *dirname = temp2;
3354 free (temp1);
3357 return (return_value);
3360 /* Handle symbolic link references and other directory name
3361 expansions while hacking completion. This should return 1 if it modifies
3362 the DIRNAME argument, 0 otherwise. It should make sure not to modify
3363 DIRNAME if it returns 0. */
3364 static int
3365 bush_directory_completion_hook (dirname)
3366 char **dirname;
3368 char *local_dirname, *new_dirname, *t;
3369 int return_value, should_expand_dirname, nextch, closer;
3370 WORD_LIST *wl;
3372 return_value = should_expand_dirname = nextch = closer = 0;
3373 local_dirname = *dirname;
3375 if (t = mbschr (local_dirname, '$'))
3377 should_expand_dirname = '$';
3378 nextch = t[1];
3379 /* Deliberately does not handle the deprecated $[...] arithmetic
3380 expansion syntax */
3381 if (nextch == '(')
3382 closer = ')';
3383 else if (nextch == '{')
3384 closer = '}';
3385 else
3386 nextch = 0;
3388 if (closer)
3390 int p;
3391 char delims[2];
3393 delims[0] = closer; delims[1] = 0;
3394 p = skip_to_delim (t, 1, delims, SD_NOJMP|SD_COMPLETE);
3395 if (t[p] != closer)
3396 should_expand_dirname = 0;
3399 else if (local_dirname[0] == '~')
3400 should_expand_dirname = '~';
3401 else
3403 t = mbschr (local_dirname, '`');
3404 if (t && unclosed_pair (local_dirname, strlen (local_dirname), "`") == 0)
3405 should_expand_dirname = '`';
3408 if (should_expand_dirname && directory_exists (local_dirname, 1))
3409 should_expand_dirname = 0;
3411 if (should_expand_dirname)
3413 new_dirname = savestring (local_dirname);
3414 wl = expand_prompt_string (new_dirname, 0, W_NOCOMSUB|W_NOPROCSUB|W_COMPLETE); /* does the right thing */
3415 if (wl)
3417 *dirname = string_list (wl);
3418 /* Tell the completer to replace the directory name only if we
3419 actually expanded something. */
3420 return_value = STREQ (local_dirname, *dirname) == 0;
3421 free (local_dirname);
3422 free (new_dirname);
3423 dispose_words (wl);
3424 local_dirname = *dirname;
3425 /* XXX - change rl_filename_quote_characters here based on
3426 should_expand_dirname/nextch/closer. This is the only place
3427 custom_filename_quote_characters is modified. */
3428 if (rl_filename_quote_characters && *rl_filename_quote_characters)
3430 int i, j, c;
3431 i = strlen (default_filename_quote_characters);
3432 custom_filename_quote_characters = xrealloc (custom_filename_quote_characters, i+1);
3433 for (i = j = 0; c = default_filename_quote_characters[i]; i++)
3435 if (c == should_expand_dirname || c == nextch || c == closer)
3436 continue;
3437 custom_filename_quote_characters[j++] = c;
3439 custom_filename_quote_characters[j] = '\0';
3440 rl_filename_quote_characters = custom_filename_quote_characters;
3441 set_filename_bstab (rl_filename_quote_characters);
3444 else
3446 free (new_dirname);
3447 free (local_dirname);
3448 *dirname = (char *)xmalloc (1);
3449 **dirname = '\0';
3450 return 1;
3453 else
3455 /* Dequote the filename even if we don't expand it. */
3456 new_dirname = bush_dequote_filename (local_dirname, rl_completion_quote_character);
3457 return_value = STREQ (local_dirname, new_dirname) == 0;
3458 free (local_dirname);
3459 local_dirname = *dirname = new_dirname;
3462 /* no_symbolic_links == 0 -> use (default) logical view of the file system.
3463 local_dirname[0] == '.' && local_dirname[1] == '/' means files in the
3464 current directory (./).
3465 local_dirname[0] == '.' && local_dirname[1] == 0 means relative pathnames
3466 in the current directory (e.g., lib/sh).
3467 XXX - should we do spelling correction on these? */
3469 /* This is test as it was in bush-4.2: skip relative pathnames in current
3470 directory. Change test to
3471 (local_dirname[0] != '.' || (local_dirname[1] && local_dirname[1] != '/'))
3472 if we want to skip paths beginning with ./ also. */
3473 if (no_symbolic_links == 0 && (local_dirname[0] != '.' || local_dirname[1]))
3475 char *temp1, *temp2;
3476 int len1, len2;
3478 /* If we have a relative path
3479 (local_dirname[0] != '/' && local_dirname[0] != '.')
3480 that is canonical after appending it to the current directory, then
3481 temp1 = temp2+'/'
3482 That is,
3483 strcmp (temp1, temp2) == 0
3484 after adding a slash to temp2 below. It should be safe to not
3485 change those.
3487 t = get_working_directory ("symlink-hook");
3488 temp1 = make_absolute (local_dirname, t);
3489 free (t);
3490 temp2 = sh_canonpath (temp1, PATH_CHECKDOTDOT|PATH_CHECKEXISTS);
3492 /* Try spelling correction if initial canonicalization fails. Make
3493 sure we are set to replace the directory name with the results so
3494 subsequent directory checks don't fail. */
3495 if (temp2 == 0 && dircomplete_spelling && dircomplete_expand)
3497 temp2 = dirspell (temp1);
3498 if (temp2)
3500 free (temp1);
3501 temp1 = temp2;
3502 temp2 = sh_canonpath (temp1, PATH_CHECKDOTDOT|PATH_CHECKEXISTS);
3503 return_value |= temp2 != 0;
3506 /* If we can't canonicalize, bail. */
3507 if (temp2 == 0)
3509 free (temp1);
3510 return return_value;
3512 len1 = strlen (temp1);
3513 if (temp1[len1 - 1] == '/')
3515 len2 = strlen (temp2);
3516 if (len2 > 2) /* don't append `/' to `/' or `//' */
3518 temp2 = (char *)xrealloc (temp2, len2 + 2);
3519 temp2[len2] = '/';
3520 temp2[len2 + 1] = '\0';
3524 /* dircomplete_expand_relpath == 0 means we want to leave relative
3525 pathnames that are unchanged by canonicalization alone.
3526 *local_dirname != '/' && *local_dirname != '.' == relative pathname
3527 (consistent with general.c:absolute_pathname())
3528 temp1 == temp2 (after appending a slash to temp2) means the pathname
3529 is not changed by canonicalization as described above. */
3530 if (dircomplete_expand_relpath || ((local_dirname[0] != '/' && local_dirname[0] != '.') && STREQ (temp1, temp2) == 0))
3531 return_value |= STREQ (local_dirname, temp2) == 0;
3532 free (local_dirname);
3533 *dirname = temp2;
3534 free (temp1);
3537 return (return_value);
3540 static char **history_completion_array = (char **)NULL;
3541 static int harry_size;
3542 static int harry_len;
3544 static void
3545 build_history_completion_array ()
3547 register int i, j;
3548 HIST_ENTRY **hlist;
3549 char **tokens;
3551 /* First, clear out the current dynamic history completion list. */
3552 if (harry_size)
3554 strvec_dispose (history_completion_array);
3555 history_completion_array = (char **)NULL;
3556 harry_size = 0;
3557 harry_len = 0;
3560 /* Next, grovel each line of history, making each shell-sized token
3561 a separate entry in the history_completion_array. */
3562 hlist = history_list ();
3564 if (hlist)
3566 for (i = 0; hlist[i]; i++)
3568 for ( --i; i >= 0; i--)
3570 /* Separate each token, and place into an array. */
3571 tokens = history_tokenize (hlist[i]->line);
3573 for (j = 0; tokens && tokens[j]; j++)
3575 if (harry_len + 2 > harry_size)
3576 history_completion_array = strvec_resize (history_completion_array, harry_size += 10);
3578 history_completion_array[harry_len++] = tokens[j];
3579 history_completion_array[harry_len] = (char *)NULL;
3581 free (tokens);
3584 /* Sort the complete list of tokens. */
3585 if (dabbrev_expand_active == 0)
3586 qsort (history_completion_array, harry_len, sizeof (char *), (QSFUNC *)strvec_strcmp);
3590 static char *
3591 history_completion_generator (hint_text, state)
3592 const char *hint_text;
3593 int state;
3595 static int local_index, len;
3596 static const char *text;
3598 /* If this is the first call to the generator, then initialize the
3599 list of strings to complete over. */
3600 if (state == 0)
3602 if (dabbrev_expand_active) /* This is kind of messy */
3603 rl_completion_suppress_append = 1;
3604 local_index = 0;
3605 build_history_completion_array ();
3606 text = hint_text;
3607 len = strlen (text);
3610 while (history_completion_array && history_completion_array[local_index])
3612 /* XXX - should this use completion-ignore-case? */
3613 if (strncmp (text, history_completion_array[local_index++], len) == 0)
3614 return (savestring (history_completion_array[local_index - 1]));
3616 return ((char *)NULL);
3619 static int
3620 dynamic_complete_history (count, key)
3621 int count, key;
3623 int r;
3624 rl_compentry_func_t *orig_func;
3625 rl_completion_func_t *orig_attempt_func;
3626 rl_compignore_func_t *orig_ignore_func;
3628 orig_func = rl_completion_entry_function;
3629 orig_attempt_func = rl_attempted_completion_function;
3630 orig_ignore_func = rl_ignore_some_completions_function;
3632 rl_completion_entry_function = history_completion_generator;
3633 rl_attempted_completion_function = (rl_completion_func_t *)NULL;
3634 rl_ignore_some_completions_function = filename_completion_ignore;
3636 /* XXX - use rl_completion_mode here? */
3637 if (rl_last_func == dynamic_complete_history)
3638 r = rl_complete_internal ('?');
3639 else
3640 r = rl_complete_internal (TAB);
3642 rl_completion_entry_function = orig_func;
3643 rl_attempted_completion_function = orig_attempt_func;
3644 rl_ignore_some_completions_function = orig_ignore_func;
3646 return r;
3649 static int
3650 bush_dabbrev_expand (count, key)
3651 int count, key;
3653 int r, orig_suppress, orig_sort;
3654 rl_compentry_func_t *orig_func;
3655 rl_completion_func_t *orig_attempt_func;
3656 rl_compignore_func_t *orig_ignore_func;
3658 orig_func = rl_menu_completion_entry_function;
3659 orig_attempt_func = rl_attempted_completion_function;
3660 orig_ignore_func = rl_ignore_some_completions_function;
3661 orig_suppress = rl_completion_suppress_append;
3662 orig_sort = rl_sort_completion_matches;
3664 rl_menu_completion_entry_function = history_completion_generator;
3665 rl_attempted_completion_function = (rl_completion_func_t *)NULL;
3666 rl_ignore_some_completions_function = filename_completion_ignore;
3667 rl_filename_completion_desired = 0;
3668 rl_completion_suppress_append = 1;
3669 rl_sort_completion_matches = 0;
3671 /* XXX - use rl_completion_mode here? */
3672 dabbrev_expand_active = 1;
3673 if (rl_last_func == bush_dabbrev_expand)
3674 rl_last_func = rl_menu_complete;
3675 r = rl_menu_complete (count, key);
3676 dabbrev_expand_active = 0;
3678 rl_last_func = bush_dabbrev_expand;
3679 rl_menu_completion_entry_function = orig_func;
3680 rl_attempted_completion_function = orig_attempt_func;
3681 rl_ignore_some_completions_function = orig_ignore_func;
3682 rl_completion_suppress_append = orig_suppress;
3683 rl_sort_completion_matches = orig_sort;
3685 return r;
3688 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
3689 static int
3690 bush_complete_username (ignore, ignore2)
3691 int ignore, ignore2;
3693 return bush_complete_username_internal (rl_completion_mode (bush_complete_username));
3696 static int
3697 bush_possible_username_completions (ignore, ignore2)
3698 int ignore, ignore2;
3700 return bush_complete_username_internal ('?');
3703 static int
3704 bush_complete_username_internal (what_to_do)
3705 int what_to_do;
3707 return bush_specific_completion (what_to_do, rl_username_completion_function);
3710 static int
3711 bush_complete_filename (ignore, ignore2)
3712 int ignore, ignore2;
3714 return bush_complete_filename_internal (rl_completion_mode (bush_complete_filename));
3717 static int
3718 bush_possible_filename_completions (ignore, ignore2)
3719 int ignore, ignore2;
3721 return bush_complete_filename_internal ('?');
3724 static int
3725 bush_complete_filename_internal (what_to_do)
3726 int what_to_do;
3728 rl_compentry_func_t *orig_func;
3729 rl_completion_func_t *orig_attempt_func;
3730 rl_icppfunc_t *orig_dir_func;
3731 rl_compignore_func_t *orig_ignore_func;
3732 /*const*/ char *orig_rl_completer_word_break_characters;
3733 int r;
3735 orig_func = rl_completion_entry_function;
3736 orig_attempt_func = rl_attempted_completion_function;
3737 orig_ignore_func = rl_ignore_some_completions_function;
3738 orig_rl_completer_word_break_characters = rl_completer_word_break_characters;
3740 orig_dir_func = save_directory_hook ();
3742 rl_completion_entry_function = rl_filename_completion_function;
3743 rl_attempted_completion_function = (rl_completion_func_t *)NULL;
3744 rl_ignore_some_completions_function = filename_completion_ignore;
3745 rl_completer_word_break_characters = " \t\n\"\'";
3747 r = rl_complete_internal (what_to_do);
3749 rl_completion_entry_function = orig_func;
3750 rl_attempted_completion_function = orig_attempt_func;
3751 rl_ignore_some_completions_function = orig_ignore_func;
3752 rl_completer_word_break_characters = orig_rl_completer_word_break_characters;
3754 restore_directory_hook (orig_dir_func);
3756 return r;
3759 static int
3760 bush_complete_hostname (ignore, ignore2)
3761 int ignore, ignore2;
3763 return bush_complete_hostname_internal (rl_completion_mode (bush_complete_hostname));
3766 static int
3767 bush_possible_hostname_completions (ignore, ignore2)
3768 int ignore, ignore2;
3770 return bush_complete_hostname_internal ('?');
3773 static int
3774 bush_complete_variable (ignore, ignore2)
3775 int ignore, ignore2;
3777 return bush_complete_variable_internal (rl_completion_mode (bush_complete_variable));
3780 static int
3781 bush_possible_variable_completions (ignore, ignore2)
3782 int ignore, ignore2;
3784 return bush_complete_variable_internal ('?');
3787 static int
3788 bush_complete_command (ignore, ignore2)
3789 int ignore, ignore2;
3791 return bush_complete_command_internal (rl_completion_mode (bush_complete_command));
3794 static int
3795 bush_possible_command_completions (ignore, ignore2)
3796 int ignore, ignore2;
3798 return bush_complete_command_internal ('?');
3801 static int
3802 bush_complete_hostname_internal (what_to_do)
3803 int what_to_do;
3805 return bush_specific_completion (what_to_do, hostname_completion_function);
3808 static int
3809 bush_complete_variable_internal (what_to_do)
3810 int what_to_do;
3812 return bush_specific_completion (what_to_do, variable_completion_function);
3815 static int
3816 bush_complete_command_internal (what_to_do)
3817 int what_to_do;
3819 return bush_specific_completion (what_to_do, command_word_completion_function);
3822 static int
3823 completion_glob_pattern (string)
3824 char *string;
3826 return (glob_pattern_p (string) == 1);
3829 static char *globtext;
3830 static char *globorig;
3832 static char *
3833 glob_complete_word (text, state)
3834 const char *text;
3835 int state;
3837 static char **matches = (char **)NULL;
3838 static int ind;
3839 int glen;
3840 char *ret, *ttext;
3842 if (state == 0)
3844 rl_filename_completion_desired = 1;
3845 FREE (matches);
3846 if (globorig != globtext)
3847 FREE (globorig);
3848 FREE (globtext);
3850 ttext = bush_tilde_expand (text, 0);
3852 if (rl_explicit_arg)
3854 globorig = savestring (ttext);
3855 glen = strlen (ttext);
3856 globtext = (char *)xmalloc (glen + 2);
3857 strcpy (globtext, ttext);
3858 globtext[glen] = '*';
3859 globtext[glen+1] = '\0';
3861 else
3862 globtext = globorig = savestring (ttext);
3864 if (ttext != text)
3865 free (ttext);
3867 matches = shell_glob_filename (globtext, 0);
3868 if (GLOB_FAILED (matches))
3869 matches = (char **)NULL;
3870 ind = 0;
3873 ret = matches ? matches[ind] : (char *)NULL;
3874 ind++;
3875 return ret;
3878 static int
3879 bush_glob_completion_internal (what_to_do)
3880 int what_to_do;
3882 return bush_specific_completion (what_to_do, glob_complete_word);
3885 /* A special quoting function so we don't end up quoting globbing characters
3886 in the word if there are no matches or multiple matches. */
3887 static char *
3888 bush_glob_quote_filename (s, rtype, qcp)
3889 char *s;
3890 int rtype;
3891 char *qcp;
3893 if (globorig && qcp && *qcp == '\0' && STREQ (s, globorig))
3894 return (savestring (s));
3895 else
3896 return (bush_quote_filename (s, rtype, qcp));
3899 static int
3900 bush_glob_complete_word (count, key)
3901 int count, key;
3903 int r;
3904 rl_quote_func_t *orig_quoting_function;
3906 if (rl_editing_mode == EMACS_EDITING_MODE)
3907 rl_explicit_arg = 1; /* force `*' append */
3908 orig_quoting_function = rl_filename_quoting_function;
3909 rl_filename_quoting_function = bush_glob_quote_filename;
3911 r = bush_glob_completion_internal (rl_completion_mode (bush_glob_complete_word));
3913 rl_filename_quoting_function = orig_quoting_function;
3914 return r;
3917 static int
3918 bush_glob_expand_word (count, key)
3919 int count, key;
3921 return bush_glob_completion_internal ('*');
3924 static int
3925 bush_glob_list_expansions (count, key)
3926 int count, key;
3928 return bush_glob_completion_internal ('?');
3931 static int
3932 bush_specific_completion (what_to_do, generator)
3933 int what_to_do;
3934 rl_compentry_func_t *generator;
3936 rl_compentry_func_t *orig_func;
3937 rl_completion_func_t *orig_attempt_func;
3938 rl_compignore_func_t *orig_ignore_func;
3939 int r;
3941 orig_func = rl_completion_entry_function;
3942 orig_attempt_func = rl_attempted_completion_function;
3943 orig_ignore_func = rl_ignore_some_completions_function;
3944 rl_completion_entry_function = generator;
3945 rl_attempted_completion_function = NULL;
3946 rl_ignore_some_completions_function = orig_ignore_func;
3948 r = rl_complete_internal (what_to_do);
3950 rl_completion_entry_function = orig_func;
3951 rl_attempted_completion_function = orig_attempt_func;
3952 rl_ignore_some_completions_function = orig_ignore_func;
3954 return r;
3957 #endif /* SPECIFIC_COMPLETION_FUNCTIONS */
3959 #if defined (VI_MODE)
3960 /* Completion, from vi mode's point of view. This is a modified version of
3961 rl_vi_complete which uses the bush globbing code to implement what POSIX
3962 specifies, which is to append a `*' and attempt filename generation (which
3963 has the side effect of expanding any globbing characters in the word). */
3964 static int
3965 bush_vi_complete (count, key)
3966 int count, key;
3968 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
3969 int p, r;
3970 char *t;
3972 if ((rl_point < rl_end) && (!whitespace (rl_line_buffer[rl_point])))
3974 if (!whitespace (rl_line_buffer[rl_point + 1]))
3975 rl_vi_end_word (1, 'E');
3976 rl_point++;
3979 /* Find boundaries of current word, according to vi definition of a
3980 `bigword'. */
3981 t = 0;
3982 if (rl_point > 0)
3984 p = rl_point;
3985 rl_vi_bWord (1, 'B');
3986 r = rl_point;
3987 rl_point = p;
3988 p = r;
3990 t = substring (rl_line_buffer, p, rl_point);
3993 if (t && completion_glob_pattern (t) == 0)
3994 rl_explicit_arg = 1; /* XXX - force glob_complete_word to append `*' */
3995 FREE (t);
3997 if (key == '*') /* Expansion and replacement. */
3998 r = bush_glob_expand_word (count, key);
3999 else if (key == '=') /* List possible completions. */
4000 r = bush_glob_list_expansions (count, key);
4001 else if (key == '\\') /* Standard completion */
4002 r = bush_glob_complete_word (count, key);
4003 else
4004 r = rl_complete (0, key);
4006 if (key == '*' || key == '\\')
4007 rl_vi_start_inserting (key, 1, 1);
4009 return (r);
4010 #else
4011 return rl_vi_complete (count, key);
4012 #endif /* !SPECIFIC_COMPLETION_FUNCTIONS */
4014 #endif /* VI_MODE */
4016 /* Filename quoting for completion. */
4017 /* A function to strip unquoted quote characters (single quotes, double
4018 quotes, and backslashes). It allows single quotes to appear
4019 within double quotes, and vice versa. It should be smarter. */
4020 static char *
4021 bush_dequote_filename (text, quote_char)
4022 char *text;
4023 int quote_char;
4025 char *ret, *p, *r;
4026 int l, quoted;
4028 l = strlen (text);
4029 ret = (char *)xmalloc (l + 1);
4030 for (quoted = quote_char, p = text, r = ret; p && *p; p++)
4032 /* Allow backslash-escaped characters to pass through unscathed. */
4033 if (*p == '\\')
4035 /* Backslashes are preserved within single quotes. */
4036 if (quoted == '\'')
4037 *r++ = *p;
4038 /* Backslashes are preserved within double quotes unless the
4039 character is one that is defined to be escaped */
4040 else if (quoted == '"' && ((sh_syntaxtab[(unsigned char)p[1]] & CBSDQUOTE) == 0))
4041 *r++ = *p;
4043 *r++ = *++p;
4044 if (*p == '\0')
4045 return ret; /* XXX - was break; */
4046 continue;
4048 /* Close quote. */
4049 if (quoted && *p == quoted)
4051 quoted = 0;
4052 continue;
4054 /* Open quote. */
4055 if (quoted == 0 && (*p == '\'' || *p == '"'))
4057 quoted = *p;
4058 continue;
4060 *r++ = *p;
4062 *r = '\0';
4063 return ret;
4066 /* Quote characters that the readline completion code would treat as
4067 word break characters with backslashes. Pass backslash-quoted
4068 characters through without examination. */
4069 static char *
4070 quote_word_break_chars (text)
4071 char *text;
4073 char *ret, *r, *s;
4074 int l;
4076 l = strlen (text);
4077 ret = (char *)xmalloc ((2 * l) + 1);
4078 for (s = text, r = ret; *s; s++)
4080 /* Pass backslash-quoted characters through, including the backslash. */
4081 if (*s == '\\')
4083 *r++ = '\\';
4084 *r++ = *++s;
4085 if (*s == '\0')
4086 break;
4087 continue;
4089 /* OK, we have an unquoted character. Check its presence in
4090 rl_completer_word_break_characters. */
4091 if (mbschr (rl_completer_word_break_characters, *s))
4092 *r++ = '\\';
4093 /* XXX -- check for standalone tildes here and backslash-quote them */
4094 if (s == text && *s == '~' && file_exists (text))
4095 *r++ = '\\';
4096 *r++ = *s;
4098 *r = '\0';
4099 return ret;
4102 /* Use characters in STRING to populate the table of characters that should
4103 be backslash-quoted. The table will be used for sh_backslash_quote from
4104 this file. */
4105 static void
4106 set_filename_bstab (string)
4107 const char *string;
4109 const char *s;
4111 memset (filename_bstab, 0, sizeof (filename_bstab));
4112 for (s = string; s && *s; s++)
4113 filename_bstab[(unsigned char)*s] = 1;
4116 /* Quote a filename using double quotes, single quotes, or backslashes
4117 depending on the value of completion_quoting_style. If we're
4118 completing using backslashes, we need to quote some additional
4119 characters (those that readline treats as word breaks), so we call
4120 quote_word_break_chars on the result. This returns newly-allocated
4121 memory. */
4122 static char *
4123 bush_quote_filename (s, rtype, qcp)
4124 char *s;
4125 int rtype;
4126 char *qcp;
4128 char *rtext, *mtext, *ret;
4129 int rlen, cs;
4131 rtext = (char *)NULL;
4133 /* If RTYPE == MULT_MATCH, it means that there is
4134 more than one match. In this case, we do not add
4135 the closing quote or attempt to perform tilde
4136 expansion. If RTYPE == SINGLE_MATCH, we try
4137 to perform tilde expansion, because single and double
4138 quotes inhibit tilde expansion by the shell. */
4140 cs = completion_quoting_style;
4141 /* Might need to modify the default completion style based on *qcp,
4142 since it's set to any user-provided opening quote. We also change
4143 to single-quoting if there is no user-provided opening quote and
4144 the word being completed contains newlines, since those are not
4145 quoted correctly using backslashes (a backslash-newline pair is
4146 special to the shell parser). */
4147 if (*qcp == '\0' && cs == COMPLETE_BSQUOTE && mbschr (s, '\n'))
4148 cs = COMPLETE_SQUOTE;
4149 else if (*qcp == '"')
4150 cs = COMPLETE_DQUOTE;
4151 else if (*qcp == '\'')
4152 cs = COMPLETE_SQUOTE;
4153 #if defined (BANG_HISTORY)
4154 else if (*qcp == '\0' && history_expansion && cs == COMPLETE_DQUOTE &&
4155 history_expansion_inhibited == 0 && mbschr (s, '!'))
4156 cs = COMPLETE_BSQUOTE;
4158 if (*qcp == '"' && history_expansion && cs == COMPLETE_DQUOTE &&
4159 history_expansion_inhibited == 0 && mbschr (s, '!'))
4161 cs = COMPLETE_BSQUOTE;
4162 *qcp = '\0';
4164 #endif
4166 /* Don't tilde-expand backslash-quoted filenames, since only single and
4167 double quotes inhibit tilde expansion. */
4168 mtext = s;
4169 if (mtext[0] == '~' && rtype == SINGLE_MATCH && cs != COMPLETE_BSQUOTE)
4170 mtext = bush_tilde_expand (s, 0);
4172 switch (cs)
4174 case COMPLETE_DQUOTE:
4175 rtext = sh_double_quote (mtext);
4176 break;
4177 case COMPLETE_SQUOTE:
4178 rtext = sh_single_quote (mtext);
4179 break;
4180 case COMPLETE_BSQUOTE:
4181 rtext = sh_backslash_quote (mtext, complete_fullquote ? 0 : filename_bstab, 0);
4182 break;
4185 if (mtext != s)
4186 free (mtext);
4188 /* We may need to quote additional characters: those that readline treats
4189 as word breaks that are not quoted by backslash_quote. */
4190 if (rtext && cs == COMPLETE_BSQUOTE)
4192 mtext = quote_word_break_chars (rtext);
4193 free (rtext);
4194 rtext = mtext;
4197 /* Leave the opening quote intact. The readline completion code takes
4198 care of avoiding doubled opening quotes. */
4199 if (rtext)
4201 rlen = strlen (rtext);
4202 ret = (char *)xmalloc (rlen + 1);
4203 strcpy (ret, rtext);
4205 else
4207 ret = (char *)xmalloc (rlen = 1);
4208 ret[0] = '\0';
4211 /* If there are multiple matches, cut off the closing quote. */
4212 if (rtype == MULT_MATCH && cs != COMPLETE_BSQUOTE)
4213 ret[rlen - 1] = '\0';
4214 free (rtext);
4215 return ret;
4218 /* Support for binding readline key sequences to Unix commands. Each editing
4219 mode has a separate Unix command keymap. */
4221 static Keymap emacs_std_cmd_xmap;
4222 #if defined (VI_MODE)
4223 static Keymap vi_insert_cmd_xmap;
4224 static Keymap vi_movement_cmd_xmap;
4225 #endif
4227 #ifdef _MINIX
4228 static void
4229 #else
4230 static int
4231 #endif
4232 putx(c)
4233 int c;
4235 int x;
4236 x = putc (c, rl_outstream);
4237 #ifndef _MINIX
4238 return x;
4239 #endif
4242 static int
4243 readline_get_char_offset (ind)
4244 int ind;
4246 int r, old_ch;
4248 r = ind;
4249 #if defined (HANDLE_MULTIBYTE)
4250 if (locale_mb_cur_max > 1)
4252 old_ch = rl_line_buffer[ind];
4253 rl_line_buffer[ind] = '\0';
4254 r = MB_STRLEN (rl_line_buffer);
4255 rl_line_buffer[ind] = old_ch;
4257 #endif
4258 return r;
4261 static void
4262 readline_set_char_offset (ind, varp)
4263 int ind;
4264 int *varp;
4266 int i;
4268 i = ind;
4270 #if defined (HANDLE_MULTIBYTE)
4271 if (i > 0 && locale_mb_cur_max > 1)
4272 i = _rl_find_next_mbchar (rl_line_buffer, 0, i, 0); /* XXX */
4273 #endif
4274 if (i != *varp)
4276 if (i > rl_end)
4277 i = rl_end;
4278 else if (i < 0)
4279 i = 0;
4280 *varp = i;
4285 bush_execute_unix_command (count, key)
4286 int count; /* ignored */
4287 int key;
4289 int type;
4290 register int i, r;
4291 intmax_t mi;
4292 sh_parser_state_t ps;
4293 char *cmd, *value, *ce, old_ch;
4294 SHELL_VAR *v;
4295 char ibuf[INT_STRLEN_BOUND(int) + 1];
4296 Keymap cmd_xmap;
4298 /* First, we need to find the right command to execute. This is tricky,
4299 because we might have already indirected into another keymap, so we
4300 have to walk cmd_xmap using the entire key sequence. */
4301 cmd_xmap = get_cmd_xmap_from_keymap (rl_get_keymap ());
4302 cmd = (char *)rl_function_of_keyseq_len (rl_executing_keyseq, rl_key_sequence_length, cmd_xmap, &type);
4304 if (type == ISKMAP && (type = ((Keymap) cmd)[ANYOTHERKEY].type) == ISMACR)
4305 cmd = (char*)((Keymap) cmd)[ANYOTHERKEY].function;
4307 if (cmd == 0 || type != ISMACR)
4309 rl_crlf ();
4310 internal_error (_("bush_execute_unix_command: cannot find keymap for command"));
4311 rl_forced_update_display ();
4312 return 1;
4315 ce = rl_get_termcap ("ce");
4316 if (ce) /* clear current line */
4318 rl_clear_visible_line ();
4319 fflush (rl_outstream);
4321 else
4322 rl_crlf (); /* move to a new line */
4324 v = bind_variable ("READLINE_LINE", rl_line_buffer, 0);
4325 if (v)
4326 VSETATTR (v, att_exported);
4328 i = readline_get_char_offset (rl_point);
4329 value = inttostr (i, ibuf, sizeof (ibuf));
4330 v = bind_int_variable ("READLINE_POINT", value, 0);
4331 if (v)
4332 VSETATTR (v, att_exported);
4334 i = readline_get_char_offset (rl_mark);
4335 value = inttostr (i, ibuf, sizeof (ibuf));
4336 v = bind_int_variable ("READLINE_MARK", value, 0);
4337 if (v)
4338 VSETATTR (v, att_exported);
4339 array_needs_making = 1;
4341 save_parser_state (&ps);
4342 rl_clear_signals ();
4343 r = parse_and_execute (savestring (cmd), "bush_execute_unix_command", SEVAL_NOHIST);
4344 rl_set_signals ();
4345 restore_parser_state (&ps);
4347 v = find_variable ("READLINE_LINE");
4348 maybe_make_readline_line (v ? value_cell (v) : 0);
4350 v = find_variable ("READLINE_POINT");
4351 if (v && legal_number (value_cell (v), &mi))
4352 readline_set_char_offset (mi, &rl_point);
4354 v = find_variable ("READLINE_MARK");
4355 if (v && legal_number (value_cell (v), &mi))
4356 readline_set_char_offset (mi, &rl_mark);
4358 check_unbind_variable ("READLINE_LINE");
4359 check_unbind_variable ("READLINE_POINT");
4360 check_unbind_variable ("READLINE_MARK");
4361 array_needs_making = 1;
4363 /* and restore the readline buffer and display after command execution. */
4364 /* If we clear the last line of the prompt above, redraw only that last
4365 line. If the command returns 124, we redraw unconditionally as in
4366 previous versions. */
4367 if (ce && r != 124)
4368 rl_redraw_prompt_last_line ();
4369 else
4370 rl_forced_update_display ();
4372 return 0;
4376 print_unix_command_map ()
4378 Keymap save, cmd_xmap;
4380 save = rl_get_keymap ();
4381 cmd_xmap = get_cmd_xmap_from_keymap (save);
4382 rl_set_keymap (cmd_xmap);
4383 rl_macro_dumper (1);
4384 rl_set_keymap (save);
4385 return 0;
4388 static void
4389 init_unix_command_map ()
4391 emacs_std_cmd_xmap = rl_make_bare_keymap ();
4393 emacs_std_cmd_xmap[CTRL('X')].type = ISKMAP;
4394 emacs_std_cmd_xmap[CTRL('X')].function = KEYMAP_TO_FUNCTION (rl_make_bare_keymap ());
4395 emacs_std_cmd_xmap[ESC].type = ISKMAP;
4396 emacs_std_cmd_xmap[ESC].function = KEYMAP_TO_FUNCTION (rl_make_bare_keymap ());
4398 #if defined (VI_MODE)
4399 vi_insert_cmd_xmap = rl_make_bare_keymap ();
4400 vi_movement_cmd_xmap = rl_make_bare_keymap ();
4401 #endif
4404 static Keymap
4405 get_cmd_xmap_from_edit_mode ()
4407 if (emacs_std_cmd_xmap == 0)
4408 init_unix_command_map ();
4410 switch (rl_editing_mode)
4412 case EMACS_EDITING_MODE:
4413 return emacs_std_cmd_xmap;
4414 #if defined (VI_MODE)
4415 case VI_EDITING_MODE:
4416 return (get_cmd_xmap_from_keymap (rl_get_keymap ()));
4417 #endif
4418 default:
4419 return (Keymap)NULL;
4423 static Keymap
4424 get_cmd_xmap_from_keymap (kmap)
4425 Keymap kmap;
4427 if (emacs_std_cmd_xmap == 0)
4428 init_unix_command_map ();
4430 if (kmap == emacs_standard_keymap)
4431 return emacs_std_cmd_xmap;
4432 else if (kmap == emacs_meta_keymap)
4433 return (FUNCTION_TO_KEYMAP (emacs_std_cmd_xmap, ESC));
4434 else if (kmap == emacs_ctlx_keymap)
4435 return (FUNCTION_TO_KEYMAP (emacs_std_cmd_xmap, CTRL('X')));
4436 #if defined (VI_MODE)
4437 else if (kmap == vi_insertion_keymap)
4438 return vi_insert_cmd_xmap;
4439 else if (kmap == vi_movement_keymap)
4440 return vi_movement_cmd_xmap;
4441 #endif
4442 else
4443 return (Keymap)NULL;
4446 static int
4447 isolate_sequence (string, ind, need_dquote, startp)
4448 char *string;
4449 int ind, need_dquote, *startp;
4451 register int i;
4452 int c, passc, delim;
4454 for (i = ind; string[i] && whitespace (string[i]); i++)
4456 /* NEED_DQUOTE means that the first non-white character *must* be `"'. */
4457 if (need_dquote && string[i] != '"')
4459 builtin_error (_("%s: first non-whitespace character is not `\"'"), string);
4460 return -1;
4463 /* We can have delimited strings even if NEED_DQUOTE == 0, like the command
4464 string to bind the key sequence to. */
4465 delim = (string[i] == '"' || string[i] == '\'') ? string[i] : 0;
4467 if (startp)
4468 *startp = delim ? ++i : i;
4470 for (passc = 0; c = string[i]; i++)
4472 if (passc)
4474 passc = 0;
4475 continue;
4477 if (c == '\\')
4479 passc++;
4480 continue;
4482 if (c == delim)
4483 break;
4486 if (delim && string[i] != delim)
4488 builtin_error (_("no closing `%c' in %s"), delim, string);
4489 return -1;
4492 return i;
4496 bind_keyseq_to_unix_command (line)
4497 char *line;
4499 Keymap kmap, cmd_xmap;
4500 char *kseq, *value;
4501 int i, kstart;
4503 kmap = rl_get_keymap ();
4505 /* We duplicate some of the work done by rl_parse_and_bind here, but
4506 this code only has to handle `"keyseq": ["]command["]' and can
4507 generate an error for anything else. */
4508 i = isolate_sequence (line, 0, 1, &kstart);
4509 if (i < 0)
4510 return -1;
4512 /* Create the key sequence string to pass to rl_generic_bind */
4513 kseq = substring (line, kstart, i);
4515 for ( ; line[i] && line[i] != ':'; i++)
4517 if (line[i] != ':')
4519 builtin_error (_("%s: missing colon separator"), line);
4520 FREE (kseq);
4521 return -1;
4524 i = isolate_sequence (line, i + 1, 0, &kstart);
4525 if (i < 0)
4527 FREE (kseq);
4528 return -1;
4531 /* Create the value string containing the command to execute. */
4532 value = substring (line, kstart, i);
4534 /* Save the command to execute and the key sequence in the CMD_XMAP */
4535 cmd_xmap = get_cmd_xmap_from_keymap (kmap);
4536 rl_generic_bind (ISMACR, kseq, value, cmd_xmap);
4538 /* and bind the key sequence in the current keymap to a function that
4539 understands how to execute from CMD_XMAP */
4540 rl_bind_keyseq_in_map (kseq, bush_execute_unix_command, kmap);
4542 free (kseq);
4543 return 0;
4547 unbind_unix_command (kseq)
4548 char *kseq;
4550 Keymap cmd_xmap;
4552 cmd_xmap = get_cmd_xmap_from_keymap (rl_get_keymap ());
4553 if (rl_bind_keyseq_in_map (kseq, (rl_command_func_t *)NULL, cmd_xmap) != 0)
4555 builtin_error (_("`%s': cannot unbind in command keymap"), kseq);
4556 return 0;
4558 return 1;
4561 /* Used by the programmable completion code. Complete TEXT as a filename,
4562 but return only directories as matches. Dequotes the filename before
4563 attempting to find matches. */
4564 char **
4565 bush_directory_completion_matches (text)
4566 const char *text;
4568 char **m1;
4569 char *dfn;
4570 int qc;
4572 qc = rl_dispatching ? rl_completion_quote_character : 0;
4573 /* If rl_completion_found_quote != 0, rl_completion_matches will call the
4574 filename dequoting function, causing the directory name to be dequoted
4575 twice. */
4576 if (rl_dispatching && rl_completion_found_quote == 0)
4577 dfn = bush_dequote_filename ((char *)text, qc);
4578 else
4579 dfn = (char *)text;
4580 m1 = rl_completion_matches (dfn, rl_filename_completion_function);
4581 if (dfn != text)
4582 free (dfn);
4584 if (m1 == 0 || m1[0] == 0)
4585 return m1;
4586 /* We don't bother recomputing the lcd of the matches, because it will just
4587 get thrown away by the programmable completion code and recomputed
4588 later. */
4589 (void)bush_progcomp_ignore_filenames (m1);
4590 return m1;
4593 char *
4594 bush_dequote_text (text)
4595 const char *text;
4597 char *dtxt;
4598 int qc;
4600 qc = (text[0] == '"' || text[0] == '\'') ? text[0] : 0;
4601 dtxt = bush_dequote_filename ((char *)text, qc);
4602 return (dtxt);
4605 /* This event hook is designed to be called after readline receives a signal
4606 that interrupts read(2). It gives reasonable responsiveness to interrupts
4607 and fatal signals without executing too much code in a signal handler
4608 context. */
4609 static int
4610 bush_event_hook ()
4612 int sig;
4614 /* XXX - see if we need to do anything here if sigterm_received == 1,
4615 we probably don't want to reset the event hook since we will not be
4616 jumping to the top level */
4617 if (sigterm_received)
4619 /* RESET_SIGTERM; */
4620 return 0;
4623 sig = 0;
4624 if (terminating_signal)
4625 sig = terminating_signal;
4626 else if (interrupt_state)
4627 sig = SIGINT;
4628 else if (sigalrm_seen)
4629 sig = SIGALRM;
4630 else
4631 sig = first_pending_trap ();
4633 /* If we're going to longjmp to top_level, make sure we clean up readline.
4634 check_signals will call QUIT, which will eventually longjmp to top_level,
4635 calling run_interrupt_trap along the way. The check for sigalrm_seen is
4636 to clean up the read builtin's state. */
4637 if (terminating_signal || interrupt_state || sigalrm_seen)
4638 rl_cleanup_after_signal ();
4639 bushline_reset_event_hook ();
4641 /* posix mode SIGINT during read -e. We only get here if SIGINT is trapped. */
4642 if (posixly_correct && this_shell_builtin == read_builtin && sig == 2)
4644 last_command_exit_value = 128|SIGINT;
4645 throw_to_top_level ();
4648 check_signals_and_traps (); /* XXX */
4649 return 0;
4652 #endif /* READLINE */