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