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