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