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