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