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