Imported from ../bash-2.04.tar.gz.
[platform/upstream/bash.git] / bashline.c
1 /* bashline.c -- Bash's interface to the readline library. */
2
3 /* Copyright (C) 1987,1991 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 #include <stdio.h>
33 #include "bashansi.h"
34 #include "shell.h"
35 #include "builtins.h"
36 #include "bashhist.h"
37 #include "bashline.h"
38 #include "execute_cmd.h"
39 #include "findcmd.h"
40 #include "pathexp.h"
41 #include "builtins/common.h"
42 #include <readline/rlconf.h>
43 #include <readline/readline.h>
44 #include <readline/history.h>
45
46 #include <glob/glob.h>
47
48 #if defined (ALIAS)
49 #  include "alias.h"
50 #endif
51
52 #if defined (PROGRAMMABLE_COMPLETION)
53 #  include "pcomplete.h"
54 #endif
55
56 #if defined (BRACE_COMPLETION)
57 extern void bash_brace_completion ();
58 #endif /* BRACE_COMPLETION */
59
60 /* Functions bound to keys in Readline for Bash users. */
61 static void shell_expand_line ();
62 static void display_shell_version (), operate_and_get_next ();
63 static void bash_ignore_filenames ();
64 static void bash_ignore_everything ();
65 static void cleanup_expansion_error (), set_up_new_line ();
66
67 #if defined (BANG_HISTORY)
68 static int history_expand_line ();
69 static int tcsh_magic_space ();
70 #endif /* BANG_HISTORY */
71 #ifdef ALIAS
72 static int alias_expand_line ();
73 #endif
74 #if defined (BANG_HISTORY) && defined (ALIAS)
75 static int history_and_alias_expand_line ();
76 #endif
77
78 /* Helper functions for Readline. */
79 static int bash_directory_completion_hook ();
80 static void filename_completion_ignore ();
81 static void bash_push_line ();
82
83 static char **attempt_shell_completion ();
84 static char *variable_completion_function ();
85 static char *hostname_completion_function ();
86 static char *command_subst_completion_function ();
87 static void dynamic_complete_history ();
88
89 static char *glob_complete_word ();
90 static void bash_glob_expand_word ();
91 static void bash_glob_list_expansions ();
92
93 static void snarf_hosts_from_file ();
94 static void add_host_name ();
95
96 static char *bash_dequote_filename ();
97 static char *bash_quote_filename ();
98
99 #if defined (ALIAS)
100 static int posix_edit_macros ();
101 #endif
102
103 #if defined (PROGRAMMABLE_COMPLETION)
104 static char **prog_complete_matches;
105 static int old_rl_completion_append_character;
106 #endif
107
108 /* Variables used here but defined in other files. */
109 extern int posixly_correct, no_symbolic_links;
110 extern int rl_explicit_arg;
111 extern char *current_prompt_string, *ps1_prompt;
112 extern STRING_INT_ALIST word_token_alist[];
113 extern Function *rl_last_func;
114 extern int rl_filename_completion_desired;
115
116 /* SPECIFIC_COMPLETION_FUNCTIONS specifies that we have individual
117    completion functions which indicate what type of completion should be
118    done (at or before point) that can be bound to key sequences with
119    the readline library. */
120 #define SPECIFIC_COMPLETION_FUNCTIONS
121
122 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
123 static void bash_specific_completion ();
124 static void bash_complete_filename (), bash_possible_filename_completions ();
125 static void bash_complete_filename_internal ();
126 static void bash_complete_username (), bash_possible_username_completions ();
127 static void bash_complete_username_internal ();
128 static void bash_complete_hostname (), bash_possible_hostname_completions ();
129 static void bash_complete_hostname_internal ();
130 static void bash_complete_variable (), bash_possible_variable_completions ();
131 static void bash_complete_variable_internal ();
132 static void bash_complete_command (), bash_possible_command_completions ();
133 static void bash_complete_command_internal ();
134 #endif /* SPECIFIC_COMPLETION_FUNCTIONS */
135
136 #if defined (VI_MODE)
137 static void vi_edit_and_execute_command ();
138 #endif
139
140 /* Non-zero once initalize_readline () has been called. */
141 int bash_readline_initialized = 0;
142
143 /* If non-zero, we do hostname completion, breaking words at `@' and
144    trying to complete the stuff after the `@' from our own internal
145    host list. */
146 int perform_hostname_completion = 1;
147
148 /* If non-zero, we don't do command completion on an empty line. */
149 int no_empty_command_completion;
150
151 static char *bash_completer_word_break_characters = " \t\n\"'@><=;|&(:";
152 static char *bash_nohostname_word_break_characters = " \t\n\"'><=;|&(:";
153
154 static Function *old_rl_startup_hook = (Function *) NULL;
155
156 /* What kind of quoting is performed by bash_quote_filename:
157         COMPLETE_DQUOTE = double-quoting the filename
158         COMPLETE_SQUOTE = single_quoting the filename
159         COMPLETE_BSQUOTE = backslash-quoting special chars in the filename
160 */
161 #define COMPLETE_DQUOTE  1
162 #define COMPLETE_SQUOTE  2
163 #define COMPLETE_BSQUOTE 3
164 static int completion_quoting_style = COMPLETE_BSQUOTE;
165
166 /* Change the readline VI-mode keymaps into or out of Posix.2 compliance.
167    Called when the shell is put into or out of `posix' mode. */
168 void
169 posix_readline_initialize (on_or_off)
170      int on_or_off;
171 {
172   if (on_or_off)
173     rl_variable_bind ("comment-begin", "#");
174 #if defined (VI_MODE)
175   rl_bind_key_in_map (CTRL('I'), on_or_off ? rl_insert : rl_complete, vi_insertion_keymap);
176 #endif
177 }
178
179 void
180 enable_hostname_completion (on_or_off)
181      int on_or_off;
182 {
183   if (on_or_off)
184     {
185       perform_hostname_completion = 1;
186       rl_special_prefixes = "$@";
187       rl_completer_word_break_characters = bash_completer_word_break_characters;
188     }
189   else
190     {
191       perform_hostname_completion = 0;
192       rl_special_prefixes = "$";
193       rl_completer_word_break_characters = bash_nohostname_word_break_characters;
194     }
195 }
196
197 /* Called once from parse.y if we are going to use readline. */
198 void
199 initialize_readline ()
200 {
201   if (bash_readline_initialized)
202     return;
203
204   rl_terminal_name = get_string_value ("TERM");
205   rl_instream = stdin;
206   rl_outstream = stderr;
207
208   /* Allow conditional parsing of the ~/.inputrc file. */
209   rl_readline_name = "Bash";
210
211   /* Bind up our special shell functions. */
212   rl_add_defun ("shell-expand-line", (Function *)shell_expand_line, -1);
213   rl_bind_key_in_map (CTRL('E'), (Function *)shell_expand_line, emacs_meta_keymap);
214
215   /* Bind up our special shell functions. */
216 #ifdef BANG_HISTORY
217   rl_add_defun ("history-expand-line", (Function *)history_expand_line, -1);
218   rl_bind_key_in_map ('^', (Function *)history_expand_line, emacs_meta_keymap);
219
220   rl_add_defun ("magic-space", (Function *)tcsh_magic_space, -1);
221 #endif
222
223 #ifdef ALIAS
224   rl_add_defun ("alias-expand-line", (Function *)alias_expand_line, -1);
225 #  ifdef BANG_HISTORY
226   rl_add_defun ("history-and-alias-expand-line", (Function *)history_and_alias_expand_line, -1);
227 #  endif
228 #endif
229
230   /* Backwards compatibility. */
231   rl_add_defun ("insert-last-argument", rl_yank_last_arg, -1);
232
233   rl_add_defun
234     ("operate-and-get-next", (Function *)operate_and_get_next, CTRL('O'));
235
236   rl_add_defun
237     ("display-shell-version", (Function *)display_shell_version, -1);
238   rl_bind_key_in_map
239     (CTRL ('V'), (Function *)display_shell_version, emacs_ctlx_keymap);
240
241   /* In Bash, the user can switch editing modes with "set -o [vi emacs]",
242      so it is not necessary to allow C-M-j for context switching.  Turn
243      off this occasionally confusing behaviour. */
244   rl_unbind_key_in_map (CTRL('J'), emacs_meta_keymap);
245   rl_unbind_key_in_map (CTRL('M'), emacs_meta_keymap);
246 #if defined (VI_MODE)
247   rl_unbind_key_in_map (CTRL('E'), vi_movement_keymap);
248 #endif
249
250 #if defined (BRACE_COMPLETION)
251   rl_add_defun ("complete-into-braces", (Function *)bash_brace_completion, -1);
252   rl_bind_key_in_map ('{', (Function *)bash_brace_completion, emacs_meta_keymap);
253 #endif /* BRACE_COMPLETION */
254
255 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
256   rl_add_defun ("complete-filename", (Function *)bash_complete_filename, -1);
257   rl_bind_key_in_map ('/', (Function *)bash_complete_filename, emacs_meta_keymap);
258   rl_add_defun ("possible-filename-completions",
259                 (Function *)bash_possible_filename_completions, -1);
260   rl_bind_key_in_map ('/', (Function *)bash_possible_filename_completions, emacs_ctlx_keymap);
261
262   rl_add_defun ("complete-username", (Function *)bash_complete_username, -1);
263   rl_bind_key_in_map ('~', (Function *)bash_complete_username, emacs_meta_keymap);
264   rl_add_defun ("possible-username-completions",
265                 (Function *)bash_possible_username_completions, -1);
266   rl_bind_key_in_map ('~', (Function *)bash_possible_username_completions, emacs_ctlx_keymap);
267
268   rl_add_defun ("complete-hostname", (Function *)bash_complete_hostname, -1);
269   rl_bind_key_in_map ('@', (Function *)bash_complete_hostname, emacs_meta_keymap);
270   rl_add_defun ("possible-hostname-completions",
271                 (Function *)bash_possible_hostname_completions, -1);
272   rl_bind_key_in_map ('@', (Function *)bash_possible_hostname_completions, emacs_ctlx_keymap);
273
274   rl_add_defun ("complete-variable", (Function *)bash_complete_variable, -1);
275   rl_bind_key_in_map ('$', (Function *)bash_complete_variable, emacs_meta_keymap);
276   rl_add_defun ("possible-variable-completions",
277                 (Function *)bash_possible_variable_completions, -1);
278   rl_bind_key_in_map ('$', (Function *)bash_possible_variable_completions, emacs_ctlx_keymap);
279
280   rl_add_defun ("complete-command", (Function *)bash_complete_command, -1);
281   rl_bind_key_in_map ('!', (Function *)bash_complete_command, emacs_meta_keymap);
282   rl_add_defun ("possible-command-completions",
283                 (Function *)bash_possible_command_completions, -1);
284   rl_bind_key_in_map ('!', (Function *)bash_possible_command_completions, emacs_ctlx_keymap);
285
286   rl_add_defun ("glob-expand-word", (Function *)bash_glob_expand_word, -1);
287   rl_add_defun ("glob-list-expansions", (Function *)bash_glob_list_expansions, -1);
288   rl_bind_key_in_map ('*', (Function *)bash_glob_expand_word, emacs_ctlx_keymap);
289   rl_bind_key_in_map ('g', (Function *)bash_glob_list_expansions, emacs_ctlx_keymap);
290
291 #endif /* SPECIFIC_COMPLETION_FUNCTIONS */
292
293   rl_add_defun ("dynamic-complete-history", (Function *)dynamic_complete_history, -1);
294   rl_bind_key_in_map (TAB, (Function *)dynamic_complete_history, emacs_meta_keymap);
295
296   /* Tell the completer that we want a crack first. */
297   rl_attempted_completion_function = (CPPFunction *)attempt_shell_completion;
298
299   /* Tell the completer that we might want to follow symbolic links or
300      do other expansion on directory names. */
301   rl_directory_completion_hook = bash_directory_completion_hook;
302
303   /* Tell the filename completer we want a chance to ignore some names. */
304   rl_ignore_some_completions_function = (Function *)filename_completion_ignore;
305
306 #if defined (VI_MODE)
307   rl_bind_key_in_map ('v', (Function *)vi_edit_and_execute_command, vi_movement_keymap);
308 #  if defined (ALIAS)
309   rl_bind_key_in_map ('@', (Function *)posix_edit_macros, vi_movement_keymap);
310 #  endif
311 #endif
312
313   rl_completer_quote_characters = "'\"";
314
315   /* This sets rl_completer_word_break_characters and rl_special_prefixes
316      to the appropriate values, depending on whether or not hostname
317      completion is enabled. */
318   enable_hostname_completion (perform_hostname_completion);
319
320   /* characters that need to be quoted when appearing in filenames. */
321   rl_filename_quote_characters = " \t\n\\\"'@<>=;|&()#$`?*[!:";
322   rl_filename_quoting_function = bash_quote_filename;
323   rl_filename_dequoting_function = bash_dequote_filename;
324   rl_char_is_quoted_p = char_is_quoted;
325
326   if (posixly_correct)
327     posix_readline_initialize (1);
328
329   bash_readline_initialized = 1;
330 }
331
332 /* On Sun systems at least, rl_attempted_completion_function can end up
333    getting set to NULL, and rl_completion_entry_function set to do command
334    word completion if Bash is interrupted while trying to complete a command
335    word.  This just resets all the completion functions to the right thing.
336    It's called from throw_to_top_level(). */
337 void
338 bashline_reinitialize ()
339 {
340   tilde_initialize ();
341   rl_attempted_completion_function = attempt_shell_completion;
342   rl_completion_entry_function = (Function *)NULL;
343   rl_directory_completion_hook = bash_directory_completion_hook;
344   rl_ignore_some_completions_function = (Function *)filename_completion_ignore;
345 }
346
347 /* Contains the line to push into readline. */
348 static char *push_to_readline = (char *)NULL;
349
350 /* Push the contents of push_to_readline into the
351    readline buffer. */
352 static void
353 bash_push_line ()
354 {
355   if (push_to_readline)
356     {
357       rl_insert_text (push_to_readline);
358       free (push_to_readline);
359       push_to_readline = (char *)NULL;
360       rl_startup_hook = old_rl_startup_hook;
361     }
362 }
363
364 /* Call this to set the initial text for the next line to read
365    from readline. */
366 int
367 bash_re_edit (line)
368      char *line;
369 {
370   FREE (push_to_readline);
371
372   push_to_readline = savestring (line);
373   old_rl_startup_hook = rl_startup_hook;
374   rl_startup_hook = (Function *)bash_push_line;
375
376   return (0);
377 }
378
379 static void
380 display_shell_version (count, c)
381      int count, c;
382 {
383   crlf ();
384   show_shell_version (0);
385   putc ('\r', rl_outstream);
386   fflush (rl_outstream);
387   rl_on_new_line ();
388   rl_redisplay ();
389 }
390
391 /* **************************************************************** */
392 /*                                                                  */
393 /*                           Readline Stuff                         */
394 /*                                                                  */
395 /* **************************************************************** */
396
397 /* If the user requests hostname completion, then simply build a list
398    of hosts, and complete from that forever more, or at least until
399    HOSTFILE is unset. */
400
401 /* THIS SHOULD BE A STRINGLIST. */
402 /* The kept list of hostnames. */
403 static char **hostname_list = (char **)NULL;
404
405 /* The physical size of the above list. */
406 static int hostname_list_size;
407
408 /* The number of hostnames in the above list. */
409 static int hostname_list_length;
410
411 /* Whether or not HOSTNAME_LIST has been initialized. */
412 int hostname_list_initialized = 0;
413
414 /* Initialize the hostname completion table. */
415 static void
416 initialize_hostname_list ()
417 {
418   char *temp;
419
420   temp = get_string_value ("HOSTFILE");
421   if (temp == 0)
422     temp = get_string_value ("hostname_completion_file");
423   if (temp == 0)
424     temp = DEFAULT_HOSTS_FILE;
425
426   snarf_hosts_from_file (temp);
427
428   if (hostname_list)
429     hostname_list_initialized++;
430 }
431
432 /* Add NAME to the list of hosts. */
433 static void
434 add_host_name (name)
435      char *name;
436 {
437   long size;
438
439   if (hostname_list_length + 2 > hostname_list_size)
440     {
441       hostname_list_size = (hostname_list_size + 32) - (hostname_list_size % 32);
442       size = hostname_list_size * sizeof (char *);
443       hostname_list = (char **)xrealloc (hostname_list, size);
444     }
445
446   hostname_list[hostname_list_length++] = savestring (name);
447   hostname_list[hostname_list_length] = (char *)NULL;
448 }
449
450 #define cr_whitespace(c) ((c) == '\r' || (c) == '\n' || whitespace(c))
451
452 static void
453 snarf_hosts_from_file (filename)
454      char *filename;
455 {
456   FILE *file;
457   char *temp, buffer[256], name[256];
458   register int i, start;
459
460   file = fopen (filename, "r");
461   if (file == 0)
462     return;
463
464   while (temp = fgets (buffer, 255, file))
465     {
466       /* Skip to first character. */
467       for (i = 0; buffer[i] && cr_whitespace (buffer[i]); i++)
468         ;
469
470       /* If comment or blank line, ignore. */
471       if (buffer[i] == '\0' || buffer[i] == '#')
472         continue;
473
474       /* If `preprocessor' directive, do the include. */
475       if (strncmp (buffer + i, "$include ", 9) == 0)
476         {
477           char *incfile, *t;
478
479           /* Find start of filename. */
480           for (incfile = buffer + i + 9; *incfile && whitespace (*incfile); incfile++)
481             ;
482
483           /* Find end of filename. */
484           for (t = incfile; *t && cr_whitespace (*t) == 0; t++)
485             ;
486
487           *t = '\0';
488
489           snarf_hosts_from_file (incfile);
490           continue;
491         }
492
493       /* Skip internet address if present. */
494       if (digit (buffer[i]))
495         for (; buffer[i] && cr_whitespace (buffer[i]) == 0; i++);
496
497       /* Gobble up names.  Each name is separated with whitespace. */
498       while (buffer[i])
499         {
500           for (; cr_whitespace (buffer[i]); i++)
501             ;
502           if (buffer[i] == '\0' || buffer[i] ==  '#')
503             break;
504
505           /* Isolate the current word. */
506           for (start = i; buffer[i] && cr_whitespace (buffer[i]) == 0; i++)
507             ;
508           if (i == start)
509             continue;
510           strncpy (name, buffer + start, i - start);
511           name[i - start] = '\0';
512           add_host_name (name);
513         }
514     }
515   fclose (file);
516 }
517
518 /* Return the hostname list. */
519 char **
520 get_hostname_list ()
521 {
522   if (hostname_list_initialized == 0)
523     initialize_hostname_list ();
524   return (hostname_list);
525 }
526
527 void
528 clear_hostname_list ()
529 {
530   register int i;
531
532   if (hostname_list_initialized == 0)
533     return;
534   for (i = 0; i < hostname_list_length; i++)
535     free (hostname_list[i]);
536   hostname_list_length = 0;
537 }
538
539 /* Return a NULL terminated list of hostnames which begin with TEXT.
540    Initialize the hostname list the first time if neccessary.
541    The array is malloc ()'ed, but not the individual strings. */
542 static char **
543 hostnames_matching (text)
544      char *text;
545 {
546   register int i, len, nmatch, rsize;
547   char **result;
548
549   if (hostname_list_initialized == 0)
550     initialize_hostname_list ();
551
552   if (hostname_list_initialized == 0)
553     return ((char **)NULL);
554
555   /* Special case.  If TEXT consists of nothing, then the whole list is
556      what is desired. */
557   if (*text == '\0')
558     {
559       result = alloc_array (1 + hostname_list_length);
560       for (i = 0; i < hostname_list_length; i++)
561         result[i] = hostname_list[i];
562       result[i] = (char *)NULL;
563       return (result);
564     }
565
566   /* Scan until found, or failure. */
567   len = strlen (text);
568   result = (char **)NULL;
569   for (i = nmatch = rsize = 0; i < hostname_list_length; i++)
570     {
571       if (STREQN (text, hostname_list[i], len) == 0)
572         continue;
573
574       /* OK, it matches.  Add it to the list. */
575       if (nmatch >= (rsize - 1))
576         {
577           rsize = (rsize + 16) - (rsize % 16);
578           result = (char **)xrealloc (result, rsize * sizeof (char *));
579         }
580
581       result[nmatch++] = hostname_list[i];
582     }
583   if (nmatch)
584     result[nmatch] = (char *)NULL;
585   return (result);
586 }
587
588 /* The equivalent of the Korn shell C-o operate-and-get-next-history-line
589    editing command. */
590 static int saved_history_line_to_use = -1;
591
592 static void
593 set_saved_history ()
594 {
595   if (saved_history_line_to_use >= 0)
596     rl_get_previous_history (history_length - saved_history_line_to_use, 0);
597   saved_history_line_to_use = -1;
598   rl_startup_hook = old_rl_startup_hook;
599 }
600
601 static void
602 operate_and_get_next (count, c)
603      int count, c;
604 {
605   int where;
606
607   /* Accept the current line. */
608   rl_newline (1, c);
609
610   /* Find the current line, and find the next line to use. */
611   where = where_history ();
612
613   if ((history_is_stifled () && (history_length >= max_input_history)) ||
614       (where >= history_length - 1))
615     saved_history_line_to_use = where;
616   else
617     saved_history_line_to_use = where + 1;
618
619   old_rl_startup_hook = rl_startup_hook;
620   rl_startup_hook = (Function *)set_saved_history;
621 }
622
623 #if defined (VI_MODE)
624 /* This vi mode command causes VI_EDIT_COMMAND to be run on the current
625    command being entered (if no explicit argument is given), otherwise on
626    a command from the history file. */
627
628 #define VI_EDIT_COMMAND "fc -e ${VISUAL:-${EDITOR:-vi}}"
629
630 static void
631 vi_edit_and_execute_command (count, c)
632      int count, c;
633 {
634   char *command;
635
636   /* Accept the current line. */
637   rl_newline (1, c);
638
639   if (rl_explicit_arg)
640     {
641       command = xmalloc (strlen (VI_EDIT_COMMAND) + 8);
642       sprintf (command, "%s %d", VI_EDIT_COMMAND, count);
643     }
644   else
645     {
646       /* Take the command we were just editing, add it to the history file,
647          then call fc to operate on it.  We have to add a dummy command to
648          the end of the history because fc ignores the last command (assumes
649          it's supposed to deal with the command before the `fc'). */
650       using_history ();
651       bash_add_history (rl_line_buffer);
652       bash_add_history ("");
653       history_lines_this_session++;
654       using_history ();
655       command = savestring (VI_EDIT_COMMAND);
656     }
657   parse_and_execute (command, "v", SEVAL_NOHIST);
658   rl_line_buffer[0] = '\0';     /* XXX */
659 }
660 #endif /* VI_MODE */
661
662 #if defined (ALIAS)
663 static int
664 posix_edit_macros (count, key)
665      int count, key;
666 {
667   int c;
668   char alias_name[3], *alias_value, *macro;
669
670   c = rl_read_key ();
671   alias_name[0] = '_';
672   alias_name[1] = c;
673   alias_name[2] = '\0';
674
675   alias_value = get_alias_value (alias_name);
676   if (alias_value && *alias_value)
677     {
678       macro = savestring (alias_value);
679       rl_push_macro_input (macro);
680     }
681   return 0;
682 }
683 #endif
684
685 /* **************************************************************** */
686 /*                                                                  */
687 /*                      How To Do Shell Completion                  */
688 /*                                                                  */
689 /* **************************************************************** */
690
691 #define COMMAND_SEPARATORS ";|&{(`"
692
693 static int
694 check_redir (ti)
695      int ti;
696 {
697   register int this_char, prev_char;
698
699   /* Handle the two character tokens `>&', `<&', and `>|'.
700      We are not in a command position after one of these. */
701   this_char = rl_line_buffer[ti];
702   prev_char = rl_line_buffer[ti - 1];
703
704   if ((this_char == '&' && (prev_char == '<' || prev_char == '>')) ||
705       (this_char == '|' && prev_char == '>'))
706     return (1);
707   else if ((this_char == '{' && prev_char == '$') || /* } */
708            (char_is_quoted (rl_line_buffer, ti)))
709     return (1);
710   return (0);
711 }
712
713 #if defined (PROGRAMMABLE_COMPLETION)
714 static int
715 find_cmd_start (start)
716      int start;
717 {
718   register int s, os;
719
720   os = 0;
721   while (((s = skip_to_delim (rl_line_buffer, os, COMMAND_SEPARATORS)) <= start) &&
722          rl_line_buffer[s])
723     os = s+1;
724   return os;
725 }
726
727 static int
728 find_cmd_end (end)
729      int end;
730 {
731   register int e;
732
733   e = skip_to_delim (rl_line_buffer, end, COMMAND_SEPARATORS);
734   return e;
735 }
736
737 static char *
738 find_cmd_name (start)
739      int start;
740 {
741   char *name;
742   register int s, e;
743
744   for (s = start; whitespace (rl_line_buffer[s]); s++)
745     ;
746
747   /* skip until a shell break character */
748   e = skip_to_delim (rl_line_buffer, s, "()<>;&| \t\n");
749
750   name = substring (rl_line_buffer, s, e);
751
752   return (name);
753 }
754
755 static char *
756 prog_complete_return (text, matchnum)
757      char *text;
758      int matchnum;
759 {
760   static int ind;
761
762   if (matchnum == 0)
763     ind = 0;
764
765   if (prog_complete_matches == 0 || prog_complete_matches[ind] == 0)
766     return (char *)NULL;
767   return (prog_complete_matches[ind++]);
768 }
769
770 #endif /* PROGRAMMABLE_COMPLETION */
771
772 /* Do some completion on TEXT.  The indices of TEXT in RL_LINE_BUFFER are
773    at START and END.  Return an array of matches, or NULL if none. */
774 static char **
775 attempt_shell_completion (text, start, end)
776      char *text;
777      int start, end;
778 {
779   int in_command_position, ti, saveti, qc;
780   char **matches, *command_separator_chars;
781
782   command_separator_chars = COMMAND_SEPARATORS;
783   matches = (char **)NULL;
784   rl_ignore_some_completions_function = (Function *)filename_completion_ignore;
785
786   /* Determine if this could be a command word.  It is if it appears at
787      the start of the line (ignoring preceding whitespace), or if it
788      appears after a character that separates commands.  It cannot be a
789      command word if we aren't at the top-level prompt. */
790   ti = start - 1;
791   saveti = qc = -1;
792
793   while ((ti > -1) && (whitespace (rl_line_buffer[ti])))
794     ti--;
795
796 #if 1
797   /* If this is an open quote, maybe we're trying to complete a quoted
798      command name. */
799   if (rl_line_buffer[ti] == '"' || rl_line_buffer[ti] == '\'')
800     {
801       qc = rl_line_buffer[ti];
802       saveti = ti--;
803       while (ti > -1 && (whitespace (rl_line_buffer[ti])))
804         ti--;
805     }
806 #endif
807       
808   in_command_position = 0;
809   if (ti < 0)
810     {
811       /* Only do command completion at the start of a line when we
812          are prompting at the top level. */
813       if (current_prompt_string == ps1_prompt)
814         in_command_position++;
815     }
816   else if (member (rl_line_buffer[ti], command_separator_chars))
817     {
818       in_command_position++;
819
820       if (check_redir (ti) == 1)
821         in_command_position = 0;
822     }
823   else
824     {
825       /* This still could be in command position.  It is possible
826          that all of the previous words on the line are variable
827          assignments. */
828     }
829
830   /* Check that we haven't incorrectly flagged a closed command substitution
831      as indicating we're in a command position. */
832   if (in_command_position && ti >= 0 && rl_line_buffer[ti] == '`' &&
833         *text != '`' && unclosed_pair (rl_line_buffer, end, "`") == 0)
834     in_command_position = 0;
835
836   /* Special handling for command substitution.  If *TEXT is a backquote,
837      it can be the start or end of an old-style command substitution, or
838      unmatched.  If it's unmatched, both calls to unclosed_pair will
839      succeed.  */
840   if (*text == '`' && 
841         (in_command_position || (unclosed_pair (rl_line_buffer, start, "`") &&
842                                  unclosed_pair (rl_line_buffer, end, "`"))))
843     matches = completion_matches (text, command_subst_completion_function);
844
845 #if defined (PROGRAMMABLE_COMPLETION)
846   /* Attempt programmable completion. */
847   if (!matches && in_command_position == 0 && prog_completion_enabled &&
848       (num_progcomps () > 0) && current_prompt_string == ps1_prompt)
849     {
850       int s, e, foundcs;
851       char *n;
852
853       /* XXX - don't free the members */
854       if (prog_complete_matches)
855         free (prog_complete_matches);
856       prog_complete_matches = (char **)NULL;
857
858       s = find_cmd_start (start);
859       e = find_cmd_end (end);
860       n = find_cmd_name (s);
861       prog_complete_matches = programmable_completions (n, text, s, e, &foundcs);
862       FREE (n);
863       /* XXX - if we found a COMPSPEC for the command, just return whatever
864          the programmable completion code returns, and disable the default
865          filename completion that readline will do. */
866       if (foundcs)
867         {
868           /* Turn what the programmable completion code returns into what
869              readline wants.  I should have made compute_lcd_of_matches
870              external... */
871           matches = completion_matches (text, prog_complete_return);
872           rl_attempted_completion_over = 1;     /* no default */
873           return (matches);
874         }
875     }
876 #endif
877
878   /* New posix-style command substitution or variable name? */
879   if (!matches && *text == '$')
880     {
881       if (qc != '\'' && text[1] == '(') /* ) */
882         matches = completion_matches (text, command_subst_completion_function);
883       else
884         matches = completion_matches (text, variable_completion_function);
885     }
886
887   /* If the word starts in `~', and there is no slash in the word, then
888      try completing this word as a username. */
889   if (!matches && *text == '~' && !strchr (text, '/'))
890     matches = completion_matches (text, username_completion_function);
891
892   /* Another one.  Why not?  If the word starts in '@', then look through
893      the world of known hostnames for completion first. */
894   if (!matches && perform_hostname_completion && *text == '@')
895     matches = completion_matches (text, hostname_completion_function);
896
897   /* And last, (but not least) if this word is in a command position, then
898      complete over possible command names, including aliases, functions,
899      and command names. */
900   if (!matches && in_command_position)
901     {
902       if (start == 0 && end == 0 && text[0] == '\0' && no_empty_command_completion)
903         {
904           matches = (char **)NULL;
905           rl_ignore_some_completions_function = (Function *)bash_ignore_everything;
906         }
907       else
908         {
909           matches = completion_matches (text, command_word_completion_function);
910           /* If we are attempting command completion and nothing matches, we
911              do not want readline to perform filename completion for us.  We
912              still want to be able to complete partial pathnames, so set the
913              completion ignore function to something which will remove
914              filenames and leave directories in the match list. */
915           if (matches == (char **)NULL)
916             rl_ignore_some_completions_function = (Function *)bash_ignore_filenames;
917         }
918     }
919
920   /* This could be a globbing pattern, so try to expand it using pathname
921      expansion. */
922   if (!matches && glob_pattern_p (text))
923     {
924       matches = completion_matches (text, glob_complete_word);
925       /* A glob expression that matches more than one filename is problematic.
926          If we match more than one filename, punt. */
927       if (matches && matches[1])
928         {
929           free_array (matches);
930           matches = (char **)0;
931         }
932     }
933
934   return (matches);
935 }
936
937 /* This is the function to call when the word to complete is in a position
938    where a command word can be found.  It grovels $PATH, looking for commands
939    that match.  It also scans aliases, function names, and the shell_builtin
940    table. */
941 char *
942 command_word_completion_function (hint_text, state)
943      char *hint_text;
944      int state;
945 {
946   static char *hint = (char *)NULL;
947   static char *path = (char *)NULL;
948   static char *val = (char *)NULL;
949   static char *filename_hint = (char *)NULL;
950   static int path_index, hint_len, istate;
951   static int mapping_over, local_index;
952   static SHELL_VAR **varlist = (SHELL_VAR **)NULL;
953 #if defined (ALIAS)
954   static alias_t **alias_list = (alias_t **)NULL;
955 #endif /* ALIAS */
956
957   /* We have to map over the possibilities for command words.  If we have
958      no state, then make one just for that purpose. */
959   if (!state)
960     {
961       if (hint)
962         free (hint);
963
964       mapping_over = 0;
965       val = (char *)NULL;
966
967       /* If this is an absolute program name, do not check it against
968          aliases, reserved words, functions or builtins.  We must check
969          whether or not it is unique, and, if so, whether that filename
970          is executable. */
971       if (absolute_program (hint_text))
972         {
973           /* Perform tilde expansion on what's passed, so we don't end up
974              passing filenames with tildes directly to stat(). */
975           if (*hint_text == '~')
976             hint = bash_tilde_expand (hint_text);
977           else
978             hint = savestring (hint_text);
979           hint_len = strlen (hint);
980
981           if (filename_hint)
982             free (filename_hint);
983           filename_hint = savestring (hint);
984
985           mapping_over = 4;
986           istate = 0;
987           goto inner;
988         }
989
990       hint = savestring (hint_text);
991       hint_len = strlen (hint);
992
993       path = get_string_value ("PATH");
994       path_index = 0;
995
996       /* Initialize the variables for each type of command word. */
997       local_index = 0;
998
999       if (varlist)
1000         free (varlist);
1001
1002       varlist = all_visible_functions ();
1003
1004 #if defined (ALIAS)
1005       if (alias_list)
1006         free (alias_list);
1007
1008       alias_list = all_aliases ();
1009 #endif /* ALIAS */
1010     }
1011
1012   /* mapping_over says what we are currently hacking.  Note that every case
1013      in this list must fall through when there are no more possibilities. */
1014
1015   switch (mapping_over)
1016     {
1017     case 0:                     /* Aliases come first. */
1018 #if defined (ALIAS)
1019       while (alias_list && alias_list[local_index])
1020         {
1021           register char *alias;
1022
1023           alias = alias_list[local_index++]->name;
1024
1025           if (STREQN (alias, hint, hint_len))
1026             return (savestring (alias));
1027         }
1028 #endif /* ALIAS */
1029       local_index = 0;
1030       mapping_over++;
1031
1032     case 1:                     /* Then shell reserved words. */
1033       {
1034         while (word_token_alist[local_index].word)
1035           {
1036             register char *reserved_word;
1037
1038             reserved_word = word_token_alist[local_index++].word;
1039
1040             if (STREQN (reserved_word, hint, hint_len))
1041               return (savestring (reserved_word));
1042           }
1043         local_index = 0;
1044         mapping_over++;
1045       }
1046
1047     case 2:                     /* Then function names. */
1048       while (varlist && varlist[local_index])
1049         {
1050           register char *varname;
1051
1052           varname = varlist[local_index++]->name;
1053
1054           if (STREQN (varname, hint, hint_len))
1055             return (savestring (varname));
1056         }
1057       local_index = 0;
1058       mapping_over++;
1059
1060     case 3:                     /* Then shell builtins. */
1061       for (; local_index < num_shell_builtins; local_index++)
1062         {
1063           /* Ignore it if it doesn't have a function pointer or if it
1064              is not currently enabled. */
1065           if (!shell_builtins[local_index].function ||
1066               (shell_builtins[local_index].flags & BUILTIN_ENABLED) == 0)
1067             continue;
1068
1069           if (STREQN (shell_builtins[local_index].name, hint, hint_len))
1070             {
1071               int i = local_index++;
1072
1073               return (savestring (shell_builtins[i].name));
1074             }
1075         }
1076       local_index = 0;
1077       mapping_over++;
1078     }
1079
1080   /* Repeatedly call filename_completion_function while we have
1081      members of PATH left.  Question:  should we stat each file?
1082      Answer: we call executable_file () on each file. */
1083  outer:
1084
1085   istate = (val != (char *)NULL);
1086
1087   if (!istate)
1088     {
1089       char *current_path;
1090
1091       /* Get the next directory from the path.  If there is none, then we
1092          are all done. */
1093       if (!path || !path[path_index] ||
1094           (current_path = extract_colon_unit (path, &path_index)) == 0)
1095         return ((char *)NULL);
1096
1097       if (*current_path == 0)
1098         {
1099           free (current_path);
1100           current_path = savestring (".");
1101         }
1102
1103       if (*current_path == '~')
1104         {
1105           char *t;
1106
1107           t = bash_tilde_expand (current_path);
1108           free (current_path);
1109           current_path = t;
1110         }
1111
1112       if (filename_hint)
1113         free (filename_hint);
1114
1115       filename_hint = xmalloc (2 + strlen (current_path) + hint_len);
1116       sprintf (filename_hint, "%s/%s", current_path, hint);
1117
1118       free (current_path);
1119     }
1120
1121  inner:
1122   val = filename_completion_function (filename_hint, istate);
1123   istate = 1;
1124
1125   if (val == 0)
1126     {
1127       /* If the hint text is an absolute program, then don't bother
1128          searching through PATH. */
1129       if (absolute_program (hint))
1130         return ((char *)NULL);
1131
1132       goto outer;
1133     }
1134   else
1135     {
1136       int match, freetemp;
1137       char *temp;
1138
1139       if (absolute_program (hint))
1140         {
1141           match = strncmp (val, hint, hint_len) == 0;
1142           /* If we performed tilde expansion, restore the original
1143              filename. */
1144           if (*hint_text == '~')
1145             {
1146               int l, tl, vl;
1147               vl = strlen (val);
1148               tl = strlen (hint_text);
1149               l = vl - hint_len;        /* # of chars added */
1150               temp = xmalloc (l + 2 + tl);
1151               strcpy (temp, hint_text);
1152               strcpy (temp + tl, val + vl - l);
1153             }
1154           else
1155             temp = savestring (val);
1156           freetemp = 1;
1157         }
1158       else
1159         {
1160           temp = strrchr (val, '/');
1161
1162           if (temp)
1163             {
1164               temp++;
1165               freetemp = match = strncmp (temp, hint, hint_len) == 0;
1166               if (match)
1167                 temp = savestring (temp);
1168             }
1169           else
1170             freetemp = match = 0;
1171         }
1172
1173       /* If we have found a match, and it is an executable file or a
1174          directory name, return it. */
1175       if (match && (executable_file (val) || is_directory (val)))
1176         {
1177           free (val);
1178           val = "";             /* So it won't be NULL. */
1179           return (temp);
1180         }
1181       else
1182         {
1183           if (freetemp)
1184             free (temp);
1185           free (val);
1186           goto inner;
1187         }
1188     }
1189 }
1190
1191 /* Completion inside an unterminated command substitution. */
1192 static char *
1193 command_subst_completion_function (text, state)
1194      char *text;
1195      int state;
1196 {
1197   static char **matches = (char **)NULL;
1198   static char *orig_start, *filename_text = (char *)NULL;
1199   static int cmd_index, start_len;
1200   char *value;
1201
1202   if (state == 0)
1203     {
1204       if (filename_text)
1205         free (filename_text);
1206       orig_start = text;
1207       if (*text == '`')
1208         text++;
1209       else if (*text == '$' && text[1] == '(')  /* ) */
1210         text += 2;
1211       start_len = text - orig_start;
1212       filename_text = savestring (text);
1213       if (matches)
1214         free (matches);
1215       matches = completion_matches (filename_text, command_word_completion_function);
1216       cmd_index = 0;
1217     }
1218
1219   if (!matches || !matches[cmd_index])
1220     {
1221       rl_filename_quoting_desired = 0;  /* disable quoting */
1222       return ((char *)NULL);
1223     }
1224   else
1225     {
1226       value = xmalloc (1 + start_len + strlen (matches[cmd_index]));
1227
1228       if (start_len == 1)
1229         value[0] = *orig_start;
1230       else
1231         strncpy (value, orig_start, start_len);
1232
1233       strcpy (value + start_len, matches[cmd_index]);
1234
1235       cmd_index++;
1236       return (value);
1237     }
1238 }
1239
1240 /* Okay, now we write the entry_function for variable completion. */
1241 static char *
1242 variable_completion_function (text, state)
1243      int state;
1244      char *text;
1245 {
1246   static char **varlist = (char **)NULL;
1247   static int varlist_index;
1248   static char *varname = (char *)NULL;
1249   static int namelen;
1250   static int first_char, first_char_loc;
1251
1252   if (!state)
1253     {
1254       if (varname)
1255         free (varname);
1256
1257       first_char_loc = 0;
1258       first_char = text[0];
1259
1260       if (first_char == '$')
1261         first_char_loc++;
1262
1263       if (text[first_char_loc] == '{')
1264         first_char_loc++;
1265
1266       varname = savestring (text + first_char_loc);
1267
1268       namelen = strlen (varname);
1269       if (varlist)
1270         free_array (varlist);
1271
1272       varlist = all_variables_matching_prefix (varname);
1273       varlist_index = 0;
1274     }
1275
1276   if (!varlist || !varlist[varlist_index])
1277     {
1278       return ((char *)NULL);
1279     }
1280   else
1281     {
1282       char *value = xmalloc (4 + strlen (varlist[varlist_index]));
1283
1284       if (first_char_loc)
1285         {
1286           value[0] = first_char;
1287           if (first_char_loc == 2)
1288             value[1] = '{';
1289         }
1290
1291       strcpy (value + first_char_loc, varlist[varlist_index]);
1292       if (first_char_loc == 2)
1293         strcat (value, "}");
1294
1295       varlist_index++;
1296       return (value);
1297     }
1298 }
1299
1300 /* How about a completion function for hostnames? */
1301 static char *
1302 hostname_completion_function (text, state)
1303      int state;
1304      char *text;
1305 {
1306   static char **list = (char **)NULL;
1307   static int list_index = 0;
1308   static int first_char, first_char_loc;
1309
1310   /* If we don't have any state, make some. */
1311   if (state == 0)
1312     {
1313       FREE (list);
1314
1315       list = (char **)NULL;
1316
1317       first_char_loc = 0;
1318       first_char = *text;
1319
1320       if (first_char == '@')
1321         first_char_loc++;
1322
1323       list = hostnames_matching (&text[first_char_loc]);
1324       list_index = 0;
1325     }
1326
1327   if (list && list[list_index])
1328     {
1329       char *t;
1330
1331       t = xmalloc (2 + strlen (list[list_index]));
1332       *t = first_char;
1333       strcpy (t + first_char_loc, list[list_index]);
1334       list_index++;
1335       return (t);
1336     }
1337
1338   return ((char *)NULL);
1339 }
1340
1341 /* Functions to perform history and alias expansions on the current line. */
1342
1343 #if defined (BANG_HISTORY)
1344 /* Perform history expansion on the current line.  If no history expansion
1345    is done, pre_process_line() returns what it was passed, so we need to
1346    allocate a new line here. */
1347 static char *
1348 history_expand_line_internal (line)
1349      char *line;
1350 {
1351   char *new_line;
1352
1353   new_line = pre_process_line (line, 0, 0);
1354   return (new_line == line) ? savestring (line) : new_line;
1355 }
1356 #endif
1357
1358 /* There was an error in expansion.  Let the preprocessor print
1359    the error here. */
1360 static void
1361 cleanup_expansion_error ()
1362 {
1363   char *to_free;
1364
1365   fprintf (rl_outstream, "\r\n");
1366   to_free = pre_process_line (rl_line_buffer, 1, 0);
1367   if (to_free != rl_line_buffer)
1368     free (to_free);
1369   putc ('\r', rl_outstream);
1370   rl_forced_update_display ();
1371 }
1372
1373 /* If NEW_LINE differs from what is in the readline line buffer, add an
1374    undo record to get from the readline line buffer contents to the new
1375    line and make NEW_LINE the current readline line. */
1376 static void
1377 maybe_make_readline_line (new_line)
1378      char *new_line;
1379 {
1380   if (strcmp (new_line, rl_line_buffer) != 0)
1381     {
1382       rl_point = rl_end;
1383
1384       rl_add_undo (UNDO_BEGIN, 0, 0, 0);
1385       rl_delete_text (0, rl_point);
1386       rl_point = rl_end = 0;
1387       rl_insert_text (new_line);
1388       rl_add_undo (UNDO_END, 0, 0, 0);
1389     }
1390 }
1391
1392 /* Make NEW_LINE be the current readline line.  This frees NEW_LINE. */
1393 static void
1394 set_up_new_line (new_line)
1395      char *new_line;
1396 {
1397   int old_point = rl_point;
1398   int at_end = rl_point == rl_end;
1399
1400   /* If the line was history and alias expanded, then make that
1401      be one thing to undo. */
1402   maybe_make_readline_line (new_line);
1403   free (new_line);
1404
1405   /* Place rl_point where we think it should go. */
1406   if (at_end)
1407     rl_point = rl_end;
1408   else if (old_point < rl_end)
1409     {
1410       rl_point = old_point;
1411       if (!whitespace (rl_line_buffer[rl_point]))
1412         rl_forward_word (1, 0);
1413     }
1414 }
1415
1416 #if defined (ALIAS)
1417 /* Expand aliases in the current readline line. */
1418 static int
1419 alias_expand_line (ignore)
1420      int ignore;
1421 {
1422   char *new_line;
1423
1424   new_line = alias_expand (rl_line_buffer);
1425
1426   if (new_line)
1427     {
1428       set_up_new_line (new_line);
1429       return (0);
1430     }
1431   else
1432     {
1433       cleanup_expansion_error ();
1434       return (1);
1435     }
1436 }
1437 #endif
1438
1439 #if defined (BANG_HISTORY)
1440 /* History expand the line. */
1441 static int
1442 history_expand_line (ignore)
1443      int ignore;
1444 {
1445   char *new_line;
1446
1447   new_line = history_expand_line_internal (rl_line_buffer);
1448
1449   if (new_line)
1450     {
1451       set_up_new_line (new_line);
1452       return (0);
1453     }
1454   else
1455     {
1456       cleanup_expansion_error ();
1457       return (1);
1458     }
1459 }
1460
1461 /* Expand history substitutions in the current line and then insert a
1462    space wherever set_up_new_line decided to put rl_point. */
1463 static int
1464 tcsh_magic_space (ignore)
1465      int ignore;
1466 {
1467   if (history_expand_line (ignore) == 0)
1468     {
1469       rl_insert (1, ' ');
1470       return (0);
1471     }
1472   else
1473     return (1);
1474 }
1475 #endif
1476
1477 /* History and alias expand the line. */
1478 static int
1479 history_and_alias_expand_line (ignore)
1480      int ignore;
1481 {
1482   char *new_line;
1483
1484   new_line = pre_process_line (rl_line_buffer, 0, 0);
1485   if (new_line == rl_line_buffer)
1486     new_line = savestring (new_line);
1487
1488 #if defined (ALIAS)
1489   if (new_line)
1490     {
1491       char *alias_line;
1492
1493       alias_line = alias_expand (new_line);
1494       free (new_line);
1495       new_line = alias_line;
1496     }
1497 #endif /* ALIAS */
1498
1499   if (new_line)
1500     {
1501       set_up_new_line (new_line);
1502       return (0);
1503     }
1504   else
1505     {
1506       cleanup_expansion_error ();
1507       return (1);
1508     }
1509 }
1510
1511 /* History and alias expand the line, then perform the shell word
1512    expansions by calling expand_string.  This can't use set_up_new_line()
1513    because we want the variable expansions as a separate undo'able
1514    set of operations. */
1515 static void
1516 shell_expand_line (ignore)
1517      int ignore;
1518 {
1519   char *new_line;
1520   WORD_LIST *expanded_string;
1521
1522   new_line = pre_process_line (rl_line_buffer, 0, 0);
1523   if (new_line == rl_line_buffer)
1524     new_line = savestring (new_line);
1525
1526 #if defined (ALIAS)
1527   if (new_line)
1528     {
1529       char *alias_line;
1530
1531       alias_line = alias_expand (new_line);
1532       free (new_line);
1533       new_line = alias_line;
1534     }
1535 #endif /* ALIAS */
1536
1537   if (new_line)
1538     {
1539       int old_point = rl_point;
1540       int at_end = rl_point == rl_end;
1541
1542       /* If the line was history and alias expanded, then make that
1543          be one thing to undo. */
1544       maybe_make_readline_line (new_line);
1545       free (new_line);
1546
1547       /* If there is variable expansion to perform, do that as a separate
1548          operation to be undone. */
1549       new_line = savestring (rl_line_buffer);
1550       expanded_string = expand_string (new_line, 0);
1551       FREE (new_line);
1552       if (expanded_string == 0)
1553         {
1554           new_line = xmalloc (1);
1555           new_line[0] = '\0';
1556         }
1557       else
1558         {
1559           new_line = string_list (expanded_string);
1560           dispose_words (expanded_string);
1561         }
1562
1563       maybe_make_readline_line (new_line);
1564       free (new_line);
1565
1566       /* Place rl_point where we think it should go. */
1567       if (at_end)
1568         rl_point = rl_end;
1569       else if (old_point < rl_end)
1570         {
1571           rl_point = old_point;
1572           if (!whitespace (rl_line_buffer[rl_point]))
1573             rl_forward_word (1, 0);
1574         }
1575     }
1576   else
1577     cleanup_expansion_error ();
1578 }
1579
1580 /* Define NO_FORCE_FIGNORE if you want to match filenames that would
1581    otherwise be ignored if they are the only possible matches. */
1582 /* #define NO_FORCE_FIGNORE */
1583
1584 /* If FIGNORE is set, then don't match files with the given suffixes when
1585    completing filenames.  If only one of the possibilities has an acceptable
1586    suffix, delete the others, else just return and let the completer
1587    signal an error.  It is called by the completer when real
1588    completions are done on filenames by the completer's internal
1589    function, not for completion lists (M-?) and not on "other"
1590    completion types, such as hostnames or commands. */
1591
1592 static struct ignorevar fignore =
1593 {
1594   "FIGNORE",
1595   (struct ign *)0,
1596   0,
1597   (char *)0,
1598   (Function *) 0,
1599 };
1600
1601 static void
1602 _ignore_completion_names (names, name_func)
1603      char **names;
1604      Function *name_func;
1605 {
1606   char **newnames;
1607   int idx, nidx;
1608 #ifdef NO_FORCE_FIGNORE
1609   char **oldnames;
1610   int oidx;
1611 #endif
1612
1613   /* If there is only one completion, see if it is acceptable.  If it is
1614      not, free it up.  In any case, short-circuit and return.  This is a
1615      special case because names[0] is not the prefix of the list of names
1616      if there is only one completion; it is the completion itself. */
1617   if (names[1] == (char *)0)
1618     {
1619 #ifndef NO_FORCE_FIGNORE
1620       if ((*name_func) (names[0]) == 0)
1621         {
1622           free (names[0]);
1623           names[0] = (char *)NULL;
1624         }
1625 #endif
1626       return;
1627     }
1628
1629   /* Allocate space for array to hold list of pointers to matching
1630      filenames.  The pointers are copied back to NAMES when done. */
1631   for (nidx = 1; names[nidx]; nidx++)
1632     ;
1633   newnames = alloc_array (nidx + 1);
1634 #ifdef NO_FORCE_FIGNORE
1635   oldnames = alloc_array (nidx - 1);
1636   oidx = 0;
1637 #endif
1638
1639   newnames[0] = names[0];
1640   for (idx = nidx = 1; names[idx]; idx++)
1641     {
1642       if ((*name_func) (names[idx]))
1643         newnames[nidx++] = names[idx];
1644       else
1645 #ifndef NO_FORCE_FIGNORE
1646         free (names[idx]);
1647 #else
1648         oldnames[oidx++] = names[idx];
1649 #endif
1650     }
1651
1652   newnames[nidx] = (char *)NULL;
1653
1654   /* If none are acceptable then let the completer handle it. */
1655   if (nidx == 1)
1656     {
1657 #ifndef NO_FORCE_FIGNORE
1658       free (names[0]);
1659       names[0] = (char *)NULL;
1660 #else
1661       free (oldnames);
1662 #endif
1663       free (newnames);
1664       return;
1665     }
1666
1667 #ifdef NO_FORCE_FIGNORE
1668   while (oidx)
1669     free (oldnames[--oidx]);
1670   free (oldnames);
1671 #endif
1672
1673   /* If only one is acceptable, copy it to names[0] and return. */
1674   if (nidx == 2)
1675     {
1676       free (names[0]);
1677       names[0] = newnames[1];
1678       names[1] = (char *)NULL;
1679       free (newnames);
1680       return;
1681     }
1682
1683   /* Copy the acceptable names back to NAMES, set the new array end,
1684      and return. */
1685   for (nidx = 1; newnames[nidx]; nidx++)
1686     names[nidx] = newnames[nidx];
1687   names[nidx] = (char *)NULL;
1688   free (newnames);
1689 }
1690
1691 static int
1692 name_is_acceptable (name)
1693      char *name;
1694 {
1695   struct ign *p;
1696   int nlen;
1697
1698   for (nlen = strlen (name), p = fignore.ignores; p->val; p++)
1699     {
1700       if (nlen > p->len && p->len > 0 && STREQ (p->val, &name[nlen - p->len]))
1701         return (0);
1702     }
1703
1704   return (1);
1705 }
1706
1707 #if 0
1708 static int
1709 ignore_dot_names (name)
1710      char *name;
1711 {
1712   return (name[0] != '.');
1713 }
1714 #endif
1715
1716 static void
1717 filename_completion_ignore (names)
1718      char **names;
1719 {
1720 #if 0
1721   if (glob_dot_filenames == 0)
1722     _ignore_completion_names (names, ignore_dot_names);
1723 #endif
1724
1725   setup_ignore_patterns (&fignore);
1726
1727   if (fignore.num_ignores == 0)
1728     return;
1729
1730   _ignore_completion_names (names, name_is_acceptable);
1731 }
1732
1733 /* Return 1 if NAME is a directory. */
1734 static int
1735 test_for_directory (name)
1736      char *name;
1737 {
1738   struct stat finfo;
1739   char *fn;
1740
1741   fn = bash_tilde_expand (name);
1742   if (stat (fn, &finfo) != 0)
1743     {
1744       free (fn);
1745       return 0;
1746     }
1747   free (fn);
1748   return (S_ISDIR (finfo.st_mode));
1749 }
1750
1751 /* Remove files from NAMES, leaving directories. */
1752 static void
1753 bash_ignore_filenames (names)
1754      char **names;
1755 {
1756   _ignore_completion_names (names, test_for_directory);
1757 }
1758
1759 static int
1760 return_zero (name)
1761      char *name;
1762 {
1763   return 0;
1764 }
1765
1766 static void
1767 bash_ignore_everything (names)
1768      char **names;
1769 {
1770   _ignore_completion_names (names, return_zero);
1771 }
1772
1773 /* Handle symbolic link references and other directory name
1774    expansions while hacking completion. */
1775 static int
1776 bash_directory_completion_hook (dirname)
1777      char **dirname;
1778 {
1779   char *local_dirname, *new_dirname, *t;
1780   int return_value, should_expand_dirname;
1781   WORD_LIST *wl;
1782
1783   return_value = should_expand_dirname = 0;
1784   local_dirname = *dirname;
1785
1786 #if 0
1787   should_expand_dirname = strchr (local_dirname, '$') || strchr (local_dirname, '`');
1788 #else
1789   if (strchr (local_dirname, '$'))
1790     should_expand_dirname = 1;
1791   else
1792     {
1793       t = strchr (local_dirname, '`');
1794       if (t && unclosed_pair (local_dirname, strlen (local_dirname), "`") == 0)
1795         should_expand_dirname = 1;
1796     }
1797 #endif
1798
1799   if (should_expand_dirname)  
1800     {
1801       new_dirname = savestring (local_dirname);
1802       wl = expand_string (new_dirname, 0);
1803       if (wl)
1804         {
1805           *dirname = string_list (wl);
1806           /* Tell the completer to replace the directory name only if we
1807              actually expanded something. */
1808           return_value = STREQ (local_dirname, *dirname) == 0;
1809           free (local_dirname);
1810           free (new_dirname);
1811           dispose_words (wl);
1812           local_dirname = *dirname;
1813         }
1814       else
1815         {
1816           free (new_dirname);
1817           free (local_dirname);
1818           *dirname = xmalloc (1);
1819           **dirname = '\0';
1820           return 1;
1821         }
1822     }
1823
1824   if (!no_symbolic_links && (local_dirname[0] != '.' || local_dirname[1]))
1825     {
1826       char *temp1, *temp2;
1827       int len1, len2;
1828
1829       t = get_working_directory ("symlink-hook");
1830       temp1 = make_absolute (local_dirname, t);
1831       free (t);
1832       temp2 = canonicalize_pathname (temp1);
1833       /* If we can't canonicalize, bail. */
1834       if (temp2 == 0)
1835         {
1836           free (temp1);
1837           return 1;
1838         }
1839       len1 = strlen (temp1);
1840       if (temp1[len1 - 1] == '/')
1841         {
1842           len2 = strlen (temp2);
1843           temp2 = xrealloc (temp2, len2 + 2);
1844           temp2[len2] = '/';
1845           temp2[len2 + 1] = '\0';
1846         }
1847       free (local_dirname);
1848       *dirname = temp2;
1849       free (temp1);
1850     }
1851   return (return_value);
1852 }
1853
1854 static char **history_completion_array = (char **)NULL;
1855 static int harry_size;
1856 static int harry_len;
1857
1858 static void
1859 build_history_completion_array ()
1860 {
1861   register int i, j;
1862   HIST_ENTRY **hlist;
1863   char **tokens;
1864
1865   /* First, clear out the current dynamic history completion list. */
1866   if (harry_size)
1867     {
1868       for (i = 0; history_completion_array[i]; i++)
1869         free (history_completion_array[i]);
1870
1871       free (history_completion_array);
1872
1873       history_completion_array = (char **)NULL;
1874       harry_size = 0;
1875       harry_len = 0;
1876     }
1877
1878   /* Next, grovel each line of history, making each shell-sized token
1879      a separate entry in the history_completion_array. */
1880   hlist = history_list ();
1881
1882   if (hlist)
1883     {
1884       for (i = 0; hlist[i]; i++)
1885         {
1886           /* Separate each token, and place into an array. */
1887           tokens = history_tokenize (hlist[i]->line);
1888
1889           for (j = 0; tokens && tokens[j]; j++)
1890             {
1891               if (harry_len + 2 > harry_size)
1892                 {
1893                   harry_size += 10;
1894                   history_completion_array = (char **) xrealloc
1895                     (history_completion_array, harry_size * sizeof (char *));
1896                 }
1897
1898               history_completion_array[harry_len++] = tokens[j];
1899               history_completion_array[harry_len] = (char *)NULL;
1900             }
1901           free (tokens);
1902         }
1903
1904       /* Sort the complete list of tokens. */
1905       qsort (history_completion_array, harry_len, sizeof (char *), (Function *)qsort_string_compare);
1906     }
1907 }
1908
1909 static char *
1910 history_completion_generator (hint_text, state)
1911      char *hint_text;
1912      int state;
1913 {
1914   static int local_index, len;
1915   static char *text;
1916
1917   /* If this is the first call to the generator, then initialize the
1918      list of strings to complete over. */
1919   if (state == 0)
1920     {
1921       local_index = 0;
1922       build_history_completion_array ();
1923       text = hint_text;
1924       len = strlen (text);
1925     }
1926
1927   while (history_completion_array && history_completion_array[local_index])
1928     {
1929       if (strncmp (text, history_completion_array[local_index++], len) == 0)
1930         return (savestring (history_completion_array[local_index - 1]));
1931     }
1932   return ((char *)NULL);
1933 }
1934
1935 static void
1936 dynamic_complete_history (count, key)
1937      int count, key;
1938 {
1939   Function *orig_func;
1940   CPPFunction *orig_attempt_func;
1941
1942   orig_func = rl_completion_entry_function;
1943   orig_attempt_func = rl_attempted_completion_function;
1944   rl_completion_entry_function = (Function *)history_completion_generator;
1945   rl_attempted_completion_function = (CPPFunction *)NULL;
1946
1947   if (rl_last_func == (Function *)dynamic_complete_history)
1948     rl_complete_internal ('?');
1949   else
1950     rl_complete_internal (TAB);
1951
1952   rl_completion_entry_function = orig_func;
1953   rl_attempted_completion_function = orig_attempt_func;
1954 }
1955
1956 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
1957 static void
1958 bash_complete_username (ignore, ignore2)
1959      int ignore, ignore2;
1960 {
1961   bash_complete_username_internal (TAB);
1962 }
1963
1964 static void
1965 bash_possible_username_completions (ignore, ignore2)
1966      int ignore, ignore2;
1967 {
1968   bash_complete_username_internal ('?');
1969 }
1970
1971 static void
1972 bash_complete_username_internal (what_to_do)
1973      int what_to_do;
1974 {
1975   bash_specific_completion
1976     (what_to_do, (Function *)username_completion_function);
1977 }
1978
1979 static void
1980 bash_complete_filename (ignore, ignore2)
1981      int ignore, ignore2;
1982 {
1983   bash_complete_filename_internal (TAB);
1984 }
1985
1986 static void
1987 bash_possible_filename_completions (ignore, ignore2)
1988      int ignore, ignore2;
1989 {
1990   bash_complete_filename_internal ('?');
1991 }
1992
1993 static void
1994 bash_complete_filename_internal (what_to_do)
1995      int what_to_do;
1996 {
1997   Function  *orig_func, *orig_dir_func;
1998   CPPFunction *orig_attempt_func;
1999   char *orig_rl_completer_word_break_characters;
2000
2001   orig_func = rl_completion_entry_function;
2002   orig_attempt_func = rl_attempted_completion_function;
2003   orig_dir_func = rl_directory_completion_hook;
2004   orig_rl_completer_word_break_characters = rl_completer_word_break_characters;
2005   rl_completion_entry_function = (Function *)filename_completion_function;
2006   rl_attempted_completion_function = (CPPFunction *)NULL;
2007   rl_directory_completion_hook = (Function *)NULL;
2008   rl_completer_word_break_characters = " \t\n\"\'";
2009
2010   rl_complete_internal (what_to_do);
2011
2012   rl_completion_entry_function = orig_func;
2013   rl_attempted_completion_function = orig_attempt_func;
2014   rl_directory_completion_hook = orig_dir_func;
2015   rl_completer_word_break_characters = orig_rl_completer_word_break_characters;
2016 }
2017
2018 static void
2019 bash_complete_hostname (ignore, ignore2)
2020      int ignore, ignore2;
2021 {
2022   bash_complete_hostname_internal (TAB);
2023 }
2024
2025 static void
2026 bash_possible_hostname_completions (ignore, ignore2)
2027      int ignore, ignore2;
2028 {
2029   bash_complete_hostname_internal ('?');
2030 }
2031
2032 static void
2033 bash_complete_variable (ignore, ignore2)
2034      int ignore, ignore2;
2035 {
2036   bash_complete_variable_internal (TAB);
2037 }
2038
2039 static void
2040 bash_possible_variable_completions (ignore, ignore2)
2041      int ignore, ignore2;
2042 {
2043   bash_complete_variable_internal ('?');
2044 }
2045
2046 static void
2047 bash_complete_command (ignore, ignore2)
2048      int ignore, ignore2;
2049 {
2050   bash_complete_command_internal (TAB);
2051 }
2052
2053 static void
2054 bash_possible_command_completions (ignore, ignore2)
2055      int ignore, ignore2;
2056 {
2057   bash_complete_command_internal ('?');
2058 }
2059
2060 static void
2061 bash_complete_hostname_internal (what_to_do)
2062      int what_to_do;
2063 {
2064   bash_specific_completion
2065     (what_to_do, (Function *)hostname_completion_function);
2066 }
2067
2068 static void
2069 bash_complete_variable_internal (what_to_do)
2070      int what_to_do;
2071 {
2072   bash_specific_completion
2073     (what_to_do, (Function *)variable_completion_function);
2074 }
2075
2076 static void
2077 bash_complete_command_internal (what_to_do)
2078      int what_to_do;
2079 {
2080   bash_specific_completion
2081     (what_to_do, (Function *)command_word_completion_function);
2082 }
2083
2084 static char *
2085 glob_complete_word (text, state)
2086      char *text;
2087      int state;
2088 {
2089   static char **matches = (char **)NULL;
2090   static int ind;
2091   char *ret;
2092
2093   if (state == 0)
2094     {
2095       rl_filename_completion_desired = 1;
2096       if (matches)
2097         free (matches);
2098       matches = shell_glob_filename (text);
2099       if (GLOB_FAILED (matches))
2100         matches = (char **)NULL;
2101       ind = 0;
2102     }
2103
2104   ret = matches ? matches[ind] : (char *)NULL;
2105   ind++;
2106   return ret;
2107 }
2108
2109 static void
2110 bash_glob_completion_internal (what_to_do)
2111      int what_to_do;
2112 {
2113   bash_specific_completion (what_to_do, (Function *)glob_complete_word);
2114 }
2115
2116 static void
2117 bash_glob_expand_word (count, key)
2118      int count, key;
2119 {
2120   bash_glob_completion_internal ('*');
2121 }
2122
2123 static void
2124 bash_glob_list_expansions (count, key)
2125      int count, key;
2126 {
2127   bash_glob_completion_internal ('?');
2128 }
2129
2130 static void
2131 bash_specific_completion (what_to_do, generator)
2132      int what_to_do;
2133      Function *generator;
2134 {
2135   Function *orig_func;
2136   CPPFunction *orig_attempt_func;
2137
2138   orig_func = rl_completion_entry_function;
2139   orig_attempt_func = rl_attempted_completion_function;
2140   rl_completion_entry_function = generator;
2141   rl_attempted_completion_function = (CPPFunction *)NULL;
2142
2143   rl_complete_internal (what_to_do);
2144
2145   rl_completion_entry_function = orig_func;
2146   rl_attempted_completion_function = orig_attempt_func;
2147 }
2148
2149 #endif  /* SPECIFIC_COMPLETION_FUNCTIONS */
2150
2151 /* Filename quoting for completion. */
2152 /* A function to strip unquoted quote characters (single quotes, double
2153    quotes, and backslashes).  It allows single quotes to appear
2154    within double quotes, and vice versa.  It should be smarter. */
2155 static char *
2156 bash_dequote_filename (text, quote_char)
2157      char *text;
2158 {
2159   char *ret, *p, *r;
2160   int l, quoted;
2161
2162   l = strlen (text);
2163   ret = xmalloc (l + 1);
2164   for (quoted = quote_char, p = text, r = ret; p && *p; p++)
2165     {
2166       /* Allow backslash-quoted characters to pass through unscathed. */
2167       if (*p == '\\')
2168         {
2169           *r++ = *++p;
2170           if (*p == '\0')
2171             break;
2172           continue;
2173         }
2174       /* Close quote. */
2175       if (quoted && *p == quoted)
2176         {
2177           quoted = 0;
2178           continue;
2179         }
2180       /* Open quote. */
2181       if (quoted == 0 && (*p == '\'' || *p == '"'))
2182         {
2183           quoted = *p;
2184           continue;
2185         }
2186       *r++ = *p;
2187     }
2188   *r = '\0';
2189   return ret;
2190 }
2191
2192 /* Quote characters that the readline completion code would treat as
2193    word break characters with backslashes.  Pass backslash-quoted
2194    characters through without examination. */
2195 static char *
2196 quote_word_break_chars (text)
2197      char *text;
2198 {
2199   char *ret, *r, *s;
2200   int l;
2201
2202   l = strlen (text);
2203   ret = xmalloc ((2 * l) + 1);
2204   for (s = text, r = ret; *s; s++)
2205     {
2206       /* Pass backslash-quoted characters through, including the backslash. */
2207       if (*s == '\\')
2208         {
2209           *r++ = '\\';
2210           *r++ = *++s;
2211           if (*s == '\0')
2212             break;
2213           continue;
2214         }
2215       /* OK, we have an unquoted character.  Check its presence in
2216          rl_completer_word_break_characters. */
2217       if (strchr (rl_completer_word_break_characters, *s))
2218         *r++ = '\\';
2219       *r++ = *s;
2220     }
2221   *r = '\0';
2222   return ret;
2223 }
2224
2225 /* Quote a filename using double quotes, single quotes, or backslashes
2226    depending on the value of completion_quoting_style.  If we're
2227    completing using backslashes, we need to quote some additional
2228    characters (those that readline treats as word breaks), so we call
2229    quote_word_break_chars on the result. */
2230 static char *
2231 bash_quote_filename (s, rtype, qcp)
2232      char *s;
2233      int rtype;
2234      char *qcp;
2235 {
2236   char *rtext, *mtext, *ret;
2237   int rlen, cs;
2238
2239   rtext = (char *)NULL;
2240
2241   /* If RTYPE == MULT_MATCH, it means that there is
2242      more than one match.  In this case, we do not add
2243      the closing quote or attempt to perform tilde
2244      expansion.  If RTYPE == SINGLE_MATCH, we try
2245      to perform tilde expansion, because single and double
2246      quotes inhibit tilde expansion by the shell. */
2247
2248   mtext = s;
2249   if (mtext[0] == '~' && rtype == SINGLE_MATCH)
2250     mtext = bash_tilde_expand (s);
2251
2252   cs = completion_quoting_style;
2253   /* Might need to modify the default completion style based on *qcp,
2254      since it's set to any user-provided opening quote.  We also change
2255      to single-quoting if there is no user-provided opening quote and
2256      the word being completed contains newlines, since those are not
2257      quoted correctly using backslashes (a backslash-newline pair is
2258      special to the shell parser). */
2259   if (*qcp == '\0' && cs == COMPLETE_BSQUOTE && strchr (mtext, '\n'))
2260     cs = COMPLETE_SQUOTE;
2261   else if (*qcp == '"')
2262     cs = COMPLETE_DQUOTE;
2263   else if (*qcp == '\'')
2264     cs = COMPLETE_SQUOTE;
2265 #if defined (BANG_HISTORY)
2266   else if (*qcp == '\0' && history_expansion && cs == COMPLETE_DQUOTE &&
2267            history_expansion_inhibited == 0 && strchr (mtext, '!'))
2268     cs = COMPLETE_BSQUOTE;
2269
2270   if (*qcp == '"' && history_expansion && cs == COMPLETE_DQUOTE &&
2271         history_expansion_inhibited == 0 && strchr (mtext, '!'))
2272     {
2273       cs = COMPLETE_BSQUOTE;
2274       *qcp = '\0';
2275     }
2276 #endif
2277
2278   switch (cs)
2279     {
2280     case COMPLETE_DQUOTE:
2281       rtext = double_quote (mtext);
2282       break;
2283     case COMPLETE_SQUOTE:
2284       rtext = single_quote (mtext);
2285       break;
2286     case COMPLETE_BSQUOTE:
2287       rtext = backslash_quote (mtext);
2288       break;
2289     }
2290
2291   if (mtext != s)
2292     free (mtext);
2293
2294   /* We may need to quote additional characters: those that readline treats
2295      as word breaks that are not quoted by backslash_quote. */
2296   if (rtext && cs == COMPLETE_BSQUOTE)
2297     {
2298       mtext = quote_word_break_chars (rtext);
2299       free (rtext);
2300       rtext = mtext;
2301     }
2302
2303   /* Leave the opening quote intact.  The readline completion code takes
2304      care of avoiding doubled opening quotes. */
2305   rlen = strlen (rtext);
2306   ret = xmalloc (rlen + 1);
2307   strcpy (ret, rtext);
2308
2309   /* If there are multiple matches, cut off the closing quote. */
2310   if (rtype == MULT_MATCH && cs != COMPLETE_BSQUOTE)
2311     ret[rlen - 1] = '\0';
2312   free (rtext);
2313   return ret;
2314 }
2315
2316 /* Support for binding readline key sequences to Unix commands. */
2317 static Keymap cmd_xmap;
2318
2319 static int
2320 bash_execute_unix_command (count, key)
2321      int count; /* ignored */
2322      int key;
2323 {
2324   Keymap ckmap;         /* current keymap */
2325   Keymap xkmap;         /* unix command executing keymap */
2326   register int i;
2327   char *cmd;
2328
2329   /* First, we need to find the right command to execute.  This is tricky,
2330      because we might have already indirected into another keymap. */
2331   ckmap = rl_get_keymap ();
2332   if (ckmap != rl_executing_keymap)
2333     {
2334       /* bogus.  we have to search.  only handle one level of indirection. */
2335       for (i = 0; i < KEYMAP_SIZE; i++)
2336         {
2337           if (ckmap[i].type == ISKMAP && (Keymap)ckmap[i].function == rl_executing_keymap)
2338             break;
2339         }
2340       if (i < KEYMAP_SIZE)
2341         xkmap = (Keymap)cmd_xmap[i].function;
2342       else
2343         {
2344           crlf ();
2345           internal_error ("bash_execute_unix_command: cannot find keymap for command");
2346           rl_forced_update_display ();
2347           return 1;
2348         }
2349     }
2350   else
2351     xkmap = cmd_xmap;
2352
2353   cmd = (char *)xkmap[key].function;
2354
2355   if (cmd == 0)
2356     {
2357       ding ();
2358       return 1;
2359     }
2360
2361   crlf ();      /* move to a new line */
2362
2363   cmd = savestring (cmd);
2364   parse_and_execute (cmd, "bash_execute_unix_command", 0);
2365
2366   /* and restore the readline buffer and display after command execution. */
2367   rl_forced_update_display ();
2368   return 0;
2369 }
2370
2371 static void
2372 init_unix_command_map ()
2373 {
2374   cmd_xmap = rl_make_bare_keymap ();
2375 }
2376
2377 static int
2378 isolate_sequence (string, ind, need_dquote, startp)
2379      char *string;
2380      int ind, need_dquote, *startp;
2381 {
2382   register int i;
2383   int c, passc, delim;
2384
2385   for (i = ind; string[i] && whitespace (string[i]); i++)
2386     ;
2387   /* NEED_DQUOTE means that the first non-white character *must* be `"'. */
2388   if (need_dquote && string[i] != '"')
2389     {
2390       builtin_error ("%s: first non-whitespace character is not `\"'", string);
2391       return -1;
2392     }
2393
2394   /* We can have delimited strings even if NEED_DQUOTE == 0, like the command
2395      string to bind the key sequence to. */
2396   delim = (string[i] == '"' || string[i] == '\'') ? string[i] : 0;
2397     
2398   if (startp)
2399     *startp = delim ? ++i : i;
2400
2401   for (passc = 0; c = string[i]; i++)
2402     {
2403       if (passc)
2404         {
2405           passc = 0;
2406           continue;
2407         }
2408       if (c == '\\')
2409         {
2410           passc++;
2411           continue;
2412         }
2413       if (c == delim)
2414         break;
2415     }
2416
2417   if (delim && string[i] != delim)
2418     {
2419       builtin_error ("%s: no closing `%c'", string, delim);
2420       return -1;
2421     }
2422
2423   return i;
2424 }
2425
2426 int
2427 bind_keyseq_to_unix_command (line)
2428      char *line;
2429 {
2430   Keymap kmap;
2431   char *kseq, *value;
2432   int i, kstart, len, ok;
2433
2434   if (cmd_xmap == 0)
2435     init_unix_command_map ();
2436
2437   kmap = rl_get_keymap ();
2438
2439   /* We duplicate some of the work done by rl_parse_and_bind here, but
2440      this code only has to handle `"keyseq": ["]command["]' and can
2441      generate an error for anything else. */
2442   i = isolate_sequence (line, 0, 1, &kstart);
2443   if (i < 0)
2444     return -1;
2445
2446   /* Create the key sequence string to pass to rl_generic_bind */
2447   kseq = substring (line, kstart, i);
2448
2449   for ( ; line[i] && line[i] != ':'; i++)
2450     ;
2451   if (line[i] != ':')
2452     {
2453       builtin_error ("%s: missing colon separator", line);
2454       return -1;
2455     }
2456
2457   i = isolate_sequence (line, i + 1, 0, &kstart);
2458   if (i < 0)
2459     return -1;
2460
2461   /* Create the value string containing the command to execute. */
2462   value = substring (line, kstart, i);
2463
2464   /* Save the command to execute and the key sequence in the CMD_XMAP */
2465   rl_generic_bind (ISMACR, kseq, value, cmd_xmap);
2466
2467   /* and bind the key sequence in the current keymap to a function that
2468      understands how to execute from CMD_XMAP */
2469   rl_set_key (kseq, (Function *)bash_execute_unix_command, kmap);
2470   
2471   return 0;
2472 }
2473
2474 /* Used by the programmable completion code.  Complete TEXT as a filename,
2475    but return only directories as matches.  Dequotes the filename before
2476    attempting to find matches. */
2477 char **
2478 bash_directory_completion_matches (text)
2479      char *text;
2480 {
2481   char **m1;
2482   char *dfn;
2483   int qc;
2484
2485   qc = (text[0] == '"' || text[0] == '\'') ? text[0] : 0;
2486   dfn = bash_dequote_filename (text, qc);
2487   m1 = completion_matches (dfn, filename_completion_function);
2488   free (dfn);
2489
2490   if (m1 == 0 || m1[0] == 0)
2491     return m1;
2492   /* We don't bother recomputing the lcd of the matches, because it will just
2493      get thrown away by the programmable completion code and recomputed
2494      later. */
2495   (void)bash_ignore_filenames (m1);
2496   return m1;
2497 }
2498 #endif /* READLINE */