]> git.ipfire.org Git - thirdparty/bash.git/blob - bashline.c
4feb7be8584c164b21d7d8086b4353e4a38917ca
[thirdparty/bash.git] / bashline.c
1 /* bashline.c -- Bash's interface to the readline library. */
2
3 /* Copyright (C) 1987,1991 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 1, 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, 675 Mass Ave, Cambridge, MA 02139, 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 #include <stdio.h>
33 #include "bashansi.h"
34 #include "shell.h"
35 #include "builtins.h"
36 #include "bashhist.h"
37 #include "bashline.h"
38 #include "execute_cmd.h"
39 #include "pathexp.h"
40 #include "builtins/common.h"
41 #include <readline/rlconf.h>
42 #include <readline/readline.h>
43 #include <readline/history.h>
44
45 #include <glob/glob.h>
46
47 #if defined (ALIAS)
48 # include "alias.h"
49 #endif
50
51 #if defined (BRACE_COMPLETION)
52 extern void bash_brace_completion ();
53 #endif /* BRACE_COMPLETION */
54
55 /* Functions bound to keys in Readline for Bash users. */
56 static void shell_expand_line ();
57 static void display_shell_version (), operate_and_get_next ();
58 static void history_expand_line (), bash_ignore_filenames ();
59 #ifdef ALIAS
60 static void alias_expand_line ();
61 #endif
62 static void history_and_alias_expand_line ();
63 static void cleanup_expansion_error (), set_up_new_line ();
64
65 /* Helper functions for Readline. */
66 static int bash_directory_completion_hook ();
67 static void filename_completion_ignore ();
68 static void bash_push_line ();
69
70 static char **attempt_shell_completion ();
71 static char *variable_completion_function ();
72 static char *hostname_completion_function ();
73 static char *command_word_completion_function ();
74 static char *command_subst_completion_function ();
75 static void dynamic_complete_history ();
76
77 static char *glob_complete_word ();
78 static void bash_glob_expand_word ();
79 static void bash_glob_list_expansions ();
80
81 static void snarf_hosts_from_file (), add_host_name ();
82
83 static char *bash_dequote_filename ();
84 static char *bash_quote_filename ();
85
86 #if defined (ALIAS)
87 static int posix_edit_macros ();
88 #endif
89
90 /* Variables used here but defined in other files. */
91 extern int posixly_correct, no_symbolic_links;
92 extern int rl_explicit_arg;
93 extern char *current_prompt_string, *ps1_prompt;
94 extern STRING_INT_ALIST word_token_alist[];
95 extern Function *rl_last_func;
96 extern int rl_filename_completion_desired;
97
98 /* Helper functions from subst.c */
99 extern int char_is_quoted ();
100 extern int unclosed_pair ();
101
102 /* SPECIFIC_COMPLETION_FUNCTIONS specifies that we have individual
103 completion functions which indicate what type of completion should be
104 done (at or before point) that can be bound to key sequences with
105 the readline library. */
106 #define SPECIFIC_COMPLETION_FUNCTIONS
107
108 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
109 static void bash_specific_completion ();
110 static void bash_complete_filename (), bash_possible_filename_completions ();
111 static void bash_complete_filename_internal ();
112 static void bash_complete_username (), bash_possible_username_completions ();
113 static void bash_complete_username_internal ();
114 static void bash_complete_hostname (), bash_possible_hostname_completions ();
115 static void bash_complete_hostname_internal ();
116 static void bash_complete_variable (), bash_possible_variable_completions ();
117 static void bash_complete_variable_internal ();
118 static void bash_complete_command (), bash_possible_command_completions ();
119 static void bash_complete_command_internal ();
120 #endif /* SPECIFIC_COMPLETION_FUNCTIONS */
121
122 #if defined (VI_MODE)
123 static void vi_edit_and_execute_command ();
124 #endif
125
126 /* Non-zero once initalize_readline () has been called. */
127 int bash_readline_initialized = 0;
128
129 /* If non-zero, we do hostname completion, breaking words at `@' and
130 trying to complete the stuff after the `@' from our own internal
131 host list. */
132 int perform_hostname_completion = 1;
133
134 static char *bash_completer_word_break_characters = " \t\n\"'@><=;|&(:";
135 static char *bash_nohostname_word_break_characters = " \t\n\"'><=;|&(:";
136
137 static Function *old_rl_startup_hook = (Function *) NULL;
138
139 /* What kind of quoting is performed by bash_quote_filename:
140 COMPLETE_DQUOTE = double-quoting the filename
141 COMPLETE_SQUOTE = single_quoting the filename
142 COMPLETE_BSQUOTE = backslash-quoting special chars in the filename
143 */
144 #define COMPLETE_DQUOTE 1
145 #define COMPLETE_SQUOTE 2
146 #define COMPLETE_BSQUOTE 3
147 static int completion_quoting_style = COMPLETE_BSQUOTE;
148
149 /* Change the readline VI-mode keymaps into or out of Posix.2 compliance.
150 Called when the shell is put into or out of `posix' mode. */
151 void
152 posix_readline_initialize (on_or_off)
153 int on_or_off;
154 {
155 if (on_or_off)
156 rl_variable_bind ("comment-begin", "#");
157 #if defined (VI_MODE)
158 rl_bind_key_in_map (CTRL('I'), on_or_off ? rl_insert : rl_complete, vi_insertion_keymap);
159 #endif
160 }
161
162 void
163 enable_hostname_completion (on_or_off)
164 int on_or_off;
165 {
166 if (on_or_off)
167 {
168 perform_hostname_completion = 1;
169 rl_special_prefixes = "$@";
170 rl_completer_word_break_characters = bash_completer_word_break_characters;
171 }
172 else
173 {
174 perform_hostname_completion = 0;
175 rl_special_prefixes = "$";
176 rl_completer_word_break_characters = bash_nohostname_word_break_characters;
177 }
178 }
179
180 /* Called once from parse.y if we are going to use readline. */
181 void
182 initialize_readline ()
183 {
184 if (bash_readline_initialized)
185 return;
186
187 rl_terminal_name = get_string_value ("TERM");
188 rl_instream = stdin;
189 rl_outstream = stderr;
190
191 /* Allow conditional parsing of the ~/.inputrc file. */
192 rl_readline_name = "Bash";
193
194 /* Bind up our special shell functions. */
195 rl_add_defun ("shell-expand-line", (Function *)shell_expand_line, -1);
196 rl_bind_key_in_map (CTRL('E'), (Function *)shell_expand_line, emacs_meta_keymap);
197
198 /* Bind up our special shell functions. */
199 rl_add_defun ("history-expand-line", (Function *)history_expand_line, -1);
200 rl_bind_key_in_map ('^', (Function *)history_expand_line, emacs_meta_keymap);
201
202 #ifdef ALIAS
203 rl_add_defun ("alias-expand-line", (Function *)alias_expand_line, -1);
204 rl_add_defun ("history-and-alias-expand-line", (Function *)history_and_alias_expand_line, -1);
205 #endif
206
207 /* Backwards compatibility. */
208 rl_add_defun ("insert-last-argument", rl_yank_last_arg, -1);
209
210 rl_add_defun
211 ("operate-and-get-next", (Function *)operate_and_get_next, CTRL('O'));
212
213 rl_add_defun
214 ("display-shell-version", (Function *)display_shell_version, -1);
215 rl_bind_key_in_map
216 (CTRL ('V'), (Function *)display_shell_version, emacs_ctlx_keymap);
217
218 /* In Bash, the user can switch editing modes with "set -o [vi emacs]",
219 so it is not necessary to allow C-M-j for context switching. Turn
220 off this occasionally confusing behaviour. */
221 rl_unbind_key_in_map (CTRL('J'), emacs_meta_keymap);
222 rl_unbind_key_in_map (CTRL('M'), emacs_meta_keymap);
223 #if defined (VI_MODE)
224 rl_unbind_key_in_map (CTRL('E'), vi_movement_keymap);
225 #endif
226
227 #if defined (BRACE_COMPLETION)
228 rl_add_defun ("complete-into-braces", bash_brace_completion, -1);
229 rl_bind_key_in_map ('{', bash_brace_completion, emacs_meta_keymap);
230 #endif /* BRACE_COMPLETION */
231
232 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
233 rl_add_defun ("complete-filename", bash_complete_filename, -1);
234 rl_bind_key_in_map ('/', bash_complete_filename, emacs_meta_keymap);
235 rl_add_defun ("possible-filename-completions",
236 bash_possible_filename_completions, -1);
237 rl_bind_key_in_map ('/', bash_possible_filename_completions, emacs_ctlx_keymap);
238
239 rl_add_defun ("complete-username", bash_complete_username, -1);
240 rl_bind_key_in_map ('~', bash_complete_username, emacs_meta_keymap);
241 rl_add_defun ("possible-username-completions",
242 bash_possible_username_completions, -1);
243 rl_bind_key_in_map ('~', bash_possible_username_completions, emacs_ctlx_keymap);
244
245 rl_add_defun ("complete-hostname", bash_complete_hostname, -1);
246 rl_bind_key_in_map ('@', bash_complete_hostname, emacs_meta_keymap);
247 rl_add_defun ("possible-hostname-completions",
248 bash_possible_hostname_completions, -1);
249 rl_bind_key_in_map ('@', bash_possible_hostname_completions, emacs_ctlx_keymap);
250
251 rl_add_defun ("complete-variable", bash_complete_variable, -1);
252 rl_bind_key_in_map ('$', bash_complete_variable, emacs_meta_keymap);
253 rl_add_defun ("possible-variable-completions",
254 bash_possible_variable_completions, -1);
255 rl_bind_key_in_map ('$', bash_possible_variable_completions, emacs_ctlx_keymap);
256
257 rl_add_defun ("complete-command", bash_complete_command, -1);
258 rl_bind_key_in_map ('!', bash_complete_command, emacs_meta_keymap);
259 rl_add_defun ("possible-command-completions",
260 bash_possible_command_completions, -1);
261 rl_bind_key_in_map ('!', bash_possible_command_completions, emacs_ctlx_keymap);
262
263 rl_add_defun ("glob-expand-word", bash_glob_expand_word, -1);
264 rl_add_defun ("glob-list-expansions", bash_glob_list_expansions, -1);
265 rl_bind_key_in_map ('*', bash_glob_expand_word, emacs_ctlx_keymap);
266 rl_bind_key_in_map ('g', bash_glob_list_expansions, emacs_ctlx_keymap);
267
268 #endif /* SPECIFIC_COMPLETION_FUNCTIONS */
269
270 rl_add_defun ("dynamic-complete-history", dynamic_complete_history, -1);
271 rl_bind_key_in_map (TAB, dynamic_complete_history, emacs_meta_keymap);
272
273 /* Tell the completer that we want a crack first. */
274 rl_attempted_completion_function = (CPPFunction *)attempt_shell_completion;
275
276 /* Tell the completer that we might want to follow symbolic links or
277 do other expansion on directory names. */
278 rl_directory_completion_hook = bash_directory_completion_hook;
279
280 /* Tell the filename completer we want a chance to ignore some names. */
281 rl_ignore_some_completions_function = (Function *)filename_completion_ignore;
282
283 #if defined (VI_MODE)
284 rl_bind_key_in_map ('v', vi_edit_and_execute_command, vi_movement_keymap);
285 # if defined (ALIAS)
286 rl_bind_key_in_map ('@', posix_edit_macros, vi_movement_keymap);
287 # endif
288 #endif
289
290 rl_completer_quote_characters = "'\"";
291
292 /* This sets rl_completer_word_break_characters and rl_special_prefixes
293 to the appropriate values, depending on whether or not hostname
294 completion is enabled. */
295 enable_hostname_completion (perform_hostname_completion);
296
297 /* characters that need to be quoted when appearing in filenames. */
298 rl_filename_quote_characters = " \t\n\\\"'@<>=;|&()#$`?*[!:";
299 rl_filename_quoting_function = bash_quote_filename;
300 rl_filename_dequoting_function = bash_dequote_filename;
301 rl_char_is_quoted_p = char_is_quoted;
302
303 if (posixly_correct)
304 posix_readline_initialize (1);
305
306 bash_readline_initialized = 1;
307 }
308
309 /* On Sun systems at least, rl_attempted_completion_function can end up
310 getting set to NULL, and rl_completion_entry_function set to do command
311 word completion if Bash is interrupted while trying to complete a command
312 word. This just resets all the completion functions to the right thing.
313 It's called from throw_to_top_level(). */
314 void
315 bashline_reinitialize ()
316 {
317 tilde_initialize ();
318 rl_attempted_completion_function = attempt_shell_completion;
319 rl_completion_entry_function = (Function *)NULL;
320 rl_directory_completion_hook = bash_directory_completion_hook;
321 rl_ignore_some_completions_function = (Function *)filename_completion_ignore;
322 }
323
324 /* Contains the line to push into readline. */
325 static char *push_to_readline = (char *)NULL;
326
327 /* Push the contents of push_to_readline into the
328 readline buffer. */
329 static void
330 bash_push_line ()
331 {
332 if (push_to_readline)
333 {
334 rl_insert_text (push_to_readline);
335 free (push_to_readline);
336 push_to_readline = (char *)NULL;
337 rl_startup_hook = old_rl_startup_hook;
338 }
339 }
340
341 /* Call this to set the initial text for the next line to read
342 from readline. */
343 int
344 bash_re_edit (line)
345 char *line;
346 {
347 FREE (push_to_readline);
348
349 push_to_readline = savestring (line);
350 old_rl_startup_hook = rl_startup_hook;
351 rl_startup_hook = (Function *)bash_push_line;
352
353 return (0);
354 }
355
356 static void
357 display_shell_version (count, c)
358 int count, c;
359 {
360 crlf ();
361 show_shell_version (0);
362 putc ('\r', rl_outstream);
363 fflush (rl_outstream);
364 rl_on_new_line ();
365 rl_redisplay ();
366 }
367
368 /* **************************************************************** */
369 /* */
370 /* Readline Stuff */
371 /* */
372 /* **************************************************************** */
373
374 /* If the user requests hostname completion, then simply build a list
375 of hosts, and complete from that forever more. */
376
377 /* The kept list of hostnames. */
378 static char **hostname_list = (char **)NULL;
379
380 /* The physical size of the above list. */
381 static int hostname_list_size;
382
383 /* The number of hostnames in the above list. */
384 static int hostname_list_length;
385
386 /* Whether or not HOSTNAME_LIST has been initialized. */
387 int hostname_list_initialized = 0;
388
389 /* Initialize the hostname completion table. */
390 static void
391 initialize_hostname_list ()
392 {
393 char *temp;
394
395 temp = get_string_value ("HOSTFILE");
396 if (temp == 0)
397 temp = get_string_value ("hostname_completion_file");
398 if (temp == 0)
399 temp = DEFAULT_HOSTS_FILE;
400
401 snarf_hosts_from_file (temp);
402
403 if (hostname_list)
404 hostname_list_initialized++;
405 }
406
407 /* Add NAME to the list of hosts. */
408 static void
409 add_host_name (name)
410 char *name;
411 {
412 long size;
413
414 if (hostname_list_length + 2 > hostname_list_size)
415 {
416 hostname_list_size = (hostname_list_size + 32) - (hostname_list_size % 32);
417 size = hostname_list_size * sizeof (char *);
418 hostname_list = (char **)xrealloc (hostname_list, size);
419 }
420
421 hostname_list[hostname_list_length++] = savestring (name);
422 hostname_list[hostname_list_length] = (char *)NULL;
423 }
424
425 #define cr_whitespace(c) ((c) == '\r' || (c) == '\n' || whitespace(c))
426
427 static void
428 snarf_hosts_from_file (filename)
429 char *filename;
430 {
431 FILE *file;
432 char *temp, buffer[256], name[256];
433 register int i, start;
434
435 file = fopen (filename, "r");
436 if (file == 0)
437 return;
438
439 while (temp = fgets (buffer, 255, file))
440 {
441 /* Skip to first character. */
442 for (i = 0; buffer[i] && cr_whitespace (buffer[i]); i++)
443 ;
444
445 /* If comment or blank line, ignore. */
446 if (buffer[i] == '\0' || buffer[i] == '#')
447 continue;
448
449 /* If `preprocessor' directive, do the include. */
450 if (strncmp (buffer + i, "$include ", 9) == 0)
451 {
452 char *incfile, *t;
453
454 /* Find start of filename. */
455 for (incfile = buffer + i + 9; *incfile && whitespace (*incfile); incfile++)
456 ;
457
458 /* Find end of filename. */
459 for (t = incfile; *t && cr_whitespace (*t) == 0; t++)
460 ;
461
462 *t = '\0';
463
464 snarf_hosts_from_file (incfile);
465 continue;
466 }
467
468 /* Skip internet address if present. */
469 if (digit (buffer[i]))
470 for (; buffer[i] && cr_whitespace (buffer[i]) == 0; i++);
471
472 /* Gobble up names. Each name is separated with whitespace. */
473 while (buffer[i])
474 {
475 for (; cr_whitespace (buffer[i]); i++)
476 ;
477 if (buffer[i] == '\0' || buffer[i] == '#')
478 break;
479
480 /* Isolate the current word. */
481 for (start = i; buffer[i] && cr_whitespace (buffer[i]) == 0; i++)
482 ;
483 if (i == start)
484 continue;
485 strncpy (name, buffer + start, i - start);
486 name[i - start] = '\0';
487 add_host_name (name);
488 }
489 }
490 fclose (file);
491 }
492
493 /* Return a NULL terminated list of hostnames which begin with TEXT.
494 Initialize the hostname list the first time if neccessary.
495 The array is malloc ()'ed, but not the individual strings. */
496 static char **
497 hostnames_matching (text)
498 char *text;
499 {
500 register int i, len, nmatch, rsize;
501 char **result;
502
503 if (hostname_list_initialized == 0)
504 initialize_hostname_list ();
505
506 if (hostname_list_initialized == 0)
507 return ((char **)NULL);
508
509 /* Special case. If TEXT consists of nothing, then the whole list is
510 what is desired. */
511 if (*text == '\0')
512 {
513 result = (char **)xmalloc ((1 + hostname_list_length) * sizeof (char *));
514 for (i = 0; i < hostname_list_length; i++)
515 result[i] = hostname_list[i];
516 result[i] = (char *)NULL;
517 return (result);
518 }
519
520 /* Scan until found, or failure. */
521 len = strlen (text);
522 result = (char **)NULL;
523 for (i = nmatch = rsize = 0; i < hostname_list_length; i++)
524 {
525 if (STREQN (text, hostname_list[i], len) == 0)
526 continue;
527
528 /* OK, it matches. Add it to the list. */
529 if (nmatch >= rsize)
530 {
531 rsize = (rsize + 16) - (rsize % 16);
532 result = (char **)xrealloc (result, rsize * sizeof (char *));
533 }
534
535 result[nmatch++] = hostname_list[i];
536 }
537 if (nmatch)
538 result[nmatch] = (char *)NULL;
539 return (result);
540 }
541
542 /* The equivalent of the Korn shell C-o operate-and-get-next-history-line
543 editing command. */
544 static int saved_history_line_to_use = -1;
545
546 static void
547 set_saved_history ()
548 {
549 if (saved_history_line_to_use >= 0)
550 rl_get_previous_history (history_length - saved_history_line_to_use);
551 saved_history_line_to_use = -1;
552 rl_startup_hook = old_rl_startup_hook;
553 }
554
555 static void
556 operate_and_get_next (count, c)
557 int count, c;
558 {
559 int where;
560
561 /* Accept the current line. */
562 rl_newline ();
563
564 /* Find the current line, and find the next line to use. */
565 where = where_history ();
566
567 if ((history_is_stifled () && (history_length >= max_input_history)) ||
568 (where >= history_length - 1))
569 saved_history_line_to_use = where;
570 else
571 saved_history_line_to_use = where + 1;
572
573 old_rl_startup_hook = rl_startup_hook;
574 rl_startup_hook = (Function *)set_saved_history;
575 }
576
577 #if defined (VI_MODE)
578 /* This vi mode command causes VI_EDIT_COMMAND to be run on the current
579 command being entered (if no explicit argument is given), otherwise on
580 a command from the history file. */
581
582 #define VI_EDIT_COMMAND "fc -e ${VISUAL:-${EDITOR:-vi}}"
583
584 static void
585 vi_edit_and_execute_command (count, c)
586 int count, c;
587 {
588 char *command;
589
590 /* Accept the current line. */
591 rl_newline ();
592
593 if (rl_explicit_arg)
594 {
595 command = xmalloc (strlen (VI_EDIT_COMMAND) + 8);
596 sprintf (command, "%s %d", VI_EDIT_COMMAND, count);
597 }
598 else
599 {
600 /* Take the command we were just editing, add it to the history file,
601 then call fc to operate on it. We have to add a dummy command to
602 the end of the history because fc ignores the last command (assumes
603 it's supposed to deal with the command before the `fc'). */
604 using_history ();
605 bash_add_history (rl_line_buffer);
606 bash_add_history ("");
607 history_lines_this_session++;
608 using_history ();
609 command = savestring (VI_EDIT_COMMAND);
610 }
611 parse_and_execute (command, "v", SEVAL_NOHIST);
612 rl_line_buffer[0] = '\0'; /* XXX */
613 }
614 #endif /* VI_MODE */
615
616 #if defined (ALIAS)
617 static int
618 posix_edit_macros (count, key)
619 int count, key;
620 {
621 int c;
622 char alias_name[3], *alias_value, *macro;
623
624 c = rl_read_key ();
625 alias_name[0] = '_';
626 alias_name[1] = c;
627 alias_name[2] = '\0';
628
629 alias_value = get_alias_value (alias_name);
630 if (alias_value && *alias_value)
631 {
632 macro = savestring (alias_value);
633 rl_push_macro_input (macro);
634 }
635 return 0;
636 }
637 #endif
638
639 /* **************************************************************** */
640 /* */
641 /* How To Do Shell Completion */
642 /* */
643 /* **************************************************************** */
644
645 /* Do some completion on TEXT. The indices of TEXT in RL_LINE_BUFFER are
646 at START and END. Return an array of matches, or NULL if none. */
647 static char **
648 attempt_shell_completion (text, start, end)
649 char *text;
650 int start, end;
651 {
652 int in_command_position, ti;
653 char **matches, *command_separator_chars;
654
655 command_separator_chars = ";|&{(`";
656 matches = (char **)NULL;
657 rl_ignore_some_completions_function = (Function *)filename_completion_ignore;
658
659 /* Determine if this could be a command word. It is if it appears at
660 the start of the line (ignoring preceding whitespace), or if it
661 appears after a character that separates commands. It cannot be a
662 command word if we aren't at the top-level prompt. */
663 ti = start - 1;
664
665 while ((ti > -1) && (whitespace (rl_line_buffer[ti])))
666 ti--;
667
668 in_command_position = 0;
669 if (ti < 0)
670 {
671 /* Only do command completion at the start of a line when we
672 are prompting at the top level. */
673 if (current_prompt_string == ps1_prompt)
674 in_command_position++;
675 }
676 else if (member (rl_line_buffer[ti], command_separator_chars))
677 {
678 register int this_char, prev_char;
679
680 in_command_position++;
681
682 /* Handle the two character tokens `>&', `<&', and `>|'.
683 We are not in a command position after one of these. */
684 this_char = rl_line_buffer[ti];
685 prev_char = rl_line_buffer[ti - 1];
686
687 if ((this_char == '&' && (prev_char == '<' || prev_char == '>')) ||
688 (this_char == '|' && prev_char == '>'))
689 in_command_position = 0;
690 else if ((this_char == '{' && prev_char == '$') ||
691 (char_is_quoted (rl_line_buffer, ti)))
692 in_command_position = 0;
693 }
694 else
695 {
696 /* This still could be in command position. It is possible
697 that all of the previous words on the line are variable
698 assignments. */
699 }
700
701 /* Check that we haven't incorrectly flagged a closed command substitution
702 as indicating we're in a command position. */
703 if (in_command_position && ti >= 0 && rl_line_buffer[ti] == '`' &&
704 *text != '`' && unclosed_pair (rl_line_buffer, 0, "`") == 0)
705 in_command_position = 0;
706
707 /* Special handling for command substitution. If *TEXT is a backquote,
708 it can be the start or end of an old-style command substitution, or
709 unmatched. If it's unmatched, both calls to unclosed_pair will
710 succeed. */
711 if (*text == '`' && unclosed_pair (rl_line_buffer, start, "`") &&
712 unclosed_pair (rl_line_buffer, end, "`"))
713 matches = completion_matches (text, command_subst_completion_function);
714
715 /* Variable name? */
716 if (!matches && *text == '$')
717 matches = completion_matches (text, variable_completion_function);
718
719 /* If the word starts in `~', and there is no slash in the word, then
720 try completing this word as a username. */
721 if (!matches && *text == '~' && !strchr (text, '/'))
722 matches = completion_matches (text, username_completion_function);
723
724 /* Another one. Why not? If the word starts in '@', then look through
725 the world of known hostnames for completion first. */
726 if (!matches && perform_hostname_completion && *text == '@')
727 matches = completion_matches (text, hostname_completion_function);
728
729 /* And last, (but not least) if this word is in a command position, then
730 complete over possible command names, including aliases, functions,
731 and command names. */
732 if (!matches && in_command_position)
733 {
734 matches = completion_matches (text, command_word_completion_function);
735 /* If we are attempting command completion and nothing matches, we
736 do not want readline to perform filename completion for us. We
737 still want to be able to complete partial pathnames, so set the
738 completion ignore function to something which will remove filenames
739 and leave directories in the match list. */
740 if (!matches)
741 rl_ignore_some_completions_function = (Function *)bash_ignore_filenames;
742 }
743
744 /* This could be a globbing pattern, so try to expand it using pathname
745 expansion. */
746 if (!matches && glob_pattern_p (text))
747 {
748 matches = completion_matches (text, glob_complete_word);
749 /* A glob expression that matches more than one filename is problematic.
750 If we match more than one filename, punt. */
751 if (matches && matches[1])
752 {
753 free_array (matches);
754 matches = (char **)0;
755 }
756 }
757
758 return (matches);
759 }
760
761 /* This is the function to call when the word to complete is in a position
762 where a command word can be found. It grovels $PATH, looking for commands
763 that match. It also scans aliases, function names, and the shell_builtin
764 table. */
765 static char *
766 command_word_completion_function (hint_text, state)
767 char *hint_text;
768 int state;
769 {
770 static char *hint = (char *)NULL;
771 static char *path = (char *)NULL;
772 static char *val = (char *)NULL;
773 static char *filename_hint = (char *)NULL;
774 static int path_index, hint_len, istate;
775 static int mapping_over, local_index;
776 static SHELL_VAR **varlist = (SHELL_VAR **)NULL;
777 #if defined (ALIAS)
778 static alias_t **alias_list = (alias_t **)NULL;
779 #endif /* ALIAS */
780
781 /* We have to map over the possibilities for command words. If we have
782 no state, then make one just for that purpose. */
783 if (!state)
784 {
785 if (hint)
786 free (hint);
787
788 mapping_over = 0;
789 val = (char *)NULL;
790
791 /* If this is an absolute program name, do not check it against
792 aliases, reserved words, functions or builtins. We must check
793 whether or not it is unique, and, if so, whether that filename
794 is executable. */
795 if (absolute_program (hint_text))
796 {
797 /* Perform tilde expansion on what's passed, so we don't end up
798 passing filenames with tildes directly to stat(). */
799 if (*hint_text == '~')
800 hint = bash_tilde_expand (hint_text);
801 else
802 hint = savestring (hint_text);
803 hint_len = strlen (hint);
804
805 if (filename_hint)
806 free (filename_hint);
807 filename_hint = savestring (hint);
808
809 mapping_over = 4;
810 istate = 0;
811 goto inner;
812 }
813
814 hint = savestring (hint_text);
815 hint_len = strlen (hint);
816
817 path = get_string_value ("PATH");
818 path_index = 0;
819
820 /* Initialize the variables for each type of command word. */
821 local_index = 0;
822
823 if (varlist)
824 free (varlist);
825
826 varlist = all_visible_functions ();
827
828 #if defined (ALIAS)
829 if (alias_list)
830 free (alias_list);
831
832 alias_list = all_aliases ();
833 #endif /* ALIAS */
834 }
835
836 /* mapping_over says what we are currently hacking. Note that every case
837 in this list must fall through when there are no more possibilities. */
838
839 switch (mapping_over)
840 {
841 case 0: /* Aliases come first. */
842 #if defined (ALIAS)
843 while (alias_list && alias_list[local_index])
844 {
845 register char *alias;
846
847 alias = alias_list[local_index++]->name;
848
849 if (STREQN (alias, hint, hint_len))
850 return (savestring (alias));
851 }
852 #endif /* ALIAS */
853 local_index = 0;
854 mapping_over++;
855
856 case 1: /* Then shell reserved words. */
857 {
858 while (word_token_alist[local_index].word)
859 {
860 register char *reserved_word;
861
862 reserved_word = word_token_alist[local_index++].word;
863
864 if (STREQN (reserved_word, hint, hint_len))
865 return (savestring (reserved_word));
866 }
867 local_index = 0;
868 mapping_over++;
869 }
870
871 case 2: /* Then function names. */
872 while (varlist && varlist[local_index])
873 {
874 register char *varname;
875
876 varname = varlist[local_index++]->name;
877
878 if (STREQN (varname, hint, hint_len))
879 return (savestring (varname));
880 }
881 local_index = 0;
882 mapping_over++;
883
884 case 3: /* Then shell builtins. */
885 for (; local_index < num_shell_builtins; local_index++)
886 {
887 /* Ignore it if it doesn't have a function pointer or if it
888 is not currently enabled. */
889 if (!shell_builtins[local_index].function ||
890 (shell_builtins[local_index].flags & BUILTIN_ENABLED) == 0)
891 continue;
892
893 if (STREQN (shell_builtins[local_index].name, hint, hint_len))
894 {
895 int i = local_index++;
896
897 return (savestring (shell_builtins[i].name));
898 }
899 }
900 local_index = 0;
901 mapping_over++;
902 }
903
904 /* Repeatedly call filename_completion_function while we have
905 members of PATH left. Question: should we stat each file?
906 Answer: we call executable_file () on each file. */
907 outer:
908
909 istate = (val != (char *)NULL);
910
911 if (!istate)
912 {
913 char *current_path;
914
915 /* Get the next directory from the path. If there is none, then we
916 are all done. */
917 if (!path || !path[path_index] ||
918 (current_path = extract_colon_unit (path, &path_index)) == 0)
919 return ((char *)NULL);
920
921 if (*current_path == 0)
922 {
923 free (current_path);
924 current_path = savestring (".");
925 }
926
927 if (*current_path == '~')
928 {
929 char *t;
930
931 t = bash_tilde_expand (current_path);
932 free (current_path);
933 current_path = t;
934 }
935
936 if (filename_hint)
937 free (filename_hint);
938
939 filename_hint = xmalloc (2 + strlen (current_path) + hint_len);
940 sprintf (filename_hint, "%s/%s", current_path, hint);
941
942 free (current_path);
943 }
944
945 inner:
946 val = filename_completion_function (filename_hint, istate);
947 istate = 1;
948
949 if (val == 0)
950 {
951 /* If the hint text is an absolute program, then don't bother
952 searching through PATH. */
953 if (absolute_program (hint))
954 return ((char *)NULL);
955
956 goto outer;
957 }
958 else
959 {
960 int match, freetemp;
961 char *temp;
962
963 if (absolute_program (hint))
964 {
965 match = strncmp (val, hint, hint_len) == 0;
966 /* If we performed tilde expansion, restore the original
967 filename. */
968 if (*hint_text == '~')
969 {
970 int l, tl, vl;
971 vl = strlen (val);
972 tl = strlen (hint_text);
973 l = vl - hint_len; /* # of chars added */
974 temp = xmalloc (l + 2 + tl);
975 strcpy (temp, hint_text);
976 strcpy (temp + tl, val + vl - l);
977 }
978 else
979 temp = savestring (val);
980 freetemp = 1;
981 }
982 else
983 {
984 temp = strrchr (val, '/');
985
986 if (temp)
987 {
988 temp++;
989 freetemp = match = strncmp (temp, hint, hint_len) == 0;
990 if (match)
991 temp = savestring (temp);
992 }
993 else
994 freetemp = match = 0;
995 }
996
997 /* If we have found a match, and it is an executable file or a
998 directory name, return it. */
999 if (match && (executable_file (val) || is_directory (val)))
1000 {
1001 free (val);
1002 val = ""; /* So it won't be NULL. */
1003 return (temp);
1004 }
1005 else
1006 {
1007 if (freetemp)
1008 free (temp);
1009 free (val);
1010 goto inner;
1011 }
1012 }
1013 }
1014
1015 /* Completion inside an unterminated command substitution. */
1016 static char *
1017 command_subst_completion_function (text, state)
1018 char *text;
1019 int state;
1020 {
1021 static char **matches = (char **)NULL;
1022 static char *orig_start, *filename_text = (char *)NULL;
1023 static int cmd_index, start_len;
1024 char *value;
1025
1026 if (state == 0)
1027 {
1028 if (filename_text)
1029 free (filename_text);
1030 orig_start = text;
1031 if (*text == '`')
1032 text++;
1033 else if (*text == '$' && text[1] == '(')
1034 text += 2;
1035 start_len = text - orig_start;
1036 filename_text = savestring (text);
1037 if (matches)
1038 free (matches);
1039 matches = completion_matches (filename_text, command_word_completion_function);
1040 cmd_index = 0;
1041 }
1042
1043 if (!matches || !matches[cmd_index])
1044 {
1045 rl_filename_quoting_desired = 0; /* disable quoting */
1046 return ((char *)NULL);
1047 }
1048 else
1049 {
1050 value = xmalloc (1 + start_len + strlen (matches[cmd_index]));
1051
1052 if (start_len == 1)
1053 value[0] = *orig_start;
1054 else
1055 strncpy (value, orig_start, start_len);
1056
1057 strcpy (value + start_len, matches[cmd_index]);
1058
1059 cmd_index++;
1060 return (value);
1061 }
1062 }
1063
1064 /* Okay, now we write the entry_function for variable completion. */
1065 static char *
1066 variable_completion_function (text, state)
1067 int state;
1068 char *text;
1069 {
1070 register SHELL_VAR *var = (SHELL_VAR *)NULL;
1071 static SHELL_VAR **varlist = (SHELL_VAR **)NULL;
1072 static int varlist_index;
1073 static char *varname = (char *)NULL;
1074 static int namelen;
1075 static int first_char, first_char_loc;
1076
1077 if (!state)
1078 {
1079 if (varname)
1080 free (varname);
1081
1082 first_char_loc = 0;
1083 first_char = text[0];
1084
1085 if (first_char == '$')
1086 first_char_loc++;
1087
1088 if (text[first_char_loc] == '{')
1089 first_char_loc++;
1090
1091 varname = savestring (text + first_char_loc);
1092
1093 namelen = strlen (varname);
1094 if (varlist)
1095 free (varlist);
1096 varlist = all_visible_variables ();
1097 varlist_index = 0;
1098 }
1099
1100 while (varlist && varlist[varlist_index])
1101 {
1102 var = varlist[varlist_index];
1103
1104 /* Compare. You can't do better than Zayre. No text is also
1105 a match. */
1106 if (!*varname || (strncmp (varname, var->name, namelen) == 0))
1107 break;
1108 varlist_index++;
1109 }
1110
1111 if (!varlist || !varlist[varlist_index])
1112 {
1113 return ((char *)NULL);
1114 }
1115 else
1116 {
1117 char *value = xmalloc (4 + strlen (var->name));
1118
1119 if (first_char_loc)
1120 {
1121 value[0] = first_char;
1122 if (first_char_loc == 2)
1123 value[1] = '{';
1124 }
1125
1126 strcpy (&value[first_char_loc], var->name);
1127 if (first_char_loc == 2)
1128 strcat (value, "}");
1129
1130 varlist_index++;
1131 return (value);
1132 }
1133 }
1134
1135 /* How about a completion function for hostnames? */
1136 static char *
1137 hostname_completion_function (text, state)
1138 int state;
1139 char *text;
1140 {
1141 static char **list = (char **)NULL;
1142 static int list_index = 0;
1143 static int first_char, first_char_loc;
1144
1145 /* If we don't have any state, make some. */
1146 if (state == 0)
1147 {
1148 FREE (list);
1149
1150 list = (char **)NULL;
1151
1152 first_char_loc = 0;
1153 first_char = *text;
1154
1155 if (first_char == '@')
1156 first_char_loc++;
1157
1158 list = hostnames_matching (&text[first_char_loc]);
1159 list_index = 0;
1160 }
1161
1162 if (list && list[list_index])
1163 {
1164 char *t;
1165
1166 t = xmalloc (2 + strlen (list[list_index]));
1167 *t = first_char;
1168 strcpy (t + first_char_loc, list[list_index]);
1169 list_index++;
1170 return (t);
1171 }
1172
1173 return ((char *)NULL);
1174 }
1175
1176 /* History and alias expand the line. */
1177 static char *
1178 history_expand_line_internal (line)
1179 char *line;
1180 {
1181 char *new_line;
1182
1183 new_line = pre_process_line (line, 0, 0);
1184 return (new_line == line) ? savestring (line) : new_line;
1185 }
1186
1187 #if defined (ALIAS)
1188 /* Expand aliases in the current readline line. */
1189 static void
1190 alias_expand_line (ignore)
1191 int ignore;
1192 {
1193 char *new_line;
1194
1195 new_line = alias_expand (rl_line_buffer);
1196
1197 if (new_line)
1198 set_up_new_line (new_line);
1199 else
1200 cleanup_expansion_error ();
1201 }
1202 #endif
1203
1204 /* There was an error in expansion. Let the preprocessor print
1205 the error here. */
1206 static void
1207 cleanup_expansion_error ()
1208 {
1209 char *to_free;
1210
1211 fprintf (rl_outstream, "\r\n");
1212 to_free = pre_process_line (rl_line_buffer, 1, 0);
1213 if (to_free != rl_line_buffer)
1214 free (to_free);
1215 putc ('\r', rl_outstream);
1216 rl_forced_update_display ();
1217 }
1218
1219 /* If NEW_LINE differs from what is in the readline line buffer, add an
1220 undo record to get from the readline line buffer contents to the new
1221 line and make NEW_LINE the current readline line. */
1222 static void
1223 maybe_make_readline_line (new_line)
1224 char *new_line;
1225 {
1226 if (strcmp (new_line, rl_line_buffer) != 0)
1227 {
1228 rl_point = rl_end;
1229
1230 rl_add_undo (UNDO_BEGIN, 0, 0, 0);
1231 rl_delete_text (0, rl_point);
1232 rl_point = rl_end = 0;
1233 rl_insert_text (new_line);
1234 rl_add_undo (UNDO_END, 0, 0, 0);
1235 }
1236 }
1237
1238 /* Make NEW_LINE be the current readline line. This frees NEW_LINE. */
1239 static void
1240 set_up_new_line (new_line)
1241 char *new_line;
1242 {
1243 int old_point = rl_point;
1244 int at_end = rl_point == rl_end;
1245
1246 /* If the line was history and alias expanded, then make that
1247 be one thing to undo. */
1248 maybe_make_readline_line (new_line);
1249 free (new_line);
1250
1251 /* Place rl_point where we think it should go. */
1252 if (at_end)
1253 rl_point = rl_end;
1254 else if (old_point < rl_end)
1255 {
1256 rl_point = old_point;
1257 if (!whitespace (rl_line_buffer[rl_point]))
1258 rl_forward_word (1);
1259 }
1260 }
1261
1262 /* History expand the line. */
1263 static void
1264 history_expand_line (ignore)
1265 int ignore;
1266 {
1267 char *new_line;
1268
1269 new_line = history_expand_line_internal (rl_line_buffer);
1270
1271 if (new_line)
1272 set_up_new_line (new_line);
1273 else
1274 cleanup_expansion_error ();
1275 }
1276
1277 /* History and alias expand the line. */
1278 static void
1279 history_and_alias_expand_line (ignore)
1280 int ignore;
1281 {
1282 char *new_line;
1283
1284 new_line = pre_process_line (rl_line_buffer, 0, 0);
1285 if (new_line == rl_line_buffer)
1286 new_line = savestring (new_line);
1287
1288 #if defined (ALIAS)
1289 if (new_line)
1290 {
1291 char *alias_line;
1292
1293 alias_line = alias_expand (new_line);
1294 free (new_line);
1295 new_line = alias_line;
1296 }
1297 #endif /* ALIAS */
1298
1299 if (new_line)
1300 set_up_new_line (new_line);
1301 else
1302 cleanup_expansion_error ();
1303 }
1304
1305 /* History and alias expand the line, then perform the shell word
1306 expansions by calling expand_string. */
1307 static void
1308 shell_expand_line (ignore)
1309 int ignore;
1310 {
1311 char *new_line;
1312 WORD_LIST *expanded_string;
1313
1314 new_line = pre_process_line (rl_line_buffer, 0, 0);
1315 if (new_line == rl_line_buffer)
1316 new_line = savestring (new_line);
1317
1318 #if defined (ALIAS)
1319 if (new_line)
1320 {
1321 char *alias_line;
1322
1323 alias_line = alias_expand (new_line);
1324 free (new_line);
1325 new_line = alias_line;
1326 }
1327 #endif /* ALIAS */
1328
1329 if (new_line)
1330 {
1331 int old_point = rl_point;
1332 int at_end = rl_point == rl_end;
1333
1334 /* If the line was history and alias expanded, then make that
1335 be one thing to undo. */
1336 maybe_make_readline_line (new_line);
1337 free (new_line);
1338
1339 /* If there is variable expansion to perform, do that as a separate
1340 operation to be undone. */
1341 new_line = savestring (rl_line_buffer);
1342 expanded_string = expand_string (new_line, 0);
1343 FREE (new_line);
1344 if (expanded_string == 0)
1345 {
1346 new_line = xmalloc (1);
1347 new_line[0] = '\0';
1348 }
1349 else
1350 {
1351 new_line = string_list (expanded_string);
1352 dispose_words (expanded_string);
1353 }
1354
1355 maybe_make_readline_line (new_line);
1356 free (new_line);
1357
1358 /* Place rl_point where we think it should go. */
1359 if (at_end)
1360 rl_point = rl_end;
1361 else if (old_point < rl_end)
1362 {
1363 rl_point = old_point;
1364 if (!whitespace (rl_line_buffer[rl_point]))
1365 rl_forward_word (1);
1366 }
1367 }
1368 else
1369 cleanup_expansion_error ();
1370 }
1371
1372 /* If FIGNORE is set, then don't match files with the given suffixes when
1373 completing filenames. If only one of the possibilities has an acceptable
1374 suffix, delete the others, else just return and let the completer
1375 signal an error. It is called by the completer when real
1376 completions are done on filenames by the completer's internal
1377 function, not for completion lists (M-?) and not on "other"
1378 completion types, such as hostnames or commands. */
1379
1380 static struct ignorevar fignore =
1381 {
1382 "FIGNORE",
1383 (struct ign *)0,
1384 0,
1385 (char *)0,
1386 (Function *) 0,
1387 };
1388
1389 static void
1390 _ignore_completion_names (names, name_func)
1391 char **names;
1392 Function *name_func;
1393 {
1394 char **newnames;
1395 int idx, nidx;
1396
1397 /* If there is only one completion, see if it is acceptable. If it is
1398 not, free it up. In any case, short-circuit and return. This is a
1399 special case because names[0] is not the prefix of the list of names
1400 if there is only one completion; it is the completion itself. */
1401 if (names[1] == (char *)0)
1402 {
1403 if ((*name_func) (names[0]) == 0)
1404 {
1405 free (names[0]);
1406 names[0] = (char *)NULL;
1407 }
1408 return;
1409 }
1410
1411 /* Allocate space for array to hold list of pointers to matching
1412 filenames. The pointers are copied back to NAMES when done. */
1413 for (nidx = 1; names[nidx]; nidx++)
1414 ;
1415 newnames = (char **)xmalloc ((nidx + 1) * (sizeof (char *)));
1416
1417 newnames[0] = names[0];
1418 for (idx = nidx = 1; names[idx]; idx++)
1419 {
1420 if ((*name_func) (names[idx]))
1421 newnames[nidx++] = names[idx];
1422 else
1423 free (names[idx]);
1424 }
1425
1426 newnames[nidx] = (char *)NULL;
1427
1428 /* If none are acceptable then let the completer handle it. */
1429 if (nidx == 1)
1430 {
1431 free (names[0]);
1432 names[0] = (char *)NULL;
1433 free (newnames);
1434 return;
1435 }
1436
1437 /* If only one is acceptable, copy it to names[0] and return. */
1438 if (nidx == 2)
1439 {
1440 free (names[0]);
1441 names[0] = newnames[1];
1442 names[1] = (char *)NULL;
1443 free (newnames);
1444 return;
1445 }
1446
1447 /* Copy the acceptable names back to NAMES, set the new array end,
1448 and return. */
1449 for (nidx = 1; newnames[nidx]; nidx++)
1450 names[nidx] = newnames[nidx];
1451 names[nidx] = (char *)NULL;
1452 free (newnames);
1453 }
1454
1455 static int
1456 name_is_acceptable (name)
1457 char *name;
1458 {
1459 struct ign *p;
1460 int nlen;
1461
1462 for (nlen = strlen (name), p = fignore.ignores; p->val; p++)
1463 {
1464 if (nlen > p->len && p->len > 0 && STREQ (p->val, &name[nlen - p->len]))
1465 return (0);
1466 }
1467
1468 return (1);
1469 }
1470
1471 static void
1472 filename_completion_ignore (names)
1473 char **names;
1474 {
1475 setup_ignore_patterns (&fignore);
1476
1477 if (fignore.num_ignores == 0)
1478 return;
1479
1480 _ignore_completion_names (names, name_is_acceptable);
1481 }
1482
1483 /* Return 1 if NAME is a directory. */
1484 static int
1485 test_for_directory (name)
1486 char *name;
1487 {
1488 struct stat finfo;
1489 char *fn;
1490
1491 fn = bash_tilde_expand (name);
1492 if (stat (fn, &finfo) != 0)
1493 {
1494 free (fn);
1495 return 0;
1496 }
1497 free (fn);
1498 return (S_ISDIR (finfo.st_mode));
1499 }
1500
1501 /* Remove files from NAMES, leaving directories. */
1502 static void
1503 bash_ignore_filenames (names)
1504 char **names;
1505 {
1506 _ignore_completion_names (names, test_for_directory);
1507 }
1508
1509 /* Handle symbolic link references and other directory name
1510 expansions while hacking completion. */
1511 static int
1512 bash_directory_completion_hook (dirname)
1513 char **dirname;
1514 {
1515 char *local_dirname, *t;
1516 int return_value = 0;
1517 WORD_LIST *wl;
1518
1519 local_dirname = *dirname;
1520 if (strchr (local_dirname, '$') || strchr (local_dirname, '`'))
1521 {
1522 wl = expand_string (local_dirname, 0);
1523 if (wl)
1524 {
1525 *dirname = string_list (wl);
1526 /* Tell the completer to replace the directory name only if we
1527 actually expanded something. */
1528 return_value = STREQ (local_dirname, *dirname) == 0;
1529 free (local_dirname);
1530 dispose_words (wl);
1531 local_dirname = *dirname;
1532 }
1533 else
1534 {
1535 free (local_dirname);
1536 *dirname = xmalloc (1);
1537 **dirname = '\0';
1538 return 1;
1539 }
1540 }
1541
1542 if (!no_symbolic_links && (local_dirname[0] != '.' || local_dirname[1]))
1543 {
1544 char *temp1, *temp2;
1545 int len1, len2;
1546
1547 t = get_working_directory ("symlink-hook");
1548 temp1 = make_absolute (local_dirname, t);
1549 free (t);
1550 temp2 = canonicalize_pathname (temp1);
1551 /* If we can't canonicalize, bail. */
1552 if (temp2 == 0)
1553 {
1554 free (temp1);
1555 return 1;
1556 }
1557 len1 = strlen (temp1);
1558 if (temp1[len1 - 1] == '/')
1559 {
1560 len2 = strlen (temp2);
1561 temp2 = xrealloc (temp2, len2 + 2);
1562 temp2[len2] = '/';
1563 temp2[len2 + 1] = '\0';
1564 }
1565 free (local_dirname);
1566 *dirname = temp2;
1567 free (temp1);
1568 }
1569 return (return_value);
1570 }
1571
1572 static char **history_completion_array = (char **)NULL;
1573 static int harry_size;
1574 static int harry_len;
1575
1576 static void
1577 build_history_completion_array ()
1578 {
1579 register int i, j;
1580 HIST_ENTRY **hlist;
1581 char **tokens;
1582
1583 /* First, clear out the current dynamic history completion list. */
1584 if (harry_size)
1585 {
1586 for (i = 0; history_completion_array[i]; i++)
1587 free (history_completion_array[i]);
1588
1589 free (history_completion_array);
1590
1591 history_completion_array = (char **)NULL;
1592 harry_size = 0;
1593 harry_len = 0;
1594 }
1595
1596 /* Next, grovel each line of history, making each shell-sized token
1597 a separate entry in the history_completion_array. */
1598 hlist = history_list ();
1599
1600 if (hlist)
1601 {
1602 for (i = 0; hlist[i]; i++)
1603 {
1604 /* Separate each token, and place into an array. */
1605 tokens = history_tokenize (hlist[i]->line);
1606
1607 for (j = 0; tokens && tokens[j]; j++)
1608 {
1609 if (harry_len + 2 > harry_size)
1610 {
1611 harry_size += 10;
1612 history_completion_array = (char **) xrealloc
1613 (history_completion_array, harry_size * sizeof (char *));
1614 }
1615
1616 history_completion_array[harry_len++] = tokens[j];
1617 history_completion_array[harry_len] = (char *)NULL;
1618 }
1619 free (tokens);
1620 }
1621
1622 /* Sort the complete list of tokens. */
1623 qsort (history_completion_array, harry_len, sizeof (char *), (Function *)qsort_string_compare);
1624 }
1625 }
1626
1627 static char *
1628 history_completion_generator (hint_text, state)
1629 char *hint_text;
1630 int state;
1631 {
1632 static int local_index, len;
1633 static char *text;
1634
1635 /* If this is the first call to the generator, then initialize the
1636 list of strings to complete over. */
1637 if (state == 0)
1638 {
1639 local_index = 0;
1640 build_history_completion_array ();
1641 text = hint_text;
1642 len = strlen (text);
1643 }
1644
1645 while (history_completion_array && history_completion_array[local_index])
1646 {
1647 if (strncmp (text, history_completion_array[local_index++], len) == 0)
1648 return (savestring (history_completion_array[local_index - 1]));
1649 }
1650 return ((char *)NULL);
1651 }
1652
1653 static void
1654 dynamic_complete_history (count, key)
1655 int count, key;
1656 {
1657 Function *orig_func;
1658 CPPFunction *orig_attempt_func;
1659
1660 orig_func = rl_completion_entry_function;
1661 orig_attempt_func = rl_attempted_completion_function;
1662 rl_completion_entry_function = (Function *)history_completion_generator;
1663 rl_attempted_completion_function = (CPPFunction *)NULL;
1664
1665 if (rl_last_func == (Function *)dynamic_complete_history)
1666 rl_complete_internal ('?');
1667 else
1668 rl_complete_internal (TAB);
1669
1670 rl_completion_entry_function = orig_func;
1671 rl_attempted_completion_function = orig_attempt_func;
1672 }
1673
1674 #if defined (SPECIFIC_COMPLETION_FUNCTIONS)
1675 static void
1676 bash_complete_username (ignore, ignore2)
1677 int ignore, ignore2;
1678 {
1679 bash_complete_username_internal (TAB);
1680 }
1681
1682 static void
1683 bash_possible_username_completions (ignore, ignore2)
1684 int ignore, ignore2;
1685 {
1686 bash_complete_username_internal ('?');
1687 }
1688
1689 static void
1690 bash_complete_username_internal (what_to_do)
1691 int what_to_do;
1692 {
1693 bash_specific_completion
1694 (what_to_do, (Function *)username_completion_function);
1695 }
1696
1697 static void
1698 bash_complete_filename (ignore, ignore2)
1699 int ignore, ignore2;
1700 {
1701 bash_complete_filename_internal (TAB);
1702 }
1703
1704 static void
1705 bash_possible_filename_completions (ignore, ignore2)
1706 int ignore, ignore2;
1707 {
1708 bash_complete_filename_internal ('?');
1709 }
1710
1711 static void
1712 bash_complete_filename_internal (what_to_do)
1713 int what_to_do;
1714 {
1715 Function *orig_func, *orig_dir_func;
1716 CPPFunction *orig_attempt_func;
1717 char *orig_rl_completer_word_break_characters;
1718
1719 orig_func = rl_completion_entry_function;
1720 orig_attempt_func = rl_attempted_completion_function;
1721 orig_dir_func = rl_directory_completion_hook;
1722 orig_rl_completer_word_break_characters = rl_completer_word_break_characters;
1723 rl_completion_entry_function = (Function *)filename_completion_function;
1724 rl_attempted_completion_function = (CPPFunction *)NULL;
1725 rl_directory_completion_hook = (Function *)NULL;
1726 rl_completer_word_break_characters = " \t\n\"\'";
1727
1728 rl_complete_internal (what_to_do);
1729
1730 rl_completion_entry_function = orig_func;
1731 rl_attempted_completion_function = orig_attempt_func;
1732 rl_directory_completion_hook = orig_dir_func;
1733 rl_completer_word_break_characters = orig_rl_completer_word_break_characters;
1734 }
1735
1736 static void
1737 bash_complete_hostname (ignore, ignore2)
1738 int ignore, ignore2;
1739 {
1740 bash_complete_hostname_internal (TAB);
1741 }
1742
1743 static void
1744 bash_possible_hostname_completions (ignore, ignore2)
1745 int ignore, ignore2;
1746 {
1747 bash_complete_hostname_internal ('?');
1748 }
1749
1750 static void
1751 bash_complete_variable (ignore, ignore2)
1752 int ignore, ignore2;
1753 {
1754 bash_complete_variable_internal (TAB);
1755 }
1756
1757 static void
1758 bash_possible_variable_completions (ignore, ignore2)
1759 int ignore, ignore2;
1760 {
1761 bash_complete_variable_internal ('?');
1762 }
1763
1764 static void
1765 bash_complete_command (ignore, ignore2)
1766 int ignore, ignore2;
1767 {
1768 bash_complete_command_internal (TAB);
1769 }
1770
1771 static void
1772 bash_possible_command_completions (ignore, ignore2)
1773 int ignore, ignore2;
1774 {
1775 bash_complete_command_internal ('?');
1776 }
1777
1778 static void
1779 bash_complete_hostname_internal (what_to_do)
1780 int what_to_do;
1781 {
1782 bash_specific_completion
1783 (what_to_do, (Function *)hostname_completion_function);
1784 }
1785
1786 static void
1787 bash_complete_variable_internal (what_to_do)
1788 int what_to_do;
1789 {
1790 bash_specific_completion
1791 (what_to_do, (Function *)variable_completion_function);
1792 }
1793
1794 static void
1795 bash_complete_command_internal (what_to_do)
1796 int what_to_do;
1797 {
1798 bash_specific_completion
1799 (what_to_do, (Function *)command_word_completion_function);
1800 }
1801
1802 static char *
1803 glob_complete_word (text, state)
1804 char *text;
1805 int state;
1806 {
1807 static char **matches = (char **)NULL;
1808 static int ind;
1809 char *ret;
1810
1811 if (state == 0)
1812 {
1813 rl_filename_completion_desired = 1;
1814 if (matches)
1815 free (matches);
1816 matches = shell_glob_filename (text);
1817 if (GLOB_FAILED (matches))
1818 matches = (char **)NULL;
1819 ind = 0;
1820 }
1821
1822 ret = matches ? matches[ind] : (char *)NULL;
1823 ind++;
1824 return ret;
1825 }
1826
1827 static void
1828 bash_glob_completion_internal (what_to_do)
1829 int what_to_do;
1830 {
1831 bash_specific_completion (what_to_do, (Function *)glob_complete_word);
1832 }
1833
1834 static void
1835 bash_glob_expand_word (count, key)
1836 int count, key;
1837 {
1838 bash_glob_completion_internal ('*');
1839 }
1840
1841 static void
1842 bash_glob_list_expansions (count, key)
1843 int count, key;
1844 {
1845 bash_glob_completion_internal ('?');
1846 }
1847
1848 static void
1849 bash_specific_completion (what_to_do, generator)
1850 int what_to_do;
1851 Function *generator;
1852 {
1853 Function *orig_func;
1854 CPPFunction *orig_attempt_func;
1855
1856 orig_func = rl_completion_entry_function;
1857 orig_attempt_func = rl_attempted_completion_function;
1858 rl_completion_entry_function = generator;
1859 rl_attempted_completion_function = (CPPFunction *)NULL;
1860
1861 rl_complete_internal (what_to_do);
1862
1863 rl_completion_entry_function = orig_func;
1864 rl_attempted_completion_function = orig_attempt_func;
1865 }
1866
1867 #endif /* SPECIFIC_COMPLETION_FUNCTIONS */
1868
1869 /* Filename quoting for completion. */
1870 /* A function to strip quotes that are not protected by backquotes. It
1871 allows single quotes to appear within double quotes, and vice versa.
1872 It should be smarter. */
1873 static char *
1874 bash_dequote_filename (text, quote_char)
1875 char *text;
1876 {
1877 char *ret, *p, *r;
1878 int l, quoted;
1879
1880 l = strlen (text);
1881 ret = xmalloc (l + 1);
1882 for (quoted = quote_char, p = text, r = ret; p && *p; p++)
1883 {
1884 /* Allow backslash-quoted characters to pass through unscathed. */
1885 if (*p == '\\')
1886 {
1887 *r++ = *++p;
1888 if (*p == '\0')
1889 break;
1890 continue;
1891 }
1892 /* Close quote. */
1893 if (quoted && *p == quoted)
1894 {
1895 quoted = 0;
1896 continue;
1897 }
1898 /* Open quote. */
1899 if (quoted == 0 && (*p == '\'' || *p == '"'))
1900 {
1901 quoted = *p;
1902 continue;
1903 }
1904 *r++ = *p;
1905 }
1906 *r = '\0';
1907 return ret;
1908 }
1909
1910 /* Quote characters that the readline completion code would treat as
1911 word break characters with backslashes. Pass backslash-quoted
1912 characters through without examination. */
1913 static char *
1914 quote_word_break_chars (text)
1915 char *text;
1916 {
1917 char *ret, *r, *s;
1918 int l;
1919
1920 l = strlen (text);
1921 ret = xmalloc ((2 * l) + 1);
1922 for (s = text, r = ret; *s; s++)
1923 {
1924 /* Pass backslash-quoted characters through, including the backslash. */
1925 if (*s == '\\')
1926 {
1927 *r++ = '\\';
1928 *r++ = *++s;
1929 if (*s == '\0')
1930 break;
1931 continue;
1932 }
1933 /* OK, we have an unquoted character. Check its presence in
1934 rl_completer_word_break_characters. */
1935 if (strchr (rl_completer_word_break_characters, *s))
1936 *r++ = '\\';
1937 *r++ = *s;
1938 }
1939 *r = '\0';
1940 return ret;
1941 }
1942
1943 /* Quote a filename using double quotes, single quotes, or backslashes
1944 depending on the value of completion_quoting_style. If we're
1945 completing using backslashes, we need to quote some additional
1946 characters (those that readline treats as word breaks), so we call
1947 quote_word_break_chars on the result. */
1948 static char *
1949 bash_quote_filename (s, rtype, qcp)
1950 char *s;
1951 int rtype;
1952 char *qcp;
1953 {
1954 char *rtext, *mtext, *ret;
1955 int rlen, cs;
1956
1957 rtext = (char *)NULL;
1958
1959 /* If RTYPE == MULT_MATCH, it means that there is
1960 more than one match. In this case, we do not add
1961 the closing quote or attempt to perform tilde
1962 expansion. If RTYPE == SINGLE_MATCH, we try
1963 to perform tilde expansion, because single and double
1964 quotes inhibit tilde expansion by the shell. */
1965
1966 mtext = s;
1967 if (mtext[0] == '~' && rtype == SINGLE_MATCH)
1968 mtext = bash_tilde_expand (s);
1969
1970 cs = completion_quoting_style;
1971 /* Might need to modify the default completion style based on *qcp,
1972 since it's set to any user-provided opening quote. */
1973 if (*qcp == '"')
1974 cs = COMPLETE_DQUOTE;
1975 else if (*qcp == '\'')
1976 cs = COMPLETE_SQUOTE;
1977 #if defined (BANG_HISTORY)
1978 else if (*qcp == '\0' && history_expansion && cs == COMPLETE_DQUOTE &&
1979 history_expansion_inhibited == 0 && strchr (mtext, '!'))
1980 cs = COMPLETE_BSQUOTE;
1981
1982 if (*qcp == '"' && history_expansion && cs == COMPLETE_DQUOTE &&
1983 history_expansion_inhibited == 0 && strchr (mtext, '!'))
1984 {
1985 cs = COMPLETE_BSQUOTE;
1986 *qcp = '\0';
1987 }
1988 #endif
1989
1990 switch (cs)
1991 {
1992 case COMPLETE_DQUOTE:
1993 rtext = double_quote (mtext);
1994 break;
1995 case COMPLETE_SQUOTE:
1996 rtext = single_quote (mtext);
1997 break;
1998 case COMPLETE_BSQUOTE:
1999 rtext = backslash_quote (mtext);
2000 break;
2001 }
2002
2003 if (mtext != s)
2004 free (mtext);
2005
2006 /* We may need to quote additional characters: those that readline treats
2007 as word breaks that are not quoted by backslash_quote. */
2008 if (rtext && cs == COMPLETE_BSQUOTE)
2009 {
2010 mtext = quote_word_break_chars (rtext);
2011 free (rtext);
2012 rtext = mtext;
2013 }
2014
2015 /* Leave the opening quote intact. The readline completion code takes
2016 care of avoiding doubled opening quotes. */
2017 rlen = strlen (rtext);
2018 ret = xmalloc (rlen + 1);
2019 strcpy (ret, rtext);
2020
2021 /* If there are multiple matches, cut off the closing quote. */
2022 if (rtype == MULT_MATCH && cs != COMPLETE_BSQUOTE)
2023 ret[rlen - 1] = '\0';
2024 free (rtext);
2025 return ret;
2026 }
2027
2028 #endif /* READLINE */