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