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