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