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