]> git.ipfire.org Git - thirdparty/bash.git/blob - bashline.c
allow builtins to assign to associative arrays using @ or * as keys; fixes to glob...
[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 ((char *)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 old_glob_ignore_case = glob_ignore_case;
1996
1997 if (glob_matches)
1998 {
1999 free (glob_matches);
2000 glob_matches = (char **)NULL;
2001 }
2002
2003 globpat = completion_glob_pattern ((char *)hint_text);
2004
2005 /* If this is an absolute program name, do not check it against
2006 aliases, reserved words, functions or builtins. We must check
2007 whether or not it is unique, and, if so, whether that filename
2008 is executable. */
2009 if (globpat || absolute_program (hint_text))
2010 {
2011 /* Perform tilde expansion on what's passed, so we don't end up
2012 passing filenames with tildes directly to stat(). The rest of
2013 the shell doesn't do variable expansion on the word following
2014 the tilde, so we don't do it here even if direxpand is set. */
2015 if (*hint_text == '~')
2016 {
2017 hint = bash_tilde_expand (hint_text, 0);
2018 directory_part = savestring (hint_text);
2019 temp = strchr (directory_part, '/');
2020 if (temp)
2021 *temp = 0;
2022 else
2023 {
2024 free (directory_part);
2025 directory_part = (char *)NULL;
2026 }
2027 }
2028 else if (dircomplete_expand)
2029 {
2030 hint = savestring (hint_text);
2031 bash_directory_completion_hook (&hint);
2032 }
2033 else
2034 hint = savestring (hint_text);
2035
2036 dequoted_hint = hint;
2037 /* If readline's completer found a quote character somewhere, but
2038 didn't set the quote character, there must have been a quote
2039 character embedded in the filename. It can't be at the start of
2040 the filename, so we need to dequote the filename before we look
2041 in the file system for it. */
2042 if (rl_completion_found_quote && rl_completion_quote_character == 0)
2043 {
2044 dequoted_hint = bash_dequote_filename (hint, 0);
2045 free (hint);
2046 hint = dequoted_hint;
2047 }
2048 hint_len = strlen (hint);
2049
2050 if (filename_hint)
2051 free (filename_hint);
2052
2053 fnhint = filename_hint = savestring (hint);
2054
2055 istate = 0;
2056
2057 if (globpat)
2058 {
2059 mapping_over = 5;
2060 goto globword;
2061 }
2062 else
2063 {
2064 if (dircomplete_expand && path_dot_or_dotdot (filename_hint))
2065 {
2066 dircomplete_expand = 0;
2067 set_directory_hook ();
2068 dircomplete_expand = 1;
2069 }
2070 mapping_over = 4;
2071 goto inner;
2072 }
2073 }
2074
2075 dequoted_hint = hint = savestring (hint_text);
2076 hint_len = strlen (hint);
2077
2078 if (rl_completion_found_quote && rl_completion_quote_character == 0)
2079 dequoted_hint = bash_dequote_filename (hint, 0);
2080
2081 path = get_string_value ("PATH");
2082 path_index = dot_in_path = 0;
2083
2084 /* Initialize the variables for each type of command word. */
2085 local_index = 0;
2086
2087 if (varlist)
2088 free (varlist);
2089
2090 varlist = all_visible_functions ();
2091
2092 #if defined (ALIAS)
2093 if (alias_list)
2094 free (alias_list);
2095
2096 alias_list = all_aliases ();
2097 #endif /* ALIAS */
2098 }
2099
2100 /* mapping_over says what we are currently hacking. Note that every case
2101 in this list must fall through when there are no more possibilities. */
2102
2103 switch (mapping_over)
2104 {
2105 case 0: /* Aliases come first. */
2106 #if defined (ALIAS)
2107 while (alias_list && alias_list[local_index])
2108 {
2109 register char *alias;
2110
2111 alias = alias_list[local_index++]->name;
2112
2113 if (igncase == 0 && (STREQN (alias, hint, hint_len)))
2114 return (savestring (alias));
2115 else if (igncase && strncasecmp (alias, hint, hint_len) == 0)
2116 return (savestring (alias));
2117 }
2118 #endif /* ALIAS */
2119 local_index = 0;
2120 mapping_over++;
2121
2122 case 1: /* Then shell reserved words. */
2123 {
2124 while (word_token_alist[local_index].word)
2125 {
2126 register char *reserved_word;
2127
2128 reserved_word = word_token_alist[local_index++].word;
2129
2130 if (STREQN (reserved_word, hint, hint_len))
2131 return (savestring (reserved_word));
2132 }
2133 local_index = 0;
2134 mapping_over++;
2135 }
2136
2137 case 2: /* Then function names. */
2138 while (varlist && varlist[local_index])
2139 {
2140 register char *varname;
2141
2142 varname = varlist[local_index++]->name;
2143
2144 /* Honor completion-ignore-case for shell function names. */
2145 if (igncase == 0 && (STREQN (varname, hint, hint_len)))
2146 return (savestring (varname));
2147 else if (igncase && strncasecmp (varname, hint, hint_len) == 0)
2148 return (savestring (varname));
2149 }
2150 local_index = 0;
2151 mapping_over++;
2152
2153 case 3: /* Then shell builtins. */
2154 for (; local_index < num_shell_builtins; local_index++)
2155 {
2156 /* Ignore it if it doesn't have a function pointer or if it
2157 is not currently enabled. */
2158 if (!shell_builtins[local_index].function ||
2159 (shell_builtins[local_index].flags & BUILTIN_ENABLED) == 0)
2160 continue;
2161
2162 if (STREQN (shell_builtins[local_index].name, hint, hint_len))
2163 {
2164 int i = local_index++;
2165
2166 return (savestring (shell_builtins[i].name));
2167 }
2168 }
2169 local_index = 0;
2170 mapping_over++;
2171 }
2172
2173 globword:
2174 /* Limited support for completing command words with globbing chars. Only
2175 a single match (multiple matches that end up reducing the number of
2176 characters in the common prefix are bad) will ever be returned on
2177 regular completion. */
2178 if (globpat)
2179 {
2180 if (state == 0)
2181 {
2182 rl_filename_completion_desired = 1;
2183
2184 glob_ignore_case = igncase;
2185 glob_matches = shell_glob_filename (hint, 0);
2186 glob_ignore_case = old_glob_ignore_case;
2187
2188 if (GLOB_FAILED (glob_matches) || glob_matches == 0)
2189 {
2190 glob_matches = (char **)NULL;
2191 return ((char *)NULL);
2192 }
2193
2194 local_index = 0;
2195
2196 if (glob_matches[1] && rl_completion_type == TAB) /* multiple matches are bad */
2197 return ((char *)NULL);
2198 }
2199
2200 while (val = glob_matches[local_index++])
2201 {
2202 if (executable_or_directory (val))
2203 {
2204 if (*hint_text == '~' && directory_part)
2205 {
2206 temp = maybe_restore_tilde (val, directory_part);
2207 free (val);
2208 val = temp;
2209 }
2210 return (val);
2211 }
2212 free (val);
2213 }
2214
2215 glob_ignore_case = old_glob_ignore_case;
2216 return ((char *)NULL);
2217 }
2218
2219 /* If the text passed is a directory in the current directory, return it
2220 as a possible match. Executables in directories in the current
2221 directory can be specified using relative pathnames and successfully
2222 executed even when `.' is not in $PATH. */
2223 if (hint_is_dir)
2224 {
2225 hint_is_dir = 0; /* only return the hint text once */
2226 return (savestring (hint_text));
2227 }
2228
2229 /* Repeatedly call filename_completion_function while we have
2230 members of PATH left. Question: should we stat each file?
2231 Answer: we call executable_file () on each file. */
2232 outer:
2233
2234 istate = (val != (char *)NULL);
2235
2236 if (istate == 0)
2237 {
2238 char *current_path;
2239
2240 /* Get the next directory from the path. If there is none, then we
2241 are all done. */
2242 if (path == 0 || path[path_index] == 0 ||
2243 (current_path = extract_colon_unit (path, &path_index)) == 0)
2244 return ((char *)NULL);
2245
2246 searching_path = 1;
2247 if (*current_path == 0)
2248 {
2249 free (current_path);
2250 current_path = savestring (".");
2251 }
2252
2253 if (*current_path == '~')
2254 {
2255 char *t;
2256
2257 t = bash_tilde_expand (current_path, 0);
2258 free (current_path);
2259 current_path = t;
2260 }
2261
2262 if (current_path[0] == '.' && current_path[1] == '\0')
2263 dot_in_path = 1;
2264
2265 if (fnhint && fnhint != filename_hint)
2266 free (fnhint);
2267 if (filename_hint)
2268 free (filename_hint);
2269
2270 filename_hint = sh_makepath (current_path, hint, 0);
2271 /* Need a quoted version (though it doesn't matter much in most
2272 cases) because rl_filename_completion_function dequotes the
2273 filename it gets, assuming that it's been quoted as part of
2274 the input line buffer. */
2275 if (strpbrk (filename_hint, "\"'\\"))
2276 fnhint = sh_backslash_quote (filename_hint, filename_bstab, 0);
2277 else
2278 fnhint = filename_hint;
2279 free (current_path); /* XXX */
2280 }
2281
2282 inner:
2283 val = rl_filename_completion_function (fnhint, istate);
2284 if (mapping_over == 4 && dircomplete_expand)
2285 set_directory_hook ();
2286
2287 istate = 1;
2288
2289 if (val == 0)
2290 {
2291 /* If the hint text is an absolute program, then don't bother
2292 searching through PATH. */
2293 if (absolute_program (hint))
2294 return ((char *)NULL);
2295
2296 goto outer;
2297 }
2298 else
2299 {
2300 int match, freetemp;
2301
2302 if (absolute_program (hint))
2303 {
2304 if (igncase == 0)
2305 match = strncmp (val, hint, hint_len) == 0;
2306 else
2307 match = strncasecmp (val, hint, hint_len) == 0;
2308
2309 /* If we performed tilde expansion, restore the original
2310 filename. */
2311 if (*hint_text == '~')
2312 temp = maybe_restore_tilde (val, directory_part);
2313 else
2314 temp = savestring (val);
2315 freetemp = 1;
2316 }
2317 else
2318 {
2319 temp = strrchr (val, '/');
2320
2321 if (temp)
2322 {
2323 temp++;
2324 if (igncase == 0)
2325 freetemp = match = strncmp (temp, hint, hint_len) == 0;
2326 else
2327 freetemp = match = strncasecmp (temp, hint, hint_len) == 0;
2328 if (match)
2329 temp = savestring (temp);
2330 }
2331 else
2332 freetemp = match = 0;
2333 }
2334
2335 /* If we have found a match, and it is an executable file, return it.
2336 We don't return directory names when searching $PATH, since the
2337 bash execution code won't find executables in directories which
2338 appear in directories in $PATH when they're specified using
2339 relative pathnames. */
2340 #if 0
2341 /* If we're not searching $PATH and we have a relative pathname, we
2342 need to re-canonicalize it before testing whether or not it's an
2343 executable or a directory so the shell treats .. relative to $PWD
2344 according to the physical/logical option. The shell already
2345 canonicalizes the directory name in order to tell readline where
2346 to look, so not doing it here will be inconsistent. */
2347 /* XXX -- currently not used -- will introduce more inconsistency,
2348 since shell does not canonicalize ../foo before passing it to
2349 shell_execve(). */
2350 if (match && searching_path == 0 && *val == '.')
2351 {
2352 char *t, *t1;
2353
2354 t = get_working_directory ("command-word-completion");
2355 t1 = make_absolute (val, t);
2356 free (t);
2357 cval = sh_canonpath (t1, PATH_CHECKDOTDOT|PATH_CHECKEXISTS);
2358 }
2359 else
2360 #endif
2361 cval = val;
2362
2363 if (match && executable_completion ((searching_path ? val : cval), searching_path))
2364 {
2365 if (cval != val)
2366 free (cval);
2367 free (val);
2368 val = ""; /* So it won't be NULL. */
2369 return (temp);
2370 }
2371 else
2372 {
2373 if (freetemp)
2374 free (temp);
2375 if (cval != val)
2376 free (cval);
2377 free (val);
2378 goto inner;
2379 }
2380 }
2381 }
2382
2383 /* Completion inside an unterminated command substitution. */
2384 static char *
2385 command_subst_completion_function (text, state)
2386 const char *text;
2387 int state;
2388 {
2389 static char **matches = (char **)NULL;
2390 static const char *orig_start;
2391 static char *filename_text = (char *)NULL;
2392 static int cmd_index, start_len;
2393 char *value;
2394
2395 if (state == 0)
2396 {
2397 if (filename_text)
2398 free (filename_text);
2399 orig_start = text;
2400 if (*text == '`')
2401 text++;
2402 else if (*text == '$' && text[1] == '(') /* ) */
2403 text += 2;
2404 /* If the text was quoted, suppress any quote character that the
2405 readline completion code would insert. */
2406 rl_completion_suppress_quote = 1;
2407 start_len = text - orig_start;
2408 filename_text = savestring (text);
2409 if (matches)
2410 free (matches);
2411
2412 /*
2413 * At this point we can entertain the idea of re-parsing
2414 * `filename_text' into a (possibly incomplete) command name and
2415 * arguments, and doing completion based on that. This is
2416 * currently very rudimentary, but it is a small improvement.
2417 */
2418 for (value = filename_text + strlen (filename_text) - 1; value > filename_text; value--)
2419 if (whitespace (*value) || member (*value, COMMAND_SEPARATORS))
2420 break;
2421 if (value <= filename_text)
2422 matches = rl_completion_matches (filename_text, command_word_completion_function);
2423 else
2424 {
2425 value++;
2426 start_len += value - filename_text;
2427 if (whitespace (value[-1]))
2428 matches = rl_completion_matches (value, rl_filename_completion_function);
2429 else
2430 matches = rl_completion_matches (value, command_word_completion_function);
2431 }
2432
2433 /* If there is more than one match, rl_completion_matches has already
2434 put the lcd in matches[0]. Skip over it. */
2435 cmd_index = matches && matches[0] && matches[1];
2436
2437 /* If there's a single match and it's a directory, set the append char
2438 to the expected `/'. Otherwise, don't append anything. */
2439 if (matches && matches[0] && matches[1] == 0 && test_for_directory (matches[0]))
2440 rl_completion_append_character = '/';
2441 else
2442 rl_completion_suppress_append = 1;
2443 }
2444
2445 if (matches == 0 || matches[cmd_index] == 0)
2446 {
2447 rl_filename_quoting_desired = 0; /* disable quoting */
2448 return ((char *)NULL);
2449 }
2450 else
2451 {
2452 value = (char *)xmalloc (1 + start_len + strlen (matches[cmd_index]));
2453
2454 if (start_len == 1)
2455 value[0] = *orig_start;
2456 else
2457 strncpy (value, orig_start, start_len);
2458
2459 strcpy (value + start_len, matches[cmd_index]);
2460
2461 cmd_index++;
2462 return (value);
2463 }
2464 }
2465
2466 /* Okay, now we write the entry_function for variable completion. */
2467 static char *
2468 variable_completion_function (text, state)
2469 const char *text;
2470 int state;
2471 {
2472 static char **varlist = (char **)NULL;
2473 static int varlist_index;
2474 static char *varname = (char *)NULL;
2475 static int first_char, first_char_loc;
2476
2477 if (!state)
2478 {
2479 if (varname)
2480 free (varname);
2481
2482 first_char_loc = 0;
2483 first_char = text[0];
2484
2485 if (first_char == '$')
2486 first_char_loc++;
2487
2488 if (text[first_char_loc] == '{')
2489 first_char_loc++;
2490
2491 varname = savestring (text + first_char_loc);
2492
2493 if (varlist)
2494 strvec_dispose (varlist);
2495
2496 varlist = all_variables_matching_prefix (varname);
2497 varlist_index = 0;
2498 }
2499
2500 if (!varlist || !varlist[varlist_index])
2501 {
2502 return ((char *)NULL);
2503 }
2504 else
2505 {
2506 char *value;
2507
2508 value = (char *)xmalloc (4 + strlen (varlist[varlist_index]));
2509
2510 if (first_char_loc)
2511 {
2512 value[0] = first_char;
2513 if (first_char_loc == 2)
2514 value[1] = '{';
2515 }
2516
2517 strcpy (value + first_char_loc, varlist[varlist_index]);
2518 if (first_char_loc == 2)
2519 strcat (value, "}");
2520
2521 varlist_index++;
2522 return (value);
2523 }
2524 }
2525
2526 /* How about a completion function for hostnames? */
2527 static char *
2528 hostname_completion_function (text, state)
2529 const char *text;
2530 int state;
2531 {
2532 static char **list = (char **)NULL;
2533 static int list_index = 0;
2534 static int first_char, first_char_loc;
2535
2536 /* If we don't have any state, make some. */
2537 if (state == 0)
2538 {
2539 FREE (list);
2540
2541 list = (char **)NULL;
2542
2543 first_char_loc = 0;
2544 first_char = *text;
2545
2546 if (first_char == '@')
2547 first_char_loc++;
2548
2549 list = hostnames_matching ((char *)text+first_char_loc);
2550 list_index = 0;
2551 }
2552
2553 if (list && list[list_index])
2554 {
2555 char *t;
2556
2557 t = (char *)xmalloc (2 + strlen (list[list_index]));
2558 *t = first_char;
2559 strcpy (t + first_char_loc, list[list_index]);
2560 list_index++;
2561 return (t);
2562 }
2563
2564 return ((char *)NULL);
2565 }
2566
2567 /*
2568 * A completion function for service names from /etc/services (or wherever).
2569 */
2570 char *
2571 bash_servicename_completion_function (text, state)
2572 const char *text;
2573 int state;
2574 {
2575 #if defined (__WIN32__) || defined (__OPENNT) || !defined (HAVE_GETSERVENT)
2576 return ((char *)NULL);
2577 #else
2578 static char *sname = (char *)NULL;
2579 static struct servent *srvent;
2580 static int snamelen;
2581 char *value;
2582 char **alist, *aentry;
2583 int afound;
2584
2585 if (state == 0)
2586 {
2587 FREE (sname);
2588
2589 sname = savestring (text);
2590 snamelen = strlen (sname);
2591 setservent (0);
2592 }
2593
2594 while (srvent = getservent ())
2595 {
2596 afound = 0;
2597 if (snamelen == 0 || (STREQN (sname, srvent->s_name, snamelen)))
2598 break;
2599 /* Not primary, check aliases */
2600 for (alist = srvent->s_aliases; *alist; alist++)
2601 {
2602 aentry = *alist;
2603 if (STREQN (sname, aentry, snamelen))
2604 {
2605 afound = 1;
2606 break;
2607 }
2608 }
2609
2610 if (afound)
2611 break;
2612 }
2613
2614 if (srvent == 0)
2615 {
2616 endservent ();
2617 return ((char *)NULL);
2618 }
2619
2620 value = afound ? savestring (aentry) : savestring (srvent->s_name);
2621 return value;
2622 #endif
2623 }
2624
2625 /*
2626 * A completion function for group names from /etc/group (or wherever).
2627 */
2628 char *
2629 bash_groupname_completion_function (text, state)
2630 const char *text;
2631 int state;
2632 {
2633 #if defined (__WIN32__) || defined (__OPENNT) || !defined (HAVE_GRP_H)
2634 return ((char *)NULL);
2635 #else
2636 static char *gname = (char *)NULL;
2637 static struct group *grent;
2638 static int gnamelen;
2639 char *value;
2640
2641 if (state == 0)
2642 {
2643 FREE (gname);
2644 gname = savestring (text);
2645 gnamelen = strlen (gname);
2646
2647 setgrent ();
2648 }
2649
2650 while (grent = getgrent ())
2651 {
2652 if (gnamelen == 0 || (STREQN (gname, grent->gr_name, gnamelen)))
2653 break;
2654 }
2655
2656 if (grent == 0)
2657 {
2658 endgrent ();
2659 return ((char *)NULL);
2660 }
2661
2662 value = savestring (grent->gr_name);
2663 return (value);
2664 #endif
2665 }
2666
2667 /* Functions to perform history and alias expansions on the current line. */
2668
2669 #if defined (BANG_HISTORY)
2670 /* Perform history expansion on the current line. If no history expansion
2671 is done, pre_process_line() returns what it was passed, so we need to
2672 allocate a new line here. */
2673 static char *
2674 history_expand_line_internal (line)
2675 char *line;
2676 {
2677 char *new_line;
2678 int old_verify;
2679
2680 old_verify = hist_verify;
2681 hist_verify = 0;
2682 new_line = pre_process_line (line, 0, 0);
2683 hist_verify = old_verify;
2684
2685 return (new_line == line) ? savestring (line) : new_line;
2686 }
2687 #endif
2688
2689 /* There was an error in expansion. Let the preprocessor print
2690 the error here. */
2691 static void
2692 cleanup_expansion_error ()
2693 {
2694 char *to_free;
2695 #if defined (BANG_HISTORY)
2696 int old_verify;
2697
2698 old_verify = hist_verify;
2699 hist_verify = 0;
2700 #endif
2701
2702 fprintf (rl_outstream, "\r\n");
2703 to_free = pre_process_line (rl_line_buffer, 1, 0);
2704 #if defined (BANG_HISTORY)
2705 hist_verify = old_verify;
2706 #endif
2707 if (to_free != rl_line_buffer)
2708 FREE (to_free);
2709 putc ('\r', rl_outstream);
2710 rl_forced_update_display ();
2711 }
2712
2713 /* If NEW_LINE differs from what is in the readline line buffer, add an
2714 undo record to get from the readline line buffer contents to the new
2715 line and make NEW_LINE the current readline line. */
2716 static void
2717 maybe_make_readline_line (new_line)
2718 char *new_line;
2719 {
2720 if (new_line && strcmp (new_line, rl_line_buffer) != 0)
2721 {
2722 rl_point = rl_end;
2723
2724 rl_add_undo (UNDO_BEGIN, 0, 0, 0);
2725 rl_delete_text (0, rl_point);
2726 rl_point = rl_end = rl_mark = 0;
2727 rl_insert_text (new_line);
2728 rl_add_undo (UNDO_END, 0, 0, 0);
2729 }
2730 }
2731
2732 /* Make NEW_LINE be the current readline line. This frees NEW_LINE. */
2733 static void
2734 set_up_new_line (new_line)
2735 char *new_line;
2736 {
2737 int old_point, at_end;
2738
2739 old_point = rl_point;
2740 at_end = rl_point == rl_end;
2741
2742 /* If the line was history and alias expanded, then make that
2743 be one thing to undo. */
2744 maybe_make_readline_line (new_line);
2745 free (new_line);
2746
2747 /* Place rl_point where we think it should go. */
2748 if (at_end)
2749 rl_point = rl_end;
2750 else if (old_point < rl_end)
2751 {
2752 rl_point = old_point;
2753 if (!whitespace (rl_line_buffer[rl_point]))
2754 rl_forward_word (1, 0);
2755 }
2756 }
2757
2758 #if defined (ALIAS)
2759 /* Expand aliases in the current readline line. */
2760 static int
2761 alias_expand_line (count, ignore)
2762 int count, ignore;
2763 {
2764 char *new_line;
2765
2766 new_line = alias_expand (rl_line_buffer);
2767
2768 if (new_line)
2769 {
2770 set_up_new_line (new_line);
2771 return (0);
2772 }
2773 else
2774 {
2775 cleanup_expansion_error ();
2776 return (1);
2777 }
2778 }
2779 #endif
2780
2781 #if defined (BANG_HISTORY)
2782 /* History expand the line. */
2783 static int
2784 history_expand_line (count, ignore)
2785 int count, ignore;
2786 {
2787 char *new_line;
2788
2789 new_line = history_expand_line_internal (rl_line_buffer);
2790
2791 if (new_line)
2792 {
2793 set_up_new_line (new_line);
2794 return (0);
2795 }
2796 else
2797 {
2798 cleanup_expansion_error ();
2799 return (1);
2800 }
2801 }
2802
2803 /* Expand history substitutions in the current line and then insert a
2804 space (hopefully close to where we were before). */
2805 static int
2806 tcsh_magic_space (count, ignore)
2807 int count, ignore;
2808 {
2809 int dist_from_end, old_point;
2810
2811 old_point = rl_point;
2812 dist_from_end = rl_end - rl_point;
2813 if (history_expand_line (count, ignore) == 0)
2814 {
2815 /* Try a simple heuristic from Stephen Gildea <gildea@intouchsys.com>.
2816 This works if all expansions were before rl_point or if no expansions
2817 were performed. */
2818 rl_point = (old_point == 0) ? old_point : rl_end - dist_from_end;
2819 rl_insert (1, ' ');
2820 return (0);
2821 }
2822 else
2823 return (1);
2824 }
2825 #endif /* BANG_HISTORY */
2826
2827 /* History and alias expand the line. */
2828 static int
2829 history_and_alias_expand_line (count, ignore)
2830 int count, ignore;
2831 {
2832 char *new_line, *t;
2833
2834 new_line = 0;
2835 #if defined (BANG_HISTORY)
2836 new_line = history_expand_line_internal (rl_line_buffer);
2837 #endif
2838
2839 t = expand_string_dollar_quote (new_line ? new_line : rl_line_buffer, 0);
2840 FREE (new_line);
2841 new_line = t;
2842
2843 #if defined (ALIAS)
2844 if (new_line)
2845 {
2846 char *alias_line;
2847
2848 alias_line = alias_expand (new_line);
2849 free (new_line);
2850 new_line = alias_line;
2851 }
2852 #endif /* ALIAS */
2853
2854 if (new_line)
2855 {
2856 set_up_new_line (new_line);
2857 return (0);
2858 }
2859 else
2860 {
2861 cleanup_expansion_error ();
2862 return (1);
2863 }
2864 }
2865
2866 /* History and alias expand the line, then perform the shell word
2867 expansions by calling expand_string. This can't use set_up_new_line()
2868 because we want the variable expansions as a separate undo'able
2869 set of operations. */
2870 static int
2871 shell_expand_line (count, ignore)
2872 int count, ignore;
2873 {
2874 char *new_line, *t;
2875 WORD_LIST *expanded_string;
2876 WORD_DESC *w;
2877
2878 new_line = 0;
2879 #if defined (BANG_HISTORY)
2880 new_line = history_expand_line_internal (rl_line_buffer);
2881 #endif
2882
2883 t = expand_string_dollar_quote (new_line ? new_line : rl_line_buffer, 0);
2884 FREE (new_line);
2885 new_line = t;
2886
2887 #if defined (ALIAS)
2888 if (new_line)
2889 {
2890 char *alias_line;
2891
2892 alias_line = alias_expand (new_line);
2893 free (new_line);
2894 new_line = alias_line;
2895 }
2896 #endif /* ALIAS */
2897
2898 if (new_line)
2899 {
2900 int old_point = rl_point;
2901 int at_end = rl_point == rl_end;
2902
2903 /* If the line was history and alias expanded, then make that
2904 be one thing to undo. */
2905 maybe_make_readline_line (new_line);
2906 free (new_line);
2907
2908 /* If there is variable expansion to perform, do that as a separate
2909 operation to be undone. */
2910
2911 #if 1
2912 w = alloc_word_desc ();
2913 w->word = savestring (rl_line_buffer);
2914 w->flags = rl_explicit_arg ? (W_NOPROCSUB|W_NOCOMSUB) : 0;
2915 expanded_string = expand_word (w, rl_explicit_arg ? Q_HERE_DOCUMENT : 0);
2916 dispose_word (w);
2917 #else
2918 new_line = savestring (rl_line_buffer);
2919 expanded_string = expand_string (new_line, 0);
2920 FREE (new_line);
2921 #endif
2922
2923 if (expanded_string == 0)
2924 {
2925 new_line = (char *)xmalloc (1);
2926 new_line[0] = '\0';
2927 }
2928 else
2929 {
2930 new_line = string_list (expanded_string);
2931 dispose_words (expanded_string);
2932 }
2933
2934 maybe_make_readline_line (new_line);
2935 free (new_line);
2936
2937 /* Place rl_point where we think it should go. */
2938 if (at_end)
2939 rl_point = rl_end;
2940 else if (old_point < rl_end)
2941 {
2942 rl_point = old_point;
2943 if (!whitespace (rl_line_buffer[rl_point]))
2944 rl_forward_word (1, 0);
2945 }
2946 return 0;
2947 }
2948 else
2949 {
2950 cleanup_expansion_error ();
2951 return 1;
2952 }
2953 }
2954
2955 /* If FIGNORE is set, then don't match files with the given suffixes when
2956 completing filenames. If only one of the possibilities has an acceptable
2957 suffix, delete the others, else just return and let the completer
2958 signal an error. It is called by the completer when real
2959 completions are done on filenames by the completer's internal
2960 function, not for completion lists (M-?) and not on "other"
2961 completion types, such as hostnames or commands. */
2962
2963 static struct ignorevar fignore =
2964 {
2965 "FIGNORE",
2966 (struct ign *)0,
2967 0,
2968 (char *)0,
2969 (sh_iv_item_func_t *) 0,
2970 };
2971
2972 static void
2973 _ignore_completion_names (names, name_func)
2974 char **names;
2975 sh_ignore_func_t *name_func;
2976 {
2977 char **newnames;
2978 int idx, nidx;
2979 char **oldnames;
2980 int oidx;
2981
2982 /* If there is only one completion, see if it is acceptable. If it is
2983 not, free it up. In any case, short-circuit and return. This is a
2984 special case because names[0] is not the prefix of the list of names
2985 if there is only one completion; it is the completion itself. */
2986 if (names[1] == (char *)0)
2987 {
2988 if (force_fignore)
2989 if ((*name_func) (names[0]) == 0)
2990 {
2991 free (names[0]);
2992 names[0] = (char *)NULL;
2993 }
2994
2995 return;
2996 }
2997
2998 /* Allocate space for array to hold list of pointers to matching
2999 filenames. The pointers are copied back to NAMES when done. */
3000 for (nidx = 1; names[nidx]; nidx++)
3001 ;
3002 newnames = strvec_create (nidx + 1);
3003
3004 if (force_fignore == 0)
3005 {
3006 oldnames = strvec_create (nidx - 1);
3007 oidx = 0;
3008 }
3009
3010 newnames[0] = names[0];
3011 for (idx = nidx = 1; names[idx]; idx++)
3012 {
3013 if ((*name_func) (names[idx]))
3014 newnames[nidx++] = names[idx];
3015 else if (force_fignore == 0)
3016 oldnames[oidx++] = names[idx];
3017 else
3018 free (names[idx]);
3019 }
3020
3021 newnames[nidx] = (char *)NULL;
3022
3023 /* If none are acceptable then let the completer handle it. */
3024 if (nidx == 1)
3025 {
3026 if (force_fignore)
3027 {
3028 free (names[0]);
3029 names[0] = (char *)NULL;
3030 }
3031 else
3032 free (oldnames);
3033
3034 free (newnames);
3035 return;
3036 }
3037
3038 if (force_fignore == 0)
3039 {
3040 while (oidx)
3041 free (oldnames[--oidx]);
3042 free (oldnames);
3043 }
3044
3045 /* If only one is acceptable, copy it to names[0] and return. */
3046 if (nidx == 2)
3047 {
3048 free (names[0]);
3049 names[0] = newnames[1];
3050 names[1] = (char *)NULL;
3051 free (newnames);
3052 return;
3053 }
3054
3055 /* Copy the acceptable names back to NAMES, set the new array end,
3056 and return. */
3057 for (nidx = 1; newnames[nidx]; nidx++)
3058 names[nidx] = newnames[nidx];
3059 names[nidx] = (char *)NULL;
3060 free (newnames);
3061 }
3062
3063 static int
3064 name_is_acceptable (name)
3065 const char *name;
3066 {
3067 struct ign *p;
3068 int nlen;
3069
3070 for (nlen = strlen (name), p = fignore.ignores; p->val; p++)
3071 {
3072 if (nlen > p->len && p->len > 0 && STREQ (p->val, &name[nlen - p->len]))
3073 return (0);
3074 }
3075
3076 return (1);
3077 }
3078
3079 #if 0
3080 static int
3081 ignore_dot_names (name)
3082 char *name;
3083 {
3084 return (name[0] != '.');
3085 }
3086 #endif
3087
3088 static int
3089 filename_completion_ignore (names)
3090 char **names;
3091 {
3092 #if 0
3093 if (glob_dot_filenames == 0)
3094 _ignore_completion_names (names, ignore_dot_names);
3095 #endif
3096
3097 setup_ignore_patterns (&fignore);
3098
3099 if (fignore.num_ignores == 0)
3100 return 0;
3101
3102 _ignore_completion_names (names, name_is_acceptable);
3103
3104 return 0;
3105 }
3106
3107 /* Return 1 if NAME is a directory. NAME undergoes tilde expansion. */
3108 static int
3109 test_for_directory (name)
3110 const char *name;
3111 {
3112 char *fn;
3113 int r;
3114
3115 fn = bash_tilde_expand (name, 0);
3116 r = file_isdir (fn);
3117 free (fn);
3118
3119 return (r);
3120 }
3121
3122 static int
3123 test_for_canon_directory (name)
3124 const char *name;
3125 {
3126 char *fn;
3127 int r;
3128
3129 fn = (*name == '~') ? bash_tilde_expand (name, 0) : savestring (name);
3130 bash_filename_stat_hook (&fn);
3131 r = file_isdir (fn);
3132 free (fn);
3133
3134 return (r);
3135 }
3136
3137 /* Remove files from NAMES, leaving directories. */
3138 static int
3139 bash_ignore_filenames (names)
3140 char **names;
3141 {
3142 _ignore_completion_names (names, test_for_directory);
3143 return 0;
3144 }
3145
3146 static int
3147 bash_progcomp_ignore_filenames (names)
3148 char **names;
3149 {
3150 _ignore_completion_names (names, test_for_canon_directory);
3151 return 0;
3152 }
3153
3154 static int
3155 return_zero (name)
3156 const char *name;
3157 {
3158 return 0;
3159 }
3160
3161 static int
3162 bash_ignore_everything (names)
3163 char **names;
3164 {
3165 _ignore_completion_names (names, return_zero);
3166 return 0;
3167 }
3168
3169 /* Replace a tilde-prefix in VAL with a `~', assuming the user typed it. VAL
3170 is an expanded filename. DIRECTORY_PART is the tilde-prefix portion
3171 of the un-tilde-expanded version of VAL (what the user typed). */
3172 static char *
3173 restore_tilde (val, directory_part)
3174 char *val, *directory_part;
3175 {
3176 int l, vl, dl2, xl;
3177 char *dh2, *expdir, *ret, *v;
3178
3179 vl = strlen (val);
3180
3181 /* We need to duplicate the expansions readline performs on the directory
3182 portion before passing it to our completion function. */
3183 dh2 = directory_part ? bash_dequote_filename (directory_part, 0) : 0;
3184 bash_directory_expansion (&dh2);
3185 dl2 = strlen (dh2);
3186
3187 expdir = bash_tilde_expand (directory_part, 0);
3188 xl = strlen (expdir);
3189 if (*directory_part == '~' && STREQ (directory_part, expdir))
3190 {
3191 /* tilde expansion failed, so what should we return? we use what the
3192 user typed. */
3193 v = mbschr (val, '/');
3194 vl = STRLEN (v);
3195 ret = (char *)xmalloc (xl + vl + 2);
3196 strcpy (ret, directory_part);
3197 if (v && *v)
3198 strcpy (ret + xl, v);
3199
3200 free (dh2);
3201 free (expdir);
3202
3203 return ret;
3204 }
3205 free (expdir);
3206
3207 /*
3208 dh2 = unexpanded but dequoted tilde-prefix
3209 dl2 = length of tilde-prefix
3210 expdir = tilde-expanded tilde-prefix
3211 xl = length of expanded tilde-prefix
3212 l = length of remainder after tilde-prefix
3213 */
3214 l = (vl - xl) + 1;
3215 if (l <= 0)
3216 {
3217 free (dh2);
3218 return (savestring (val)); /* XXX - just punt */
3219 }
3220
3221 ret = (char *)xmalloc (dl2 + 2 + l);
3222 strcpy (ret, dh2);
3223 strcpy (ret + dl2, val + xl);
3224
3225 free (dh2);
3226 return (ret);
3227 }
3228
3229 static char *
3230 maybe_restore_tilde (val, directory_part)
3231 char *val, *directory_part;
3232 {
3233 rl_icppfunc_t *save;
3234 char *ret;
3235
3236 save = (dircomplete_expand == 0) ? save_directory_hook () : (rl_icppfunc_t *)0;
3237 ret = restore_tilde (val, directory_part);
3238 if (save)
3239 restore_directory_hook (save);
3240 return ret;
3241 }
3242
3243 /* Simulate the expansions that will be performed by
3244 rl_filename_completion_function. This must be called with the address of
3245 a pointer to malloc'd memory. */
3246 static void
3247 bash_directory_expansion (dirname)
3248 char **dirname;
3249 {
3250 char *d, *nd;
3251
3252 d = savestring (*dirname);
3253
3254 if ((rl_directory_rewrite_hook) && (*rl_directory_rewrite_hook) (&d))
3255 {
3256 free (*dirname);
3257 *dirname = d;
3258 }
3259 else if (rl_directory_completion_hook && (*rl_directory_completion_hook) (&d))
3260 {
3261 free (*dirname);
3262 *dirname = d;
3263 }
3264 else if (rl_completion_found_quote)
3265 {
3266 nd = bash_dequote_filename (d, rl_completion_quote_character);
3267 free (*dirname);
3268 free (d);
3269 *dirname = nd;
3270 }
3271 }
3272
3273 /* If necessary, rewrite directory entry */
3274 static char *
3275 bash_filename_rewrite_hook (fname, fnlen)
3276 char *fname;
3277 int fnlen;
3278 {
3279 char *conv;
3280
3281 conv = fnx_fromfs (fname, fnlen);
3282 if (conv != fname)
3283 conv = savestring (conv);
3284 return conv;
3285 }
3286
3287 /* Functions to save and restore the appropriate directory hook */
3288 /* This is not static so the shopt code can call it */
3289 void
3290 set_directory_hook ()
3291 {
3292 if (dircomplete_expand)
3293 {
3294 rl_directory_completion_hook = bash_directory_completion_hook;
3295 rl_directory_rewrite_hook = (rl_icppfunc_t *)0;
3296 }
3297 else
3298 {
3299 rl_directory_rewrite_hook = bash_directory_completion_hook;
3300 rl_directory_completion_hook = (rl_icppfunc_t *)0;
3301 }
3302 }
3303
3304 static rl_icppfunc_t *
3305 save_directory_hook ()
3306 {
3307 rl_icppfunc_t *ret;
3308
3309 if (dircomplete_expand)
3310 {
3311 ret = rl_directory_completion_hook;
3312 rl_directory_completion_hook = (rl_icppfunc_t *)NULL;
3313 }
3314 else
3315 {
3316 ret = rl_directory_rewrite_hook;
3317 rl_directory_rewrite_hook = (rl_icppfunc_t *)NULL;
3318 }
3319
3320 return ret;
3321 }
3322
3323 static void
3324 restore_directory_hook (hookf)
3325 rl_icppfunc_t *hookf;
3326 {
3327 if (dircomplete_expand)
3328 rl_directory_completion_hook = hookf;
3329 else
3330 rl_directory_rewrite_hook = hookf;
3331 }
3332
3333 /* Check whether not DIRNAME, with any trailing slash removed, exists. If
3334 SHOULD_DEQUOTE is non-zero, we dequote the directory name first. */
3335 static int
3336 directory_exists (dirname, should_dequote)
3337 const char *dirname;
3338 int should_dequote;
3339 {
3340 char *new_dirname;
3341 int dirlen, r;
3342 struct stat sb;
3343
3344 /* We save the string and chop the trailing slash because stat/lstat behave
3345 inconsistently if one is present. */
3346 new_dirname = should_dequote ? bash_dequote_filename ((char *)dirname, rl_completion_quote_character) : savestring (dirname);
3347 dirlen = STRLEN (new_dirname);
3348 if (new_dirname[dirlen - 1] == '/')
3349 new_dirname[dirlen - 1] = '\0';
3350 #if defined (HAVE_LSTAT)
3351 r = lstat (new_dirname, &sb) == 0;
3352 #else
3353 r = stat (new_dirname, &sb) == 0;
3354 #endif
3355 free (new_dirname);
3356 return (r);
3357 }
3358
3359 /* Expand a filename before the readline completion code passes it to stat(2).
3360 The filename will already have had tilde expansion performed. */
3361 static int
3362 bash_filename_stat_hook (dirname)
3363 char **dirname;
3364 {
3365 char *local_dirname, *new_dirname, *t;
3366 int should_expand_dirname, return_value;
3367 int global_nounset;
3368 WORD_LIST *wl;
3369
3370 local_dirname = *dirname;
3371 should_expand_dirname = return_value = 0;
3372 if (t = mbschr (local_dirname, '$'))
3373 should_expand_dirname = '$';
3374 else if (t = mbschr (local_dirname, '`')) /* XXX */
3375 should_expand_dirname = '`';
3376
3377 if (should_expand_dirname && directory_exists (local_dirname, 0))
3378 should_expand_dirname = 0;
3379
3380 if (should_expand_dirname)
3381 {
3382 new_dirname = savestring (local_dirname);
3383 /* no error messages, and expand_prompt_string doesn't longjmp so we don't
3384 have to worry about restoring this setting. */
3385 global_nounset = unbound_vars_is_error;
3386 unbound_vars_is_error = 0;
3387 wl = expand_prompt_string (new_dirname, 0, W_NOCOMSUB|W_NOPROCSUB|W_COMPLETE); /* does the right thing */
3388 unbound_vars_is_error = global_nounset;
3389 if (wl)
3390 {
3391 free (new_dirname);
3392 new_dirname = string_list (wl);
3393 /* Tell the completer we actually expanded something and change
3394 *dirname only if we expanded to something non-null -- stat
3395 behaves unpredictably when passed null or empty strings */
3396 if (new_dirname && *new_dirname)
3397 {
3398 free (local_dirname); /* XXX */
3399 local_dirname = *dirname = new_dirname;
3400 return_value = STREQ (local_dirname, *dirname) == 0;
3401 }
3402 else
3403 free (new_dirname);
3404 dispose_words (wl);
3405 }
3406 else
3407 free (new_dirname);
3408 }
3409
3410 /* This is very similar to the code in bash_directory_completion_hook below,
3411 but without spelling correction and not worrying about whether or not
3412 we change relative pathnames. */
3413 if (no_symbolic_links == 0 && (local_dirname[0] != '.' || local_dirname[1]))
3414 {
3415 char *temp1, *temp2;
3416
3417 t = get_working_directory ("symlink-hook");
3418 temp1 = make_absolute (local_dirname, t);
3419 free (t);
3420 temp2 = sh_canonpath (temp1, PATH_CHECKDOTDOT|PATH_CHECKEXISTS);
3421
3422 /* If we can't canonicalize, bail. */
3423 if (temp2 == 0)
3424 {
3425 free (temp1);
3426 return return_value;
3427 }
3428
3429 free (local_dirname);
3430 *dirname = temp2;
3431 free (temp1);
3432 }
3433
3434 return (return_value);
3435 }
3436
3437 /* Handle symbolic link references and other directory name
3438 expansions while hacking completion. This should return 1 if it modifies
3439 the DIRNAME argument, 0 otherwise. It should make sure not to modify
3440 DIRNAME if it returns 0. */
3441 static int
3442 bash_directory_completion_hook (dirname)
3443 char **dirname;
3444 {
3445 char *local_dirname, *new_dirname, *t;
3446 int return_value, should_expand_dirname, nextch, closer;
3447 WORD_LIST *wl;
3448
3449 return_value = should_expand_dirname = nextch = closer = 0;
3450 local_dirname = *dirname;
3451
3452 if (t = mbschr (local_dirname, '$'))
3453 {
3454 should_expand_dirname = '$';
3455 nextch = t[1];
3456 /* Deliberately does not handle the deprecated $[...] arithmetic
3457 expansion syntax */
3458 if (nextch == '(')
3459 closer = ')';
3460 else if (nextch == '{')
3461 closer = '}';
3462 else
3463 nextch = 0;
3464
3465 if (closer)
3466 {
3467 int p;
3468 char delims[2];
3469
3470 delims[0] = closer; delims[1] = 0;
3471 p = skip_to_delim (t, 1, delims, SD_NOJMP|SD_COMPLETE);
3472 if (t[p] != closer)
3473 should_expand_dirname = 0;
3474 }
3475 }
3476 else if (local_dirname[0] == '~')
3477 should_expand_dirname = '~';
3478 else
3479 {
3480 t = mbschr (local_dirname, '`');
3481 if (t && unclosed_pair (local_dirname, strlen (local_dirname), "`") == 0)
3482 should_expand_dirname = '`';
3483 }
3484
3485 if (should_expand_dirname && directory_exists (local_dirname, 1))
3486 should_expand_dirname = 0;
3487
3488 if (should_expand_dirname)
3489 {
3490 new_dirname = savestring (local_dirname);
3491 wl = expand_prompt_string (new_dirname, 0, W_NOCOMSUB|W_NOPROCSUB|W_COMPLETE); /* does the right thing */
3492 if (wl)
3493 {
3494 *dirname = string_list (wl);
3495 /* Tell the completer to replace the directory name only if we
3496 actually expanded something. */
3497 return_value = STREQ (local_dirname, *dirname) == 0;
3498 free (local_dirname);
3499 free (new_dirname);
3500 dispose_words (wl);
3501 local_dirname = *dirname;
3502 /* XXX - change rl_filename_quote_characters here based on
3503 should_expand_dirname/nextch/closer. This is the only place
3504 custom_filename_quote_characters is modified. */
3505 if (rl_filename_quote_characters && *rl_filename_quote_characters)
3506 {
3507 int i, j, c;
3508 i = strlen (default_filename_quote_characters);
3509 custom_filename_quote_characters = xrealloc (custom_filename_quote_characters, i+1);
3510 for (i = j = 0; c = default_filename_quote_characters[i]; i++)
3511 {
3512 if (c == should_expand_dirname || c == nextch || c == closer)
3513 continue;
3514 custom_filename_quote_characters[j++] = c;
3515 }
3516 custom_filename_quote_characters[j] = '\0';
3517 rl_filename_quote_characters = custom_filename_quote_characters;
3518 set_filename_bstab (rl_filename_quote_characters);
3519 }
3520 }
3521 else
3522 {
3523 free (new_dirname);
3524 free (local_dirname);
3525 *dirname = (char *)xmalloc (1);
3526 **dirname = '\0';
3527 return 1;
3528 }
3529 }
3530 else
3531 {
3532 /* Dequote the filename even if we don't expand it. */
3533 new_dirname = bash_dequote_filename (local_dirname, rl_completion_quote_character);
3534 return_value = STREQ (local_dirname, new_dirname) == 0;
3535 free (local_dirname);
3536 local_dirname = *dirname = new_dirname;
3537 }
3538
3539 /* no_symbolic_links == 0 -> use (default) logical view of the file system.
3540 local_dirname[0] == '.' && local_dirname[1] == '/' means files in the
3541 current directory (./).
3542 local_dirname[0] == '.' && local_dirname[1] == 0 means relative pathnames
3543 in the current directory (e.g., lib/sh).
3544 XXX - should we do spelling correction on these? */
3545
3546 /* This is test as it was in bash-4.2: skip relative pathnames in current
3547 directory. Change test to
3548 (local_dirname[0] != '.' || (local_dirname[1] && local_dirname[1] != '/'))
3549 if we want to skip paths beginning with ./ also. */
3550 if (no_symbolic_links == 0 && (local_dirname[0] != '.' || local_dirname[1]))
3551 {
3552 char *temp1, *temp2;
3553 int len1, len2;
3554
3555 /* If we have a relative path
3556 (local_dirname[0] != '/' && local_dirname[0] != '.')
3557 that is canonical after appending it to the current directory, then
3558 temp1 = temp2+'/'
3559 That is,
3560 strcmp (temp1, temp2) == 0
3561 after adding a slash to temp2 below. It should be safe to not
3562 change those.
3563 */
3564 t = get_working_directory ("symlink-hook");
3565 temp1 = make_absolute (local_dirname, t);
3566 free (t);
3567 temp2 = sh_canonpath (temp1, PATH_CHECKDOTDOT|PATH_CHECKEXISTS);
3568
3569 /* Try spelling correction if initial canonicalization fails. Make
3570 sure we are set to replace the directory name with the results so
3571 subsequent directory checks don't fail. */
3572 if (temp2 == 0 && dircomplete_spelling && dircomplete_expand)
3573 {
3574 temp2 = dirspell (temp1);
3575 if (temp2)
3576 {
3577 free (temp1);
3578 temp1 = temp2;
3579 temp2 = sh_canonpath (temp1, PATH_CHECKDOTDOT|PATH_CHECKEXISTS);
3580 return_value |= temp2 != 0;
3581 }
3582 }
3583 /* If we can't canonicalize, bail. */
3584 if (temp2 == 0)
3585 {
3586 free (temp1);
3587 return return_value;
3588 }
3589 len1 = strlen (temp1);
3590 if (temp1[len1 - 1] == '/')
3591 {
3592 len2 = strlen (temp2);
3593 if (len2 > 2) /* don't append `/' to `/' or `//' */
3594 {
3595 temp2 = (char *)xrealloc (temp2, len2 + 2);
3596 temp2[len2] = '/';
3597 temp2[len2 + 1] = '\0';
3598 }
3599 }
3600
3601 /* dircomplete_expand_relpath == 0 means we want to leave relative
3602 pathnames that are unchanged by canonicalization alone.
3603 *local_dirname != '/' && *local_dirname != '.' == relative pathname
3604 (consistent with general.c:absolute_pathname())
3605 temp1 == temp2 (after appending a slash to temp2) means the pathname
3606 is not changed by canonicalization as described above. */
3607 if (dircomplete_expand_relpath || ((local_dirname[0] != '/' && local_dirname[0] != '.') && STREQ (temp1, temp2) == 0))
3608 return_value |= STREQ (local_dirname, temp2) == 0;
3609 free (local_dirname);
3610 *dirname = temp2;
3611 free (temp1);
3612 }
3613
3614 return (return_value);
3615 }
3616
3617 static char **history_completion_array = (char **)NULL;
3618 static int harry_size;
3619 static int harry_len;
3620
3621 static void
3622 build_history_completion_array ()
3623 {
3624 register int i, j;
3625 HIST_ENTRY **hlist;
3626 char **tokens;
3627
3628 /* First, clear out the current dynamic history completion list. */
3629 if (harry_size)
3630 {
3631 strvec_dispose (history_completion_array);
3632 history_completion_array = (char **)NULL;
3633 harry_size = 0;
3634 harry_len = 0;
3635 }
3636
3637 /* Next, grovel each line of history, making each shell-sized token
3638 a separate entry in the history_completion_array. */
3639 hlist = history_list ();
3640
3641 if (hlist)
3642 {
3643 for (i = 0; hlist[i]; i++)
3644 ;
3645 for ( --i; i >= 0; i--)
3646 {
3647 /* Separate each token, and place into an array. */
3648 tokens = history_tokenize (hlist[i]->line);
3649
3650 for (j = 0; tokens && tokens[j]; j++)
3651 {
3652 if (harry_len + 2 > harry_size)
3653 history_completion_array = strvec_resize (history_completion_array, harry_size += 10);
3654
3655 history_completion_array[harry_len++] = tokens[j];
3656 history_completion_array[harry_len] = (char *)NULL;
3657 }
3658 free (tokens);
3659 }
3660
3661 /* Sort the complete list of tokens. */
3662 if (dabbrev_expand_active == 0)
3663 qsort (history_completion_array, harry_len, sizeof (char *), (QSFUNC *)strvec_strcmp);
3664 }
3665 }
3666
3667 static char *
3668 history_completion_generator (hint_text, state)
3669 const char *hint_text;
3670 int state;
3671 {
3672 static int local_index, len;
3673 static const char *text;
3674
3675 /* If this is the first call to the generator, then initialize the
3676 list of strings to complete over. */
3677 if (state == 0)
3678 {
3679 if (dabbrev_expand_active) /* This is kind of messy */
3680 rl_completion_suppress_append = 1;
3681 local_index = 0;
3682 build_history_completion_array ();
3683 text = hint_text;
3684 len = strlen (text);
3685 }
3686
3687 while (history_completion_array && history_completion_array[local_index])
3688 {
3689 /* XXX - should this use completion-ignore-case? */
3690 if (strncmp (text, history_completion_array[local_index++], len) == 0)
3691 return (savestring (history_completion_array[local_index - 1]));
3692 }
3693 return ((char *)NULL);
3694 }
3695
3696 static int
3697 dynamic_complete_history (count, key)
3698 int count, key;
3699 {
3700 int r;
3701 rl_compentry_func_t *orig_func;
3702 rl_completion_func_t *orig_attempt_func;
3703 rl_compignore_func_t *orig_ignore_func;
3704
3705 orig_func = rl_completion_entry_function;
3706 orig_attempt_func = rl_attempted_completion_function;
3707 orig_ignore_func = rl_ignore_some_completions_function;
3708
3709 rl_completion_entry_function = history_completion_generator;
3710 rl_attempted_completion_function = (rl_completion_func_t *)NULL;
3711 rl_ignore_some_completions_function = filename_completion_ignore;
3712
3713 /* XXX - use rl_completion_mode here? */
3714 if (rl_last_func == dynamic_complete_history)
3715 r = rl_complete_internal ('?');
3716 else
3717 r = rl_complete_internal (TAB);
3718
3719 rl_completion_entry_function = orig_func;
3720 rl_attempted_completion_function = orig_attempt_func;
3721 rl_ignore_some_completions_function = orig_ignore_func;
3722
3723 return r;
3724 }
3725
3726 static int
3727 bash_dabbrev_expand (count, key)
3728 int count, key;
3729 {
3730 int r, orig_suppress, orig_sort;
3731 rl_compentry_func_t *orig_func;
3732 rl_completion_func_t *orig_attempt_func;
3733 rl_compignore_func_t *orig_ignore_func;
3734
3735 orig_func = rl_menu_completion_entry_function;
3736 orig_attempt_func = rl_attempted_completion_function;
3737 orig_ignore_func = rl_ignore_some_completions_function;
3738 orig_suppress = rl_completion_suppress_append;
3739 orig_sort = rl_sort_completion_matches;
3740
3741 rl_menu_completion_entry_function = history_completion_generator;
3742 rl_attempted_completion_function = (rl_completion_func_t *)NULL;
3743 rl_ignore_some_completions_function = filename_completion_ignore;
3744 rl_filename_completion_desired = 0;
3745 rl_completion_suppress_append = 1;
3746 rl_sort_completion_matches = 0;
3747
3748 /* XXX - use rl_completion_mode here? */
3749 dabbrev_expand_active = 1;
3750 if (rl_last_func == bash_dabbrev_expand)
3751 rl_last_func = rl_menu_complete;
3752 r = rl_menu_complete (count, key);
3753 dabbrev_expand_active = 0;
3754
3755 rl_last_func = bash_dabbrev_expand;
3756 rl_menu_completion_entry_function = orig_func;
3757 rl_attempted_completion_function = orig_attempt_func;
3758 rl_ignore_some_completions_function = orig_ignore_func;
3759 rl_completion_suppress_append = orig_suppress;
3760 rl_sort_completion_matches = orig_sort;
3761
3762 return r;
3763 }
3764
3765 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
3766 static int
3767 bash_complete_username (ignore, ignore2)
3768 int ignore, ignore2;
3769 {
3770 return bash_complete_username_internal (rl_completion_mode (bash_complete_username));
3771 }
3772
3773 static int
3774 bash_possible_username_completions (ignore, ignore2)
3775 int ignore, ignore2;
3776 {
3777 return bash_complete_username_internal ('?');
3778 }
3779
3780 static int
3781 bash_complete_username_internal (what_to_do)
3782 int what_to_do;
3783 {
3784 return bash_specific_completion (what_to_do, rl_username_completion_function);
3785 }
3786
3787 static int
3788 bash_complete_filename (ignore, ignore2)
3789 int ignore, ignore2;
3790 {
3791 return bash_complete_filename_internal (rl_completion_mode (bash_complete_filename));
3792 }
3793
3794 static int
3795 bash_possible_filename_completions (ignore, ignore2)
3796 int ignore, ignore2;
3797 {
3798 return bash_complete_filename_internal ('?');
3799 }
3800
3801 static int
3802 bash_complete_filename_internal (what_to_do)
3803 int what_to_do;
3804 {
3805 rl_compentry_func_t *orig_func;
3806 rl_completion_func_t *orig_attempt_func;
3807 rl_icppfunc_t *orig_dir_func;
3808 rl_compignore_func_t *orig_ignore_func;
3809 /*const*/ char *orig_rl_completer_word_break_characters;
3810 int r;
3811
3812 orig_func = rl_completion_entry_function;
3813 orig_attempt_func = rl_attempted_completion_function;
3814 orig_ignore_func = rl_ignore_some_completions_function;
3815 orig_rl_completer_word_break_characters = rl_completer_word_break_characters;
3816
3817 orig_dir_func = save_directory_hook ();
3818
3819 rl_completion_entry_function = rl_filename_completion_function;
3820 rl_attempted_completion_function = (rl_completion_func_t *)NULL;
3821 rl_ignore_some_completions_function = filename_completion_ignore;
3822 rl_completer_word_break_characters = " \t\n\"\'";
3823
3824 r = rl_complete_internal (what_to_do);
3825
3826 rl_completion_entry_function = orig_func;
3827 rl_attempted_completion_function = orig_attempt_func;
3828 rl_ignore_some_completions_function = orig_ignore_func;
3829 rl_completer_word_break_characters = orig_rl_completer_word_break_characters;
3830
3831 restore_directory_hook (orig_dir_func);
3832
3833 return r;
3834 }
3835
3836 static int
3837 bash_complete_hostname (ignore, ignore2)
3838 int ignore, ignore2;
3839 {
3840 return bash_complete_hostname_internal (rl_completion_mode (bash_complete_hostname));
3841 }
3842
3843 static int
3844 bash_possible_hostname_completions (ignore, ignore2)
3845 int ignore, ignore2;
3846 {
3847 return bash_complete_hostname_internal ('?');
3848 }
3849
3850 static int
3851 bash_complete_variable (ignore, ignore2)
3852 int ignore, ignore2;
3853 {
3854 return bash_complete_variable_internal (rl_completion_mode (bash_complete_variable));
3855 }
3856
3857 static int
3858 bash_possible_variable_completions (ignore, ignore2)
3859 int ignore, ignore2;
3860 {
3861 return bash_complete_variable_internal ('?');
3862 }
3863
3864 static int
3865 bash_complete_command (ignore, ignore2)
3866 int ignore, ignore2;
3867 {
3868 return bash_complete_command_internal (rl_completion_mode (bash_complete_command));
3869 }
3870
3871 static int
3872 bash_possible_command_completions (ignore, ignore2)
3873 int ignore, ignore2;
3874 {
3875 return bash_complete_command_internal ('?');
3876 }
3877
3878 static int
3879 bash_complete_hostname_internal (what_to_do)
3880 int what_to_do;
3881 {
3882 return bash_specific_completion (what_to_do, hostname_completion_function);
3883 }
3884
3885 static int
3886 bash_complete_variable_internal (what_to_do)
3887 int what_to_do;
3888 {
3889 return bash_specific_completion (what_to_do, variable_completion_function);
3890 }
3891
3892 static int
3893 bash_complete_command_internal (what_to_do)
3894 int what_to_do;
3895 {
3896 return bash_specific_completion (what_to_do, command_word_completion_function);
3897 }
3898
3899 static int
3900 completion_glob_pattern (string)
3901 char *string;
3902 {
3903 return (glob_pattern_p (string) == 1);
3904 }
3905
3906 static char *globtext;
3907 static char *globorig;
3908
3909 static char *
3910 glob_complete_word (text, state)
3911 const char *text;
3912 int state;
3913 {
3914 static char **matches = (char **)NULL;
3915 static int ind;
3916 int glen;
3917 char *ret, *ttext;
3918
3919 if (state == 0)
3920 {
3921 rl_filename_completion_desired = 1;
3922 FREE (matches);
3923 if (globorig != globtext)
3924 FREE (globorig);
3925 FREE (globtext);
3926
3927 ttext = bash_tilde_expand (text, 0);
3928
3929 if (rl_explicit_arg)
3930 {
3931 globorig = savestring (ttext);
3932 glen = strlen (ttext);
3933 globtext = (char *)xmalloc (glen + 2);
3934 strcpy (globtext, ttext);
3935 globtext[glen] = '*';
3936 globtext[glen+1] = '\0';
3937 }
3938 else
3939 globtext = globorig = savestring (ttext);
3940
3941 if (ttext != text)
3942 free (ttext);
3943
3944 matches = shell_glob_filename (globtext, 0);
3945 if (GLOB_FAILED (matches))
3946 matches = (char **)NULL;
3947 ind = 0;
3948 }
3949
3950 ret = matches ? matches[ind] : (char *)NULL;
3951 ind++;
3952 return ret;
3953 }
3954
3955 static int
3956 bash_glob_completion_internal (what_to_do)
3957 int what_to_do;
3958 {
3959 return bash_specific_completion (what_to_do, glob_complete_word);
3960 }
3961
3962 /* A special quoting function so we don't end up quoting globbing characters
3963 in the word if there are no matches or multiple matches. */
3964 static char *
3965 bash_glob_quote_filename (s, rtype, qcp)
3966 char *s;
3967 int rtype;
3968 char *qcp;
3969 {
3970 if (globorig && qcp && *qcp == '\0' && STREQ (s, globorig))
3971 return (savestring (s));
3972 else
3973 return (bash_quote_filename (s, rtype, qcp));
3974 }
3975
3976 static int
3977 bash_glob_complete_word (count, key)
3978 int count, key;
3979 {
3980 int r;
3981 rl_quote_func_t *orig_quoting_function;
3982
3983 if (rl_editing_mode == EMACS_EDITING_MODE)
3984 rl_explicit_arg = 1; /* force `*' append */
3985 orig_quoting_function = rl_filename_quoting_function;
3986 rl_filename_quoting_function = bash_glob_quote_filename;
3987
3988 r = bash_glob_completion_internal (rl_completion_mode (bash_glob_complete_word));
3989
3990 rl_filename_quoting_function = orig_quoting_function;
3991 return r;
3992 }
3993
3994 static int
3995 bash_glob_expand_word (count, key)
3996 int count, key;
3997 {
3998 return bash_glob_completion_internal ('*');
3999 }
4000
4001 static int
4002 bash_glob_list_expansions (count, key)
4003 int count, key;
4004 {
4005 return bash_glob_completion_internal ('?');
4006 }
4007
4008 static int
4009 bash_specific_completion (what_to_do, generator)
4010 int what_to_do;
4011 rl_compentry_func_t *generator;
4012 {
4013 rl_compentry_func_t *orig_func;
4014 rl_completion_func_t *orig_attempt_func;
4015 rl_compignore_func_t *orig_ignore_func;
4016 int r;
4017
4018 orig_func = rl_completion_entry_function;
4019 orig_attempt_func = rl_attempted_completion_function;
4020 orig_ignore_func = rl_ignore_some_completions_function;
4021 rl_completion_entry_function = generator;
4022 rl_attempted_completion_function = NULL;
4023 rl_ignore_some_completions_function = orig_ignore_func;
4024
4025 r = rl_complete_internal (what_to_do);
4026
4027 rl_completion_entry_function = orig_func;
4028 rl_attempted_completion_function = orig_attempt_func;
4029 rl_ignore_some_completions_function = orig_ignore_func;
4030
4031 return r;
4032 }
4033
4034 #endif /* SPECIFIC_COMPLETION_FUNCTIONS */
4035
4036 #if defined (VI_MODE)
4037 /* Completion, from vi mode's point of view. This is a modified version of
4038 rl_vi_complete which uses the bash globbing code to implement what POSIX
4039 specifies, which is to append a `*' and attempt filename generation (which
4040 has the side effect of expanding any globbing characters in the word). */
4041 static int
4042 bash_vi_complete (count, key)
4043 int count, key;
4044 {
4045 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
4046 int p, r;
4047 char *t;
4048
4049 if ((rl_point < rl_end) && (!whitespace (rl_line_buffer[rl_point])))
4050 {
4051 if (!whitespace (rl_line_buffer[rl_point + 1]))
4052 rl_vi_end_word (1, 'E');
4053 rl_point++;
4054 }
4055
4056 /* Find boundaries of current word, according to vi definition of a
4057 `bigword'. */
4058 t = 0;
4059 if (rl_point > 0)
4060 {
4061 p = rl_point;
4062 rl_vi_bWord (1, 'B');
4063 r = rl_point;
4064 rl_point = p;
4065 p = r;
4066
4067 t = substring (rl_line_buffer, p, rl_point);
4068 }
4069
4070 if (t && completion_glob_pattern (t) == 0)
4071 rl_explicit_arg = 1; /* XXX - force glob_complete_word to append `*' */
4072 FREE (t);
4073
4074 if (key == '*') /* Expansion and replacement. */
4075 r = bash_glob_expand_word (count, key);
4076 else if (key == '=') /* List possible completions. */
4077 r = bash_glob_list_expansions (count, key);
4078 else if (key == '\\') /* Standard completion */
4079 r = bash_glob_complete_word (count, key);
4080 else
4081 r = rl_complete (0, key);
4082
4083 if (key == '*' || key == '\\')
4084 rl_vi_start_inserting (key, 1, 1);
4085
4086 return (r);
4087 #else
4088 return rl_vi_complete (count, key);
4089 #endif /* !SPECIFIC_COMPLETION_FUNCTIONS */
4090 }
4091 #endif /* VI_MODE */
4092
4093 /* Filename quoting for completion. */
4094 /* A function to strip unquoted quote characters (single quotes, double
4095 quotes, and backslashes). It allows single quotes to appear
4096 within double quotes, and vice versa. It should be smarter. */
4097 static char *
4098 bash_dequote_filename (text, quote_char)
4099 char *text;
4100 int quote_char;
4101 {
4102 char *ret, *p, *r;
4103 int l, quoted;
4104
4105 l = strlen (text);
4106 ret = (char *)xmalloc (l + 1);
4107 for (quoted = quote_char, p = text, r = ret; p && *p; p++)
4108 {
4109 /* Allow backslash-escaped characters to pass through unscathed. */
4110 if (*p == '\\')
4111 {
4112 /* Backslashes are preserved within single quotes. */
4113 if (quoted == '\'')
4114 *r++ = *p;
4115 /* Backslashes are preserved within double quotes unless the
4116 character is one that is defined to be escaped */
4117 else if (quoted == '"' && ((sh_syntaxtab[(unsigned char)p[1]] & CBSDQUOTE) == 0))
4118 *r++ = *p;
4119
4120 *r++ = *++p;
4121 if (*p == '\0')
4122 return ret; /* XXX - was break; */
4123 continue;
4124 }
4125 /* Close quote. */
4126 if (quoted && *p == quoted)
4127 {
4128 quoted = 0;
4129 continue;
4130 }
4131 /* Open quote. */
4132 if (quoted == 0 && (*p == '\'' || *p == '"'))
4133 {
4134 quoted = *p;
4135 continue;
4136 }
4137 *r++ = *p;
4138 }
4139 *r = '\0';
4140 return ret;
4141 }
4142
4143 /* Quote characters that the readline completion code would treat as
4144 word break characters with backslashes. Pass backslash-quoted
4145 characters through without examination. */
4146 static char *
4147 quote_word_break_chars (text)
4148 char *text;
4149 {
4150 char *ret, *r, *s;
4151 int l;
4152
4153 l = strlen (text);
4154 ret = (char *)xmalloc ((2 * l) + 1);
4155 for (s = text, r = ret; *s; s++)
4156 {
4157 /* Pass backslash-quoted characters through, including the backslash. */
4158 if (*s == '\\')
4159 {
4160 *r++ = '\\';
4161 *r++ = *++s;
4162 if (*s == '\0')
4163 break;
4164 continue;
4165 }
4166 /* OK, we have an unquoted character. Check its presence in
4167 rl_completer_word_break_characters. */
4168 if (mbschr (rl_completer_word_break_characters, *s))
4169 *r++ = '\\';
4170 /* XXX -- check for standalone tildes here and backslash-quote them */
4171 if (s == text && *s == '~' && file_exists (text))
4172 *r++ = '\\';
4173 *r++ = *s;
4174 }
4175 *r = '\0';
4176 return ret;
4177 }
4178
4179 /* Use characters in STRING to populate the table of characters that should
4180 be backslash-quoted. The table will be used for sh_backslash_quote from
4181 this file. */
4182 static void
4183 set_filename_bstab (string)
4184 const char *string;
4185 {
4186 const char *s;
4187
4188 memset (filename_bstab, 0, sizeof (filename_bstab));
4189 for (s = string; s && *s; s++)
4190 filename_bstab[(unsigned char)*s] = 1;
4191 }
4192
4193 /* Quote a filename using double quotes, single quotes, or backslashes
4194 depending on the value of completion_quoting_style. If we're
4195 completing using backslashes, we need to quote some additional
4196 characters (those that readline treats as word breaks), so we call
4197 quote_word_break_chars on the result. This returns newly-allocated
4198 memory. */
4199 static char *
4200 bash_quote_filename (s, rtype, qcp)
4201 char *s;
4202 int rtype;
4203 char *qcp;
4204 {
4205 char *rtext, *mtext, *ret;
4206 int rlen, cs;
4207
4208 rtext = (char *)NULL;
4209
4210 /* If RTYPE == MULT_MATCH, it means that there is
4211 more than one match. In this case, we do not add
4212 the closing quote or attempt to perform tilde
4213 expansion. If RTYPE == SINGLE_MATCH, we try
4214 to perform tilde expansion, because single and double
4215 quotes inhibit tilde expansion by the shell. */
4216
4217 cs = completion_quoting_style;
4218 /* Might need to modify the default completion style based on *qcp,
4219 since it's set to any user-provided opening quote. We also change
4220 to single-quoting if there is no user-provided opening quote and
4221 the word being completed contains newlines, since those are not
4222 quoted correctly using backslashes (a backslash-newline pair is
4223 special to the shell parser). */
4224 if (*qcp == '\0' && cs == COMPLETE_BSQUOTE && mbschr (s, '\n'))
4225 cs = COMPLETE_SQUOTE;
4226 else if (*qcp == '"')
4227 cs = COMPLETE_DQUOTE;
4228 else if (*qcp == '\'')
4229 cs = COMPLETE_SQUOTE;
4230 #if defined (BANG_HISTORY)
4231 else if (*qcp == '\0' && history_expansion && cs == COMPLETE_DQUOTE &&
4232 history_expansion_inhibited == 0 && mbschr (s, '!'))
4233 cs = COMPLETE_BSQUOTE;
4234
4235 if (*qcp == '"' && history_expansion && cs == COMPLETE_DQUOTE &&
4236 history_expansion_inhibited == 0 && mbschr (s, '!'))
4237 {
4238 cs = COMPLETE_BSQUOTE;
4239 *qcp = '\0';
4240 }
4241 #endif
4242
4243 /* Don't tilde-expand backslash-quoted filenames, since only single and
4244 double quotes inhibit tilde expansion. */
4245 mtext = s;
4246 if (mtext[0] == '~' && rtype == SINGLE_MATCH && cs != COMPLETE_BSQUOTE)
4247 mtext = bash_tilde_expand (s, 0);
4248
4249 switch (cs)
4250 {
4251 case COMPLETE_DQUOTE:
4252 rtext = sh_double_quote (mtext);
4253 break;
4254 case COMPLETE_SQUOTE:
4255 rtext = sh_single_quote (mtext);
4256 break;
4257 case COMPLETE_BSQUOTE:
4258 rtext = sh_backslash_quote (mtext, complete_fullquote ? 0 : filename_bstab, 0);
4259 break;
4260 }
4261
4262 if (mtext != s)
4263 free (mtext);
4264
4265 /* We may need to quote additional characters: those that readline treats
4266 as word breaks that are not quoted by backslash_quote. */
4267 if (rtext && cs == COMPLETE_BSQUOTE)
4268 {
4269 mtext = quote_word_break_chars (rtext);
4270 free (rtext);
4271 rtext = mtext;
4272 }
4273
4274 /* Leave the opening quote intact. The readline completion code takes
4275 care of avoiding doubled opening quotes. */
4276 if (rtext)
4277 {
4278 rlen = strlen (rtext);
4279 ret = (char *)xmalloc (rlen + 1);
4280 strcpy (ret, rtext);
4281 }
4282 else
4283 {
4284 ret = (char *)xmalloc (rlen = 1);
4285 ret[0] = '\0';
4286 }
4287
4288 /* If there are multiple matches, cut off the closing quote. */
4289 if (rtype == MULT_MATCH && cs != COMPLETE_BSQUOTE)
4290 ret[rlen - 1] = '\0';
4291 free (rtext);
4292 return ret;
4293 }
4294
4295 /* Support for binding readline key sequences to Unix commands. Each editing
4296 mode has a separate Unix command keymap. */
4297
4298 static Keymap emacs_std_cmd_xmap;
4299 #if defined (VI_MODE)
4300 static Keymap vi_insert_cmd_xmap;
4301 static Keymap vi_movement_cmd_xmap;
4302 #endif
4303
4304 #ifdef _MINIX
4305 static void
4306 #else
4307 static int
4308 #endif
4309 putx(c)
4310 int c;
4311 {
4312 int x;
4313 x = putc (c, rl_outstream);
4314 #ifndef _MINIX
4315 return x;
4316 #endif
4317 }
4318
4319 static int
4320 readline_get_char_offset (ind)
4321 int ind;
4322 {
4323 int r, old_ch;
4324
4325 r = ind;
4326 #if defined (HANDLE_MULTIBYTE)
4327 if (locale_mb_cur_max > 1)
4328 {
4329 old_ch = rl_line_buffer[ind];
4330 rl_line_buffer[ind] = '\0';
4331 r = MB_STRLEN (rl_line_buffer);
4332 rl_line_buffer[ind] = old_ch;
4333 }
4334 #endif
4335 return r;
4336 }
4337
4338 static void
4339 readline_set_char_offset (ind, varp)
4340 int ind;
4341 int *varp;
4342 {
4343 int i;
4344
4345 i = ind;
4346
4347 #if defined (HANDLE_MULTIBYTE)
4348 if (i > 0 && locale_mb_cur_max > 1)
4349 i = _rl_find_next_mbchar (rl_line_buffer, 0, i, 0); /* XXX */
4350 #endif
4351 if (i != *varp)
4352 {
4353 if (i > rl_end)
4354 i = rl_end;
4355 else if (i < 0)
4356 i = 0;
4357 *varp = i;
4358 }
4359 }
4360
4361 int
4362 bash_execute_unix_command (count, key)
4363 int count; /* ignored */
4364 int key;
4365 {
4366 int type;
4367 register int i, r;
4368 intmax_t mi;
4369 sh_parser_state_t ps;
4370 char *cmd, *value, *ce, old_ch;
4371 SHELL_VAR *v;
4372 char ibuf[INT_STRLEN_BOUND(int) + 1];
4373 Keymap cmd_xmap;
4374
4375 /* First, we need to find the right command to execute. This is tricky,
4376 because we might have already indirected into another keymap, so we
4377 have to walk cmd_xmap using the entire key sequence. */
4378 cmd_xmap = get_cmd_xmap_from_keymap (rl_get_keymap ());
4379 cmd = (char *)rl_function_of_keyseq_len (rl_executing_keyseq, rl_key_sequence_length, cmd_xmap, &type);
4380
4381 if (type == ISKMAP && (type = ((Keymap) cmd)[ANYOTHERKEY].type) == ISMACR)
4382 cmd = (char*)((Keymap) cmd)[ANYOTHERKEY].function;
4383
4384 if (cmd == 0 || type != ISMACR)
4385 {
4386 rl_crlf ();
4387 internal_error (_("bash_execute_unix_command: cannot find keymap for command"));
4388 rl_forced_update_display ();
4389 return 1;
4390 }
4391
4392 ce = rl_get_termcap ("ce");
4393 if (ce) /* clear current line */
4394 {
4395 rl_clear_visible_line ();
4396 fflush (rl_outstream);
4397 }
4398 else
4399 rl_crlf (); /* move to a new line */
4400
4401 v = bind_variable ("READLINE_LINE", rl_line_buffer, 0);
4402 if (v)
4403 VSETATTR (v, att_exported);
4404
4405 i = readline_get_char_offset (rl_point);
4406 value = inttostr (i, ibuf, sizeof (ibuf));
4407 v = bind_int_variable ("READLINE_POINT", value, 0);
4408 if (v)
4409 VSETATTR (v, att_exported);
4410
4411 i = readline_get_char_offset (rl_mark);
4412 value = inttostr (i, ibuf, sizeof (ibuf));
4413 v = bind_int_variable ("READLINE_MARK", value, 0);
4414 if (v)
4415 VSETATTR (v, att_exported);
4416 array_needs_making = 1;
4417
4418 save_parser_state (&ps);
4419 rl_clear_signals ();
4420 r = parse_and_execute (savestring (cmd), "bash_execute_unix_command", SEVAL_NOHIST);
4421 rl_set_signals ();
4422 restore_parser_state (&ps);
4423
4424 v = find_variable ("READLINE_LINE");
4425 maybe_make_readline_line (v ? value_cell (v) : 0);
4426
4427 v = find_variable ("READLINE_POINT");
4428 if (v && legal_number (value_cell (v), &mi))
4429 readline_set_char_offset (mi, &rl_point);
4430
4431 v = find_variable ("READLINE_MARK");
4432 if (v && legal_number (value_cell (v), &mi))
4433 readline_set_char_offset (mi, &rl_mark);
4434
4435 check_unbind_variable ("READLINE_LINE");
4436 check_unbind_variable ("READLINE_POINT");
4437 check_unbind_variable ("READLINE_MARK");
4438 array_needs_making = 1;
4439
4440 /* and restore the readline buffer and display after command execution. */
4441 /* If we clear the last line of the prompt above, redraw only that last
4442 line. If the command returns 124, we redraw unconditionally as in
4443 previous versions. */
4444 if (ce && r != 124)
4445 rl_redraw_prompt_last_line ();
4446 else
4447 rl_forced_update_display ();
4448
4449 return 0;
4450 }
4451
4452 int
4453 print_unix_command_map ()
4454 {
4455 Keymap save, cmd_xmap;
4456
4457 save = rl_get_keymap ();
4458 cmd_xmap = get_cmd_xmap_from_keymap (save);
4459 rl_set_keymap (cmd_xmap);
4460 rl_macro_dumper (1);
4461 rl_set_keymap (save);
4462 return 0;
4463 }
4464
4465 static void
4466 init_unix_command_map ()
4467 {
4468 emacs_std_cmd_xmap = rl_make_bare_keymap ();
4469
4470 emacs_std_cmd_xmap[CTRL('X')].type = ISKMAP;
4471 emacs_std_cmd_xmap[CTRL('X')].function = KEYMAP_TO_FUNCTION (rl_make_bare_keymap ());
4472 emacs_std_cmd_xmap[ESC].type = ISKMAP;
4473 emacs_std_cmd_xmap[ESC].function = KEYMAP_TO_FUNCTION (rl_make_bare_keymap ());
4474
4475 #if defined (VI_MODE)
4476 vi_insert_cmd_xmap = rl_make_bare_keymap ();
4477 vi_movement_cmd_xmap = rl_make_bare_keymap ();
4478 #endif
4479 }
4480
4481 static Keymap
4482 get_cmd_xmap_from_edit_mode ()
4483 {
4484 if (emacs_std_cmd_xmap == 0)
4485 init_unix_command_map ();
4486
4487 switch (rl_editing_mode)
4488 {
4489 case EMACS_EDITING_MODE:
4490 return emacs_std_cmd_xmap;
4491 #if defined (VI_MODE)
4492 case VI_EDITING_MODE:
4493 return (get_cmd_xmap_from_keymap (rl_get_keymap ()));
4494 #endif
4495 default:
4496 return (Keymap)NULL;
4497 }
4498 }
4499
4500 static Keymap
4501 get_cmd_xmap_from_keymap (kmap)
4502 Keymap kmap;
4503 {
4504 if (emacs_std_cmd_xmap == 0)
4505 init_unix_command_map ();
4506
4507 if (kmap == emacs_standard_keymap)
4508 return emacs_std_cmd_xmap;
4509 else if (kmap == emacs_meta_keymap)
4510 return (FUNCTION_TO_KEYMAP (emacs_std_cmd_xmap, ESC));
4511 else if (kmap == emacs_ctlx_keymap)
4512 return (FUNCTION_TO_KEYMAP (emacs_std_cmd_xmap, CTRL('X')));
4513 #if defined (VI_MODE)
4514 else if (kmap == vi_insertion_keymap)
4515 return vi_insert_cmd_xmap;
4516 else if (kmap == vi_movement_keymap)
4517 return vi_movement_cmd_xmap;
4518 #endif
4519 else
4520 return (Keymap)NULL;
4521 }
4522
4523 static int
4524 isolate_sequence (string, ind, need_dquote, startp)
4525 char *string;
4526 int ind, need_dquote, *startp;
4527 {
4528 register int i;
4529 int c, passc, delim;
4530
4531 for (i = ind; string[i] && whitespace (string[i]); i++)
4532 ;
4533 /* NEED_DQUOTE means that the first non-white character *must* be `"'. */
4534 if (need_dquote && string[i] != '"')
4535 {
4536 builtin_error (_("%s: first non-whitespace character is not `\"'"), string);
4537 return -1;
4538 }
4539
4540 /* We can have delimited strings even if NEED_DQUOTE == 0, like the command
4541 string to bind the key sequence to. */
4542 delim = (string[i] == '"' || string[i] == '\'') ? string[i] : 0;
4543
4544 if (startp)
4545 *startp = delim ? ++i : i;
4546
4547 for (passc = 0; c = string[i]; i++)
4548 {
4549 if (passc)
4550 {
4551 passc = 0;
4552 continue;
4553 }
4554 if (c == '\\')
4555 {
4556 passc++;
4557 continue;
4558 }
4559 if (c == delim)
4560 break;
4561 }
4562
4563 if (delim && string[i] != delim)
4564 {
4565 builtin_error (_("no closing `%c' in %s"), delim, string);
4566 return -1;
4567 }
4568
4569 return i;
4570 }
4571
4572 int
4573 bind_keyseq_to_unix_command (line)
4574 char *line;
4575 {
4576 Keymap kmap, cmd_xmap;
4577 char *kseq, *value;
4578 int i, kstart;
4579
4580 kmap = rl_get_keymap ();
4581
4582 /* We duplicate some of the work done by rl_parse_and_bind here, but
4583 this code only has to handle `"keyseq": ["]command["]' and can
4584 generate an error for anything else. */
4585 i = isolate_sequence (line, 0, 1, &kstart);
4586 if (i < 0)
4587 return -1;
4588
4589 /* Create the key sequence string to pass to rl_generic_bind */
4590 kseq = substring (line, kstart, i);
4591
4592 for ( ; line[i] && line[i] != ':'; i++)
4593 ;
4594 if (line[i] != ':')
4595 {
4596 builtin_error (_("%s: missing colon separator"), line);
4597 FREE (kseq);
4598 return -1;
4599 }
4600
4601 i = isolate_sequence (line, i + 1, 0, &kstart);
4602 if (i < 0)
4603 {
4604 FREE (kseq);
4605 return -1;
4606 }
4607
4608 /* Create the value string containing the command to execute. */
4609 value = substring (line, kstart, i);
4610
4611 /* Save the command to execute and the key sequence in the CMD_XMAP */
4612 cmd_xmap = get_cmd_xmap_from_keymap (kmap);
4613 rl_generic_bind (ISMACR, kseq, value, cmd_xmap);
4614
4615 /* and bind the key sequence in the current keymap to a function that
4616 understands how to execute from CMD_XMAP */
4617 rl_bind_keyseq_in_map (kseq, bash_execute_unix_command, kmap);
4618
4619 free (kseq);
4620 return 0;
4621 }
4622
4623 int
4624 unbind_unix_command (kseq)
4625 char *kseq;
4626 {
4627 Keymap cmd_xmap;
4628
4629 cmd_xmap = get_cmd_xmap_from_keymap (rl_get_keymap ());
4630 if (rl_bind_keyseq_in_map (kseq, (rl_command_func_t *)NULL, cmd_xmap) != 0)
4631 {
4632 builtin_error (_("`%s': cannot unbind in command keymap"), kseq);
4633 return 0;
4634 }
4635 return 1;
4636 }
4637
4638 /* Used by the programmable completion code. Complete TEXT as a filename,
4639 but return only directories as matches. Dequotes the filename before
4640 attempting to find matches. */
4641 char **
4642 bash_directory_completion_matches (text)
4643 const char *text;
4644 {
4645 char **m1;
4646 char *dfn;
4647 int qc;
4648
4649 qc = rl_dispatching ? rl_completion_quote_character : 0;
4650 /* If rl_completion_found_quote != 0, rl_completion_matches will call the
4651 filename dequoting function, causing the directory name to be dequoted
4652 twice. */
4653 if (rl_dispatching && rl_completion_found_quote == 0)
4654 dfn = bash_dequote_filename ((char *)text, qc);
4655 else
4656 dfn = (char *)text;
4657 m1 = rl_completion_matches (dfn, rl_filename_completion_function);
4658 if (dfn != text)
4659 free (dfn);
4660
4661 if (m1 == 0 || m1[0] == 0)
4662 return m1;
4663 /* We don't bother recomputing the lcd of the matches, because it will just
4664 get thrown away by the programmable completion code and recomputed
4665 later. */
4666 (void)bash_progcomp_ignore_filenames (m1);
4667 return m1;
4668 }
4669
4670 char *
4671 bash_dequote_text (text)
4672 const char *text;
4673 {
4674 char *dtxt;
4675 int qc;
4676
4677 qc = (text[0] == '"' || text[0] == '\'') ? text[0] : 0;
4678 dtxt = bash_dequote_filename ((char *)text, qc);
4679 return (dtxt);
4680 }
4681
4682 /* This event hook is designed to be called after readline receives a signal
4683 that interrupts read(2). It gives reasonable responsiveness to interrupts
4684 and fatal signals without executing too much code in a signal handler
4685 context. */
4686 static int
4687 bash_event_hook ()
4688 {
4689 int sig;
4690
4691 /* XXX - see if we need to do anything here if sigterm_received == 1,
4692 we probably don't want to reset the event hook since we will not be
4693 jumping to the top level */
4694 if (sigterm_received)
4695 {
4696 /* RESET_SIGTERM; */
4697 return 0;
4698 }
4699
4700 sig = 0;
4701 if (terminating_signal)
4702 sig = terminating_signal;
4703 else if (interrupt_state)
4704 sig = SIGINT;
4705 else if (read_timeout && read_timeout->alrmflag)
4706 sig = SIGALRM;
4707 else if (RL_ISSTATE (RL_STATE_TIMEOUT)) /* just in case */
4708 {
4709 sig = SIGALRM;
4710 if (read_timeout)
4711 read_timeout->alrmflag = 1;
4712 }
4713 else
4714 sig = first_pending_trap ();
4715
4716 /* If we're going to longjmp to top_level, make sure we clean up readline.
4717 check_signals will call QUIT, which will eventually longjmp to top_level,
4718 calling run_interrupt_trap along the way. The check against read_timeout
4719 is so we can clean up the read builtin's state. */
4720 if (terminating_signal || interrupt_state || (read_timeout && read_timeout->alrmflag))
4721 rl_cleanup_after_signal ();
4722 bashline_reset_event_hook ();
4723
4724 RL_UNSETSTATE (RL_STATE_TIMEOUT); /* XXX */
4725
4726 /* posix mode SIGINT during read -e. We only get here if SIGINT is trapped. */
4727 if (posixly_correct && this_shell_builtin == read_builtin && sig == SIGINT)
4728 {
4729 last_command_exit_value = 128|SIGINT;
4730 throw_to_top_level ();
4731 }
4732
4733 check_signals_and_traps (); /* XXX */
4734 return 0;
4735 }
4736
4737 #endif /* READLINE */