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