]> git.ipfire.org Git - thirdparty/bash.git/blob - bashline.c
Bash-4.3 patch 39
[thirdparty/bash.git] / bashline.c
1 /* bashline.c -- Bash's interface to the readline library. */
2
3 /* Copyright (C) 1987-2013 Free Software Foundation, Inc.
4
5 This file is part of GNU Bash, the Bourne Again SHell.
6
7 Bash is free software: you can redistribute it and/or modify
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.
11
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.
16
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/>.
19 */
20
21 #include "config.h"
22
23 #if defined (READLINE)
24
25 #include "bashtypes.h"
26 #include "posixstat.h"
27
28 #if defined (HAVE_UNISTD_H)
29 # include <unistd.h>
30 #endif
31
32 #if defined (HAVE_GRP_H)
33 # include <grp.h>
34 #endif
35
36 #if defined (HAVE_NETDB_H)
37 # include <netdb.h>
38 #endif
39
40 #include <signal.h>
41
42 #include <stdio.h>
43 #include "chartypes.h"
44 #include "bashansi.h"
45 #include "bashintl.h"
46
47 #include "shell.h"
48 #include "input.h"
49 #include "builtins.h"
50 #include "bashhist.h"
51 #include "bashline.h"
52 #include "execute_cmd.h"
53 #include "findcmd.h"
54 #include "pathexp.h"
55 #include "shmbutil.h"
56 #include "trap.h"
57
58 #include "builtins/common.h"
59
60 #include <readline/rlconf.h>
61 #include <readline/readline.h>
62 #include <readline/history.h>
63
64 #include <glob/glob.h>
65
66 #if defined (ALIAS)
67 # include "alias.h"
68 #endif
69
70 #if defined (PROGRAMMABLE_COMPLETION)
71 # include "pcomplete.h"
72 #endif
73
74 /* These should agree with the defines for emacs_mode and vi_mode in
75 rldefs.h, even though that's not a public readline header file. */
76 #ifndef EMACS_EDITING_MODE
77 # define NO_EDITING_MODE -1
78 # define EMACS_EDITING_MODE 1
79 # define VI_EDITING_MODE 0
80 #endif
81
82 #define RL_BOOLEAN_VARIABLE_VALUE(s) ((s)[0] == 'o' && (s)[1] == 'n' && (s)[2] == '\0')
83
84 #if defined (BRACE_COMPLETION)
85 extern int bash_brace_completion __P((int, int));
86 #endif /* BRACE_COMPLETION */
87
88 /* To avoid including curses.h/term.h/termcap.h and that whole mess. */
89 #ifdef _MINIX
90 extern int tputs __P((const char *string, int nlines, void (*outx)(int)));
91 #else
92 extern int tputs __P((const char *string, int nlines, int (*outx)(int)));
93 #endif
94
95 /* Forward declarations */
96
97 /* Functions bound to keys in Readline for Bash users. */
98 static int shell_expand_line __P((int, int));
99 static int display_shell_version __P((int, int));
100 static int operate_and_get_next __P((int, int));
101
102 static int bash_ignore_filenames __P((char **));
103 static int bash_ignore_everything __P((char **));
104
105 #if defined (BANG_HISTORY)
106 static char *history_expand_line_internal __P((char *));
107 static int history_expand_line __P((int, int));
108 static int tcsh_magic_space __P((int, int));
109 #endif /* BANG_HISTORY */
110 #ifdef ALIAS
111 static int alias_expand_line __P((int, int));
112 #endif
113 #if defined (BANG_HISTORY) && defined (ALIAS)
114 static int history_and_alias_expand_line __P((int, int));
115 #endif
116
117 static int bash_forward_shellword __P((int, int));
118 static int bash_backward_shellword __P((int, int));
119 static int bash_kill_shellword __P((int, int));
120 static int bash_backward_kill_shellword __P((int, int));
121
122 /* Helper functions for Readline. */
123 static char *restore_tilde __P((char *, char *));
124 static char *maybe_restore_tilde __P((char *, char *));
125
126 static char *bash_filename_rewrite_hook __P((char *, int));
127
128 static void bash_directory_expansion __P((char **));
129 static int bash_filename_stat_hook __P((char **));
130 static int bash_command_name_stat_hook __P((char **));
131 static int bash_directory_completion_hook __P((char **));
132 static int filename_completion_ignore __P((char **));
133 static int bash_push_line __P((void));
134
135 static int executable_completion __P((const char *, int));
136
137 static rl_icppfunc_t *save_directory_hook __P((void));
138 static void restore_directory_hook __P((rl_icppfunc_t));
139
140 static void cleanup_expansion_error __P((void));
141 static void maybe_make_readline_line __P((char *));
142 static void set_up_new_line __P((char *));
143
144 static int check_redir __P((int));
145 static char **attempt_shell_completion __P((const char *, int, int));
146 static char *variable_completion_function __P((const char *, int));
147 static char *hostname_completion_function __P((const char *, int));
148 static char *command_subst_completion_function __P((const char *, int));
149
150 static void build_history_completion_array __P((void));
151 static char *history_completion_generator __P((const char *, int));
152 static int dynamic_complete_history __P((int, int));
153 static int bash_dabbrev_expand __P((int, int));
154
155 static void initialize_hostname_list __P((void));
156 static void add_host_name __P((char *));
157 static void snarf_hosts_from_file __P((char *));
158 static char **hostnames_matching __P((char *));
159
160 static void _ignore_completion_names __P((char **, sh_ignore_func_t *));
161 static int name_is_acceptable __P((const char *));
162 static int test_for_directory __P((const char *));
163 static int return_zero __P((const char *));
164
165 static char *bash_dequote_filename __P((char *, int));
166 static char *quote_word_break_chars __P((char *));
167 static void set_filename_bstab __P((const char *));
168 static char *bash_quote_filename __P((char *, int, char *));
169
170 #ifdef _MINIX
171 static void putx __P((int));
172 #else
173 static int putx __P((int));
174 #endif
175 static int bash_execute_unix_command __P((int, int));
176 static void init_unix_command_map __P((void));
177 static int isolate_sequence __P((char *, int, int, int *));
178
179 static int set_saved_history __P((void));
180
181 #if defined (ALIAS)
182 static int posix_edit_macros __P((int, int));
183 #endif
184
185 static int bash_event_hook __P((void));
186
187 #if defined (PROGRAMMABLE_COMPLETION)
188 static int find_cmd_start __P((int));
189 static int find_cmd_end __P((int));
190 static char *find_cmd_name __P((int, int *, int *));
191 static char *prog_complete_return __P((const char *, int));
192
193 static char **prog_complete_matches;
194 #endif
195
196 /* Variables used here but defined in other files. */
197 #if defined (BANG_HISTORY)
198 extern int hist_verify;
199 #endif
200
201 extern int current_command_line_count, saved_command_line_count;
202 extern int last_command_exit_value;
203 extern int array_needs_making;
204 extern int posixly_correct, no_symbolic_links;
205 extern int sigalrm_seen;
206 extern char *current_prompt_string, *ps1_prompt;
207 extern STRING_INT_ALIST word_token_alist[];
208 extern sh_builtin_func_t *last_shell_builtin, *this_shell_builtin;
209
210 /* SPECIFIC_COMPLETION_FUNCTIONS specifies that we have individual
211 completion functions which indicate what type of completion should be
212 done (at or before point) that can be bound to key sequences with
213 the readline library. */
214 #define SPECIFIC_COMPLETION_FUNCTIONS
215
216 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
217 static int bash_specific_completion __P((int, rl_compentry_func_t *));
218
219 static int bash_complete_filename_internal __P((int));
220 static int bash_complete_username_internal __P((int));
221 static int bash_complete_hostname_internal __P((int));
222 static int bash_complete_variable_internal __P((int));
223 static int bash_complete_command_internal __P((int));
224
225 static int bash_complete_filename __P((int, int));
226 static int bash_possible_filename_completions __P((int, int));
227 static int bash_complete_username __P((int, int));
228 static int bash_possible_username_completions __P((int, int));
229 static int bash_complete_hostname __P((int, int));
230 static int bash_possible_hostname_completions __P((int, int));
231 static int bash_complete_variable __P((int, int));
232 static int bash_possible_variable_completions __P((int, int));
233 static int bash_complete_command __P((int, int));
234 static int bash_possible_command_completions __P((int, int));
235
236 static char *glob_complete_word __P((const char *, int));
237 static int bash_glob_completion_internal __P((int));
238 static int bash_glob_complete_word __P((int, int));
239 static int bash_glob_expand_word __P((int, int));
240 static int bash_glob_list_expansions __P((int, int));
241
242 #endif /* SPECIFIC_COMPLETION_FUNCTIONS */
243
244 static int edit_and_execute_command __P((int, int, int, char *));
245 #if defined (VI_MODE)
246 static int vi_edit_and_execute_command __P((int, int));
247 static int bash_vi_complete __P((int, int));
248 #endif
249 static int emacs_edit_and_execute_command __P((int, int));
250
251 /* Non-zero once initalize_readline () has been called. */
252 int bash_readline_initialized = 0;
253
254 /* If non-zero, we do hostname completion, breaking words at `@' and
255 trying to complete the stuff after the `@' from our own internal
256 host list. */
257 int perform_hostname_completion = 1;
258
259 /* If non-zero, we don't do command completion on an empty line. */
260 int no_empty_command_completion;
261
262 /* Set FORCE_FIGNORE if you want to honor FIGNORE even if it ignores the
263 only possible matches. Set to 0 if you want to match filenames if they
264 are the only possible matches, even if FIGNORE says to. */
265 int force_fignore = 1;
266
267 /* Perform spelling correction on directory names during word completion */
268 int dircomplete_spelling = 0;
269
270 /* Expand directory names during word/filename completion. */
271 #if DIRCOMPLETE_EXPAND_DEFAULT
272 int dircomplete_expand = 1;
273 int dircomplete_expand_relpath = 1;
274 #else
275 int dircomplete_expand = 0;
276 int dircomplete_expand_relpath = 0;
277 #endif
278
279 /* When non-zero, perform `normal' shell quoting on completed filenames
280 even when the completed name contains a directory name with a shell
281 variable referene, so dollar signs in a filename get quoted appropriately.
282 Set to zero to remove dollar sign (and braces or parens as needed) from
283 the set of characters that will be quoted. */
284 int complete_fullquote = 1;
285
286 static char *bash_completer_word_break_characters = " \t\n\"'@><=;|&(:";
287 static char *bash_nohostname_word_break_characters = " \t\n\"'><=;|&(:";
288 /* )) */
289
290 static const char *default_filename_quote_characters = " \t\n\\\"'@<>=;|&()#$`?*[!:{~"; /*}*/
291 static char *custom_filename_quote_characters = 0;
292 static char filename_bstab[256];
293
294 static rl_hook_func_t *old_rl_startup_hook = (rl_hook_func_t *)NULL;
295
296 static int dot_in_path = 0;
297
298 /* Set to non-zero when dabbrev-expand is running */
299 static int dabbrev_expand_active = 0;
300
301 /* What kind of quoting is performed by bash_quote_filename:
302 COMPLETE_DQUOTE = double-quoting the filename
303 COMPLETE_SQUOTE = single_quoting the filename
304 COMPLETE_BSQUOTE = backslash-quoting special chars in the filename
305 */
306 #define COMPLETE_DQUOTE 1
307 #define COMPLETE_SQUOTE 2
308 #define COMPLETE_BSQUOTE 3
309 static int completion_quoting_style = COMPLETE_BSQUOTE;
310
311 /* Flag values for the final argument to bash_default_completion */
312 #define DEFCOMP_CMDPOS 1
313
314 /* Change the readline VI-mode keymaps into or out of Posix.2 compliance.
315 Called when the shell is put into or out of `posix' mode. */
316 void
317 posix_readline_initialize (on_or_off)
318 int on_or_off;
319 {
320 if (on_or_off)
321 rl_variable_bind ("comment-begin", "#");
322 #if defined (VI_MODE)
323 rl_bind_key_in_map (CTRL ('I'), on_or_off ? rl_insert : rl_complete, vi_insertion_keymap);
324 #endif
325 }
326
327 void
328 reset_completer_word_break_chars ()
329 {
330 rl_completer_word_break_characters = perform_hostname_completion ? savestring (bash_completer_word_break_characters) : savestring (bash_nohostname_word_break_characters);
331 }
332
333 /* When this function returns, rl_completer_word_break_characters points to
334 dynamically allocated memory. */
335 int
336 enable_hostname_completion (on_or_off)
337 int on_or_off;
338 {
339 int old_value;
340 char *at, *nv, *nval;
341
342 old_value = perform_hostname_completion;
343
344 if (on_or_off)
345 {
346 perform_hostname_completion = 1;
347 rl_special_prefixes = "$@";
348 }
349 else
350 {
351 perform_hostname_completion = 0;
352 rl_special_prefixes = "$";
353 }
354
355 /* Now we need to figure out how to appropriately modify and assign
356 rl_completer_word_break_characters depending on whether we want
357 hostname completion on or off. */
358
359 /* If this is the first time this has been called
360 (bash_readline_initialized == 0), use the sames values as before, but
361 allocate new memory for rl_completer_word_break_characters. */
362
363 if (bash_readline_initialized == 0 &&
364 (rl_completer_word_break_characters == 0 ||
365 rl_completer_word_break_characters == rl_basic_word_break_characters))
366 {
367 if (on_or_off)
368 rl_completer_word_break_characters = savestring (bash_completer_word_break_characters);
369 else
370 rl_completer_word_break_characters = savestring (bash_nohostname_word_break_characters);
371 }
372 else
373 {
374 /* See if we have anything to do. */
375 at = strchr (rl_completer_word_break_characters, '@');
376 if ((at == 0 && on_or_off == 0) || (at != 0 && on_or_off != 0))
377 return old_value;
378
379 /* We have something to do. Do it. */
380 nval = (char *)xmalloc (strlen (rl_completer_word_break_characters) + 1 + on_or_off);
381
382 if (on_or_off == 0)
383 {
384 /* Turn it off -- just remove `@' from word break chars. We want
385 to remove all occurrences of `@' from the char list, so we loop
386 rather than just copy the rest of the list over AT. */
387 for (nv = nval, at = rl_completer_word_break_characters; *at; )
388 if (*at != '@')
389 *nv++ = *at++;
390 else
391 at++;
392 *nv = '\0';
393 }
394 else
395 {
396 nval[0] = '@';
397 strcpy (nval + 1, rl_completer_word_break_characters);
398 }
399
400 free (rl_completer_word_break_characters);
401 rl_completer_word_break_characters = nval;
402 }
403
404 return (old_value);
405 }
406
407 /* Called once from parse.y if we are going to use readline. */
408 void
409 initialize_readline ()
410 {
411 rl_command_func_t *func;
412 char kseq[2];
413
414 if (bash_readline_initialized)
415 return;
416
417 rl_terminal_name = get_string_value ("TERM");
418 rl_instream = stdin;
419 rl_outstream = stderr;
420
421 /* Allow conditional parsing of the ~/.inputrc file. */
422 rl_readline_name = "Bash";
423
424 /* Add bindable names before calling rl_initialize so they may be
425 referenced in the various inputrc files. */
426 rl_add_defun ("shell-expand-line", shell_expand_line, -1);
427 #ifdef BANG_HISTORY
428 rl_add_defun ("history-expand-line", history_expand_line, -1);
429 rl_add_defun ("magic-space", tcsh_magic_space, -1);
430 #endif
431
432 rl_add_defun ("shell-forward-word", bash_forward_shellword, -1);
433 rl_add_defun ("shell-backward-word", bash_backward_shellword, -1);
434 rl_add_defun ("shell-kill-word", bash_kill_shellword, -1);
435 rl_add_defun ("shell-backward-kill-word", bash_backward_kill_shellword, -1);
436
437 #ifdef ALIAS
438 rl_add_defun ("alias-expand-line", alias_expand_line, -1);
439 # ifdef BANG_HISTORY
440 rl_add_defun ("history-and-alias-expand-line", history_and_alias_expand_line, -1);
441 # endif
442 #endif
443
444 /* Backwards compatibility. */
445 rl_add_defun ("insert-last-argument", rl_yank_last_arg, -1);
446
447 rl_add_defun ("operate-and-get-next", operate_and_get_next, -1);
448 rl_add_defun ("display-shell-version", display_shell_version, -1);
449 rl_add_defun ("edit-and-execute-command", emacs_edit_and_execute_command, -1);
450
451 #if defined (BRACE_COMPLETION)
452 rl_add_defun ("complete-into-braces", bash_brace_completion, -1);
453 #endif
454
455 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
456 rl_add_defun ("complete-filename", bash_complete_filename, -1);
457 rl_add_defun ("possible-filename-completions", bash_possible_filename_completions, -1);
458 rl_add_defun ("complete-username", bash_complete_username, -1);
459 rl_add_defun ("possible-username-completions", bash_possible_username_completions, -1);
460 rl_add_defun ("complete-hostname", bash_complete_hostname, -1);
461 rl_add_defun ("possible-hostname-completions", bash_possible_hostname_completions, -1);
462 rl_add_defun ("complete-variable", bash_complete_variable, -1);
463 rl_add_defun ("possible-variable-completions", bash_possible_variable_completions, -1);
464 rl_add_defun ("complete-command", bash_complete_command, -1);
465 rl_add_defun ("possible-command-completions", bash_possible_command_completions, -1);
466 rl_add_defun ("glob-complete-word", bash_glob_complete_word, -1);
467 rl_add_defun ("glob-expand-word", bash_glob_expand_word, -1);
468 rl_add_defun ("glob-list-expansions", bash_glob_list_expansions, -1);
469 #endif
470
471 rl_add_defun ("dynamic-complete-history", dynamic_complete_history, -1);
472 rl_add_defun ("dabbrev-expand", bash_dabbrev_expand, -1);
473
474 /* Bind defaults before binding our custom shell keybindings. */
475 if (RL_ISSTATE(RL_STATE_INITIALIZED) == 0)
476 rl_initialize ();
477
478 /* Bind up our special shell functions. */
479 rl_bind_key_if_unbound_in_map (CTRL('E'), shell_expand_line, emacs_meta_keymap);
480
481 #ifdef BANG_HISTORY
482 rl_bind_key_if_unbound_in_map ('^', history_expand_line, emacs_meta_keymap);
483 #endif
484
485 rl_bind_key_if_unbound_in_map (CTRL ('O'), operate_and_get_next, emacs_standard_keymap);
486 rl_bind_key_if_unbound_in_map (CTRL ('V'), display_shell_version, emacs_ctlx_keymap);
487
488 /* In Bash, the user can switch editing modes with "set -o [vi emacs]",
489 so it is not necessary to allow C-M-j for context switching. Turn
490 off this occasionally confusing behaviour. */
491 kseq[0] = CTRL('J');
492 kseq[1] = '\0';
493 func = rl_function_of_keyseq (kseq, emacs_meta_keymap, (int *)NULL);
494 if (func == rl_vi_editing_mode)
495 rl_unbind_key_in_map (CTRL('J'), emacs_meta_keymap);
496 kseq[0] = CTRL('M');
497 func = rl_function_of_keyseq (kseq, emacs_meta_keymap, (int *)NULL);
498 if (func == rl_vi_editing_mode)
499 rl_unbind_key_in_map (CTRL('M'), emacs_meta_keymap);
500 #if defined (VI_MODE)
501 rl_unbind_key_in_map (CTRL('E'), vi_movement_keymap);
502 #endif
503
504 #if defined (BRACE_COMPLETION)
505 rl_bind_key_if_unbound_in_map ('{', bash_brace_completion, emacs_meta_keymap); /*}*/
506 #endif /* BRACE_COMPLETION */
507
508 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
509 rl_bind_key_if_unbound_in_map ('/', bash_complete_filename, emacs_meta_keymap);
510 rl_bind_key_if_unbound_in_map ('/', bash_possible_filename_completions, emacs_ctlx_keymap);
511
512 /* Have to jump through hoops here because there is a default binding for
513 M-~ (rl_tilde_expand) */
514 kseq[0] = '~';
515 kseq[1] = '\0';
516 func = rl_function_of_keyseq (kseq, emacs_meta_keymap, (int *)NULL);
517 if (func == 0 || func == rl_tilde_expand)
518 rl_bind_keyseq_in_map (kseq, bash_complete_username, emacs_meta_keymap);
519
520 rl_bind_key_if_unbound_in_map ('~', bash_possible_username_completions, emacs_ctlx_keymap);
521
522 rl_bind_key_if_unbound_in_map ('@', bash_complete_hostname, emacs_meta_keymap);
523 rl_bind_key_if_unbound_in_map ('@', bash_possible_hostname_completions, emacs_ctlx_keymap);
524
525 rl_bind_key_if_unbound_in_map ('$', bash_complete_variable, emacs_meta_keymap);
526 rl_bind_key_if_unbound_in_map ('$', bash_possible_variable_completions, emacs_ctlx_keymap);
527
528 rl_bind_key_if_unbound_in_map ('!', bash_complete_command, emacs_meta_keymap);
529 rl_bind_key_if_unbound_in_map ('!', bash_possible_command_completions, emacs_ctlx_keymap);
530
531 rl_bind_key_if_unbound_in_map ('g', bash_glob_complete_word, emacs_meta_keymap);
532 rl_bind_key_if_unbound_in_map ('*', bash_glob_expand_word, emacs_ctlx_keymap);
533 rl_bind_key_if_unbound_in_map ('g', bash_glob_list_expansions, emacs_ctlx_keymap);
534
535 #endif /* SPECIFIC_COMPLETION_FUNCTIONS */
536
537 kseq[0] = TAB;
538 kseq[1] = '\0';
539 func = rl_function_of_keyseq (kseq, emacs_meta_keymap, (int *)NULL);
540 if (func == 0 || func == rl_tab_insert)
541 rl_bind_key_in_map (TAB, dynamic_complete_history, emacs_meta_keymap);
542
543 /* Tell the completer that we want a crack first. */
544 rl_attempted_completion_function = attempt_shell_completion;
545
546 /* Tell the completer that we might want to follow symbolic links or
547 do other expansion on directory names. */
548 set_directory_hook ();
549
550 rl_filename_rewrite_hook = bash_filename_rewrite_hook;
551
552 rl_filename_stat_hook = bash_filename_stat_hook;
553
554 /* Tell the filename completer we want a chance to ignore some names. */
555 rl_ignore_some_completions_function = filename_completion_ignore;
556
557 /* Bind C-xC-e to invoke emacs and run result as commands. */
558 rl_bind_key_if_unbound_in_map (CTRL ('E'), emacs_edit_and_execute_command, emacs_ctlx_keymap);
559 #if defined (VI_MODE)
560 rl_bind_key_if_unbound_in_map ('v', vi_edit_and_execute_command, vi_movement_keymap);
561 # if defined (ALIAS)
562 rl_bind_key_if_unbound_in_map ('@', posix_edit_macros, vi_movement_keymap);
563 # endif
564
565 rl_bind_key_in_map ('\\', bash_vi_complete, vi_movement_keymap);
566 rl_bind_key_in_map ('*', bash_vi_complete, vi_movement_keymap);
567 rl_bind_key_in_map ('=', bash_vi_complete, vi_movement_keymap);
568 #endif
569
570 rl_completer_quote_characters = "'\"";
571
572 /* This sets rl_completer_word_break_characters and rl_special_prefixes
573 to the appropriate values, depending on whether or not hostname
574 completion is enabled. */
575 enable_hostname_completion (perform_hostname_completion);
576
577 /* characters that need to be quoted when appearing in filenames. */
578 rl_filename_quote_characters = default_filename_quote_characters;
579 set_filename_bstab (rl_filename_quote_characters);
580
581 rl_filename_quoting_function = bash_quote_filename;
582 rl_filename_dequoting_function = bash_dequote_filename;
583 rl_char_is_quoted_p = char_is_quoted;
584
585 #if 0
586 /* This is superfluous and makes it impossible to use tab completion in
587 vi mode even when explicitly binding it in ~/.inputrc. sv_strict_posix()
588 should already have called posix_readline_initialize() when
589 posixly_correct was set. */
590 if (posixly_correct)
591 posix_readline_initialize (1);
592 #endif
593
594 bash_readline_initialized = 1;
595 }
596
597 void
598 bashline_reinitialize ()
599 {
600 bash_readline_initialized = 0;
601 }
602
603 void
604 bashline_set_event_hook ()
605 {
606 rl_signal_event_hook = bash_event_hook;
607 }
608
609 void
610 bashline_reset_event_hook ()
611 {
612 rl_signal_event_hook = 0;
613 }
614
615 /* On Sun systems at least, rl_attempted_completion_function can end up
616 getting set to NULL, and rl_completion_entry_function set to do command
617 word completion if Bash is interrupted while trying to complete a command
618 word. This just resets all the completion functions to the right thing.
619 It's called from throw_to_top_level(). */
620 void
621 bashline_reset ()
622 {
623 tilde_initialize ();
624 rl_attempted_completion_function = attempt_shell_completion;
625 rl_completion_entry_function = NULL;
626 rl_ignore_some_completions_function = filename_completion_ignore;
627 rl_filename_quote_characters = default_filename_quote_characters;
628 set_filename_bstab (rl_filename_quote_characters);
629
630 set_directory_hook ();
631 rl_filename_stat_hook = bash_filename_stat_hook;
632
633 bashline_reset_event_hook ();
634 }
635
636 /* Contains the line to push into readline. */
637 static char *push_to_readline = (char *)NULL;
638
639 /* Push the contents of push_to_readline into the
640 readline buffer. */
641 static int
642 bash_push_line ()
643 {
644 if (push_to_readline)
645 {
646 rl_insert_text (push_to_readline);
647 free (push_to_readline);
648 push_to_readline = (char *)NULL;
649 rl_startup_hook = old_rl_startup_hook;
650 }
651 return 0;
652 }
653
654 /* Call this to set the initial text for the next line to read
655 from readline. */
656 int
657 bash_re_edit (line)
658 char *line;
659 {
660 FREE (push_to_readline);
661
662 push_to_readline = savestring (line);
663 old_rl_startup_hook = rl_startup_hook;
664 rl_startup_hook = bash_push_line;
665
666 return (0);
667 }
668
669 static int
670 display_shell_version (count, c)
671 int count, c;
672 {
673 rl_crlf ();
674 show_shell_version (0);
675 putc ('\r', rl_outstream);
676 fflush (rl_outstream);
677 rl_on_new_line ();
678 rl_redisplay ();
679 return 0;
680 }
681
682 /* **************************************************************** */
683 /* */
684 /* Readline Stuff */
685 /* */
686 /* **************************************************************** */
687
688 /* If the user requests hostname completion, then simply build a list
689 of hosts, and complete from that forever more, or at least until
690 HOSTFILE is unset. */
691
692 /* THIS SHOULD BE A STRINGLIST. */
693 /* The kept list of hostnames. */
694 static char **hostname_list = (char **)NULL;
695
696 /* The physical size of the above list. */
697 static int hostname_list_size;
698
699 /* The number of hostnames in the above list. */
700 static int hostname_list_length;
701
702 /* Whether or not HOSTNAME_LIST has been initialized. */
703 int hostname_list_initialized = 0;
704
705 /* Initialize the hostname completion table. */
706 static void
707 initialize_hostname_list ()
708 {
709 char *temp;
710
711 temp = get_string_value ("HOSTFILE");
712 if (temp == 0)
713 temp = get_string_value ("hostname_completion_file");
714 if (temp == 0)
715 temp = DEFAULT_HOSTS_FILE;
716
717 snarf_hosts_from_file (temp);
718
719 if (hostname_list)
720 hostname_list_initialized++;
721 }
722
723 /* Add NAME to the list of hosts. */
724 static void
725 add_host_name (name)
726 char *name;
727 {
728 if (hostname_list_length + 2 > hostname_list_size)
729 {
730 hostname_list_size = (hostname_list_size + 32) - (hostname_list_size % 32);
731 hostname_list = strvec_resize (hostname_list, hostname_list_size);
732 }
733
734 hostname_list[hostname_list_length++] = savestring (name);
735 hostname_list[hostname_list_length] = (char *)NULL;
736 }
737
738 #define cr_whitespace(c) ((c) == '\r' || (c) == '\n' || whitespace(c))
739
740 static void
741 snarf_hosts_from_file (filename)
742 char *filename;
743 {
744 FILE *file;
745 char *temp, buffer[256], name[256];
746 register int i, start;
747
748 file = fopen (filename, "r");
749 if (file == 0)
750 return;
751
752 while (temp = fgets (buffer, 255, file))
753 {
754 /* Skip to first character. */
755 for (i = 0; buffer[i] && cr_whitespace (buffer[i]); i++)
756 ;
757
758 /* If comment or blank line, ignore. */
759 if (buffer[i] == '\0' || buffer[i] == '#')
760 continue;
761
762 /* If `preprocessor' directive, do the include. */
763 if (strncmp (buffer + i, "$include ", 9) == 0)
764 {
765 char *incfile, *t;
766
767 /* Find start of filename. */
768 for (incfile = buffer + i + 9; *incfile && whitespace (*incfile); incfile++)
769 ;
770
771 /* Find end of filename. */
772 for (t = incfile; *t && cr_whitespace (*t) == 0; t++)
773 ;
774
775 *t = '\0';
776
777 snarf_hosts_from_file (incfile);
778 continue;
779 }
780
781 /* Skip internet address if present. */
782 if (DIGIT (buffer[i]))
783 for (; buffer[i] && cr_whitespace (buffer[i]) == 0; i++);
784
785 /* Gobble up names. Each name is separated with whitespace. */
786 while (buffer[i])
787 {
788 for (; cr_whitespace (buffer[i]); i++)
789 ;
790 if (buffer[i] == '\0' || buffer[i] == '#')
791 break;
792
793 /* Isolate the current word. */
794 for (start = i; buffer[i] && cr_whitespace (buffer[i]) == 0; i++)
795 ;
796 if (i == start)
797 continue;
798 strncpy (name, buffer + start, i - start);
799 name[i - start] = '\0';
800 add_host_name (name);
801 }
802 }
803 fclose (file);
804 }
805
806 /* Return the hostname list. */
807 char **
808 get_hostname_list ()
809 {
810 if (hostname_list_initialized == 0)
811 initialize_hostname_list ();
812 return (hostname_list);
813 }
814
815 void
816 clear_hostname_list ()
817 {
818 register int i;
819
820 if (hostname_list_initialized == 0)
821 return;
822 for (i = 0; i < hostname_list_length; i++)
823 free (hostname_list[i]);
824 hostname_list_length = hostname_list_initialized = 0;
825 }
826
827 /* Return a NULL terminated list of hostnames which begin with TEXT.
828 Initialize the hostname list the first time if necessary.
829 The array is malloc ()'ed, but not the individual strings. */
830 static char **
831 hostnames_matching (text)
832 char *text;
833 {
834 register int i, len, nmatch, rsize;
835 char **result;
836
837 if (hostname_list_initialized == 0)
838 initialize_hostname_list ();
839
840 if (hostname_list_initialized == 0)
841 return ((char **)NULL);
842
843 /* Special case. If TEXT consists of nothing, then the whole list is
844 what is desired. */
845 if (*text == '\0')
846 {
847 result = strvec_create (1 + hostname_list_length);
848 for (i = 0; i < hostname_list_length; i++)
849 result[i] = hostname_list[i];
850 result[i] = (char *)NULL;
851 return (result);
852 }
853
854 /* Scan until found, or failure. */
855 len = strlen (text);
856 result = (char **)NULL;
857 for (i = nmatch = rsize = 0; i < hostname_list_length; i++)
858 {
859 if (STREQN (text, hostname_list[i], len) == 0)
860 continue;
861
862 /* OK, it matches. Add it to the list. */
863 if (nmatch >= (rsize - 1))
864 {
865 rsize = (rsize + 16) - (rsize % 16);
866 result = strvec_resize (result, rsize);
867 }
868
869 result[nmatch++] = hostname_list[i];
870 }
871 if (nmatch)
872 result[nmatch] = (char *)NULL;
873 return (result);
874 }
875
876 /* The equivalent of the Korn shell C-o operate-and-get-next-history-line
877 editing command. */
878 static int saved_history_line_to_use = -1;
879 static int last_saved_history_line = -1;
880
881 #define HISTORY_FULL() (history_is_stifled () && history_length >= history_max_entries)
882
883 static int
884 set_saved_history ()
885 {
886 /* XXX - compensate for assumption that history was `shuffled' if it was
887 actually not. */
888 if (HISTORY_FULL () &&
889 hist_last_line_added == 0 &&
890 saved_history_line_to_use < history_length - 1)
891 saved_history_line_to_use++;
892
893 if (saved_history_line_to_use >= 0)
894 {
895 rl_get_previous_history (history_length - saved_history_line_to_use, 0);
896 last_saved_history_line = saved_history_line_to_use;
897 }
898 saved_history_line_to_use = -1;
899 rl_startup_hook = old_rl_startup_hook;
900 return (0);
901 }
902
903 static int
904 operate_and_get_next (count, c)
905 int count, c;
906 {
907 int where;
908
909 /* Accept the current line. */
910 rl_newline (1, c);
911
912 /* Find the current line, and find the next line to use. */
913 where = where_history ();
914
915 if (HISTORY_FULL () || (where >= history_length - 1))
916 saved_history_line_to_use = where;
917 else
918 saved_history_line_to_use = where + 1;
919
920 old_rl_startup_hook = rl_startup_hook;
921 rl_startup_hook = set_saved_history;
922
923 return 0;
924 }
925
926 /* This vi mode command causes VI_EDIT_COMMAND to be run on the current
927 command being entered (if no explicit argument is given), otherwise on
928 a command from the history file. */
929
930 #define VI_EDIT_COMMAND "fc -e \"${VISUAL:-${EDITOR:-vi}}\""
931 #define EMACS_EDIT_COMMAND "fc -e \"${VISUAL:-${EDITOR:-emacs}}\""
932 #define POSIX_VI_EDIT_COMMAND "fc -e vi"
933
934 static int
935 edit_and_execute_command (count, c, editing_mode, edit_command)
936 int count, c, editing_mode;
937 char *edit_command;
938 {
939 char *command, *metaval;
940 int r, rrs, metaflag;
941 sh_parser_state_t ps;
942
943 rrs = rl_readline_state;
944 saved_command_line_count = current_command_line_count;
945
946 /* Accept the current line. */
947 rl_newline (1, c);
948
949 if (rl_explicit_arg)
950 {
951 command = (char *)xmalloc (strlen (edit_command) + 8);
952 sprintf (command, "%s %d", edit_command, count);
953 }
954 else
955 {
956 /* Take the command we were just editing, add it to the history file,
957 then call fc to operate on it. We have to add a dummy command to
958 the end of the history because fc ignores the last command (assumes
959 it's supposed to deal with the command before the `fc'). */
960 /* This breaks down when using command-oriented history and are not
961 finished with the command, so we should not ignore the last command */
962 using_history ();
963 current_command_line_count++; /* for rl_newline above */
964 bash_add_history (rl_line_buffer);
965 current_command_line_count = 0; /* for dummy history entry */
966 bash_add_history ("");
967 history_lines_this_session++;
968 using_history ();
969 command = savestring (edit_command);
970 }
971
972 metaval = rl_variable_value ("input-meta");
973 metaflag = RL_BOOLEAN_VARIABLE_VALUE (metaval);
974
975 /* Now, POSIX.1-2001 and SUSv3 say that the commands executed from the
976 temporary file should be placed into the history. We don't do that
977 yet. */
978 if (rl_deprep_term_function)
979 (*rl_deprep_term_function) ();
980 save_parser_state (&ps);
981 r = parse_and_execute (command, (editing_mode == VI_EDITING_MODE) ? "v" : "C-xC-e", SEVAL_NOHIST);
982 restore_parser_state (&ps);
983 if (rl_prep_term_function)
984 (*rl_prep_term_function) (metaflag);
985
986 current_command_line_count = saved_command_line_count;
987
988 /* Now erase the contents of the current line and undo the effects of the
989 rl_accept_line() above. We don't even want to make the text we just
990 executed available for undoing. */
991 rl_line_buffer[0] = '\0'; /* XXX */
992 rl_point = rl_end = 0;
993 rl_done = 0;
994 rl_readline_state = rrs;
995
996 rl_forced_update_display ();
997
998 return r;
999 }
1000
1001 #if defined (VI_MODE)
1002 static int
1003 vi_edit_and_execute_command (count, c)
1004 int count, c;
1005 {
1006 if (posixly_correct)
1007 return (edit_and_execute_command (count, c, VI_EDITING_MODE, POSIX_VI_EDIT_COMMAND));
1008 else
1009 return (edit_and_execute_command (count, c, VI_EDITING_MODE, VI_EDIT_COMMAND));
1010 }
1011 #endif /* VI_MODE */
1012
1013 static int
1014 emacs_edit_and_execute_command (count, c)
1015 int count, c;
1016 {
1017 return (edit_and_execute_command (count, c, EMACS_EDITING_MODE, EMACS_EDIT_COMMAND));
1018 }
1019
1020 #if defined (ALIAS)
1021 static int
1022 posix_edit_macros (count, key)
1023 int count, key;
1024 {
1025 int c;
1026 char alias_name[3], *alias_value, *macro;
1027
1028 c = rl_read_key ();
1029 alias_name[0] = '_';
1030 alias_name[1] = c;
1031 alias_name[2] = '\0';
1032
1033 alias_value = get_alias_value (alias_name);
1034 if (alias_value && *alias_value)
1035 {
1036 macro = savestring (alias_value);
1037 rl_push_macro_input (macro);
1038 }
1039 return 0;
1040 }
1041 #endif
1042
1043 /* Bindable commands that move `shell-words': that is, sequences of
1044 non-unquoted-metacharacters. */
1045
1046 #define WORDDELIM(c) (shellmeta(c) || shellblank(c))
1047
1048 static int
1049 bash_forward_shellword (count, key)
1050 int count, key;
1051 {
1052 size_t slen;
1053 int sindex, c, p;
1054 DECLARE_MBSTATE;
1055
1056 if (count < 0)
1057 return (bash_backward_shellword (-count, key));
1058
1059 /* The tricky part of this is deciding whether or not the first character
1060 we're on is an unquoted metacharacter. Not completely handled yet. */
1061 /* XXX - need to test this stuff with backslash-escaped shell
1062 metacharacters and unclosed single- and double-quoted strings. */
1063
1064 p = rl_point;
1065 slen = rl_end;
1066
1067 while (count)
1068 {
1069 if (p == rl_end)
1070 {
1071 rl_point = rl_end;
1072 return 0;
1073 }
1074
1075 /* Are we in a quoted string? If we are, move to the end of the quoted
1076 string and continue the outer loop. We only want quoted strings, not
1077 backslash-escaped characters, but char_is_quoted doesn't
1078 differentiate. */
1079 if (char_is_quoted (rl_line_buffer, p) && p > 0 && rl_line_buffer[p-1] != '\\')
1080 {
1081 do
1082 ADVANCE_CHAR (rl_line_buffer, slen, p);
1083 while (p < rl_end && char_is_quoted (rl_line_buffer, p));
1084 count--;
1085 continue;
1086 }
1087
1088 /* Rest of code assumes we are not in a quoted string. */
1089 /* Move forward until we hit a non-metacharacter. */
1090 while (p < rl_end && (c = rl_line_buffer[p]) && WORDDELIM (c))
1091 {
1092 switch (c)
1093 {
1094 default:
1095 ADVANCE_CHAR (rl_line_buffer, slen, p);
1096 continue; /* straight back to loop, don't increment p */
1097 case '\\':
1098 if (p < rl_end && rl_line_buffer[p])
1099 ADVANCE_CHAR (rl_line_buffer, slen, p);
1100 break;
1101 case '\'':
1102 p = skip_to_delim (rl_line_buffer, ++p, "'", SD_NOJMP);
1103 break;
1104 case '"':
1105 p = skip_to_delim (rl_line_buffer, ++p, "\"", SD_NOJMP);
1106 break;
1107 }
1108
1109 if (p < rl_end)
1110 p++;
1111 }
1112
1113 if (rl_line_buffer[p] == 0 || p == rl_end)
1114 {
1115 rl_point = rl_end;
1116 rl_ding ();
1117 return 0;
1118 }
1119
1120 /* Now move forward until we hit a non-quoted metacharacter or EOL */
1121 while (p < rl_end && (c = rl_line_buffer[p]) && WORDDELIM (c) == 0)
1122 {
1123 switch (c)
1124 {
1125 default:
1126 ADVANCE_CHAR (rl_line_buffer, slen, p);
1127 continue; /* straight back to loop, don't increment p */
1128 case '\\':
1129 if (p < rl_end && rl_line_buffer[p])
1130 ADVANCE_CHAR (rl_line_buffer, slen, p);
1131 break;
1132 case '\'':
1133 p = skip_to_delim (rl_line_buffer, ++p, "'", SD_NOJMP);
1134 break;
1135 case '"':
1136 p = skip_to_delim (rl_line_buffer, ++p, "\"", SD_NOJMP);
1137 break;
1138 }
1139
1140 if (p < rl_end)
1141 p++;
1142 }
1143
1144 if (p == rl_end || rl_line_buffer[p] == 0)
1145 {
1146 rl_point = rl_end;
1147 return (0);
1148 }
1149
1150 count--;
1151 }
1152
1153 rl_point = p;
1154 return (0);
1155 }
1156
1157 static int
1158 bash_backward_shellword (count, key)
1159 int count, key;
1160 {
1161 size_t slen;
1162 int sindex, c, p;
1163 DECLARE_MBSTATE;
1164
1165 if (count < 0)
1166 return (bash_forward_shellword (-count, key));
1167
1168 p = rl_point;
1169 slen = rl_end;
1170
1171 while (count)
1172 {
1173 if (p == 0)
1174 {
1175 rl_point = 0;
1176 return 0;
1177 }
1178
1179 /* Move backward until we hit a non-metacharacter. */
1180 while (p > 0)
1181 {
1182 c = rl_line_buffer[p];
1183 if (WORDDELIM (c) && char_is_quoted (rl_line_buffer, p) == 0)
1184 BACKUP_CHAR (rl_line_buffer, slen, p);
1185 break;
1186 }
1187
1188 if (p == 0)
1189 {
1190 rl_point = 0;
1191 return 0;
1192 }
1193
1194 /* Now move backward until we hit a metacharacter or BOL. */
1195 while (p > 0)
1196 {
1197 c = rl_line_buffer[p];
1198 if (WORDDELIM (c) && char_is_quoted (rl_line_buffer, p) == 0)
1199 break;
1200 BACKUP_CHAR (rl_line_buffer, slen, p);
1201 }
1202
1203 count--;
1204 }
1205
1206 rl_point = p;
1207 return 0;
1208 }
1209
1210 static int
1211 bash_kill_shellword (count, key)
1212 int count, key;
1213 {
1214 int p;
1215
1216 if (count < 0)
1217 return (bash_backward_kill_shellword (-count, key));
1218
1219 p = rl_point;
1220 bash_forward_shellword (count, key);
1221
1222 if (rl_point != p)
1223 rl_kill_text (p, rl_point);
1224
1225 rl_point = p;
1226 if (rl_editing_mode == 1) /* 1 == emacs_mode */
1227 rl_mark = rl_point;
1228
1229 return 0;
1230 }
1231
1232 static int
1233 bash_backward_kill_shellword (count, key)
1234 int count, key;
1235 {
1236 int p;
1237
1238 if (count < 0)
1239 return (bash_kill_shellword (-count, key));
1240
1241 p = rl_point;
1242 bash_backward_shellword (count, key);
1243
1244 if (rl_point != p)
1245 rl_kill_text (p, rl_point);
1246
1247 if (rl_editing_mode == 1) /* 1 == emacs_mode */
1248 rl_mark = rl_point;
1249
1250 return 0;
1251 }
1252
1253
1254 /* **************************************************************** */
1255 /* */
1256 /* How To Do Shell Completion */
1257 /* */
1258 /* **************************************************************** */
1259
1260 #define COMMAND_SEPARATORS ";|&{(`"
1261 /* )} */
1262 #define COMMAND_SEPARATORS_PLUS_WS ";|&{(` \t"
1263 /* )} */
1264
1265 /* check for redirections and other character combinations that are not
1266 command separators */
1267 static int
1268 check_redir (ti)
1269 int ti;
1270 {
1271 register int this_char, prev_char;
1272
1273 /* Handle the two character tokens `>&', `<&', and `>|'.
1274 We are not in a command position after one of these. */
1275 this_char = rl_line_buffer[ti];
1276 prev_char = rl_line_buffer[ti - 1];
1277
1278 if ((this_char == '&' && (prev_char == '<' || prev_char == '>')) ||
1279 (this_char == '|' && prev_char == '>'))
1280 return (1);
1281 else if (this_char == '{' && prev_char == '$') /*}*/
1282 return (1);
1283 #if 0 /* Not yet */
1284 else if (this_char == '(' && prev_char == '$') /*)*/
1285 return (1);
1286 else if (this_char == '(' && prev_char == '<') /*)*/
1287 return (1);
1288 #if defined (EXTENDED_GLOB)
1289 else if (extended_glob && this_char == '(' && prev_char == '!') /*)*/
1290 return (1);
1291 #endif
1292 #endif
1293 else if (char_is_quoted (rl_line_buffer, ti))
1294 return (1);
1295 return (0);
1296 }
1297
1298 #if defined (PROGRAMMABLE_COMPLETION)
1299 /*
1300 * XXX - because of the <= start test, and setting os = s+1, this can
1301 * potentially return os > start. This is probably not what we want to
1302 * happen, but fix later after 2.05a-release.
1303 */
1304 static int
1305 find_cmd_start (start)
1306 int start;
1307 {
1308 register int s, os;
1309
1310 os = 0;
1311 /* Flags == SD_NOJMP only because we want to skip over command substitutions
1312 in assignment statements. Have to test whether this affects `standalone'
1313 command substitutions as individual words. */
1314 while (((s = skip_to_delim (rl_line_buffer, os, COMMAND_SEPARATORS, SD_NOJMP/*|SD_NOSKIPCMD*/)) <= start) &&
1315 rl_line_buffer[s])
1316 os = s+1;
1317 return os;
1318 }
1319
1320 static int
1321 find_cmd_end (end)
1322 int end;
1323 {
1324 register int e;
1325
1326 e = skip_to_delim (rl_line_buffer, end, COMMAND_SEPARATORS, SD_NOJMP);
1327 return e;
1328 }
1329
1330 static char *
1331 find_cmd_name (start, sp, ep)
1332 int start;
1333 int *sp, *ep;
1334 {
1335 char *name;
1336 register int s, e;
1337
1338 for (s = start; whitespace (rl_line_buffer[s]); s++)
1339 ;
1340
1341 /* skip until a shell break character */
1342 e = skip_to_delim (rl_line_buffer, s, "()<>;&| \t\n", SD_NOJMP);
1343
1344 name = substring (rl_line_buffer, s, e);
1345
1346 if (sp)
1347 *sp = s;
1348 if (ep)
1349 *ep = e;
1350
1351 return (name);
1352 }
1353
1354 static char *
1355 prog_complete_return (text, matchnum)
1356 const char *text;
1357 int matchnum;
1358 {
1359 static int ind;
1360
1361 if (matchnum == 0)
1362 ind = 0;
1363
1364 if (prog_complete_matches == 0 || prog_complete_matches[ind] == 0)
1365 return (char *)NULL;
1366 return (prog_complete_matches[ind++]);
1367 }
1368
1369 #endif /* PROGRAMMABLE_COMPLETION */
1370
1371 /* Do some completion on TEXT. The indices of TEXT in RL_LINE_BUFFER are
1372 at START and END. Return an array of matches, or NULL if none. */
1373 static char **
1374 attempt_shell_completion (text, start, end)
1375 const char *text;
1376 int start, end;
1377 {
1378 int in_command_position, ti, saveti, qc, dflags;
1379 char **matches, *command_separator_chars;
1380 #if defined (PROGRAMMABLE_COMPLETION)
1381 int have_progcomps, was_assignment;
1382 #endif
1383
1384 command_separator_chars = COMMAND_SEPARATORS;
1385 matches = (char **)NULL;
1386 rl_ignore_some_completions_function = filename_completion_ignore;
1387
1388 rl_filename_quote_characters = default_filename_quote_characters;
1389 set_filename_bstab (rl_filename_quote_characters);
1390 set_directory_hook ();
1391 rl_filename_stat_hook = bash_filename_stat_hook;
1392
1393 /* Determine if this could be a command word. It is if it appears at
1394 the start of the line (ignoring preceding whitespace), or if it
1395 appears after a character that separates commands. It cannot be a
1396 command word if we aren't at the top-level prompt. */
1397 ti = start - 1;
1398 saveti = qc = -1;
1399
1400 while ((ti > -1) && (whitespace (rl_line_buffer[ti])))
1401 ti--;
1402
1403 #if 1
1404 /* If this is an open quote, maybe we're trying to complete a quoted
1405 command name. */
1406 if (ti >= 0 && (rl_line_buffer[ti] == '"' || rl_line_buffer[ti] == '\''))
1407 {
1408 qc = rl_line_buffer[ti];
1409 saveti = ti--;
1410 while (ti > -1 && (whitespace (rl_line_buffer[ti])))
1411 ti--;
1412 }
1413 #endif
1414
1415 in_command_position = 0;
1416 if (ti < 0)
1417 {
1418 /* Only do command completion at the start of a line when we
1419 are prompting at the top level. */
1420 if (current_prompt_string == ps1_prompt)
1421 in_command_position++;
1422 else if (parser_in_command_position ())
1423 in_command_position++;
1424 }
1425 else if (member (rl_line_buffer[ti], command_separator_chars))
1426 {
1427 in_command_position++;
1428
1429 if (check_redir (ti) == 1)
1430 in_command_position = 0;
1431 }
1432 else
1433 {
1434 /* This still could be in command position. It is possible
1435 that all of the previous words on the line are variable
1436 assignments. */
1437 }
1438
1439 /* Check that we haven't incorrectly flagged a closed command substitution
1440 as indicating we're in a command position. */
1441 if (in_command_position && ti >= 0 && rl_line_buffer[ti] == '`' &&
1442 *text != '`' && unclosed_pair (rl_line_buffer, end, "`") == 0)
1443 in_command_position = 0;
1444
1445 /* Special handling for command substitution. If *TEXT is a backquote,
1446 it can be the start or end of an old-style command substitution, or
1447 unmatched. If it's unmatched, both calls to unclosed_pair will
1448 succeed. Don't bother if readline found a single quote and we are
1449 completing on the substring. */
1450 if (*text == '`' && rl_completion_quote_character != '\'' &&
1451 (in_command_position || (unclosed_pair (rl_line_buffer, start, "`") &&
1452 unclosed_pair (rl_line_buffer, end, "`"))))
1453 matches = rl_completion_matches (text, command_subst_completion_function);
1454
1455 #if defined (PROGRAMMABLE_COMPLETION)
1456 /* Attempt programmable completion. */
1457 have_progcomps = prog_completion_enabled && (progcomp_size () > 0);
1458 if (matches == 0 && (in_command_position == 0 || text[0] == '\0') &&
1459 current_prompt_string == ps1_prompt)
1460 {
1461 int s, e, s1, e1, os, foundcs;
1462 char *n;
1463
1464 /* XXX - don't free the members */
1465 if (prog_complete_matches)
1466 free (prog_complete_matches);
1467 prog_complete_matches = (char **)NULL;
1468
1469 os = start;
1470 n = 0;
1471 s = find_cmd_start (os);
1472 e = find_cmd_end (end);
1473 do
1474 {
1475 /* Skip over assignment statements preceding a command name. If we
1476 don't find a command name at all, we can perform command name
1477 completion. If we find a partial command name, we should perform
1478 command name completion on it. */
1479 FREE (n);
1480 n = find_cmd_name (s, &s1, &e1);
1481 s = e1 + 1;
1482 }
1483 while (was_assignment = assignment (n, 0));
1484 s = s1; /* reset to index where name begins */
1485
1486 /* s == index of where command name begins (reset above)
1487 e == end of current command, may be end of line
1488 s1 = index of where command name begins
1489 e1 == index of where command name ends
1490 start == index of where word to be completed begins
1491 end == index of where word to be completed ends
1492 if (s == start) we are doing command word completion for sure
1493 if (e1 == end) we are at the end of the command name and completing it */
1494 if (start == 0 && end == 0 && e != 0 && text[0] == '\0') /* beginning of non-empty line */
1495 foundcs = 0;
1496 else if (start == end && start == s1 && e != 0 && e1 > end) /* beginning of command name, leading whitespace */
1497 foundcs = 0;
1498 else if (e == 0 && e == s && text[0] == '\0' && have_progcomps) /* beginning of empty line */
1499 prog_complete_matches = programmable_completions ("_EmptycmD_", text, s, e, &foundcs);
1500 else if (start == end && text[0] == '\0' && s1 > start && whitespace (rl_line_buffer[start]))
1501 foundcs = 0; /* whitespace before command name */
1502 else if (e > s && was_assignment == 0 && e1 == end && rl_line_buffer[e] == 0 && whitespace (rl_line_buffer[e-1]) == 0)
1503 {
1504 /* not assignment statement, but still want to perform command
1505 completion if we are composing command word. */
1506 foundcs = 0;
1507 in_command_position = s == start && STREQ (n, text); /* XXX */
1508 }
1509 else if (e > s && was_assignment == 0 && have_progcomps)
1510 {
1511 prog_complete_matches = programmable_completions (n, text, s, e, &foundcs);
1512 /* command completion if programmable completion fails */
1513 in_command_position = s == start && STREQ (n, text); /* XXX */
1514 }
1515 else if (s >= e && n[0] == '\0' && text[0] == '\0' && start > 0)
1516 {
1517 foundcs = 0; /* empty command name following assignments */
1518 in_command_position = was_assignment;
1519 }
1520 else if (s == start && e == end && STREQ (n, text) && start > 0)
1521 {
1522 foundcs = 0; /* partial command name following assignments */
1523 in_command_position = 1;
1524 }
1525 else
1526 foundcs = 0;
1527 FREE (n);
1528 /* XXX - if we found a COMPSPEC for the command, just return whatever
1529 the programmable completion code returns, and disable the default
1530 filename completion that readline will do unless the COPT_DEFAULT
1531 option has been set with the `-o default' option to complete or
1532 compopt. */
1533 if (foundcs)
1534 {
1535 pcomp_set_readline_variables (foundcs, 1);
1536 /* Turn what the programmable completion code returns into what
1537 readline wants. I should have made compute_lcd_of_matches
1538 external... */
1539 matches = rl_completion_matches (text, prog_complete_return);
1540 if ((foundcs & COPT_DEFAULT) == 0)
1541 rl_attempted_completion_over = 1; /* no default */
1542 if (matches || ((foundcs & COPT_BASHDEFAULT) == 0))
1543 return (matches);
1544 }
1545 }
1546 #endif
1547
1548 if (matches == 0)
1549 {
1550 dflags = 0;
1551 if (in_command_position)
1552 dflags |= DEFCOMP_CMDPOS;
1553 matches = bash_default_completion (text, start, end, qc, dflags);
1554 }
1555
1556 return matches;
1557 }
1558
1559 char **
1560 bash_default_completion (text, start, end, qc, compflags)
1561 const char *text;
1562 int start, end, qc, compflags;
1563 {
1564 char **matches, *t;
1565
1566 matches = (char **)NULL;
1567
1568 /* New posix-style command substitution or variable name? */
1569 if (!matches && *text == '$')
1570 {
1571 if (qc != '\'' && text[1] == '(') /* ) */
1572 matches = rl_completion_matches (text, command_subst_completion_function);
1573 else
1574 {
1575 matches = rl_completion_matches (text, variable_completion_function);
1576 if (matches && matches[0] && matches[1] == 0)
1577 {
1578 t = savestring (matches[0]);
1579 bash_filename_stat_hook (&t);
1580 /* doesn't use test_for_directory because that performs tilde
1581 expansion */
1582 if (file_isdir (t))
1583 rl_completion_append_character = '/';
1584 free (t);
1585 }
1586 }
1587 }
1588
1589 /* If the word starts in `~', and there is no slash in the word, then
1590 try completing this word as a username. */
1591 if (matches == 0 && *text == '~' && mbschr (text, '/') == 0)
1592 matches = rl_completion_matches (text, rl_username_completion_function);
1593
1594 /* Another one. Why not? If the word starts in '@', then look through
1595 the world of known hostnames for completion first. */
1596 if (matches == 0 && perform_hostname_completion && *text == '@')
1597 matches = rl_completion_matches (text, hostname_completion_function);
1598
1599 /* And last, (but not least) if this word is in a command position, then
1600 complete over possible command names, including aliases, functions,
1601 and command names. */
1602 if (matches == 0 && (compflags & DEFCOMP_CMDPOS))
1603 {
1604 /* If END == START and text[0] == 0, we are trying to complete an empty
1605 command word. */
1606 if (no_empty_command_completion && end == start && text[0] == '\0')
1607 {
1608 matches = (char **)NULL;
1609 rl_ignore_some_completions_function = bash_ignore_everything;
1610 }
1611 else
1612 {
1613 #define CMD_IS_DIR(x) (absolute_pathname(x) == 0 && absolute_program(x) == 0 && *(x) != '~' && test_for_directory (x))
1614
1615 dot_in_path = 0;
1616 matches = rl_completion_matches (text, command_word_completion_function);
1617
1618 /* If we are attempting command completion and nothing matches, we
1619 do not want readline to perform filename completion for us. We
1620 still want to be able to complete partial pathnames, so set the
1621 completion ignore function to something which will remove
1622 filenames and leave directories in the match list. */
1623 if (matches == (char **)NULL)
1624 rl_ignore_some_completions_function = bash_ignore_filenames;
1625 else if (matches[1] == 0 && CMD_IS_DIR(matches[0]) && dot_in_path == 0)
1626 /* If we found a single match, without looking in the current
1627 directory (because it's not in $PATH), but the found name is
1628 also a command in the current directory, suppress appending any
1629 terminating character, since it's ambiguous. */
1630 {
1631 rl_completion_suppress_append = 1;
1632 rl_filename_completion_desired = 0;
1633 }
1634 else if (matches[0] && matches[1] && STREQ (matches[0], matches[1]) && CMD_IS_DIR (matches[0]))
1635 /* There are multiple instances of the same match (duplicate
1636 completions haven't yet been removed). In this case, all of
1637 the matches will be the same, and the duplicate removal code
1638 will distill them all down to one. We turn on
1639 rl_completion_suppress_append for the same reason as above.
1640 Remember: we only care if there's eventually a single unique
1641 completion. If there are multiple completions this won't
1642 make a difference and the problem won't occur. */
1643 {
1644 rl_completion_suppress_append = 1;
1645 rl_filename_completion_desired = 0;
1646 }
1647 }
1648 }
1649
1650 /* This could be a globbing pattern, so try to expand it using pathname
1651 expansion. */
1652 if (!matches && glob_pattern_p (text))
1653 {
1654 matches = rl_completion_matches (text, glob_complete_word);
1655 /* A glob expression that matches more than one filename is problematic.
1656 If we match more than one filename, punt. */
1657 if (matches && matches[1] && rl_completion_type == TAB)
1658 {
1659 strvec_dispose (matches);
1660 matches = (char **)0;
1661 }
1662 else if (matches && matches[1] && rl_completion_type == '!')
1663 {
1664 rl_completion_suppress_append = 1;
1665 rl_filename_completion_desired = 0;
1666 }
1667 }
1668
1669 return (matches);
1670 }
1671
1672 static int
1673 bash_command_name_stat_hook (name)
1674 char **name;
1675 {
1676 char *cname, *result;
1677
1678 /* If it's not something we're going to look up in $PATH, just call the
1679 normal filename stat hook. */
1680 if (absolute_program (*name))
1681 return (bash_filename_stat_hook (name));
1682
1683 cname = *name;
1684 /* XXX - we could do something here with converting aliases, builtins,
1685 and functions into something that came out as executable, but we don't. */
1686 result = search_for_command (cname, 0);
1687 if (result)
1688 {
1689 *name = result;
1690 return 1;
1691 }
1692 return 0;
1693 }
1694
1695 static int
1696 executable_completion (filename, searching_path)
1697 const char *filename;
1698 int searching_path;
1699 {
1700 char *f;
1701 int r;
1702
1703 f = savestring (filename);
1704 bash_directory_completion_hook (&f);
1705
1706 r = searching_path ? executable_file (f) : executable_or_directory (f);
1707 free (f);
1708 return r;
1709 }
1710
1711 /* This is the function to call when the word to complete is in a position
1712 where a command word can be found. It grovels $PATH, looking for commands
1713 that match. It also scans aliases, function names, and the shell_builtin
1714 table. */
1715 char *
1716 command_word_completion_function (hint_text, state)
1717 const char *hint_text;
1718 int state;
1719 {
1720 static char *hint = (char *)NULL;
1721 static char *path = (char *)NULL;
1722 static char *val = (char *)NULL;
1723 static char *filename_hint = (char *)NULL;
1724 static char *fnhint = (char *)NULL;
1725 static char *dequoted_hint = (char *)NULL;
1726 static char *directory_part = (char *)NULL;
1727 static char **glob_matches = (char **)NULL;
1728 static int path_index, hint_len, dequoted_len, istate, igncase;
1729 static int mapping_over, local_index, searching_path, hint_is_dir;
1730 static int old_glob_ignore_case, globpat;
1731 static SHELL_VAR **varlist = (SHELL_VAR **)NULL;
1732 #if defined (ALIAS)
1733 static alias_t **alias_list = (alias_t **)NULL;
1734 #endif /* ALIAS */
1735 char *temp, *cval;
1736
1737 /* We have to map over the possibilities for command words. If we have
1738 no state, then make one just for that purpose. */
1739 if (state == 0)
1740 {
1741 rl_filename_stat_hook = bash_command_name_stat_hook;
1742
1743 if (dequoted_hint && dequoted_hint != hint)
1744 free (dequoted_hint);
1745 if (hint)
1746 free (hint);
1747
1748 mapping_over = searching_path = 0;
1749 hint_is_dir = CMD_IS_DIR (hint_text);
1750 val = (char *)NULL;
1751
1752 temp = rl_variable_value ("completion-ignore-case");
1753 igncase = RL_BOOLEAN_VARIABLE_VALUE (temp);
1754
1755 if (glob_matches)
1756 {
1757 free (glob_matches);
1758 glob_matches = (char **)NULL;
1759 }
1760
1761 globpat = glob_pattern_p (hint_text);
1762
1763 /* If this is an absolute program name, do not check it against
1764 aliases, reserved words, functions or builtins. We must check
1765 whether or not it is unique, and, if so, whether that filename
1766 is executable. */
1767 if (globpat || absolute_program (hint_text))
1768 {
1769 /* Perform tilde expansion on what's passed, so we don't end up
1770 passing filenames with tildes directly to stat(). */
1771 if (*hint_text == '~')
1772 {
1773 hint = bash_tilde_expand (hint_text, 0);
1774 directory_part = savestring (hint_text);
1775 temp = strchr (directory_part, '/');
1776 if (temp)
1777 *temp = 0;
1778 else
1779 {
1780 free (directory_part);
1781 directory_part = (char *)NULL;
1782 }
1783 }
1784 else
1785 hint = savestring (hint_text);
1786
1787 dequoted_hint = hint;
1788 /* If readline's completer found a quote character somewhere, but
1789 didn't set the quote character, there must have been a quote
1790 character embedded in the filename. It can't be at the start of
1791 the filename, so we need to dequote the filename before we look
1792 in the file system for it. */
1793 if (rl_completion_found_quote && rl_completion_quote_character == 0)
1794 {
1795 dequoted_hint = bash_dequote_filename (hint, 0);
1796 free (hint);
1797 hint = dequoted_hint;
1798 }
1799 dequoted_len = hint_len = strlen (hint);
1800
1801 if (filename_hint)
1802 free (filename_hint);
1803
1804 fnhint = filename_hint = savestring (hint);
1805
1806 istate = 0;
1807
1808 if (globpat)
1809 {
1810 mapping_over = 5;
1811 goto globword;
1812 }
1813 else
1814 {
1815 if (dircomplete_expand && path_dot_or_dotdot (filename_hint))
1816 {
1817 dircomplete_expand = 0;
1818 set_directory_hook ();
1819 dircomplete_expand = 1;
1820 }
1821 mapping_over = 4;
1822 goto inner;
1823 }
1824 }
1825
1826 dequoted_hint = hint = savestring (hint_text);
1827 dequoted_len = hint_len = strlen (hint);
1828
1829 if (rl_completion_found_quote && rl_completion_quote_character == 0)
1830 {
1831 dequoted_hint = bash_dequote_filename (hint, 0);
1832 dequoted_len = strlen (dequoted_hint);
1833 }
1834
1835 path = get_string_value ("PATH");
1836 path_index = dot_in_path = 0;
1837
1838 /* Initialize the variables for each type of command word. */
1839 local_index = 0;
1840
1841 if (varlist)
1842 free (varlist);
1843
1844 varlist = all_visible_functions ();
1845
1846 #if defined (ALIAS)
1847 if (alias_list)
1848 free (alias_list);
1849
1850 alias_list = all_aliases ();
1851 #endif /* ALIAS */
1852 }
1853
1854 /* mapping_over says what we are currently hacking. Note that every case
1855 in this list must fall through when there are no more possibilities. */
1856
1857 switch (mapping_over)
1858 {
1859 case 0: /* Aliases come first. */
1860 #if defined (ALIAS)
1861 while (alias_list && alias_list[local_index])
1862 {
1863 register char *alias;
1864
1865 alias = alias_list[local_index++]->name;
1866
1867 if (STREQN (alias, hint, hint_len))
1868 return (savestring (alias));
1869 }
1870 #endif /* ALIAS */
1871 local_index = 0;
1872 mapping_over++;
1873
1874 case 1: /* Then shell reserved words. */
1875 {
1876 while (word_token_alist[local_index].word)
1877 {
1878 register char *reserved_word;
1879
1880 reserved_word = word_token_alist[local_index++].word;
1881
1882 if (STREQN (reserved_word, hint, hint_len))
1883 return (savestring (reserved_word));
1884 }
1885 local_index = 0;
1886 mapping_over++;
1887 }
1888
1889 case 2: /* Then function names. */
1890 while (varlist && varlist[local_index])
1891 {
1892 register char *varname;
1893
1894 varname = varlist[local_index++]->name;
1895
1896 if (STREQN (varname, hint, hint_len))
1897 return (savestring (varname));
1898 }
1899 local_index = 0;
1900 mapping_over++;
1901
1902 case 3: /* Then shell builtins. */
1903 for (; local_index < num_shell_builtins; local_index++)
1904 {
1905 /* Ignore it if it doesn't have a function pointer or if it
1906 is not currently enabled. */
1907 if (!shell_builtins[local_index].function ||
1908 (shell_builtins[local_index].flags & BUILTIN_ENABLED) == 0)
1909 continue;
1910
1911 if (STREQN (shell_builtins[local_index].name, hint, hint_len))
1912 {
1913 int i = local_index++;
1914
1915 return (savestring (shell_builtins[i].name));
1916 }
1917 }
1918 local_index = 0;
1919 mapping_over++;
1920 }
1921
1922 globword:
1923 /* Limited support for completing command words with globbing chars. Only
1924 a single match (multiple matches that end up reducing the number of
1925 characters in the common prefix are bad) will ever be returned on
1926 regular completion. */
1927 if (globpat)
1928 {
1929 if (state == 0)
1930 {
1931 glob_ignore_case = igncase;
1932 glob_matches = shell_glob_filename (hint);
1933 glob_ignore_case = old_glob_ignore_case;
1934
1935 if (GLOB_FAILED (glob_matches) || glob_matches == 0)
1936 {
1937 glob_matches = (char **)NULL;
1938 return ((char *)NULL);
1939 }
1940
1941 local_index = 0;
1942
1943 if (glob_matches[1] && rl_completion_type == TAB) /* multiple matches are bad */
1944 return ((char *)NULL);
1945 }
1946
1947 while (val = glob_matches[local_index++])
1948 {
1949 if (executable_or_directory (val))
1950 {
1951 if (*hint_text == '~' && directory_part)
1952 {
1953 temp = maybe_restore_tilde (val, directory_part);
1954 free (val);
1955 val = temp;
1956 }
1957 return (val);
1958 }
1959 free (val);
1960 }
1961
1962 glob_ignore_case = old_glob_ignore_case;
1963 return ((char *)NULL);
1964 }
1965
1966 /* If the text passed is a directory in the current directory, return it
1967 as a possible match. Executables in directories in the current
1968 directory can be specified using relative pathnames and successfully
1969 executed even when `.' is not in $PATH. */
1970 if (hint_is_dir)
1971 {
1972 hint_is_dir = 0; /* only return the hint text once */
1973 return (savestring (hint_text));
1974 }
1975
1976 /* Repeatedly call filename_completion_function while we have
1977 members of PATH left. Question: should we stat each file?
1978 Answer: we call executable_file () on each file. */
1979 outer:
1980
1981 istate = (val != (char *)NULL);
1982
1983 if (istate == 0)
1984 {
1985 char *current_path;
1986
1987 /* Get the next directory from the path. If there is none, then we
1988 are all done. */
1989 if (path == 0 || path[path_index] == 0 ||
1990 (current_path = extract_colon_unit (path, &path_index)) == 0)
1991 return ((char *)NULL);
1992
1993 searching_path = 1;
1994 if (*current_path == 0)
1995 {
1996 free (current_path);
1997 current_path = savestring (".");
1998 }
1999
2000 if (*current_path == '~')
2001 {
2002 char *t;
2003
2004 t = bash_tilde_expand (current_path, 0);
2005 free (current_path);
2006 current_path = t;
2007 }
2008
2009 if (current_path[0] == '.' && current_path[1] == '\0')
2010 dot_in_path = 1;
2011
2012 if (fnhint && fnhint != filename_hint)
2013 free (fnhint);
2014 if (filename_hint)
2015 free (filename_hint);
2016
2017 filename_hint = sh_makepath (current_path, hint, 0);
2018 /* Need a quoted version (though it doesn't matter much in most
2019 cases) because rl_filename_completion_function dequotes the
2020 filename it gets, assuming that it's been quoted as part of
2021 the input line buffer. */
2022 if (strpbrk (filename_hint, "\"'\\"))
2023 fnhint = sh_backslash_quote (filename_hint, filename_bstab, 0);
2024 else
2025 fnhint = filename_hint;
2026 free (current_path); /* XXX */
2027 }
2028
2029 inner:
2030 val = rl_filename_completion_function (fnhint, istate);
2031 if (mapping_over == 4 && dircomplete_expand)
2032 set_directory_hook ();
2033
2034 istate = 1;
2035
2036 if (val == 0)
2037 {
2038 /* If the hint text is an absolute program, then don't bother
2039 searching through PATH. */
2040 if (absolute_program (hint))
2041 return ((char *)NULL);
2042
2043 goto outer;
2044 }
2045 else
2046 {
2047 int match, freetemp;
2048
2049 if (absolute_program (hint))
2050 {
2051 if (igncase == 0)
2052 match = strncmp (val, hint, hint_len) == 0;
2053 else
2054 match = strncasecmp (val, hint, hint_len) == 0;
2055
2056 /* If we performed tilde expansion, restore the original
2057 filename. */
2058 if (*hint_text == '~')
2059 temp = maybe_restore_tilde (val, directory_part);
2060 else
2061 temp = savestring (val);
2062 freetemp = 1;
2063 }
2064 else
2065 {
2066 temp = strrchr (val, '/');
2067
2068 if (temp)
2069 {
2070 temp++;
2071 if (igncase == 0)
2072 freetemp = match = strncmp (temp, hint, hint_len) == 0;
2073 else
2074 freetemp = match = strncasecmp (temp, hint, hint_len) == 0;
2075 if (match)
2076 temp = savestring (temp);
2077 }
2078 else
2079 freetemp = match = 0;
2080 }
2081
2082 /* If we have found a match, and it is an executable file, return it.
2083 We don't return directory names when searching $PATH, since the
2084 bash execution code won't find executables in directories which
2085 appear in directories in $PATH when they're specified using
2086 relative pathnames. */
2087 #if 0
2088 /* If we're not searching $PATH and we have a relative pathname, we
2089 need to re-canonicalize it before testing whether or not it's an
2090 executable or a directory so the shell treats .. relative to $PWD
2091 according to the physical/logical option. The shell already
2092 canonicalizes the directory name in order to tell readline where
2093 to look, so not doing it here will be inconsistent. */
2094 /* XXX -- currently not used -- will introduce more inconsistency,
2095 since shell does not canonicalize ../foo before passing it to
2096 shell_execve(). */
2097 if (match && searching_path == 0 && *val == '.')
2098 {
2099 char *t, *t1;
2100
2101 t = get_working_directory ("command-word-completion");
2102 t1 = make_absolute (val, t);
2103 free (t);
2104 cval = sh_canonpath (t1, PATH_CHECKDOTDOT|PATH_CHECKEXISTS);
2105 }
2106 else
2107 #endif
2108 cval = val;
2109
2110 if (match && executable_completion ((searching_path ? val : cval), searching_path))
2111 {
2112 if (cval != val)
2113 free (cval);
2114 free (val);
2115 val = ""; /* So it won't be NULL. */
2116 return (temp);
2117 }
2118 else
2119 {
2120 if (freetemp)
2121 free (temp);
2122 if (cval != val)
2123 free (cval);
2124 free (val);
2125 goto inner;
2126 }
2127 }
2128 }
2129
2130 /* Completion inside an unterminated command substitution. */
2131 static char *
2132 command_subst_completion_function (text, state)
2133 const char *text;
2134 int state;
2135 {
2136 static char **matches = (char **)NULL;
2137 static const char *orig_start;
2138 static char *filename_text = (char *)NULL;
2139 static int cmd_index, start_len;
2140 char *value;
2141
2142 if (state == 0)
2143 {
2144 if (filename_text)
2145 free (filename_text);
2146 orig_start = text;
2147 if (*text == '`')
2148 text++;
2149 else if (*text == '$' && text[1] == '(') /* ) */
2150 text += 2;
2151 /* If the text was quoted, suppress any quote character that the
2152 readline completion code would insert. */
2153 rl_completion_suppress_quote = 1;
2154 start_len = text - orig_start;
2155 filename_text = savestring (text);
2156 if (matches)
2157 free (matches);
2158
2159 /*
2160 * At this point we can entertain the idea of re-parsing
2161 * `filename_text' into a (possibly incomplete) command name and
2162 * arguments, and doing completion based on that. This is
2163 * currently very rudimentary, but it is a small improvement.
2164 */
2165 for (value = filename_text + strlen (filename_text) - 1; value > filename_text; value--)
2166 if (whitespace (*value) || member (*value, COMMAND_SEPARATORS))
2167 break;
2168 if (value <= filename_text)
2169 matches = rl_completion_matches (filename_text, command_word_completion_function);
2170 else
2171 {
2172 value++;
2173 start_len += value - filename_text;
2174 if (whitespace (value[-1]))
2175 matches = rl_completion_matches (value, rl_filename_completion_function);
2176 else
2177 matches = rl_completion_matches (value, command_word_completion_function);
2178 }
2179
2180 /* If there is more than one match, rl_completion_matches has already
2181 put the lcd in matches[0]. Skip over it. */
2182 cmd_index = matches && matches[0] && matches[1];
2183
2184 /* If there's a single match and it's a directory, set the append char
2185 to the expected `/'. Otherwise, don't append anything. */
2186 if (matches && matches[0] && matches[1] == 0 && test_for_directory (matches[0]))
2187 rl_completion_append_character = '/';
2188 else
2189 rl_completion_suppress_append = 1;
2190 }
2191
2192 if (matches == 0 || matches[cmd_index] == 0)
2193 {
2194 rl_filename_quoting_desired = 0; /* disable quoting */
2195 return ((char *)NULL);
2196 }
2197 else
2198 {
2199 value = (char *)xmalloc (1 + start_len + strlen (matches[cmd_index]));
2200
2201 if (start_len == 1)
2202 value[0] = *orig_start;
2203 else
2204 strncpy (value, orig_start, start_len);
2205
2206 strcpy (value + start_len, matches[cmd_index]);
2207
2208 cmd_index++;
2209 return (value);
2210 }
2211 }
2212
2213 /* Okay, now we write the entry_function for variable completion. */
2214 static char *
2215 variable_completion_function (text, state)
2216 const char *text;
2217 int state;
2218 {
2219 static char **varlist = (char **)NULL;
2220 static int varlist_index;
2221 static char *varname = (char *)NULL;
2222 static int namelen;
2223 static int first_char, first_char_loc;
2224
2225 if (!state)
2226 {
2227 if (varname)
2228 free (varname);
2229
2230 first_char_loc = 0;
2231 first_char = text[0];
2232
2233 if (first_char == '$')
2234 first_char_loc++;
2235
2236 if (text[first_char_loc] == '{')
2237 first_char_loc++;
2238
2239 varname = savestring (text + first_char_loc);
2240
2241 namelen = strlen (varname);
2242 if (varlist)
2243 strvec_dispose (varlist);
2244
2245 varlist = all_variables_matching_prefix (varname);
2246 varlist_index = 0;
2247 }
2248
2249 if (!varlist || !varlist[varlist_index])
2250 {
2251 return ((char *)NULL);
2252 }
2253 else
2254 {
2255 char *value;
2256
2257 value = (char *)xmalloc (4 + strlen (varlist[varlist_index]));
2258
2259 if (first_char_loc)
2260 {
2261 value[0] = first_char;
2262 if (first_char_loc == 2)
2263 value[1] = '{';
2264 }
2265
2266 strcpy (value + first_char_loc, varlist[varlist_index]);
2267 if (first_char_loc == 2)
2268 strcat (value, "}");
2269
2270 varlist_index++;
2271 return (value);
2272 }
2273 }
2274
2275 /* How about a completion function for hostnames? */
2276 static char *
2277 hostname_completion_function (text, state)
2278 const char *text;
2279 int state;
2280 {
2281 static char **list = (char **)NULL;
2282 static int list_index = 0;
2283 static int first_char, first_char_loc;
2284
2285 /* If we don't have any state, make some. */
2286 if (state == 0)
2287 {
2288 FREE (list);
2289
2290 list = (char **)NULL;
2291
2292 first_char_loc = 0;
2293 first_char = *text;
2294
2295 if (first_char == '@')
2296 first_char_loc++;
2297
2298 list = hostnames_matching ((char *)text+first_char_loc);
2299 list_index = 0;
2300 }
2301
2302 if (list && list[list_index])
2303 {
2304 char *t;
2305
2306 t = (char *)xmalloc (2 + strlen (list[list_index]));
2307 *t = first_char;
2308 strcpy (t + first_char_loc, list[list_index]);
2309 list_index++;
2310 return (t);
2311 }
2312
2313 return ((char *)NULL);
2314 }
2315
2316 /*
2317 * A completion function for service names from /etc/services (or wherever).
2318 */
2319 char *
2320 bash_servicename_completion_function (text, state)
2321 const char *text;
2322 int state;
2323 {
2324 #if defined (__WIN32__) || defined (__OPENNT) || !defined (HAVE_GETSERVENT)
2325 return ((char *)NULL);
2326 #else
2327 static char *sname = (char *)NULL;
2328 static struct servent *srvent;
2329 static int snamelen, firstc;
2330 char *value;
2331 char **alist, *aentry;
2332 int afound;
2333
2334 if (state == 0)
2335 {
2336 FREE (sname);
2337 firstc = *text;
2338
2339 sname = savestring (text);
2340 snamelen = strlen (sname);
2341 setservent (0);
2342 }
2343
2344 while (srvent = getservent ())
2345 {
2346 afound = 0;
2347 if (snamelen == 0 || (STREQN (sname, srvent->s_name, snamelen)))
2348 break;
2349 /* Not primary, check aliases */
2350 for (alist = srvent->s_aliases; *alist; alist++)
2351 {
2352 aentry = *alist;
2353 if (STREQN (sname, aentry, snamelen))
2354 {
2355 afound = 1;
2356 break;
2357 }
2358 }
2359
2360 if (afound)
2361 break;
2362 }
2363
2364 if (srvent == 0)
2365 {
2366 endservent ();
2367 return ((char *)NULL);
2368 }
2369
2370 value = afound ? savestring (aentry) : savestring (srvent->s_name);
2371 return value;
2372 #endif
2373 }
2374
2375 /*
2376 * A completion function for group names from /etc/group (or wherever).
2377 */
2378 char *
2379 bash_groupname_completion_function (text, state)
2380 const char *text;
2381 int state;
2382 {
2383 #if defined (__WIN32__) || defined (__OPENNT) || !defined (HAVE_GRP_H)
2384 return ((char *)NULL);
2385 #else
2386 static char *gname = (char *)NULL;
2387 static struct group *grent;
2388 static int gnamelen;
2389 char *value;
2390
2391 if (state == 0)
2392 {
2393 FREE (gname);
2394 gname = savestring (text);
2395 gnamelen = strlen (gname);
2396
2397 setgrent ();
2398 }
2399
2400 while (grent = getgrent ())
2401 {
2402 if (gnamelen == 0 || (STREQN (gname, grent->gr_name, gnamelen)))
2403 break;
2404 }
2405
2406 if (grent == 0)
2407 {
2408 endgrent ();
2409 return ((char *)NULL);
2410 }
2411
2412 value = savestring (grent->gr_name);
2413 return (value);
2414 #endif
2415 }
2416
2417 /* Functions to perform history and alias expansions on the current line. */
2418
2419 #if defined (BANG_HISTORY)
2420 /* Perform history expansion on the current line. If no history expansion
2421 is done, pre_process_line() returns what it was passed, so we need to
2422 allocate a new line here. */
2423 static char *
2424 history_expand_line_internal (line)
2425 char *line;
2426 {
2427 char *new_line;
2428 int old_verify;
2429
2430 old_verify = hist_verify;
2431 hist_verify = 0;
2432 new_line = pre_process_line (line, 0, 0);
2433 hist_verify = old_verify;
2434
2435 return (new_line == line) ? savestring (line) : new_line;
2436 }
2437 #endif
2438
2439 /* There was an error in expansion. Let the preprocessor print
2440 the error here. */
2441 static void
2442 cleanup_expansion_error ()
2443 {
2444 char *to_free;
2445 #if defined (BANG_HISTORY)
2446 int old_verify;
2447
2448 old_verify = hist_verify;
2449 hist_verify = 0;
2450 #endif
2451
2452 fprintf (rl_outstream, "\r\n");
2453 to_free = pre_process_line (rl_line_buffer, 1, 0);
2454 #if defined (BANG_HISTORY)
2455 hist_verify = old_verify;
2456 #endif
2457 if (to_free != rl_line_buffer)
2458 FREE (to_free);
2459 putc ('\r', rl_outstream);
2460 rl_forced_update_display ();
2461 }
2462
2463 /* If NEW_LINE differs from what is in the readline line buffer, add an
2464 undo record to get from the readline line buffer contents to the new
2465 line and make NEW_LINE the current readline line. */
2466 static void
2467 maybe_make_readline_line (new_line)
2468 char *new_line;
2469 {
2470 if (strcmp (new_line, rl_line_buffer) != 0)
2471 {
2472 rl_point = rl_end;
2473
2474 rl_add_undo (UNDO_BEGIN, 0, 0, 0);
2475 rl_delete_text (0, rl_point);
2476 rl_point = rl_end = rl_mark = 0;
2477 rl_insert_text (new_line);
2478 rl_add_undo (UNDO_END, 0, 0, 0);
2479 }
2480 }
2481
2482 /* Make NEW_LINE be the current readline line. This frees NEW_LINE. */
2483 static void
2484 set_up_new_line (new_line)
2485 char *new_line;
2486 {
2487 int old_point, at_end;
2488
2489 old_point = rl_point;
2490 at_end = rl_point == rl_end;
2491
2492 /* If the line was history and alias expanded, then make that
2493 be one thing to undo. */
2494 maybe_make_readline_line (new_line);
2495 free (new_line);
2496
2497 /* Place rl_point where we think it should go. */
2498 if (at_end)
2499 rl_point = rl_end;
2500 else if (old_point < rl_end)
2501 {
2502 rl_point = old_point;
2503 if (!whitespace (rl_line_buffer[rl_point]))
2504 rl_forward_word (1, 0);
2505 }
2506 }
2507
2508 #if defined (ALIAS)
2509 /* Expand aliases in the current readline line. */
2510 static int
2511 alias_expand_line (count, ignore)
2512 int count, ignore;
2513 {
2514 char *new_line;
2515
2516 new_line = alias_expand (rl_line_buffer);
2517
2518 if (new_line)
2519 {
2520 set_up_new_line (new_line);
2521 return (0);
2522 }
2523 else
2524 {
2525 cleanup_expansion_error ();
2526 return (1);
2527 }
2528 }
2529 #endif
2530
2531 #if defined (BANG_HISTORY)
2532 /* History expand the line. */
2533 static int
2534 history_expand_line (count, ignore)
2535 int count, ignore;
2536 {
2537 char *new_line;
2538
2539 new_line = history_expand_line_internal (rl_line_buffer);
2540
2541 if (new_line)
2542 {
2543 set_up_new_line (new_line);
2544 return (0);
2545 }
2546 else
2547 {
2548 cleanup_expansion_error ();
2549 return (1);
2550 }
2551 }
2552
2553 /* Expand history substitutions in the current line and then insert a
2554 space (hopefully close to where we were before). */
2555 static int
2556 tcsh_magic_space (count, ignore)
2557 int count, ignore;
2558 {
2559 int dist_from_end, old_point;
2560
2561 old_point = rl_point;
2562 dist_from_end = rl_end - rl_point;
2563 if (history_expand_line (count, ignore) == 0)
2564 {
2565 /* Try a simple heuristic from Stephen Gildea <gildea@intouchsys.com>.
2566 This works if all expansions were before rl_point or if no expansions
2567 were performed. */
2568 rl_point = (old_point == 0) ? old_point : rl_end - dist_from_end;
2569 rl_insert (1, ' ');
2570 return (0);
2571 }
2572 else
2573 return (1);
2574 }
2575 #endif /* BANG_HISTORY */
2576
2577 /* History and alias expand the line. */
2578 static int
2579 history_and_alias_expand_line (count, ignore)
2580 int count, ignore;
2581 {
2582 char *new_line;
2583
2584 new_line = 0;
2585 #if defined (BANG_HISTORY)
2586 new_line = history_expand_line_internal (rl_line_buffer);
2587 #endif
2588
2589 #if defined (ALIAS)
2590 if (new_line)
2591 {
2592 char *alias_line;
2593
2594 alias_line = alias_expand (new_line);
2595 free (new_line);
2596 new_line = alias_line;
2597 }
2598 #endif /* ALIAS */
2599
2600 if (new_line)
2601 {
2602 set_up_new_line (new_line);
2603 return (0);
2604 }
2605 else
2606 {
2607 cleanup_expansion_error ();
2608 return (1);
2609 }
2610 }
2611
2612 /* History and alias expand the line, then perform the shell word
2613 expansions by calling expand_string. This can't use set_up_new_line()
2614 because we want the variable expansions as a separate undo'able
2615 set of operations. */
2616 static int
2617 shell_expand_line (count, ignore)
2618 int count, ignore;
2619 {
2620 char *new_line;
2621 WORD_LIST *expanded_string;
2622
2623 new_line = 0;
2624 #if defined (BANG_HISTORY)
2625 new_line = history_expand_line_internal (rl_line_buffer);
2626 #endif
2627
2628 #if defined (ALIAS)
2629 if (new_line)
2630 {
2631 char *alias_line;
2632
2633 alias_line = alias_expand (new_line);
2634 free (new_line);
2635 new_line = alias_line;
2636 }
2637 #endif /* ALIAS */
2638
2639 if (new_line)
2640 {
2641 int old_point = rl_point;
2642 int at_end = rl_point == rl_end;
2643
2644 /* If the line was history and alias expanded, then make that
2645 be one thing to undo. */
2646 maybe_make_readline_line (new_line);
2647 free (new_line);
2648
2649 /* If there is variable expansion to perform, do that as a separate
2650 operation to be undone. */
2651 new_line = savestring (rl_line_buffer);
2652 expanded_string = expand_string (new_line, 0);
2653 FREE (new_line);
2654 if (expanded_string == 0)
2655 {
2656 new_line = (char *)xmalloc (1);
2657 new_line[0] = '\0';
2658 }
2659 else
2660 {
2661 new_line = string_list (expanded_string);
2662 dispose_words (expanded_string);
2663 }
2664
2665 maybe_make_readline_line (new_line);
2666 free (new_line);
2667
2668 /* Place rl_point where we think it should go. */
2669 if (at_end)
2670 rl_point = rl_end;
2671 else if (old_point < rl_end)
2672 {
2673 rl_point = old_point;
2674 if (!whitespace (rl_line_buffer[rl_point]))
2675 rl_forward_word (1, 0);
2676 }
2677 return 0;
2678 }
2679 else
2680 {
2681 cleanup_expansion_error ();
2682 return 1;
2683 }
2684 }
2685
2686 /* If FIGNORE is set, then don't match files with the given suffixes when
2687 completing filenames. If only one of the possibilities has an acceptable
2688 suffix, delete the others, else just return and let the completer
2689 signal an error. It is called by the completer when real
2690 completions are done on filenames by the completer's internal
2691 function, not for completion lists (M-?) and not on "other"
2692 completion types, such as hostnames or commands. */
2693
2694 static struct ignorevar fignore =
2695 {
2696 "FIGNORE",
2697 (struct ign *)0,
2698 0,
2699 (char *)0,
2700 (sh_iv_item_func_t *) 0,
2701 };
2702
2703 static void
2704 _ignore_completion_names (names, name_func)
2705 char **names;
2706 sh_ignore_func_t *name_func;
2707 {
2708 char **newnames;
2709 int idx, nidx;
2710 char **oldnames;
2711 int oidx;
2712
2713 /* If there is only one completion, see if it is acceptable. If it is
2714 not, free it up. In any case, short-circuit and return. This is a
2715 special case because names[0] is not the prefix of the list of names
2716 if there is only one completion; it is the completion itself. */
2717 if (names[1] == (char *)0)
2718 {
2719 if (force_fignore)
2720 if ((*name_func) (names[0]) == 0)
2721 {
2722 free (names[0]);
2723 names[0] = (char *)NULL;
2724 }
2725
2726 return;
2727 }
2728
2729 /* Allocate space for array to hold list of pointers to matching
2730 filenames. The pointers are copied back to NAMES when done. */
2731 for (nidx = 1; names[nidx]; nidx++)
2732 ;
2733 newnames = strvec_create (nidx + 1);
2734
2735 if (force_fignore == 0)
2736 {
2737 oldnames = strvec_create (nidx - 1);
2738 oidx = 0;
2739 }
2740
2741 newnames[0] = names[0];
2742 for (idx = nidx = 1; names[idx]; idx++)
2743 {
2744 if ((*name_func) (names[idx]))
2745 newnames[nidx++] = names[idx];
2746 else if (force_fignore == 0)
2747 oldnames[oidx++] = names[idx];
2748 else
2749 free (names[idx]);
2750 }
2751
2752 newnames[nidx] = (char *)NULL;
2753
2754 /* If none are acceptable then let the completer handle it. */
2755 if (nidx == 1)
2756 {
2757 if (force_fignore)
2758 {
2759 free (names[0]);
2760 names[0] = (char *)NULL;
2761 }
2762 else
2763 free (oldnames);
2764
2765 free (newnames);
2766 return;
2767 }
2768
2769 if (force_fignore == 0)
2770 {
2771 while (oidx)
2772 free (oldnames[--oidx]);
2773 free (oldnames);
2774 }
2775
2776 /* If only one is acceptable, copy it to names[0] and return. */
2777 if (nidx == 2)
2778 {
2779 free (names[0]);
2780 names[0] = newnames[1];
2781 names[1] = (char *)NULL;
2782 free (newnames);
2783 return;
2784 }
2785
2786 /* Copy the acceptable names back to NAMES, set the new array end,
2787 and return. */
2788 for (nidx = 1; newnames[nidx]; nidx++)
2789 names[nidx] = newnames[nidx];
2790 names[nidx] = (char *)NULL;
2791 free (newnames);
2792 }
2793
2794 static int
2795 name_is_acceptable (name)
2796 const char *name;
2797 {
2798 struct ign *p;
2799 int nlen;
2800
2801 for (nlen = strlen (name), p = fignore.ignores; p->val; p++)
2802 {
2803 if (nlen > p->len && p->len > 0 && STREQ (p->val, &name[nlen - p->len]))
2804 return (0);
2805 }
2806
2807 return (1);
2808 }
2809
2810 #if 0
2811 static int
2812 ignore_dot_names (name)
2813 char *name;
2814 {
2815 return (name[0] != '.');
2816 }
2817 #endif
2818
2819 static int
2820 filename_completion_ignore (names)
2821 char **names;
2822 {
2823 #if 0
2824 if (glob_dot_filenames == 0)
2825 _ignore_completion_names (names, ignore_dot_names);
2826 #endif
2827
2828 setup_ignore_patterns (&fignore);
2829
2830 if (fignore.num_ignores == 0)
2831 return 0;
2832
2833 _ignore_completion_names (names, name_is_acceptable);
2834
2835 return 0;
2836 }
2837
2838 /* Return 1 if NAME is a directory. NAME undergoes tilde expansion. */
2839 static int
2840 test_for_directory (name)
2841 const char *name;
2842 {
2843 char *fn;
2844 int r;
2845
2846 fn = bash_tilde_expand (name, 0);
2847 r = file_isdir (fn);
2848 free (fn);
2849
2850 return (r);
2851 }
2852
2853 /* Remove files from NAMES, leaving directories. */
2854 static int
2855 bash_ignore_filenames (names)
2856 char **names;
2857 {
2858 _ignore_completion_names (names, test_for_directory);
2859 return 0;
2860 }
2861
2862 static int
2863 return_zero (name)
2864 const char *name;
2865 {
2866 return 0;
2867 }
2868
2869 static int
2870 bash_ignore_everything (names)
2871 char **names;
2872 {
2873 _ignore_completion_names (names, return_zero);
2874 return 0;
2875 }
2876
2877 /* Replace a tilde-prefix in VAL with a `~', assuming the user typed it. VAL
2878 is an expanded filename. DIRECTORY_PART is the tilde-prefix portion
2879 of the un-tilde-expanded version of VAL (what the user typed). */
2880 static char *
2881 restore_tilde (val, directory_part)
2882 char *val, *directory_part;
2883 {
2884 int l, vl, dl2, xl;
2885 char *dh2, *expdir, *ret;
2886
2887 vl = strlen (val);
2888
2889 /* We need to duplicate the expansions readline performs on the directory
2890 portion before passing it to our completion function. */
2891 dh2 = directory_part ? bash_dequote_filename (directory_part, 0) : 0;
2892 bash_directory_expansion (&dh2);
2893 dl2 = strlen (dh2);
2894
2895 expdir = bash_tilde_expand (directory_part, 0);
2896 xl = strlen (expdir);
2897 free (expdir);
2898
2899 /*
2900 dh2 = unexpanded but dequoted tilde-prefix
2901 dl2 = length of tilde-prefix
2902 expdir = tilde-expanded tilde-prefix
2903 xl = length of expanded tilde-prefix
2904 l = length of remainder after tilde-prefix
2905 */
2906 l = (vl - xl) + 1;
2907
2908 ret = (char *)xmalloc (dl2 + 2 + l);
2909 strcpy (ret, dh2);
2910 strcpy (ret + dl2, val + xl);
2911
2912 free (dh2);
2913 return (ret);
2914 }
2915
2916 static char *
2917 maybe_restore_tilde (val, directory_part)
2918 char *val, *directory_part;
2919 {
2920 rl_icppfunc_t *save;
2921 char *ret;
2922
2923 save = (dircomplete_expand == 0) ? save_directory_hook () : (rl_icppfunc_t *)0;
2924 ret = restore_tilde (val, directory_part);
2925 if (save)
2926 restore_directory_hook (save);
2927 return ret;
2928 }
2929
2930 /* Simulate the expansions that will be performed by
2931 rl_filename_completion_function. This must be called with the address of
2932 a pointer to malloc'd memory. */
2933 static void
2934 bash_directory_expansion (dirname)
2935 char **dirname;
2936 {
2937 char *d, *nd;
2938
2939 d = savestring (*dirname);
2940
2941 if ((rl_directory_rewrite_hook) && (*rl_directory_rewrite_hook) (&d))
2942 {
2943 free (*dirname);
2944 *dirname = d;
2945 }
2946 else if (rl_directory_completion_hook && (*rl_directory_completion_hook) (&d))
2947 {
2948 free (*dirname);
2949 *dirname = d;
2950 }
2951 else if (rl_completion_found_quote)
2952 {
2953 nd = bash_dequote_filename (d, rl_completion_quote_character);
2954 free (*dirname);
2955 free (d);
2956 *dirname = nd;
2957 }
2958 }
2959
2960 /* If necessary, rewrite directory entry */
2961 static char *
2962 bash_filename_rewrite_hook (fname, fnlen)
2963 char *fname;
2964 int fnlen;
2965 {
2966 char *conv;
2967
2968 conv = fnx_fromfs (fname, fnlen);
2969 if (conv != fname)
2970 conv = savestring (conv);
2971 return conv;
2972 }
2973
2974 /* Functions to save and restore the appropriate directory hook */
2975 /* This is not static so the shopt code can call it */
2976 void
2977 set_directory_hook ()
2978 {
2979 if (dircomplete_expand)
2980 {
2981 rl_directory_completion_hook = bash_directory_completion_hook;
2982 rl_directory_rewrite_hook = (rl_icppfunc_t *)0;
2983 }
2984 else
2985 {
2986 rl_directory_rewrite_hook = bash_directory_completion_hook;
2987 rl_directory_completion_hook = (rl_icppfunc_t *)0;
2988 }
2989 }
2990
2991 static rl_icppfunc_t *
2992 save_directory_hook ()
2993 {
2994 rl_icppfunc_t *ret;
2995
2996 if (dircomplete_expand)
2997 {
2998 ret = rl_directory_completion_hook;
2999 rl_directory_completion_hook = (rl_icppfunc_t *)NULL;
3000 }
3001 else
3002 {
3003 ret = rl_directory_rewrite_hook;
3004 rl_directory_rewrite_hook = (rl_icppfunc_t *)NULL;
3005 }
3006
3007 return ret;
3008 }
3009
3010 static void
3011 restore_directory_hook (hookf)
3012 rl_icppfunc_t *hookf;
3013 {
3014 if (dircomplete_expand)
3015 rl_directory_completion_hook = hookf;
3016 else
3017 rl_directory_rewrite_hook = hookf;
3018 }
3019
3020 /* Expand a filename before the readline completion code passes it to stat(2).
3021 The filename will already have had tilde expansion performed. */
3022 static int
3023 bash_filename_stat_hook (dirname)
3024 char **dirname;
3025 {
3026 char *local_dirname, *new_dirname, *t;
3027 int should_expand_dirname, return_value;
3028 WORD_LIST *wl;
3029 struct stat sb;
3030
3031 local_dirname = *dirname;
3032 should_expand_dirname = return_value = 0;
3033 if (t = mbschr (local_dirname, '$'))
3034 should_expand_dirname = '$';
3035 else if (t = mbschr (local_dirname, '`')) /* XXX */
3036 should_expand_dirname = '`';
3037
3038 #if defined (HAVE_LSTAT)
3039 if (should_expand_dirname && lstat (local_dirname, &sb) == 0)
3040 #else
3041 if (should_expand_dirname && stat (local_dirname, &sb) == 0)
3042 #endif
3043 should_expand_dirname = 0;
3044
3045 if (should_expand_dirname)
3046 {
3047 new_dirname = savestring (local_dirname);
3048 wl = expand_prompt_string (new_dirname, 0, W_NOCOMSUB); /* does the right thing */
3049 if (wl)
3050 {
3051 free (new_dirname);
3052 new_dirname = string_list (wl);
3053 /* Tell the completer we actually expanded something and change
3054 *dirname only if we expanded to something non-null -- stat
3055 behaves unpredictably when passed null or empty strings */
3056 if (new_dirname && *new_dirname)
3057 {
3058 free (local_dirname); /* XXX */
3059 local_dirname = *dirname = new_dirname;
3060 return_value = STREQ (local_dirname, *dirname) == 0;
3061 }
3062 else
3063 free (new_dirname);
3064 dispose_words (wl);
3065 }
3066 else
3067 free (new_dirname);
3068 }
3069
3070 /* This is very similar to the code in bash_directory_completion_hook below,
3071 but without spelling correction and not worrying about whether or not
3072 we change relative pathnames. */
3073 if (no_symbolic_links == 0 && (local_dirname[0] != '.' || local_dirname[1]))
3074 {
3075 char *temp1, *temp2;
3076
3077 t = get_working_directory ("symlink-hook");
3078 temp1 = make_absolute (local_dirname, t);
3079 free (t);
3080 temp2 = sh_canonpath (temp1, PATH_CHECKDOTDOT|PATH_CHECKEXISTS);
3081
3082 /* If we can't canonicalize, bail. */
3083 if (temp2 == 0)
3084 {
3085 free (temp1);
3086 return return_value;
3087 }
3088
3089 free (local_dirname);
3090 *dirname = temp2;
3091 free (temp1);
3092 }
3093
3094 return (return_value);
3095 }
3096
3097 /* Handle symbolic link references and other directory name
3098 expansions while hacking completion. This should return 1 if it modifies
3099 the DIRNAME argument, 0 otherwise. It should make sure not to modify
3100 DIRNAME if it returns 0. */
3101 static int
3102 bash_directory_completion_hook (dirname)
3103 char **dirname;
3104 {
3105 char *local_dirname, *new_dirname, *t;
3106 int return_value, should_expand_dirname, nextch, closer;
3107 WORD_LIST *wl;
3108 struct stat sb;
3109
3110 return_value = should_expand_dirname = nextch = closer = 0;
3111 local_dirname = *dirname;
3112
3113 if (t = mbschr (local_dirname, '$'))
3114 {
3115 should_expand_dirname = '$';
3116 nextch = t[1];
3117 /* Deliberately does not handle the deprecated $[...] arithmetic
3118 expansion syntax */
3119 if (nextch == '(')
3120 closer = ')';
3121 else if (nextch == '{')
3122 closer = '}';
3123 else
3124 nextch = 0;
3125 }
3126 else if (local_dirname[0] == '~')
3127 should_expand_dirname = '~';
3128 else
3129 {
3130 t = mbschr (local_dirname, '`');
3131 if (t && unclosed_pair (local_dirname, strlen (local_dirname), "`") == 0)
3132 should_expand_dirname = '`';
3133 }
3134
3135 #if defined (HAVE_LSTAT)
3136 if (should_expand_dirname && lstat (local_dirname, &sb) == 0)
3137 #else
3138 if (should_expand_dirname && stat (local_dirname, &sb) == 0)
3139 #endif
3140 should_expand_dirname = 0;
3141
3142 if (should_expand_dirname)
3143 {
3144 new_dirname = savestring (local_dirname);
3145 wl = expand_prompt_string (new_dirname, 0, W_NOCOMSUB); /* does the right thing */
3146 if (wl)
3147 {
3148 *dirname = string_list (wl);
3149 /* Tell the completer to replace the directory name only if we
3150 actually expanded something. */
3151 return_value = STREQ (local_dirname, *dirname) == 0;
3152 free (local_dirname);
3153 free (new_dirname);
3154 dispose_words (wl);
3155 local_dirname = *dirname;
3156 /* XXX - change rl_filename_quote_characters here based on
3157 should_expand_dirname/nextch/closer. This is the only place
3158 custom_filename_quote_characters is modified. */
3159 if (rl_filename_quote_characters && *rl_filename_quote_characters)
3160 {
3161 int i, j, c;
3162 i = strlen (default_filename_quote_characters);
3163 custom_filename_quote_characters = xrealloc (custom_filename_quote_characters, i+1);
3164 for (i = j = 0; c = default_filename_quote_characters[i]; i++)
3165 {
3166 if (c == should_expand_dirname || c == nextch || c == closer)
3167 continue;
3168 custom_filename_quote_characters[j++] = c;
3169 }
3170 custom_filename_quote_characters[j] = '\0';
3171 rl_filename_quote_characters = custom_filename_quote_characters;
3172 set_filename_bstab (rl_filename_quote_characters);
3173 }
3174 }
3175 else
3176 {
3177 free (new_dirname);
3178 free (local_dirname);
3179 *dirname = (char *)xmalloc (1);
3180 **dirname = '\0';
3181 return 1;
3182 }
3183 }
3184 else
3185 {
3186 /* Dequote the filename even if we don't expand it. */
3187 new_dirname = bash_dequote_filename (local_dirname, rl_completion_quote_character);
3188 return_value = STREQ (local_dirname, new_dirname) == 0;
3189 free (local_dirname);
3190 local_dirname = *dirname = new_dirname;
3191 }
3192
3193 /* no_symbolic_links == 0 -> use (default) logical view of the file system.
3194 local_dirname[0] == '.' && local_dirname[1] == '/' means files in the
3195 current directory (./).
3196 local_dirname[0] == '.' && local_dirname[1] == 0 means relative pathnames
3197 in the current directory (e.g., lib/sh).
3198 XXX - should we do spelling correction on these? */
3199
3200 /* This is test as it was in bash-4.2: skip relative pathnames in current
3201 directory. Change test to
3202 (local_dirname[0] != '.' || (local_dirname[1] && local_dirname[1] != '/'))
3203 if we want to skip paths beginning with ./ also. */
3204 if (no_symbolic_links == 0 && (local_dirname[0] != '.' || local_dirname[1]))
3205 {
3206 char *temp1, *temp2;
3207 int len1, len2;
3208
3209 /* If we have a relative path
3210 (local_dirname[0] != '/' && local_dirname[0] != '.')
3211 that is canonical after appending it to the current directory, then
3212 temp1 = temp2+'/'
3213 That is,
3214 strcmp (temp1, temp2) == 0
3215 after adding a slash to temp2 below. It should be safe to not
3216 change those.
3217 */
3218 t = get_working_directory ("symlink-hook");
3219 temp1 = make_absolute (local_dirname, t);
3220 free (t);
3221 temp2 = sh_canonpath (temp1, PATH_CHECKDOTDOT|PATH_CHECKEXISTS);
3222
3223 /* Try spelling correction if initial canonicalization fails. Make
3224 sure we are set to replace the directory name with the results so
3225 subsequent directory checks don't fail. */
3226 if (temp2 == 0 && dircomplete_spelling && dircomplete_expand)
3227 {
3228 temp2 = dirspell (temp1);
3229 if (temp2)
3230 {
3231 free (temp1);
3232 temp1 = temp2;
3233 temp2 = sh_canonpath (temp1, PATH_CHECKDOTDOT|PATH_CHECKEXISTS);
3234 return_value |= temp2 != 0;
3235 }
3236 }
3237 /* If we can't canonicalize, bail. */
3238 if (temp2 == 0)
3239 {
3240 free (temp1);
3241 return return_value;
3242 }
3243 len1 = strlen (temp1);
3244 if (temp1[len1 - 1] == '/')
3245 {
3246 len2 = strlen (temp2);
3247 if (len2 > 2) /* don't append `/' to `/' or `//' */
3248 {
3249 temp2 = (char *)xrealloc (temp2, len2 + 2);
3250 temp2[len2] = '/';
3251 temp2[len2 + 1] = '\0';
3252 }
3253 }
3254
3255 /* dircomplete_expand_relpath == 0 means we want to leave relative
3256 pathnames that are unchanged by canonicalization alone.
3257 *local_dirname != '/' && *local_dirname != '.' == relative pathname
3258 (consistent with general.c:absolute_pathname())
3259 temp1 == temp2 (after appending a slash to temp2) means the pathname
3260 is not changed by canonicalization as described above. */
3261 if (dircomplete_expand_relpath || ((local_dirname[0] != '/' && local_dirname[0] != '.') && STREQ (temp1, temp2) == 0))
3262 return_value |= STREQ (local_dirname, temp2) == 0;
3263 free (local_dirname);
3264 *dirname = temp2;
3265 free (temp1);
3266 }
3267
3268 return (return_value);
3269 }
3270
3271 static char **history_completion_array = (char **)NULL;
3272 static int harry_size;
3273 static int harry_len;
3274
3275 static void
3276 build_history_completion_array ()
3277 {
3278 register int i, j;
3279 HIST_ENTRY **hlist;
3280 char **tokens;
3281
3282 /* First, clear out the current dynamic history completion list. */
3283 if (harry_size)
3284 {
3285 strvec_dispose (history_completion_array);
3286 history_completion_array = (char **)NULL;
3287 harry_size = 0;
3288 harry_len = 0;
3289 }
3290
3291 /* Next, grovel each line of history, making each shell-sized token
3292 a separate entry in the history_completion_array. */
3293 hlist = history_list ();
3294
3295 if (hlist)
3296 {
3297 for (i = 0; hlist[i]; i++)
3298 ;
3299 for ( --i; i >= 0; i--)
3300 {
3301 /* Separate each token, and place into an array. */
3302 tokens = history_tokenize (hlist[i]->line);
3303
3304 for (j = 0; tokens && tokens[j]; j++)
3305 {
3306 if (harry_len + 2 > harry_size)
3307 history_completion_array = strvec_resize (history_completion_array, harry_size += 10);
3308
3309 history_completion_array[harry_len++] = tokens[j];
3310 history_completion_array[harry_len] = (char *)NULL;
3311 }
3312 free (tokens);
3313 }
3314
3315 /* Sort the complete list of tokens. */
3316 if (dabbrev_expand_active == 0)
3317 qsort (history_completion_array, harry_len, sizeof (char *), (QSFUNC *)strvec_strcmp);
3318 }
3319 }
3320
3321 static char *
3322 history_completion_generator (hint_text, state)
3323 const char *hint_text;
3324 int state;
3325 {
3326 static int local_index, len;
3327 static const char *text;
3328
3329 /* If this is the first call to the generator, then initialize the
3330 list of strings to complete over. */
3331 if (state == 0)
3332 {
3333 if (dabbrev_expand_active) /* This is kind of messy */
3334 rl_completion_suppress_append = 1;
3335 local_index = 0;
3336 build_history_completion_array ();
3337 text = hint_text;
3338 len = strlen (text);
3339 }
3340
3341 while (history_completion_array && history_completion_array[local_index])
3342 {
3343 if (strncmp (text, history_completion_array[local_index++], len) == 0)
3344 return (savestring (history_completion_array[local_index - 1]));
3345 }
3346 return ((char *)NULL);
3347 }
3348
3349 static int
3350 dynamic_complete_history (count, key)
3351 int count, key;
3352 {
3353 int r;
3354 rl_compentry_func_t *orig_func;
3355 rl_completion_func_t *orig_attempt_func;
3356 rl_compignore_func_t *orig_ignore_func;
3357
3358 orig_func = rl_completion_entry_function;
3359 orig_attempt_func = rl_attempted_completion_function;
3360 orig_ignore_func = rl_ignore_some_completions_function;
3361
3362 rl_completion_entry_function = history_completion_generator;
3363 rl_attempted_completion_function = (rl_completion_func_t *)NULL;
3364 rl_ignore_some_completions_function = filename_completion_ignore;
3365
3366 /* XXX - use rl_completion_mode here? */
3367 if (rl_last_func == dynamic_complete_history)
3368 r = rl_complete_internal ('?');
3369 else
3370 r = rl_complete_internal (TAB);
3371
3372 rl_completion_entry_function = orig_func;
3373 rl_attempted_completion_function = orig_attempt_func;
3374 rl_ignore_some_completions_function = orig_ignore_func;
3375
3376 return r;
3377 }
3378
3379 static int
3380 bash_dabbrev_expand (count, key)
3381 int count, key;
3382 {
3383 int r, orig_suppress, orig_sort;
3384 rl_compentry_func_t *orig_func;
3385 rl_completion_func_t *orig_attempt_func;
3386 rl_compignore_func_t *orig_ignore_func;
3387
3388 orig_func = rl_menu_completion_entry_function;
3389 orig_attempt_func = rl_attempted_completion_function;
3390 orig_ignore_func = rl_ignore_some_completions_function;
3391 orig_suppress = rl_completion_suppress_append;
3392 orig_sort = rl_sort_completion_matches;
3393
3394 rl_menu_completion_entry_function = history_completion_generator;
3395 rl_attempted_completion_function = (rl_completion_func_t *)NULL;
3396 rl_ignore_some_completions_function = filename_completion_ignore;
3397 rl_filename_completion_desired = 0;
3398 rl_completion_suppress_append = 1;
3399 rl_sort_completion_matches = 0;
3400
3401 /* XXX - use rl_completion_mode here? */
3402 dabbrev_expand_active = 1;
3403 if (rl_last_func == bash_dabbrev_expand)
3404 rl_last_func = rl_menu_complete;
3405 r = rl_menu_complete (count, key);
3406 dabbrev_expand_active = 0;
3407
3408 rl_last_func = bash_dabbrev_expand;
3409 rl_menu_completion_entry_function = orig_func;
3410 rl_attempted_completion_function = orig_attempt_func;
3411 rl_ignore_some_completions_function = orig_ignore_func;
3412 rl_completion_suppress_append = orig_suppress;
3413 rl_sort_completion_matches = orig_sort;
3414
3415 return r;
3416 }
3417
3418 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
3419 static int
3420 bash_complete_username (ignore, ignore2)
3421 int ignore, ignore2;
3422 {
3423 return bash_complete_username_internal (rl_completion_mode (bash_complete_username));
3424 }
3425
3426 static int
3427 bash_possible_username_completions (ignore, ignore2)
3428 int ignore, ignore2;
3429 {
3430 return bash_complete_username_internal ('?');
3431 }
3432
3433 static int
3434 bash_complete_username_internal (what_to_do)
3435 int what_to_do;
3436 {
3437 return bash_specific_completion (what_to_do, rl_username_completion_function);
3438 }
3439
3440 static int
3441 bash_complete_filename (ignore, ignore2)
3442 int ignore, ignore2;
3443 {
3444 return bash_complete_filename_internal (rl_completion_mode (bash_complete_filename));
3445 }
3446
3447 static int
3448 bash_possible_filename_completions (ignore, ignore2)
3449 int ignore, ignore2;
3450 {
3451 return bash_complete_filename_internal ('?');
3452 }
3453
3454 static int
3455 bash_complete_filename_internal (what_to_do)
3456 int what_to_do;
3457 {
3458 rl_compentry_func_t *orig_func;
3459 rl_completion_func_t *orig_attempt_func;
3460 rl_icppfunc_t *orig_dir_func;
3461 rl_compignore_func_t *orig_ignore_func;
3462 /*const*/ char *orig_rl_completer_word_break_characters;
3463 int r;
3464
3465 orig_func = rl_completion_entry_function;
3466 orig_attempt_func = rl_attempted_completion_function;
3467 orig_ignore_func = rl_ignore_some_completions_function;
3468 orig_rl_completer_word_break_characters = rl_completer_word_break_characters;
3469
3470 orig_dir_func = save_directory_hook ();
3471
3472 rl_completion_entry_function = rl_filename_completion_function;
3473 rl_attempted_completion_function = (rl_completion_func_t *)NULL;
3474 rl_ignore_some_completions_function = filename_completion_ignore;
3475 rl_completer_word_break_characters = " \t\n\"\'";
3476
3477 r = rl_complete_internal (what_to_do);
3478
3479 rl_completion_entry_function = orig_func;
3480 rl_attempted_completion_function = orig_attempt_func;
3481 rl_ignore_some_completions_function = orig_ignore_func;
3482 rl_completer_word_break_characters = orig_rl_completer_word_break_characters;
3483
3484 restore_directory_hook (orig_dir_func);
3485
3486 return r;
3487 }
3488
3489 static int
3490 bash_complete_hostname (ignore, ignore2)
3491 int ignore, ignore2;
3492 {
3493 return bash_complete_hostname_internal (rl_completion_mode (bash_complete_hostname));
3494 }
3495
3496 static int
3497 bash_possible_hostname_completions (ignore, ignore2)
3498 int ignore, ignore2;
3499 {
3500 return bash_complete_hostname_internal ('?');
3501 }
3502
3503 static int
3504 bash_complete_variable (ignore, ignore2)
3505 int ignore, ignore2;
3506 {
3507 return bash_complete_variable_internal (rl_completion_mode (bash_complete_variable));
3508 }
3509
3510 static int
3511 bash_possible_variable_completions (ignore, ignore2)
3512 int ignore, ignore2;
3513 {
3514 return bash_complete_variable_internal ('?');
3515 }
3516
3517 static int
3518 bash_complete_command (ignore, ignore2)
3519 int ignore, ignore2;
3520 {
3521 return bash_complete_command_internal (rl_completion_mode (bash_complete_command));
3522 }
3523
3524 static int
3525 bash_possible_command_completions (ignore, ignore2)
3526 int ignore, ignore2;
3527 {
3528 return bash_complete_command_internal ('?');
3529 }
3530
3531 static int
3532 bash_complete_hostname_internal (what_to_do)
3533 int what_to_do;
3534 {
3535 return bash_specific_completion (what_to_do, hostname_completion_function);
3536 }
3537
3538 static int
3539 bash_complete_variable_internal (what_to_do)
3540 int what_to_do;
3541 {
3542 return bash_specific_completion (what_to_do, variable_completion_function);
3543 }
3544
3545 static int
3546 bash_complete_command_internal (what_to_do)
3547 int what_to_do;
3548 {
3549 return bash_specific_completion (what_to_do, command_word_completion_function);
3550 }
3551
3552 static char *globtext;
3553 static char *globorig;
3554
3555 static char *
3556 glob_complete_word (text, state)
3557 const char *text;
3558 int state;
3559 {
3560 static char **matches = (char **)NULL;
3561 static int ind;
3562 int glen;
3563 char *ret, *ttext;
3564
3565 if (state == 0)
3566 {
3567 rl_filename_completion_desired = 1;
3568 FREE (matches);
3569 if (globorig != globtext)
3570 FREE (globorig);
3571 FREE (globtext);
3572
3573 ttext = bash_tilde_expand (text, 0);
3574
3575 if (rl_explicit_arg)
3576 {
3577 globorig = savestring (ttext);
3578 glen = strlen (ttext);
3579 globtext = (char *)xmalloc (glen + 2);
3580 strcpy (globtext, ttext);
3581 globtext[glen] = '*';
3582 globtext[glen+1] = '\0';
3583 }
3584 else
3585 globtext = globorig = savestring (ttext);
3586
3587 if (ttext != text)
3588 free (ttext);
3589
3590 matches = shell_glob_filename (globtext);
3591 if (GLOB_FAILED (matches))
3592 matches = (char **)NULL;
3593 ind = 0;
3594 }
3595
3596 ret = matches ? matches[ind] : (char *)NULL;
3597 ind++;
3598 return ret;
3599 }
3600
3601 static int
3602 bash_glob_completion_internal (what_to_do)
3603 int what_to_do;
3604 {
3605 return bash_specific_completion (what_to_do, glob_complete_word);
3606 }
3607
3608 /* A special quoting function so we don't end up quoting globbing characters
3609 in the word if there are no matches or multiple matches. */
3610 static char *
3611 bash_glob_quote_filename (s, rtype, qcp)
3612 char *s;
3613 int rtype;
3614 char *qcp;
3615 {
3616 if (globorig && qcp && *qcp == '\0' && STREQ (s, globorig))
3617 return (savestring (s));
3618 else
3619 return (bash_quote_filename (s, rtype, qcp));
3620 }
3621
3622 static int
3623 bash_glob_complete_word (count, key)
3624 int count, key;
3625 {
3626 int r;
3627 rl_quote_func_t *orig_quoting_function;
3628
3629 if (rl_editing_mode == EMACS_EDITING_MODE)
3630 rl_explicit_arg = 1; /* force `*' append */
3631 orig_quoting_function = rl_filename_quoting_function;
3632 rl_filename_quoting_function = bash_glob_quote_filename;
3633
3634 r = bash_glob_completion_internal (rl_completion_mode (bash_glob_complete_word));
3635
3636 rl_filename_quoting_function = orig_quoting_function;
3637 return r;
3638 }
3639
3640 static int
3641 bash_glob_expand_word (count, key)
3642 int count, key;
3643 {
3644 return bash_glob_completion_internal ('*');
3645 }
3646
3647 static int
3648 bash_glob_list_expansions (count, key)
3649 int count, key;
3650 {
3651 return bash_glob_completion_internal ('?');
3652 }
3653
3654 static int
3655 bash_specific_completion (what_to_do, generator)
3656 int what_to_do;
3657 rl_compentry_func_t *generator;
3658 {
3659 rl_compentry_func_t *orig_func;
3660 rl_completion_func_t *orig_attempt_func;
3661 rl_compignore_func_t *orig_ignore_func;
3662 int r;
3663
3664 orig_func = rl_completion_entry_function;
3665 orig_attempt_func = rl_attempted_completion_function;
3666 orig_ignore_func = rl_ignore_some_completions_function;
3667 rl_completion_entry_function = generator;
3668 rl_attempted_completion_function = NULL;
3669 rl_ignore_some_completions_function = orig_ignore_func;
3670
3671 r = rl_complete_internal (what_to_do);
3672
3673 rl_completion_entry_function = orig_func;
3674 rl_attempted_completion_function = orig_attempt_func;
3675 rl_ignore_some_completions_function = orig_ignore_func;
3676
3677 return r;
3678 }
3679
3680 #endif /* SPECIFIC_COMPLETION_FUNCTIONS */
3681
3682 #if defined (VI_MODE)
3683 /* Completion, from vi mode's point of view. This is a modified version of
3684 rl_vi_complete which uses the bash globbing code to implement what POSIX
3685 specifies, which is to append a `*' and attempt filename generation (which
3686 has the side effect of expanding any globbing characters in the word). */
3687 static int
3688 bash_vi_complete (count, key)
3689 int count, key;
3690 {
3691 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
3692 int p, r;
3693 char *t;
3694
3695 if ((rl_point < rl_end) && (!whitespace (rl_line_buffer[rl_point])))
3696 {
3697 if (!whitespace (rl_line_buffer[rl_point + 1]))
3698 rl_vi_end_word (1, 'E');
3699 rl_point++;
3700 }
3701
3702 /* Find boundaries of current word, according to vi definition of a
3703 `bigword'. */
3704 t = 0;
3705 if (rl_point > 0)
3706 {
3707 p = rl_point;
3708 rl_vi_bWord (1, 'B');
3709 r = rl_point;
3710 rl_point = p;
3711 p = r;
3712
3713 t = substring (rl_line_buffer, p, rl_point);
3714 }
3715
3716 if (t && glob_pattern_p (t) == 0)
3717 rl_explicit_arg = 1; /* XXX - force glob_complete_word to append `*' */
3718 FREE (t);
3719
3720 if (key == '*') /* Expansion and replacement. */
3721 r = bash_glob_expand_word (count, key);
3722 else if (key == '=') /* List possible completions. */
3723 r = bash_glob_list_expansions (count, key);
3724 else if (key == '\\') /* Standard completion */
3725 r = bash_glob_complete_word (count, key);
3726 else
3727 r = rl_complete (0, key);
3728
3729 if (key == '*' || key == '\\')
3730 rl_vi_start_inserting (key, 1, 1);
3731
3732 return (r);
3733 #else
3734 return rl_vi_complete (count, key);
3735 #endif /* !SPECIFIC_COMPLETION_FUNCTIONS */
3736 }
3737 #endif /* VI_MODE */
3738
3739 /* Filename quoting for completion. */
3740 /* A function to strip unquoted quote characters (single quotes, double
3741 quotes, and backslashes). It allows single quotes to appear
3742 within double quotes, and vice versa. It should be smarter. */
3743 static char *
3744 bash_dequote_filename (text, quote_char)
3745 char *text;
3746 int quote_char;
3747 {
3748 char *ret, *p, *r;
3749 int l, quoted;
3750
3751 l = strlen (text);
3752 ret = (char *)xmalloc (l + 1);
3753 for (quoted = quote_char, p = text, r = ret; p && *p; p++)
3754 {
3755 /* Allow backslash-escaped characters to pass through unscathed. */
3756 if (*p == '\\')
3757 {
3758 /* Backslashes are preserved within single quotes. */
3759 if (quoted == '\'')
3760 *r++ = *p;
3761 /* Backslashes are preserved within double quotes unless the
3762 character is one that is defined to be escaped */
3763 else if (quoted == '"' && ((sh_syntaxtab[p[1]] & CBSDQUOTE) == 0))
3764 *r++ = *p;
3765
3766 *r++ = *++p;
3767 if (*p == '\0')
3768 return ret; /* XXX - was break; */
3769 continue;
3770 }
3771 /* Close quote. */
3772 if (quoted && *p == quoted)
3773 {
3774 quoted = 0;
3775 continue;
3776 }
3777 /* Open quote. */
3778 if (quoted == 0 && (*p == '\'' || *p == '"'))
3779 {
3780 quoted = *p;
3781 continue;
3782 }
3783 *r++ = *p;
3784 }
3785 *r = '\0';
3786 return ret;
3787 }
3788
3789 /* Quote characters that the readline completion code would treat as
3790 word break characters with backslashes. Pass backslash-quoted
3791 characters through without examination. */
3792 static char *
3793 quote_word_break_chars (text)
3794 char *text;
3795 {
3796 char *ret, *r, *s;
3797 int l;
3798
3799 l = strlen (text);
3800 ret = (char *)xmalloc ((2 * l) + 1);
3801 for (s = text, r = ret; *s; s++)
3802 {
3803 /* Pass backslash-quoted characters through, including the backslash. */
3804 if (*s == '\\')
3805 {
3806 *r++ = '\\';
3807 *r++ = *++s;
3808 if (*s == '\0')
3809 break;
3810 continue;
3811 }
3812 /* OK, we have an unquoted character. Check its presence in
3813 rl_completer_word_break_characters. */
3814 if (mbschr (rl_completer_word_break_characters, *s))
3815 *r++ = '\\';
3816 /* XXX -- check for standalone tildes here and backslash-quote them */
3817 if (s == text && *s == '~' && file_exists (text))
3818 *r++ = '\\';
3819 *r++ = *s;
3820 }
3821 *r = '\0';
3822 return ret;
3823 }
3824
3825 /* Use characters in STRING to populate the table of characters that should
3826 be backslash-quoted. The table will be used for sh_backslash_quote from
3827 this file. */
3828 static void
3829 set_filename_bstab (string)
3830 const char *string;
3831 {
3832 const char *s;
3833
3834 memset (filename_bstab, 0, sizeof (filename_bstab));
3835 for (s = string; s && *s; s++)
3836 filename_bstab[*s] = 1;
3837 }
3838
3839 /* Quote a filename using double quotes, single quotes, or backslashes
3840 depending on the value of completion_quoting_style. If we're
3841 completing using backslashes, we need to quote some additional
3842 characters (those that readline treats as word breaks), so we call
3843 quote_word_break_chars on the result. This returns newly-allocated
3844 memory. */
3845 static char *
3846 bash_quote_filename (s, rtype, qcp)
3847 char *s;
3848 int rtype;
3849 char *qcp;
3850 {
3851 char *rtext, *mtext, *ret;
3852 int rlen, cs;
3853
3854 rtext = (char *)NULL;
3855
3856 /* If RTYPE == MULT_MATCH, it means that there is
3857 more than one match. In this case, we do not add
3858 the closing quote or attempt to perform tilde
3859 expansion. If RTYPE == SINGLE_MATCH, we try
3860 to perform tilde expansion, because single and double
3861 quotes inhibit tilde expansion by the shell. */
3862
3863 cs = completion_quoting_style;
3864 /* Might need to modify the default completion style based on *qcp,
3865 since it's set to any user-provided opening quote. We also change
3866 to single-quoting if there is no user-provided opening quote and
3867 the word being completed contains newlines, since those are not
3868 quoted correctly using backslashes (a backslash-newline pair is
3869 special to the shell parser). */
3870 if (*qcp == '\0' && cs == COMPLETE_BSQUOTE && mbschr (s, '\n'))
3871 cs = COMPLETE_SQUOTE;
3872 else if (*qcp == '"')
3873 cs = COMPLETE_DQUOTE;
3874 else if (*qcp == '\'')
3875 cs = COMPLETE_SQUOTE;
3876 #if defined (BANG_HISTORY)
3877 else if (*qcp == '\0' && history_expansion && cs == COMPLETE_DQUOTE &&
3878 history_expansion_inhibited == 0 && mbschr (s, '!'))
3879 cs = COMPLETE_BSQUOTE;
3880
3881 if (*qcp == '"' && history_expansion && cs == COMPLETE_DQUOTE &&
3882 history_expansion_inhibited == 0 && mbschr (s, '!'))
3883 {
3884 cs = COMPLETE_BSQUOTE;
3885 *qcp = '\0';
3886 }
3887 #endif
3888
3889 /* Don't tilde-expand backslash-quoted filenames, since only single and
3890 double quotes inhibit tilde expansion. */
3891 mtext = s;
3892 if (mtext[0] == '~' && rtype == SINGLE_MATCH && cs != COMPLETE_BSQUOTE)
3893 mtext = bash_tilde_expand (s, 0);
3894
3895 switch (cs)
3896 {
3897 case COMPLETE_DQUOTE:
3898 rtext = sh_double_quote (mtext);
3899 break;
3900 case COMPLETE_SQUOTE:
3901 rtext = sh_single_quote (mtext);
3902 break;
3903 case COMPLETE_BSQUOTE:
3904 rtext = sh_backslash_quote (mtext, complete_fullquote ? 0 : filename_bstab, 0);
3905 break;
3906 }
3907
3908 if (mtext != s)
3909 free (mtext);
3910
3911 /* We may need to quote additional characters: those that readline treats
3912 as word breaks that are not quoted by backslash_quote. */
3913 if (rtext && cs == COMPLETE_BSQUOTE)
3914 {
3915 mtext = quote_word_break_chars (rtext);
3916 free (rtext);
3917 rtext = mtext;
3918 }
3919
3920 /* Leave the opening quote intact. The readline completion code takes
3921 care of avoiding doubled opening quotes. */
3922 if (rtext)
3923 {
3924 rlen = strlen (rtext);
3925 ret = (char *)xmalloc (rlen + 1);
3926 strcpy (ret, rtext);
3927 }
3928 else
3929 {
3930 ret = (char *)xmalloc (rlen = 1);
3931 ret[0] = '\0';
3932 }
3933
3934 /* If there are multiple matches, cut off the closing quote. */
3935 if (rtype == MULT_MATCH && cs != COMPLETE_BSQUOTE)
3936 ret[rlen - 1] = '\0';
3937 free (rtext);
3938 return ret;
3939 }
3940
3941 /* Support for binding readline key sequences to Unix commands. */
3942 static Keymap cmd_xmap;
3943
3944 #ifdef _MINIX
3945 static void
3946 #else
3947 static int
3948 #endif
3949 putx(c)
3950 int c;
3951 {
3952 int x;
3953 x = putc (c, rl_outstream);
3954 #ifndef _MINIX
3955 return x;
3956 #endif
3957 }
3958
3959 static int
3960 bash_execute_unix_command (count, key)
3961 int count; /* ignored */
3962 int key;
3963 {
3964 Keymap ckmap; /* current keymap */
3965 Keymap xkmap; /* unix command executing keymap */
3966 rl_command_func_t *func;
3967 int type;
3968 register int i, r;
3969 intmax_t mi;
3970 sh_parser_state_t ps;
3971 char *cmd, *value, *l, *l1, *ce;
3972 SHELL_VAR *v;
3973 char ibuf[INT_STRLEN_BOUND(int) + 1];
3974
3975 /* First, we need to find the right command to execute. This is tricky,
3976 because we might have already indirected into another keymap, so we
3977 have to walk cmd_xmap using the entire key sequence. */
3978 cmd = (char *)rl_function_of_keyseq (rl_executing_keyseq, cmd_xmap, &type);
3979
3980 if (cmd == 0 || type != ISMACR)
3981 {
3982 rl_crlf ();
3983 internal_error (_("bash_execute_unix_command: cannot find keymap for command"));
3984 rl_forced_update_display ();
3985 return 1;
3986 }
3987
3988 ce = rl_get_termcap ("ce");
3989 if (ce) /* clear current line */
3990 {
3991 fprintf (rl_outstream, "\r");
3992 tputs (ce, 1, putx);
3993 fflush (rl_outstream);
3994 }
3995 else
3996 rl_crlf (); /* move to a new line */
3997
3998 v = bind_variable ("READLINE_LINE", rl_line_buffer, 0);
3999 if (v)
4000 VSETATTR (v, att_exported);
4001 l = v ? value_cell (v) : 0;
4002 value = inttostr (rl_point, ibuf, sizeof (ibuf));
4003 v = bind_int_variable ("READLINE_POINT", value);
4004 if (v)
4005 VSETATTR (v, att_exported);
4006 array_needs_making = 1;
4007
4008 save_parser_state (&ps);
4009 r = parse_and_execute (cmd, "bash_execute_unix_command", SEVAL_NOHIST|SEVAL_NOFREE);
4010 restore_parser_state (&ps);
4011
4012 v = find_variable ("READLINE_LINE");
4013 l1 = v ? value_cell (v) : 0;
4014 if (l1 != l)
4015 maybe_make_readline_line (value_cell (v));
4016 v = find_variable ("READLINE_POINT");
4017 if (v && legal_number (value_cell (v), &mi))
4018 {
4019 i = mi;
4020 if (i != rl_point)
4021 {
4022 rl_point = i;
4023 if (rl_point > rl_end)
4024 rl_point = rl_end;
4025 else if (rl_point < 0)
4026 rl_point = 0;
4027 }
4028 }
4029
4030 unbind_variable ("READLINE_LINE");
4031 unbind_variable ("READLINE_POINT");
4032 array_needs_making = 1;
4033
4034 /* and restore the readline buffer and display after command execution. */
4035 rl_forced_update_display ();
4036 return 0;
4037 }
4038
4039 int
4040 print_unix_command_map ()
4041 {
4042 Keymap save;
4043
4044 save = rl_get_keymap ();
4045 rl_set_keymap (cmd_xmap);
4046 rl_macro_dumper (1);
4047 rl_set_keymap (save);
4048 return 0;
4049 }
4050
4051 static void
4052 init_unix_command_map ()
4053 {
4054 cmd_xmap = rl_make_bare_keymap ();
4055 }
4056
4057 static int
4058 isolate_sequence (string, ind, need_dquote, startp)
4059 char *string;
4060 int ind, need_dquote, *startp;
4061 {
4062 register int i;
4063 int c, passc, delim;
4064
4065 for (i = ind; string[i] && whitespace (string[i]); i++)
4066 ;
4067 /* NEED_DQUOTE means that the first non-white character *must* be `"'. */
4068 if (need_dquote && string[i] != '"')
4069 {
4070 builtin_error (_("%s: first non-whitespace character is not `\"'"), string);
4071 return -1;
4072 }
4073
4074 /* We can have delimited strings even if NEED_DQUOTE == 0, like the command
4075 string to bind the key sequence to. */
4076 delim = (string[i] == '"' || string[i] == '\'') ? string[i] : 0;
4077
4078 if (startp)
4079 *startp = delim ? ++i : i;
4080
4081 for (passc = 0; c = string[i]; i++)
4082 {
4083 if (passc)
4084 {
4085 passc = 0;
4086 continue;
4087 }
4088 if (c == '\\')
4089 {
4090 passc++;
4091 continue;
4092 }
4093 if (c == delim)
4094 break;
4095 }
4096
4097 if (delim && string[i] != delim)
4098 {
4099 builtin_error (_("no closing `%c' in %s"), delim, string);
4100 return -1;
4101 }
4102
4103 return i;
4104 }
4105
4106 int
4107 bind_keyseq_to_unix_command (line)
4108 char *line;
4109 {
4110 Keymap kmap;
4111 char *kseq, *value;
4112 int i, kstart;
4113
4114 if (cmd_xmap == 0)
4115 init_unix_command_map ();
4116
4117 kmap = rl_get_keymap ();
4118
4119 /* We duplicate some of the work done by rl_parse_and_bind here, but
4120 this code only has to handle `"keyseq": ["]command["]' and can
4121 generate an error for anything else. */
4122 i = isolate_sequence (line, 0, 1, &kstart);
4123 if (i < 0)
4124 return -1;
4125
4126 /* Create the key sequence string to pass to rl_generic_bind */
4127 kseq = substring (line, kstart, i);
4128
4129 for ( ; line[i] && line[i] != ':'; i++)
4130 ;
4131 if (line[i] != ':')
4132 {
4133 builtin_error (_("%s: missing colon separator"), line);
4134 FREE (kseq);
4135 return -1;
4136 }
4137
4138 i = isolate_sequence (line, i + 1, 0, &kstart);
4139 if (i < 0)
4140 {
4141 FREE (kseq);
4142 return -1;
4143 }
4144
4145 /* Create the value string containing the command to execute. */
4146 value = substring (line, kstart, i);
4147
4148 /* Save the command to execute and the key sequence in the CMD_XMAP */
4149 rl_generic_bind (ISMACR, kseq, value, cmd_xmap);
4150
4151 /* and bind the key sequence in the current keymap to a function that
4152 understands how to execute from CMD_XMAP */
4153 rl_bind_keyseq_in_map (kseq, bash_execute_unix_command, kmap);
4154
4155 free (kseq);
4156 return 0;
4157 }
4158
4159 /* Used by the programmable completion code. Complete TEXT as a filename,
4160 but return only directories as matches. Dequotes the filename before
4161 attempting to find matches. */
4162 char **
4163 bash_directory_completion_matches (text)
4164 const char *text;
4165 {
4166 char **m1;
4167 char *dfn;
4168 int qc;
4169
4170 qc = rl_dispatching ? rl_completion_quote_character : 0;
4171 /* If rl_completion_found_quote != 0, rl_completion_matches will call the
4172 filename dequoting function, causing the directory name to be dequoted
4173 twice. */
4174 if (rl_dispatching && rl_completion_found_quote == 0)
4175 dfn = bash_dequote_filename ((char *)text, qc);
4176 else
4177 dfn = (char *)text;
4178 m1 = rl_completion_matches (dfn, rl_filename_completion_function);
4179 if (dfn != text)
4180 free (dfn);
4181
4182 if (m1 == 0 || m1[0] == 0)
4183 return m1;
4184 /* We don't bother recomputing the lcd of the matches, because it will just
4185 get thrown away by the programmable completion code and recomputed
4186 later. */
4187 (void)bash_ignore_filenames (m1);
4188 return m1;
4189 }
4190
4191 char *
4192 bash_dequote_text (text)
4193 const char *text;
4194 {
4195 char *dtxt;
4196 int qc;
4197
4198 qc = (text[0] == '"' || text[0] == '\'') ? text[0] : 0;
4199 dtxt = bash_dequote_filename ((char *)text, qc);
4200 return (dtxt);
4201 }
4202
4203 /* This event hook is designed to be called after readline receives a signal
4204 that interrupts read(2). It gives reasonable responsiveness to interrupts
4205 and fatal signals without executing too much code in a signal handler
4206 context. */
4207 static int
4208 bash_event_hook ()
4209 {
4210 /* If we're going to longjmp to top_level, make sure we clean up readline.
4211 check_signals will call QUIT, which will eventually longjmp to top_level,
4212 calling run_interrupt_trap along the way. The check for sigalrm_seen is
4213 to clean up the read builtin's state. */
4214 if (terminating_signal || interrupt_state || sigalrm_seen)
4215 rl_cleanup_after_signal ();
4216 bashline_reset_event_hook ();
4217 check_signals_and_traps (); /* XXX */
4218 return 0;
4219 }
4220
4221 #endif /* READLINE */