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