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