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