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