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