1 /* bashline.c -- Bash's interface to the readline library. */
3 /* Copyright (C) 1987,1991 Free Software Foundation, Inc.
5 This file is part of GNU Bash, the Bourne Again SHell.
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)
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.
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. */
23 #if defined (READLINE)
25 #include "bashtypes.h"
26 #include "posixstat.h"
28 #if defined (HAVE_UNISTD_H)
38 #include "execute_cmd.h"
40 #include "builtins/common.h"
41 #include <readline/rlconf.h>
42 #include <readline/readline.h>
43 #include <readline/history.h>
45 #include <glob/glob.h>
51 #if defined (BRACE_COMPLETION)
52 extern void bash_brace_completion ();
53 #endif /* BRACE_COMPLETION */
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 ();
60 /* Helper functions for Readline. */
61 static int bash_directory_completion_hook ();
62 static void filename_completion_ignore ();
63 static void bash_push_line ();
65 static char **attempt_shell_completion ();
66 static char *variable_completion_function ();
67 static char *hostname_completion_function ();
68 static char *command_word_completion_function ();
69 static char *command_subst_completion_function ();
70 static void dynamic_complete_history ();
72 static char *glob_complete_word ();
73 static void bash_glob_expand_word ();
74 static void bash_glob_list_expansions ();
76 static void snarf_hosts_from_file (), add_host_name ();
78 static char *bash_dequote_filename ();
79 static char *bash_quote_filename ();
82 static int posix_edit_macros ();
85 /* Variables used here but defined in other files. */
86 extern int posixly_correct, no_symbolic_links;
87 extern int rl_explicit_arg;
88 extern char *current_prompt_string, *ps1_prompt;
89 extern STRING_INT_ALIST word_token_alist[];
90 extern Function *rl_last_func;
91 extern int rl_filename_completion_desired;
93 /* Helper functions from subst.c */
94 extern int char_is_quoted ();
95 extern int unclosed_pair ();
97 /* SPECIFIC_COMPLETION_FUNCTIONS specifies that we have individual
98 completion functions which indicate what type of completion should be
99 done (at or before point) that can be bound to key sequences with
100 the readline library. */
101 #define SPECIFIC_COMPLETION_FUNCTIONS
103 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
104 static void bash_specific_completion ();
105 static void bash_complete_filename (), bash_possible_filename_completions ();
106 static void bash_complete_filename_internal ();
107 static void bash_complete_username (), bash_possible_username_completions ();
108 static void bash_complete_username_internal ();
109 static void bash_complete_hostname (), bash_possible_hostname_completions ();
110 static void bash_complete_hostname_internal ();
111 static void bash_complete_variable (), bash_possible_variable_completions ();
112 static void bash_complete_variable_internal ();
113 static void bash_complete_command (), bash_possible_command_completions ();
114 static void bash_complete_command_internal ();
115 #endif /* SPECIFIC_COMPLETION_FUNCTIONS */
117 #if defined (VI_MODE)
118 static void vi_edit_and_execute_command ();
121 /* Non-zero once initalize_readline () has been called. */
122 int bash_readline_initialized = 0;
124 /* If non-zero, we do hostname completion, breaking words at `@' and
125 trying to complete the stuff after the `@' from our own internal
127 int perform_hostname_completion = 1;
129 static char *bash_completer_word_break_characters = " \t\n\"'@><=;|&(:";
130 static char *bash_nohostname_word_break_characters = " \t\n\"'><=;|&(:";
132 static Function *old_rl_startup_hook = (Function *) NULL;
134 /* What kind of quoting is performed by bash_quote_filename:
135 COMPLETE_DQUOTE = double-quoting the filename
136 COMPLETE_SQUOTE = single_quoting the filename
137 COMPLETE_BSQUOTE = backslash-quoting special chars in the filename
139 #define COMPLETE_DQUOTE 1
140 #define COMPLETE_SQUOTE 2
141 #define COMPLETE_BSQUOTE 3
142 static int completion_quoting_style = COMPLETE_BSQUOTE;
144 /* Change the readline VI-mode keymaps into or out of Posix.2 compliance.
145 Called when the shell is put into or out of `posix' mode. */
147 posix_readline_initialize (on_or_off)
151 rl_variable_bind ("comment-begin", "#");
152 #if defined (VI_MODE)
153 rl_bind_key_in_map (CTRL('I'), on_or_off ? rl_insert : rl_complete, vi_insertion_keymap);
158 enable_hostname_completion (on_or_off)
163 perform_hostname_completion = 1;
164 rl_special_prefixes = "$@";
165 rl_completer_word_break_characters = bash_completer_word_break_characters;
169 perform_hostname_completion = 0;
170 rl_special_prefixes = "$";
171 rl_completer_word_break_characters = bash_nohostname_word_break_characters;
175 /* Called once from parse.y if we are going to use readline. */
177 initialize_readline ()
179 if (bash_readline_initialized)
182 rl_terminal_name = get_string_value ("TERM");
184 rl_outstream = stderr;
186 /* Allow conditional parsing of the ~/.inputrc file. */
187 rl_readline_name = "Bash";
189 /* Bind up our special shell functions. */
190 rl_add_defun ("shell-expand-line", (Function *)shell_expand_line, -1);
191 rl_bind_key_in_map (CTRL('E'), (Function *)shell_expand_line, emacs_meta_keymap);
193 /* Bind up our special shell functions. */
194 rl_add_defun ("history-expand-line", (Function *)history_expand_line, -1);
195 rl_bind_key_in_map ('^', (Function *)history_expand_line, emacs_meta_keymap);
197 /* Backwards compatibility. */
198 rl_add_defun ("insert-last-argument", rl_yank_last_arg, -1);
201 ("operate-and-get-next", (Function *)operate_and_get_next, CTRL('O'));
204 ("display-shell-version", (Function *)display_shell_version, -1);
206 (CTRL ('V'), (Function *)display_shell_version, emacs_ctlx_keymap);
208 /* In Bash, the user can switch editing modes with "set -o [vi emacs]",
209 so it is not necessary to allow C-M-j for context switching. Turn
210 off this occasionally confusing behaviour. */
211 rl_unbind_key_in_map (CTRL('J'), emacs_meta_keymap);
212 rl_unbind_key_in_map (CTRL('M'), emacs_meta_keymap);
213 #if defined (VI_MODE)
214 rl_unbind_key_in_map (CTRL('E'), vi_movement_keymap);
217 #if defined (BRACE_COMPLETION)
218 rl_add_defun ("complete-into-braces", bash_brace_completion, -1);
219 rl_bind_key_in_map ('{', bash_brace_completion, emacs_meta_keymap);
220 #endif /* BRACE_COMPLETION */
222 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
223 rl_add_defun ("complete-filename", bash_complete_filename, -1);
224 rl_bind_key_in_map ('/', bash_complete_filename, emacs_meta_keymap);
225 rl_add_defun ("possible-filename-completions",
226 bash_possible_filename_completions, -1);
227 rl_bind_key_in_map ('/', bash_possible_filename_completions, emacs_ctlx_keymap);
229 rl_add_defun ("complete-username", bash_complete_username, -1);
230 rl_bind_key_in_map ('~', bash_complete_username, emacs_meta_keymap);
231 rl_add_defun ("possible-username-completions",
232 bash_possible_username_completions, -1);
233 rl_bind_key_in_map ('~', bash_possible_username_completions, emacs_ctlx_keymap);
235 rl_add_defun ("complete-hostname", bash_complete_hostname, -1);
236 rl_bind_key_in_map ('@', bash_complete_hostname, emacs_meta_keymap);
237 rl_add_defun ("possible-hostname-completions",
238 bash_possible_hostname_completions, -1);
239 rl_bind_key_in_map ('@', bash_possible_hostname_completions, emacs_ctlx_keymap);
241 rl_add_defun ("complete-variable", bash_complete_variable, -1);
242 rl_bind_key_in_map ('$', bash_complete_variable, emacs_meta_keymap);
243 rl_add_defun ("possible-variable-completions",
244 bash_possible_variable_completions, -1);
245 rl_bind_key_in_map ('$', bash_possible_variable_completions, emacs_ctlx_keymap);
247 rl_add_defun ("complete-command", bash_complete_command, -1);
248 rl_bind_key_in_map ('!', bash_complete_command, emacs_meta_keymap);
249 rl_add_defun ("possible-command-completions",
250 bash_possible_command_completions, -1);
251 rl_bind_key_in_map ('!', bash_possible_command_completions, emacs_ctlx_keymap);
253 rl_add_defun ("glob-expand-word", bash_glob_expand_word, -1);
254 rl_add_defun ("glob-list-expansions", bash_glob_list_expansions, -1);
255 rl_bind_key_in_map ('*', bash_glob_expand_word, emacs_ctlx_keymap);
256 rl_bind_key_in_map ('g', bash_glob_list_expansions, emacs_ctlx_keymap);
258 #endif /* SPECIFIC_COMPLETION_FUNCTIONS */
260 rl_add_defun ("dynamic-complete-history", dynamic_complete_history, -1);
261 rl_bind_key_in_map (TAB, dynamic_complete_history, emacs_meta_keymap);
263 /* Tell the completer that we want a crack first. */
264 rl_attempted_completion_function = (CPPFunction *)attempt_shell_completion;
266 /* Tell the completer that we might want to follow symbolic links or
267 do other expansion on directory names. */
268 rl_directory_completion_hook = bash_directory_completion_hook;
270 /* Tell the filename completer we want a chance to ignore some names. */
271 rl_ignore_some_completions_function = (Function *)filename_completion_ignore;
273 #if defined (VI_MODE)
274 rl_bind_key_in_map ('v', vi_edit_and_execute_command, vi_movement_keymap);
276 rl_bind_key_in_map ('@', posix_edit_macros, vi_movement_keymap);
280 rl_completer_quote_characters = "'\"";
282 /* This sets rl_completer_word_break_characters and rl_special_prefixes
283 to the appropriate values, depending on whether or not hostname
284 completion is enabled. */
285 enable_hostname_completion (perform_hostname_completion);
287 /* characters that need to be quoted when appearing in filenames. */
288 rl_filename_quote_characters = " \t\n\\\"'@<>=;|&()#$`?*[!";
289 rl_filename_quoting_function = bash_quote_filename;
290 rl_filename_dequoting_function = bash_dequote_filename;
291 rl_char_is_quoted_p = char_is_quoted;
294 posix_readline_initialize (1);
296 bash_readline_initialized = 1;
299 /* On Sun systems at least, rl_attempted_completion_function can end up
300 getting set to NULL, and rl_completion_entry_function set to do command
301 word completion if Bash is interrupted while trying to complete a command
302 word. This just resets all the completion functions to the right thing.
303 It's called from throw_to_top_level(). */
305 bashline_reinitialize ()
308 rl_attempted_completion_function = attempt_shell_completion;
309 rl_completion_entry_function = (Function *)NULL;
310 rl_directory_completion_hook = bash_directory_completion_hook;
311 rl_ignore_some_completions_function = (Function *)filename_completion_ignore;
314 /* Contains the line to push into readline. */
315 static char *push_to_readline = (char *)NULL;
317 /* Push the contents of push_to_readline into the
322 if (push_to_readline)
324 rl_insert_text (push_to_readline);
325 free (push_to_readline);
326 push_to_readline = (char *)NULL;
327 rl_startup_hook = old_rl_startup_hook;
331 /* Call this to set the initial text for the next line to read
337 FREE (push_to_readline);
339 push_to_readline = savestring (line);
340 old_rl_startup_hook = rl_startup_hook;
341 rl_startup_hook = (Function *)bash_push_line;
347 display_shell_version (count, c)
351 show_shell_version (0);
352 putc ('\r', rl_outstream);
353 fflush (rl_outstream);
358 /* **************************************************************** */
362 /* **************************************************************** */
364 /* If the user requests hostname completion, then simply build a list
365 of hosts, and complete from that forever more. */
367 /* The kept list of hostnames. */
368 static char **hostname_list = (char **)NULL;
370 /* The physical size of the above list. */
371 static int hostname_list_size;
373 /* The number of hostnames in the above list. */
374 static int hostname_list_length;
376 /* Whether or not HOSTNAME_LIST has been initialized. */
377 int hostname_list_initialized = 0;
379 /* Initialize the hostname completion table. */
381 initialize_hostname_list ()
385 temp = get_string_value ("HOSTFILE");
387 temp = get_string_value ("hostname_completion_file");
389 temp = DEFAULT_HOSTS_FILE;
391 snarf_hosts_from_file (temp);
394 hostname_list_initialized++;
397 /* Add NAME to the list of hosts. */
404 if (hostname_list_length + 2 > hostname_list_size)
406 hostname_list_size = (hostname_list_size + 32) - (hostname_list_size % 32);
407 size = hostname_list_size * sizeof (char *);
408 hostname_list = (char **)xrealloc (hostname_list, size);
411 hostname_list[hostname_list_length++] = savestring (name);
412 hostname_list[hostname_list_length] = (char *)NULL;
415 #define cr_whitespace(c) ((c) == '\r' || (c) == '\n' || whitespace(c))
418 snarf_hosts_from_file (filename)
422 char *temp, buffer[256], name[256];
423 register int i, start;
425 file = fopen (filename, "r");
429 while (temp = fgets (buffer, 255, file))
431 /* Skip to first character. */
432 for (i = 0; buffer[i] && cr_whitespace (buffer[i]); i++)
435 /* If comment or blank line, ignore. */
436 if (buffer[i] == '\0' || buffer[i] == '#')
439 /* If `preprocessor' directive, do the include. */
440 if (strncmp (buffer + i, "$include ", 9) == 0)
444 /* Find start of filename. */
445 for (incfile = buffer + i + 9; *incfile && whitespace (*incfile); incfile++)
448 /* Find end of filename. */
449 for (t = incfile; *t && cr_whitespace (*t) == 0; t++)
454 snarf_hosts_from_file (incfile);
458 /* Skip internet address if present. */
459 if (digit (buffer[i]))
460 for (; buffer[i] && cr_whitespace (buffer[i]) == 0; i++);
462 /* Gobble up names. Each name is separated with whitespace. */
465 for (; cr_whitespace (buffer[i]); i++)
467 if (buffer[i] == '\0' || buffer[i] == '#')
470 /* Isolate the current word. */
471 for (start = i; buffer[i] && cr_whitespace (buffer[i]) == 0; i++)
475 strncpy (name, buffer + start, i - start);
476 name[i - start] = '\0';
477 add_host_name (name);
483 /* Return a NULL terminated list of hostnames which begin with TEXT.
484 Initialize the hostname list the first time if neccessary.
485 The array is malloc ()'ed, but not the individual strings. */
487 hostnames_matching (text)
490 register int i, len, nmatch, rsize;
493 if (hostname_list_initialized == 0)
494 initialize_hostname_list ();
496 if (hostname_list_initialized == 0)
497 return ((char **)NULL);
499 /* Special case. If TEXT consists of nothing, then the whole list is
503 result = (char **)xmalloc ((1 + hostname_list_length) * sizeof (char *));
504 for (i = 0; i < hostname_list_length; i++)
505 result[i] = hostname_list[i];
506 result[i] = (char *)NULL;
510 /* Scan until found, or failure. */
512 result = (char **)NULL;
513 for (i = nmatch = rsize = 0; i < hostname_list_length; i++)
515 if (STREQN (text, hostname_list[i], len) == 0)
518 /* OK, it matches. Add it to the list. */
521 rsize = (rsize + 16) - (rsize % 16);
522 result = (char **)xrealloc (result, rsize * sizeof (char *));
525 result[nmatch++] = hostname_list[i];
528 result[nmatch] = (char *)NULL;
532 /* The equivalent of the Korn shell C-o operate-and-get-next-history-line
534 static int saved_history_line_to_use = -1;
539 if (saved_history_line_to_use >= 0)
540 rl_get_previous_history (history_length - saved_history_line_to_use);
541 saved_history_line_to_use = -1;
542 rl_startup_hook = old_rl_startup_hook;
546 operate_and_get_next (count, c)
551 /* Accept the current line. */
554 /* Find the current line, and find the next line to use. */
555 where = where_history ();
557 if ((history_is_stifled () && (history_length >= max_input_history)) ||
558 (where >= history_length - 1))
559 saved_history_line_to_use = where;
561 saved_history_line_to_use = where + 1;
563 old_rl_startup_hook = rl_startup_hook;
564 rl_startup_hook = (Function *)set_saved_history;
567 #if defined (VI_MODE)
568 /* This vi mode command causes VI_EDIT_COMMAND to be run on the current
569 command being entered (if no explicit argument is given), otherwise on
570 a command from the history file. */
572 #define VI_EDIT_COMMAND "fc -e ${VISUAL:-${EDITOR:-vi}}"
575 vi_edit_and_execute_command (count, c)
580 /* Accept the current line. */
585 command = xmalloc (strlen (VI_EDIT_COMMAND) + 8);
586 sprintf (command, "%s %d", VI_EDIT_COMMAND, count);
590 /* Take the command we were just editing, add it to the history file,
591 then call fc to operate on it. We have to add a dummy command to
592 the end of the history because fc ignores the last command (assumes
593 it's supposed to deal with the command before the `fc'). */
595 add_history (rl_line_buffer);
597 history_lines_this_session++;
599 command = savestring (VI_EDIT_COMMAND);
601 parse_and_execute (command, "v", -1);
602 rl_line_buffer[0] = '\0'; /* XXX */
608 posix_edit_macros (count, key)
612 char alias_name[3], *alias_value, *macro;
617 alias_name[2] = '\0';
619 alias_value = get_alias_value (alias_name);
620 if (alias_value && *alias_value)
622 macro = savestring (alias_value);
623 rl_push_macro_input (macro);
629 /* **************************************************************** */
631 /* How To Do Shell Completion */
633 /* **************************************************************** */
635 /* Do some completion on TEXT. The indices of TEXT in RL_LINE_BUFFER are
636 at START and END. Return an array of matches, or NULL if none. */
638 attempt_shell_completion (text, start, end)
642 int in_command_position, ti;
643 char **matches, *command_separator_chars;
645 command_separator_chars = ";|&{(`";
646 matches = (char **)NULL;
647 rl_ignore_some_completions_function = (Function *)filename_completion_ignore;
649 /* Determine if this could be a command word. It is if it appears at
650 the start of the line (ignoring preceding whitespace), or if it
651 appears after a character that separates commands. It cannot be a
652 command word if we aren't at the top-level prompt. */
655 while ((ti > -1) && (whitespace (rl_line_buffer[ti])))
658 in_command_position = 0;
661 /* Only do command completion at the start of a line when we
662 are prompting at the top level. */
663 if (current_prompt_string == ps1_prompt)
664 in_command_position++;
666 else if (member (rl_line_buffer[ti], command_separator_chars))
668 register int this_char, prev_char;
670 in_command_position++;
672 /* Handle the two character tokens `>&', `<&', and `>|'.
673 We are not in a command position after one of these. */
674 this_char = rl_line_buffer[ti];
675 prev_char = rl_line_buffer[ti - 1];
677 if ((this_char == '&' && (prev_char == '<' || prev_char == '>')) ||
678 (this_char == '|' && prev_char == '>'))
679 in_command_position = 0;
680 else if ((this_char == '{' && prev_char == '$') ||
681 (char_is_quoted (rl_line_buffer, ti)))
682 in_command_position = 0;
686 /* This still could be in command position. It is possible
687 that all of the previous words on the line are variable
691 /* Special handling for command substitution. */
692 if (*text == '`' && unclosed_pair (rl_line_buffer, start, "`"))
693 matches = completion_matches (text, command_subst_completion_function);
696 if (!matches && *text == '$')
697 matches = completion_matches (text, variable_completion_function);
699 /* If the word starts in `~', and there is no slash in the word, then
700 try completing this word as a username. */
701 if (!matches && *text == '~' && !strchr (text, '/'))
702 matches = completion_matches (text, username_completion_function);
704 /* Another one. Why not? If the word starts in '@', then look through
705 the world of known hostnames for completion first. */
706 if (!matches && perform_hostname_completion && *text == '@')
707 matches = completion_matches (text, hostname_completion_function);
709 /* And last, (but not least) if this word is in a command position, then
710 complete over possible command names, including aliases, functions,
711 and command names. */
712 if (!matches && in_command_position)
714 matches = completion_matches (text, command_word_completion_function);
715 /* If we are attempting command completion and nothing matches, we
716 do not want readline to perform filename completion for us. We
717 still want to be able to complete partial pathnames, so set the
718 completion ignore function to something which will remove filenames
719 and leave directories in the match list. */
721 rl_ignore_some_completions_function = (Function *)bash_ignore_filenames;
724 /* This could be a globbing pattern, so try to expand it using pathname
726 if (!matches && glob_pattern_p (text))
727 matches = completion_matches (text, glob_complete_word);
732 /* This is the function to call when the word to complete is in a position
733 where a command word can be found. It grovels $PATH, looking for commands
734 that match. It also scans aliases, function names, and the shell_builtin
737 command_word_completion_function (hint_text, state)
741 static char *hint = (char *)NULL;
742 static char *path = (char *)NULL;
743 static char *val = (char *)NULL;
744 static char *filename_hint = (char *)NULL;
745 static int path_index, hint_len, istate;
746 static int mapping_over, local_index;
747 static SHELL_VAR **varlist = (SHELL_VAR **)NULL;
749 static alias_t **alias_list = (alias_t **)NULL;
752 /* We have to map over the possibilities for command words. If we have
753 no state, then make one just for that purpose. */
762 /* If this is an absolute program name, do not check it against
763 aliases, reserved words, functions or builtins. We must check
764 whether or not it is unique, and, if so, whether that filename
766 if (absolute_program (hint_text))
768 /* Perform tilde expansion on what's passed, so we don't end up
769 passing filenames with tildes directly to stat(). */
770 if (*hint_text == '~')
771 hint = bash_tilde_expand (hint_text);
773 hint = savestring (hint_text);
774 hint_len = strlen (hint);
777 free (filename_hint);
778 filename_hint = savestring (hint);
785 hint = savestring (hint_text);
786 hint_len = strlen (hint);
788 path = get_string_value ("PATH");
791 /* Initialize the variables for each type of command word. */
797 varlist = all_visible_functions ();
803 alias_list = all_aliases ();
807 /* mapping_over says what we are currently hacking. Note that every case
808 in this list must fall through when there are no more possibilities. */
810 switch (mapping_over)
812 case 0: /* Aliases come first. */
814 while (alias_list && alias_list[local_index])
816 register char *alias;
818 alias = alias_list[local_index++]->name;
820 if (STREQN (alias, hint, hint_len))
821 return (savestring (alias));
827 case 1: /* Then shell reserved words. */
829 while (word_token_alist[local_index].word)
831 register char *reserved_word;
833 reserved_word = word_token_alist[local_index++].word;
835 if (STREQN (reserved_word, hint, hint_len))
836 return (savestring (reserved_word));
842 case 2: /* Then function names. */
843 while (varlist && varlist[local_index])
845 register char *varname;
847 varname = varlist[local_index++]->name;
849 if (STREQN (varname, hint, hint_len))
850 return (savestring (varname));
855 case 3: /* Then shell builtins. */
856 for (; local_index < num_shell_builtins; local_index++)
858 /* Ignore it if it doesn't have a function pointer or if it
859 is not currently enabled. */
860 if (!shell_builtins[local_index].function ||
861 (shell_builtins[local_index].flags & BUILTIN_ENABLED) == 0)
864 if (STREQN (shell_builtins[local_index].name, hint, hint_len))
866 int i = local_index++;
868 return (savestring (shell_builtins[i].name));
875 /* Repeatedly call filename_completion_function while we have
876 members of PATH left. Question: should we stat each file?
877 Answer: we call executable_file () on each file. */
880 istate = (val != (char *)NULL);
886 /* Get the next directory from the path. If there is none, then we
888 if (!path || !path[path_index] ||
889 (current_path = extract_colon_unit (path, &path_index)) == 0)
890 return ((char *)NULL);
892 if (*current_path == 0)
895 current_path = savestring (".");
898 if (*current_path == '~')
902 t = bash_tilde_expand (current_path);
908 free (filename_hint);
910 filename_hint = xmalloc (2 + strlen (current_path) + hint_len);
911 sprintf (filename_hint, "%s/%s", current_path, hint);
917 val = filename_completion_function (filename_hint, istate);
922 /* If the hint text is an absolute program, then don't bother
923 searching through PATH. */
924 if (absolute_program (hint))
925 return ((char *)NULL);
934 if (absolute_program (hint))
936 match = strncmp (val, hint, hint_len) == 0;
937 /* If we performed tilde expansion, restore the original
939 if (*hint_text == '~')
943 tl = strlen (hint_text);
944 l = vl - hint_len; /* # of chars added */
945 temp = xmalloc (l + 2 + tl);
946 strcpy (temp, hint_text);
947 strcpy (temp + tl, val + vl - l);
950 temp = savestring (val);
954 temp = strrchr (val, '/');
959 match = strncmp (temp, hint, hint_len) == 0;
961 temp = savestring (temp);
967 /* If we have found a match, and it is an executable file or a
968 directory name, return it. */
969 if (match && (executable_file (val) || is_directory (val)))
972 val = ""; /* So it won't be NULL. */
984 command_subst_completion_function (text, state)
988 static char **matches = (char **)NULL;
989 static char *orig_start, *filename_text = (char *)NULL;
990 static int cmd_index, start_len;
996 free (filename_text);
1000 else if (*text == '$' && text[1] == '(')
1002 start_len = text - orig_start;
1003 filename_text = savestring (text);
1006 matches = completion_matches (filename_text, command_word_completion_function);
1010 if (!matches || !matches[cmd_index])
1012 rl_filename_quoting_desired = 0; /* disable quoting */
1013 return ((char *)NULL);
1017 value = xmalloc (1 + start_len + strlen (matches[cmd_index]));
1020 value[0] = *orig_start;
1022 strncpy (value, orig_start, start_len);
1024 strcpy (value + start_len, matches[cmd_index]);
1031 /* Okay, now we write the entry_function for variable completion. */
1033 variable_completion_function (text, state)
1037 register SHELL_VAR *var = (SHELL_VAR *)NULL;
1038 static SHELL_VAR **varlist = (SHELL_VAR **)NULL;
1039 static int varlist_index;
1040 static char *varname = (char *)NULL;
1042 static int first_char, first_char_loc;
1050 first_char = text[0];
1052 if (first_char == '$')
1055 if (text[first_char_loc] == '{')
1058 varname = savestring (text + first_char_loc);
1060 namelen = strlen (varname);
1063 varlist = all_visible_variables ();
1067 while (varlist && varlist[varlist_index])
1069 var = varlist[varlist_index];
1071 /* Compare. You can't do better than Zayre. No text is also
1073 if (!*varname || (strncmp (varname, var->name, namelen) == 0))
1078 if (!varlist || !varlist[varlist_index])
1080 return ((char *)NULL);
1084 char *value = xmalloc (4 + strlen (var->name));
1088 value[0] = first_char;
1089 if (first_char_loc == 2)
1093 strcpy (&value[first_char_loc], var->name);
1094 if (first_char_loc == 2)
1095 strcat (value, "}");
1102 /* How about a completion function for hostnames? */
1104 hostname_completion_function (text, state)
1108 static char **list = (char **)NULL;
1109 static int list_index = 0;
1110 static int first_char, first_char_loc;
1112 /* If we don't have any state, make some. */
1117 list = (char **)NULL;
1122 if (first_char == '@')
1125 list = hostnames_matching (&text[first_char_loc]);
1129 if (list && list[list_index])
1133 t = xmalloc (2 + strlen (list[list_index]));
1135 strcpy (t + first_char_loc, list[list_index]);
1140 return ((char *)NULL);
1143 /* History and alias expand the line. */
1145 history_expand_line_internal (line)
1150 new_line = pre_process_line (line, 0, 0);
1155 /* Perform alias expansion on LINE and return the new line. */
1157 alias_expand_line_internal (line)
1162 alias_line = alias_expand (line);
1167 /* There was an error in expansion. Let the preprocessor print
1170 cleanup_expansion_error ()
1174 fprintf (rl_outstream, "\r\n");
1175 to_free = pre_process_line (rl_line_buffer, 1, 0);
1177 putc ('\r', rl_outstream);
1178 rl_forced_update_display ();
1181 /* If NEW_LINE differs from what is in the readline line buffer, add an
1182 undo record to get from the readline line buffer contents to the new
1183 line and make NEW_LINE the current readline line. */
1185 maybe_make_readline_line (new_line)
1188 if (strcmp (new_line, rl_line_buffer) != 0)
1192 rl_add_undo (UNDO_BEGIN, 0, 0, 0);
1193 rl_delete_text (0, rl_point);
1194 rl_point = rl_end = 0;
1195 rl_insert_text (new_line);
1196 rl_add_undo (UNDO_END, 0, 0, 0);
1200 /* Make NEW_LINE be the current readline line. This frees NEW_LINE. */
1202 set_up_new_line (new_line)
1205 int old_point = rl_point;
1206 int at_end = rl_point == rl_end;
1208 /* If the line was history and alias expanded, then make that
1209 be one thing to undo. */
1210 maybe_make_readline_line (new_line);
1213 /* Place rl_point where we think it should go. */
1216 else if (old_point < rl_end)
1218 rl_point = old_point;
1219 if (!whitespace (rl_line_buffer[rl_point]))
1220 rl_forward_word (1);
1224 /* History expand the line. */
1226 history_expand_line (ignore)
1231 new_line = history_expand_line_internal (rl_line_buffer);
1234 set_up_new_line (new_line);
1236 cleanup_expansion_error ();
1239 /* History and alias expand the line. */
1241 history_and_alias_expand_line (ignore)
1246 new_line = pre_process_line (rl_line_buffer, 0, 0);
1253 alias_line = alias_expand (new_line);
1255 new_line = alias_line;
1260 set_up_new_line (new_line);
1262 cleanup_expansion_error ();
1265 /* History and alias expand the line, then perform the shell word
1266 expansions by calling expand_string. */
1268 shell_expand_line (ignore)
1272 WORD_LIST *expanded_string;
1274 new_line = pre_process_line (rl_line_buffer, 0, 0);
1281 alias_line = alias_expand (new_line);
1283 new_line = alias_line;
1289 int old_point = rl_point;
1290 int at_end = rl_point == rl_end;
1292 /* If the line was history and alias expanded, then make that
1293 be one thing to undo. */
1294 maybe_make_readline_line (new_line);
1297 /* If there is variable expansion to perform, do that as a separate
1298 operation to be undone. */
1299 expanded_string = expand_string (rl_line_buffer, 0);
1300 if (expanded_string == 0)
1302 new_line = xmalloc (1);
1307 new_line = string_list (expanded_string);
1308 dispose_words (expanded_string);
1311 maybe_make_readline_line (new_line);
1314 /* Place rl_point where we think it should go. */
1317 else if (old_point < rl_end)
1319 rl_point = old_point;
1320 if (!whitespace (rl_line_buffer[rl_point]))
1321 rl_forward_word (1);
1325 cleanup_expansion_error ();
1328 /* If FIGNORE is set, then don't match files with the given suffixes when
1329 completing filenames. If only one of the possibilities has an acceptable
1330 suffix, delete the others, else just return and let the completer
1331 signal an error. It is called by the completer when real
1332 completions are done on filenames by the completer's internal
1333 function, not for completion lists (M-?) and not on "other"
1334 completion types, such as hostnames or commands. */
1336 static struct ignorevar fignore =
1346 _ignore_completion_names (names, name_func)
1348 Function *name_func;
1353 /* If there is only one completion, see if it is acceptable. If it is
1354 not, free it up. In any case, short-circuit and return. This is a
1355 special case because names[0] is not the prefix of the list of names
1356 if there is only one completion; it is the completion itself. */
1357 if (names[1] == (char *)0)
1359 if ((*name_func) (names[0]) == 0)
1362 names[0] = (char *)NULL;
1367 /* Allocate space for array to hold list of pointers to matching
1368 filenames. The pointers are copied back to NAMES when done. */
1369 for (nidx = 1; names[nidx]; nidx++)
1371 newnames = (char **)xmalloc ((nidx + 1) * (sizeof (char *)));
1373 newnames[0] = names[0];
1374 for (idx = nidx = 1; names[idx]; idx++)
1376 if ((*name_func) (names[idx]))
1377 newnames[nidx++] = names[idx];
1382 newnames[nidx] = (char *)NULL;
1384 /* If none are acceptable then let the completer handle it. */
1388 names[0] = (char *)NULL;
1393 /* If only one is acceptable, copy it to names[0] and return. */
1397 names[0] = newnames[1];
1398 names[1] = (char *)NULL;
1403 /* Copy the acceptable names back to NAMES, set the new array end,
1405 for (nidx = 1; newnames[nidx]; nidx++)
1406 names[nidx] = newnames[nidx];
1407 names[nidx] = (char *)NULL;
1412 name_is_acceptable (name)
1418 for (nlen = strlen (name), p = fignore.ignores; p->val; p++)
1420 if (nlen > p->len && p->len > 0 && STREQ (p->val, &name[nlen - p->len]))
1428 filename_completion_ignore (names)
1431 setup_ignore_patterns (&fignore);
1433 if (fignore.num_ignores == 0)
1436 _ignore_completion_names (names, name_is_acceptable);
1439 /* Return 1 if NAME is a directory. */
1441 test_for_directory (name)
1447 fn = bash_tilde_expand (name);
1448 if (stat (fn, &finfo) != 0)
1454 return (S_ISDIR (finfo.st_mode));
1457 /* Remove files from NAMES, leaving directories. */
1459 bash_ignore_filenames (names)
1462 _ignore_completion_names (names, test_for_directory);
1465 /* Handle symbolic link references and other directory name
1466 expansions while hacking completion. */
1468 bash_directory_completion_hook (dirname)
1471 char *local_dirname, *t;
1472 int return_value = 0;
1475 local_dirname = *dirname;
1476 if (strchr (local_dirname, '$') || strchr (local_dirname, '`'))
1478 wl = expand_string (local_dirname, 0);
1481 *dirname = string_list (wl);
1482 /* Tell the completer to replace the directory name only if we
1483 actually expanded something. */
1484 return_value = STREQ (local_dirname, *dirname) == 0;
1485 free (local_dirname);
1487 local_dirname = *dirname;
1491 free (local_dirname);
1492 *dirname = xmalloc (1);
1498 if (!no_symbolic_links && (local_dirname[0] != '.' || local_dirname[1]))
1500 char *temp1, *temp2;
1503 t = get_working_directory ("symlink-hook");
1504 temp1 = make_absolute (local_dirname, t);
1506 temp2 = canonicalize_pathname (temp1);
1507 /* If we can't canonicalize, bail. */
1513 len1 = strlen (temp1);
1514 if (temp1[len1 - 1] == '/')
1516 len2 = strlen (temp2);
1517 temp2 = xrealloc (temp2, len2 + 2);
1519 temp2[len2 + 1] = '\0';
1521 free (local_dirname);
1525 return (return_value);
1528 static char **history_completion_array = (char **)NULL;
1529 static int harry_size;
1530 static int harry_len;
1533 build_history_completion_array ()
1539 /* First, clear out the current dynamic history completion list. */
1542 for (i = 0; history_completion_array[i]; i++)
1543 free (history_completion_array[i]);
1545 free (history_completion_array);
1547 history_completion_array = (char **)NULL;
1552 /* Next, grovel each line of history, making each shell-sized token
1553 a separate entry in the history_completion_array. */
1554 hlist = history_list ();
1558 for (i = 0; hlist[i]; i++)
1560 /* Separate each token, and place into an array. */
1561 tokens = history_tokenize (hlist[i]->line);
1563 for (j = 0; tokens && tokens[j]; j++)
1565 if (harry_len + 2 > harry_size)
1568 history_completion_array = (char **) xrealloc
1569 (history_completion_array, harry_size * sizeof (char *));
1572 history_completion_array[harry_len++] = tokens[j];
1573 history_completion_array[harry_len] = (char *)NULL;
1578 /* Sort the complete list of tokens. */
1579 qsort (history_completion_array, harry_len, sizeof (char *), (Function *)qsort_string_compare);
1584 history_completion_generator (hint_text, state)
1588 static int local_index, len;
1591 /* If this is the first call to the generator, then initialize the
1592 list of strings to complete over. */
1596 build_history_completion_array ();
1598 len = strlen (text);
1601 while (history_completion_array && history_completion_array[local_index])
1603 if (strncmp (text, history_completion_array[local_index++], len) == 0)
1604 return (savestring (history_completion_array[local_index - 1]));
1606 return ((char *)NULL);
1610 dynamic_complete_history (count, key)
1613 Function *orig_func;
1614 CPPFunction *orig_attempt_func;
1616 orig_func = rl_completion_entry_function;
1617 orig_attempt_func = rl_attempted_completion_function;
1618 rl_completion_entry_function = (Function *)history_completion_generator;
1619 rl_attempted_completion_function = (CPPFunction *)NULL;
1621 if (rl_last_func == (Function *)dynamic_complete_history)
1622 rl_complete_internal ('?');
1624 rl_complete_internal (TAB);
1626 rl_completion_entry_function = orig_func;
1627 rl_attempted_completion_function = orig_attempt_func;
1630 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
1632 bash_complete_username (ignore, ignore2)
1633 int ignore, ignore2;
1635 bash_complete_username_internal (TAB);
1639 bash_possible_username_completions (ignore, ignore2)
1640 int ignore, ignore2;
1642 bash_complete_username_internal ('?');
1646 bash_complete_username_internal (what_to_do)
1649 bash_specific_completion
1650 (what_to_do, (Function *)username_completion_function);
1654 bash_complete_filename (ignore, ignore2)
1655 int ignore, ignore2;
1657 bash_complete_filename_internal (TAB);
1661 bash_possible_filename_completions (ignore, ignore2)
1662 int ignore, ignore2;
1664 bash_complete_filename_internal ('?');
1668 bash_complete_filename_internal (what_to_do)
1671 Function *orig_func, *orig_dir_func;
1672 CPPFunction *orig_attempt_func;
1673 char *orig_rl_completer_word_break_characters;
1675 orig_func = rl_completion_entry_function;
1676 orig_attempt_func = rl_attempted_completion_function;
1677 orig_dir_func = rl_directory_completion_hook;
1678 orig_rl_completer_word_break_characters = rl_completer_word_break_characters;
1679 rl_completion_entry_function = (Function *)filename_completion_function;
1680 rl_attempted_completion_function = (CPPFunction *)NULL;
1681 rl_directory_completion_hook = (Function *)NULL;
1682 rl_completer_word_break_characters = " \t\n\"\'";
1684 rl_complete_internal (what_to_do);
1686 rl_completion_entry_function = orig_func;
1687 rl_attempted_completion_function = orig_attempt_func;
1688 rl_directory_completion_hook = orig_dir_func;
1689 rl_completer_word_break_characters = orig_rl_completer_word_break_characters;
1693 bash_complete_hostname (ignore, ignore2)
1694 int ignore, ignore2;
1696 bash_complete_hostname_internal (TAB);
1700 bash_possible_hostname_completions (ignore, ignore2)
1701 int ignore, ignore2;
1703 bash_complete_hostname_internal ('?');
1707 bash_complete_variable (ignore, ignore2)
1708 int ignore, ignore2;
1710 bash_complete_variable_internal (TAB);
1714 bash_possible_variable_completions (ignore, ignore2)
1715 int ignore, ignore2;
1717 bash_complete_variable_internal ('?');
1721 bash_complete_command (ignore, ignore2)
1722 int ignore, ignore2;
1724 bash_complete_command_internal (TAB);
1728 bash_possible_command_completions (ignore, ignore2)
1729 int ignore, ignore2;
1731 bash_complete_command_internal ('?');
1735 bash_complete_hostname_internal (what_to_do)
1738 bash_specific_completion
1739 (what_to_do, (Function *)hostname_completion_function);
1743 bash_complete_variable_internal (what_to_do)
1746 bash_specific_completion
1747 (what_to_do, (Function *)variable_completion_function);
1751 bash_complete_command_internal (what_to_do)
1754 bash_specific_completion
1755 (what_to_do, (Function *)command_word_completion_function);
1759 glob_complete_word (text, state)
1763 static char **matches = (char **)NULL;
1771 matches = shell_glob_filename (text);
1772 if (GLOB_FAILED (matches))
1773 matches = (char **)NULL;
1777 ret = matches ? matches[ind] : (char *)NULL;
1783 bash_glob_completion_internal (what_to_do)
1786 bash_specific_completion (what_to_do, (Function *)glob_complete_word);
1790 bash_glob_expand_word (count, key)
1793 bash_glob_completion_internal ('*');
1797 bash_glob_list_expansions (count, key)
1800 bash_glob_completion_internal ('?');
1804 bash_specific_completion (what_to_do, generator)
1806 Function *generator;
1808 Function *orig_func;
1809 CPPFunction *orig_attempt_func;
1811 orig_func = rl_completion_entry_function;
1812 orig_attempt_func = rl_attempted_completion_function;
1813 rl_completion_entry_function = generator;
1814 rl_attempted_completion_function = (CPPFunction *)NULL;
1816 rl_complete_internal (what_to_do);
1818 rl_completion_entry_function = orig_func;
1819 rl_attempted_completion_function = orig_attempt_func;
1822 #endif /* SPECIFIC_COMPLETION_FUNCTIONS */
1824 /* Filename quoting for completion. */
1825 /* A function to strip quotes that are not protected by backquotes. It
1826 allows single quotes to appear within double quotes, and vice versa.
1827 It should be smarter. */
1829 bash_dequote_filename (text, quote_char)
1836 ret = xmalloc (l + 1);
1837 for (quoted = quote_char, p = text, r = ret; p && *p; p++)
1839 /* Allow backslash-quoted characters to pass through unscathed. */
1848 if (quoted && *p == quoted)
1854 if (quoted == 0 && (*p == '\'' || *p == '"'))
1865 /* Quote a filename using double quotes. */
1867 bash_quote_filename (s, rtype, qcp)
1872 char *rtext, *mtext, *ret;
1875 rtext = (char *)NULL;
1877 /* If RTYPE == MULT_MATCH, it means that there is
1878 more than one match. In this case, we do not add
1879 the closing quote or attempt to perform tilde
1880 expansion. If RTYPE == SINGLE_MATCH, we try
1881 to perform tilde expansion, because single and double
1882 quotes inhibit tilde expansion by the shell. */
1885 if (mtext[0] == '~' && rtype == SINGLE_MATCH)
1886 mtext = bash_tilde_expand (s);
1888 cs = completion_quoting_style;
1889 /* Might need to modify the default completion style based on *qcp,
1890 since it's set to any user-provided opening quote. */
1892 cs = COMPLETE_DQUOTE;
1893 else if (*qcp == '\'')
1894 cs = COMPLETE_SQUOTE;
1895 #if defined (BANG_HISTORY)
1896 else if (*qcp == '\0' && history_expansion && cs == COMPLETE_DQUOTE &&
1897 history_expansion_inhibited == 0 && strchr (mtext, '!'))
1898 cs = COMPLETE_BSQUOTE;
1903 case COMPLETE_DQUOTE:
1904 rtext = double_quote (mtext);
1906 case COMPLETE_SQUOTE:
1907 rtext = single_quote (mtext);
1909 case COMPLETE_BSQUOTE:
1910 rtext = backslash_quote (mtext);
1917 /* Leave the opening quote intact. The readline completion code takes
1918 care of avoiding doubled opening quotes. */
1919 rlen = strlen (rtext);
1920 ret = xmalloc (rlen + 1);
1921 strcpy (ret, rtext);
1923 /* If there are multiple matches, cut off the closing quote. */
1924 if (rtype == MULT_MATCH && cs != COMPLETE_BSQUOTE)
1925 ret[rlen - 1] = '\0';
1930 #endif /* READLINE */