Added gitignore entries needed to ignore derived objects generated from full build...
[bash.git] / bashline.c
blob52c6de6ad4a57e342bc238f057e9a517fef4731a
1 /* bashline.c -- Bash's interface to the readline library. */
3 /* Copyright (C) 1987-2011 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
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 Bash is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Bash. If not, see <http://www.gnu.org/licenses/>.
21 #include "config.h"
23 #if defined (READLINE)
25 #include "bashtypes.h"
26 #include "posixstat.h"
28 #if defined (HAVE_UNISTD_H)
29 # include <unistd.h>
30 #endif
32 #if defined (HAVE_GRP_H)
33 # include <grp.h>
34 #endif
36 #if defined (HAVE_NETDB_H)
37 # include <netdb.h>
38 #endif
40 #include <stdio.h>
41 #include "chartypes.h"
42 #include "bashansi.h"
43 #include "bashintl.h"
45 #include "shell.h"
46 #include "input.h"
47 #include "builtins.h"
48 #include "bashhist.h"
49 #include "bashline.h"
50 #include "execute_cmd.h"
51 #include "findcmd.h"
52 #include "pathexp.h"
53 #include "shmbutil.h"
55 #include "builtins/common.h"
57 #include <readline/rlconf.h>
58 #include <readline/readline.h>
59 #include <readline/history.h>
61 #include <glob/glob.h>
63 #if defined (ALIAS)
64 # include "alias.h"
65 #endif
67 #if defined (PROGRAMMABLE_COMPLETION)
68 # include "pcomplete.h"
69 #endif
71 /* These should agree with the defines for emacs_mode and vi_mode in
72 rldefs.h, even though that's not a public readline header file. */
73 #ifndef EMACS_EDITING_MODE
74 # define NO_EDITING_MODE -1
75 # define EMACS_EDITING_MODE 1
76 # define VI_EDITING_MODE 0
77 #endif
79 #define RL_BOOLEAN_VARIABLE_VALUE(s) ((s)[0] == 'o' && (s)[1] == 'n' && (s)[2] == '\0')
81 #if defined (BRACE_COMPLETION)
82 extern int bash_brace_completion __P((int, int));
83 #endif /* BRACE_COMPLETION */
85 /* To avoid including curses.h/term.h/termcap.h and that whole mess. */
86 extern int tputs __P((const char *string, int nlines, int (*outx)(int)));
88 /* Forward declarations */
90 /* Functions bound to keys in Readline for Bash users. */
91 static int shell_expand_line __P((int, int));
92 static int display_shell_version __P((int, int));
93 static int operate_and_get_next __P((int, int));
95 static int bash_ignore_filenames __P((char **));
96 static int bash_ignore_everything __P((char **));
98 #if defined (BANG_HISTORY)
99 static char *history_expand_line_internal __P((char *));
100 static int history_expand_line __P((int, int));
101 static int tcsh_magic_space __P((int, int));
102 #endif /* BANG_HISTORY */
103 #ifdef ALIAS
104 static int alias_expand_line __P((int, int));
105 #endif
106 #if defined (BANG_HISTORY) && defined (ALIAS)
107 static int history_and_alias_expand_line __P((int, int));
108 #endif
110 static int bash_forward_shellword __P((int, int));
111 static int bash_backward_shellword __P((int, int));
112 static int bash_kill_shellword __P((int, int));
113 static int bash_backward_kill_shellword __P((int, int));
115 /* Helper functions for Readline. */
116 static char *restore_tilde __P((char *, char *));
118 static char *bash_filename_rewrite_hook __P((char *, int));
119 static void bash_directory_expansion __P((char **));
120 static int bash_directory_completion_hook __P((char **));
121 static int filename_completion_ignore __P((char **));
122 static int bash_push_line __P((void));
124 static void cleanup_expansion_error __P((void));
125 static void maybe_make_readline_line __P((char *));
126 static void set_up_new_line __P((char *));
128 static int check_redir __P((int));
129 static char **attempt_shell_completion __P((const char *, int, int));
130 static char *variable_completion_function __P((const char *, int));
131 static char *hostname_completion_function __P((const char *, int));
132 static char *command_subst_completion_function __P((const char *, int));
134 static void build_history_completion_array __P((void));
135 static char *history_completion_generator __P((const char *, int));
136 static int dynamic_complete_history __P((int, int));
137 static int bash_dabbrev_expand __P((int, int));
139 static void initialize_hostname_list __P((void));
140 static void add_host_name __P((char *));
141 static void snarf_hosts_from_file __P((char *));
142 static char **hostnames_matching __P((char *));
144 static void _ignore_completion_names __P((char **, sh_ignore_func_t *));
145 static int name_is_acceptable __P((const char *));
146 static int test_for_directory __P((const char *));
147 static int return_zero __P((const char *));
149 static char *bash_dequote_filename __P((char *, int));
150 static char *quote_word_break_chars __P((char *));
151 static char *bash_quote_filename __P((char *, int, char *));
153 static int putx __P((int));
154 static int bash_execute_unix_command __P((int, int));
155 static void init_unix_command_map __P((void));
156 static int isolate_sequence __P((char *, int, int, int *));
158 static int set_saved_history __P((void));
160 #if defined (ALIAS)
161 static int posix_edit_macros __P((int, int));
162 #endif
164 #if defined (PROGRAMMABLE_COMPLETION)
165 static int find_cmd_start __P((int));
166 static int find_cmd_end __P((int));
167 static char *find_cmd_name __P((int));
168 static char *prog_complete_return __P((const char *, int));
170 static char **prog_complete_matches;
171 #endif
173 /* Variables used here but defined in other files. */
174 #if defined (BANG_HISTORY)
175 extern int hist_verify;
176 #endif
178 extern int current_command_line_count, saved_command_line_count;
179 extern int last_command_exit_value;
180 extern int array_needs_making;
181 extern int posixly_correct, no_symbolic_links;
182 extern char *current_prompt_string, *ps1_prompt;
183 extern STRING_INT_ALIST word_token_alist[];
184 extern sh_builtin_func_t *last_shell_builtin, *this_shell_builtin;
186 /* SPECIFIC_COMPLETION_FUNCTIONS specifies that we have individual
187 completion functions which indicate what type of completion should be
188 done (at or before point) that can be bound to key sequences with
189 the readline library. */
190 #define SPECIFIC_COMPLETION_FUNCTIONS
192 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
193 static int bash_specific_completion __P((int, rl_compentry_func_t *));
195 static int bash_complete_filename_internal __P((int));
196 static int bash_complete_username_internal __P((int));
197 static int bash_complete_hostname_internal __P((int));
198 static int bash_complete_variable_internal __P((int));
199 static int bash_complete_command_internal __P((int));
201 static int bash_complete_filename __P((int, int));
202 static int bash_possible_filename_completions __P((int, int));
203 static int bash_complete_username __P((int, int));
204 static int bash_possible_username_completions __P((int, int));
205 static int bash_complete_hostname __P((int, int));
206 static int bash_possible_hostname_completions __P((int, int));
207 static int bash_complete_variable __P((int, int));
208 static int bash_possible_variable_completions __P((int, int));
209 static int bash_complete_command __P((int, int));
210 static int bash_possible_command_completions __P((int, int));
212 static char *glob_complete_word __P((const char *, int));
213 static int bash_glob_completion_internal __P((int));
214 static int bash_glob_complete_word __P((int, int));
215 static int bash_glob_expand_word __P((int, int));
216 static int bash_glob_list_expansions __P((int, int));
218 #endif /* SPECIFIC_COMPLETION_FUNCTIONS */
220 static int edit_and_execute_command __P((int, int, int, char *));
221 #if defined (VI_MODE)
222 static int vi_edit_and_execute_command __P((int, int));
223 static int bash_vi_complete __P((int, int));
224 #endif
225 static int emacs_edit_and_execute_command __P((int, int));
227 /* Non-zero once initalize_readline () has been called. */
228 int bash_readline_initialized = 0;
230 /* If non-zero, we do hostname completion, breaking words at `@' and
231 trying to complete the stuff after the `@' from our own internal
232 host list. */
233 int perform_hostname_completion = 1;
235 /* If non-zero, we don't do command completion on an empty line. */
236 int no_empty_command_completion;
238 /* Set FORCE_FIGNORE if you want to honor FIGNORE even if it ignores the
239 only possible matches. Set to 0 if you want to match filenames if they
240 are the only possible matches, even if FIGNORE says to. */
241 int force_fignore = 1;
243 /* Perform spelling correction on directory names during word completion */
244 int dircomplete_spelling = 0;
246 static char *bash_completer_word_break_characters = " \t\n\"'@><=;|&(:";
247 static char *bash_nohostname_word_break_characters = " \t\n\"'><=;|&(:";
248 /* )) */
250 static rl_hook_func_t *old_rl_startup_hook = (rl_hook_func_t *)NULL;
252 static int dot_in_path = 0;
254 /* Set to non-zero when dabbrev-expand is running */
255 static int dabbrev_expand_active = 0;
257 /* What kind of quoting is performed by bash_quote_filename:
258 COMPLETE_DQUOTE = double-quoting the filename
259 COMPLETE_SQUOTE = single_quoting the filename
260 COMPLETE_BSQUOTE = backslash-quoting special chars in the filename
262 #define COMPLETE_DQUOTE 1
263 #define COMPLETE_SQUOTE 2
264 #define COMPLETE_BSQUOTE 3
265 static int completion_quoting_style = COMPLETE_BSQUOTE;
267 /* Flag values for the final argument to bash_default_completion */
268 #define DEFCOMP_CMDPOS 1
270 /* Change the readline VI-mode keymaps into or out of Posix.2 compliance.
271 Called when the shell is put into or out of `posix' mode. */
272 void
273 posix_readline_initialize (on_or_off)
274 int on_or_off;
276 if (on_or_off)
277 rl_variable_bind ("comment-begin", "#");
278 #if defined (VI_MODE)
279 rl_bind_key_in_map (CTRL ('I'), on_or_off ? rl_insert : rl_complete, vi_insertion_keymap);
280 #endif
283 void
284 reset_completer_word_break_chars ()
286 rl_completer_word_break_characters = perform_hostname_completion ? savestring (bash_completer_word_break_characters) : savestring (bash_nohostname_word_break_characters);
289 /* When this function returns, rl_completer_word_break_characters points to
290 dynamically allocated memory. */
292 enable_hostname_completion (on_or_off)
293 int on_or_off;
295 int old_value;
296 char *at, *nv, *nval;
298 old_value = perform_hostname_completion;
300 if (on_or_off)
302 perform_hostname_completion = 1;
303 rl_special_prefixes = "$@";
305 else
307 perform_hostname_completion = 0;
308 rl_special_prefixes = "$";
311 /* Now we need to figure out how to appropriately modify and assign
312 rl_completer_word_break_characters depending on whether we want
313 hostname completion on or off. */
315 /* If this is the first time this has been called
316 (bash_readline_initialized == 0), use the sames values as before, but
317 allocate new memory for rl_completer_word_break_characters. */
319 if (bash_readline_initialized == 0 &&
320 (rl_completer_word_break_characters == 0 ||
321 rl_completer_word_break_characters == rl_basic_word_break_characters))
323 if (on_or_off)
324 rl_completer_word_break_characters = savestring (bash_completer_word_break_characters);
325 else
326 rl_completer_word_break_characters = savestring (bash_nohostname_word_break_characters);
328 else
330 /* See if we have anything to do. */
331 at = strchr (rl_completer_word_break_characters, '@');
332 if ((at == 0 && on_or_off == 0) || (at != 0 && on_or_off != 0))
333 return old_value;
335 /* We have something to do. Do it. */
336 nval = (char *)xmalloc (strlen (rl_completer_word_break_characters) + 1 + on_or_off);
338 if (on_or_off == 0)
340 /* Turn it off -- just remove `@' from word break chars. We want
341 to remove all occurrences of `@' from the char list, so we loop
342 rather than just copy the rest of the list over AT. */
343 for (nv = nval, at = rl_completer_word_break_characters; *at; )
344 if (*at != '@')
345 *nv++ = *at++;
346 else
347 at++;
348 *nv = '\0';
350 else
352 nval[0] = '@';
353 strcpy (nval + 1, rl_completer_word_break_characters);
356 free (rl_completer_word_break_characters);
357 rl_completer_word_break_characters = nval;
360 return (old_value);
363 /* Called once from parse.y if we are going to use readline. */
364 void
365 initialize_readline ()
367 rl_command_func_t *func;
368 char kseq[2];
370 if (bash_readline_initialized)
371 return;
373 rl_terminal_name = get_string_value ("TERM");
374 rl_instream = stdin;
375 rl_outstream = stderr;
377 /* Allow conditional parsing of the ~/.inputrc file. */
378 rl_readline_name = "Bash";
380 /* Add bindable names before calling rl_initialize so they may be
381 referenced in the various inputrc files. */
382 rl_add_defun ("shell-expand-line", shell_expand_line, -1);
383 #ifdef BANG_HISTORY
384 rl_add_defun ("history-expand-line", history_expand_line, -1);
385 rl_add_defun ("magic-space", tcsh_magic_space, -1);
386 #endif
388 rl_add_defun ("shell-forward-word", bash_forward_shellword, -1);
389 rl_add_defun ("shell-backward-word", bash_backward_shellword, -1);
390 rl_add_defun ("shell-kill-word", bash_kill_shellword, -1);
391 rl_add_defun ("shell-backward-kill-word", bash_backward_kill_shellword, -1);
393 #ifdef ALIAS
394 rl_add_defun ("alias-expand-line", alias_expand_line, -1);
395 # ifdef BANG_HISTORY
396 rl_add_defun ("history-and-alias-expand-line", history_and_alias_expand_line, -1);
397 # endif
398 #endif
400 /* Backwards compatibility. */
401 rl_add_defun ("insert-last-argument", rl_yank_last_arg, -1);
403 rl_add_defun ("operate-and-get-next", operate_and_get_next, -1);
404 rl_add_defun ("display-shell-version", display_shell_version, -1);
405 rl_add_defun ("edit-and-execute-command", emacs_edit_and_execute_command, -1);
407 #if defined (BRACE_COMPLETION)
408 rl_add_defun ("complete-into-braces", bash_brace_completion, -1);
409 #endif
411 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
412 rl_add_defun ("complete-filename", bash_complete_filename, -1);
413 rl_add_defun ("possible-filename-completions", bash_possible_filename_completions, -1);
414 rl_add_defun ("complete-username", bash_complete_username, -1);
415 rl_add_defun ("possible-username-completions", bash_possible_username_completions, -1);
416 rl_add_defun ("complete-hostname", bash_complete_hostname, -1);
417 rl_add_defun ("possible-hostname-completions", bash_possible_hostname_completions, -1);
418 rl_add_defun ("complete-variable", bash_complete_variable, -1);
419 rl_add_defun ("possible-variable-completions", bash_possible_variable_completions, -1);
420 rl_add_defun ("complete-command", bash_complete_command, -1);
421 rl_add_defun ("possible-command-completions", bash_possible_command_completions, -1);
422 rl_add_defun ("glob-complete-word", bash_glob_complete_word, -1);
423 rl_add_defun ("glob-expand-word", bash_glob_expand_word, -1);
424 rl_add_defun ("glob-list-expansions", bash_glob_list_expansions, -1);
425 #endif
427 rl_add_defun ("dynamic-complete-history", dynamic_complete_history, -1);
428 rl_add_defun ("dabbrev-expand", bash_dabbrev_expand, -1);
430 /* Bind defaults before binding our custom shell keybindings. */
431 if (RL_ISSTATE(RL_STATE_INITIALIZED) == 0)
432 rl_initialize ();
434 /* Bind up our special shell functions. */
435 rl_bind_key_if_unbound_in_map (CTRL('E'), shell_expand_line, emacs_meta_keymap);
437 #ifdef BANG_HISTORY
438 rl_bind_key_if_unbound_in_map ('^', history_expand_line, emacs_meta_keymap);
439 #endif
441 rl_bind_key_if_unbound_in_map (CTRL ('O'), operate_and_get_next, emacs_standard_keymap);
442 rl_bind_key_if_unbound_in_map (CTRL ('V'), display_shell_version, emacs_ctlx_keymap);
444 /* In Bash, the user can switch editing modes with "set -o [vi emacs]",
445 so it is not necessary to allow C-M-j for context switching. Turn
446 off this occasionally confusing behaviour. */
447 kseq[0] = CTRL('J');
448 kseq[1] = '\0';
449 func = rl_function_of_keyseq (kseq, emacs_meta_keymap, (int *)NULL);
450 if (func == rl_vi_editing_mode)
451 rl_unbind_key_in_map (CTRL('J'), emacs_meta_keymap);
452 kseq[0] = CTRL('M');
453 func = rl_function_of_keyseq (kseq, emacs_meta_keymap, (int *)NULL);
454 if (func == rl_vi_editing_mode)
455 rl_unbind_key_in_map (CTRL('M'), emacs_meta_keymap);
456 #if defined (VI_MODE)
457 rl_unbind_key_in_map (CTRL('E'), vi_movement_keymap);
458 #endif
460 #if defined (BRACE_COMPLETION)
461 rl_bind_key_if_unbound_in_map ('{', bash_brace_completion, emacs_meta_keymap); /*}*/
462 #endif /* BRACE_COMPLETION */
464 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
465 rl_bind_key_if_unbound_in_map ('/', bash_complete_filename, emacs_meta_keymap);
466 rl_bind_key_if_unbound_in_map ('/', bash_possible_filename_completions, emacs_ctlx_keymap);
468 /* Have to jump through hoops here because there is a default binding for
469 M-~ (rl_tilde_expand) */
470 kseq[0] = '~';
471 kseq[1] = '\0';
472 func = rl_function_of_keyseq (kseq, emacs_meta_keymap, (int *)NULL);
473 if (func == 0 || func == rl_tilde_expand)
474 rl_bind_keyseq_in_map (kseq, bash_complete_username, emacs_meta_keymap);
476 rl_bind_key_if_unbound_in_map ('~', bash_possible_username_completions, emacs_ctlx_keymap);
478 rl_bind_key_if_unbound_in_map ('@', bash_complete_hostname, emacs_meta_keymap);
479 rl_bind_key_if_unbound_in_map ('@', bash_possible_hostname_completions, emacs_ctlx_keymap);
481 rl_bind_key_if_unbound_in_map ('$', bash_complete_variable, emacs_meta_keymap);
482 rl_bind_key_if_unbound_in_map ('$', bash_possible_variable_completions, emacs_ctlx_keymap);
484 rl_bind_key_if_unbound_in_map ('!', bash_complete_command, emacs_meta_keymap);
485 rl_bind_key_if_unbound_in_map ('!', bash_possible_command_completions, emacs_ctlx_keymap);
487 rl_bind_key_if_unbound_in_map ('g', bash_glob_complete_word, emacs_meta_keymap);
488 rl_bind_key_if_unbound_in_map ('*', bash_glob_expand_word, emacs_ctlx_keymap);
489 rl_bind_key_if_unbound_in_map ('g', bash_glob_list_expansions, emacs_ctlx_keymap);
491 #endif /* SPECIFIC_COMPLETION_FUNCTIONS */
493 kseq[0] = TAB;
494 kseq[1] = '\0';
495 func = rl_function_of_keyseq (kseq, emacs_meta_keymap, (int *)NULL);
496 if (func == 0 || func == rl_tab_insert)
497 rl_bind_key_in_map (TAB, dynamic_complete_history, emacs_meta_keymap);
499 /* Tell the completer that we want a crack first. */
500 rl_attempted_completion_function = attempt_shell_completion;
502 /* Tell the completer that we might want to follow symbolic links or
503 do other expansion on directory names. */
504 rl_directory_rewrite_hook = bash_directory_completion_hook;
506 rl_filename_rewrite_hook = bash_filename_rewrite_hook;
508 /* Tell the filename completer we want a chance to ignore some names. */
509 rl_ignore_some_completions_function = filename_completion_ignore;
511 /* Bind C-xC-e to invoke emacs and run result as commands. */
512 rl_bind_key_if_unbound_in_map (CTRL ('E'), emacs_edit_and_execute_command, emacs_ctlx_keymap);
513 #if defined (VI_MODE)
514 rl_bind_key_if_unbound_in_map ('v', vi_edit_and_execute_command, vi_movement_keymap);
515 # if defined (ALIAS)
516 rl_bind_key_if_unbound_in_map ('@', posix_edit_macros, vi_movement_keymap);
517 # endif
519 rl_bind_key_in_map ('\\', bash_vi_complete, vi_movement_keymap);
520 rl_bind_key_in_map ('*', bash_vi_complete, vi_movement_keymap);
521 rl_bind_key_in_map ('=', bash_vi_complete, vi_movement_keymap);
522 #endif
524 rl_completer_quote_characters = "'\"";
526 /* This sets rl_completer_word_break_characters and rl_special_prefixes
527 to the appropriate values, depending on whether or not hostname
528 completion is enabled. */
529 enable_hostname_completion (perform_hostname_completion);
531 /* characters that need to be quoted when appearing in filenames. */
532 rl_filename_quote_characters = " \t\n\\\"'@<>=;|&()#$`?*[!:{~"; /*}*/
534 rl_filename_quoting_function = bash_quote_filename;
535 rl_filename_dequoting_function = bash_dequote_filename;
536 rl_char_is_quoted_p = char_is_quoted;
538 #if 0
539 /* This is superfluous and makes it impossible to use tab completion in
540 vi mode even when explicitly binding it in ~/.inputrc. sv_strict_posix()
541 should already have called posix_readline_initialize() when
542 posixly_correct was set. */
543 if (posixly_correct)
544 posix_readline_initialize (1);
545 #endif
547 bash_readline_initialized = 1;
550 void
551 bashline_reinitialize ()
553 bash_readline_initialized = 0;
556 /* On Sun systems at least, rl_attempted_completion_function can end up
557 getting set to NULL, and rl_completion_entry_function set to do command
558 word completion if Bash is interrupted while trying to complete a command
559 word. This just resets all the completion functions to the right thing.
560 It's called from throw_to_top_level(). */
561 void
562 bashline_reset ()
564 tilde_initialize ();
565 rl_attempted_completion_function = attempt_shell_completion;
566 rl_completion_entry_function = NULL;
567 rl_directory_rewrite_hook = bash_directory_completion_hook;
568 rl_ignore_some_completions_function = filename_completion_ignore;
571 /* Contains the line to push into readline. */
572 static char *push_to_readline = (char *)NULL;
574 /* Push the contents of push_to_readline into the
575 readline buffer. */
576 static int
577 bash_push_line ()
579 if (push_to_readline)
581 rl_insert_text (push_to_readline);
582 free (push_to_readline);
583 push_to_readline = (char *)NULL;
584 rl_startup_hook = old_rl_startup_hook;
586 return 0;
589 /* Call this to set the initial text for the next line to read
590 from readline. */
592 bash_re_edit (line)
593 char *line;
595 FREE (push_to_readline);
597 push_to_readline = savestring (line);
598 old_rl_startup_hook = rl_startup_hook;
599 rl_startup_hook = bash_push_line;
601 return (0);
604 static int
605 display_shell_version (count, c)
606 int count, c;
608 rl_crlf ();
609 show_shell_version (0);
610 putc ('\r', rl_outstream);
611 fflush (rl_outstream);
612 rl_on_new_line ();
613 rl_redisplay ();
614 return 0;
617 /* **************************************************************** */
618 /* */
619 /* Readline Stuff */
620 /* */
621 /* **************************************************************** */
623 /* If the user requests hostname completion, then simply build a list
624 of hosts, and complete from that forever more, or at least until
625 HOSTFILE is unset. */
627 /* THIS SHOULD BE A STRINGLIST. */
628 /* The kept list of hostnames. */
629 static char **hostname_list = (char **)NULL;
631 /* The physical size of the above list. */
632 static int hostname_list_size;
634 /* The number of hostnames in the above list. */
635 static int hostname_list_length;
637 /* Whether or not HOSTNAME_LIST has been initialized. */
638 int hostname_list_initialized = 0;
640 /* Initialize the hostname completion table. */
641 static void
642 initialize_hostname_list ()
644 char *temp;
646 temp = get_string_value ("HOSTFILE");
647 if (temp == 0)
648 temp = get_string_value ("hostname_completion_file");
649 if (temp == 0)
650 temp = DEFAULT_HOSTS_FILE;
652 snarf_hosts_from_file (temp);
654 if (hostname_list)
655 hostname_list_initialized++;
658 /* Add NAME to the list of hosts. */
659 static void
660 add_host_name (name)
661 char *name;
663 if (hostname_list_length + 2 > hostname_list_size)
665 hostname_list_size = (hostname_list_size + 32) - (hostname_list_size % 32);
666 hostname_list = strvec_resize (hostname_list, hostname_list_size);
669 hostname_list[hostname_list_length++] = savestring (name);
670 hostname_list[hostname_list_length] = (char *)NULL;
673 #define cr_whitespace(c) ((c) == '\r' || (c) == '\n' || whitespace(c))
675 static void
676 snarf_hosts_from_file (filename)
677 char *filename;
679 FILE *file;
680 char *temp, buffer[256], name[256];
681 register int i, start;
683 file = fopen (filename, "r");
684 if (file == 0)
685 return;
687 while (temp = fgets (buffer, 255, file))
689 /* Skip to first character. */
690 for (i = 0; buffer[i] && cr_whitespace (buffer[i]); i++)
693 /* If comment or blank line, ignore. */
694 if (buffer[i] == '\0' || buffer[i] == '#')
695 continue;
697 /* If `preprocessor' directive, do the include. */
698 if (strncmp (buffer + i, "$include ", 9) == 0)
700 char *incfile, *t;
702 /* Find start of filename. */
703 for (incfile = buffer + i + 9; *incfile && whitespace (*incfile); incfile++)
706 /* Find end of filename. */
707 for (t = incfile; *t && cr_whitespace (*t) == 0; t++)
710 *t = '\0';
712 snarf_hosts_from_file (incfile);
713 continue;
716 /* Skip internet address if present. */
717 if (DIGIT (buffer[i]))
718 for (; buffer[i] && cr_whitespace (buffer[i]) == 0; i++);
720 /* Gobble up names. Each name is separated with whitespace. */
721 while (buffer[i])
723 for (; cr_whitespace (buffer[i]); i++)
725 if (buffer[i] == '\0' || buffer[i] == '#')
726 break;
728 /* Isolate the current word. */
729 for (start = i; buffer[i] && cr_whitespace (buffer[i]) == 0; i++)
731 if (i == start)
732 continue;
733 strncpy (name, buffer + start, i - start);
734 name[i - start] = '\0';
735 add_host_name (name);
738 fclose (file);
741 /* Return the hostname list. */
742 char **
743 get_hostname_list ()
745 if (hostname_list_initialized == 0)
746 initialize_hostname_list ();
747 return (hostname_list);
750 void
751 clear_hostname_list ()
753 register int i;
755 if (hostname_list_initialized == 0)
756 return;
757 for (i = 0; i < hostname_list_length; i++)
758 free (hostname_list[i]);
759 hostname_list_length = hostname_list_initialized = 0;
762 /* Return a NULL terminated list of hostnames which begin with TEXT.
763 Initialize the hostname list the first time if neccessary.
764 The array is malloc ()'ed, but not the individual strings. */
765 static char **
766 hostnames_matching (text)
767 char *text;
769 register int i, len, nmatch, rsize;
770 char **result;
772 if (hostname_list_initialized == 0)
773 initialize_hostname_list ();
775 if (hostname_list_initialized == 0)
776 return ((char **)NULL);
778 /* Special case. If TEXT consists of nothing, then the whole list is
779 what is desired. */
780 if (*text == '\0')
782 result = strvec_create (1 + hostname_list_length);
783 for (i = 0; i < hostname_list_length; i++)
784 result[i] = hostname_list[i];
785 result[i] = (char *)NULL;
786 return (result);
789 /* Scan until found, or failure. */
790 len = strlen (text);
791 result = (char **)NULL;
792 for (i = nmatch = rsize = 0; i < hostname_list_length; i++)
794 if (STREQN (text, hostname_list[i], len) == 0)
795 continue;
797 /* OK, it matches. Add it to the list. */
798 if (nmatch >= (rsize - 1))
800 rsize = (rsize + 16) - (rsize % 16);
801 result = strvec_resize (result, rsize);
804 result[nmatch++] = hostname_list[i];
806 if (nmatch)
807 result[nmatch] = (char *)NULL;
808 return (result);
811 /* The equivalent of the Korn shell C-o operate-and-get-next-history-line
812 editing command. */
813 static int saved_history_line_to_use = -1;
815 static int
816 set_saved_history ()
818 if (saved_history_line_to_use >= 0)
819 rl_get_previous_history (history_length - saved_history_line_to_use, 0);
820 saved_history_line_to_use = -1;
821 rl_startup_hook = old_rl_startup_hook;
822 return (0);
825 static int
826 operate_and_get_next (count, c)
827 int count, c;
829 int where;
831 /* Accept the current line. */
832 rl_newline (1, c);
834 /* Find the current line, and find the next line to use. */
835 where = where_history ();
837 if ((history_is_stifled () && (history_length >= history_max_entries)) ||
838 (where >= history_length - 1))
839 saved_history_line_to_use = where;
840 else
841 saved_history_line_to_use = where + 1;
843 old_rl_startup_hook = rl_startup_hook;
844 rl_startup_hook = set_saved_history;
846 return 0;
849 /* This vi mode command causes VI_EDIT_COMMAND to be run on the current
850 command being entered (if no explicit argument is given), otherwise on
851 a command from the history file. */
853 #define VI_EDIT_COMMAND "fc -e \"${VISUAL:-${EDITOR:-vi}}\""
854 #define EMACS_EDIT_COMMAND "fc -e \"${VISUAL:-${EDITOR:-emacs}}\""
855 #define POSIX_VI_EDIT_COMMAND "fc -e vi"
857 static int
858 edit_and_execute_command (count, c, editing_mode, edit_command)
859 int count, c, editing_mode;
860 char *edit_command;
862 char *command, *metaval;
863 int r, rrs, metaflag;
864 sh_parser_state_t ps;
866 rrs = rl_readline_state;
867 saved_command_line_count = current_command_line_count;
869 /* Accept the current line. */
870 rl_newline (1, c);
872 if (rl_explicit_arg)
874 command = (char *)xmalloc (strlen (edit_command) + 8);
875 sprintf (command, "%s %d", edit_command, count);
877 else
879 /* Take the command we were just editing, add it to the history file,
880 then call fc to operate on it. We have to add a dummy command to
881 the end of the history because fc ignores the last command (assumes
882 it's supposed to deal with the command before the `fc'). */
883 /* This breaks down when using command-oriented history and are not
884 finished with the command, so we should not ignore the last command */
885 using_history ();
886 bash_add_history (rl_line_buffer);
887 bash_add_history ("");
888 history_lines_this_session++;
889 using_history ();
890 command = savestring (edit_command);
893 metaval = rl_variable_value ("input-meta");
894 metaflag = RL_BOOLEAN_VARIABLE_VALUE (metaval);
896 /* Now, POSIX.1-2001 and SUSv3 say that the commands executed from the
897 temporary file should be placed into the history. We don't do that
898 yet. */
899 if (rl_deprep_term_function)
900 (*rl_deprep_term_function) ();
901 save_parser_state (&ps);
902 r = parse_and_execute (command, (editing_mode == VI_EDITING_MODE) ? "v" : "C-xC-e", SEVAL_NOHIST);
903 restore_parser_state (&ps);
904 if (rl_prep_term_function)
905 (*rl_prep_term_function) (metaflag);
907 current_command_line_count = saved_command_line_count;
909 /* Now erase the contents of the current line and undo the effects of the
910 rl_accept_line() above. We don't even want to make the text we just
911 executed available for undoing. */
912 rl_line_buffer[0] = '\0'; /* XXX */
913 rl_point = rl_end = 0;
914 rl_done = 0;
915 rl_readline_state = rrs;
917 rl_forced_update_display ();
919 return r;
922 #if defined (VI_MODE)
923 static int
924 vi_edit_and_execute_command (count, c)
925 int count, c;
927 if (posixly_correct)
928 return (edit_and_execute_command (count, c, VI_EDITING_MODE, POSIX_VI_EDIT_COMMAND));
929 else
930 return (edit_and_execute_command (count, c, VI_EDITING_MODE, VI_EDIT_COMMAND));
932 #endif /* VI_MODE */
934 static int
935 emacs_edit_and_execute_command (count, c)
936 int count, c;
938 return (edit_and_execute_command (count, c, EMACS_EDITING_MODE, EMACS_EDIT_COMMAND));
941 #if defined (ALIAS)
942 static int
943 posix_edit_macros (count, key)
944 int count, key;
946 int c;
947 char alias_name[3], *alias_value, *macro;
949 c = rl_read_key ();
950 alias_name[0] = '_';
951 alias_name[1] = c;
952 alias_name[2] = '\0';
954 alias_value = get_alias_value (alias_name);
955 if (alias_value && *alias_value)
957 macro = savestring (alias_value);
958 rl_push_macro_input (macro);
960 return 0;
962 #endif
964 /* Bindable commands that move `shell-words': that is, sequences of
965 non-unquoted-metacharacters. */
967 #define WORDDELIM(c) (shellmeta(c) || shellblank(c))
969 static int
970 bash_forward_shellword (count, key)
971 int count, key;
973 size_t slen;
974 int sindex, c, p;
975 DECLARE_MBSTATE;
977 if (count < 0)
978 return (bash_backward_shellword (-count, key));
980 /* The tricky part of this is deciding whether or not the first character
981 we're on is an unquoted metacharacter. Not completely handled yet. */
982 /* XXX - need to test this stuff with backslash-escaped shell
983 metacharacters and unclosed single- and double-quoted strings. */
985 p = rl_point;
986 slen = rl_end;
988 while (count)
990 if (p == rl_end)
992 rl_point = rl_end;
993 return 0;
996 /* Are we in a quoted string? If we are, move to the end of the quoted
997 string and continue the outer loop. We only want quoted strings, not
998 backslash-escaped characters, but char_is_quoted doesn't
999 differentiate. */
1000 if (char_is_quoted (rl_line_buffer, p) && p > 0 && rl_line_buffer[p-1] != '\\')
1003 ADVANCE_CHAR (rl_line_buffer, slen, p);
1004 while (p < rl_end && char_is_quoted (rl_line_buffer, p));
1005 count--;
1006 continue;
1009 /* Rest of code assumes we are not in a quoted string. */
1010 /* Move forward until we hit a non-metacharacter. */
1011 while (p < rl_end && (c = rl_line_buffer[p]) && WORDDELIM (c))
1013 switch (c)
1015 default:
1016 ADVANCE_CHAR (rl_line_buffer, slen, p);
1017 continue; /* straight back to loop, don't increment p */
1018 case '\\':
1019 if (p < rl_end && rl_line_buffer[p])
1020 ADVANCE_CHAR (rl_line_buffer, slen, p);
1021 break;
1022 case '\'':
1023 p = skip_to_delim (rl_line_buffer, ++p, "'", SD_NOJMP);
1024 break;
1025 case '"':
1026 p = skip_to_delim (rl_line_buffer, ++p, "\"", SD_NOJMP);
1027 break;
1030 if (p < rl_end)
1031 p++;
1034 if (rl_line_buffer[p] == 0 || p == rl_end)
1036 rl_point = rl_end;
1037 rl_ding ();
1038 return 0;
1041 /* Now move forward until we hit a non-quoted metacharacter or EOL */
1042 while (p < rl_end && (c = rl_line_buffer[p]) && WORDDELIM (c) == 0)
1044 switch (c)
1046 default:
1047 ADVANCE_CHAR (rl_line_buffer, slen, p);
1048 continue; /* straight back to loop, don't increment p */
1049 case '\\':
1050 if (p < rl_end && rl_line_buffer[p])
1051 ADVANCE_CHAR (rl_line_buffer, slen, p);
1052 break;
1053 case '\'':
1054 p = skip_to_delim (rl_line_buffer, ++p, "'", SD_NOJMP);
1055 break;
1056 case '"':
1057 p = skip_to_delim (rl_line_buffer, ++p, "\"", SD_NOJMP);
1058 break;
1061 if (p < rl_end)
1062 p++;
1065 if (p == rl_end || rl_line_buffer[p] == 0)
1067 rl_point = rl_end;
1068 return (0);
1071 count--;
1074 rl_point = p;
1075 return (0);
1078 static int
1079 bash_backward_shellword (count, key)
1080 int count, key;
1082 size_t slen;
1083 int sindex, c, p;
1084 DECLARE_MBSTATE;
1086 if (count < 0)
1087 return (bash_forward_shellword (-count, key));
1089 p = rl_point;
1090 slen = rl_end;
1092 while (count)
1094 if (p == 0)
1096 rl_point = 0;
1097 return 0;
1100 /* Move backward until we hit a non-metacharacter. */
1101 while (p > 0)
1103 c = rl_line_buffer[p];
1104 if (WORDDELIM (c) && char_is_quoted (rl_line_buffer, p) == 0)
1105 BACKUP_CHAR (rl_line_buffer, slen, p);
1106 break;
1109 if (p == 0)
1111 rl_point = 0;
1112 return 0;
1115 /* Now move backward until we hit a metacharacter or BOL. */
1116 while (p > 0)
1118 c = rl_line_buffer[p];
1119 if (WORDDELIM (c) && char_is_quoted (rl_line_buffer, p) == 0)
1120 break;
1121 BACKUP_CHAR (rl_line_buffer, slen, p);
1124 count--;
1127 rl_point = p;
1128 return 0;
1131 static int
1132 bash_kill_shellword (count, key)
1133 int count, key;
1135 int p;
1137 if (count < 0)
1138 return (bash_backward_kill_shellword (-count, key));
1140 p = rl_point;
1141 bash_forward_shellword (count, key);
1143 if (rl_point != p)
1144 rl_kill_text (p, rl_point);
1146 rl_point = p;
1147 if (rl_editing_mode == 1) /* 1 == emacs_mode */
1148 rl_mark = rl_point;
1150 return 0;
1153 static int
1154 bash_backward_kill_shellword (count, key)
1155 int count, key;
1157 int p;
1159 if (count < 0)
1160 return (bash_kill_shellword (-count, key));
1162 p = rl_point;
1163 bash_backward_shellword (count, key);
1165 if (rl_point != p)
1166 rl_kill_text (p, rl_point);
1168 if (rl_editing_mode == 1) /* 1 == emacs_mode */
1169 rl_mark = rl_point;
1171 return 0;
1175 /* **************************************************************** */
1176 /* */
1177 /* How To Do Shell Completion */
1178 /* */
1179 /* **************************************************************** */
1181 #define COMMAND_SEPARATORS ";|&{(`"
1182 /* )} */
1184 static int
1185 check_redir (ti)
1186 int ti;
1188 register int this_char, prev_char;
1190 /* Handle the two character tokens `>&', `<&', and `>|'.
1191 We are not in a command position after one of these. */
1192 this_char = rl_line_buffer[ti];
1193 prev_char = rl_line_buffer[ti - 1];
1195 if ((this_char == '&' && (prev_char == '<' || prev_char == '>')) ||
1196 (this_char == '|' && prev_char == '>'))
1197 return (1);
1198 else if ((this_char == '{' && prev_char == '$') || /* } */
1199 (char_is_quoted (rl_line_buffer, ti)))
1200 return (1);
1201 return (0);
1204 #if defined (PROGRAMMABLE_COMPLETION)
1206 * XXX - because of the <= start test, and setting os = s+1, this can
1207 * potentially return os > start. This is probably not what we want to
1208 * happen, but fix later after 2.05a-release.
1210 static int
1211 find_cmd_start (start)
1212 int start;
1214 register int s, os;
1216 os = 0;
1217 while (((s = skip_to_delim (rl_line_buffer, os, COMMAND_SEPARATORS, SD_NOJMP|SD_NOSKIPCMD)) <= start) &&
1218 rl_line_buffer[s])
1219 os = s+1;
1220 return os;
1223 static int
1224 find_cmd_end (end)
1225 int end;
1227 register int e;
1229 e = skip_to_delim (rl_line_buffer, end, COMMAND_SEPARATORS, SD_NOJMP);
1230 return e;
1233 static char *
1234 find_cmd_name (start)
1235 int start;
1237 char *name;
1238 register int s, e;
1240 for (s = start; whitespace (rl_line_buffer[s]); s++)
1243 /* skip until a shell break character */
1244 e = skip_to_delim (rl_line_buffer, s, "()<>;&| \t\n", SD_NOJMP);
1246 name = substring (rl_line_buffer, s, e);
1248 return (name);
1251 static char *
1252 prog_complete_return (text, matchnum)
1253 const char *text;
1254 int matchnum;
1256 static int ind;
1258 if (matchnum == 0)
1259 ind = 0;
1261 if (prog_complete_matches == 0 || prog_complete_matches[ind] == 0)
1262 return (char *)NULL;
1263 return (prog_complete_matches[ind++]);
1266 #endif /* PROGRAMMABLE_COMPLETION */
1268 /* Do some completion on TEXT. The indices of TEXT in RL_LINE_BUFFER are
1269 at START and END. Return an array of matches, or NULL if none. */
1270 static char **
1271 attempt_shell_completion (text, start, end)
1272 const char *text;
1273 int start, end;
1275 int in_command_position, ti, saveti, qc, dflags;
1276 char **matches, *command_separator_chars;
1278 command_separator_chars = COMMAND_SEPARATORS;
1279 matches = (char **)NULL;
1280 rl_ignore_some_completions_function = filename_completion_ignore;
1282 /* Determine if this could be a command word. It is if it appears at
1283 the start of the line (ignoring preceding whitespace), or if it
1284 appears after a character that separates commands. It cannot be a
1285 command word if we aren't at the top-level prompt. */
1286 ti = start - 1;
1287 saveti = qc = -1;
1289 while ((ti > -1) && (whitespace (rl_line_buffer[ti])))
1290 ti--;
1292 #if 1
1293 /* If this is an open quote, maybe we're trying to complete a quoted
1294 command name. */
1295 if (ti >= 0 && (rl_line_buffer[ti] == '"' || rl_line_buffer[ti] == '\''))
1297 qc = rl_line_buffer[ti];
1298 saveti = ti--;
1299 while (ti > -1 && (whitespace (rl_line_buffer[ti])))
1300 ti--;
1302 #endif
1304 in_command_position = 0;
1305 if (ti < 0)
1307 /* Only do command completion at the start of a line when we
1308 are prompting at the top level. */
1309 if (current_prompt_string == ps1_prompt)
1310 in_command_position++;
1312 else if (member (rl_line_buffer[ti], command_separator_chars))
1314 in_command_position++;
1316 if (check_redir (ti) == 1)
1317 in_command_position = 0;
1319 else
1321 /* This still could be in command position. It is possible
1322 that all of the previous words on the line are variable
1323 assignments. */
1326 /* Check that we haven't incorrectly flagged a closed command substitution
1327 as indicating we're in a command position. */
1328 if (in_command_position && ti >= 0 && rl_line_buffer[ti] == '`' &&
1329 *text != '`' && unclosed_pair (rl_line_buffer, end, "`") == 0)
1330 in_command_position = 0;
1332 /* Special handling for command substitution. If *TEXT is a backquote,
1333 it can be the start or end of an old-style command substitution, or
1334 unmatched. If it's unmatched, both calls to unclosed_pair will
1335 succeed. Don't bother if readline found a single quote and we are
1336 completing on the substring. */
1337 if (*text == '`' && rl_completion_quote_character != '\'' &&
1338 (in_command_position || (unclosed_pair (rl_line_buffer, start, "`") &&
1339 unclosed_pair (rl_line_buffer, end, "`"))))
1340 matches = rl_completion_matches (text, command_subst_completion_function);
1342 #if defined (PROGRAMMABLE_COMPLETION)
1343 /* Attempt programmable completion. */
1344 if (matches == 0 && (in_command_position == 0 || text[0] == '\0') &&
1345 prog_completion_enabled && (progcomp_size () > 0) &&
1346 current_prompt_string == ps1_prompt)
1348 int s, e, foundcs;
1349 char *n;
1351 /* XXX - don't free the members */
1352 if (prog_complete_matches)
1353 free (prog_complete_matches);
1354 prog_complete_matches = (char **)NULL;
1356 s = find_cmd_start (start);
1357 e = find_cmd_end (end);
1358 n = find_cmd_name (s);
1359 if (e == 0 && e == s && text[0] == '\0')
1360 prog_complete_matches = programmable_completions ("_EmptycmD_", text, s, e, &foundcs);
1361 else if (e > s && assignment (n, 0) == 0)
1362 prog_complete_matches = programmable_completions (n, text, s, e, &foundcs);
1363 else
1364 foundcs = 0;
1365 FREE (n);
1366 /* XXX - if we found a COMPSPEC for the command, just return whatever
1367 the programmable completion code returns, and disable the default
1368 filename completion that readline will do unless the COPT_DEFAULT
1369 option has been set with the `-o default' option to complete or
1370 compopt. */
1371 if (foundcs)
1373 pcomp_set_readline_variables (foundcs, 1);
1374 /* Turn what the programmable completion code returns into what
1375 readline wants. I should have made compute_lcd_of_matches
1376 external... */
1377 matches = rl_completion_matches (text, prog_complete_return);
1378 if ((foundcs & COPT_DEFAULT) == 0)
1379 rl_attempted_completion_over = 1; /* no default */
1380 if (matches || ((foundcs & COPT_BASHDEFAULT) == 0))
1381 return (matches);
1384 #endif
1386 if (matches == 0)
1388 dflags = 0;
1389 if (in_command_position)
1390 dflags |= DEFCOMP_CMDPOS;
1391 matches = bash_default_completion (text, start, end, qc, dflags);
1394 return matches;
1397 char **
1398 bash_default_completion (text, start, end, qc, compflags)
1399 const char *text;
1400 int start, end, qc, compflags;
1402 char **matches;
1404 matches = (char **)NULL;
1406 /* New posix-style command substitution or variable name? */
1407 if (!matches && *text == '$')
1409 if (qc != '\'' && text[1] == '(') /* ) */
1410 matches = rl_completion_matches (text, command_subst_completion_function);
1411 else
1412 matches = rl_completion_matches (text, variable_completion_function);
1415 /* If the word starts in `~', and there is no slash in the word, then
1416 try completing this word as a username. */
1417 if (matches == 0 && *text == '~' && mbschr (text, '/') == 0)
1418 matches = rl_completion_matches (text, rl_username_completion_function);
1420 /* Another one. Why not? If the word starts in '@', then look through
1421 the world of known hostnames for completion first. */
1422 if (matches == 0 && perform_hostname_completion && *text == '@')
1423 matches = rl_completion_matches (text, hostname_completion_function);
1425 /* And last, (but not least) if this word is in a command position, then
1426 complete over possible command names, including aliases, functions,
1427 and command names. */
1428 if (matches == 0 && (compflags & DEFCOMP_CMDPOS))
1430 /* If END == START and text[0] == 0, we are trying to complete an empty
1431 command word. */
1432 if (no_empty_command_completion && end == start && text[0] == '\0')
1434 matches = (char **)NULL;
1435 rl_ignore_some_completions_function = bash_ignore_everything;
1437 else
1439 #define CMD_IS_DIR(x) (absolute_pathname(x) == 0 && absolute_program(x) == 0 && *(x) != '~' && test_for_directory (x))
1441 dot_in_path = 0;
1442 matches = rl_completion_matches (text, command_word_completion_function);
1444 /* If we are attempting command completion and nothing matches, we
1445 do not want readline to perform filename completion for us. We
1446 still want to be able to complete partial pathnames, so set the
1447 completion ignore function to something which will remove
1448 filenames and leave directories in the match list. */
1449 if (matches == (char **)NULL)
1450 rl_ignore_some_completions_function = bash_ignore_filenames;
1451 else if (matches[1] == 0 && CMD_IS_DIR(matches[0]) && dot_in_path == 0)
1452 /* If we found a single match, without looking in the current
1453 directory (because it's not in $PATH), but the found name is
1454 also a command in the current directory, suppress appending any
1455 terminating character, since it's ambiguous. */
1457 rl_completion_suppress_append = 1;
1458 rl_filename_completion_desired = 0;
1460 else if (matches[0] && matches[1] && STREQ (matches[0], matches[1]) && CMD_IS_DIR (matches[0]))
1461 /* There are multiple instances of the same match (duplicate
1462 completions haven't yet been removed). In this case, all of
1463 the matches will be the same, and the duplicate removal code
1464 will distill them all down to one. We turn on
1465 rl_completion_suppress_append for the same reason as above.
1466 Remember: we only care if there's eventually a single unique
1467 completion. If there are multiple completions this won't
1468 make a difference and the problem won't occur. */
1470 rl_completion_suppress_append = 1;
1471 rl_filename_completion_desired = 0;
1476 /* This could be a globbing pattern, so try to expand it using pathname
1477 expansion. */
1478 if (!matches && glob_pattern_p (text))
1480 matches = rl_completion_matches (text, glob_complete_word);
1481 /* A glob expression that matches more than one filename is problematic.
1482 If we match more than one filename, punt. */
1483 if (matches && matches[1] && rl_completion_type == TAB)
1485 strvec_dispose (matches);
1486 matches = (char **)0;
1490 return (matches);
1493 /* This is the function to call when the word to complete is in a position
1494 where a command word can be found. It grovels $PATH, looking for commands
1495 that match. It also scans aliases, function names, and the shell_builtin
1496 table. */
1497 char *
1498 command_word_completion_function (hint_text, state)
1499 const char *hint_text;
1500 int state;
1502 static char *hint = (char *)NULL;
1503 static char *path = (char *)NULL;
1504 static char *val = (char *)NULL;
1505 static char *filename_hint = (char *)NULL;
1506 static char *dequoted_hint = (char *)NULL;
1507 static char *directory_part = (char *)NULL;
1508 static char **glob_matches = (char **)NULL;
1509 static int path_index, hint_len, dequoted_len, istate, igncase;
1510 static int mapping_over, local_index, searching_path, hint_is_dir;
1511 static int old_glob_ignore_case, globpat;
1512 static SHELL_VAR **varlist = (SHELL_VAR **)NULL;
1513 #if defined (ALIAS)
1514 static alias_t **alias_list = (alias_t **)NULL;
1515 #endif /* ALIAS */
1516 char *temp;
1518 /* We have to map over the possibilities for command words. If we have
1519 no state, then make one just for that purpose. */
1520 if (state == 0)
1522 if (dequoted_hint && dequoted_hint != hint)
1523 free (dequoted_hint);
1524 if (hint)
1525 free (hint);
1527 mapping_over = searching_path = 0;
1528 hint_is_dir = CMD_IS_DIR (hint_text);
1529 val = (char *)NULL;
1531 temp = rl_variable_value ("completion-ignore-case");
1532 igncase = RL_BOOLEAN_VARIABLE_VALUE (temp);
1534 if (glob_matches)
1536 free (glob_matches);
1537 glob_matches = (char **)NULL;
1540 globpat = glob_pattern_p (hint_text);
1542 /* If this is an absolute program name, do not check it against
1543 aliases, reserved words, functions or builtins. We must check
1544 whether or not it is unique, and, if so, whether that filename
1545 is executable. */
1546 if (globpat || absolute_program (hint_text))
1548 /* Perform tilde expansion on what's passed, so we don't end up
1549 passing filenames with tildes directly to stat(). */
1550 if (*hint_text == '~')
1552 hint = bash_tilde_expand (hint_text, 0);
1553 directory_part = savestring (hint_text);
1554 temp = strchr (directory_part, '/');
1555 if (temp)
1556 *temp = 0;
1557 else
1559 free (directory_part);
1560 directory_part = (char *)NULL;
1563 else
1564 hint = savestring (hint_text);
1566 dequoted_hint = hint;
1567 /* If readline's completer found a quote character somewhere, but
1568 didn't set the quote character, there must have been a quote
1569 character embedded in the filename. It can't be at the start of
1570 the filename, so we need to dequote the filename before we look
1571 in the file system for it. */
1572 if (rl_completion_found_quote && rl_completion_quote_character == 0)
1574 dequoted_hint = bash_dequote_filename (hint, 0);
1575 free (hint);
1576 hint = dequoted_hint;
1578 dequoted_len = hint_len = strlen (hint);
1580 if (filename_hint)
1581 free (filename_hint);
1583 filename_hint = savestring (hint);
1585 istate = 0;
1587 if (globpat)
1589 mapping_over = 5;
1590 goto globword;
1592 else
1594 mapping_over = 4;
1595 goto inner;
1599 dequoted_hint = hint = savestring (hint_text);
1600 dequoted_len = hint_len = strlen (hint);
1602 if (rl_completion_found_quote && rl_completion_quote_character == 0)
1604 dequoted_hint = bash_dequote_filename (hint, 0);
1605 dequoted_len = strlen (dequoted_hint);
1608 path = get_string_value ("PATH");
1609 path_index = dot_in_path = 0;
1611 /* Initialize the variables for each type of command word. */
1612 local_index = 0;
1614 if (varlist)
1615 free (varlist);
1617 varlist = all_visible_functions ();
1619 #if defined (ALIAS)
1620 if (alias_list)
1621 free (alias_list);
1623 alias_list = all_aliases ();
1624 #endif /* ALIAS */
1627 /* mapping_over says what we are currently hacking. Note that every case
1628 in this list must fall through when there are no more possibilities. */
1630 switch (mapping_over)
1632 case 0: /* Aliases come first. */
1633 #if defined (ALIAS)
1634 while (alias_list && alias_list[local_index])
1636 register char *alias;
1638 alias = alias_list[local_index++]->name;
1640 if (STREQN (alias, hint, hint_len))
1641 return (savestring (alias));
1643 #endif /* ALIAS */
1644 local_index = 0;
1645 mapping_over++;
1647 case 1: /* Then shell reserved words. */
1649 while (word_token_alist[local_index].word)
1651 register char *reserved_word;
1653 reserved_word = word_token_alist[local_index++].word;
1655 if (STREQN (reserved_word, hint, hint_len))
1656 return (savestring (reserved_word));
1658 local_index = 0;
1659 mapping_over++;
1662 case 2: /* Then function names. */
1663 while (varlist && varlist[local_index])
1665 register char *varname;
1667 varname = varlist[local_index++]->name;
1669 if (STREQN (varname, hint, hint_len))
1670 return (savestring (varname));
1672 local_index = 0;
1673 mapping_over++;
1675 case 3: /* Then shell builtins. */
1676 for (; local_index < num_shell_builtins; local_index++)
1678 /* Ignore it if it doesn't have a function pointer or if it
1679 is not currently enabled. */
1680 if (!shell_builtins[local_index].function ||
1681 (shell_builtins[local_index].flags & BUILTIN_ENABLED) == 0)
1682 continue;
1684 if (STREQN (shell_builtins[local_index].name, hint, hint_len))
1686 int i = local_index++;
1688 return (savestring (shell_builtins[i].name));
1691 local_index = 0;
1692 mapping_over++;
1695 globword:
1696 /* Limited support for completing command words with globbing chars. Only
1697 a single match (multiple matches that end up reducing the number of
1698 characters in the common prefix are bad) will ever be returned on
1699 regular completion. */
1700 if (globpat)
1702 if (state == 0)
1704 glob_ignore_case = igncase;
1705 glob_matches = shell_glob_filename (hint);
1706 glob_ignore_case = old_glob_ignore_case;
1708 if (GLOB_FAILED (glob_matches) || glob_matches == 0)
1710 glob_matches = (char **)NULL;
1711 return ((char *)NULL);
1714 local_index = 0;
1716 if (glob_matches[1] && rl_completion_type == TAB) /* multiple matches are bad */
1717 return ((char *)NULL);
1720 while (val = glob_matches[local_index++])
1722 if (executable_or_directory (val))
1724 if (*hint_text == '~')
1726 temp = restore_tilde (val, directory_part);
1727 free (val);
1728 val = temp;
1730 return (val);
1732 free (val);
1735 glob_ignore_case = old_glob_ignore_case;
1736 return ((char *)NULL);
1739 /* If the text passed is a directory in the current directory, return it
1740 as a possible match. Executables in directories in the current
1741 directory can be specified using relative pathnames and successfully
1742 executed even when `.' is not in $PATH. */
1743 if (hint_is_dir)
1745 hint_is_dir = 0; /* only return the hint text once */
1746 return (savestring (hint_text));
1749 /* Repeatedly call filename_completion_function while we have
1750 members of PATH left. Question: should we stat each file?
1751 Answer: we call executable_file () on each file. */
1752 outer:
1754 istate = (val != (char *)NULL);
1756 if (istate == 0)
1758 char *current_path;
1760 /* Get the next directory from the path. If there is none, then we
1761 are all done. */
1762 if (path == 0 || path[path_index] == 0 ||
1763 (current_path = extract_colon_unit (path, &path_index)) == 0)
1764 return ((char *)NULL);
1766 searching_path = 1;
1767 if (*current_path == 0)
1769 free (current_path);
1770 current_path = savestring (".");
1773 if (*current_path == '~')
1775 char *t;
1777 t = bash_tilde_expand (current_path, 0);
1778 free (current_path);
1779 current_path = t;
1782 if (current_path[0] == '.' && current_path[1] == '\0')
1783 dot_in_path = 1;
1785 if (filename_hint)
1786 free (filename_hint);
1788 filename_hint = sh_makepath (current_path, hint, 0);
1789 free (current_path); /* XXX */
1792 inner:
1793 val = rl_filename_completion_function (filename_hint, istate);
1794 istate = 1;
1796 if (val == 0)
1798 /* If the hint text is an absolute program, then don't bother
1799 searching through PATH. */
1800 if (absolute_program (hint))
1801 return ((char *)NULL);
1803 goto outer;
1805 else
1807 int match, freetemp;
1809 if (absolute_program (hint))
1811 if (igncase == 0)
1812 match = strncmp (val, hint, hint_len) == 0;
1813 else
1814 match = strncasecmp (val, hint, hint_len) == 0;
1816 /* If we performed tilde expansion, restore the original
1817 filename. */
1818 if (*hint_text == '~')
1819 temp = restore_tilde (val, directory_part);
1820 else
1821 temp = savestring (val);
1822 freetemp = 1;
1824 else
1826 temp = strrchr (val, '/');
1828 if (temp)
1830 temp++;
1831 if (igncase == 0)
1832 freetemp = match = strncmp (temp, hint, hint_len) == 0;
1833 else
1834 freetemp = match = strncasecmp (temp, hint, hint_len) == 0;
1835 if (match)
1836 temp = savestring (temp);
1838 else
1839 freetemp = match = 0;
1842 #if 0
1843 /* If we have found a match, and it is an executable file or a
1844 directory name, return it. */
1845 if (match && executable_or_directory (val))
1846 #else
1847 /* If we have found a match, and it is an executable file, return it.
1848 We don't return directory names when searching $PATH, since the
1849 bash execution code won't find executables in directories which
1850 appear in directories in $PATH when they're specified using
1851 relative pathnames. */
1852 if (match && (searching_path ? executable_file (val) : executable_or_directory (val)))
1853 #endif
1855 free (val);
1856 val = ""; /* So it won't be NULL. */
1857 return (temp);
1859 else
1861 if (freetemp)
1862 free (temp);
1863 free (val);
1864 goto inner;
1869 /* Completion inside an unterminated command substitution. */
1870 static char *
1871 command_subst_completion_function (text, state)
1872 const char *text;
1873 int state;
1875 static char **matches = (char **)NULL;
1876 static const char *orig_start;
1877 static char *filename_text = (char *)NULL;
1878 static int cmd_index, start_len;
1879 char *value;
1881 if (state == 0)
1883 if (filename_text)
1884 free (filename_text);
1885 orig_start = text;
1886 if (*text == '`')
1887 text++;
1888 else if (*text == '$' && text[1] == '(') /* ) */
1889 text += 2;
1890 /* If the text was quoted, suppress any quote character that the
1891 readline completion code would insert. */
1892 rl_completion_suppress_quote = 1;
1893 start_len = text - orig_start;
1894 filename_text = savestring (text);
1895 if (matches)
1896 free (matches);
1899 * At this point we can entertain the idea of re-parsing
1900 * `filename_text' into a (possibly incomplete) command name and
1901 * arguments, and doing completion based on that. This is
1902 * currently very rudimentary, but it is a small improvement.
1904 for (value = filename_text + strlen (filename_text) - 1; value > filename_text; value--)
1905 if (whitespace (*value) || member (*value, COMMAND_SEPARATORS))
1906 break;
1907 if (value <= filename_text)
1908 matches = rl_completion_matches (filename_text, command_word_completion_function);
1909 else
1911 value++;
1912 start_len += value - filename_text;
1913 if (whitespace (value[-1]))
1914 matches = rl_completion_matches (value, rl_filename_completion_function);
1915 else
1916 matches = rl_completion_matches (value, command_word_completion_function);
1919 /* If there is more than one match, rl_completion_matches has already
1920 put the lcd in matches[0]. Skip over it. */
1921 cmd_index = matches && matches[0] && matches[1];
1923 /* If there's a single match and it's a directory, set the append char
1924 to the expected `/'. Otherwise, don't append anything. */
1925 if (matches && matches[0] && matches[1] == 0 && test_for_directory (matches[0]))
1926 rl_completion_append_character = '/';
1927 else
1928 rl_completion_suppress_append = 1;
1931 if (!matches || !matches[cmd_index])
1933 rl_filename_quoting_desired = 0; /* disable quoting */
1934 return ((char *)NULL);
1936 else
1938 value = (char *)xmalloc (1 + start_len + strlen (matches[cmd_index]));
1940 if (start_len == 1)
1941 value[0] = *orig_start;
1942 else
1943 strncpy (value, orig_start, start_len);
1945 strcpy (value + start_len, matches[cmd_index]);
1947 cmd_index++;
1948 return (value);
1952 /* Okay, now we write the entry_function for variable completion. */
1953 static char *
1954 variable_completion_function (text, state)
1955 const char *text;
1956 int state;
1958 static char **varlist = (char **)NULL;
1959 static int varlist_index;
1960 static char *varname = (char *)NULL;
1961 static int namelen;
1962 static int first_char, first_char_loc;
1964 if (!state)
1966 if (varname)
1967 free (varname);
1969 first_char_loc = 0;
1970 first_char = text[0];
1972 if (first_char == '$')
1973 first_char_loc++;
1975 if (text[first_char_loc] == '{')
1976 first_char_loc++;
1978 varname = savestring (text + first_char_loc);
1980 namelen = strlen (varname);
1981 if (varlist)
1982 strvec_dispose (varlist);
1984 varlist = all_variables_matching_prefix (varname);
1985 varlist_index = 0;
1988 if (!varlist || !varlist[varlist_index])
1990 return ((char *)NULL);
1992 else
1994 char *value;
1996 value = (char *)xmalloc (4 + strlen (varlist[varlist_index]));
1998 if (first_char_loc)
2000 value[0] = first_char;
2001 if (first_char_loc == 2)
2002 value[1] = '{';
2005 strcpy (value + first_char_loc, varlist[varlist_index]);
2006 if (first_char_loc == 2)
2007 strcat (value, "}");
2009 varlist_index++;
2010 return (value);
2014 /* How about a completion function for hostnames? */
2015 static char *
2016 hostname_completion_function (text, state)
2017 const char *text;
2018 int state;
2020 static char **list = (char **)NULL;
2021 static int list_index = 0;
2022 static int first_char, first_char_loc;
2024 /* If we don't have any state, make some. */
2025 if (state == 0)
2027 FREE (list);
2029 list = (char **)NULL;
2031 first_char_loc = 0;
2032 first_char = *text;
2034 if (first_char == '@')
2035 first_char_loc++;
2037 list = hostnames_matching ((char *)text+first_char_loc);
2038 list_index = 0;
2041 if (list && list[list_index])
2043 char *t;
2045 t = (char *)xmalloc (2 + strlen (list[list_index]));
2046 *t = first_char;
2047 strcpy (t + first_char_loc, list[list_index]);
2048 list_index++;
2049 return (t);
2052 return ((char *)NULL);
2056 * A completion function for service names from /etc/services (or wherever).
2058 char *
2059 bash_servicename_completion_function (text, state)
2060 const char *text;
2061 int state;
2063 #if defined (__WIN32__) || defined (__OPENNT) || !defined (HAVE_GETSERVENT)
2064 return ((char *)NULL);
2065 #else
2066 static char *sname = (char *)NULL;
2067 static struct servent *srvent;
2068 static int snamelen, firstc;
2069 char *value;
2070 char **alist, *aentry;
2071 int afound;
2073 if (state == 0)
2075 FREE (sname);
2076 firstc = *text;
2078 sname = savestring (text);
2079 snamelen = strlen (sname);
2080 setservent (0);
2083 while (srvent = getservent ())
2085 afound = 0;
2086 if (snamelen == 0 || (STREQN (sname, srvent->s_name, snamelen)))
2087 break;
2088 /* Not primary, check aliases */
2089 for (alist = srvent->s_aliases; *alist; alist++)
2091 aentry = *alist;
2092 if (STREQN (sname, aentry, snamelen))
2094 afound = 1;
2095 break;
2099 if (afound)
2100 break;
2103 if (srvent == 0)
2105 endservent ();
2106 return ((char *)NULL);
2109 value = afound ? savestring (aentry) : savestring (srvent->s_name);
2110 return value;
2111 #endif
2115 * A completion function for group names from /etc/group (or wherever).
2117 char *
2118 bash_groupname_completion_function (text, state)
2119 const char *text;
2120 int state;
2122 #if defined (__WIN32__) || defined (__OPENNT) || !defined (HAVE_GRP_H)
2123 return ((char *)NULL);
2124 #else
2125 static char *gname = (char *)NULL;
2126 static struct group *grent;
2127 static int gnamelen;
2128 char *value;
2130 if (state == 0)
2132 FREE (gname);
2133 gname = savestring (text);
2134 gnamelen = strlen (gname);
2136 setgrent ();
2139 while (grent = getgrent ())
2141 if (gnamelen == 0 || (STREQN (gname, grent->gr_name, gnamelen)))
2142 break;
2145 if (grent == 0)
2147 endgrent ();
2148 return ((char *)NULL);
2151 value = savestring (grent->gr_name);
2152 return (value);
2153 #endif
2156 /* Functions to perform history and alias expansions on the current line. */
2158 #if defined (BANG_HISTORY)
2159 /* Perform history expansion on the current line. If no history expansion
2160 is done, pre_process_line() returns what it was passed, so we need to
2161 allocate a new line here. */
2162 static char *
2163 history_expand_line_internal (line)
2164 char *line;
2166 char *new_line;
2167 int old_verify;
2169 old_verify = hist_verify;
2170 hist_verify = 0;
2171 new_line = pre_process_line (line, 0, 0);
2172 hist_verify = old_verify;
2174 return (new_line == line) ? savestring (line) : new_line;
2176 #endif
2178 /* There was an error in expansion. Let the preprocessor print
2179 the error here. */
2180 static void
2181 cleanup_expansion_error ()
2183 char *to_free;
2184 #if defined (BANG_HISTORY)
2185 int old_verify;
2187 old_verify = hist_verify;
2188 hist_verify = 0;
2189 #endif
2191 fprintf (rl_outstream, "\r\n");
2192 to_free = pre_process_line (rl_line_buffer, 1, 0);
2193 #if defined (BANG_HISTORY)
2194 hist_verify = old_verify;
2195 #endif
2196 if (to_free != rl_line_buffer)
2197 FREE (to_free);
2198 putc ('\r', rl_outstream);
2199 rl_forced_update_display ();
2202 /* If NEW_LINE differs from what is in the readline line buffer, add an
2203 undo record to get from the readline line buffer contents to the new
2204 line and make NEW_LINE the current readline line. */
2205 static void
2206 maybe_make_readline_line (new_line)
2207 char *new_line;
2209 if (strcmp (new_line, rl_line_buffer) != 0)
2211 rl_point = rl_end;
2213 rl_add_undo (UNDO_BEGIN, 0, 0, 0);
2214 rl_delete_text (0, rl_point);
2215 rl_point = rl_end = rl_mark = 0;
2216 rl_insert_text (new_line);
2217 rl_add_undo (UNDO_END, 0, 0, 0);
2221 /* Make NEW_LINE be the current readline line. This frees NEW_LINE. */
2222 static void
2223 set_up_new_line (new_line)
2224 char *new_line;
2226 int old_point, at_end;
2228 old_point = rl_point;
2229 at_end = rl_point == rl_end;
2231 /* If the line was history and alias expanded, then make that
2232 be one thing to undo. */
2233 maybe_make_readline_line (new_line);
2234 free (new_line);
2236 /* Place rl_point where we think it should go. */
2237 if (at_end)
2238 rl_point = rl_end;
2239 else if (old_point < rl_end)
2241 rl_point = old_point;
2242 if (!whitespace (rl_line_buffer[rl_point]))
2243 rl_forward_word (1, 0);
2247 #if defined (ALIAS)
2248 /* Expand aliases in the current readline line. */
2249 static int
2250 alias_expand_line (count, ignore)
2251 int count, ignore;
2253 char *new_line;
2255 new_line = alias_expand (rl_line_buffer);
2257 if (new_line)
2259 set_up_new_line (new_line);
2260 return (0);
2262 else
2264 cleanup_expansion_error ();
2265 return (1);
2268 #endif
2270 #if defined (BANG_HISTORY)
2271 /* History expand the line. */
2272 static int
2273 history_expand_line (count, ignore)
2274 int count, ignore;
2276 char *new_line;
2278 new_line = history_expand_line_internal (rl_line_buffer);
2280 if (new_line)
2282 set_up_new_line (new_line);
2283 return (0);
2285 else
2287 cleanup_expansion_error ();
2288 return (1);
2292 /* Expand history substitutions in the current line and then insert a
2293 space (hopefully close to where we were before). */
2294 static int
2295 tcsh_magic_space (count, ignore)
2296 int count, ignore;
2298 int dist_from_end, old_point;
2300 old_point = rl_point;
2301 dist_from_end = rl_end - rl_point;
2302 if (history_expand_line (count, ignore) == 0)
2304 /* Try a simple heuristic from Stephen Gildea <gildea@intouchsys.com>.
2305 This works if all expansions were before rl_point or if no expansions
2306 were performed. */
2307 rl_point = (old_point == 0) ? old_point : rl_end - dist_from_end;
2308 rl_insert (1, ' ');
2309 return (0);
2311 else
2312 return (1);
2314 #endif /* BANG_HISTORY */
2316 /* History and alias expand the line. */
2317 static int
2318 history_and_alias_expand_line (count, ignore)
2319 int count, ignore;
2321 char *new_line;
2323 new_line = 0;
2324 #if defined (BANG_HISTORY)
2325 new_line = history_expand_line_internal (rl_line_buffer);
2326 #endif
2328 #if defined (ALIAS)
2329 if (new_line)
2331 char *alias_line;
2333 alias_line = alias_expand (new_line);
2334 free (new_line);
2335 new_line = alias_line;
2337 #endif /* ALIAS */
2339 if (new_line)
2341 set_up_new_line (new_line);
2342 return (0);
2344 else
2346 cleanup_expansion_error ();
2347 return (1);
2351 /* History and alias expand the line, then perform the shell word
2352 expansions by calling expand_string. This can't use set_up_new_line()
2353 because we want the variable expansions as a separate undo'able
2354 set of operations. */
2355 static int
2356 shell_expand_line (count, ignore)
2357 int count, ignore;
2359 char *new_line;
2360 WORD_LIST *expanded_string;
2362 new_line = 0;
2363 #if defined (BANG_HISTORY)
2364 new_line = history_expand_line_internal (rl_line_buffer);
2365 #endif
2367 #if defined (ALIAS)
2368 if (new_line)
2370 char *alias_line;
2372 alias_line = alias_expand (new_line);
2373 free (new_line);
2374 new_line = alias_line;
2376 #endif /* ALIAS */
2378 if (new_line)
2380 int old_point = rl_point;
2381 int at_end = rl_point == rl_end;
2383 /* If the line was history and alias expanded, then make that
2384 be one thing to undo. */
2385 maybe_make_readline_line (new_line);
2386 free (new_line);
2388 /* If there is variable expansion to perform, do that as a separate
2389 operation to be undone. */
2390 new_line = savestring (rl_line_buffer);
2391 expanded_string = expand_string (new_line, 0);
2392 FREE (new_line);
2393 if (expanded_string == 0)
2395 new_line = (char *)xmalloc (1);
2396 new_line[0] = '\0';
2398 else
2400 new_line = string_list (expanded_string);
2401 dispose_words (expanded_string);
2404 maybe_make_readline_line (new_line);
2405 free (new_line);
2407 /* Place rl_point where we think it should go. */
2408 if (at_end)
2409 rl_point = rl_end;
2410 else if (old_point < rl_end)
2412 rl_point = old_point;
2413 if (!whitespace (rl_line_buffer[rl_point]))
2414 rl_forward_word (1, 0);
2416 return 0;
2418 else
2420 cleanup_expansion_error ();
2421 return 1;
2425 /* If FIGNORE is set, then don't match files with the given suffixes when
2426 completing filenames. If only one of the possibilities has an acceptable
2427 suffix, delete the others, else just return and let the completer
2428 signal an error. It is called by the completer when real
2429 completions are done on filenames by the completer's internal
2430 function, not for completion lists (M-?) and not on "other"
2431 completion types, such as hostnames or commands. */
2433 static struct ignorevar fignore =
2435 "FIGNORE",
2436 (struct ign *)0,
2438 (char *)0,
2439 (sh_iv_item_func_t *) 0,
2442 static void
2443 _ignore_completion_names (names, name_func)
2444 char **names;
2445 sh_ignore_func_t *name_func;
2447 char **newnames;
2448 int idx, nidx;
2449 char **oldnames;
2450 int oidx;
2452 /* If there is only one completion, see if it is acceptable. If it is
2453 not, free it up. In any case, short-circuit and return. This is a
2454 special case because names[0] is not the prefix of the list of names
2455 if there is only one completion; it is the completion itself. */
2456 if (names[1] == (char *)0)
2458 if (force_fignore)
2459 if ((*name_func) (names[0]) == 0)
2461 free (names[0]);
2462 names[0] = (char *)NULL;
2465 return;
2468 /* Allocate space for array to hold list of pointers to matching
2469 filenames. The pointers are copied back to NAMES when done. */
2470 for (nidx = 1; names[nidx]; nidx++)
2472 newnames = strvec_create (nidx + 1);
2474 if (force_fignore == 0)
2476 oldnames = strvec_create (nidx - 1);
2477 oidx = 0;
2480 newnames[0] = names[0];
2481 for (idx = nidx = 1; names[idx]; idx++)
2483 if ((*name_func) (names[idx]))
2484 newnames[nidx++] = names[idx];
2485 else if (force_fignore == 0)
2486 oldnames[oidx++] = names[idx];
2487 else
2488 free (names[idx]);
2491 newnames[nidx] = (char *)NULL;
2493 /* If none are acceptable then let the completer handle it. */
2494 if (nidx == 1)
2496 if (force_fignore)
2498 free (names[0]);
2499 names[0] = (char *)NULL;
2501 else
2502 free (oldnames);
2504 free (newnames);
2505 return;
2508 if (force_fignore == 0)
2510 while (oidx)
2511 free (oldnames[--oidx]);
2512 free (oldnames);
2515 /* If only one is acceptable, copy it to names[0] and return. */
2516 if (nidx == 2)
2518 free (names[0]);
2519 names[0] = newnames[1];
2520 names[1] = (char *)NULL;
2521 free (newnames);
2522 return;
2525 /* Copy the acceptable names back to NAMES, set the new array end,
2526 and return. */
2527 for (nidx = 1; newnames[nidx]; nidx++)
2528 names[nidx] = newnames[nidx];
2529 names[nidx] = (char *)NULL;
2530 free (newnames);
2533 static int
2534 name_is_acceptable (name)
2535 const char *name;
2537 struct ign *p;
2538 int nlen;
2540 for (nlen = strlen (name), p = fignore.ignores; p->val; p++)
2542 if (nlen > p->len && p->len > 0 && STREQ (p->val, &name[nlen - p->len]))
2543 return (0);
2546 return (1);
2549 #if 0
2550 static int
2551 ignore_dot_names (name)
2552 char *name;
2554 return (name[0] != '.');
2556 #endif
2558 static int
2559 filename_completion_ignore (names)
2560 char **names;
2562 #if 0
2563 if (glob_dot_filenames == 0)
2564 _ignore_completion_names (names, ignore_dot_names);
2565 #endif
2567 setup_ignore_patterns (&fignore);
2569 if (fignore.num_ignores == 0)
2570 return 0;
2572 _ignore_completion_names (names, name_is_acceptable);
2574 return 0;
2577 /* Return 1 if NAME is a directory. NAME undergoes tilde expansion. */
2578 static int
2579 test_for_directory (name)
2580 const char *name;
2582 char *fn;
2583 int r;
2585 fn = bash_tilde_expand (name, 0);
2586 r = file_isdir (fn);
2587 free (fn);
2589 return (r);
2592 /* Remove files from NAMES, leaving directories. */
2593 static int
2594 bash_ignore_filenames (names)
2595 char **names;
2597 _ignore_completion_names (names, test_for_directory);
2598 return 0;
2601 static int
2602 return_zero (name)
2603 const char *name;
2605 return 0;
2608 static int
2609 bash_ignore_everything (names)
2610 char **names;
2612 _ignore_completion_names (names, return_zero);
2613 return 0;
2616 /* Replace a tilde-prefix in VAL with a `~', assuming the user typed it. VAL
2617 is an expanded filename. DIRECTORY_PART is the tilde-prefix portion
2618 of the un-tilde-expanded version of VAL (what the user typed). */
2619 static char *
2620 restore_tilde (val, directory_part)
2621 char *val, *directory_part;
2623 int l, vl, dl2, xl;
2624 char *dh2, *expdir, *ret;
2626 vl = strlen (val);
2628 /* We need to duplicate the expansions readline performs on the directory
2629 portion before passing it to our completion function. */
2630 dh2 = directory_part ? bash_dequote_filename (directory_part, 0) : 0;
2631 bash_directory_expansion (&dh2);
2632 dl2 = strlen (dh2);
2634 expdir = bash_tilde_expand (directory_part, 0);
2635 xl = strlen (expdir);
2636 free (expdir);
2639 dh2 = unexpanded but dequoted tilde-prefix
2640 dl2 = length of tilde-prefix
2641 expdir = tilde-expanded tilde-prefix
2642 xl = length of expanded tilde-prefix
2643 l = length of remainder after tilde-prefix
2645 l = (vl - xl) + 1;
2647 ret = (char *)xmalloc (dl2 + 2 + l);
2648 strcpy (ret, dh2);
2649 strcpy (ret + dl2, val + xl);
2651 free (dh2);
2652 return (ret);
2655 /* Simulate the expansions that will be performed by
2656 rl_filename_completion_function. This must be called with the address of
2657 a pointer to malloc'd memory. */
2658 static void
2659 bash_directory_expansion (dirname)
2660 char **dirname;
2662 char *d, *nd;
2664 d = savestring (*dirname);
2666 if (rl_directory_rewrite_hook)
2667 (*rl_directory_rewrite_hook) (&d);
2668 else if (rl_directory_completion_hook && (*rl_directory_completion_hook) (&d))
2670 free (*dirname);
2671 *dirname = d;
2673 else if (rl_completion_found_quote)
2675 nd = bash_dequote_filename (d, rl_completion_quote_character);
2676 free (*dirname);
2677 free (d);
2678 *dirname = nd;
2682 /* If necessary, rewrite directory entry */
2683 static char *
2684 bash_filename_rewrite_hook (fname, fnlen)
2685 char *fname;
2686 int fnlen;
2688 char *conv;
2690 conv = fnx_fromfs (fname, fnlen);
2691 if (conv != fname)
2692 conv = savestring (conv);
2693 return conv;
2696 /* Handle symbolic link references and other directory name
2697 expansions while hacking completion. This should return 1 if it modifies
2698 the DIRNAME argument, 0 otherwise. It should make sure not to modify
2699 DIRNAME if it returns 0. */
2700 static int
2701 bash_directory_completion_hook (dirname)
2702 char **dirname;
2704 char *local_dirname, *new_dirname, *t;
2705 int return_value, should_expand_dirname;
2706 WORD_LIST *wl;
2707 struct stat sb;
2709 return_value = should_expand_dirname = 0;
2710 local_dirname = *dirname;
2712 if (mbschr (local_dirname, '$'))
2713 should_expand_dirname = 1;
2714 else
2716 t = mbschr (local_dirname, '`');
2717 if (t && unclosed_pair (local_dirname, strlen (local_dirname), "`") == 0)
2718 should_expand_dirname = 1;
2721 #if defined (HAVE_LSTAT)
2722 if (should_expand_dirname && lstat (local_dirname, &sb) == 0)
2723 #else
2724 if (should_expand_dirname && stat (local_dirname, &sb) == 0)
2725 #endif
2726 should_expand_dirname = 0;
2728 if (should_expand_dirname)
2730 new_dirname = savestring (local_dirname);
2731 wl = expand_prompt_string (new_dirname, 0, W_NOCOMSUB); /* does the right thing */
2732 if (wl)
2734 *dirname = string_list (wl);
2735 /* Tell the completer to replace the directory name only if we
2736 actually expanded something. */
2737 return_value = STREQ (local_dirname, *dirname) == 0;
2738 free (local_dirname);
2739 free (new_dirname);
2740 dispose_words (wl);
2741 local_dirname = *dirname;
2743 else
2745 free (new_dirname);
2746 free (local_dirname);
2747 *dirname = (char *)xmalloc (1);
2748 **dirname = '\0';
2749 return 1;
2752 else
2754 /* Dequote the filename even if we don't expand it. */
2755 new_dirname = bash_dequote_filename (local_dirname, rl_completion_quote_character);
2756 return_value = STREQ (local_dirname, new_dirname) == 0;
2757 free (local_dirname);
2758 local_dirname = *dirname = new_dirname;
2761 if (no_symbolic_links == 0 && (local_dirname[0] != '.' || local_dirname[1]))
2763 char *temp1, *temp2;
2764 int len1, len2;
2766 t = get_working_directory ("symlink-hook");
2767 temp1 = make_absolute (local_dirname, t);
2768 free (t);
2769 temp2 = sh_canonpath (temp1, PATH_CHECKDOTDOT|PATH_CHECKEXISTS);
2771 /* Try spelling correction if initial canonicalization fails. */
2772 if (temp2 == 0 && dircomplete_spelling)
2774 temp2 = dirspell (temp1);
2775 if (temp2)
2777 free (temp1);
2778 temp1 = temp2;
2779 temp2 = sh_canonpath (temp1, PATH_CHECKDOTDOT|PATH_CHECKEXISTS);
2780 return_value |= temp2 != 0;
2783 /* If we can't canonicalize, bail. */
2784 if (temp2 == 0)
2786 free (temp1);
2787 return return_value;
2789 len1 = strlen (temp1);
2790 if (temp1[len1 - 1] == '/')
2792 len2 = strlen (temp2);
2793 if (len2 > 2) /* don't append `/' to `/' or `//' */
2795 temp2 = (char *)xrealloc (temp2, len2 + 2);
2796 temp2[len2] = '/';
2797 temp2[len2 + 1] = '\0';
2800 return_value |= STREQ (local_dirname, temp2) == 0;
2801 free (local_dirname);
2802 *dirname = temp2;
2803 free (temp1);
2806 return (return_value);
2809 static char **history_completion_array = (char **)NULL;
2810 static int harry_size;
2811 static int harry_len;
2813 static void
2814 build_history_completion_array ()
2816 register int i, j;
2817 HIST_ENTRY **hlist;
2818 char **tokens;
2820 /* First, clear out the current dynamic history completion list. */
2821 if (harry_size)
2823 strvec_dispose (history_completion_array);
2824 history_completion_array = (char **)NULL;
2825 harry_size = 0;
2826 harry_len = 0;
2829 /* Next, grovel each line of history, making each shell-sized token
2830 a separate entry in the history_completion_array. */
2831 hlist = history_list ();
2833 if (hlist)
2835 for (i = 0; hlist[i]; i++)
2837 for ( --i; i >= 0; i--)
2839 /* Separate each token, and place into an array. */
2840 tokens = history_tokenize (hlist[i]->line);
2842 for (j = 0; tokens && tokens[j]; j++)
2844 if (harry_len + 2 > harry_size)
2845 history_completion_array = strvec_resize (history_completion_array, harry_size += 10);
2847 history_completion_array[harry_len++] = tokens[j];
2848 history_completion_array[harry_len] = (char *)NULL;
2850 free (tokens);
2853 /* Sort the complete list of tokens. */
2854 if (dabbrev_expand_active == 0)
2855 qsort (history_completion_array, harry_len, sizeof (char *), (QSFUNC *)strvec_strcmp);
2859 static char *
2860 history_completion_generator (hint_text, state)
2861 const char *hint_text;
2862 int state;
2864 static int local_index, len;
2865 static const char *text;
2867 /* If this is the first call to the generator, then initialize the
2868 list of strings to complete over. */
2869 if (state == 0)
2871 if (dabbrev_expand_active) /* This is kind of messy */
2872 rl_completion_suppress_append = 1;
2873 local_index = 0;
2874 build_history_completion_array ();
2875 text = hint_text;
2876 len = strlen (text);
2879 while (history_completion_array && history_completion_array[local_index])
2881 if (strncmp (text, history_completion_array[local_index++], len) == 0)
2882 return (savestring (history_completion_array[local_index - 1]));
2884 return ((char *)NULL);
2887 static int
2888 dynamic_complete_history (count, key)
2889 int count, key;
2891 int r;
2892 rl_compentry_func_t *orig_func;
2893 rl_completion_func_t *orig_attempt_func;
2894 rl_compignore_func_t *orig_ignore_func;
2896 orig_func = rl_completion_entry_function;
2897 orig_attempt_func = rl_attempted_completion_function;
2898 orig_ignore_func = rl_ignore_some_completions_function;
2900 rl_completion_entry_function = history_completion_generator;
2901 rl_attempted_completion_function = (rl_completion_func_t *)NULL;
2902 rl_ignore_some_completions_function = filename_completion_ignore;
2904 /* XXX - use rl_completion_mode here? */
2905 if (rl_last_func == dynamic_complete_history)
2906 r = rl_complete_internal ('?');
2907 else
2908 r = rl_complete_internal (TAB);
2910 rl_completion_entry_function = orig_func;
2911 rl_attempted_completion_function = orig_attempt_func;
2912 rl_ignore_some_completions_function = orig_ignore_func;
2914 return r;
2917 static int
2918 bash_dabbrev_expand (count, key)
2919 int count, key;
2921 int r, orig_suppress, orig_sort;
2922 rl_compentry_func_t *orig_func;
2923 rl_completion_func_t *orig_attempt_func;
2924 rl_compignore_func_t *orig_ignore_func;
2926 orig_func = rl_menu_completion_entry_function;
2927 orig_attempt_func = rl_attempted_completion_function;
2928 orig_ignore_func = rl_ignore_some_completions_function;
2929 orig_suppress = rl_completion_suppress_append;
2930 orig_sort = rl_sort_completion_matches;
2932 rl_menu_completion_entry_function = history_completion_generator;
2933 rl_attempted_completion_function = (rl_completion_func_t *)NULL;
2934 rl_ignore_some_completions_function = filename_completion_ignore;
2935 rl_filename_completion_desired = 0;
2936 rl_completion_suppress_append = 1;
2937 rl_sort_completion_matches = 0;
2939 /* XXX - use rl_completion_mode here? */
2940 dabbrev_expand_active = 1;
2941 if (rl_last_func == bash_dabbrev_expand)
2942 rl_last_func = rl_menu_complete;
2943 r = rl_menu_complete (count, key);
2944 dabbrev_expand_active = 0;
2946 rl_last_func = bash_dabbrev_expand;
2947 rl_menu_completion_entry_function = orig_func;
2948 rl_attempted_completion_function = orig_attempt_func;
2949 rl_ignore_some_completions_function = orig_ignore_func;
2950 rl_completion_suppress_append = orig_suppress;
2951 rl_sort_completion_matches = orig_sort;
2953 return r;
2956 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
2957 static int
2958 bash_complete_username (ignore, ignore2)
2959 int ignore, ignore2;
2961 return bash_complete_username_internal (rl_completion_mode (bash_complete_username));
2964 static int
2965 bash_possible_username_completions (ignore, ignore2)
2966 int ignore, ignore2;
2968 return bash_complete_username_internal ('?');
2971 static int
2972 bash_complete_username_internal (what_to_do)
2973 int what_to_do;
2975 return bash_specific_completion (what_to_do, rl_username_completion_function);
2978 static int
2979 bash_complete_filename (ignore, ignore2)
2980 int ignore, ignore2;
2982 return bash_complete_filename_internal (rl_completion_mode (bash_complete_filename));
2985 static int
2986 bash_possible_filename_completions (ignore, ignore2)
2987 int ignore, ignore2;
2989 return bash_complete_filename_internal ('?');
2992 static int
2993 bash_complete_filename_internal (what_to_do)
2994 int what_to_do;
2996 rl_compentry_func_t *orig_func;
2997 rl_completion_func_t *orig_attempt_func;
2998 rl_icppfunc_t *orig_dir_func;
2999 rl_compignore_func_t *orig_ignore_func;
3000 /*const*/ char *orig_rl_completer_word_break_characters;
3001 int r;
3003 orig_func = rl_completion_entry_function;
3004 orig_attempt_func = rl_attempted_completion_function;
3005 orig_dir_func = rl_directory_rewrite_hook;
3006 orig_ignore_func = rl_ignore_some_completions_function;
3007 orig_rl_completer_word_break_characters = rl_completer_word_break_characters;
3008 rl_completion_entry_function = rl_filename_completion_function;
3009 rl_attempted_completion_function = (rl_completion_func_t *)NULL;
3010 rl_directory_rewrite_hook = (rl_icppfunc_t *)NULL;
3011 rl_ignore_some_completions_function = filename_completion_ignore;
3012 rl_completer_word_break_characters = " \t\n\"\'";
3014 r = rl_complete_internal (what_to_do);
3016 rl_completion_entry_function = orig_func;
3017 rl_attempted_completion_function = orig_attempt_func;
3018 rl_directory_rewrite_hook = orig_dir_func;
3019 rl_ignore_some_completions_function = orig_ignore_func;
3020 rl_completer_word_break_characters = orig_rl_completer_word_break_characters;
3022 return r;
3025 static int
3026 bash_complete_hostname (ignore, ignore2)
3027 int ignore, ignore2;
3029 return bash_complete_hostname_internal (rl_completion_mode (bash_complete_hostname));
3032 static int
3033 bash_possible_hostname_completions (ignore, ignore2)
3034 int ignore, ignore2;
3036 return bash_complete_hostname_internal ('?');
3039 static int
3040 bash_complete_variable (ignore, ignore2)
3041 int ignore, ignore2;
3043 return bash_complete_variable_internal (rl_completion_mode (bash_complete_variable));
3046 static int
3047 bash_possible_variable_completions (ignore, ignore2)
3048 int ignore, ignore2;
3050 return bash_complete_variable_internal ('?');
3053 static int
3054 bash_complete_command (ignore, ignore2)
3055 int ignore, ignore2;
3057 return bash_complete_command_internal (rl_completion_mode (bash_complete_command));
3060 static int
3061 bash_possible_command_completions (ignore, ignore2)
3062 int ignore, ignore2;
3064 return bash_complete_command_internal ('?');
3067 static int
3068 bash_complete_hostname_internal (what_to_do)
3069 int what_to_do;
3071 return bash_specific_completion (what_to_do, hostname_completion_function);
3074 static int
3075 bash_complete_variable_internal (what_to_do)
3076 int what_to_do;
3078 return bash_specific_completion (what_to_do, variable_completion_function);
3081 static int
3082 bash_complete_command_internal (what_to_do)
3083 int what_to_do;
3085 return bash_specific_completion (what_to_do, command_word_completion_function);
3088 static char *globtext;
3089 static char *globorig;
3091 static char *
3092 glob_complete_word (text, state)
3093 const char *text;
3094 int state;
3096 static char **matches = (char **)NULL;
3097 static int ind;
3098 int glen;
3099 char *ret, *ttext;
3101 if (state == 0)
3103 rl_filename_completion_desired = 1;
3104 FREE (matches);
3105 if (globorig != globtext)
3106 FREE (globorig);
3107 FREE (globtext);
3109 ttext = bash_tilde_expand (text, 0);
3111 if (rl_explicit_arg)
3113 globorig = savestring (ttext);
3114 glen = strlen (ttext);
3115 globtext = (char *)xmalloc (glen + 2);
3116 strcpy (globtext, ttext);
3117 globtext[glen] = '*';
3118 globtext[glen+1] = '\0';
3120 else
3121 globtext = globorig = savestring (ttext);
3123 if (ttext != text)
3124 free (ttext);
3126 matches = shell_glob_filename (globtext);
3127 if (GLOB_FAILED (matches))
3128 matches = (char **)NULL;
3129 ind = 0;
3132 ret = matches ? matches[ind] : (char *)NULL;
3133 ind++;
3134 return ret;
3137 static int
3138 bash_glob_completion_internal (what_to_do)
3139 int what_to_do;
3141 return bash_specific_completion (what_to_do, glob_complete_word);
3144 /* A special quoting function so we don't end up quoting globbing characters
3145 in the word if there are no matches or multiple matches. */
3146 static char *
3147 bash_glob_quote_filename (s, rtype, qcp)
3148 char *s;
3149 int rtype;
3150 char *qcp;
3152 if (globorig && qcp && *qcp == '\0' && STREQ (s, globorig))
3153 return (savestring (s));
3154 else
3155 return (bash_quote_filename (s, rtype, qcp));
3158 static int
3159 bash_glob_complete_word (count, key)
3160 int count, key;
3162 int r;
3163 rl_quote_func_t *orig_quoting_function;
3165 if (rl_editing_mode == EMACS_EDITING_MODE)
3166 rl_explicit_arg = 1; /* force `*' append */
3167 orig_quoting_function = rl_filename_quoting_function;
3168 rl_filename_quoting_function = bash_glob_quote_filename;
3170 r = bash_glob_completion_internal (rl_completion_mode (bash_glob_complete_word));
3172 rl_filename_quoting_function = orig_quoting_function;
3173 return r;
3176 static int
3177 bash_glob_expand_word (count, key)
3178 int count, key;
3180 return bash_glob_completion_internal ('*');
3183 static int
3184 bash_glob_list_expansions (count, key)
3185 int count, key;
3187 return bash_glob_completion_internal ('?');
3190 static int
3191 bash_specific_completion (what_to_do, generator)
3192 int what_to_do;
3193 rl_compentry_func_t *generator;
3195 rl_compentry_func_t *orig_func;
3196 rl_completion_func_t *orig_attempt_func;
3197 rl_compignore_func_t *orig_ignore_func;
3198 int r;
3200 orig_func = rl_completion_entry_function;
3201 orig_attempt_func = rl_attempted_completion_function;
3202 orig_ignore_func = rl_ignore_some_completions_function;
3203 rl_completion_entry_function = generator;
3204 rl_attempted_completion_function = NULL;
3205 rl_ignore_some_completions_function = orig_ignore_func;
3207 r = rl_complete_internal (what_to_do);
3209 rl_completion_entry_function = orig_func;
3210 rl_attempted_completion_function = orig_attempt_func;
3211 rl_ignore_some_completions_function = orig_ignore_func;
3213 return r;
3216 #endif /* SPECIFIC_COMPLETION_FUNCTIONS */
3218 #if defined (VI_MODE)
3219 /* Completion, from vi mode's point of view. This is a modified version of
3220 rl_vi_complete which uses the bash globbing code to implement what POSIX
3221 specifies, which is to append a `*' and attempt filename generation (which
3222 has the side effect of expanding any globbing characters in the word). */
3223 static int
3224 bash_vi_complete (count, key)
3225 int count, key;
3227 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
3228 int p, r;
3229 char *t;
3231 if ((rl_point < rl_end) && (!whitespace (rl_line_buffer[rl_point])))
3233 if (!whitespace (rl_line_buffer[rl_point + 1]))
3234 rl_vi_end_word (1, 'E');
3235 rl_point++;
3238 /* Find boundaries of current word, according to vi definition of a
3239 `bigword'. */
3240 t = 0;
3241 if (rl_point > 0)
3243 p = rl_point;
3244 rl_vi_bWord (1, 'B');
3245 r = rl_point;
3246 rl_point = p;
3247 p = r;
3249 t = substring (rl_line_buffer, p, rl_point);
3252 if (t && glob_pattern_p (t) == 0)
3253 rl_explicit_arg = 1; /* XXX - force glob_complete_word to append `*' */
3254 FREE (t);
3256 if (key == '*') /* Expansion and replacement. */
3257 r = bash_glob_expand_word (count, key);
3258 else if (key == '=') /* List possible completions. */
3259 r = bash_glob_list_expansions (count, key);
3260 else if (key == '\\') /* Standard completion */
3261 r = bash_glob_complete_word (count, key);
3262 else
3263 r = rl_complete (0, key);
3265 if (key == '*' || key == '\\')
3266 rl_vi_start_inserting (key, 1, 1);
3268 return (r);
3269 #else
3270 return rl_vi_complete (count, key);
3271 #endif /* !SPECIFIC_COMPLETION_FUNCTIONS */
3273 #endif /* VI_MODE */
3275 /* Filename quoting for completion. */
3276 /* A function to strip unquoted quote characters (single quotes, double
3277 quotes, and backslashes). It allows single quotes to appear
3278 within double quotes, and vice versa. It should be smarter. */
3279 static char *
3280 bash_dequote_filename (text, quote_char)
3281 char *text;
3282 int quote_char;
3284 char *ret, *p, *r;
3285 int l, quoted;
3287 l = strlen (text);
3288 ret = (char *)xmalloc (l + 1);
3289 for (quoted = quote_char, p = text, r = ret; p && *p; p++)
3291 /* Allow backslash-escaped characters to pass through unscathed. */
3292 if (*p == '\\')
3294 /* Backslashes are preserved within single quotes. */
3295 if (quoted == '\'')
3296 *r++ = *p;
3297 /* Backslashes are preserved within double quotes unless the
3298 character is one that is defined to be escaped */
3299 else if (quoted == '"' && ((sh_syntaxtab[p[1]] & CBSDQUOTE) == 0))
3300 *r++ = *p;
3302 *r++ = *++p;
3303 if (*p == '\0')
3304 return ret; /* XXX - was break; */
3305 continue;
3307 /* Close quote. */
3308 if (quoted && *p == quoted)
3310 quoted = 0;
3311 continue;
3313 /* Open quote. */
3314 if (quoted == 0 && (*p == '\'' || *p == '"'))
3316 quoted = *p;
3317 continue;
3319 *r++ = *p;
3321 *r = '\0';
3322 return ret;
3325 /* Quote characters that the readline completion code would treat as
3326 word break characters with backslashes. Pass backslash-quoted
3327 characters through without examination. */
3328 static char *
3329 quote_word_break_chars (text)
3330 char *text;
3332 char *ret, *r, *s;
3333 int l;
3335 l = strlen (text);
3336 ret = (char *)xmalloc ((2 * l) + 1);
3337 for (s = text, r = ret; *s; s++)
3339 /* Pass backslash-quoted characters through, including the backslash. */
3340 if (*s == '\\')
3342 *r++ = '\\';
3343 *r++ = *++s;
3344 if (*s == '\0')
3345 break;
3346 continue;
3348 /* OK, we have an unquoted character. Check its presence in
3349 rl_completer_word_break_characters. */
3350 if (mbschr (rl_completer_word_break_characters, *s))
3351 *r++ = '\\';
3352 /* XXX -- check for standalone tildes here and backslash-quote them */
3353 if (s == text && *s == '~' && file_exists (text))
3354 *r++ = '\\';
3355 *r++ = *s;
3357 *r = '\0';
3358 return ret;
3361 /* Quote a filename using double quotes, single quotes, or backslashes
3362 depending on the value of completion_quoting_style. If we're
3363 completing using backslashes, we need to quote some additional
3364 characters (those that readline treats as word breaks), so we call
3365 quote_word_break_chars on the result. This returns newly-allocated
3366 memory. */
3367 static char *
3368 bash_quote_filename (s, rtype, qcp)
3369 char *s;
3370 int rtype;
3371 char *qcp;
3373 char *rtext, *mtext, *ret;
3374 int rlen, cs;
3376 rtext = (char *)NULL;
3378 /* If RTYPE == MULT_MATCH, it means that there is
3379 more than one match. In this case, we do not add
3380 the closing quote or attempt to perform tilde
3381 expansion. If RTYPE == SINGLE_MATCH, we try
3382 to perform tilde expansion, because single and double
3383 quotes inhibit tilde expansion by the shell. */
3385 cs = completion_quoting_style;
3386 /* Might need to modify the default completion style based on *qcp,
3387 since it's set to any user-provided opening quote. We also change
3388 to single-quoting if there is no user-provided opening quote and
3389 the word being completed contains newlines, since those are not
3390 quoted correctly using backslashes (a backslash-newline pair is
3391 special to the shell parser). */
3392 if (*qcp == '\0' && cs == COMPLETE_BSQUOTE && mbschr (s, '\n'))
3393 cs = COMPLETE_SQUOTE;
3394 else if (*qcp == '"')
3395 cs = COMPLETE_DQUOTE;
3396 else if (*qcp == '\'')
3397 cs = COMPLETE_SQUOTE;
3398 #if defined (BANG_HISTORY)
3399 else if (*qcp == '\0' && history_expansion && cs == COMPLETE_DQUOTE &&
3400 history_expansion_inhibited == 0 && mbschr (s, '!'))
3401 cs = COMPLETE_BSQUOTE;
3403 if (*qcp == '"' && history_expansion && cs == COMPLETE_DQUOTE &&
3404 history_expansion_inhibited == 0 && mbschr (s, '!'))
3406 cs = COMPLETE_BSQUOTE;
3407 *qcp = '\0';
3409 #endif
3411 /* Don't tilde-expand backslash-quoted filenames, since only single and
3412 double quotes inhibit tilde expansion. */
3413 mtext = s;
3414 if (mtext[0] == '~' && rtype == SINGLE_MATCH && cs != COMPLETE_BSQUOTE)
3415 mtext = bash_tilde_expand (s, 0);
3417 switch (cs)
3419 case COMPLETE_DQUOTE:
3420 rtext = sh_double_quote (mtext);
3421 break;
3422 case COMPLETE_SQUOTE:
3423 rtext = sh_single_quote (mtext);
3424 break;
3425 case COMPLETE_BSQUOTE:
3426 rtext = sh_backslash_quote (mtext);
3427 break;
3430 if (mtext != s)
3431 free (mtext);
3433 /* We may need to quote additional characters: those that readline treats
3434 as word breaks that are not quoted by backslash_quote. */
3435 if (rtext && cs == COMPLETE_BSQUOTE)
3437 mtext = quote_word_break_chars (rtext);
3438 free (rtext);
3439 rtext = mtext;
3442 /* Leave the opening quote intact. The readline completion code takes
3443 care of avoiding doubled opening quotes. */
3444 rlen = strlen (rtext);
3445 ret = (char *)xmalloc (rlen + 1);
3446 strcpy (ret, rtext);
3448 /* If there are multiple matches, cut off the closing quote. */
3449 if (rtype == MULT_MATCH && cs != COMPLETE_BSQUOTE)
3450 ret[rlen - 1] = '\0';
3451 free (rtext);
3452 return ret;
3455 /* Support for binding readline key sequences to Unix commands. */
3456 static Keymap cmd_xmap;
3458 static int
3459 putx(c)
3460 int c;
3462 int x;
3464 x = putc (c, rl_outstream);
3465 return (x);
3468 static int
3469 bash_execute_unix_command (count, key)
3470 int count; /* ignored */
3471 int key;
3473 Keymap ckmap; /* current keymap */
3474 Keymap xkmap; /* unix command executing keymap */
3475 register int i, r;
3476 intmax_t mi;
3477 sh_parser_state_t ps;
3478 char *cmd, *value, *l, *l1, *ce;
3479 SHELL_VAR *v;
3480 char ibuf[INT_STRLEN_BOUND(int) + 1];
3482 /* First, we need to find the right command to execute. This is tricky,
3483 because we might have already indirected into another keymap. */
3484 ckmap = rl_get_keymap ();
3485 if (ckmap != rl_executing_keymap)
3487 /* bogus. we have to search. only handle one level of indirection. */
3488 for (i = 0; i < KEYMAP_SIZE; i++)
3490 if (ckmap[i].type == ISKMAP && (Keymap)ckmap[i].function == rl_executing_keymap)
3491 break;
3493 if (i < KEYMAP_SIZE)
3494 xkmap = (Keymap)cmd_xmap[i].function;
3495 else
3497 rl_crlf ();
3498 internal_error (_("bash_execute_unix_command: cannot find keymap for command"));
3499 rl_forced_update_display ();
3500 return 1;
3503 else
3504 xkmap = cmd_xmap;
3506 cmd = (char *)xkmap[key].function;
3508 if (cmd == 0)
3510 rl_ding ();
3511 return 1;
3514 ce = rl_get_termcap ("ce");
3515 if (ce) /* clear current line */
3517 fprintf (rl_outstream, "\r");
3518 tputs (ce, 1, putx);
3519 fflush (rl_outstream);
3521 else
3522 rl_crlf (); /* move to a new line */
3524 v = bind_variable ("READLINE_LINE", rl_line_buffer, 0);
3525 if (v)
3526 VSETATTR (v, att_exported);
3527 l = v ? value_cell (v) : 0;
3528 value = inttostr (rl_point, ibuf, sizeof (ibuf));
3529 v = bind_int_variable ("READLINE_POINT", value);
3530 if (v)
3531 VSETATTR (v, att_exported);
3532 array_needs_making = 1;
3534 save_parser_state (&ps);
3535 r = parse_and_execute (cmd, "bash_execute_unix_command", SEVAL_NOHIST|SEVAL_NOFREE);
3536 restore_parser_state (&ps);
3538 v = find_variable ("READLINE_LINE");
3539 l1 = v ? value_cell (v) : 0;
3540 if (l1 != l)
3541 maybe_make_readline_line (value_cell (v));
3542 v = find_variable ("READLINE_POINT");
3543 if (v && legal_number (value_cell (v), &mi))
3545 i = mi;
3546 if (i != rl_point)
3548 rl_point = i;
3549 if (rl_point > rl_end)
3550 rl_point = rl_end;
3551 else if (rl_point < 0)
3552 rl_point = 0;
3556 unbind_variable ("READLINE_LINE");
3557 unbind_variable ("READLINE_POINT");
3558 array_needs_making = 1;
3560 /* and restore the readline buffer and display after command execution. */
3561 rl_forced_update_display ();
3562 return 0;
3565 static void
3566 init_unix_command_map ()
3568 cmd_xmap = rl_make_bare_keymap ();
3571 static int
3572 isolate_sequence (string, ind, need_dquote, startp)
3573 char *string;
3574 int ind, need_dquote, *startp;
3576 register int i;
3577 int c, passc, delim;
3579 for (i = ind; string[i] && whitespace (string[i]); i++)
3581 /* NEED_DQUOTE means that the first non-white character *must* be `"'. */
3582 if (need_dquote && string[i] != '"')
3584 builtin_error (_("%s: first non-whitespace character is not `\"'"), string);
3585 return -1;
3588 /* We can have delimited strings even if NEED_DQUOTE == 0, like the command
3589 string to bind the key sequence to. */
3590 delim = (string[i] == '"' || string[i] == '\'') ? string[i] : 0;
3592 if (startp)
3593 *startp = delim ? ++i : i;
3595 for (passc = 0; c = string[i]; i++)
3597 if (passc)
3599 passc = 0;
3600 continue;
3602 if (c == '\\')
3604 passc++;
3605 continue;
3607 if (c == delim)
3608 break;
3611 if (delim && string[i] != delim)
3613 builtin_error (_("no closing `%c' in %s"), delim, string);
3614 return -1;
3617 return i;
3621 bind_keyseq_to_unix_command (line)
3622 char *line;
3624 Keymap kmap;
3625 char *kseq, *value;
3626 int i, kstart;
3628 if (cmd_xmap == 0)
3629 init_unix_command_map ();
3631 kmap = rl_get_keymap ();
3633 /* We duplicate some of the work done by rl_parse_and_bind here, but
3634 this code only has to handle `"keyseq": ["]command["]' and can
3635 generate an error for anything else. */
3636 i = isolate_sequence (line, 0, 1, &kstart);
3637 if (i < 0)
3638 return -1;
3640 /* Create the key sequence string to pass to rl_generic_bind */
3641 kseq = substring (line, kstart, i);
3643 for ( ; line[i] && line[i] != ':'; i++)
3645 if (line[i] != ':')
3647 builtin_error (_("%s: missing colon separator"), line);
3648 return -1;
3651 i = isolate_sequence (line, i + 1, 0, &kstart);
3652 if (i < 0)
3653 return -1;
3655 /* Create the value string containing the command to execute. */
3656 value = substring (line, kstart, i);
3658 /* Save the command to execute and the key sequence in the CMD_XMAP */
3659 rl_generic_bind (ISMACR, kseq, value, cmd_xmap);
3661 /* and bind the key sequence in the current keymap to a function that
3662 understands how to execute from CMD_XMAP */
3663 rl_bind_keyseq_in_map (kseq, bash_execute_unix_command, kmap);
3665 return 0;
3668 /* Used by the programmable completion code. Complete TEXT as a filename,
3669 but return only directories as matches. Dequotes the filename before
3670 attempting to find matches. */
3671 char **
3672 bash_directory_completion_matches (text)
3673 const char *text;
3675 char **m1;
3676 char *dfn;
3677 int qc;
3679 qc = rl_dispatching ? rl_completion_quote_character : 0;
3680 dfn = bash_dequote_filename ((char *)text, qc);
3681 m1 = rl_completion_matches (dfn, rl_filename_completion_function);
3682 free (dfn);
3684 if (m1 == 0 || m1[0] == 0)
3685 return m1;
3686 /* We don't bother recomputing the lcd of the matches, because it will just
3687 get thrown away by the programmable completion code and recomputed
3688 later. */
3689 (void)bash_ignore_filenames (m1);
3690 return m1;
3693 char *
3694 bash_dequote_text (text)
3695 const char *text;
3697 char *dtxt;
3698 int qc;
3700 qc = (text[0] == '"' || text[0] == '\'') ? text[0] : 0;
3701 dtxt = bash_dequote_filename ((char *)text, qc);
3702 return (dtxt);
3704 #endif /* READLINE */