]> git.ipfire.org Git - thirdparty/bash.git/blame - bashline.c
bash-20141003 remove leftover and stray files
[thirdparty/bash.git] / bashline.c
CommitLineData
726f6388
JA
1/* bashline.c -- Bash's interface to the readline library. */
2
1b1fe467 3/* Copyright (C) 1987-2013 Free Software Foundation, Inc.
726f6388
JA
4
5 This file is part of GNU Bash, the Bourne Again SHell.
6
2e4498b3
CR
7 Bash is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
726f6388 11
2e4498b3
CR
12 Bash is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
726f6388
JA
16
17 You should have received a copy of the GNU General Public License
2e4498b3
CR
18 along with Bash. If not, see <http://www.gnu.org/licenses/>.
19*/
726f6388 20
ccc6cda3
JA
21#include "config.h"
22
23#if defined (READLINE)
24
726f6388
JA
25#include "bashtypes.h"
26#include "posixstat.h"
27
ccc6cda3
JA
28#if defined (HAVE_UNISTD_H)
29# include <unistd.h>
30#endif
31
f73dda09
JA
32#if defined (HAVE_GRP_H)
33# include <grp.h>
34#endif
35
7117c2d2
JA
36#if defined (HAVE_NETDB_H)
37# include <netdb.h>
38#endif
39
ad4aef08
CR
40#include <signal.h>
41
726f6388 42#include <stdio.h>
f73dda09 43#include "chartypes.h"
726f6388 44#include "bashansi.h"
5e13499c
CR
45#include "bashintl.h"
46
726f6388 47#include "shell.h"
7117c2d2 48#include "input.h"
726f6388 49#include "builtins.h"
726f6388 50#include "bashhist.h"
ccc6cda3 51#include "bashline.h"
726f6388 52#include "execute_cmd.h"
cce855bc 53#include "findcmd.h"
ccc6cda3 54#include "pathexp.h"
8c2fef19 55#include "shmbutil.h"
d76edd30 56#include "trap.h"
8c2fef19 57
ccc6cda3 58#include "builtins/common.h"
8c2fef19 59
ccc6cda3
JA
60#include <readline/rlconf.h>
61#include <readline/readline.h>
62#include <readline/history.h>
63
64#include <glob/glob.h>
726f6388
JA
65
66#if defined (ALIAS)
67# include "alias.h"
68#endif
69
bb70624e
JA
70#if defined (PROGRAMMABLE_COMPLETION)
71# include "pcomplete.h"
72#endif
73
7117c2d2
JA
74/* These should agree with the defines for emacs_mode and vi_mode in
75 rldefs.h, even though that's not a public readline header file. */
76#ifndef EMACS_EDITING_MODE
77# define NO_EDITING_MODE -1
78# define EMACS_EDITING_MODE 1
79# define VI_EDITING_MODE 0
80#endif
81
4ac1ff98
CR
82#define RL_BOOLEAN_VARIABLE_VALUE(s) ((s)[0] == 'o' && (s)[1] == 'n' && (s)[2] == '\0')
83
726f6388 84#if defined (BRACE_COMPLETION)
28ef6c31 85extern int bash_brace_completion __P((int, int));
726f6388
JA
86#endif /* BRACE_COMPLETION */
87
dfc21851 88/* To avoid including curses.h/term.h/termcap.h and that whole mess. */
7175a77f
CR
89#ifdef _MINIX
90extern int tputs __P((const char *string, int nlines, void (*outx)(int)));
91#else
dfc21851 92extern int tputs __P((const char *string, int nlines, int (*outx)(int)));
7175a77f 93#endif
dfc21851 94
28ef6c31
JA
95/* Forward declarations */
96
726f6388 97/* Functions bound to keys in Readline for Bash users. */
28ef6c31
JA
98static int shell_expand_line __P((int, int));
99static int display_shell_version __P((int, int));
100static int operate_and_get_next __P((int, int));
101
102static int bash_ignore_filenames __P((char **));
103static int bash_ignore_everything __P((char **));
104
cce855bc 105#if defined (BANG_HISTORY)
f73dda09 106static char *history_expand_line_internal __P((char *));
28ef6c31
JA
107static int history_expand_line __P((int, int));
108static int tcsh_magic_space __P((int, int));
cce855bc 109#endif /* BANG_HISTORY */
d166f048 110#ifdef ALIAS
28ef6c31 111static int alias_expand_line __P((int, int));
cce855bc
JA
112#endif
113#if defined (BANG_HISTORY) && defined (ALIAS)
28ef6c31 114static int history_and_alias_expand_line __P((int, int));
d166f048 115#endif
726f6388 116
8c2fef19
CR
117static int bash_forward_shellword __P((int, int));
118static int bash_backward_shellword __P((int, int));
119static int bash_kill_shellword __P((int, int));
120static int bash_backward_kill_shellword __P((int, int));
121
726f6388 122/* Helper functions for Readline. */
6a8fd0ed 123static char *restore_tilde __P((char *, char *));
39feef01 124static char *maybe_restore_tilde __P((char *, char *));
6a8fd0ed 125
8f714a7c 126static char *bash_filename_rewrite_hook __P((char *, int));
ddef12ff 127
e624d0f7 128static void bash_directory_expansion __P((char **));
ddef12ff 129static int bash_filename_stat_hook __P((char **));
5a318736 130static int bash_command_name_stat_hook __P((char **));
f73dda09
JA
131static int bash_directory_completion_hook __P((char **));
132static int filename_completion_ignore __P((char **));
28ef6c31 133static int bash_push_line __P((void));
726f6388 134
5a318736
CR
135static int executable_completion __P((const char *, int));
136
adf2f609 137static rl_icppfunc_t *save_directory_hook __P((void));
ddef12ff 138static void restore_directory_hook __P((rl_icppfunc_t));
adf2f609 139
f73dda09
JA
140static void cleanup_expansion_error __P((void));
141static void maybe_make_readline_line __P((char *));
142static void set_up_new_line __P((char *));
143
144static int check_redir __P((int));
28ef6c31
JA
145static char **attempt_shell_completion __P((const char *, int, int));
146static char *variable_completion_function __P((const char *, int));
147static char *hostname_completion_function __P((const char *, int));
148static char *command_subst_completion_function __P((const char *, int));
ccc6cda3 149
f73dda09
JA
150static void build_history_completion_array __P((void));
151static char *history_completion_generator __P((const char *, int));
28ef6c31 152static int dynamic_complete_history __P((int, int));
8943768b 153static int bash_dabbrev_expand __P((int, int));
726f6388 154
f73dda09 155static void initialize_hostname_list __P((void));
28ef6c31 156static void add_host_name __P((char *));
f73dda09
JA
157static void snarf_hosts_from_file __P((char *));
158static char **hostnames_matching __P((char *));
159
160static void _ignore_completion_names __P((char **, sh_ignore_func_t *));
161static int name_is_acceptable __P((const char *));
162static int test_for_directory __P((const char *));
163static int return_zero __P((const char *));
28ef6c31
JA
164
165static char *bash_dequote_filename __P((char *, int));
f73dda09 166static char *quote_word_break_chars __P((char *));
ddef12ff 167static void set_filename_bstab __P((const char *));
28ef6c31 168static char *bash_quote_filename __P((char *, int, char *));
ccc6cda3 169
7175a77f
CR
170#ifdef _MINIX
171static void putx __P((int));
172#else
dfc21851 173static int putx __P((int));
7175a77f 174#endif
f73dda09
JA
175static int bash_execute_unix_command __P((int, int));
176static void init_unix_command_map __P((void));
177static int isolate_sequence __P((char *, int, int, int *));
178
179static int set_saved_history __P((void));
180
ccc6cda3 181#if defined (ALIAS)
28ef6c31 182static int posix_edit_macros __P((int, int));
ccc6cda3 183#endif
726f6388 184
d9e1f41e
CR
185static int bash_event_hook __P((void));
186
bb70624e 187#if defined (PROGRAMMABLE_COMPLETION)
f73dda09
JA
188static int find_cmd_start __P((int));
189static int find_cmd_end __P((int));
51f7ea36 190static char *find_cmd_name __P((int, int *, int *));
f73dda09
JA
191static char *prog_complete_return __P((const char *, int));
192
bb70624e 193static char **prog_complete_matches;
bb70624e
JA
194#endif
195
726f6388 196/* Variables used here but defined in other files. */
d3a24ed2
CR
197#if defined (BANG_HISTORY)
198extern int hist_verify;
199#endif
200
112ff2a6
CR
201extern int current_command_line_count, saved_command_line_count;
202extern int last_command_exit_value;
8943768b 203extern int array_needs_making;
726f6388 204extern int posixly_correct, no_symbolic_links;
fe570ea1 205extern int sigalrm_seen;
726f6388
JA
206extern char *current_prompt_string, *ps1_prompt;
207extern STRING_INT_ALIST word_token_alist[];
d3a24ed2 208extern sh_builtin_func_t *last_shell_builtin, *this_shell_builtin;
726f6388
JA
209
210/* SPECIFIC_COMPLETION_FUNCTIONS specifies that we have individual
211 completion functions which indicate what type of completion should be
212 done (at or before point) that can be bound to key sequences with
213 the readline library. */
214#define SPECIFIC_COMPLETION_FUNCTIONS
215
216#if defined (SPECIFIC_COMPLETION_FUNCTIONS)
28ef6c31
JA
217static int bash_specific_completion __P((int, rl_compentry_func_t *));
218
219static int bash_complete_filename_internal __P((int));
220static int bash_complete_username_internal __P((int));
221static int bash_complete_hostname_internal __P((int));
222static int bash_complete_variable_internal __P((int));
223static int bash_complete_command_internal __P((int));
224
225static int bash_complete_filename __P((int, int));
226static int bash_possible_filename_completions __P((int, int));
227static int bash_complete_username __P((int, int));
228static int bash_possible_username_completions __P((int, int));
229static int bash_complete_hostname __P((int, int));
230static int bash_possible_hostname_completions __P((int, int));
231static int bash_complete_variable __P((int, int));
232static int bash_possible_variable_completions __P((int, int));
233static int bash_complete_command __P((int, int));
234static int bash_possible_command_completions __P((int, int));
f73dda09
JA
235
236static char *glob_complete_word __P((const char *, int));
237static int bash_glob_completion_internal __P((int));
7117c2d2 238static int bash_glob_complete_word __P((int, int));
f73dda09
JA
239static int bash_glob_expand_word __P((int, int));
240static int bash_glob_list_expansions __P((int, int));
da5b17cd 241
726f6388
JA
242#endif /* SPECIFIC_COMPLETION_FUNCTIONS */
243
7117c2d2 244static int edit_and_execute_command __P((int, int, int, char *));
726f6388 245#if defined (VI_MODE)
28ef6c31 246static int vi_edit_and_execute_command __P((int, int));
da5b17cd 247static int bash_vi_complete __P((int, int));
726f6388 248#endif
7117c2d2 249static int emacs_edit_and_execute_command __P((int, int));
726f6388 250
ccc6cda3
JA
251/* Non-zero once initalize_readline () has been called. */
252int bash_readline_initialized = 0;
253
254/* If non-zero, we do hostname completion, breaking words at `@' and
255 trying to complete the stuff after the `@' from our own internal
256 host list. */
257int perform_hostname_completion = 1;
258
bb70624e
JA
259/* If non-zero, we don't do command completion on an empty line. */
260int no_empty_command_completion;
261
d3a24ed2
CR
262/* Set FORCE_FIGNORE if you want to honor FIGNORE even if it ignores the
263 only possible matches. Set to 0 if you want to match filenames if they
264 are the only possible matches, even if FIGNORE says to. */
265int force_fignore = 1;
266
4ac1ff98
CR
267/* Perform spelling correction on directory names during word completion */
268int dircomplete_spelling = 0;
269
adf2f609 270/* Expand directory names during word/filename completion. */
f14388d3
CR
271#if DIRCOMPLETE_EXPAND_DEFAULT
272int dircomplete_expand = 1;
273int dircomplete_expand_relpath = 1;
274#else
adf2f609 275int dircomplete_expand = 0;
e73012f1 276int dircomplete_expand_relpath = 0;
f14388d3 277#endif
adf2f609 278
ddef12ff
CR
279/* When non-zero, perform `normal' shell quoting on completed filenames
280 even when the completed name contains a directory name with a shell
281 variable referene, so dollar signs in a filename get quoted appropriately.
282 Set to zero to remove dollar sign (and braces or parens as needed) from
283 the set of characters that will be quoted. */
284int complete_fullquote = 1;
285
ccc6cda3
JA
286static char *bash_completer_word_break_characters = " \t\n\"'@><=;|&(:";
287static char *bash_nohostname_word_break_characters = " \t\n\"'><=;|&(:";
d3a24ed2 288/* )) */
ccc6cda3 289
7df0c1b2
CR
290static const char *default_filename_quote_characters = " \t\n\\\"'@<>=;|&()#$`?*[!:{~"; /*}*/
291static char *custom_filename_quote_characters = 0;
ddef12ff 292static char filename_bstab[256];
7df0c1b2 293
28ef6c31 294static rl_hook_func_t *old_rl_startup_hook = (rl_hook_func_t *)NULL;
726f6388 295
633e5c6d
CR
296static int dot_in_path = 0;
297
3eb2d94a
CR
298/* Set to non-zero when dabbrev-expand is running */
299static int dabbrev_expand_active = 0;
300
ccc6cda3
JA
301/* What kind of quoting is performed by bash_quote_filename:
302 COMPLETE_DQUOTE = double-quoting the filename
303 COMPLETE_SQUOTE = single_quoting the filename
304 COMPLETE_BSQUOTE = backslash-quoting special chars in the filename
305*/
306#define COMPLETE_DQUOTE 1
307#define COMPLETE_SQUOTE 2
308#define COMPLETE_BSQUOTE 3
309static int completion_quoting_style = COMPLETE_BSQUOTE;
310
2abb7255
CR
311/* Flag values for the final argument to bash_default_completion */
312#define DEFCOMP_CMDPOS 1
313
726f6388
JA
314/* Change the readline VI-mode keymaps into or out of Posix.2 compliance.
315 Called when the shell is put into or out of `posix' mode. */
316void
317posix_readline_initialize (on_or_off)
318 int on_or_off;
319{
ccc6cda3
JA
320 if (on_or_off)
321 rl_variable_bind ("comment-begin", "#");
726f6388 322#if defined (VI_MODE)
7117c2d2 323 rl_bind_key_in_map (CTRL ('I'), on_or_off ? rl_insert : rl_complete, vi_insertion_keymap);
ccc6cda3
JA
324#endif
325}
326
9614c166
CR
327void
328reset_completer_word_break_chars ()
329{
330 rl_completer_word_break_characters = perform_hostname_completion ? savestring (bash_completer_word_break_characters) : savestring (bash_nohostname_word_break_characters);
331}
332
d3a24ed2
CR
333/* When this function returns, rl_completer_word_break_characters points to
334 dynamically allocated memory. */
f73dda09 335int
ccc6cda3
JA
336enable_hostname_completion (on_or_off)
337 int on_or_off;
338{
f73dda09 339 int old_value;
d3a24ed2 340 char *at, *nv, *nval;
f73dda09
JA
341
342 old_value = perform_hostname_completion;
343
726f6388
JA
344 if (on_or_off)
345 {
ccc6cda3
JA
346 perform_hostname_completion = 1;
347 rl_special_prefixes = "$@";
726f6388
JA
348 }
349 else
ccc6cda3
JA
350 {
351 perform_hostname_completion = 0;
352 rl_special_prefixes = "$";
d3a24ed2
CR
353 }
354
355 /* Now we need to figure out how to appropriately modify and assign
356 rl_completer_word_break_characters depending on whether we want
357 hostname completion on or off. */
358
359 /* If this is the first time this has been called
360 (bash_readline_initialized == 0), use the sames values as before, but
361 allocate new memory for rl_completer_word_break_characters. */
362
363 if (bash_readline_initialized == 0 &&
364 (rl_completer_word_break_characters == 0 ||
365 rl_completer_word_break_characters == rl_basic_word_break_characters))
366 {
367 if (on_or_off)
368 rl_completer_word_break_characters = savestring (bash_completer_word_break_characters);
369 else
370 rl_completer_word_break_characters = savestring (bash_nohostname_word_break_characters);
371 }
372 else
373 {
374 /* See if we have anything to do. */
375 at = strchr (rl_completer_word_break_characters, '@');
376 if ((at == 0 && on_or_off == 0) || (at != 0 && on_or_off != 0))
e6e3b444 377 return old_value;
d3a24ed2
CR
378
379 /* We have something to do. Do it. */
380 nval = (char *)xmalloc (strlen (rl_completer_word_break_characters) + 1 + on_or_off);
381
382 if (on_or_off == 0)
383 {
384 /* Turn it off -- just remove `@' from word break chars. We want
385 to remove all occurrences of `@' from the char list, so we loop
386 rather than just copy the rest of the list over AT. */
387 for (nv = nval, at = rl_completer_word_break_characters; *at; )
388 if (*at != '@')
389 *nv++ = *at++;
390 else
391 at++;
392 *nv = '\0';
393 }
394 else
395 {
396 nval[0] = '@';
397 strcpy (nval + 1, rl_completer_word_break_characters);
398 }
399
400 free (rl_completer_word_break_characters);
401 rl_completer_word_break_characters = nval;
ccc6cda3 402 }
8943768b 403
f73dda09 404 return (old_value);
ccc6cda3 405}
726f6388
JA
406
407/* Called once from parse.y if we are going to use readline. */
408void
409initialize_readline ()
410{
12d937f9
CR
411 rl_command_func_t *func;
412 char kseq[2];
413
726f6388
JA
414 if (bash_readline_initialized)
415 return;
416
417 rl_terminal_name = get_string_value ("TERM");
418 rl_instream = stdin;
419 rl_outstream = stderr;
726f6388
JA
420
421 /* Allow conditional parsing of the ~/.inputrc file. */
422 rl_readline_name = "Bash";
423
28ef6c31
JA
424 /* Add bindable names before calling rl_initialize so they may be
425 referenced in the various inputrc files. */
426 rl_add_defun ("shell-expand-line", shell_expand_line, -1);
cce855bc 427#ifdef BANG_HISTORY
28ef6c31
JA
428 rl_add_defun ("history-expand-line", history_expand_line, -1);
429 rl_add_defun ("magic-space", tcsh_magic_space, -1);
cce855bc
JA
430#endif
431
8c2fef19
CR
432 rl_add_defun ("shell-forward-word", bash_forward_shellword, -1);
433 rl_add_defun ("shell-backward-word", bash_backward_shellword, -1);
434 rl_add_defun ("shell-kill-word", bash_kill_shellword, -1);
435 rl_add_defun ("shell-backward-kill-word", bash_backward_kill_shellword, -1);
436
d166f048 437#ifdef ALIAS
28ef6c31 438 rl_add_defun ("alias-expand-line", alias_expand_line, -1);
bc4cd23c 439# ifdef BANG_HISTORY
28ef6c31 440 rl_add_defun ("history-and-alias-expand-line", history_and_alias_expand_line, -1);
bc4cd23c 441# endif
d166f048
JA
442#endif
443
726f6388
JA
444 /* Backwards compatibility. */
445 rl_add_defun ("insert-last-argument", rl_yank_last_arg, -1);
446
28ef6c31
JA
447 rl_add_defun ("operate-and-get-next", operate_and_get_next, -1);
448 rl_add_defun ("display-shell-version", display_shell_version, -1);
7117c2d2 449 rl_add_defun ("edit-and-execute-command", emacs_edit_and_execute_command, -1);
28ef6c31
JA
450
451#if defined (BRACE_COMPLETION)
452 rl_add_defun ("complete-into-braces", bash_brace_completion, -1);
453#endif
454
455#if defined (SPECIFIC_COMPLETION_FUNCTIONS)
456 rl_add_defun ("complete-filename", bash_complete_filename, -1);
457 rl_add_defun ("possible-filename-completions", bash_possible_filename_completions, -1);
458 rl_add_defun ("complete-username", bash_complete_username, -1);
459 rl_add_defun ("possible-username-completions", bash_possible_username_completions, -1);
460 rl_add_defun ("complete-hostname", bash_complete_hostname, -1);
461 rl_add_defun ("possible-hostname-completions", bash_possible_hostname_completions, -1);
462 rl_add_defun ("complete-variable", bash_complete_variable, -1);
463 rl_add_defun ("possible-variable-completions", bash_possible_variable_completions, -1);
464 rl_add_defun ("complete-command", bash_complete_command, -1);
465 rl_add_defun ("possible-command-completions", bash_possible_command_completions, -1);
7117c2d2 466 rl_add_defun ("glob-complete-word", bash_glob_complete_word, -1);
28ef6c31
JA
467 rl_add_defun ("glob-expand-word", bash_glob_expand_word, -1);
468 rl_add_defun ("glob-list-expansions", bash_glob_list_expansions, -1);
469#endif
470
471 rl_add_defun ("dynamic-complete-history", dynamic_complete_history, -1);
8943768b 472 rl_add_defun ("dabbrev-expand", bash_dabbrev_expand, -1);
726f6388 473
28ef6c31
JA
474 /* Bind defaults before binding our custom shell keybindings. */
475 if (RL_ISSTATE(RL_STATE_INITIALIZED) == 0)
476 rl_initialize ();
477
478 /* Bind up our special shell functions. */
d3a24ed2 479 rl_bind_key_if_unbound_in_map (CTRL('E'), shell_expand_line, emacs_meta_keymap);
28ef6c31 480
28ef6c31 481#ifdef BANG_HISTORY
d3a24ed2 482 rl_bind_key_if_unbound_in_map ('^', history_expand_line, emacs_meta_keymap);
28ef6c31
JA
483#endif
484
d3a24ed2
CR
485 rl_bind_key_if_unbound_in_map (CTRL ('O'), operate_and_get_next, emacs_standard_keymap);
486 rl_bind_key_if_unbound_in_map (CTRL ('V'), display_shell_version, emacs_ctlx_keymap);
726f6388
JA
487
488 /* In Bash, the user can switch editing modes with "set -o [vi emacs]",
489 so it is not necessary to allow C-M-j for context switching. Turn
490 off this occasionally confusing behaviour. */
12d937f9
CR
491 kseq[0] = CTRL('J');
492 kseq[1] = '\0';
493 func = rl_function_of_keyseq (kseq, emacs_meta_keymap, (int *)NULL);
494 if (func == rl_vi_editing_mode)
495 rl_unbind_key_in_map (CTRL('J'), emacs_meta_keymap);
496 kseq[0] = CTRL('M');
497 func = rl_function_of_keyseq (kseq, emacs_meta_keymap, (int *)NULL);
498 if (func == rl_vi_editing_mode)
499 rl_unbind_key_in_map (CTRL('M'), emacs_meta_keymap);
726f6388
JA
500#if defined (VI_MODE)
501 rl_unbind_key_in_map (CTRL('E'), vi_movement_keymap);
502#endif
ccc6cda3 503
726f6388 504#if defined (BRACE_COMPLETION)
d3a24ed2 505 rl_bind_key_if_unbound_in_map ('{', bash_brace_completion, emacs_meta_keymap); /*}*/
726f6388
JA
506#endif /* BRACE_COMPLETION */
507
508#if defined (SPECIFIC_COMPLETION_FUNCTIONS)
d3a24ed2
CR
509 rl_bind_key_if_unbound_in_map ('/', bash_complete_filename, emacs_meta_keymap);
510 rl_bind_key_if_unbound_in_map ('/', bash_possible_filename_completions, emacs_ctlx_keymap);
28ef6c31 511
fb65be05
CR
512 /* Have to jump through hoops here because there is a default binding for
513 M-~ (rl_tilde_expand) */
514 kseq[0] = '~';
515 kseq[1] = '\0';
516 func = rl_function_of_keyseq (kseq, emacs_meta_keymap, (int *)NULL);
517 if (func == 0 || func == rl_tilde_expand)
518 rl_bind_keyseq_in_map (kseq, bash_complete_username, emacs_meta_keymap);
519
d3a24ed2 520 rl_bind_key_if_unbound_in_map ('~', bash_possible_username_completions, emacs_ctlx_keymap);
28ef6c31 521
d3a24ed2
CR
522 rl_bind_key_if_unbound_in_map ('@', bash_complete_hostname, emacs_meta_keymap);
523 rl_bind_key_if_unbound_in_map ('@', bash_possible_hostname_completions, emacs_ctlx_keymap);
28ef6c31 524
d3a24ed2
CR
525 rl_bind_key_if_unbound_in_map ('$', bash_complete_variable, emacs_meta_keymap);
526 rl_bind_key_if_unbound_in_map ('$', bash_possible_variable_completions, emacs_ctlx_keymap);
28ef6c31 527
d3a24ed2
CR
528 rl_bind_key_if_unbound_in_map ('!', bash_complete_command, emacs_meta_keymap);
529 rl_bind_key_if_unbound_in_map ('!', bash_possible_command_completions, emacs_ctlx_keymap);
28ef6c31 530
d3a24ed2
CR
531 rl_bind_key_if_unbound_in_map ('g', bash_glob_complete_word, emacs_meta_keymap);
532 rl_bind_key_if_unbound_in_map ('*', bash_glob_expand_word, emacs_ctlx_keymap);
533 rl_bind_key_if_unbound_in_map ('g', bash_glob_list_expansions, emacs_ctlx_keymap);
726f6388
JA
534
535#endif /* SPECIFIC_COMPLETION_FUNCTIONS */
536
66e6d7cf
CR
537 kseq[0] = TAB;
538 kseq[1] = '\0';
539 func = rl_function_of_keyseq (kseq, emacs_meta_keymap, (int *)NULL);
540 if (func == 0 || func == rl_tab_insert)
541 rl_bind_key_in_map (TAB, dynamic_complete_history, emacs_meta_keymap);
726f6388
JA
542
543 /* Tell the completer that we want a crack first. */
28ef6c31 544 rl_attempted_completion_function = attempt_shell_completion;
726f6388
JA
545
546 /* Tell the completer that we might want to follow symbolic links or
547 do other expansion on directory names. */
adf2f609 548 set_directory_hook ();
726f6388 549
8f714a7c
CR
550 rl_filename_rewrite_hook = bash_filename_rewrite_hook;
551
122f603c
CR
552 rl_filename_stat_hook = bash_filename_stat_hook;
553
726f6388 554 /* Tell the filename completer we want a chance to ignore some names. */
28ef6c31 555 rl_ignore_some_completions_function = filename_completion_ignore;
726f6388 556
7117c2d2 557 /* Bind C-xC-e to invoke emacs and run result as commands. */
d3a24ed2 558 rl_bind_key_if_unbound_in_map (CTRL ('E'), emacs_edit_and_execute_command, emacs_ctlx_keymap);
726f6388 559#if defined (VI_MODE)
d3a24ed2 560 rl_bind_key_if_unbound_in_map ('v', vi_edit_and_execute_command, vi_movement_keymap);
ccc6cda3 561# if defined (ALIAS)
d3a24ed2 562 rl_bind_key_if_unbound_in_map ('@', posix_edit_macros, vi_movement_keymap);
ccc6cda3 563# endif
da5b17cd
CR
564
565 rl_bind_key_in_map ('\\', bash_vi_complete, vi_movement_keymap);
566 rl_bind_key_in_map ('*', bash_vi_complete, vi_movement_keymap);
567 rl_bind_key_in_map ('=', bash_vi_complete, vi_movement_keymap);
726f6388
JA
568#endif
569
570 rl_completer_quote_characters = "'\"";
ccc6cda3
JA
571
572 /* This sets rl_completer_word_break_characters and rl_special_prefixes
573 to the appropriate values, depending on whether or not hostname
574 completion is enabled. */
575 enable_hostname_completion (perform_hostname_completion);
576
577 /* characters that need to be quoted when appearing in filenames. */
7df0c1b2 578 rl_filename_quote_characters = default_filename_quote_characters;
ddef12ff 579 set_filename_bstab (rl_filename_quote_characters);
ee56a865 580
ccc6cda3
JA
581 rl_filename_quoting_function = bash_quote_filename;
582 rl_filename_dequoting_function = bash_dequote_filename;
583 rl_char_is_quoted_p = char_is_quoted;
726f6388 584
7117c2d2
JA
585#if 0
586 /* This is superfluous and makes it impossible to use tab completion in
587 vi mode even when explicitly binding it in ~/.inputrc. sv_strict_posix()
588 should already have called posix_readline_initialize() when
589 posixly_correct was set. */
726f6388
JA
590 if (posixly_correct)
591 posix_readline_initialize (1);
7117c2d2 592#endif
726f6388
JA
593
594 bash_readline_initialized = 1;
595}
596
33fe8777 597void
8943768b 598bashline_reinitialize ()
33fe8777
CR
599{
600 bash_readline_initialized = 0;
601}
602
f4f5e1c2
CR
603void
604bashline_set_event_hook ()
605{
1b1fe467 606 rl_signal_event_hook = bash_event_hook;
f4f5e1c2
CR
607}
608
609void
610bashline_reset_event_hook ()
611{
1b1fe467 612 rl_signal_event_hook = 0;
f4f5e1c2
CR
613}
614
726f6388
JA
615/* On Sun systems at least, rl_attempted_completion_function can end up
616 getting set to NULL, and rl_completion_entry_function set to do command
617 word completion if Bash is interrupted while trying to complete a command
618 word. This just resets all the completion functions to the right thing.
619 It's called from throw_to_top_level(). */
620void
8943768b 621bashline_reset ()
726f6388
JA
622{
623 tilde_initialize ();
624 rl_attempted_completion_function = attempt_shell_completion;
28ef6c31 625 rl_completion_entry_function = NULL;
28ef6c31 626 rl_ignore_some_completions_function = filename_completion_ignore;
7df0c1b2 627 rl_filename_quote_characters = default_filename_quote_characters;
ddef12ff 628 set_filename_bstab (rl_filename_quote_characters);
adf2f609
CR
629
630 set_directory_hook ();
5a318736 631 rl_filename_stat_hook = bash_filename_stat_hook;
55a5a4ac
CR
632
633 bashline_reset_event_hook ();
726f6388
JA
634}
635
636/* Contains the line to push into readline. */
637static char *push_to_readline = (char *)NULL;
638
639/* Push the contents of push_to_readline into the
640 readline buffer. */
28ef6c31 641static int
726f6388
JA
642bash_push_line ()
643{
644 if (push_to_readline)
645 {
646 rl_insert_text (push_to_readline);
647 free (push_to_readline);
648 push_to_readline = (char *)NULL;
649 rl_startup_hook = old_rl_startup_hook;
650 }
28ef6c31 651 return 0;
726f6388
JA
652}
653
654/* Call this to set the initial text for the next line to read
655 from readline. */
656int
657bash_re_edit (line)
658 char *line;
659{
ccc6cda3 660 FREE (push_to_readline);
726f6388
JA
661
662 push_to_readline = savestring (line);
663 old_rl_startup_hook = rl_startup_hook;
28ef6c31 664 rl_startup_hook = bash_push_line;
726f6388
JA
665
666 return (0);
667}
668
28ef6c31 669static int
726f6388
JA
670display_shell_version (count, c)
671 int count, c;
672{
28ef6c31 673 rl_crlf ();
ccc6cda3 674 show_shell_version (0);
726f6388
JA
675 putc ('\r', rl_outstream);
676 fflush (rl_outstream);
677 rl_on_new_line ();
678 rl_redisplay ();
28ef6c31 679 return 0;
726f6388
JA
680}
681
682/* **************************************************************** */
683/* */
684/* Readline Stuff */
685/* */
686/* **************************************************************** */
687
688/* If the user requests hostname completion, then simply build a list
bb70624e
JA
689 of hosts, and complete from that forever more, or at least until
690 HOSTFILE is unset. */
726f6388 691
bb70624e 692/* THIS SHOULD BE A STRINGLIST. */
726f6388
JA
693/* The kept list of hostnames. */
694static char **hostname_list = (char **)NULL;
695
696/* The physical size of the above list. */
ccc6cda3 697static int hostname_list_size;
726f6388 698
ccc6cda3
JA
699/* The number of hostnames in the above list. */
700static int hostname_list_length;
726f6388
JA
701
702/* Whether or not HOSTNAME_LIST has been initialized. */
703int hostname_list_initialized = 0;
704
726f6388
JA
705/* Initialize the hostname completion table. */
706static void
707initialize_hostname_list ()
708{
709 char *temp;
710
711 temp = get_string_value ("HOSTFILE");
ccc6cda3 712 if (temp == 0)
726f6388 713 temp = get_string_value ("hostname_completion_file");
ccc6cda3
JA
714 if (temp == 0)
715 temp = DEFAULT_HOSTS_FILE;
726f6388
JA
716
717 snarf_hosts_from_file (temp);
726f6388
JA
718
719 if (hostname_list)
720 hostname_list_initialized++;
721}
722
723/* Add NAME to the list of hosts. */
724static void
725add_host_name (name)
726 char *name;
727{
728 if (hostname_list_length + 2 > hostname_list_size)
729 {
ccc6cda3 730 hostname_list_size = (hostname_list_size + 32) - (hostname_list_size % 32);
7117c2d2 731 hostname_list = strvec_resize (hostname_list, hostname_list_size);
726f6388
JA
732 }
733
ccc6cda3
JA
734 hostname_list[hostname_list_length++] = savestring (name);
735 hostname_list[hostname_list_length] = (char *)NULL;
726f6388
JA
736}
737
738#define cr_whitespace(c) ((c) == '\r' || (c) == '\n' || whitespace(c))
739
740static void
741snarf_hosts_from_file (filename)
742 char *filename;
743{
ccc6cda3 744 FILE *file;
726f6388
JA
745 char *temp, buffer[256], name[256];
746 register int i, start;
747
ccc6cda3
JA
748 file = fopen (filename, "r");
749 if (file == 0)
726f6388
JA
750 return;
751
752 while (temp = fgets (buffer, 255, file))
753 {
754 /* Skip to first character. */
ccc6cda3
JA
755 for (i = 0; buffer[i] && cr_whitespace (buffer[i]); i++)
756 ;
726f6388 757
ccc6cda3
JA
758 /* If comment or blank line, ignore. */
759 if (buffer[i] == '\0' || buffer[i] == '#')
726f6388
JA
760 continue;
761
762 /* If `preprocessor' directive, do the include. */
ccc6cda3 763 if (strncmp (buffer + i, "$include ", 9) == 0)
726f6388 764 {
ccc6cda3 765 char *incfile, *t;
726f6388
JA
766
767 /* Find start of filename. */
ccc6cda3
JA
768 for (incfile = buffer + i + 9; *incfile && whitespace (*incfile); incfile++)
769 ;
726f6388
JA
770
771 /* Find end of filename. */
ccc6cda3
JA
772 for (t = incfile; *t && cr_whitespace (*t) == 0; t++)
773 ;
726f6388
JA
774
775 *t = '\0';
776
ccc6cda3 777 snarf_hosts_from_file (incfile);
726f6388
JA
778 continue;
779 }
780
ccc6cda3 781 /* Skip internet address if present. */
f73dda09 782 if (DIGIT (buffer[i]))
ccc6cda3 783 for (; buffer[i] && cr_whitespace (buffer[i]) == 0; i++);
726f6388
JA
784
785 /* Gobble up names. Each name is separated with whitespace. */
ccc6cda3 786 while (buffer[i])
726f6388 787 {
ccc6cda3
JA
788 for (; cr_whitespace (buffer[i]); i++)
789 ;
790 if (buffer[i] == '\0' || buffer[i] == '#')
791 break;
792
793 /* Isolate the current word. */
794 for (start = i; buffer[i] && cr_whitespace (buffer[i]) == 0; i++)
795 ;
796 if (i == start)
726f6388
JA
797 continue;
798 strncpy (name, buffer + start, i - start);
799 name[i - start] = '\0';
800 add_host_name (name);
801 }
802 }
803 fclose (file);
804}
805
bb70624e
JA
806/* Return the hostname list. */
807char **
808get_hostname_list ()
809{
810 if (hostname_list_initialized == 0)
811 initialize_hostname_list ();
812 return (hostname_list);
813}
814
815void
816clear_hostname_list ()
817{
818 register int i;
819
820 if (hostname_list_initialized == 0)
821 return;
822 for (i = 0; i < hostname_list_length; i++)
823 free (hostname_list[i]);
9dd88db7 824 hostname_list_length = hostname_list_initialized = 0;
bb70624e
JA
825}
826
726f6388 827/* Return a NULL terminated list of hostnames which begin with TEXT.
39feef01 828 Initialize the hostname list the first time if necessary.
726f6388
JA
829 The array is malloc ()'ed, but not the individual strings. */
830static char **
831hostnames_matching (text)
832 char *text;
833{
ccc6cda3
JA
834 register int i, len, nmatch, rsize;
835 char **result;
726f6388 836
ccc6cda3
JA
837 if (hostname_list_initialized == 0)
838 initialize_hostname_list ();
726f6388 839
ccc6cda3
JA
840 if (hostname_list_initialized == 0)
841 return ((char **)NULL);
726f6388
JA
842
843 /* Special case. If TEXT consists of nothing, then the whole list is
844 what is desired. */
ccc6cda3 845 if (*text == '\0')
726f6388 846 {
7117c2d2 847 result = strvec_create (1 + hostname_list_length);
726f6388
JA
848 for (i = 0; i < hostname_list_length; i++)
849 result[i] = hostname_list[i];
850 result[i] = (char *)NULL;
851 return (result);
852 }
853
854 /* Scan until found, or failure. */
ccc6cda3
JA
855 len = strlen (text);
856 result = (char **)NULL;
857 for (i = nmatch = rsize = 0; i < hostname_list_length; i++)
726f6388 858 {
ccc6cda3 859 if (STREQN (text, hostname_list[i], len) == 0)
28ef6c31 860 continue;
726f6388 861
ccc6cda3 862 /* OK, it matches. Add it to the list. */
bc4cd23c 863 if (nmatch >= (rsize - 1))
726f6388 864 {
ccc6cda3 865 rsize = (rsize + 16) - (rsize % 16);
7117c2d2 866 result = strvec_resize (result, rsize);
726f6388
JA
867 }
868
ccc6cda3 869 result[nmatch++] = hostname_list[i];
726f6388 870 }
ccc6cda3
JA
871 if (nmatch)
872 result[nmatch] = (char *)NULL;
873 return (result);
726f6388
JA
874}
875
ccc6cda3 876/* The equivalent of the Korn shell C-o operate-and-get-next-history-line
726f6388 877 editing command. */
ccc6cda3 878static int saved_history_line_to_use = -1;
b28ff8c9
CR
879static int last_saved_history_line = -1;
880
881#define HISTORY_FULL() (history_is_stifled () && history_length >= history_max_entries)
726f6388 882
28ef6c31 883static int
726f6388
JA
884set_saved_history ()
885{
b28ff8c9
CR
886 /* XXX - compensate for assumption that history was `shuffled' if it was
887 actually not. */
888 if (HISTORY_FULL () &&
889 hist_last_line_added == 0 &&
890 saved_history_line_to_use < history_length - 1)
891 saved_history_line_to_use++;
892
ccc6cda3 893 if (saved_history_line_to_use >= 0)
b28ff8c9
CR
894 {
895 rl_get_previous_history (history_length - saved_history_line_to_use, 0);
896 last_saved_history_line = saved_history_line_to_use;
897 }
ccc6cda3 898 saved_history_line_to_use = -1;
726f6388 899 rl_startup_hook = old_rl_startup_hook;
f73dda09 900 return (0);
ccc6cda3 901}
726f6388 902
28ef6c31 903static int
726f6388
JA
904operate_and_get_next (count, c)
905 int count, c;
906{
907 int where;
908
909 /* Accept the current line. */
b72432fd 910 rl_newline (1, c);
726f6388
JA
911
912 /* Find the current line, and find the next line to use. */
913 where = where_history ();
914
b28ff8c9 915 if (HISTORY_FULL () || (where >= history_length - 1))
726f6388
JA
916 saved_history_line_to_use = where;
917 else
918 saved_history_line_to_use = where + 1;
919
920 old_rl_startup_hook = rl_startup_hook;
28ef6c31
JA
921 rl_startup_hook = set_saved_history;
922
923 return 0;
726f6388
JA
924}
925
726f6388
JA
926/* This vi mode command causes VI_EDIT_COMMAND to be run on the current
927 command being entered (if no explicit argument is given), otherwise on
928 a command from the history file. */
929
d3a24ed2
CR
930#define VI_EDIT_COMMAND "fc -e \"${VISUAL:-${EDITOR:-vi}}\""
931#define EMACS_EDIT_COMMAND "fc -e \"${VISUAL:-${EDITOR:-emacs}}\""
ff247e74 932#define POSIX_VI_EDIT_COMMAND "fc -e vi"
726f6388 933
28ef6c31 934static int
7117c2d2
JA
935edit_and_execute_command (count, c, editing_mode, edit_command)
936 int count, c, editing_mode;
937 char *edit_command;
726f6388 938{
4ac1ff98 939 char *command, *metaval;
112ff2a6 940 int r, rrs, metaflag;
9e51a74d 941 sh_parser_state_t ps;
f73dda09
JA
942
943 rrs = rl_readline_state;
112ff2a6 944 saved_command_line_count = current_command_line_count;
726f6388
JA
945
946 /* Accept the current line. */
b72432fd 947 rl_newline (1, c);
726f6388
JA
948
949 if (rl_explicit_arg)
950 {
7117c2d2
JA
951 command = (char *)xmalloc (strlen (edit_command) + 8);
952 sprintf (command, "%s %d", edit_command, count);
726f6388
JA
953 }
954 else
955 {
956 /* Take the command we were just editing, add it to the history file,
957 then call fc to operate on it. We have to add a dummy command to
958 the end of the history because fc ignores the last command (assumes
959 it's supposed to deal with the command before the `fc'). */
112ff2a6
CR
960 /* This breaks down when using command-oriented history and are not
961 finished with the command, so we should not ignore the last command */
726f6388 962 using_history ();
49cf7828 963 current_command_line_count++; /* for rl_newline above */
d166f048 964 bash_add_history (rl_line_buffer);
49cf7828 965 current_command_line_count = 0; /* for dummy history entry */
d166f048 966 bash_add_history ("");
726f6388
JA
967 history_lines_this_session++;
968 using_history ();
7117c2d2 969 command = savestring (edit_command);
726f6388 970 }
7117c2d2 971
4ac1ff98
CR
972 metaval = rl_variable_value ("input-meta");
973 metaflag = RL_BOOLEAN_VARIABLE_VALUE (metaval);
974
7117c2d2
JA
975 /* Now, POSIX.1-2001 and SUSv3 say that the commands executed from the
976 temporary file should be placed into the history. We don't do that
977 yet. */
4ac1ff98
CR
978 if (rl_deprep_term_function)
979 (*rl_deprep_term_function) ();
9e51a74d 980 save_parser_state (&ps);
7117c2d2 981 r = parse_and_execute (command, (editing_mode == VI_EDITING_MODE) ? "v" : "C-xC-e", SEVAL_NOHIST);
9e51a74d 982 restore_parser_state (&ps);
4ac1ff98
CR
983 if (rl_prep_term_function)
984 (*rl_prep_term_function) (metaflag);
f73dda09 985
112ff2a6 986 current_command_line_count = saved_command_line_count;
f73dda09
JA
987
988 /* Now erase the contents of the current line and undo the effects of the
989 rl_accept_line() above. We don't even want to make the text we just
990 executed available for undoing. */
ccc6cda3 991 rl_line_buffer[0] = '\0'; /* XXX */
f73dda09
JA
992 rl_point = rl_end = 0;
993 rl_done = 0;
994 rl_readline_state = rrs;
995
996 rl_forced_update_display ();
28ef6c31
JA
997
998 return r;
726f6388 999}
7117c2d2
JA
1000
1001#if defined (VI_MODE)
1002static int
1003vi_edit_and_execute_command (count, c)
1004 int count, c;
1005{
ff247e74
CR
1006 if (posixly_correct)
1007 return (edit_and_execute_command (count, c, VI_EDITING_MODE, POSIX_VI_EDIT_COMMAND));
1008 else
1009 return (edit_and_execute_command (count, c, VI_EDITING_MODE, VI_EDIT_COMMAND));
7117c2d2 1010}
726f6388
JA
1011#endif /* VI_MODE */
1012
7117c2d2
JA
1013static int
1014emacs_edit_and_execute_command (count, c)
1015 int count, c;
1016{
1017 return (edit_and_execute_command (count, c, EMACS_EDITING_MODE, EMACS_EDIT_COMMAND));
1018}
1019
ccc6cda3
JA
1020#if defined (ALIAS)
1021static int
1022posix_edit_macros (count, key)
1023 int count, key;
1024{
1025 int c;
1026 char alias_name[3], *alias_value, *macro;
1027
1028 c = rl_read_key ();
1029 alias_name[0] = '_';
1030 alias_name[1] = c;
1031 alias_name[2] = '\0';
1032
1033 alias_value = get_alias_value (alias_name);
1034 if (alias_value && *alias_value)
1035 {
1036 macro = savestring (alias_value);
1037 rl_push_macro_input (macro);
1038 }
1039 return 0;
1040}
1041#endif
1042
8c2fef19
CR
1043/* Bindable commands that move `shell-words': that is, sequences of
1044 non-unquoted-metacharacters. */
1045
1046#define WORDDELIM(c) (shellmeta(c) || shellblank(c))
1047
1048static int
1049bash_forward_shellword (count, key)
1050 int count, key;
1051{
1052 size_t slen;
1053 int sindex, c, p;
1054 DECLARE_MBSTATE;
1055
1056 if (count < 0)
012bac39 1057 return (bash_backward_shellword (-count, key));
8c2fef19
CR
1058
1059 /* The tricky part of this is deciding whether or not the first character
1060 we're on is an unquoted metacharacter. Not completely handled yet. */
1061 /* XXX - need to test this stuff with backslash-escaped shell
1062 metacharacters and unclosed single- and double-quoted strings. */
1063
1064 p = rl_point;
1065 slen = rl_end;
1066
1067 while (count)
1068 {
1069 if (p == rl_end)
1070 {
1071 rl_point = rl_end;
1072 return 0;
1073 }
1074
e05be32d
CR
1075 /* Are we in a quoted string? If we are, move to the end of the quoted
1076 string and continue the outer loop. We only want quoted strings, not
1077 backslash-escaped characters, but char_is_quoted doesn't
1078 differentiate. */
1079 if (char_is_quoted (rl_line_buffer, p) && p > 0 && rl_line_buffer[p-1] != '\\')
1080 {
1081 do
1082 ADVANCE_CHAR (rl_line_buffer, slen, p);
1083 while (p < rl_end && char_is_quoted (rl_line_buffer, p));
1084 count--;
1085 continue;
1086 }
1087
1088 /* Rest of code assumes we are not in a quoted string. */
8c2fef19
CR
1089 /* Move forward until we hit a non-metacharacter. */
1090 while (p < rl_end && (c = rl_line_buffer[p]) && WORDDELIM (c))
1091 {
1092 switch (c)
1093 {
1094 default:
1095 ADVANCE_CHAR (rl_line_buffer, slen, p);
1096 continue; /* straight back to loop, don't increment p */
1097 case '\\':
1098 if (p < rl_end && rl_line_buffer[p])
1099 ADVANCE_CHAR (rl_line_buffer, slen, p);
1100 break;
1101 case '\'':
1102 p = skip_to_delim (rl_line_buffer, ++p, "'", SD_NOJMP);
1103 break;
1104 case '"':
1105 p = skip_to_delim (rl_line_buffer, ++p, "\"", SD_NOJMP);
1106 break;
1107 }
1108
1109 if (p < rl_end)
1110 p++;
1111 }
1112
1113 if (rl_line_buffer[p] == 0 || p == rl_end)
1114 {
dc9f44b3
CR
1115 rl_point = rl_end;
1116 rl_ding ();
8c2fef19
CR
1117 return 0;
1118 }
1119
1120 /* Now move forward until we hit a non-quoted metacharacter or EOL */
1121 while (p < rl_end && (c = rl_line_buffer[p]) && WORDDELIM (c) == 0)
1122 {
1123 switch (c)
1124 {
1125 default:
1126 ADVANCE_CHAR (rl_line_buffer, slen, p);
1127 continue; /* straight back to loop, don't increment p */
1128 case '\\':
1129 if (p < rl_end && rl_line_buffer[p])
1130 ADVANCE_CHAR (rl_line_buffer, slen, p);
1131 break;
1132 case '\'':
1133 p = skip_to_delim (rl_line_buffer, ++p, "'", SD_NOJMP);
1134 break;
1135 case '"':
1136 p = skip_to_delim (rl_line_buffer, ++p, "\"", SD_NOJMP);
1137 break;
1138 }
1139
1140 if (p < rl_end)
1141 p++;
1142 }
1143
1144 if (p == rl_end || rl_line_buffer[p] == 0)
1145 {
1146 rl_point = rl_end;
1147 return (0);
1148 }
1149
1150 count--;
1151 }
1152
1153 rl_point = p;
1154 return (0);
1155}
1156
1157static int
1158bash_backward_shellword (count, key)
1159 int count, key;
1160{
1161 size_t slen;
1162 int sindex, c, p;
1163 DECLARE_MBSTATE;
1164
1165 if (count < 0)
012bac39 1166 return (bash_forward_shellword (-count, key));
8c2fef19
CR
1167
1168 p = rl_point;
1169 slen = rl_end;
1170
1171 while (count)
1172 {
1173 if (p == 0)
1174 {
1175 rl_point = 0;
1176 return 0;
1177 }
1178
1179 /* Move backward until we hit a non-metacharacter. */
1180 while (p > 0)
1181 {
1182 c = rl_line_buffer[p];
1183 if (WORDDELIM (c) && char_is_quoted (rl_line_buffer, p) == 0)
1184 BACKUP_CHAR (rl_line_buffer, slen, p);
1185 break;
1186 }
1187
1188 if (p == 0)
1189 {
1190 rl_point = 0;
1191 return 0;
1192 }
1193
1194 /* Now move backward until we hit a metacharacter or BOL. */
1195 while (p > 0)
1196 {
1197 c = rl_line_buffer[p];
1198 if (WORDDELIM (c) && char_is_quoted (rl_line_buffer, p) == 0)
1199 break;
1200 BACKUP_CHAR (rl_line_buffer, slen, p);
1201 }
1202
1203 count--;
1204 }
1205
1206 rl_point = p;
1207 return 0;
1208}
1209
1210static int
1211bash_kill_shellword (count, key)
1212 int count, key;
1213{
1214 int p;
1215
1216 if (count < 0)
1217 return (bash_backward_kill_shellword (-count, key));
1218
1219 p = rl_point;
1220 bash_forward_shellword (count, key);
1221
1222 if (rl_point != p)
1223 rl_kill_text (p, rl_point);
1224
1225 rl_point = p;
1226 if (rl_editing_mode == 1) /* 1 == emacs_mode */
1227 rl_mark = rl_point;
1228
1229 return 0;
1230}
1231
1232static int
1233bash_backward_kill_shellword (count, key)
1234 int count, key;
1235{
1236 int p;
1237
1238 if (count < 0)
1239 return (bash_kill_shellword (-count, key));
1240
1241 p = rl_point;
1242 bash_backward_shellword (count, key);
1243
1244 if (rl_point != p)
1245 rl_kill_text (p, rl_point);
1246
1247 if (rl_editing_mode == 1) /* 1 == emacs_mode */
1248 rl_mark = rl_point;
1249
1250 return 0;
1251}
1252
1253
726f6388
JA
1254/* **************************************************************** */
1255/* */
1256/* How To Do Shell Completion */
1257/* */
1258/* **************************************************************** */
1259
bb70624e 1260#define COMMAND_SEPARATORS ";|&{(`"
d3a24ed2 1261/* )} */
ba4ab055
CR
1262#define COMMAND_SEPARATORS_PLUS_WS ";|&{(` \t"
1263/* )} */
bb70624e 1264
ba4ab055
CR
1265/* check for redirections and other character combinations that are not
1266 command separators */
bb70624e
JA
1267static int
1268check_redir (ti)
1269 int ti;
1270{
1271 register int this_char, prev_char;
1272
1273 /* Handle the two character tokens `>&', `<&', and `>|'.
1274 We are not in a command position after one of these. */
1275 this_char = rl_line_buffer[ti];
1276 prev_char = rl_line_buffer[ti - 1];
1277
1278 if ((this_char == '&' && (prev_char == '<' || prev_char == '>')) ||
1279 (this_char == '|' && prev_char == '>'))
1280 return (1);
ba4ab055
CR
1281 else if (this_char == '{' && prev_char == '$') /*}*/
1282 return (1);
1283#if 0 /* Not yet */
1284 else if (this_char == '(' && prev_char == '$') /*)*/
1285 return (1);
1286 else if (this_char == '(' && prev_char == '<') /*)*/
1287 return (1);
1288#if defined (EXTENDED_GLOB)
1289 else if (extended_glob && this_char == '(' && prev_char == '!') /*)*/
1290 return (1);
1291#endif
1292#endif
1293 else if (char_is_quoted (rl_line_buffer, ti))
bb70624e
JA
1294 return (1);
1295 return (0);
1296}
1297
1298#if defined (PROGRAMMABLE_COMPLETION)
f73dda09
JA
1299/*
1300 * XXX - because of the <= start test, and setting os = s+1, this can
1301 * potentially return os > start. This is probably not what we want to
1302 * happen, but fix later after 2.05a-release.
1303 */
bb70624e
JA
1304static int
1305find_cmd_start (start)
1306 int start;
1307{
e198129d 1308 register int s, os, ns;
bb70624e
JA
1309
1310 os = 0;
ba4ab055
CR
1311 /* Flags == SD_NOJMP only because we want to skip over command substitutions
1312 in assignment statements. Have to test whether this affects `standalone'
1313 command substitutions as individual words. */
1314 while (((s = skip_to_delim (rl_line_buffer, os, COMMAND_SEPARATORS, SD_NOJMP/*|SD_NOSKIPCMD*/)) <= start) &&
bb70624e 1315 rl_line_buffer[s])
e198129d
CR
1316 {
1317 /* Handle >| token crudely; treat as > not | */
1318 if (rl_line_buffer[s] == '|' && rl_line_buffer[s-1] == '>')
1319 {
1320 ns = skip_to_delim (rl_line_buffer, s+1, COMMAND_SEPARATORS, SD_NOJMP/*|SD_NOSKIPCMD*/);
1321 if (ns > start || rl_line_buffer[ns] == 0)
1322 return os;
1323 os = ns+1;
1324 continue;
1325 }
1326 os = s+1;
1327 }
bb70624e
JA
1328 return os;
1329}
1330
1331static int
1332find_cmd_end (end)
1333 int end;
1334{
1335 register int e;
1336
4d8d005b 1337 e = skip_to_delim (rl_line_buffer, end, COMMAND_SEPARATORS, SD_NOJMP);
bb70624e
JA
1338 return e;
1339}
1340
1341static char *
51f7ea36 1342find_cmd_name (start, sp, ep)
bb70624e 1343 int start;
51f7ea36 1344 int *sp, *ep;
bb70624e
JA
1345{
1346 char *name;
1347 register int s, e;
1348
1349 for (s = start; whitespace (rl_line_buffer[s]); s++)
1350 ;
1351
1352 /* skip until a shell break character */
4d8d005b 1353 e = skip_to_delim (rl_line_buffer, s, "()<>;&| \t\n", SD_NOJMP);
bb70624e
JA
1354
1355 name = substring (rl_line_buffer, s, e);
1356
51f7ea36
CR
1357 if (sp)
1358 *sp = s;
1359 if (ep)
1360 *ep = e;
1361
bb70624e
JA
1362 return (name);
1363}
1364
1365static char *
1366prog_complete_return (text, matchnum)
f73dda09 1367 const char *text;
bb70624e
JA
1368 int matchnum;
1369{
1370 static int ind;
1371
1372 if (matchnum == 0)
1373 ind = 0;
1374
1375 if (prog_complete_matches == 0 || prog_complete_matches[ind] == 0)
1376 return (char *)NULL;
1377 return (prog_complete_matches[ind++]);
1378}
1379
1380#endif /* PROGRAMMABLE_COMPLETION */
1381
c28fcb7e
CR
1382/* Try and catch completion attempts that are syntax errors or otherwise
1383 invalid. */
1384static int
1385invalid_completion (text, ind)
1386 const char *text;
1387 int ind;
1388{
1389 int pind;
1390
1391 /* If we don't catch these here, the next clause will */
1392 if (ind > 0 && rl_line_buffer[ind] == '(' && /*)*/
1393 member (rl_line_buffer[ind-1], "$<>"))
1394 return 0;
1395
1396 pind = ind - 1;
1397 while (pind > 0 && whitespace (rl_line_buffer[pind]))
1398 pind--;
1399 /* If we have only whitespace preceding a paren, it's valid */
1400 if (ind >= 0 && pind <= 0 && rl_line_buffer[ind] == '(') /*)*/
1401 return 0;
1402 /* Flag the invalid completions, which are mostly syntax errors */
1403 if (ind > 0 && rl_line_buffer[ind] == '(' && /*)*/
1404 member (rl_line_buffer[pind], COMMAND_SEPARATORS) == 0)
1405 return 1;
1406
1407 return 0;
1408}
1409
726f6388
JA
1410/* Do some completion on TEXT. The indices of TEXT in RL_LINE_BUFFER are
1411 at START and END. Return an array of matches, or NULL if none. */
1412static char **
1413attempt_shell_completion (text, start, end)
28ef6c31 1414 const char *text;
726f6388
JA
1415 int start, end;
1416{
2abb7255 1417 int in_command_position, ti, saveti, qc, dflags;
ccc6cda3 1418 char **matches, *command_separator_chars;
912dc4e9
CR
1419#if defined (PROGRAMMABLE_COMPLETION)
1420 int have_progcomps, was_assignment;
1421#endif
726f6388 1422
bb70624e 1423 command_separator_chars = COMMAND_SEPARATORS;
ccc6cda3 1424 matches = (char **)NULL;
28ef6c31 1425 rl_ignore_some_completions_function = filename_completion_ignore;
726f6388 1426
7df0c1b2 1427 rl_filename_quote_characters = default_filename_quote_characters;
ddef12ff 1428 set_filename_bstab (rl_filename_quote_characters);
3d4f66ca 1429 set_directory_hook ();
5a318736 1430 rl_filename_stat_hook = bash_filename_stat_hook;
7df0c1b2 1431
726f6388
JA
1432 /* Determine if this could be a command word. It is if it appears at
1433 the start of the line (ignoring preceding whitespace), or if it
1434 appears after a character that separates commands. It cannot be a
1435 command word if we aren't at the top-level prompt. */
1436 ti = start - 1;
bb70624e 1437 saveti = qc = -1;
726f6388
JA
1438
1439 while ((ti > -1) && (whitespace (rl_line_buffer[ti])))
1440 ti--;
1441
bb70624e
JA
1442#if 1
1443 /* If this is an open quote, maybe we're trying to complete a quoted
1444 command name. */
5e13499c 1445 if (ti >= 0 && (rl_line_buffer[ti] == '"' || rl_line_buffer[ti] == '\''))
bb70624e
JA
1446 {
1447 qc = rl_line_buffer[ti];
1448 saveti = ti--;
1449 while (ti > -1 && (whitespace (rl_line_buffer[ti])))
28ef6c31 1450 ti--;
bb70624e
JA
1451 }
1452#endif
1453
726f6388
JA
1454 in_command_position = 0;
1455 if (ti < 0)
1456 {
1457 /* Only do command completion at the start of a line when we
28ef6c31 1458 are prompting at the top level. */
726f6388
JA
1459 if (current_prompt_string == ps1_prompt)
1460 in_command_position++;
ba4ab055
CR
1461 else if (parser_in_command_position ())
1462 in_command_position++;
726f6388
JA
1463 }
1464 else if (member (rl_line_buffer[ti], command_separator_chars))
1465 {
726f6388
JA
1466 in_command_position++;
1467
bb70624e 1468 if (check_redir (ti) == 1)
28ef6c31 1469 in_command_position = 0;
726f6388
JA
1470 }
1471 else
1472 {
1473 /* This still could be in command position. It is possible
1474 that all of the previous words on the line are variable
1475 assignments. */
1476 }
1477
c28fcb7e
CR
1478 if (in_command_position && invalid_completion (text, ti))
1479 {
1480 rl_attempted_completion_over = 1;
1481 return ((char **)NULL);
1482 }
1483
d166f048
JA
1484 /* Check that we haven't incorrectly flagged a closed command substitution
1485 as indicating we're in a command position. */
e8ce775d 1486 if (in_command_position && ti >= 0 && rl_line_buffer[ti] == '`' &&
bb70624e 1487 *text != '`' && unclosed_pair (rl_line_buffer, end, "`") == 0)
d166f048
JA
1488 in_command_position = 0;
1489
1490 /* Special handling for command substitution. If *TEXT is a backquote,
1491 it can be the start or end of an old-style command substitution, or
1492 unmatched. If it's unmatched, both calls to unclosed_pair will
b06e584e
CR
1493 succeed. Don't bother if readline found a single quote and we are
1494 completing on the substring. */
1495 if (*text == '`' && rl_completion_quote_character != '\'' &&
bb70624e
JA
1496 (in_command_position || (unclosed_pair (rl_line_buffer, start, "`") &&
1497 unclosed_pair (rl_line_buffer, end, "`"))))
28ef6c31 1498 matches = rl_completion_matches (text, command_subst_completion_function);
726f6388 1499
bb70624e
JA
1500#if defined (PROGRAMMABLE_COMPLETION)
1501 /* Attempt programmable completion. */
912dc4e9 1502 have_progcomps = prog_completion_enabled && (progcomp_size () > 0);
6a8fd0ed 1503 if (matches == 0 && (in_command_position == 0 || text[0] == '\0') &&
6a8fd0ed 1504 current_prompt_string == ps1_prompt)
bb70624e 1505 {
ba4ab055 1506 int s, e, s1, e1, os, foundcs;
bb70624e
JA
1507 char *n;
1508
1509 /* XXX - don't free the members */
1510 if (prog_complete_matches)
1511 free (prog_complete_matches);
1512 prog_complete_matches = (char **)NULL;
1513
ba4ab055
CR
1514 os = start;
1515 n = 0;
1516 s = find_cmd_start (os);
bb70624e 1517 e = find_cmd_end (end);
ba4ab055
CR
1518 do
1519 {
1520 /* Skip over assignment statements preceding a command name. If we
1521 don't find a command name at all, we can perform command name
1522 completion. If we find a partial command name, we should perform
1523 command name completion on it. */
1524 FREE (n);
1525 n = find_cmd_name (s, &s1, &e1);
1526 s = e1 + 1;
1527 }
912dc4e9 1528 while (was_assignment = assignment (n, 0));
ba4ab055
CR
1529 s = s1; /* reset to index where name begins */
1530
912dc4e9
CR
1531 /* s == index of where command name begins (reset above)
1532 e == end of current command, may be end of line
1533 s1 = index of where command name begins
1534 e1 == index of where command name ends
1535 start == index of where word to be completed begins
1536 end == index of where word to be completed ends
1537 if (s == start) we are doing command word completion for sure
1538 if (e1 == end) we are at the end of the command name and completing it */
51f7ea36
CR
1539 if (start == 0 && end == 0 && e != 0 && text[0] == '\0') /* beginning of non-empty line */
1540 foundcs = 0;
1541 else if (start == end && start == s1 && e != 0 && e1 > end) /* beginning of command name, leading whitespace */
1542 foundcs = 0;
912dc4e9 1543 else if (e == 0 && e == s && text[0] == '\0' && have_progcomps) /* beginning of empty line */
6a8fd0ed 1544 prog_complete_matches = programmable_completions ("_EmptycmD_", text, s, e, &foundcs);
51f7ea36
CR
1545 else if (start == end && text[0] == '\0' && s1 > start && whitespace (rl_line_buffer[start]))
1546 foundcs = 0; /* whitespace before command name */
912dc4e9
CR
1547 else if (e > s && was_assignment == 0 && e1 == end && rl_line_buffer[e] == 0 && whitespace (rl_line_buffer[e-1]) == 0)
1548 {
1549 /* not assignment statement, but still want to perform command
1550 completion if we are composing command word. */
1551 foundcs = 0;
1552 in_command_position = s == start && STREQ (n, text); /* XXX */
1553 }
1554 else if (e > s && was_assignment == 0 && have_progcomps)
1555 {
1556 prog_complete_matches = programmable_completions (n, text, s, e, &foundcs);
1557 /* command completion if programmable completion fails */
1558 in_command_position = s == start && STREQ (n, text); /* XXX */
1559 }
c28fcb7e
CR
1560 /* empty command name following command separator */
1561 else if (s >= e && n[0] == '\0' && text[0] == '\0' && start > 0 &&
1562 was_assignment == 0 && member (rl_line_buffer[start-1], COMMAND_SEPARATORS))
1563 {
1564 foundcs = 0;
1565 in_command_position = 1;
1566 }
ba4ab055
CR
1567 else if (s >= e && n[0] == '\0' && text[0] == '\0' && start > 0)
1568 {
1569 foundcs = 0; /* empty command name following assignments */
912dc4e9 1570 in_command_position = was_assignment;
ba4ab055
CR
1571 }
1572 else if (s == start && e == end && STREQ (n, text) && start > 0)
1573 {
1574 foundcs = 0; /* partial command name following assignments */
1575 in_command_position = 1;
1576 }
f73dda09
JA
1577 else
1578 foundcs = 0;
bb70624e
JA
1579 FREE (n);
1580 /* XXX - if we found a COMPSPEC for the command, just return whatever
1581 the programmable completion code returns, and disable the default
28ef6c31 1582 filename completion that readline will do unless the COPT_DEFAULT
6a8fd0ed
CR
1583 option has been set with the `-o default' option to complete or
1584 compopt. */
bb70624e
JA
1585 if (foundcs)
1586 {
7e52d2bf 1587 pcomp_set_readline_variables (foundcs, 1);
bb70624e
JA
1588 /* Turn what the programmable completion code returns into what
1589 readline wants. I should have made compute_lcd_of_matches
1590 external... */
28ef6c31
JA
1591 matches = rl_completion_matches (text, prog_complete_return);
1592 if ((foundcs & COPT_DEFAULT) == 0)
1593 rl_attempted_completion_over = 1; /* no default */
d3a24ed2
CR
1594 if (matches || ((foundcs & COPT_BASHDEFAULT) == 0))
1595 return (matches);
bb70624e
JA
1596 }
1597 }
1598#endif
1599
d3a24ed2 1600 if (matches == 0)
2abb7255
CR
1601 {
1602 dflags = 0;
1603 if (in_command_position)
1604 dflags |= DEFCOMP_CMDPOS;
1605 matches = bash_default_completion (text, start, end, qc, dflags);
1606 }
d3a24ed2
CR
1607
1608 return matches;
1609}
1610
1611char **
2abb7255 1612bash_default_completion (text, start, end, qc, compflags)
d3a24ed2 1613 const char *text;
2abb7255 1614 int start, end, qc, compflags;
d3a24ed2 1615{
122f603c 1616 char **matches, *t;
d3a24ed2
CR
1617
1618 matches = (char **)NULL;
1619
bb70624e 1620 /* New posix-style command substitution or variable name? */
726f6388 1621 if (!matches && *text == '$')
bb70624e
JA
1622 {
1623 if (qc != '\'' && text[1] == '(') /* ) */
28ef6c31 1624 matches = rl_completion_matches (text, command_subst_completion_function);
bb70624e 1625 else
122f603c
CR
1626 {
1627 matches = rl_completion_matches (text, variable_completion_function);
1628 if (matches && matches[0] && matches[1] == 0)
1629 {
1630 t = savestring (matches[0]);
1631 bash_filename_stat_hook (&t);
1632 /* doesn't use test_for_directory because that performs tilde
1633 expansion */
1634 if (file_isdir (t))
1635 rl_completion_append_character = '/';
1636 free (t);
1637 }
1638 }
bb70624e 1639 }
726f6388
JA
1640
1641 /* If the word starts in `~', and there is no slash in the word, then
1642 try completing this word as a username. */
aad3dfa2 1643 if (matches == 0 && *text == '~' && mbschr (text, '/') == 0)
28ef6c31 1644 matches = rl_completion_matches (text, rl_username_completion_function);
726f6388
JA
1645
1646 /* Another one. Why not? If the word starts in '@', then look through
1647 the world of known hostnames for completion first. */
aad3dfa2 1648 if (matches == 0 && perform_hostname_completion && *text == '@')
28ef6c31 1649 matches = rl_completion_matches (text, hostname_completion_function);
726f6388
JA
1650
1651 /* And last, (but not least) if this word is in a command position, then
1652 complete over possible command names, including aliases, functions,
1653 and command names. */
2abb7255 1654 if (matches == 0 && (compflags & DEFCOMP_CMDPOS))
726f6388 1655 {
2abb7255
CR
1656 /* If END == START and text[0] == 0, we are trying to complete an empty
1657 command word. */
1658 if (no_empty_command_completion && end == start && text[0] == '\0')
bb70624e
JA
1659 {
1660 matches = (char **)NULL;
28ef6c31 1661 rl_ignore_some_completions_function = bash_ignore_everything;
bb70624e
JA
1662 }
1663 else
1664 {
d3a24ed2
CR
1665#define CMD_IS_DIR(x) (absolute_pathname(x) == 0 && absolute_program(x) == 0 && *(x) != '~' && test_for_directory (x))
1666
633e5c6d 1667 dot_in_path = 0;
28ef6c31 1668 matches = rl_completion_matches (text, command_word_completion_function);
d3a24ed2 1669
bb70624e
JA
1670 /* If we are attempting command completion and nothing matches, we
1671 do not want readline to perform filename completion for us. We
1672 still want to be able to complete partial pathnames, so set the
1673 completion ignore function to something which will remove
1674 filenames and leave directories in the match list. */
1675 if (matches == (char **)NULL)
28ef6c31 1676 rl_ignore_some_completions_function = bash_ignore_filenames;
633e5c6d
CR
1677 else if (matches[1] == 0 && CMD_IS_DIR(matches[0]) && dot_in_path == 0)
1678 /* If we found a single match, without looking in the current
1679 directory (because it's not in $PATH), but the found name is
1680 also a command in the current directory, suppress appending any
1681 terminating character, since it's ambiguous. */
1682 {
1683 rl_completion_suppress_append = 1;
1684 rl_filename_completion_desired = 0;
1685 }
d3a24ed2 1686 else if (matches[0] && matches[1] && STREQ (matches[0], matches[1]) && CMD_IS_DIR (matches[0]))
7117c2d2
JA
1687 /* There are multiple instances of the same match (duplicate
1688 completions haven't yet been removed). In this case, all of
1689 the matches will be the same, and the duplicate removal code
633e5c6d
CR
1690 will distill them all down to one. We turn on
1691 rl_completion_suppress_append for the same reason as above.
7117c2d2
JA
1692 Remember: we only care if there's eventually a single unique
1693 completion. If there are multiple completions this won't
1694 make a difference and the problem won't occur. */
633e5c6d
CR
1695 {
1696 rl_completion_suppress_append = 1;
1697 rl_filename_completion_desired = 0;
1698 }
bb70624e 1699 }
726f6388
JA
1700 }
1701
ccc6cda3
JA
1702 /* This could be a globbing pattern, so try to expand it using pathname
1703 expansion. */
f73dda09 1704 if (!matches && glob_pattern_p (text))
e8ce775d 1705 {
28ef6c31 1706 matches = rl_completion_matches (text, glob_complete_word);
e8ce775d
JA
1707 /* A glob expression that matches more than one filename is problematic.
1708 If we match more than one filename, punt. */
7117c2d2 1709 if (matches && matches[1] && rl_completion_type == TAB)
e8ce775d 1710 {
7117c2d2 1711 strvec_dispose (matches);
e8ce775d
JA
1712 matches = (char **)0;
1713 }
c677e9e0
CR
1714 else if (matches && matches[1] && rl_completion_type == '!')
1715 {
1716 rl_completion_suppress_append = 1;
1717 rl_filename_completion_desired = 0;
1718 }
e8ce775d 1719 }
ccc6cda3 1720
726f6388
JA
1721 return (matches);
1722}
1723
5a318736
CR
1724static int
1725bash_command_name_stat_hook (name)
1726 char **name;
1727{
1728 char *cname, *result;
1729
912dc4e9
CR
1730 /* If it's not something we're going to look up in $PATH, just call the
1731 normal filename stat hook. */
1732 if (absolute_program (*name))
1733 return (bash_filename_stat_hook (name));
1734
5a318736
CR
1735 cname = *name;
1736 /* XXX - we could do something here with converting aliases, builtins,
1737 and functions into something that came out as executable, but we don't. */
1738 result = search_for_command (cname, 0);
1739 if (result)
1740 {
1741 *name = result;
1742 return 1;
1743 }
1744 return 0;
1745}
1746
1747static int
1748executable_completion (filename, searching_path)
1749 const char *filename;
1750 int searching_path;
1751{
1752 char *f;
1753 int r;
1754
1755 f = savestring (filename);
1756 bash_directory_completion_hook (&f);
1757
1758 r = searching_path ? executable_file (f) : executable_or_directory (f);
1759 free (f);
1760 return r;
1761}
1762
726f6388
JA
1763/* This is the function to call when the word to complete is in a position
1764 where a command word can be found. It grovels $PATH, looking for commands
1765 that match. It also scans aliases, function names, and the shell_builtin
1766 table. */
bb70624e 1767char *
726f6388 1768command_word_completion_function (hint_text, state)
28ef6c31 1769 const char *hint_text;
726f6388
JA
1770 int state;
1771{
1772 static char *hint = (char *)NULL;
1773 static char *path = (char *)NULL;
1774 static char *val = (char *)NULL;
1775 static char *filename_hint = (char *)NULL;
595e3e69 1776 static char *fnhint = (char *)NULL;
1c72c0cd 1777 static char *dequoted_hint = (char *)NULL;
57a07124 1778 static char *directory_part = (char *)NULL;
6a8fd0ed 1779 static char **glob_matches = (char **)NULL;
1c72c0cd 1780 static int path_index, hint_len, dequoted_len, istate, igncase;
d3ad40de 1781 static int mapping_over, local_index, searching_path, hint_is_dir;
6a8fd0ed 1782 static int old_glob_ignore_case, globpat;
726f6388
JA
1783 static SHELL_VAR **varlist = (SHELL_VAR **)NULL;
1784#if defined (ALIAS)
ccc6cda3 1785 static alias_t **alias_list = (alias_t **)NULL;
726f6388 1786#endif /* ALIAS */
51f7ea36 1787 char *temp, *cval;
726f6388
JA
1788
1789 /* We have to map over the possibilities for command words. If we have
1790 no state, then make one just for that purpose. */
6a8fd0ed 1791 if (state == 0)
726f6388 1792 {
5a318736
CR
1793 rl_filename_stat_hook = bash_command_name_stat_hook;
1794
1c72c0cd
CR
1795 if (dequoted_hint && dequoted_hint != hint)
1796 free (dequoted_hint);
726f6388
JA
1797 if (hint)
1798 free (hint);
1799
d3ad40de
CR
1800 mapping_over = searching_path = 0;
1801 hint_is_dir = CMD_IS_DIR (hint_text);
726f6388
JA
1802 val = (char *)NULL;
1803
1c72c0cd 1804 temp = rl_variable_value ("completion-ignore-case");
4ac1ff98 1805 igncase = RL_BOOLEAN_VARIABLE_VALUE (temp);
1c72c0cd 1806
6a8fd0ed
CR
1807 if (glob_matches)
1808 {
1809 free (glob_matches);
1810 glob_matches = (char **)NULL;
1811 }
1812
1813 globpat = glob_pattern_p (hint_text);
1814
726f6388
JA
1815 /* If this is an absolute program name, do not check it against
1816 aliases, reserved words, functions or builtins. We must check
1817 whether or not it is unique, and, if so, whether that filename
1818 is executable. */
6a8fd0ed 1819 if (globpat || absolute_program (hint_text))
726f6388
JA
1820 {
1821 /* Perform tilde expansion on what's passed, so we don't end up
1822 passing filenames with tildes directly to stat(). */
1823 if (*hint_text == '~')
57a07124
CR
1824 {
1825 hint = bash_tilde_expand (hint_text, 0);
1826 directory_part = savestring (hint_text);
1827 temp = strchr (directory_part, '/');
1828 if (temp)
1829 *temp = 0;
1830 else
1831 {
1832 free (directory_part);
1833 directory_part = (char *)NULL;
1834 }
1835 }
726f6388
JA
1836 else
1837 hint = savestring (hint_text);
1c72c0cd
CR
1838
1839 dequoted_hint = hint;
1840 /* If readline's completer found a quote character somewhere, but
1841 didn't set the quote character, there must have been a quote
1842 character embedded in the filename. It can't be at the start of
1843 the filename, so we need to dequote the filename before we look
1844 in the file system for it. */
1845 if (rl_completion_found_quote && rl_completion_quote_character == 0)
1846 {
1847 dequoted_hint = bash_dequote_filename (hint, 0);
1848 free (hint);
1849 hint = dequoted_hint;
1850 }
1851 dequoted_len = hint_len = strlen (hint);
726f6388
JA
1852
1853 if (filename_hint)
1854 free (filename_hint);
1c72c0cd 1855
595e3e69 1856 fnhint = filename_hint = savestring (hint);
726f6388 1857
726f6388 1858 istate = 0;
6a8fd0ed
CR
1859
1860 if (globpat)
1861 {
1862 mapping_over = 5;
1863 goto globword;
1864 }
1865 else
1866 {
3d4f66ca
CR
1867 if (dircomplete_expand && path_dot_or_dotdot (filename_hint))
1868 {
1869 dircomplete_expand = 0;
1870 set_directory_hook ();
1871 dircomplete_expand = 1;
1872 }
6a8fd0ed
CR
1873 mapping_over = 4;
1874 goto inner;
1875 }
726f6388
JA
1876 }
1877
1c72c0cd
CR
1878 dequoted_hint = hint = savestring (hint_text);
1879 dequoted_len = hint_len = strlen (hint);
726f6388 1880
1c72c0cd
CR
1881 if (rl_completion_found_quote && rl_completion_quote_character == 0)
1882 {
1883 dequoted_hint = bash_dequote_filename (hint, 0);
1884 dequoted_len = strlen (dequoted_hint);
1885 }
1886
726f6388 1887 path = get_string_value ("PATH");
633e5c6d 1888 path_index = dot_in_path = 0;
726f6388
JA
1889
1890 /* Initialize the variables for each type of command word. */
1891 local_index = 0;
1892
1893 if (varlist)
1894 free (varlist);
1895
1896 varlist = all_visible_functions ();
1897
1898#if defined (ALIAS)
1899 if (alias_list)
1900 free (alias_list);
1901
1902 alias_list = all_aliases ();
1903#endif /* ALIAS */
1904 }
1905
1906 /* mapping_over says what we are currently hacking. Note that every case
1907 in this list must fall through when there are no more possibilities. */
1908
1909 switch (mapping_over)
1910 {
1911 case 0: /* Aliases come first. */
1912#if defined (ALIAS)
1913 while (alias_list && alias_list[local_index])
1914 {
1915 register char *alias;
1916
1917 alias = alias_list[local_index++]->name;
1918
1919 if (STREQN (alias, hint, hint_len))
1920 return (savestring (alias));
1921 }
1922#endif /* ALIAS */
1923 local_index = 0;
1924 mapping_over++;
1925
1926 case 1: /* Then shell reserved words. */
1927 {
1928 while (word_token_alist[local_index].word)
1929 {
1930 register char *reserved_word;
1931
1932 reserved_word = word_token_alist[local_index++].word;
1933
1934 if (STREQN (reserved_word, hint, hint_len))
1935 return (savestring (reserved_word));
1936 }
1937 local_index = 0;
1938 mapping_over++;
1939 }
1940
1941 case 2: /* Then function names. */
1942 while (varlist && varlist[local_index])
1943 {
1944 register char *varname;
1945
1946 varname = varlist[local_index++]->name;
1947
1948 if (STREQN (varname, hint, hint_len))
1949 return (savestring (varname));
1950 }
1951 local_index = 0;
1952 mapping_over++;
1953
1954 case 3: /* Then shell builtins. */
1955 for (; local_index < num_shell_builtins; local_index++)
1956 {
1957 /* Ignore it if it doesn't have a function pointer or if it
1958 is not currently enabled. */
1959 if (!shell_builtins[local_index].function ||
1960 (shell_builtins[local_index].flags & BUILTIN_ENABLED) == 0)
1961 continue;
1962
1963 if (STREQN (shell_builtins[local_index].name, hint, hint_len))
1964 {
1965 int i = local_index++;
1966
1967 return (savestring (shell_builtins[i].name));
1968 }
1969 }
1970 local_index = 0;
1971 mapping_over++;
1972 }
1973
6a8fd0ed
CR
1974globword:
1975 /* Limited support for completing command words with globbing chars. Only
1976 a single match (multiple matches that end up reducing the number of
1977 characters in the common prefix are bad) will ever be returned on
1978 regular completion. */
108a433e 1979 if (globpat)
6a8fd0ed
CR
1980 {
1981 if (state == 0)
1982 {
1983 glob_ignore_case = igncase;
1984 glob_matches = shell_glob_filename (hint);
1985 glob_ignore_case = old_glob_ignore_case;
1986
1987 if (GLOB_FAILED (glob_matches) || glob_matches == 0)
1988 {
1989 glob_matches = (char **)NULL;
1990 return ((char *)NULL);
1991 }
1992
1993 local_index = 0;
1994
1995 if (glob_matches[1] && rl_completion_type == TAB) /* multiple matches are bad */
1996 return ((char *)NULL);
1997 }
1998
1999 while (val = glob_matches[local_index++])
2000 {
2001 if (executable_or_directory (val))
2002 {
631b20c6 2003 if (*hint_text == '~' && directory_part)
6a8fd0ed 2004 {
39feef01 2005 temp = maybe_restore_tilde (val, directory_part);
6a8fd0ed
CR
2006 free (val);
2007 val = temp;
2008 }
2009 return (val);
2010 }
2011 free (val);
2012 }
2013
2014 glob_ignore_case = old_glob_ignore_case;
2015 return ((char *)NULL);
2016 }
2017
d3ad40de
CR
2018 /* If the text passed is a directory in the current directory, return it
2019 as a possible match. Executables in directories in the current
2020 directory can be specified using relative pathnames and successfully
2021 executed even when `.' is not in $PATH. */
2022 if (hint_is_dir)
2023 {
2024 hint_is_dir = 0; /* only return the hint text once */
2025 return (savestring (hint_text));
2026 }
2027
ccc6cda3 2028 /* Repeatedly call filename_completion_function while we have
726f6388
JA
2029 members of PATH left. Question: should we stat each file?
2030 Answer: we call executable_file () on each file. */
2031 outer:
2032
2033 istate = (val != (char *)NULL);
2034
6a8fd0ed 2035 if (istate == 0)
726f6388
JA
2036 {
2037 char *current_path;
2038
2039 /* Get the next directory from the path. If there is none, then we
2040 are all done. */
8943768b 2041 if (path == 0 || path[path_index] == 0 ||
726f6388
JA
2042 (current_path = extract_colon_unit (path, &path_index)) == 0)
2043 return ((char *)NULL);
2044
d3ad40de 2045 searching_path = 1;
726f6388
JA
2046 if (*current_path == 0)
2047 {
2048 free (current_path);
2049 current_path = savestring (".");
2050 }
2051
2052 if (*current_path == '~')
2053 {
2054 char *t;
2055
7117c2d2 2056 t = bash_tilde_expand (current_path, 0);
726f6388
JA
2057 free (current_path);
2058 current_path = t;
2059 }
2060
633e5c6d
CR
2061 if (current_path[0] == '.' && current_path[1] == '\0')
2062 dot_in_path = 1;
2063
595e3e69
CR
2064 if (fnhint && fnhint != filename_hint)
2065 free (fnhint);
726f6388
JA
2066 if (filename_hint)
2067 free (filename_hint);
2068
7117c2d2 2069 filename_hint = sh_makepath (current_path, hint, 0);
595e3e69
CR
2070 /* Need a quoted version (though it doesn't matter much in most
2071 cases) because rl_filename_completion_function dequotes the
2072 filename it gets, assuming that it's been quoted as part of
2073 the input line buffer. */
2074 if (strpbrk (filename_hint, "\"'\\"))
2075 fnhint = sh_backslash_quote (filename_hint, filename_bstab, 0);
2076 else
2077 fnhint = filename_hint;
8943768b 2078 free (current_path); /* XXX */
726f6388
JA
2079 }
2080
2081 inner:
595e3e69 2082 val = rl_filename_completion_function (fnhint, istate);
3d4f66ca
CR
2083 if (mapping_over == 4 && dircomplete_expand)
2084 set_directory_hook ();
2085
726f6388
JA
2086 istate = 1;
2087
ccc6cda3 2088 if (val == 0)
726f6388
JA
2089 {
2090 /* If the hint text is an absolute program, then don't bother
2091 searching through PATH. */
2092 if (absolute_program (hint))
2093 return ((char *)NULL);
2094
2095 goto outer;
2096 }
2097 else
2098 {
d166f048 2099 int match, freetemp;
726f6388
JA
2100
2101 if (absolute_program (hint))
2102 {
1c72c0cd
CR
2103 if (igncase == 0)
2104 match = strncmp (val, hint, hint_len) == 0;
2105 else
2106 match = strncasecmp (val, hint, hint_len) == 0;
2107
726f6388
JA
2108 /* If we performed tilde expansion, restore the original
2109 filename. */
2110 if (*hint_text == '~')
39feef01 2111 temp = maybe_restore_tilde (val, directory_part);
726f6388
JA
2112 else
2113 temp = savestring (val);
d166f048 2114 freetemp = 1;
726f6388
JA
2115 }
2116 else
2117 {
2118 temp = strrchr (val, '/');
2119
2120 if (temp)
2121 {
2122 temp++;
1c72c0cd
CR
2123 if (igncase == 0)
2124 freetemp = match = strncmp (temp, hint, hint_len) == 0;
2125 else
2126 freetemp = match = strncasecmp (temp, hint, hint_len) == 0;
726f6388
JA
2127 if (match)
2128 temp = savestring (temp);
2129 }
2130 else
d166f048 2131 freetemp = match = 0;
726f6388
JA
2132 }
2133
d3ad40de
CR
2134 /* If we have found a match, and it is an executable file, return it.
2135 We don't return directory names when searching $PATH, since the
2136 bash execution code won't find executables in directories which
2137 appear in directories in $PATH when they're specified using
51f7ea36
CR
2138 relative pathnames. */
2139#if 0
2140 /* If we're not searching $PATH and we have a relative pathname, we
2141 need to re-canonicalize it before testing whether or not it's an
2142 executable or a directory so the shell treats .. relative to $PWD
2143 according to the physical/logical option. The shell already
2144 canonicalizes the directory name in order to tell readline where
2145 to look, so not doing it here will be inconsistent. */
2146 /* XXX -- currently not used -- will introduce more inconsistency,
2147 since shell does not canonicalize ../foo before passing it to
2148 shell_execve(). */
2149 if (match && searching_path == 0 && *val == '.')
2150 {
2151 char *t, *t1;
2152
2153 t = get_working_directory ("command-word-completion");
2154 t1 = make_absolute (val, t);
2155 free (t);
2156 cval = sh_canonpath (t1, PATH_CHECKDOTDOT|PATH_CHECKEXISTS);
2157 }
2158 else
d3ad40de 2159#endif
51f7ea36
CR
2160 cval = val;
2161
5a318736 2162 if (match && executable_completion ((searching_path ? val : cval), searching_path))
726f6388 2163 {
51f7ea36
CR
2164 if (cval != val)
2165 free (cval);
726f6388
JA
2166 free (val);
2167 val = ""; /* So it won't be NULL. */
2168 return (temp);
2169 }
2170 else
2171 {
d166f048
JA
2172 if (freetemp)
2173 free (temp);
51f7ea36
CR
2174 if (cval != val)
2175 free (cval);
726f6388
JA
2176 free (val);
2177 goto inner;
2178 }
2179 }
2180}
2181
d166f048 2182/* Completion inside an unterminated command substitution. */
726f6388
JA
2183static char *
2184command_subst_completion_function (text, state)
28ef6c31 2185 const char *text;
ccc6cda3 2186 int state;
726f6388
JA
2187{
2188 static char **matches = (char **)NULL;
28ef6c31
JA
2189 static const char *orig_start;
2190 static char *filename_text = (char *)NULL;
726f6388 2191 static int cmd_index, start_len;
ccc6cda3 2192 char *value;
726f6388
JA
2193
2194 if (state == 0)
2195 {
2196 if (filename_text)
2197 free (filename_text);
2198 orig_start = text;
2199 if (*text == '`')
28ef6c31 2200 text++;
cce855bc 2201 else if (*text == '$' && text[1] == '(') /* ) */
28ef6c31 2202 text += 2;
5e13499c
CR
2203 /* If the text was quoted, suppress any quote character that the
2204 readline completion code would insert. */
2205 rl_completion_suppress_quote = 1;
726f6388
JA
2206 start_len = text - orig_start;
2207 filename_text = savestring (text);
2208 if (matches)
2209 free (matches);
7117c2d2
JA
2210
2211 /*
2212 * At this point we can entertain the idea of re-parsing
2213 * `filename_text' into a (possibly incomplete) command name and
2214 * arguments, and doing completion based on that. This is
2215 * currently very rudimentary, but it is a small improvement.
2216 */
2217 for (value = filename_text + strlen (filename_text) - 1; value > filename_text; value--)
2218 if (whitespace (*value) || member (*value, COMMAND_SEPARATORS))
2219 break;
2220 if (value <= filename_text)
2221 matches = rl_completion_matches (filename_text, command_word_completion_function);
2222 else
2223 {
2224 value++;
2225 start_len += value - filename_text;
2226 if (whitespace (value[-1]))
2227 matches = rl_completion_matches (value, rl_filename_completion_function);
2228 else
2229 matches = rl_completion_matches (value, command_word_completion_function);
2230 }
2231
2232 /* If there is more than one match, rl_completion_matches has already
2233 put the lcd in matches[0]. Skip over it. */
2234 cmd_index = matches && matches[0] && matches[1];
6d763f92
CR
2235
2236 /* If there's a single match and it's a directory, set the append char
2237 to the expected `/'. Otherwise, don't append anything. */
2238 if (matches && matches[0] && matches[1] == 0 && test_for_directory (matches[0]))
2239 rl_completion_append_character = '/';
2240 else
2241 rl_completion_suppress_append = 1;
726f6388
JA
2242 }
2243
3d4f66ca 2244 if (matches == 0 || matches[cmd_index] == 0)
726f6388
JA
2245 {
2246 rl_filename_quoting_desired = 0; /* disable quoting */
2247 return ((char *)NULL);
2248 }
2249 else
2250 {
f73dda09 2251 value = (char *)xmalloc (1 + start_len + strlen (matches[cmd_index]));
726f6388
JA
2252
2253 if (start_len == 1)
28ef6c31 2254 value[0] = *orig_start;
726f6388 2255 else
28ef6c31 2256 strncpy (value, orig_start, start_len);
726f6388
JA
2257
2258 strcpy (value + start_len, matches[cmd_index]);
2259
2260 cmd_index++;
2261 return (value);
2262 }
2263}
2264
2265/* Okay, now we write the entry_function for variable completion. */
2266static char *
2267variable_completion_function (text, state)
28ef6c31 2268 const char *text;
726f6388 2269 int state;
726f6388 2270{
bb70624e 2271 static char **varlist = (char **)NULL;
726f6388
JA
2272 static int varlist_index;
2273 static char *varname = (char *)NULL;
2274 static int namelen;
2275 static int first_char, first_char_loc;
2276
2277 if (!state)
2278 {
2279 if (varname)
2280 free (varname);
2281
2282 first_char_loc = 0;
2283 first_char = text[0];
2284
2285 if (first_char == '$')
2286 first_char_loc++;
2287
ccc6cda3 2288 if (text[first_char_loc] == '{')
28ef6c31 2289 first_char_loc++;
ccc6cda3 2290
726f6388
JA
2291 varname = savestring (text + first_char_loc);
2292
2293 namelen = strlen (varname);
2294 if (varlist)
7117c2d2 2295 strvec_dispose (varlist);
726f6388 2296
bb70624e
JA
2297 varlist = all_variables_matching_prefix (varname);
2298 varlist_index = 0;
726f6388
JA
2299 }
2300
2301 if (!varlist || !varlist[varlist_index])
2302 {
2303 return ((char *)NULL);
2304 }
2305 else
2306 {
f73dda09
JA
2307 char *value;
2308
2309 value = (char *)xmalloc (4 + strlen (varlist[varlist_index]));
726f6388
JA
2310
2311 if (first_char_loc)
ccc6cda3
JA
2312 {
2313 value[0] = first_char;
2314 if (first_char_loc == 2)
2315 value[1] = '{';
2316 }
726f6388 2317
bb70624e 2318 strcpy (value + first_char_loc, varlist[varlist_index]);
ccc6cda3 2319 if (first_char_loc == 2)
28ef6c31 2320 strcat (value, "}");
726f6388
JA
2321
2322 varlist_index++;
2323 return (value);
2324 }
2325}
2326
2327/* How about a completion function for hostnames? */
2328static char *
2329hostname_completion_function (text, state)
28ef6c31 2330 const char *text;
726f6388 2331 int state;
726f6388
JA
2332{
2333 static char **list = (char **)NULL;
2334 static int list_index = 0;
2335 static int first_char, first_char_loc;
2336
2337 /* If we don't have any state, make some. */
ccc6cda3 2338 if (state == 0)
726f6388 2339 {
ccc6cda3 2340 FREE (list);
726f6388
JA
2341
2342 list = (char **)NULL;
2343
2344 first_char_loc = 0;
2345 first_char = *text;
2346
2347 if (first_char == '@')
2348 first_char_loc++;
2349
f73dda09 2350 list = hostnames_matching ((char *)text+first_char_loc);
726f6388
JA
2351 list_index = 0;
2352 }
2353
2354 if (list && list[list_index])
2355 {
ccc6cda3 2356 char *t;
726f6388 2357
f73dda09 2358 t = (char *)xmalloc (2 + strlen (list[list_index]));
726f6388
JA
2359 *t = first_char;
2360 strcpy (t + first_char_loc, list[list_index]);
2361 list_index++;
2362 return (t);
2363 }
ccc6cda3
JA
2364
2365 return ((char *)NULL);
726f6388
JA
2366}
2367
7117c2d2
JA
2368/*
2369 * A completion function for service names from /etc/services (or wherever).
2370 */
2371char *
2372bash_servicename_completion_function (text, state)
2373 const char *text;
2374 int state;
2375{
2376#if defined (__WIN32__) || defined (__OPENNT) || !defined (HAVE_GETSERVENT)
2377 return ((char *)NULL);
2378#else
2379 static char *sname = (char *)NULL;
2380 static struct servent *srvent;
2381 static int snamelen, firstc;
2382 char *value;
2383 char **alist, *aentry;
2384 int afound;
2385
2386 if (state == 0)
2387 {
2388 FREE (sname);
2389 firstc = *text;
2390
2391 sname = savestring (text);
2392 snamelen = strlen (sname);
2393 setservent (0);
2394 }
2395
2396 while (srvent = getservent ())
2397 {
2398 afound = 0;
2399 if (snamelen == 0 || (STREQN (sname, srvent->s_name, snamelen)))
2400 break;
2401 /* Not primary, check aliases */
d3ad40de 2402 for (alist = srvent->s_aliases; *alist; alist++)
7117c2d2 2403 {
d3ad40de 2404 aentry = *alist;
7117c2d2
JA
2405 if (STREQN (sname, aentry, snamelen))
2406 {
2407 afound = 1;
2408 break;
2409 }
2410 }
2411
2412 if (afound)
2413 break;
2414 }
2415
2416 if (srvent == 0)
2417 {
2418 endservent ();
2419 return ((char *)NULL);
2420 }
2421
2422 value = afound ? savestring (aentry) : savestring (srvent->s_name);
2423 return value;
2424#endif
2425}
2426
2427/*
2428 * A completion function for group names from /etc/group (or wherever).
2429 */
f73dda09
JA
2430char *
2431bash_groupname_completion_function (text, state)
2432 const char *text;
2433 int state;
2434{
2435#if defined (__WIN32__) || defined (__OPENNT) || !defined (HAVE_GRP_H)
2436 return ((char *)NULL);
2437#else
2438 static char *gname = (char *)NULL;
2439 static struct group *grent;
2440 static int gnamelen;
2441 char *value;
2442
2443 if (state == 0)
2444 {
2445 FREE (gname);
2446 gname = savestring (text);
2447 gnamelen = strlen (gname);
2448
2449 setgrent ();
2450 }
2451
2452 while (grent = getgrent ())
2453 {
2454 if (gnamelen == 0 || (STREQN (gname, grent->gr_name, gnamelen)))
2455 break;
2456 }
2457
2458 if (grent == 0)
2459 {
2460 endgrent ();
2461 return ((char *)NULL);
2462 }
2463
2464 value = savestring (grent->gr_name);
2465 return (value);
2466#endif
2467}
2468
cce855bc
JA
2469/* Functions to perform history and alias expansions on the current line. */
2470
2471#if defined (BANG_HISTORY)
2472/* Perform history expansion on the current line. If no history expansion
2473 is done, pre_process_line() returns what it was passed, so we need to
2474 allocate a new line here. */
726f6388
JA
2475static char *
2476history_expand_line_internal (line)
2477 char *line;
2478{
2479 char *new_line;
d3a24ed2 2480 int old_verify;
726f6388 2481
d3a24ed2
CR
2482 old_verify = hist_verify;
2483 hist_verify = 0;
726f6388 2484 new_line = pre_process_line (line, 0, 0);
d3a24ed2
CR
2485 hist_verify = old_verify;
2486
d166f048 2487 return (new_line == line) ? savestring (line) : new_line;
726f6388 2488}
726f6388
JA
2489#endif
2490
2491/* There was an error in expansion. Let the preprocessor print
2492 the error here. */
2493static void
2494cleanup_expansion_error ()
2495{
2496 char *to_free;
d3a24ed2
CR
2497#if defined (BANG_HISTORY)
2498 int old_verify;
2499
2500 old_verify = hist_verify;
2501 hist_verify = 0;
2502#endif
726f6388
JA
2503
2504 fprintf (rl_outstream, "\r\n");
2505 to_free = pre_process_line (rl_line_buffer, 1, 0);
d3a24ed2
CR
2506#if defined (BANG_HISTORY)
2507 hist_verify = old_verify;
2508#endif
d166f048 2509 if (to_free != rl_line_buffer)
762a763b 2510 FREE (to_free);
726f6388
JA
2511 putc ('\r', rl_outstream);
2512 rl_forced_update_display ();
2513}
2514
2515/* If NEW_LINE differs from what is in the readline line buffer, add an
2516 undo record to get from the readline line buffer contents to the new
2517 line and make NEW_LINE the current readline line. */
2518static void
2519maybe_make_readline_line (new_line)
2520 char *new_line;
2521{
2522 if (strcmp (new_line, rl_line_buffer) != 0)
2523 {
2524 rl_point = rl_end;
2525
2526 rl_add_undo (UNDO_BEGIN, 0, 0, 0);
2527 rl_delete_text (0, rl_point);
7117c2d2 2528 rl_point = rl_end = rl_mark = 0;
726f6388
JA
2529 rl_insert_text (new_line);
2530 rl_add_undo (UNDO_END, 0, 0, 0);
2531 }
2532}
2533
2534/* Make NEW_LINE be the current readline line. This frees NEW_LINE. */
2535static void
2536set_up_new_line (new_line)
2537 char *new_line;
2538{
f73dda09
JA
2539 int old_point, at_end;
2540
2541 old_point = rl_point;
2542 at_end = rl_point == rl_end;
726f6388
JA
2543
2544 /* If the line was history and alias expanded, then make that
2545 be one thing to undo. */
2546 maybe_make_readline_line (new_line);
2547 free (new_line);
2548
2549 /* Place rl_point where we think it should go. */
2550 if (at_end)
2551 rl_point = rl_end;
2552 else if (old_point < rl_end)
2553 {
2554 rl_point = old_point;
2555 if (!whitespace (rl_line_buffer[rl_point]))
b72432fd 2556 rl_forward_word (1, 0);
726f6388
JA
2557 }
2558}
2559
cce855bc
JA
2560#if defined (ALIAS)
2561/* Expand aliases in the current readline line. */
2562static int
28ef6c31
JA
2563alias_expand_line (count, ignore)
2564 int count, ignore;
cce855bc
JA
2565{
2566 char *new_line;
2567
2568 new_line = alias_expand (rl_line_buffer);
2569
2570 if (new_line)
2571 {
2572 set_up_new_line (new_line);
2573 return (0);
2574 }
2575 else
2576 {
2577 cleanup_expansion_error ();
2578 return (1);
2579 }
2580}
2581#endif
2582
2583#if defined (BANG_HISTORY)
726f6388 2584/* History expand the line. */
cce855bc 2585static int
28ef6c31
JA
2586history_expand_line (count, ignore)
2587 int count, ignore;
726f6388
JA
2588{
2589 char *new_line;
2590
2591 new_line = history_expand_line_internal (rl_line_buffer);
2592
2593 if (new_line)
cce855bc
JA
2594 {
2595 set_up_new_line (new_line);
2596 return (0);
2597 }
726f6388 2598 else
cce855bc
JA
2599 {
2600 cleanup_expansion_error ();
2601 return (1);
2602 }
2603}
2604
2605/* Expand history substitutions in the current line and then insert a
28ef6c31 2606 space (hopefully close to where we were before). */
cce855bc 2607static int
28ef6c31
JA
2608tcsh_magic_space (count, ignore)
2609 int count, ignore;
cce855bc 2610{
28ef6c31
JA
2611 int dist_from_end, old_point;
2612
2613 old_point = rl_point;
2614 dist_from_end = rl_end - rl_point;
2615 if (history_expand_line (count, ignore) == 0)
cce855bc 2616 {
28ef6c31
JA
2617 /* Try a simple heuristic from Stephen Gildea <gildea@intouchsys.com>.
2618 This works if all expansions were before rl_point or if no expansions
2619 were performed. */
2620 rl_point = (old_point == 0) ? old_point : rl_end - dist_from_end;
cce855bc
JA
2621 rl_insert (1, ' ');
2622 return (0);
2623 }
2624 else
2625 return (1);
726f6388 2626}
0f445e6c 2627#endif /* BANG_HISTORY */
ccc6cda3 2628
726f6388 2629/* History and alias expand the line. */
cce855bc 2630static int
28ef6c31
JA
2631history_and_alias_expand_line (count, ignore)
2632 int count, ignore;
726f6388
JA
2633{
2634 char *new_line;
2635
0f445e6c
CR
2636 new_line = 0;
2637#if defined (BANG_HISTORY)
d3a24ed2 2638 new_line = history_expand_line_internal (rl_line_buffer);
0f445e6c 2639#endif
726f6388
JA
2640
2641#if defined (ALIAS)
2642 if (new_line)
2643 {
2644 char *alias_line;
2645
2646 alias_line = alias_expand (new_line);
2647 free (new_line);
2648 new_line = alias_line;
2649 }
2650#endif /* ALIAS */
2651
2652 if (new_line)
cce855bc
JA
2653 {
2654 set_up_new_line (new_line);
2655 return (0);
2656 }
726f6388 2657 else
cce855bc
JA
2658 {
2659 cleanup_expansion_error ();
2660 return (1);
2661 }
726f6388
JA
2662}
2663
2664/* History and alias expand the line, then perform the shell word
cce855bc
JA
2665 expansions by calling expand_string. This can't use set_up_new_line()
2666 because we want the variable expansions as a separate undo'able
2667 set of operations. */
28ef6c31
JA
2668static int
2669shell_expand_line (count, ignore)
2670 int count, ignore;
726f6388
JA
2671{
2672 char *new_line;
ccc6cda3 2673 WORD_LIST *expanded_string;
726f6388 2674
0f445e6c
CR
2675 new_line = 0;
2676#if defined (BANG_HISTORY)
d3a24ed2 2677 new_line = history_expand_line_internal (rl_line_buffer);
0f445e6c 2678#endif
726f6388
JA
2679
2680#if defined (ALIAS)
2681 if (new_line)
2682 {
2683 char *alias_line;
2684
2685 alias_line = alias_expand (new_line);
2686 free (new_line);
2687 new_line = alias_line;
2688 }
2689#endif /* ALIAS */
2690
2691 if (new_line)
2692 {
2693 int old_point = rl_point;
2694 int at_end = rl_point == rl_end;
2695
2696 /* If the line was history and alias expanded, then make that
2697 be one thing to undo. */
2698 maybe_make_readline_line (new_line);
2699 free (new_line);
2700
2701 /* If there is variable expansion to perform, do that as a separate
2702 operation to be undone. */
d166f048
JA
2703 new_line = savestring (rl_line_buffer);
2704 expanded_string = expand_string (new_line, 0);
2705 FREE (new_line);
ccc6cda3
JA
2706 if (expanded_string == 0)
2707 {
f73dda09 2708 new_line = (char *)xmalloc (1);
ccc6cda3
JA
2709 new_line[0] = '\0';
2710 }
2711 else
2712 {
2713 new_line = string_list (expanded_string);
2714 dispose_words (expanded_string);
2715 }
726f6388 2716
ccc6cda3
JA
2717 maybe_make_readline_line (new_line);
2718 free (new_line);
726f6388 2719
ccc6cda3
JA
2720 /* Place rl_point where we think it should go. */
2721 if (at_end)
2722 rl_point = rl_end;
2723 else if (old_point < rl_end)
2724 {
2725 rl_point = old_point;
2726 if (!whitespace (rl_line_buffer[rl_point]))
b72432fd 2727 rl_forward_word (1, 0);
ccc6cda3 2728 }
28ef6c31 2729 return 0;
726f6388
JA
2730 }
2731 else
28ef6c31
JA
2732 {
2733 cleanup_expansion_error ();
2734 return 1;
2735 }
726f6388
JA
2736}
2737
ccc6cda3
JA
2738/* If FIGNORE is set, then don't match files with the given suffixes when
2739 completing filenames. If only one of the possibilities has an acceptable
726f6388
JA
2740 suffix, delete the others, else just return and let the completer
2741 signal an error. It is called by the completer when real
2742 completions are done on filenames by the completer's internal
2743 function, not for completion lists (M-?) and not on "other"
ccc6cda3 2744 completion types, such as hostnames or commands. */
726f6388 2745
ccc6cda3 2746static struct ignorevar fignore =
726f6388 2747{
ccc6cda3
JA
2748 "FIGNORE",
2749 (struct ign *)0,
2750 0,
2751 (char *)0,
f73dda09 2752 (sh_iv_item_func_t *) 0,
ccc6cda3 2753};
726f6388 2754
726f6388 2755static void
ccc6cda3 2756_ignore_completion_names (names, name_func)
726f6388 2757 char **names;
f73dda09 2758 sh_ignore_func_t *name_func;
726f6388
JA
2759{
2760 char **newnames;
2761 int idx, nidx;
cce855bc
JA
2762 char **oldnames;
2763 int oidx;
726f6388
JA
2764
2765 /* If there is only one completion, see if it is acceptable. If it is
2766 not, free it up. In any case, short-circuit and return. This is a
2767 special case because names[0] is not the prefix of the list of names
2768 if there is only one completion; it is the completion itself. */
2769 if (names[1] == (char *)0)
2770 {
d3a24ed2
CR
2771 if (force_fignore)
2772 if ((*name_func) (names[0]) == 0)
2773 {
2774 free (names[0]);
2775 names[0] = (char *)NULL;
2776 }
2777
726f6388
JA
2778 return;
2779 }
2780
2781 /* Allocate space for array to hold list of pointers to matching
2782 filenames. The pointers are copied back to NAMES when done. */
2783 for (nidx = 1; names[nidx]; nidx++)
2784 ;
7117c2d2 2785 newnames = strvec_create (nidx + 1);
d3a24ed2
CR
2786
2787 if (force_fignore == 0)
2788 {
2789 oldnames = strvec_create (nidx - 1);
2790 oidx = 0;
2791 }
726f6388
JA
2792
2793 newnames[0] = names[0];
2794 for (idx = nidx = 1; names[idx]; idx++)
2795 {
2796 if ((*name_func) (names[idx]))
2797 newnames[nidx++] = names[idx];
d3a24ed2
CR
2798 else if (force_fignore == 0)
2799 oldnames[oidx++] = names[idx];
726f6388 2800 else
28ef6c31 2801 free (names[idx]);
726f6388
JA
2802 }
2803
2804 newnames[nidx] = (char *)NULL;
2805
2806 /* If none are acceptable then let the completer handle it. */
2807 if (nidx == 1)
2808 {
d3a24ed2
CR
2809 if (force_fignore)
2810 {
2811 free (names[0]);
2812 names[0] = (char *)NULL;
2813 }
2814 else
2815 free (oldnames);
2816
726f6388
JA
2817 free (newnames);
2818 return;
2819 }
2820
d3a24ed2
CR
2821 if (force_fignore == 0)
2822 {
2823 while (oidx)
2824 free (oldnames[--oidx]);
2825 free (oldnames);
2826 }
cce855bc 2827
726f6388
JA
2828 /* If only one is acceptable, copy it to names[0] and return. */
2829 if (nidx == 2)
2830 {
2831 free (names[0]);
2832 names[0] = newnames[1];
2833 names[1] = (char *)NULL;
2834 free (newnames);
2835 return;
2836 }
ccc6cda3 2837
726f6388
JA
2838 /* Copy the acceptable names back to NAMES, set the new array end,
2839 and return. */
2840 for (nidx = 1; newnames[nidx]; nidx++)
2841 names[nidx] = newnames[nidx];
2842 names[nidx] = (char *)NULL;
ccc6cda3
JA
2843 free (newnames);
2844}
2845
2846static int
2847name_is_acceptable (name)
f73dda09 2848 const char *name;
ccc6cda3
JA
2849{
2850 struct ign *p;
2851 int nlen;
2852
2853 for (nlen = strlen (name), p = fignore.ignores; p->val; p++)
2854 {
2855 if (nlen > p->len && p->len > 0 && STREQ (p->val, &name[nlen - p->len]))
2856 return (0);
2857 }
2858
2859 return (1);
726f6388
JA
2860}
2861
b72432fd
JA
2862#if 0
2863static int
2864ignore_dot_names (name)
2865 char *name;
2866{
2867 return (name[0] != '.');
2868}
2869#endif
2870
28ef6c31 2871static int
726f6388
JA
2872filename_completion_ignore (names)
2873 char **names;
2874{
b72432fd
JA
2875#if 0
2876 if (glob_dot_filenames == 0)
2877 _ignore_completion_names (names, ignore_dot_names);
2878#endif
2879
ccc6cda3 2880 setup_ignore_patterns (&fignore);
726f6388 2881
ccc6cda3 2882 if (fignore.num_ignores == 0)
28ef6c31 2883 return 0;
726f6388 2884
ccc6cda3 2885 _ignore_completion_names (names, name_is_acceptable);
28ef6c31
JA
2886
2887 return 0;
726f6388
JA
2888}
2889
57a07124 2890/* Return 1 if NAME is a directory. NAME undergoes tilde expansion. */
726f6388
JA
2891static int
2892test_for_directory (name)
f73dda09 2893 const char *name;
726f6388 2894{
726f6388 2895 char *fn;
57a07124 2896 int r;
726f6388 2897
7117c2d2 2898 fn = bash_tilde_expand (name, 0);
57a07124 2899 r = file_isdir (fn);
726f6388 2900 free (fn);
57a07124
CR
2901
2902 return (r);
726f6388
JA
2903}
2904
2905/* Remove files from NAMES, leaving directories. */
28ef6c31 2906static int
726f6388
JA
2907bash_ignore_filenames (names)
2908 char **names;
2909{
ccc6cda3 2910 _ignore_completion_names (names, test_for_directory);
28ef6c31 2911 return 0;
726f6388
JA
2912}
2913
bb70624e
JA
2914static int
2915return_zero (name)
f73dda09 2916 const char *name;
bb70624e
JA
2917{
2918 return 0;
2919}
2920
28ef6c31 2921static int
bb70624e
JA
2922bash_ignore_everything (names)
2923 char **names;
2924{
2925 _ignore_completion_names (names, return_zero);
28ef6c31 2926 return 0;
bb70624e
JA
2927}
2928
6a8fd0ed
CR
2929/* Replace a tilde-prefix in VAL with a `~', assuming the user typed it. VAL
2930 is an expanded filename. DIRECTORY_PART is the tilde-prefix portion
2931 of the un-tilde-expanded version of VAL (what the user typed). */
2932static char *
2933restore_tilde (val, directory_part)
2934 char *val, *directory_part;
2935{
2936 int l, vl, dl2, xl;
2937 char *dh2, *expdir, *ret;
2938
2939 vl = strlen (val);
2940
2941 /* We need to duplicate the expansions readline performs on the directory
2942 portion before passing it to our completion function. */
2943 dh2 = directory_part ? bash_dequote_filename (directory_part, 0) : 0;
2944 bash_directory_expansion (&dh2);
2945 dl2 = strlen (dh2);
2946
2947 expdir = bash_tilde_expand (directory_part, 0);
2948 xl = strlen (expdir);
2949 free (expdir);
2950
2951 /*
2952 dh2 = unexpanded but dequoted tilde-prefix
2953 dl2 = length of tilde-prefix
2954 expdir = tilde-expanded tilde-prefix
2955 xl = length of expanded tilde-prefix
2956 l = length of remainder after tilde-prefix
2957 */
2958 l = (vl - xl) + 1;
2959
2960 ret = (char *)xmalloc (dl2 + 2 + l);
2961 strcpy (ret, dh2);
2962 strcpy (ret + dl2, val + xl);
2963
2964 free (dh2);
2965 return (ret);
2966}
2967
39feef01
CR
2968static char *
2969maybe_restore_tilde (val, directory_part)
2970 char *val, *directory_part;
2971{
2972 rl_icppfunc_t *save;
2973 char *ret;
2974
2975 save = (dircomplete_expand == 0) ? save_directory_hook () : (rl_icppfunc_t *)0;
2976 ret = restore_tilde (val, directory_part);
2977 if (save)
2978 restore_directory_hook (save);
2979 return ret;
2980}
2981
40b074c6
CR
2982/* Simulate the expansions that will be performed by
2983 rl_filename_completion_function. This must be called with the address of
2984 a pointer to malloc'd memory. */
e624d0f7 2985static void
40b074c6
CR
2986bash_directory_expansion (dirname)
2987 char **dirname;
2988{
ac18b312 2989 char *d, *nd;
40b074c6
CR
2990
2991 d = savestring (*dirname);
2992
e73012f1 2993 if ((rl_directory_rewrite_hook) && (*rl_directory_rewrite_hook) (&d))
631b20c6
CR
2994 {
2995 free (*dirname);
2996 *dirname = d;
2997 }
deeba0d2 2998 else if (rl_directory_completion_hook && (*rl_directory_completion_hook) (&d))
40b074c6
CR
2999 {
3000 free (*dirname);
3001 *dirname = d;
3002 }
ac18b312
CR
3003 else if (rl_completion_found_quote)
3004 {
3005 nd = bash_dequote_filename (d, rl_completion_quote_character);
3006 free (*dirname);
3007 free (d);
3008 *dirname = nd;
3009 }
40b074c6 3010}
8943768b 3011
8f714a7c
CR
3012/* If necessary, rewrite directory entry */
3013static char *
3014bash_filename_rewrite_hook (fname, fnlen)
3015 char *fname;
3016 int fnlen;
3017{
3018 char *conv;
3019
3020 conv = fnx_fromfs (fname, fnlen);
3021 if (conv != fname)
3022 conv = savestring (conv);
3023 return conv;
3024}
3025
adf2f609 3026/* Functions to save and restore the appropriate directory hook */
74d0116b
CR
3027/* This is not static so the shopt code can call it */
3028void
adf2f609
CR
3029set_directory_hook ()
3030{
3031 if (dircomplete_expand)
74d0116b
CR
3032 {
3033 rl_directory_completion_hook = bash_directory_completion_hook;
3034 rl_directory_rewrite_hook = (rl_icppfunc_t *)0;
3035 }
adf2f609 3036 else
74d0116b
CR
3037 {
3038 rl_directory_rewrite_hook = bash_directory_completion_hook;
3039 rl_directory_completion_hook = (rl_icppfunc_t *)0;
3040 }
adf2f609
CR
3041}
3042
3043static rl_icppfunc_t *
3044save_directory_hook ()
3045{
3046 rl_icppfunc_t *ret;
3047
3048 if (dircomplete_expand)
3049 {
3050 ret = rl_directory_completion_hook;
3051 rl_directory_completion_hook = (rl_icppfunc_t *)NULL;
3052 }
3053 else
3054 {
3055 ret = rl_directory_rewrite_hook;
3056 rl_directory_rewrite_hook = (rl_icppfunc_t *)NULL;
3057 }
3058
3059 return ret;
3060}
3061
3062static void
3063restore_directory_hook (hookf)
3064 rl_icppfunc_t *hookf;
3065{
3066 if (dircomplete_expand)
3067 rl_directory_completion_hook = hookf;
3068 else
3069 rl_directory_rewrite_hook = hookf;
3070}
3071
122f603c
CR
3072/* Expand a filename before the readline completion code passes it to stat(2).
3073 The filename will already have had tilde expansion performed. */
ddef12ff
CR
3074static int
3075bash_filename_stat_hook (dirname)
3076 char **dirname;
3077{
3078 char *local_dirname, *new_dirname, *t;
3079 int should_expand_dirname, return_value;
3080 WORD_LIST *wl;
3081 struct stat sb;
3082
3083 local_dirname = *dirname;
3084 should_expand_dirname = return_value = 0;
3085 if (t = mbschr (local_dirname, '$'))
3086 should_expand_dirname = '$';
3087 else if (t = mbschr (local_dirname, '`')) /* XXX */
3088 should_expand_dirname = '`';
3089
3090#if defined (HAVE_LSTAT)
3091 if (should_expand_dirname && lstat (local_dirname, &sb) == 0)
3092#else
3093 if (should_expand_dirname && stat (local_dirname, &sb) == 0)
3094#endif
3095 should_expand_dirname = 0;
3096
3097 if (should_expand_dirname)
3098 {
3099 new_dirname = savestring (local_dirname);
3100 wl = expand_prompt_string (new_dirname, 0, W_NOCOMSUB); /* does the right thing */
3101 if (wl)
3102 {
3103 free (new_dirname);
3104 new_dirname = string_list (wl);
3105 /* Tell the completer we actually expanded something and change
3106 *dirname only if we expanded to something non-null -- stat
3107 behaves unpredictably when passed null or empty strings */
3108 if (new_dirname && *new_dirname)
3109 {
200aed9a
CR
3110 free (local_dirname); /* XXX */
3111 local_dirname = *dirname = new_dirname;
ddef12ff
CR
3112 return_value = STREQ (local_dirname, *dirname) == 0;
3113 }
122f603c
CR
3114 else
3115 free (new_dirname);
ddef12ff
CR
3116 dispose_words (wl);
3117 }
3118 else
3119 free (new_dirname);
3120 }
3121
e107650c
CR
3122 /* This is very similar to the code in bash_directory_completion_hook below,
3123 but without spelling correction and not worrying about whether or not
3124 we change relative pathnames. */
3125 if (no_symbolic_links == 0 && (local_dirname[0] != '.' || local_dirname[1]))
3126 {
3127 char *temp1, *temp2;
3128
3129 t = get_working_directory ("symlink-hook");
3130 temp1 = make_absolute (local_dirname, t);
3131 free (t);
3132 temp2 = sh_canonpath (temp1, PATH_CHECKDOTDOT|PATH_CHECKEXISTS);
3133
3134 /* If we can't canonicalize, bail. */
3135 if (temp2 == 0)
3136 {
3137 free (temp1);
3138 return return_value;
3139 }
3140
3141 free (local_dirname);
3142 *dirname = temp2;
3143 free (temp1);
3144 }
3145
ddef12ff
CR
3146 return (return_value);
3147}
3148
726f6388 3149/* Handle symbolic link references and other directory name
54a1fa7c
CR
3150 expansions while hacking completion. This should return 1 if it modifies
3151 the DIRNAME argument, 0 otherwise. It should make sure not to modify
3152 DIRNAME if it returns 0. */
726f6388
JA
3153static int
3154bash_directory_completion_hook (dirname)
3155 char **dirname;
3156{
b72432fd 3157 char *local_dirname, *new_dirname, *t;
7df0c1b2 3158 int return_value, should_expand_dirname, nextch, closer;
726f6388 3159 WORD_LIST *wl;
56299fa5 3160 struct stat sb;
726f6388 3161
7df0c1b2 3162 return_value = should_expand_dirname = nextch = closer = 0;
726f6388 3163 local_dirname = *dirname;
bb70624e 3164
7df0c1b2
CR
3165 if (t = mbschr (local_dirname, '$'))
3166 {
3167 should_expand_dirname = '$';
3168 nextch = t[1];
3169 /* Deliberately does not handle the deprecated $[...] arithmetic
3170 expansion syntax */
3171 if (nextch == '(')
3172 closer = ')';
3173 else if (nextch == '{')
3174 closer = '}';
3175 else
3176 nextch = 0;
3177 }
8360b906
CR
3178 else if (local_dirname[0] == '~')
3179 should_expand_dirname = '~';
bb70624e
JA
3180 else
3181 {
d0ca3503 3182 t = mbschr (local_dirname, '`');
bb70624e 3183 if (t && unclosed_pair (local_dirname, strlen (local_dirname), "`") == 0)
7df0c1b2 3184 should_expand_dirname = '`';
bb70624e 3185 }
bb70624e 3186
56299fa5
CR
3187#if defined (HAVE_LSTAT)
3188 if (should_expand_dirname && lstat (local_dirname, &sb) == 0)
3189#else
3190 if (should_expand_dirname && stat (local_dirname, &sb) == 0)
3191#endif
3192 should_expand_dirname = 0;
3193
bb70624e 3194 if (should_expand_dirname)
726f6388 3195 {
bb70624e 3196 new_dirname = savestring (local_dirname);
4d8d005b 3197 wl = expand_prompt_string (new_dirname, 0, W_NOCOMSUB); /* does the right thing */
726f6388
JA
3198 if (wl)
3199 {
3200 *dirname = string_list (wl);
3201 /* Tell the completer to replace the directory name only if we
3202 actually expanded something. */
3203 return_value = STREQ (local_dirname, *dirname) == 0;
3204 free (local_dirname);
b72432fd 3205 free (new_dirname);
726f6388
JA
3206 dispose_words (wl);
3207 local_dirname = *dirname;
7df0c1b2
CR
3208 /* XXX - change rl_filename_quote_characters here based on
3209 should_expand_dirname/nextch/closer. This is the only place
3210 custom_filename_quote_characters is modified. */
3211 if (rl_filename_quote_characters && *rl_filename_quote_characters)
3212 {
3213 int i, j, c;
3214 i = strlen (default_filename_quote_characters);
3215 custom_filename_quote_characters = xrealloc (custom_filename_quote_characters, i+1);
3216 for (i = j = 0; c = default_filename_quote_characters[i]; i++)
3217 {
3218 if (c == should_expand_dirname || c == nextch || c == closer)
3219 continue;
3220 custom_filename_quote_characters[j++] = c;
3221 }
3222 custom_filename_quote_characters[j] = '\0';
3223 rl_filename_quote_characters = custom_filename_quote_characters;
ddef12ff 3224 set_filename_bstab (rl_filename_quote_characters);
7df0c1b2 3225 }
726f6388
JA
3226 }
3227 else
3228 {
b72432fd 3229 free (new_dirname);
726f6388 3230 free (local_dirname);
f73dda09 3231 *dirname = (char *)xmalloc (1);
ccc6cda3 3232 **dirname = '\0';
726f6388
JA
3233 return 1;
3234 }
3235 }
ac18b312
CR
3236 else
3237 {
3238 /* Dequote the filename even if we don't expand it. */
3239 new_dirname = bash_dequote_filename (local_dirname, rl_completion_quote_character);
54a1fa7c 3240 return_value = STREQ (local_dirname, new_dirname) == 0;
ac18b312
CR
3241 free (local_dirname);
3242 local_dirname = *dirname = new_dirname;
3243 }
726f6388 3244
e73012f1
CR
3245 /* no_symbolic_links == 0 -> use (default) logical view of the file system.
3246 local_dirname[0] == '.' && local_dirname[1] == '/' means files in the
3247 current directory (./).
3248 local_dirname[0] == '.' && local_dirname[1] == 0 means relative pathnames
3249 in the current directory (e.g., lib/sh).
3250 XXX - should we do spelling correction on these? */
3251
3252 /* This is test as it was in bash-4.2: skip relative pathnames in current
3253 directory. Change test to
3254 (local_dirname[0] != '.' || (local_dirname[1] && local_dirname[1] != '/'))
3255 if we want to skip paths beginning with ./ also. */
57a07124 3256 if (no_symbolic_links == 0 && (local_dirname[0] != '.' || local_dirname[1]))
726f6388
JA
3257 {
3258 char *temp1, *temp2;
3259 int len1, len2;
3260
e73012f1
CR
3261 /* If we have a relative path
3262 (local_dirname[0] != '/' && local_dirname[0] != '.')
3263 that is canonical after appending it to the current directory, then
3264 temp1 = temp2+'/'
3265 That is,
3266 strcmp (temp1, temp2) == 0
3267 after adding a slash to temp2 below. It should be safe to not
3268 change those.
3269 */
726f6388
JA
3270 t = get_working_directory ("symlink-hook");
3271 temp1 = make_absolute (local_dirname, t);
3272 free (t);
28ef6c31 3273 temp2 = sh_canonpath (temp1, PATH_CHECKDOTDOT|PATH_CHECKEXISTS);
4ac1ff98 3274
8360b906
CR
3275 /* Try spelling correction if initial canonicalization fails. Make
3276 sure we are set to replace the directory name with the results so
3277 subsequent directory checks don't fail. */
3278 if (temp2 == 0 && dircomplete_spelling && dircomplete_expand)
4ac1ff98
CR
3279 {
3280 temp2 = dirspell (temp1);
3281 if (temp2)
3282 {
3283 free (temp1);
3284 temp1 = temp2;
3285 temp2 = sh_canonpath (temp1, PATH_CHECKDOTDOT|PATH_CHECKEXISTS);
54a1fa7c 3286 return_value |= temp2 != 0;
4ac1ff98
CR
3287 }
3288 }
ccc6cda3
JA
3289 /* If we can't canonicalize, bail. */
3290 if (temp2 == 0)
3291 {
3292 free (temp1);
54a1fa7c 3293 return return_value;
ccc6cda3 3294 }
726f6388
JA
3295 len1 = strlen (temp1);
3296 if (temp1[len1 - 1] == '/')
28ef6c31 3297 {
726f6388 3298 len2 = strlen (temp2);
da719982
CR
3299 if (len2 > 2) /* don't append `/' to `/' or `//' */
3300 {
3301 temp2 = (char *)xrealloc (temp2, len2 + 2);
3302 temp2[len2] = '/';
3303 temp2[len2 + 1] = '\0';
3304 }
28ef6c31 3305 }
e73012f1
CR
3306
3307 /* dircomplete_expand_relpath == 0 means we want to leave relative
3308 pathnames that are unchanged by canonicalization alone.
3309 *local_dirname != '/' && *local_dirname != '.' == relative pathname
3310 (consistent with general.c:absolute_pathname())
3311 temp1 == temp2 (after appending a slash to temp2) means the pathname
3312 is not changed by canonicalization as described above. */
3313 if (dircomplete_expand_relpath || ((local_dirname[0] != '/' && local_dirname[0] != '.') && STREQ (temp1, temp2) == 0))
3314 return_value |= STREQ (local_dirname, temp2) == 0;
726f6388
JA
3315 free (local_dirname);
3316 *dirname = temp2;
3317 free (temp1);
3318 }
54a1fa7c 3319
726f6388
JA
3320 return (return_value);
3321}
3322
726f6388 3323static char **history_completion_array = (char **)NULL;
ccc6cda3
JA
3324static int harry_size;
3325static int harry_len;
726f6388
JA
3326
3327static void
3328build_history_completion_array ()
3329{
ccc6cda3
JA
3330 register int i, j;
3331 HIST_ENTRY **hlist;
3332 char **tokens;
726f6388
JA
3333
3334 /* First, clear out the current dynamic history completion list. */
3335 if (harry_size)
3336 {
7117c2d2 3337 strvec_dispose (history_completion_array);
726f6388
JA
3338 history_completion_array = (char **)NULL;
3339 harry_size = 0;
3340 harry_len = 0;
3341 }
3342
3343 /* Next, grovel each line of history, making each shell-sized token
3344 a separate entry in the history_completion_array. */
ccc6cda3 3345 hlist = history_list ();
726f6388 3346
ccc6cda3
JA
3347 if (hlist)
3348 {
3349 for (i = 0; hlist[i]; i++)
3eb2d94a
CR
3350 ;
3351 for ( --i; i >= 0; i--)
ccc6cda3
JA
3352 {
3353 /* Separate each token, and place into an array. */
3354 tokens = history_tokenize (hlist[i]->line);
726f6388 3355
ccc6cda3
JA
3356 for (j = 0; tokens && tokens[j]; j++)
3357 {
3358 if (harry_len + 2 > harry_size)
7117c2d2 3359 history_completion_array = strvec_resize (history_completion_array, harry_size += 10);
726f6388 3360
ccc6cda3
JA
3361 history_completion_array[harry_len++] = tokens[j];
3362 history_completion_array[harry_len] = (char *)NULL;
3363 }
3364 free (tokens);
3365 }
726f6388 3366
ccc6cda3 3367 /* Sort the complete list of tokens. */
3eb2d94a
CR
3368 if (dabbrev_expand_active == 0)
3369 qsort (history_completion_array, harry_len, sizeof (char *), (QSFUNC *)strvec_strcmp);
ccc6cda3 3370 }
726f6388
JA
3371}
3372
3373static char *
3374history_completion_generator (hint_text, state)
f73dda09 3375 const char *hint_text;
726f6388
JA
3376 int state;
3377{
ccc6cda3 3378 static int local_index, len;
f73dda09 3379 static const char *text;
726f6388
JA
3380
3381 /* If this is the first call to the generator, then initialize the
3382 list of strings to complete over. */
ccc6cda3 3383 if (state == 0)
726f6388 3384 {
3eb2d94a
CR
3385 if (dabbrev_expand_active) /* This is kind of messy */
3386 rl_completion_suppress_append = 1;
726f6388
JA
3387 local_index = 0;
3388 build_history_completion_array ();
3389 text = hint_text;
3390 len = strlen (text);
3391 }
3392
3393 while (history_completion_array && history_completion_array[local_index])
3394 {
3395 if (strncmp (text, history_completion_array[local_index++], len) == 0)
3396 return (savestring (history_completion_array[local_index - 1]));
3397 }
3398 return ((char *)NULL);
3399}
3400
28ef6c31 3401static int
726f6388
JA
3402dynamic_complete_history (count, key)
3403 int count, key;
3404{
f73dda09 3405 int r;
28ef6c31
JA
3406 rl_compentry_func_t *orig_func;
3407 rl_completion_func_t *orig_attempt_func;
6faad625 3408 rl_compignore_func_t *orig_ignore_func;
726f6388
JA
3409
3410 orig_func = rl_completion_entry_function;
3411 orig_attempt_func = rl_attempted_completion_function;
6faad625 3412 orig_ignore_func = rl_ignore_some_completions_function;
8943768b 3413
28ef6c31
JA
3414 rl_completion_entry_function = history_completion_generator;
3415 rl_attempted_completion_function = (rl_completion_func_t *)NULL;
6faad625 3416 rl_ignore_some_completions_function = filename_completion_ignore;
726f6388 3417
7117c2d2 3418 /* XXX - use rl_completion_mode here? */
28ef6c31 3419 if (rl_last_func == dynamic_complete_history)
f73dda09 3420 r = rl_complete_internal ('?');
726f6388 3421 else
f73dda09 3422 r = rl_complete_internal (TAB);
726f6388
JA
3423
3424 rl_completion_entry_function = orig_func;
3425 rl_attempted_completion_function = orig_attempt_func;
6faad625
CR
3426 rl_ignore_some_completions_function = orig_ignore_func;
3427
f73dda09 3428 return r;
726f6388
JA
3429}
3430
8943768b
CR
3431static int
3432bash_dabbrev_expand (count, key)
3433 int count, key;
3434{
3eb2d94a 3435 int r, orig_suppress, orig_sort;
8943768b
CR
3436 rl_compentry_func_t *orig_func;
3437 rl_completion_func_t *orig_attempt_func;
6faad625 3438 rl_compignore_func_t *orig_ignore_func;
8943768b
CR
3439
3440 orig_func = rl_menu_completion_entry_function;
3441 orig_attempt_func = rl_attempted_completion_function;
6faad625 3442 orig_ignore_func = rl_ignore_some_completions_function;
3eb2d94a
CR
3443 orig_suppress = rl_completion_suppress_append;
3444 orig_sort = rl_sort_completion_matches;
8943768b
CR
3445
3446 rl_menu_completion_entry_function = history_completion_generator;
3447 rl_attempted_completion_function = (rl_completion_func_t *)NULL;
6faad625 3448 rl_ignore_some_completions_function = filename_completion_ignore;
8943768b 3449 rl_filename_completion_desired = 0;
3eb2d94a
CR
3450 rl_completion_suppress_append = 1;
3451 rl_sort_completion_matches = 0;
8943768b
CR
3452
3453 /* XXX - use rl_completion_mode here? */
3eb2d94a 3454 dabbrev_expand_active = 1;
8943768b
CR
3455 if (rl_last_func == bash_dabbrev_expand)
3456 rl_last_func = rl_menu_complete;
3457 r = rl_menu_complete (count, key);
3eb2d94a 3458 dabbrev_expand_active = 0;
8943768b
CR
3459
3460 rl_last_func = bash_dabbrev_expand;
3461 rl_menu_completion_entry_function = orig_func;
3462 rl_attempted_completion_function = orig_attempt_func;
6faad625 3463 rl_ignore_some_completions_function = orig_ignore_func;
3eb2d94a
CR
3464 rl_completion_suppress_append = orig_suppress;
3465 rl_sort_completion_matches = orig_sort;
8943768b
CR
3466
3467 return r;
3468}
3469
726f6388 3470#if defined (SPECIFIC_COMPLETION_FUNCTIONS)
28ef6c31 3471static int
726f6388
JA
3472bash_complete_username (ignore, ignore2)
3473 int ignore, ignore2;
3474{
7117c2d2 3475 return bash_complete_username_internal (rl_completion_mode (bash_complete_username));
726f6388
JA
3476}
3477
28ef6c31 3478static int
726f6388
JA
3479bash_possible_username_completions (ignore, ignore2)
3480 int ignore, ignore2;
3481{
28ef6c31 3482 return bash_complete_username_internal ('?');
726f6388
JA
3483}
3484
28ef6c31 3485static int
726f6388
JA
3486bash_complete_username_internal (what_to_do)
3487 int what_to_do;
3488{
28ef6c31 3489 return bash_specific_completion (what_to_do, rl_username_completion_function);
726f6388
JA
3490}
3491
28ef6c31 3492static int
726f6388
JA
3493bash_complete_filename (ignore, ignore2)
3494 int ignore, ignore2;
3495{
7117c2d2 3496 return bash_complete_filename_internal (rl_completion_mode (bash_complete_filename));
726f6388
JA
3497}
3498
28ef6c31 3499static int
726f6388
JA
3500bash_possible_filename_completions (ignore, ignore2)
3501 int ignore, ignore2;
3502{
28ef6c31 3503 return bash_complete_filename_internal ('?');
726f6388
JA
3504}
3505
28ef6c31 3506static int
726f6388
JA
3507bash_complete_filename_internal (what_to_do)
3508 int what_to_do;
3509{
28ef6c31
JA
3510 rl_compentry_func_t *orig_func;
3511 rl_completion_func_t *orig_attempt_func;
3512 rl_icppfunc_t *orig_dir_func;
6faad625 3513 rl_compignore_func_t *orig_ignore_func;
d3a24ed2 3514 /*const*/ char *orig_rl_completer_word_break_characters;
28ef6c31 3515 int r;
726f6388
JA
3516
3517 orig_func = rl_completion_entry_function;
3518 orig_attempt_func = rl_attempted_completion_function;
6faad625 3519 orig_ignore_func = rl_ignore_some_completions_function;
726f6388 3520 orig_rl_completer_word_break_characters = rl_completer_word_break_characters;
adf2f609
CR
3521
3522 orig_dir_func = save_directory_hook ();
3523
28ef6c31
JA
3524 rl_completion_entry_function = rl_filename_completion_function;
3525 rl_attempted_completion_function = (rl_completion_func_t *)NULL;
6faad625 3526 rl_ignore_some_completions_function = filename_completion_ignore;
726f6388
JA
3527 rl_completer_word_break_characters = " \t\n\"\'";
3528
28ef6c31 3529 r = rl_complete_internal (what_to_do);
726f6388
JA
3530
3531 rl_completion_entry_function = orig_func;
3532 rl_attempted_completion_function = orig_attempt_func;
6faad625 3533 rl_ignore_some_completions_function = orig_ignore_func;
726f6388 3534 rl_completer_word_break_characters = orig_rl_completer_word_break_characters;
28ef6c31 3535
adf2f609
CR
3536 restore_directory_hook (orig_dir_func);
3537
28ef6c31 3538 return r;
726f6388
JA
3539}
3540
28ef6c31 3541static int
726f6388
JA
3542bash_complete_hostname (ignore, ignore2)
3543 int ignore, ignore2;
3544{
7117c2d2 3545 return bash_complete_hostname_internal (rl_completion_mode (bash_complete_hostname));
726f6388
JA
3546}
3547
28ef6c31 3548static int
726f6388
JA
3549bash_possible_hostname_completions (ignore, ignore2)
3550 int ignore, ignore2;
3551{
28ef6c31 3552 return bash_complete_hostname_internal ('?');
726f6388
JA
3553}
3554
28ef6c31 3555static int
726f6388
JA
3556bash_complete_variable (ignore, ignore2)
3557 int ignore, ignore2;
3558{
7117c2d2 3559 return bash_complete_variable_internal (rl_completion_mode (bash_complete_variable));
726f6388
JA
3560}
3561
28ef6c31 3562static int
726f6388
JA
3563bash_possible_variable_completions (ignore, ignore2)
3564 int ignore, ignore2;
3565{
28ef6c31 3566 return bash_complete_variable_internal ('?');
726f6388
JA
3567}
3568
28ef6c31 3569static int
726f6388
JA
3570bash_complete_command (ignore, ignore2)
3571 int ignore, ignore2;
3572{
7117c2d2 3573 return bash_complete_command_internal (rl_completion_mode (bash_complete_command));
726f6388
JA
3574}
3575
28ef6c31 3576static int
726f6388
JA
3577bash_possible_command_completions (ignore, ignore2)
3578 int ignore, ignore2;
3579{
28ef6c31 3580 return bash_complete_command_internal ('?');
726f6388
JA
3581}
3582
28ef6c31 3583static int
726f6388
JA
3584bash_complete_hostname_internal (what_to_do)
3585 int what_to_do;
3586{
28ef6c31 3587 return bash_specific_completion (what_to_do, hostname_completion_function);
726f6388
JA
3588}
3589
28ef6c31 3590static int
726f6388
JA
3591bash_complete_variable_internal (what_to_do)
3592 int what_to_do;
3593{
28ef6c31 3594 return bash_specific_completion (what_to_do, variable_completion_function);
726f6388
JA
3595}
3596
28ef6c31 3597static int
726f6388
JA
3598bash_complete_command_internal (what_to_do)
3599 int what_to_do;
3600{
28ef6c31 3601 return bash_specific_completion (what_to_do, command_word_completion_function);
726f6388
JA
3602}
3603
7117c2d2
JA
3604static char *globtext;
3605static char *globorig;
3606
ccc6cda3
JA
3607static char *
3608glob_complete_word (text, state)
28ef6c31 3609 const char *text;
ccc6cda3
JA
3610 int state;
3611{
3612 static char **matches = (char **)NULL;
3613 static int ind;
7117c2d2 3614 int glen;
898cc92e 3615 char *ret, *ttext;
ccc6cda3
JA
3616
3617 if (state == 0)
3618 {
e8ce775d 3619 rl_filename_completion_desired = 1;
7117c2d2
JA
3620 FREE (matches);
3621 if (globorig != globtext)
3622 FREE (globorig);
3623 FREE (globtext);
3624
898cc92e
CR
3625 ttext = bash_tilde_expand (text, 0);
3626
7117c2d2
JA
3627 if (rl_explicit_arg)
3628 {
898cc92e
CR
3629 globorig = savestring (ttext);
3630 glen = strlen (ttext);
7117c2d2 3631 globtext = (char *)xmalloc (glen + 2);
898cc92e 3632 strcpy (globtext, ttext);
7117c2d2
JA
3633 globtext[glen] = '*';
3634 globtext[glen+1] = '\0';
3635 }
3636 else
898cc92e
CR
3637 globtext = globorig = savestring (ttext);
3638
3639 if (ttext != text)
3640 free (ttext);
7117c2d2
JA
3641
3642 matches = shell_glob_filename (globtext);
ccc6cda3 3643 if (GLOB_FAILED (matches))
28ef6c31 3644 matches = (char **)NULL;
ccc6cda3
JA
3645 ind = 0;
3646 }
3647
3648 ret = matches ? matches[ind] : (char *)NULL;
3649 ind++;
3650 return ret;
3651}
3652
28ef6c31 3653static int
ccc6cda3
JA
3654bash_glob_completion_internal (what_to_do)
3655 int what_to_do;
3656{
28ef6c31 3657 return bash_specific_completion (what_to_do, glob_complete_word);
ccc6cda3
JA
3658}
3659
7117c2d2
JA
3660/* A special quoting function so we don't end up quoting globbing characters
3661 in the word if there are no matches or multiple matches. */
3662static char *
3663bash_glob_quote_filename (s, rtype, qcp)
3664 char *s;
3665 int rtype;
3666 char *qcp;
3667{
3668 if (globorig && qcp && *qcp == '\0' && STREQ (s, globorig))
3669 return (savestring (s));
3670 else
3671 return (bash_quote_filename (s, rtype, qcp));
3672}
3673
3674static int
3675bash_glob_complete_word (count, key)
3676 int count, key;
3677{
3678 int r;
3679 rl_quote_func_t *orig_quoting_function;
3680
56299fa5
CR
3681 if (rl_editing_mode == EMACS_EDITING_MODE)
3682 rl_explicit_arg = 1; /* force `*' append */
7117c2d2
JA
3683 orig_quoting_function = rl_filename_quoting_function;
3684 rl_filename_quoting_function = bash_glob_quote_filename;
3685
3686 r = bash_glob_completion_internal (rl_completion_mode (bash_glob_complete_word));
3687
3688 rl_filename_quoting_function = orig_quoting_function;
3689 return r;
3690}
3691
28ef6c31 3692static int
ccc6cda3
JA
3693bash_glob_expand_word (count, key)
3694 int count, key;
3695{
28ef6c31 3696 return bash_glob_completion_internal ('*');
ccc6cda3
JA
3697}
3698
28ef6c31 3699static int
ccc6cda3
JA
3700bash_glob_list_expansions (count, key)
3701 int count, key;
3702{
28ef6c31 3703 return bash_glob_completion_internal ('?');
ccc6cda3
JA
3704}
3705
28ef6c31 3706static int
726f6388
JA
3707bash_specific_completion (what_to_do, generator)
3708 int what_to_do;
28ef6c31 3709 rl_compentry_func_t *generator;
726f6388 3710{
28ef6c31
JA
3711 rl_compentry_func_t *orig_func;
3712 rl_completion_func_t *orig_attempt_func;
6faad625 3713 rl_compignore_func_t *orig_ignore_func;
28ef6c31 3714 int r;
726f6388
JA
3715
3716 orig_func = rl_completion_entry_function;
3717 orig_attempt_func = rl_attempted_completion_function;
6faad625 3718 orig_ignore_func = rl_ignore_some_completions_function;
726f6388 3719 rl_completion_entry_function = generator;
28ef6c31 3720 rl_attempted_completion_function = NULL;
6faad625 3721 rl_ignore_some_completions_function = orig_ignore_func;
726f6388 3722
28ef6c31 3723 r = rl_complete_internal (what_to_do);
726f6388
JA
3724
3725 rl_completion_entry_function = orig_func;
3726 rl_attempted_completion_function = orig_attempt_func;
6faad625 3727 rl_ignore_some_completions_function = orig_ignore_func;
28ef6c31
JA
3728
3729 return r;
726f6388
JA
3730}
3731
3732#endif /* SPECIFIC_COMPLETION_FUNCTIONS */
ccc6cda3 3733
da5b17cd
CR
3734#if defined (VI_MODE)
3735/* Completion, from vi mode's point of view. This is a modified version of
3736 rl_vi_complete which uses the bash globbing code to implement what POSIX
3737 specifies, which is to append a `*' and attempt filename generation (which
3738 has the side effect of expanding any globbing characters in the word). */
3739static int
3740bash_vi_complete (count, key)
3741 int count, key;
3742{
3743#if defined (SPECIFIC_COMPLETION_FUNCTIONS)
56299fa5
CR
3744 int p, r;
3745 char *t;
da5b17cd
CR
3746
3747 if ((rl_point < rl_end) && (!whitespace (rl_line_buffer[rl_point])))
3748 {
3749 if (!whitespace (rl_line_buffer[rl_point + 1]))
3750 rl_vi_end_word (1, 'E');
3751 rl_point++;
3752 }
3753
56299fa5
CR
3754 /* Find boundaries of current word, according to vi definition of a
3755 `bigword'. */
3756 t = 0;
3757 if (rl_point > 0)
3758 {
3759 p = rl_point;
3760 rl_vi_bWord (1, 'B');
3761 r = rl_point;
3762 rl_point = p;
3763 p = r;
3764
3765 t = substring (rl_line_buffer, p, rl_point);
3766 }
3767
3768 if (t && glob_pattern_p (t) == 0)
3769 rl_explicit_arg = 1; /* XXX - force glob_complete_word to append `*' */
3770 FREE (t);
da5b17cd
CR
3771
3772 if (key == '*') /* Expansion and replacement. */
3773 r = bash_glob_expand_word (count, key);
3774 else if (key == '=') /* List possible completions. */
3775 r = bash_glob_list_expansions (count, key);
3776 else if (key == '\\') /* Standard completion */
3777 r = bash_glob_complete_word (count, key);
3778 else
3779 r = rl_complete (0, key);
3780
3781 if (key == '*' || key == '\\')
3782 rl_vi_start_inserting (key, 1, 1);
3783
3784 return (r);
3785#else
3786 return rl_vi_complete (count, key);
3787#endif /* !SPECIFIC_COMPLETION_FUNCTIONS */
3788}
3789#endif /* VI_MODE */
3790
ccc6cda3 3791/* Filename quoting for completion. */
bb70624e
JA
3792/* A function to strip unquoted quote characters (single quotes, double
3793 quotes, and backslashes). It allows single quotes to appear
3794 within double quotes, and vice versa. It should be smarter. */
ccc6cda3
JA
3795static char *
3796bash_dequote_filename (text, quote_char)
3797 char *text;
28ef6c31 3798 int quote_char;
ccc6cda3
JA
3799{
3800 char *ret, *p, *r;
3801 int l, quoted;
3802
3803 l = strlen (text);
f73dda09 3804 ret = (char *)xmalloc (l + 1);
ccc6cda3
JA
3805 for (quoted = quote_char, p = text, r = ret; p && *p; p++)
3806 {
7e52d2bf 3807 /* Allow backslash-escaped characters to pass through unscathed. */
ccc6cda3
JA
3808 if (*p == '\\')
3809 {
7e52d2bf
CR
3810 /* Backslashes are preserved within single quotes. */
3811 if (quoted == '\'')
3812 *r++ = *p;
3813 /* Backslashes are preserved within double quotes unless the
3814 character is one that is defined to be escaped */
3815 else if (quoted == '"' && ((sh_syntaxtab[p[1]] & CBSDQUOTE) == 0))
3816 *r++ = *p;
3817
ccc6cda3
JA
3818 *r++ = *++p;
3819 if (*p == '\0')
5ccad779 3820 return ret; /* XXX - was break; */
ccc6cda3
JA
3821 continue;
3822 }
3823 /* Close quote. */
3824 if (quoted && *p == quoted)
28ef6c31
JA
3825 {
3826 quoted = 0;
3827 continue;
3828 }
ccc6cda3
JA
3829 /* Open quote. */
3830 if (quoted == 0 && (*p == '\'' || *p == '"'))
28ef6c31
JA
3831 {
3832 quoted = *p;
3833 continue;
3834 }
ccc6cda3
JA
3835 *r++ = *p;
3836 }
3837 *r = '\0';
3838 return ret;
3839}
3840
d166f048
JA
3841/* Quote characters that the readline completion code would treat as
3842 word break characters with backslashes. Pass backslash-quoted
3843 characters through without examination. */
3844static char *
3845quote_word_break_chars (text)
3846 char *text;
3847{
3848 char *ret, *r, *s;
3849 int l;
3850
3851 l = strlen (text);
f73dda09 3852 ret = (char *)xmalloc ((2 * l) + 1);
d166f048
JA
3853 for (s = text, r = ret; *s; s++)
3854 {
3855 /* Pass backslash-quoted characters through, including the backslash. */
3856 if (*s == '\\')
3857 {
3858 *r++ = '\\';
3859 *r++ = *++s;
3860 if (*s == '\0')
3861 break;
3862 continue;
3863 }
3864 /* OK, we have an unquoted character. Check its presence in
3865 rl_completer_word_break_characters. */
d0ca3503 3866 if (mbschr (rl_completer_word_break_characters, *s))
28ef6c31 3867 *r++ = '\\';
a9fac3b2
CR
3868 /* XXX -- check for standalone tildes here and backslash-quote them */
3869 if (s == text && *s == '~' && file_exists (text))
3870 *r++ = '\\';
d166f048
JA
3871 *r++ = *s;
3872 }
3873 *r = '\0';
3874 return ret;
3875}
3876
ddef12ff
CR
3877/* Use characters in STRING to populate the table of characters that should
3878 be backslash-quoted. The table will be used for sh_backslash_quote from
3879 this file. */
3880static void
3881set_filename_bstab (string)
3882 const char *string;
3883{
3884 const char *s;
3885
3886 memset (filename_bstab, 0, sizeof (filename_bstab));
3887 for (s = string; s && *s; s++)
3888 filename_bstab[*s] = 1;
3889}
3890
d166f048
JA
3891/* Quote a filename using double quotes, single quotes, or backslashes
3892 depending on the value of completion_quoting_style. If we're
3893 completing using backslashes, we need to quote some additional
3894 characters (those that readline treats as word breaks), so we call
7117c2d2
JA
3895 quote_word_break_chars on the result. This returns newly-allocated
3896 memory. */
ccc6cda3
JA
3897static char *
3898bash_quote_filename (s, rtype, qcp)
3899 char *s;
3900 int rtype;
3901 char *qcp;
3902{
3903 char *rtext, *mtext, *ret;
3904 int rlen, cs;
3905
3906 rtext = (char *)NULL;
3907
3908 /* If RTYPE == MULT_MATCH, it means that there is
3909 more than one match. In this case, we do not add
3910 the closing quote or attempt to perform tilde
3911 expansion. If RTYPE == SINGLE_MATCH, we try
3912 to perform tilde expansion, because single and double
3913 quotes inhibit tilde expansion by the shell. */
3914
ccc6cda3
JA
3915 cs = completion_quoting_style;
3916 /* Might need to modify the default completion style based on *qcp,
bb70624e
JA
3917 since it's set to any user-provided opening quote. We also change
3918 to single-quoting if there is no user-provided opening quote and
3919 the word being completed contains newlines, since those are not
3920 quoted correctly using backslashes (a backslash-newline pair is
3921 special to the shell parser). */
d0ca3503 3922 if (*qcp == '\0' && cs == COMPLETE_BSQUOTE && mbschr (s, '\n'))
bb70624e
JA
3923 cs = COMPLETE_SQUOTE;
3924 else if (*qcp == '"')
ccc6cda3
JA
3925 cs = COMPLETE_DQUOTE;
3926 else if (*qcp == '\'')
3927 cs = COMPLETE_SQUOTE;
3928#if defined (BANG_HISTORY)
3929 else if (*qcp == '\0' && history_expansion && cs == COMPLETE_DQUOTE &&
d0ca3503 3930 history_expansion_inhibited == 0 && mbschr (s, '!'))
ccc6cda3 3931 cs = COMPLETE_BSQUOTE;
d166f048
JA
3932
3933 if (*qcp == '"' && history_expansion && cs == COMPLETE_DQUOTE &&
d0ca3503 3934 history_expansion_inhibited == 0 && mbschr (s, '!'))
d166f048
JA
3935 {
3936 cs = COMPLETE_BSQUOTE;
3937 *qcp = '\0';
3938 }
ccc6cda3
JA
3939#endif
3940
6bf74e5a
CR
3941 /* Don't tilde-expand backslash-quoted filenames, since only single and
3942 double quotes inhibit tilde expansion. */
3943 mtext = s;
3944 if (mtext[0] == '~' && rtype == SINGLE_MATCH && cs != COMPLETE_BSQUOTE)
3945 mtext = bash_tilde_expand (s, 0);
3946
ccc6cda3
JA
3947 switch (cs)
3948 {
3949 case COMPLETE_DQUOTE:
28ef6c31 3950 rtext = sh_double_quote (mtext);
ccc6cda3
JA
3951 break;
3952 case COMPLETE_SQUOTE:
28ef6c31 3953 rtext = sh_single_quote (mtext);
ccc6cda3
JA
3954 break;
3955 case COMPLETE_BSQUOTE:
8360b906 3956 rtext = sh_backslash_quote (mtext, complete_fullquote ? 0 : filename_bstab, 0);
ccc6cda3
JA
3957 break;
3958 }
3959
3960 if (mtext != s)
3961 free (mtext);
3962
d166f048
JA
3963 /* We may need to quote additional characters: those that readline treats
3964 as word breaks that are not quoted by backslash_quote. */
3965 if (rtext && cs == COMPLETE_BSQUOTE)
3966 {
3967 mtext = quote_word_break_chars (rtext);
3968 free (rtext);
3969 rtext = mtext;
3970 }
3971
ccc6cda3
JA
3972 /* Leave the opening quote intact. The readline completion code takes
3973 care of avoiding doubled opening quotes. */
b28ff8c9
CR
3974 if (rtext)
3975 {
3976 rlen = strlen (rtext);
3977 ret = (char *)xmalloc (rlen + 1);
3978 strcpy (ret, rtext);
3979 }
3980 else
3981 {
3982 ret = (char *)xmalloc (rlen = 1);
3983 ret[0] = '\0';
3984 }
ccc6cda3
JA
3985
3986 /* If there are multiple matches, cut off the closing quote. */
3987 if (rtype == MULT_MATCH && cs != COMPLETE_BSQUOTE)
3988 ret[rlen - 1] = '\0';
3989 free (rtext);
3990 return ret;
3991}
3992
bb70624e
JA
3993/* Support for binding readline key sequences to Unix commands. */
3994static Keymap cmd_xmap;
3995
7175a77f
CR
3996#ifdef _MINIX
3997static void
3998#else
dfc21851 3999static int
7175a77f 4000#endif
dfc21851
CR
4001putx(c)
4002 int c;
4003{
7175a77f
CR
4004 int x;
4005 x = putc (c, rl_outstream);
4006#ifndef _MINIX
4007 return x;
4008#endif
dfc21851
CR
4009}
4010
bb70624e
JA
4011static int
4012bash_execute_unix_command (count, key)
4013 int count; /* ignored */
4014 int key;
4015{
4016 Keymap ckmap; /* current keymap */
4017 Keymap xkmap; /* unix command executing keymap */
ba4ab055
CR
4018 rl_command_func_t *func;
4019 int type;
dfc21851 4020 register int i, r;
8943768b 4021 intmax_t mi;
d3a24ed2 4022 sh_parser_state_t ps;
824dfe68 4023 char *cmd, *value, *l, *l1, *ce;
8943768b
CR
4024 SHELL_VAR *v;
4025 char ibuf[INT_STRLEN_BOUND(int) + 1];
bb70624e
JA
4026
4027 /* First, we need to find the right command to execute. This is tricky,
ba4ab055
CR
4028 because we might have already indirected into another keymap, so we
4029 have to walk cmd_xmap using the entire key sequence. */
4030 cmd = (char *)rl_function_of_keyseq (rl_executing_keyseq, cmd_xmap, &type);
4031
4032 if (cmd == 0 || type != ISMACR)
bb70624e 4033 {
ba4ab055
CR
4034 rl_crlf ();
4035 internal_error (_("bash_execute_unix_command: cannot find keymap for command"));
4036 rl_forced_update_display ();
bb70624e
JA
4037 return 1;
4038 }
4039
dfc21851
CR
4040 ce = rl_get_termcap ("ce");
4041 if (ce) /* clear current line */
4042 {
4043 fprintf (rl_outstream, "\r");
4044 tputs (ce, 1, putx);
4045 fflush (rl_outstream);
4046 }
4047 else
4048 rl_crlf (); /* move to a new line */
bb70624e 4049
8943768b
CR
4050 v = bind_variable ("READLINE_LINE", rl_line_buffer, 0);
4051 if (v)
4052 VSETATTR (v, att_exported);
824dfe68 4053 l = v ? value_cell (v) : 0;
8943768b
CR
4054 value = inttostr (rl_point, ibuf, sizeof (ibuf));
4055 v = bind_int_variable ("READLINE_POINT", value);
4056 if (v)
4057 VSETATTR (v, att_exported);
4058 array_needs_making = 1;
4059
d3a24ed2 4060 save_parser_state (&ps);
dfc21851 4061 r = parse_and_execute (cmd, "bash_execute_unix_command", SEVAL_NOHIST|SEVAL_NOFREE);
8943768b 4062 restore_parser_state (&ps);
7117c2d2 4063
8943768b 4064 v = find_variable ("READLINE_LINE");
824dfe68
CR
4065 l1 = v ? value_cell (v) : 0;
4066 if (l1 != l)
8943768b
CR
4067 maybe_make_readline_line (value_cell (v));
4068 v = find_variable ("READLINE_POINT");
4069 if (v && legal_number (value_cell (v), &mi))
4070 {
4071 i = mi;
0527c903 4072 if (i != rl_point)
8943768b
CR
4073 {
4074 rl_point = i;
4075 if (rl_point > rl_end)
4076 rl_point = rl_end;
4077 else if (rl_point < 0)
4078 rl_point = 0;
4079 }
4080 }
7117c2d2 4081
8943768b
CR
4082 unbind_variable ("READLINE_LINE");
4083 unbind_variable ("READLINE_POINT");
4084 array_needs_making = 1;
bb70624e
JA
4085
4086 /* and restore the readline buffer and display after command execution. */
4087 rl_forced_update_display ();
4088 return 0;
4089}
4090
ba4ab055
CR
4091int
4092print_unix_command_map ()
4093{
4094 Keymap save;
4095
4096 save = rl_get_keymap ();
4097 rl_set_keymap (cmd_xmap);
4098 rl_macro_dumper (1);
4099 rl_set_keymap (save);
4100 return 0;
4101}
4102
bb70624e
JA
4103static void
4104init_unix_command_map ()
4105{
4106 cmd_xmap = rl_make_bare_keymap ();
4107}
4108
4109static int
4110isolate_sequence (string, ind, need_dquote, startp)
4111 char *string;
4112 int ind, need_dquote, *startp;
4113{
4114 register int i;
4115 int c, passc, delim;
4116
4117 for (i = ind; string[i] && whitespace (string[i]); i++)
4118 ;
4119 /* NEED_DQUOTE means that the first non-white character *must* be `"'. */
4120 if (need_dquote && string[i] != '"')
4121 {
5e13499c 4122 builtin_error (_("%s: first non-whitespace character is not `\"'"), string);
bb70624e
JA
4123 return -1;
4124 }
4125
4126 /* We can have delimited strings even if NEED_DQUOTE == 0, like the command
4127 string to bind the key sequence to. */
4128 delim = (string[i] == '"' || string[i] == '\'') ? string[i] : 0;
4129
4130 if (startp)
4131 *startp = delim ? ++i : i;
4132
4133 for (passc = 0; c = string[i]; i++)
4134 {
4135 if (passc)
4136 {
4137 passc = 0;
4138 continue;
4139 }
4140 if (c == '\\')
4141 {
4142 passc++;
4143 continue;
4144 }
4145 if (c == delim)
28ef6c31 4146 break;
bb70624e
JA
4147 }
4148
4149 if (delim && string[i] != delim)
4150 {
5e13499c 4151 builtin_error (_("no closing `%c' in %s"), delim, string);
bb70624e
JA
4152 return -1;
4153 }
4154
4155 return i;
4156}
4157
4158int
4159bind_keyseq_to_unix_command (line)
4160 char *line;
4161{
4162 Keymap kmap;
4163 char *kseq, *value;
f73dda09 4164 int i, kstart;
bb70624e
JA
4165
4166 if (cmd_xmap == 0)
4167 init_unix_command_map ();
4168
4169 kmap = rl_get_keymap ();
4170
4171 /* We duplicate some of the work done by rl_parse_and_bind here, but
4172 this code only has to handle `"keyseq": ["]command["]' and can
4173 generate an error for anything else. */
4174 i = isolate_sequence (line, 0, 1, &kstart);
4175 if (i < 0)
4176 return -1;
4177
4178 /* Create the key sequence string to pass to rl_generic_bind */
4179 kseq = substring (line, kstart, i);
4180
4181 for ( ; line[i] && line[i] != ':'; i++)
4182 ;
4183 if (line[i] != ':')
4184 {
5e13499c 4185 builtin_error (_("%s: missing colon separator"), line);
631b20c6 4186 FREE (kseq);
bb70624e
JA
4187 return -1;
4188 }
4189
4190 i = isolate_sequence (line, i + 1, 0, &kstart);
4191 if (i < 0)
631b20c6
CR
4192 {
4193 FREE (kseq);
4194 return -1;
4195 }
bb70624e
JA
4196
4197 /* Create the value string containing the command to execute. */
4198 value = substring (line, kstart, i);
4199
4200 /* Save the command to execute and the key sequence in the CMD_XMAP */
4201 rl_generic_bind (ISMACR, kseq, value, cmd_xmap);
4202
4203 /* and bind the key sequence in the current keymap to a function that
4204 understands how to execute from CMD_XMAP */
d3a24ed2 4205 rl_bind_keyseq_in_map (kseq, bash_execute_unix_command, kmap);
631b20c6
CR
4206
4207 free (kseq);
bb70624e
JA
4208 return 0;
4209}
4210
4211/* Used by the programmable completion code. Complete TEXT as a filename,
4212 but return only directories as matches. Dequotes the filename before
4213 attempting to find matches. */
4214char **
4215bash_directory_completion_matches (text)
28ef6c31 4216 const char *text;
bb70624e
JA
4217{
4218 char **m1;
4219 char *dfn;
4220 int qc;
4221
5e13499c 4222 qc = rl_dispatching ? rl_completion_quote_character : 0;
b4a17eba
CR
4223 /* If rl_completion_found_quote != 0, rl_completion_matches will call the
4224 filename dequoting function, causing the directory name to be dequoted
4225 twice. */
4226 if (rl_dispatching && rl_completion_found_quote == 0)
4227 dfn = bash_dequote_filename ((char *)text, qc);
4228 else
4229 dfn = (char *)text;
28ef6c31 4230 m1 = rl_completion_matches (dfn, rl_filename_completion_function);
b4a17eba
CR
4231 if (dfn != text)
4232 free (dfn);
bb70624e
JA
4233
4234 if (m1 == 0 || m1[0] == 0)
4235 return m1;
4236 /* We don't bother recomputing the lcd of the matches, because it will just
4237 get thrown away by the programmable completion code and recomputed
4238 later. */
4239 (void)bash_ignore_filenames (m1);
4240 return m1;
4241}
d3a24ed2
CR
4242
4243char *
4244bash_dequote_text (text)
4245 const char *text;
4246{
4247 char *dtxt;
4248 int qc;
4249
4250 qc = (text[0] == '"' || text[0] == '\'') ? text[0] : 0;
4251 dtxt = bash_dequote_filename ((char *)text, qc);
4252 return (dtxt);
4253}
d9e1f41e 4254
1b1fe467
CR
4255/* This event hook is designed to be called after readline receives a signal
4256 that interrupts read(2). It gives reasonable responsiveness to interrupts
4257 and fatal signals without executing too much code in a signal handler
4258 context. */
d9e1f41e
CR
4259static int
4260bash_event_hook ()
4261{
bb579650
CR
4262 /* If we're going to longjmp to top_level, make sure we clean up readline.
4263 check_signals will call QUIT, which will eventually longjmp to top_level,
fe570ea1
CR
4264 calling run_interrupt_trap along the way. The check for sigalrm_seen is
4265 to clean up the read builtin's state. */
96f3fb66 4266 if (terminating_signal || interrupt_state || sigalrm_seen)
1b1fe467 4267 rl_cleanup_after_signal ();
55a5a4ac 4268 bashline_reset_event_hook ();
1b1fe467 4269 check_signals_and_traps (); /* XXX */
d76edd30 4270 return 0;
d9e1f41e
CR
4271}
4272
ccc6cda3 4273#endif /* READLINE */