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