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