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