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