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