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