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