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