f68b5fa858e45ff2681877528312e728deb53b5e
[platform/upstream/bash.git] / lib / readline / bind.c
1 /* bind.c -- key binding and startup file support for the readline library. */
2
3 /* Copyright (C) 1987-2009 Free Software Foundation, Inc.
4
5    This file is part of the GNU Readline Library (Readline), a library
6    for reading lines of text with interactive input and history editing.
7
8    Readline is free software: you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation, either version 3 of the License, or
11    (at your option) any later version.
12
13    Readline is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with Readline.  If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 #define READLINE_LIBRARY
23
24 #if defined (__TANDEM)
25 #  include <floss.h>
26 #endif
27
28 #if defined (HAVE_CONFIG_H)
29 #  include <config.h>
30 #endif
31
32 #include <stdio.h>
33 #include <sys/types.h>
34 #include <fcntl.h>
35 #if defined (HAVE_SYS_FILE_H)
36 #  include <sys/file.h>
37 #endif /* HAVE_SYS_FILE_H */
38
39 #if defined (HAVE_UNISTD_H)
40 #  include <unistd.h>
41 #endif /* HAVE_UNISTD_H */
42
43 #if defined (HAVE_STDLIB_H)
44 #  include <stdlib.h>
45 #else
46 #  include "ansi_stdlib.h"
47 #endif /* HAVE_STDLIB_H */
48
49 #include <errno.h>
50
51 #if !defined (errno)
52 extern int errno;
53 #endif /* !errno */
54
55 #include "posixstat.h"
56
57 /* System-specific feature definitions and include files. */
58 #include "rldefs.h"
59
60 /* Some standard library routines. */
61 #include "readline.h"
62 #include "history.h"
63
64 #include "rlprivate.h"
65 #include "rlshell.h"
66 #include "xmalloc.h"
67
68 #if !defined (strchr) && !defined (__STDC__)
69 extern char *strchr (), *strrchr ();
70 #endif /* !strchr && !__STDC__ */
71
72 /* Variables exported by this file. */
73 Keymap rl_binding_keymap;
74
75 static char *_rl_read_file PARAMS((char *, size_t *));
76 static void _rl_init_file_error PARAMS((const char *));
77 static int _rl_read_init_file PARAMS((const char *, int));
78 static int glean_key_from_name PARAMS((char *));
79 static int find_boolean_var PARAMS((const char *));
80
81 static char *_rl_get_string_variable_value PARAMS((const char *));
82 static int substring_member_of_array PARAMS((const char *, const char * const *));
83
84 static int currently_reading_init_file;
85
86 /* used only in this file */
87 static int _rl_prefer_visible_bell = 1;
88
89 /* **************************************************************** */
90 /*                                                                  */
91 /*                      Binding keys                                */
92 /*                                                                  */
93 /* **************************************************************** */
94
95 /* rl_add_defun (char *name, rl_command_func_t *function, int key)
96    Add NAME to the list of named functions.  Make FUNCTION be the function
97    that gets called.  If KEY is not -1, then bind it. */
98 int
99 rl_add_defun (name, function, key)
100      const char *name;
101      rl_command_func_t *function;
102      int key;
103 {
104   if (key != -1)
105     rl_bind_key (key, function);
106   rl_add_funmap_entry (name, function);
107   return 0;
108 }
109
110 /* Bind KEY to FUNCTION.  Returns non-zero if KEY is out of range. */
111 int
112 rl_bind_key (key, function)
113      int key;
114      rl_command_func_t *function;
115 {
116   if (key < 0)
117     return (key);
118
119   if (META_CHAR (key) && _rl_convert_meta_chars_to_ascii)
120     {
121       if (_rl_keymap[ESC].type == ISKMAP)
122         {
123           Keymap escmap;
124
125           escmap = FUNCTION_TO_KEYMAP (_rl_keymap, ESC);
126           key = UNMETA (key);
127           escmap[key].type = ISFUNC;
128           escmap[key].function = function;
129           return (0);
130         }
131       return (key);
132     }
133
134   _rl_keymap[key].type = ISFUNC;
135   _rl_keymap[key].function = function;
136   rl_binding_keymap = _rl_keymap;
137   return (0);
138 }
139
140 /* Bind KEY to FUNCTION in MAP.  Returns non-zero in case of invalid
141    KEY. */
142 int
143 rl_bind_key_in_map (key, function, map)
144      int key;
145      rl_command_func_t *function;
146      Keymap map;
147 {
148   int result;
149   Keymap oldmap;
150
151   oldmap = _rl_keymap;
152   _rl_keymap = map;
153   result = rl_bind_key (key, function);
154   _rl_keymap = oldmap;
155   return (result);
156 }
157
158 /* Bind key sequence KEYSEQ to DEFAULT_FUNC if KEYSEQ is unbound.  Right
159    now, this is always used to attempt to bind the arrow keys, hence the
160    check for rl_vi_movement_mode. */
161 int
162 rl_bind_key_if_unbound_in_map (key, default_func, kmap)
163      int key;
164      rl_command_func_t *default_func;
165      Keymap kmap;
166 {
167   char keyseq[2];
168
169   keyseq[0] = (unsigned char)key;
170   keyseq[1] = '\0';
171   return (rl_bind_keyseq_if_unbound_in_map (keyseq, default_func, kmap));
172 }
173
174 int
175 rl_bind_key_if_unbound (key, default_func)
176      int key;
177      rl_command_func_t *default_func;
178 {
179   char keyseq[2];
180
181   keyseq[0] = (unsigned char)key;
182   keyseq[1] = '\0';
183   return (rl_bind_keyseq_if_unbound_in_map (keyseq, default_func, _rl_keymap));
184 }
185
186 /* Make KEY do nothing in the currently selected keymap.
187    Returns non-zero in case of error. */
188 int
189 rl_unbind_key (key)
190      int key;
191 {
192   return (rl_bind_key (key, (rl_command_func_t *)NULL));
193 }
194
195 /* Make KEY do nothing in MAP.
196    Returns non-zero in case of error. */
197 int
198 rl_unbind_key_in_map (key, map)
199      int key;
200      Keymap map;
201 {
202   return (rl_bind_key_in_map (key, (rl_command_func_t *)NULL, map));
203 }
204
205 /* Unbind all keys bound to FUNCTION in MAP. */
206 int
207 rl_unbind_function_in_map (func, map)
208      rl_command_func_t *func;
209      Keymap map;
210 {
211   register int i, rval;
212
213   for (i = rval = 0; i < KEYMAP_SIZE; i++)
214     {
215       if (map[i].type == ISFUNC && map[i].function == func)
216         {
217           map[i].function = (rl_command_func_t *)NULL;
218           rval = 1;
219         }
220     }
221   return rval;
222 }
223
224 int
225 rl_unbind_command_in_map (command, map)
226      const char *command;
227      Keymap map;
228 {
229   rl_command_func_t *func;
230
231   func = rl_named_function (command);
232   if (func == 0)
233     return 0;
234   return (rl_unbind_function_in_map (func, map));
235 }
236
237 /* Bind the key sequence represented by the string KEYSEQ to
238    FUNCTION, starting in the current keymap.  This makes new
239    keymaps as necessary. */
240 int
241 rl_bind_keyseq (keyseq, function)
242      const char *keyseq;
243      rl_command_func_t *function;
244 {
245   return (rl_generic_bind (ISFUNC, keyseq, (char *)function, _rl_keymap));
246 }
247
248 /* Bind the key sequence represented by the string KEYSEQ to
249    FUNCTION.  This makes new keymaps as necessary.  The initial
250    place to do bindings is in MAP. */
251 int
252 rl_bind_keyseq_in_map (keyseq, function, map)
253      const char *keyseq;
254      rl_command_func_t *function;
255      Keymap map;
256 {
257   return (rl_generic_bind (ISFUNC, keyseq, (char *)function, map));
258 }
259
260 /* Backwards compatibility; equivalent to rl_bind_keyseq_in_map() */
261 int
262 rl_set_key (keyseq, function, map)
263      const char *keyseq;
264      rl_command_func_t *function;
265      Keymap map;
266 {
267   return (rl_generic_bind (ISFUNC, keyseq, (char *)function, map));
268 }
269
270 /* Bind key sequence KEYSEQ to DEFAULT_FUNC if KEYSEQ is unbound.  Right
271    now, this is always used to attempt to bind the arrow keys, hence the
272    check for rl_vi_movement_mode. */
273 int
274 rl_bind_keyseq_if_unbound_in_map (keyseq, default_func, kmap)
275      const char *keyseq;
276      rl_command_func_t *default_func;
277      Keymap kmap;
278 {
279   rl_command_func_t *func;
280
281   if (keyseq)
282     {
283       func = rl_function_of_keyseq (keyseq, kmap, (int *)NULL);
284 #if defined (VI_MODE)
285       if (!func || func == rl_do_lowercase_version || func == rl_vi_movement_mode)
286 #else
287       if (!func || func == rl_do_lowercase_version)
288 #endif
289         return (rl_bind_keyseq_in_map (keyseq, default_func, kmap));
290       else
291         return 1;
292     }
293   return 0;
294 }
295
296 int
297 rl_bind_keyseq_if_unbound (keyseq, default_func)
298      const char *keyseq;
299      rl_command_func_t *default_func;
300 {
301   return (rl_bind_keyseq_if_unbound_in_map (keyseq, default_func, _rl_keymap));
302 }
303
304 /* Bind the key sequence represented by the string KEYSEQ to
305    the string of characters MACRO.  This makes new keymaps as
306    necessary.  The initial place to do bindings is in MAP. */
307 int
308 rl_macro_bind (keyseq, macro, map)
309      const char *keyseq, *macro;
310      Keymap map;
311 {
312   char *macro_keys;
313   int macro_keys_len;
314
315   macro_keys = (char *)xmalloc ((2 * strlen (macro)) + 1);
316
317   if (rl_translate_keyseq (macro, macro_keys, &macro_keys_len))
318     {
319       xfree (macro_keys);
320       return -1;
321     }
322   rl_generic_bind (ISMACR, keyseq, macro_keys, map);
323   return 0;
324 }
325
326 /* Bind the key sequence represented by the string KEYSEQ to
327    the arbitrary pointer DATA.  TYPE says what kind of data is
328    pointed to by DATA, right now this can be a function (ISFUNC),
329    a macro (ISMACR), or a keymap (ISKMAP).  This makes new keymaps
330    as necessary.  The initial place to do bindings is in MAP. */
331 int
332 rl_generic_bind (type, keyseq, data, map)
333      int type;
334      const char *keyseq;
335      char *data;
336      Keymap map;
337 {
338   char *keys;
339   int keys_len;
340   register int i;
341   KEYMAP_ENTRY k;
342
343   k.function = 0;
344
345   /* If no keys to bind to, exit right away. */
346   if (keyseq == 0 || *keyseq == 0)
347     {
348       if (type == ISMACR)
349         xfree (data);
350       return -1;
351     }
352
353   keys = (char *)xmalloc (1 + (2 * strlen (keyseq)));
354
355   /* Translate the ASCII representation of KEYSEQ into an array of
356      characters.  Stuff the characters into KEYS, and the length of
357      KEYS into KEYS_LEN. */
358   if (rl_translate_keyseq (keyseq, keys, &keys_len))
359     {
360       xfree (keys);
361       return -1;
362     }
363
364   /* Bind keys, making new keymaps as necessary. */
365   for (i = 0; i < keys_len; i++)
366     {
367       unsigned char uc = keys[i];
368       int ic;
369
370       ic = uc;
371       if (ic < 0 || ic >= KEYMAP_SIZE)
372         {
373           xfree (keys);
374           return -1;
375         }
376
377       if (META_CHAR (ic) && _rl_convert_meta_chars_to_ascii)
378         {
379           ic = UNMETA (ic);
380           if (map[ESC].type == ISKMAP)
381             map = FUNCTION_TO_KEYMAP (map, ESC);
382         }
383
384       if ((i + 1) < keys_len)
385         {
386           if (map[ic].type != ISKMAP)
387             {
388               /* We allow subsequences of keys.  If a keymap is being
389                  created that will `shadow' an existing function or macro
390                  key binding, we save that keybinding into the ANYOTHERKEY
391                  index in the new map.  The dispatch code will look there
392                  to find the function to execute if the subsequence is not
393                  matched.  ANYOTHERKEY was chosen to be greater than
394                  UCHAR_MAX. */
395               k = map[ic];
396
397               map[ic].type = ISKMAP;
398               map[ic].function = KEYMAP_TO_FUNCTION (rl_make_bare_keymap());
399             }
400           map = FUNCTION_TO_KEYMAP (map, ic);
401           /* The dispatch code will return this function if no matching
402              key sequence is found in the keymap.  This (with a little
403              help from the dispatch code in readline.c) allows `a' to be
404              mapped to something, `abc' to be mapped to something else,
405              and the function bound  to `a' to be executed when the user
406              types `abx', leaving `bx' in the input queue. */
407           if (k.function && ((k.type == ISFUNC && k.function != rl_do_lowercase_version) || k.type == ISMACR))
408             {
409               map[ANYOTHERKEY] = k;
410               k.function = 0;
411             }
412         }
413       else
414         {
415           if (map[ic].type == ISMACR)
416             xfree ((char *)map[ic].function);
417           else if (map[ic].type == ISKMAP)
418             {
419               map = FUNCTION_TO_KEYMAP (map, ic);
420               ic = ANYOTHERKEY;
421             }
422
423           map[ic].function = KEYMAP_TO_FUNCTION (data);
424           map[ic].type = type;
425         }
426
427       rl_binding_keymap = map;
428     }
429   xfree (keys);
430   return 0;
431 }
432
433 /* Translate the ASCII representation of SEQ, stuffing the values into ARRAY,
434    an array of characters.  LEN gets the final length of ARRAY.  Return
435    non-zero if there was an error parsing SEQ. */
436 int
437 rl_translate_keyseq (seq, array, len)
438      const char *seq;
439      char *array;
440      int *len;
441 {
442   register int i, c, l, temp;
443
444   for (i = l = 0; c = seq[i]; i++)
445     {
446       if (c == '\\')
447         {
448           c = seq[++i];
449
450           if (c == 0)
451             break;
452
453           /* Handle \C- and \M- prefixes. */
454           if ((c == 'C' || c == 'M') && seq[i + 1] == '-')
455             {
456               /* Handle special case of backwards define. */
457               if (strncmp (&seq[i], "C-\\M-", 5) == 0)
458                 {
459                   array[l++] = ESC;     /* ESC is meta-prefix */
460                   i += 5;
461                   array[l++] = CTRL (_rl_to_upper (seq[i]));
462                   if (seq[i] == '\0')
463                     i--;
464                 }
465               else if (c == 'M')
466                 {
467                   i++;          /* seq[i] == '-' */
468                   /* XXX - obey convert-meta setting */
469                   if (_rl_convert_meta_chars_to_ascii && _rl_keymap[ESC].type == ISKMAP)
470                     array[l++] = ESC;   /* ESC is meta-prefix */
471                   else if (seq[i+1] == '\\' && seq[i+2] == 'C' && seq[i+3] == '-')
472                     {
473                       i += 4;
474                       temp = (seq[i] == '?') ? RUBOUT : CTRL (_rl_to_upper (seq[i]));
475                       array[l++] = META (temp);
476                     }
477                   else
478                     {
479                       /* This doesn't yet handle things like \M-\a, which may
480                          or may not have any reasonable meaning.  You're
481                          probably better off using straight octal or hex. */
482                       i++;
483                       array[l++] = META (seq[i]);
484                     }
485                 }
486               else if (c == 'C')
487                 {
488                   i += 2;
489                   /* Special hack for C-?... */
490                   array[l++] = (seq[i] == '?') ? RUBOUT : CTRL (_rl_to_upper (seq[i]));
491                 }
492               continue;
493             }         
494
495           /* Translate other backslash-escaped characters.  These are the
496              same escape sequences that bash's `echo' and `printf' builtins
497              handle, with the addition of \d -> RUBOUT.  A backslash
498              preceding a character that is not special is stripped. */
499           switch (c)
500             {
501             case 'a':
502               array[l++] = '\007';
503               break;
504             case 'b':
505               array[l++] = '\b';
506               break;
507             case 'd':
508               array[l++] = RUBOUT;      /* readline-specific */
509               break;
510             case 'e':
511               array[l++] = ESC;
512               break;
513             case 'f':
514               array[l++] = '\f';
515               break;
516             case 'n':
517               array[l++] = NEWLINE;
518               break;
519             case 'r':
520               array[l++] = RETURN;
521               break;
522             case 't':
523               array[l++] = TAB;
524               break;
525             case 'v':
526               array[l++] = 0x0B;
527               break;
528             case '\\':
529               array[l++] = '\\';
530               break;
531             case '0': case '1': case '2': case '3':
532             case '4': case '5': case '6': case '7':
533               i++;
534               for (temp = 2, c -= '0'; ISOCTAL (seq[i]) && temp--; i++)
535                 c = (c * 8) + OCTVALUE (seq[i]);
536               i--;      /* auto-increment in for loop */
537               array[l++] = c & largest_char;
538               break;
539             case 'x':
540               i++;
541               for (temp = 2, c = 0; ISXDIGIT ((unsigned char)seq[i]) && temp--; i++)
542                 c = (c * 16) + HEXVALUE (seq[i]);
543               if (temp == 2)
544                 c = 'x';
545               i--;      /* auto-increment in for loop */
546               array[l++] = c & largest_char;
547               break;
548             default:    /* backslashes before non-special chars just add the char */
549               array[l++] = c;
550               break;    /* the backslash is stripped */
551             }
552           continue;
553         }
554
555       array[l++] = c;
556     }
557
558   *len = l;
559   array[l] = '\0';
560   return (0);
561 }
562
563 char *
564 rl_untranslate_keyseq (seq)
565      int seq;
566 {
567   static char kseq[16];
568   int i, c;
569
570   i = 0;
571   c = seq;
572   if (META_CHAR (c))
573     {
574       kseq[i++] = '\\';
575       kseq[i++] = 'M';
576       kseq[i++] = '-';
577       c = UNMETA (c);
578     }
579   else if (c == ESC)
580     {
581       kseq[i++] = '\\';
582       c = 'e';
583     }
584   else if (CTRL_CHAR (c))
585     {
586       kseq[i++] = '\\';
587       kseq[i++] = 'C';
588       kseq[i++] = '-';
589       c = _rl_to_lower (UNCTRL (c));
590     }
591   else if (c == RUBOUT)
592     {
593       kseq[i++] = '\\';
594       kseq[i++] = 'C';
595       kseq[i++] = '-';
596       c = '?';
597     }
598
599   if (c == ESC)
600     {
601       kseq[i++] = '\\';
602       c = 'e';
603     }
604   else if (c == '\\' || c == '"')
605     {
606       kseq[i++] = '\\';
607     }
608
609   kseq[i++] = (unsigned char) c;
610   kseq[i] = '\0';
611   return kseq;
612 }
613
614 static char *
615 _rl_untranslate_macro_value (seq)
616      char *seq;
617 {
618   char *ret, *r, *s;
619   int c;
620
621   r = ret = (char *)xmalloc (7 * strlen (seq) + 1);
622   for (s = seq; *s; s++)
623     {
624       c = *s;
625       if (META_CHAR (c))
626         {
627           *r++ = '\\';
628           *r++ = 'M';
629           *r++ = '-';
630           c = UNMETA (c);
631         }
632       else if (c == ESC)
633         {
634           *r++ = '\\';
635           c = 'e';
636         }
637       else if (CTRL_CHAR (c))
638         {
639           *r++ = '\\';
640           *r++ = 'C';
641           *r++ = '-';
642           c = _rl_to_lower (UNCTRL (c));
643         }
644       else if (c == RUBOUT)
645         {
646           *r++ = '\\';
647           *r++ = 'C';
648           *r++ = '-';
649           c = '?';
650         }
651
652       if (c == ESC)
653         {
654           *r++ = '\\';
655           c = 'e';
656         }
657       else if (c == '\\' || c == '"')
658         *r++ = '\\';
659
660       *r++ = (unsigned char)c;
661     }
662   *r = '\0';
663   return ret;
664 }
665
666 /* Return a pointer to the function that STRING represents.
667    If STRING doesn't have a matching function, then a NULL pointer
668    is returned. */
669 rl_command_func_t *
670 rl_named_function (string)
671      const char *string;
672 {
673   register int i;
674
675   rl_initialize_funmap ();
676
677   for (i = 0; funmap[i]; i++)
678     if (_rl_stricmp (funmap[i]->name, string) == 0)
679       return (funmap[i]->function);
680   return ((rl_command_func_t *)NULL);
681 }
682
683 /* Return the function (or macro) definition which would be invoked via
684    KEYSEQ if executed in MAP.  If MAP is NULL, then the current keymap is
685    used.  TYPE, if non-NULL, is a pointer to an int which will receive the
686    type of the object pointed to.  One of ISFUNC (function), ISKMAP (keymap),
687    or ISMACR (macro). */
688 rl_command_func_t *
689 rl_function_of_keyseq (keyseq, map, type)
690      const char *keyseq;
691      Keymap map;
692      int *type;
693 {
694   register int i;
695
696   if (map == 0)
697     map = _rl_keymap;
698
699   for (i = 0; keyseq && keyseq[i]; i++)
700     {
701       unsigned char ic = keyseq[i];
702
703       if (META_CHAR (ic) && _rl_convert_meta_chars_to_ascii)
704         {
705           if (map[ESC].type == ISKMAP)
706             {
707               map = FUNCTION_TO_KEYMAP (map, ESC);
708               ic = UNMETA (ic);
709             }
710           /* XXX - should we just return NULL here, since this obviously
711              doesn't match? */
712           else
713             {
714               if (type)
715                 *type = map[ESC].type;
716
717               return (map[ESC].function);
718             }
719         }
720
721       if (map[ic].type == ISKMAP)
722         {
723           /* If this is the last key in the key sequence, return the
724              map. */
725           if (keyseq[i + 1] == '\0')
726             {
727               if (type)
728                 *type = ISKMAP;
729
730               return (map[ic].function);
731             }
732           else
733             map = FUNCTION_TO_KEYMAP (map, ic);
734         }
735       /* If we're not at the end of the key sequence, and the current key
736          is bound to something other than a keymap, then the entire key
737          sequence is not bound. */
738       else if (map[ic].type != ISKMAP && keyseq[i+1])
739         return ((rl_command_func_t *)NULL);
740       else      /* map[ic].type != ISKMAP && keyseq[i+1] == 0 */
741         {
742           if (type)
743             *type = map[ic].type;
744
745           return (map[ic].function);
746         }
747     }
748   return ((rl_command_func_t *) NULL);
749 }
750
751 /* The last key bindings file read. */
752 static char *last_readline_init_file = (char *)NULL;
753
754 /* The file we're currently reading key bindings from. */
755 static const char *current_readline_init_file;
756 static int current_readline_init_include_level;
757 static int current_readline_init_lineno;
758
759 /* Read FILENAME into a locally-allocated buffer and return the buffer.
760    The size of the buffer is returned in *SIZEP.  Returns NULL if any
761    errors were encountered. */
762 static char *
763 _rl_read_file (filename, sizep)
764      char *filename;
765      size_t *sizep;
766 {
767   struct stat finfo;
768   size_t file_size;
769   char *buffer;
770   int i, file;
771
772   if ((stat (filename, &finfo) < 0) || (file = open (filename, O_RDONLY, 0666)) < 0)
773     return ((char *)NULL);
774
775   file_size = (size_t)finfo.st_size;
776
777   /* check for overflow on very large files */
778   if (file_size != finfo.st_size || file_size + 1 < file_size)
779     {
780       if (file >= 0)
781         close (file);
782 #if defined (EFBIG)
783       errno = EFBIG;
784 #endif
785       return ((char *)NULL);
786     }
787
788   /* Read the file into BUFFER. */
789   buffer = (char *)xmalloc (file_size + 1);
790   i = read (file, buffer, file_size);
791   close (file);
792
793   if (i < 0)
794     {
795       xfree (buffer);
796       return ((char *)NULL);
797     }
798
799   buffer[i] = '\0';
800   if (sizep)
801     *sizep = i;
802
803   return (buffer);
804 }
805
806 /* Re-read the current keybindings file. */
807 int
808 rl_re_read_init_file (count, ignore)
809      int count, ignore;
810 {
811   int r;
812   r = rl_read_init_file ((const char *)NULL);
813   rl_set_keymap_from_edit_mode ();
814   return r;
815 }
816
817 /* Do key bindings from a file.  If FILENAME is NULL it defaults
818    to the first non-null filename from this list:
819      1. the filename used for the previous call
820      2. the value of the shell variable `INPUTRC'
821      3. ~/.inputrc
822      4. /etc/inputrc
823    If the file existed and could be opened and read, 0 is returned,
824    otherwise errno is returned. */
825 int
826 rl_read_init_file (filename)
827      const char *filename;
828 {
829   /* Default the filename. */
830   if (filename == 0)
831     filename = last_readline_init_file;
832   if (filename == 0)
833     filename = sh_get_env_value ("INPUTRC");
834   if (filename == 0 || *filename == 0)
835     {
836       filename = DEFAULT_INPUTRC;
837       /* Try to read DEFAULT_INPUTRC; fall back to SYS_INPUTRC on failure */
838       if (_rl_read_init_file (filename, 0) == 0)
839         return 0;
840       filename = SYS_INPUTRC;
841     }
842
843 #if defined (__MSDOS__)
844   if (_rl_read_init_file (filename, 0) == 0)
845     return 0;
846   filename = "~/_inputrc";
847 #endif
848   return (_rl_read_init_file (filename, 0));
849 }
850
851 static int
852 _rl_read_init_file (filename, include_level)
853      const char *filename;
854      int include_level;
855 {
856   register int i;
857   char *buffer, *openname, *line, *end;
858   size_t file_size;
859
860   current_readline_init_file = filename;
861   current_readline_init_include_level = include_level;
862
863   openname = tilde_expand (filename);
864   buffer = _rl_read_file (openname, &file_size);
865   xfree (openname);
866
867   if (buffer == 0)
868     return (errno);
869   
870   if (include_level == 0 && filename != last_readline_init_file)
871     {
872       FREE (last_readline_init_file);
873       last_readline_init_file = savestring (filename);
874     }
875
876   currently_reading_init_file = 1;
877
878   /* Loop over the lines in the file.  Lines that start with `#' are
879      comments; all other lines are commands for readline initialization. */
880   current_readline_init_lineno = 1;
881   line = buffer;
882   end = buffer + file_size;
883   while (line < end)
884     {
885       /* Find the end of this line. */
886       for (i = 0; line + i != end && line[i] != '\n'; i++);
887
888 #if defined (__CYGWIN__)
889       /* ``Be liberal in what you accept.'' */
890       if (line[i] == '\n' && line[i-1] == '\r')
891         line[i - 1] = '\0';
892 #endif
893
894       /* Mark end of line. */
895       line[i] = '\0';
896
897       /* Skip leading whitespace. */
898       while (*line && whitespace (*line))
899         {
900           line++;
901           i--;
902         }
903
904       /* If the line is not a comment, then parse it. */
905       if (*line && *line != '#')
906         rl_parse_and_bind (line);
907
908       /* Move to the next line. */
909       line += i + 1;
910       current_readline_init_lineno++;
911     }
912
913   xfree (buffer);
914   currently_reading_init_file = 0;
915   return (0);
916 }
917
918 static void
919 _rl_init_file_error (msg)
920      const char *msg;
921 {
922   if (currently_reading_init_file)
923     _rl_errmsg ("%s: line %d: %s\n", current_readline_init_file,
924                      current_readline_init_lineno, msg);
925   else
926     _rl_errmsg ("%s", msg);
927 }
928
929 /* **************************************************************** */
930 /*                                                                  */
931 /*                      Parser Directives                           */
932 /*                                                                  */
933 /* **************************************************************** */
934
935 typedef int _rl_parser_func_t PARAMS((char *));
936
937 /* Things that mean `Control'. */
938 const char * const _rl_possible_control_prefixes[] = {
939   "Control-", "C-", "CTRL-", (const char *)NULL
940 };
941
942 const char * const _rl_possible_meta_prefixes[] = {
943   "Meta", "M-", (const char *)NULL
944 };
945
946 /* Conditionals. */
947
948 /* Calling programs set this to have their argv[0]. */
949 const char *rl_readline_name = "other";
950
951 /* Stack of previous values of parsing_conditionalized_out. */
952 static unsigned char *if_stack = (unsigned char *)NULL;
953 static int if_stack_depth;
954 static int if_stack_size;
955
956 /* Push _rl_parsing_conditionalized_out, and set parser state based
957    on ARGS. */
958 static int
959 parser_if (args)
960      char *args;
961 {
962   register int i;
963
964   /* Push parser state. */
965   if (if_stack_depth + 1 >= if_stack_size)
966     {
967       if (!if_stack)
968         if_stack = (unsigned char *)xmalloc (if_stack_size = 20);
969       else
970         if_stack = (unsigned char *)xrealloc (if_stack, if_stack_size += 20);
971     }
972   if_stack[if_stack_depth++] = _rl_parsing_conditionalized_out;
973
974   /* If parsing is turned off, then nothing can turn it back on except
975      for finding the matching endif.  In that case, return right now. */
976   if (_rl_parsing_conditionalized_out)
977     return 0;
978
979   /* Isolate first argument. */
980   for (i = 0; args[i] && !whitespace (args[i]); i++);
981
982   if (args[i])
983     args[i++] = '\0';
984
985   /* Handle "$if term=foo" and "$if mode=emacs" constructs.  If this
986      isn't term=foo, or mode=emacs, then check to see if the first
987      word in ARGS is the same as the value stored in rl_readline_name. */
988   if (rl_terminal_name && _rl_strnicmp (args, "term=", 5) == 0)
989     {
990       char *tem, *tname;
991
992       /* Terminals like "aaa-60" are equivalent to "aaa". */
993       tname = savestring (rl_terminal_name);
994       tem = strchr (tname, '-');
995       if (tem)
996         *tem = '\0';
997
998       /* Test the `long' and `short' forms of the terminal name so that
999          if someone has a `sun-cmd' and does not want to have bindings
1000          that will be executed if the terminal is a `sun', they can put
1001          `$if term=sun-cmd' into their .inputrc. */
1002       _rl_parsing_conditionalized_out = _rl_stricmp (args + 5, tname) &&
1003                                         _rl_stricmp (args + 5, rl_terminal_name);
1004       xfree (tname);
1005     }
1006 #if defined (VI_MODE)
1007   else if (_rl_strnicmp (args, "mode=", 5) == 0)
1008     {
1009       int mode;
1010
1011       if (_rl_stricmp (args + 5, "emacs") == 0)
1012         mode = emacs_mode;
1013       else if (_rl_stricmp (args + 5, "vi") == 0)
1014         mode = vi_mode;
1015       else
1016         mode = no_mode;
1017
1018       _rl_parsing_conditionalized_out = mode != rl_editing_mode;
1019     }
1020 #endif /* VI_MODE */
1021   /* Check to see if the first word in ARGS is the same as the
1022      value stored in rl_readline_name. */
1023   else if (_rl_stricmp (args, rl_readline_name) == 0)
1024     _rl_parsing_conditionalized_out = 0;
1025   else
1026     _rl_parsing_conditionalized_out = 1;
1027   return 0;
1028 }
1029
1030 /* Invert the current parser state if there is anything on the stack. */
1031 static int
1032 parser_else (args)
1033      char *args;
1034 {
1035   register int i;
1036
1037   if (if_stack_depth == 0)
1038     {
1039       _rl_init_file_error ("$else found without matching $if");
1040       return 0;
1041     }
1042
1043 #if 0
1044   /* Check the previous (n - 1) levels of the stack to make sure that
1045      we haven't previously turned off parsing. */
1046   for (i = 0; i < if_stack_depth - 1; i++)
1047 #else
1048   /* Check the previous (n) levels of the stack to make sure that
1049      we haven't previously turned off parsing. */
1050   for (i = 0; i < if_stack_depth; i++)
1051 #endif
1052     if (if_stack[i] == 1)
1053       return 0;
1054
1055   /* Invert the state of parsing if at top level. */
1056   _rl_parsing_conditionalized_out = !_rl_parsing_conditionalized_out;
1057   return 0;
1058 }
1059
1060 /* Terminate a conditional, popping the value of
1061    _rl_parsing_conditionalized_out from the stack. */
1062 static int
1063 parser_endif (args)
1064      char *args;
1065 {
1066   if (if_stack_depth)
1067     _rl_parsing_conditionalized_out = if_stack[--if_stack_depth];
1068   else
1069     _rl_init_file_error ("$endif without matching $if");
1070   return 0;
1071 }
1072
1073 static int
1074 parser_include (args)
1075      char *args;
1076 {
1077   const char *old_init_file;
1078   char *e;
1079   int old_line_number, old_include_level, r;
1080
1081   if (_rl_parsing_conditionalized_out)
1082     return (0);
1083
1084   old_init_file = current_readline_init_file;
1085   old_line_number = current_readline_init_lineno;
1086   old_include_level = current_readline_init_include_level;
1087
1088   e = strchr (args, '\n');
1089   if (e)
1090     *e = '\0';
1091   r = _rl_read_init_file ((const char *)args, old_include_level + 1);
1092
1093   current_readline_init_file = old_init_file;
1094   current_readline_init_lineno = old_line_number;
1095   current_readline_init_include_level = old_include_level;
1096
1097   return r;
1098 }
1099   
1100 /* Associate textual names with actual functions. */
1101 static const struct {
1102   const char * const name;
1103   _rl_parser_func_t *function;
1104 } parser_directives [] = {
1105   { "if", parser_if },
1106   { "endif", parser_endif },
1107   { "else", parser_else },
1108   { "include", parser_include },
1109   { (char *)0x0, (_rl_parser_func_t *)0x0 }
1110 };
1111
1112 /* Handle a parser directive.  STATEMENT is the line of the directive
1113    without any leading `$'. */
1114 static int
1115 handle_parser_directive (statement)
1116      char *statement;
1117 {
1118   register int i;
1119   char *directive, *args;
1120
1121   /* Isolate the actual directive. */
1122
1123   /* Skip whitespace. */
1124   for (i = 0; whitespace (statement[i]); i++);
1125
1126   directive = &statement[i];
1127
1128   for (; statement[i] && !whitespace (statement[i]); i++);
1129
1130   if (statement[i])
1131     statement[i++] = '\0';
1132
1133   for (; statement[i] && whitespace (statement[i]); i++);
1134
1135   args = &statement[i];
1136
1137   /* Lookup the command, and act on it. */
1138   for (i = 0; parser_directives[i].name; i++)
1139     if (_rl_stricmp (directive, parser_directives[i].name) == 0)
1140       {
1141         (*parser_directives[i].function) (args);
1142         return (0);
1143       }
1144
1145   /* display an error message about the unknown parser directive */
1146   _rl_init_file_error ("unknown parser directive");
1147   return (1);
1148 }
1149
1150 /* Read the binding command from STRING and perform it.
1151    A key binding command looks like: Keyname: function-name\0,
1152    a variable binding command looks like: set variable value.
1153    A new-style keybinding looks like "\C-x\C-x": exchange-point-and-mark. */
1154 int
1155 rl_parse_and_bind (string)
1156      char *string;
1157 {
1158   char *funname, *kname;
1159   register int c, i;
1160   int key, equivalency;
1161
1162   while (string && whitespace (*string))
1163     string++;
1164
1165   if (!string || !*string || *string == '#')
1166     return 0;
1167
1168   /* If this is a parser directive, act on it. */
1169   if (*string == '$')
1170     {
1171       handle_parser_directive (&string[1]);
1172       return 0;
1173     }
1174
1175   /* If we aren't supposed to be parsing right now, then we're done. */
1176   if (_rl_parsing_conditionalized_out)
1177     return 0;
1178
1179   i = 0;
1180   /* If this keyname is a complex key expression surrounded by quotes,
1181      advance to after the matching close quote.  This code allows the
1182      backslash to quote characters in the key expression. */
1183   if (*string == '"')
1184     {
1185       int passc = 0;
1186
1187       for (i = 1; c = string[i]; i++)
1188         {
1189           if (passc)
1190             {
1191               passc = 0;
1192               continue;
1193             }
1194
1195           if (c == '\\')
1196             {
1197               passc++;
1198               continue;
1199             }
1200
1201           if (c == '"')
1202             break;
1203         }
1204       /* If we didn't find a closing quote, abort the line. */
1205       if (string[i] == '\0')
1206         {
1207           _rl_init_file_error ("no closing `\"' in key binding");
1208           return 1;
1209         }
1210     }
1211
1212   /* Advance to the colon (:) or whitespace which separates the two objects. */
1213   for (; (c = string[i]) && c != ':' && c != ' ' && c != '\t'; i++ );
1214
1215   equivalency = (c == ':' && string[i + 1] == '=');
1216
1217   /* Mark the end of the command (or keyname). */
1218   if (string[i])
1219     string[i++] = '\0';
1220
1221   /* If doing assignment, skip the '=' sign as well. */
1222   if (equivalency)
1223     string[i++] = '\0';
1224
1225   /* If this is a command to set a variable, then do that. */
1226   if (_rl_stricmp (string, "set") == 0)
1227     {
1228       char *var, *value, *e;
1229
1230       var = string + i;
1231       /* Make VAR point to start of variable name. */
1232       while (*var && whitespace (*var)) var++;
1233
1234       /* Make VALUE point to start of value string. */
1235       value = var;
1236       while (*value && !whitespace (*value)) value++;
1237       if (*value)
1238         *value++ = '\0';
1239       while (*value && whitespace (*value)) value++;
1240
1241       /* Strip trailing whitespace from values to boolean variables.  Temp
1242          fix until I get a real quoted-string parser here. */
1243       i = find_boolean_var (var);
1244       if (i >= 0)
1245         {
1246           /* remove trailing whitespace */
1247           e = value + strlen (value) - 1;
1248           while (e >= value && whitespace (*e))
1249             e--;
1250           e++;          /* skip back to whitespace or EOS */
1251           if (*e && e >= value)
1252             *e = '\0';
1253         }
1254
1255       rl_variable_bind (var, value);
1256       return 0;
1257     }
1258
1259   /* Skip any whitespace between keyname and funname. */
1260   for (; string[i] && whitespace (string[i]); i++);
1261   funname = &string[i];
1262
1263   /* Now isolate funname.
1264      For straight function names just look for whitespace, since
1265      that will signify the end of the string.  But this could be a
1266      macro definition.  In that case, the string is quoted, so skip
1267      to the matching delimiter.  We allow the backslash to quote the
1268      delimiter characters in the macro body. */
1269   /* This code exists to allow whitespace in macro expansions, which
1270      would otherwise be gobbled up by the next `for' loop.*/
1271   /* XXX - it may be desirable to allow backslash quoting only if " is
1272      the quoted string delimiter, like the shell. */
1273   if (*funname == '\'' || *funname == '"')
1274     {
1275       int delimiter, passc;
1276
1277       delimiter = string[i++];
1278       for (passc = 0; c = string[i]; i++)
1279         {
1280           if (passc)
1281             {
1282               passc = 0;
1283               continue;
1284             }
1285
1286           if (c == '\\')
1287             {
1288               passc = 1;
1289               continue;
1290             }
1291
1292           if (c == delimiter)
1293             break;
1294         }
1295       if (c)
1296         i++;
1297     }
1298
1299   /* Advance to the end of the string.  */
1300   for (; string[i] && !whitespace (string[i]); i++);
1301
1302   /* No extra whitespace at the end of the string. */
1303   string[i] = '\0';
1304
1305   /* Handle equivalency bindings here.  Make the left-hand side be exactly
1306      whatever the right-hand evaluates to, including keymaps. */
1307   if (equivalency)
1308     {
1309       return 0;
1310     }
1311
1312   /* If this is a new-style key-binding, then do the binding with
1313      rl_bind_keyseq ().  Otherwise, let the older code deal with it. */
1314   if (*string == '"')
1315     {
1316       char *seq;
1317       register int j, k, passc;
1318
1319       seq = (char *)xmalloc (1 + strlen (string));
1320       for (j = 1, k = passc = 0; string[j]; j++)
1321         {
1322           /* Allow backslash to quote characters, but leave them in place.
1323              This allows a string to end with a backslash quoting another
1324              backslash, or with a backslash quoting a double quote.  The
1325              backslashes are left in place for rl_translate_keyseq (). */
1326           if (passc || (string[j] == '\\'))
1327             {
1328               seq[k++] = string[j];
1329               passc = !passc;
1330               continue;
1331             }
1332
1333           if (string[j] == '"')
1334             break;
1335
1336           seq[k++] = string[j];
1337         }
1338       seq[k] = '\0';
1339
1340       /* Binding macro? */
1341       if (*funname == '\'' || *funname == '"')
1342         {
1343           j = strlen (funname);
1344
1345           /* Remove the delimiting quotes from each end of FUNNAME. */
1346           if (j && funname[j - 1] == *funname)
1347             funname[j - 1] = '\0';
1348
1349           rl_macro_bind (seq, &funname[1], _rl_keymap);
1350         }
1351       else
1352         rl_bind_keyseq (seq, rl_named_function (funname));
1353
1354       xfree (seq);
1355       return 0;
1356     }
1357
1358   /* Get the actual character we want to deal with. */
1359   kname = strrchr (string, '-');
1360   if (!kname)
1361     kname = string;
1362   else
1363     kname++;
1364
1365   key = glean_key_from_name (kname);
1366
1367   /* Add in control and meta bits. */
1368   if (substring_member_of_array (string, _rl_possible_control_prefixes))
1369     key = CTRL (_rl_to_upper (key));
1370
1371   if (substring_member_of_array (string, _rl_possible_meta_prefixes))
1372     key = META (key);
1373
1374   /* Temporary.  Handle old-style keyname with macro-binding. */
1375   if (*funname == '\'' || *funname == '"')
1376     {
1377       char useq[2];
1378       int fl = strlen (funname);
1379
1380       useq[0] = key; useq[1] = '\0';
1381       if (fl && funname[fl - 1] == *funname)
1382         funname[fl - 1] = '\0';
1383
1384       rl_macro_bind (useq, &funname[1], _rl_keymap);
1385     }
1386 #if defined (PREFIX_META_HACK)
1387   /* Ugly, but working hack to keep prefix-meta around. */
1388   else if (_rl_stricmp (funname, "prefix-meta") == 0)
1389     {
1390       char seq[2];
1391
1392       seq[0] = key;
1393       seq[1] = '\0';
1394       rl_generic_bind (ISKMAP, seq, (char *)emacs_meta_keymap, _rl_keymap);
1395     }
1396 #endif /* PREFIX_META_HACK */
1397   else
1398     rl_bind_key (key, rl_named_function (funname));
1399   return 0;
1400 }
1401
1402 /* Simple structure for boolean readline variables (i.e., those that can
1403    have one of two values; either "On" or 1 for truth, or "Off" or 0 for
1404    false. */
1405
1406 #define V_SPECIAL       0x1
1407
1408 static const struct {
1409   const char * const name;
1410   int *value;
1411   int flags;
1412 } boolean_varlist [] = {
1413   { "bind-tty-special-chars",   &_rl_bind_stty_chars,           0 },
1414   { "blink-matching-paren",     &rl_blink_matching_paren,       V_SPECIAL },
1415   { "byte-oriented",            &rl_byte_oriented,              0 },
1416   { "completion-ignore-case",   &_rl_completion_case_fold,      0 },
1417   { "convert-meta",             &_rl_convert_meta_chars_to_ascii, 0 },
1418   { "disable-completion",       &rl_inhibit_completion,         0 },
1419   { "enable-keypad",            &_rl_enable_keypad,             0 },
1420   { "expand-tilde",             &rl_complete_with_tilde_expansion, 0 },
1421   { "history-preserve-point",   &_rl_history_preserve_point,    0 },
1422   { "horizontal-scroll-mode",   &_rl_horizontal_scroll_mode,    0 },
1423   { "input-meta",               &_rl_meta_flag,                 0 },
1424   { "mark-directories",         &_rl_complete_mark_directories, 0 },
1425   { "mark-modified-lines",      &_rl_mark_modified_lines,       0 },
1426   { "mark-symlinked-directories", &_rl_complete_mark_symlink_dirs, 0 },
1427   { "match-hidden-files",       &_rl_match_hidden_files,        0 },
1428   { "meta-flag",                &_rl_meta_flag,                 0 },
1429   { "output-meta",              &_rl_output_meta_chars,         0 },
1430   { "page-completions",         &_rl_page_completions,          0 },
1431   { "prefer-visible-bell",      &_rl_prefer_visible_bell,       V_SPECIAL },
1432   { "print-completions-horizontally", &_rl_print_completions_horizontally, 0 },
1433   { "revert-all-at-newline",    &_rl_revert_all_at_newline,     0 },
1434   { "show-all-if-ambiguous",    &_rl_complete_show_all,         0 },
1435   { "show-all-if-unmodified",   &_rl_complete_show_unmodified,  0 },
1436 #if defined (VISIBLE_STATS)
1437   { "visible-stats",            &rl_visible_stats,              0 },
1438 #endif /* VISIBLE_STATS */
1439   { (char *)NULL, (int *)NULL }
1440 };
1441
1442 static int
1443 find_boolean_var (name)
1444      const char *name;
1445 {
1446   register int i;
1447
1448   for (i = 0; boolean_varlist[i].name; i++)
1449     if (_rl_stricmp (name, boolean_varlist[i].name) == 0)
1450       return i;
1451   return -1;
1452 }
1453
1454 /* Hooks for handling special boolean variables, where a
1455    function needs to be called or another variable needs
1456    to be changed when they're changed. */
1457 static void
1458 hack_special_boolean_var (i)
1459      int i;
1460 {
1461   const char *name;
1462
1463   name = boolean_varlist[i].name;
1464
1465   if (_rl_stricmp (name, "blink-matching-paren") == 0)
1466     _rl_enable_paren_matching (rl_blink_matching_paren);
1467   else if (_rl_stricmp (name, "prefer-visible-bell") == 0)
1468     {
1469       if (_rl_prefer_visible_bell)
1470         _rl_bell_preference = VISIBLE_BELL;
1471       else
1472         _rl_bell_preference = AUDIBLE_BELL;
1473     }
1474 }
1475
1476 typedef int _rl_sv_func_t PARAMS((const char *));
1477
1478 /* These *must* correspond to the array indices for the appropriate
1479    string variable.  (Though they're not used right now.) */
1480 #define V_BELLSTYLE     0
1481 #define V_COMBEGIN      1
1482 #define V_EDITMODE      2
1483 #define V_ISRCHTERM     3
1484 #define V_KEYMAP        4
1485
1486 #define V_STRING        1
1487 #define V_INT           2
1488
1489 /* Forward declarations */
1490 static int sv_bell_style PARAMS((const char *));
1491 static int sv_combegin PARAMS((const char *));
1492 static int sv_dispprefix PARAMS((const char *));
1493 static int sv_compquery PARAMS((const char *));
1494 static int sv_editmode PARAMS((const char *));
1495 static int sv_histsize PARAMS((const char *));
1496 static int sv_isrchterm PARAMS((const char *));
1497 static int sv_keymap PARAMS((const char *));
1498
1499 static const struct {
1500   const char * const name;
1501   int flags;
1502   _rl_sv_func_t *set_func;
1503 } string_varlist[] = {
1504   { "bell-style",       V_STRING,       sv_bell_style },
1505   { "comment-begin",    V_STRING,       sv_combegin },
1506   { "completion-prefix-display-length", V_INT,  sv_dispprefix },
1507   { "completion-query-items", V_INT,    sv_compquery },
1508   { "editing-mode",     V_STRING,       sv_editmode },
1509   { "history-size",     V_INT,          sv_histsize },
1510   { "isearch-terminators", V_STRING,    sv_isrchterm },
1511   { "keymap",           V_STRING,       sv_keymap },
1512   { (char *)NULL,       0 }
1513 };
1514
1515 static int
1516 find_string_var (name)
1517      const char *name;
1518 {
1519   register int i;
1520
1521   for (i = 0; string_varlist[i].name; i++)
1522     if (_rl_stricmp (name, string_varlist[i].name) == 0)
1523       return i;
1524   return -1;
1525 }
1526
1527 /* A boolean value that can appear in a `set variable' command is true if
1528    the value is null or empty, `on' (case-insenstive), or "1".  Any other
1529    values result in 0 (false). */
1530 static int
1531 bool_to_int (value)
1532      const char *value;
1533 {
1534   return (value == 0 || *value == '\0' ||
1535                 (_rl_stricmp (value, "on") == 0) ||
1536                 (value[0] == '1' && value[1] == '\0'));
1537 }
1538
1539 char *
1540 rl_variable_value (name)
1541      const char *name;
1542 {
1543   register int i;
1544
1545   /* Check for simple variables first. */
1546   i = find_boolean_var (name);
1547   if (i >= 0)
1548     return (*boolean_varlist[i].value ? "on" : "off");
1549
1550   i = find_string_var (name);
1551   if (i >= 0)
1552     return (_rl_get_string_variable_value (string_varlist[i].name));
1553
1554   /* Unknown variable names return NULL. */
1555   return 0;
1556 }
1557
1558 int
1559 rl_variable_bind (name, value)
1560      const char *name, *value;
1561 {
1562   register int i;
1563   int   v;
1564
1565   /* Check for simple variables first. */
1566   i = find_boolean_var (name);
1567   if (i >= 0)
1568     {
1569       *boolean_varlist[i].value = bool_to_int (value);
1570       if (boolean_varlist[i].flags & V_SPECIAL)
1571         hack_special_boolean_var (i);
1572       return 0;
1573     }
1574
1575   i = find_string_var (name);
1576
1577   /* For the time being, unknown variable names or string names without a
1578      handler function are simply ignored. */
1579   if (i < 0 || string_varlist[i].set_func == 0)
1580     return 0;
1581
1582   v = (*string_varlist[i].set_func) (value);
1583   return v;
1584 }
1585
1586 static int
1587 sv_editmode (value)
1588      const char *value;
1589 {
1590   if (_rl_strnicmp (value, "vi", 2) == 0)
1591     {
1592 #if defined (VI_MODE)
1593       _rl_keymap = vi_insertion_keymap;
1594       rl_editing_mode = vi_mode;
1595 #endif /* VI_MODE */
1596       return 0;
1597     }
1598   else if (_rl_strnicmp (value, "emacs", 5) == 0)
1599     {
1600       _rl_keymap = emacs_standard_keymap;
1601       rl_editing_mode = emacs_mode;
1602       return 0;
1603     }
1604   return 1;
1605 }
1606
1607 static int
1608 sv_combegin (value)
1609      const char *value;
1610 {
1611   if (value && *value)
1612     {
1613       FREE (_rl_comment_begin);
1614       _rl_comment_begin = savestring (value);
1615       return 0;
1616     }
1617   return 1;
1618 }
1619
1620 static int
1621 sv_dispprefix (value)
1622      const char *value;
1623 {
1624   int nval = 0;
1625
1626   if (value && *value)
1627     {
1628       nval = atoi (value);
1629       if (nval < 0)
1630         nval = 0;
1631     }
1632   _rl_completion_prefix_display_length = nval;
1633   return 0;
1634 }
1635
1636 static int
1637 sv_compquery (value)
1638      const char *value;
1639 {
1640   int nval = 100;
1641
1642   if (value && *value)
1643     {
1644       nval = atoi (value);
1645       if (nval < 0)
1646         nval = 0;
1647     }
1648   rl_completion_query_items = nval;
1649   return 0;
1650 }
1651
1652 static int
1653 sv_histsize (value)
1654      const char *value;
1655 {
1656   int nval = 500;
1657
1658   if (value && *value)
1659     {
1660       nval = atoi (value);
1661       if (nval < 0)
1662         return 1;
1663     }
1664   stifle_history (nval);
1665   return 0;
1666 }
1667
1668 static int
1669 sv_keymap (value)
1670      const char *value;
1671 {
1672   Keymap kmap;
1673
1674   kmap = rl_get_keymap_by_name (value);
1675   if (kmap)
1676     {
1677       rl_set_keymap (kmap);
1678       return 0;
1679     }
1680   return 1;
1681 }
1682
1683 static int
1684 sv_bell_style (value)
1685      const char *value;
1686 {
1687   if (value == 0 || *value == '\0')
1688     _rl_bell_preference = AUDIBLE_BELL;
1689   else if (_rl_stricmp (value, "none") == 0 || _rl_stricmp (value, "off") == 0)
1690     _rl_bell_preference = NO_BELL;
1691   else if (_rl_stricmp (value, "audible") == 0 || _rl_stricmp (value, "on") == 0)
1692     _rl_bell_preference = AUDIBLE_BELL;
1693   else if (_rl_stricmp (value, "visible") == 0)
1694     _rl_bell_preference = VISIBLE_BELL;
1695   else
1696     return 1;
1697   return 0;
1698 }
1699
1700 static int
1701 sv_isrchterm (value)
1702      const char *value;
1703 {
1704   int beg, end, delim;
1705   char *v;
1706
1707   if (value == 0)
1708     return 1;
1709
1710   /* Isolate the value and translate it into a character string. */
1711   v = savestring (value);
1712   FREE (_rl_isearch_terminators);
1713   if (v[0] == '"' || v[0] == '\'')
1714     {
1715       delim = v[0];
1716       for (beg = end = 1; v[end] && v[end] != delim; end++)
1717         ;
1718     }
1719   else
1720     {
1721       for (beg = end = 0; whitespace (v[end]) == 0; end++)
1722         ;
1723     }
1724
1725   v[end] = '\0';
1726
1727   /* The value starts at v + beg.  Translate it into a character string. */
1728   _rl_isearch_terminators = (char *)xmalloc (2 * strlen (v) + 1);
1729   rl_translate_keyseq (v + beg, _rl_isearch_terminators, &end);
1730   _rl_isearch_terminators[end] = '\0';
1731
1732   xfree (v);
1733   return 0;
1734 }
1735       
1736 /* Return the character which matches NAME.
1737    For example, `Space' returns ' '. */
1738
1739 typedef struct {
1740   const char * const name;
1741   int value;
1742 } assoc_list;
1743
1744 static const assoc_list name_key_alist[] = {
1745   { "DEL", 0x7f },
1746   { "ESC", '\033' },
1747   { "Escape", '\033' },
1748   { "LFD", '\n' },
1749   { "Newline", '\n' },
1750   { "RET", '\r' },
1751   { "Return", '\r' },
1752   { "Rubout", 0x7f },
1753   { "SPC", ' ' },
1754   { "Space", ' ' },
1755   { "Tab", 0x09 },
1756   { (char *)0x0, 0 }
1757 };
1758
1759 static int
1760 glean_key_from_name (name)
1761      char *name;
1762 {
1763   register int i;
1764
1765   for (i = 0; name_key_alist[i].name; i++)
1766     if (_rl_stricmp (name, name_key_alist[i].name) == 0)
1767       return (name_key_alist[i].value);
1768
1769   return (*(unsigned char *)name);      /* XXX was return (*name) */
1770 }
1771
1772 /* Auxiliary functions to manage keymaps. */
1773 static const struct {
1774   const char * const name;
1775   Keymap map;
1776 } keymap_names[] = {
1777   { "emacs", emacs_standard_keymap },
1778   { "emacs-standard", emacs_standard_keymap },
1779   { "emacs-meta", emacs_meta_keymap },
1780   { "emacs-ctlx", emacs_ctlx_keymap },
1781 #if defined (VI_MODE)
1782   { "vi", vi_movement_keymap },
1783   { "vi-move", vi_movement_keymap },
1784   { "vi-command", vi_movement_keymap },
1785   { "vi-insert", vi_insertion_keymap },
1786 #endif /* VI_MODE */
1787   { (char *)0x0, (Keymap)0x0 }
1788 };
1789
1790 Keymap
1791 rl_get_keymap_by_name (name)
1792      const char *name;
1793 {
1794   register int i;
1795
1796   for (i = 0; keymap_names[i].name; i++)
1797     if (_rl_stricmp (name, keymap_names[i].name) == 0)
1798       return (keymap_names[i].map);
1799   return ((Keymap) NULL);
1800 }
1801
1802 char *
1803 rl_get_keymap_name (map)
1804      Keymap map;
1805 {
1806   register int i;
1807   for (i = 0; keymap_names[i].name; i++)
1808     if (map == keymap_names[i].map)
1809       return ((char *)keymap_names[i].name);
1810   return ((char *)NULL);
1811 }
1812   
1813 void
1814 rl_set_keymap (map)
1815      Keymap map;
1816 {
1817   if (map)
1818     _rl_keymap = map;
1819 }
1820
1821 Keymap
1822 rl_get_keymap ()
1823 {
1824   return (_rl_keymap);
1825 }
1826
1827 void
1828 rl_set_keymap_from_edit_mode ()
1829 {
1830   if (rl_editing_mode == emacs_mode)
1831     _rl_keymap = emacs_standard_keymap;
1832 #if defined (VI_MODE)
1833   else if (rl_editing_mode == vi_mode)
1834     _rl_keymap = vi_insertion_keymap;
1835 #endif /* VI_MODE */
1836 }
1837
1838 char *
1839 rl_get_keymap_name_from_edit_mode ()
1840 {
1841   if (rl_editing_mode == emacs_mode)
1842     return "emacs";
1843 #if defined (VI_MODE)
1844   else if (rl_editing_mode == vi_mode)
1845     return "vi";
1846 #endif /* VI_MODE */
1847   else
1848     return "none";
1849 }
1850
1851 /* **************************************************************** */
1852 /*                                                                  */
1853 /*                Key Binding and Function Information              */
1854 /*                                                                  */
1855 /* **************************************************************** */
1856
1857 /* Each of the following functions produces information about the
1858    state of keybindings and functions known to Readline.  The info
1859    is always printed to rl_outstream, and in such a way that it can
1860    be read back in (i.e., passed to rl_parse_and_bind ()). */
1861
1862 /* Print the names of functions known to Readline. */
1863 void
1864 rl_list_funmap_names ()
1865 {
1866   register int i;
1867   const char **funmap_names;
1868
1869   funmap_names = rl_funmap_names ();
1870
1871   if (!funmap_names)
1872     return;
1873
1874   for (i = 0; funmap_names[i]; i++)
1875     fprintf (rl_outstream, "%s\n", funmap_names[i]);
1876
1877   xfree (funmap_names);
1878 }
1879
1880 static char *
1881 _rl_get_keyname (key)
1882      int key;
1883 {
1884   char *keyname;
1885   int i, c;
1886
1887   keyname = (char *)xmalloc (8);
1888
1889   c = key;
1890   /* Since this is going to be used to write out keysequence-function
1891      pairs for possible inclusion in an inputrc file, we don't want to
1892      do any special meta processing on KEY. */
1893
1894 #if 1
1895   /* XXX - Experimental */
1896   /* We might want to do this, but the old version of the code did not. */
1897
1898   /* If this is an escape character, we don't want to do any more processing.
1899      Just add the special ESC key sequence and return. */
1900   if (c == ESC)
1901     {
1902       keyname[0] = '\\';
1903       keyname[1] = 'e';
1904       keyname[2] = '\0';
1905       return keyname;
1906     }
1907 #endif
1908
1909   /* RUBOUT is translated directly into \C-? */
1910   if (key == RUBOUT)
1911     {
1912       keyname[0] = '\\';
1913       keyname[1] = 'C';
1914       keyname[2] = '-';
1915       keyname[3] = '?';
1916       keyname[4] = '\0';
1917       return keyname;
1918     }
1919
1920   i = 0;
1921   /* Now add special prefixes needed for control characters.  This can
1922      potentially change C. */
1923   if (CTRL_CHAR (c))
1924     {
1925       keyname[i++] = '\\';
1926       keyname[i++] = 'C';
1927       keyname[i++] = '-';
1928       c = _rl_to_lower (UNCTRL (c));
1929     }
1930
1931   /* XXX experimental code.  Turn the characters that are not ASCII or
1932      ISO Latin 1 (128 - 159) into octal escape sequences (\200 - \237).
1933      This changes C. */
1934   if (c >= 128 && c <= 159)
1935     {
1936       keyname[i++] = '\\';
1937       keyname[i++] = '2';
1938       c -= 128;
1939       keyname[i++] = (c / 8) + '0';
1940       c = (c % 8) + '0';
1941     }
1942
1943   /* Now, if the character needs to be quoted with a backslash, do that. */
1944   if (c == '\\' || c == '"')
1945     keyname[i++] = '\\';
1946
1947   /* Now add the key, terminate the string, and return it. */
1948   keyname[i++] = (char) c;
1949   keyname[i] = '\0';
1950
1951   return keyname;
1952 }
1953
1954 /* Return a NULL terminated array of strings which represent the key
1955    sequences that are used to invoke FUNCTION in MAP. */
1956 char **
1957 rl_invoking_keyseqs_in_map (function, map)
1958      rl_command_func_t *function;
1959      Keymap map;
1960 {
1961   register int key;
1962   char **result;
1963   int result_index, result_size;
1964
1965   result = (char **)NULL;
1966   result_index = result_size = 0;
1967
1968   for (key = 0; key < KEYMAP_SIZE; key++)
1969     {
1970       switch (map[key].type)
1971         {
1972         case ISMACR:
1973           /* Macros match, if, and only if, the pointers are identical.
1974              Thus, they are treated exactly like functions in here. */
1975         case ISFUNC:
1976           /* If the function in the keymap is the one we are looking for,
1977              then add the current KEY to the list of invoking keys. */
1978           if (map[key].function == function)
1979             {
1980               char *keyname;
1981
1982               keyname = _rl_get_keyname (key);
1983
1984               if (result_index + 2 > result_size)
1985                 {
1986                   result_size += 10;
1987                   result = (char **)xrealloc (result, result_size * sizeof (char *));
1988                 }
1989
1990               result[result_index++] = keyname;
1991               result[result_index] = (char *)NULL;
1992             }
1993           break;
1994
1995         case ISKMAP:
1996           {
1997             char **seqs;
1998             register int i;
1999
2000             /* Find the list of keyseqs in this map which have FUNCTION as
2001                their target.  Add the key sequences found to RESULT. */
2002             if (map[key].function)
2003               seqs =
2004                 rl_invoking_keyseqs_in_map (function, FUNCTION_TO_KEYMAP (map, key));
2005             else
2006               break;
2007
2008             if (seqs == 0)
2009               break;
2010
2011             for (i = 0; seqs[i]; i++)
2012               {
2013                 char *keyname = (char *)xmalloc (6 + strlen (seqs[i]));
2014
2015                 if (key == ESC)
2016                   {
2017                     /* If ESC is the meta prefix and we're converting chars
2018                        with the eighth bit set to ESC-prefixed sequences, then
2019                        we can use \M-.  Otherwise we need to use the sequence
2020                        for ESC. */
2021                     if (_rl_convert_meta_chars_to_ascii && map[ESC].type == ISKMAP)
2022                       sprintf (keyname, "\\M-");
2023                     else
2024                       sprintf (keyname, "\\e");
2025                   }
2026                 else if (CTRL_CHAR (key))
2027                   sprintf (keyname, "\\C-%c", _rl_to_lower (UNCTRL (key)));
2028                 else if (key == RUBOUT)
2029                   sprintf (keyname, "\\C-?");
2030                 else if (key == '\\' || key == '"')
2031                   {
2032                     keyname[0] = '\\';
2033                     keyname[1] = (char) key;
2034                     keyname[2] = '\0';
2035                   }
2036                 else
2037                   {
2038                     keyname[0] = (char) key;
2039                     keyname[1] = '\0';
2040                   }
2041                 
2042                 strcat (keyname, seqs[i]);
2043                 xfree (seqs[i]);
2044
2045                 if (result_index + 2 > result_size)
2046                   {
2047                     result_size += 10;
2048                     result = (char **)xrealloc (result, result_size * sizeof (char *));
2049                   }
2050
2051                 result[result_index++] = keyname;
2052                 result[result_index] = (char *)NULL;
2053               }
2054
2055             xfree (seqs);
2056           }
2057           break;
2058         }
2059     }
2060   return (result);
2061 }
2062
2063 /* Return a NULL terminated array of strings which represent the key
2064    sequences that can be used to invoke FUNCTION using the current keymap. */
2065 char **
2066 rl_invoking_keyseqs (function)
2067      rl_command_func_t *function;
2068 {
2069   return (rl_invoking_keyseqs_in_map (function, _rl_keymap));
2070 }
2071
2072 /* Print all of the functions and their bindings to rl_outstream.  If
2073    PRINT_READABLY is non-zero, then print the output in such a way
2074    that it can be read back in. */
2075 void
2076 rl_function_dumper (print_readably)
2077      int print_readably;
2078 {
2079   register int i;
2080   const char **names;
2081   const char *name;
2082
2083   names = rl_funmap_names ();
2084
2085   fprintf (rl_outstream, "\n");
2086
2087   for (i = 0; name = names[i]; i++)
2088     {
2089       rl_command_func_t *function;
2090       char **invokers;
2091
2092       function = rl_named_function (name);
2093       invokers = rl_invoking_keyseqs_in_map (function, _rl_keymap);
2094
2095       if (print_readably)
2096         {
2097           if (!invokers)
2098             fprintf (rl_outstream, "# %s (not bound)\n", name);
2099           else
2100             {
2101               register int j;
2102
2103               for (j = 0; invokers[j]; j++)
2104                 {
2105                   fprintf (rl_outstream, "\"%s\": %s\n",
2106                            invokers[j], name);
2107                   xfree (invokers[j]);
2108                 }
2109
2110               xfree (invokers);
2111             }
2112         }
2113       else
2114         {
2115           if (!invokers)
2116             fprintf (rl_outstream, "%s is not bound to any keys\n",
2117                      name);
2118           else
2119             {
2120               register int j;
2121
2122               fprintf (rl_outstream, "%s can be found on ", name);
2123
2124               for (j = 0; invokers[j] && j < 5; j++)
2125                 {
2126                   fprintf (rl_outstream, "\"%s\"%s", invokers[j],
2127                            invokers[j + 1] ? ", " : ".\n");
2128                 }
2129
2130               if (j == 5 && invokers[j])
2131                 fprintf (rl_outstream, "...\n");
2132
2133               for (j = 0; invokers[j]; j++)
2134                 xfree (invokers[j]);
2135
2136               xfree (invokers);
2137             }
2138         }
2139     }
2140 }
2141
2142 /* Print all of the current functions and their bindings to
2143    rl_outstream.  If an explicit argument is given, then print
2144    the output in such a way that it can be read back in. */
2145 int
2146 rl_dump_functions (count, key)
2147      int count, key;
2148 {
2149   if (rl_dispatching)
2150     fprintf (rl_outstream, "\r\n");
2151   rl_function_dumper (rl_explicit_arg);
2152   rl_on_new_line ();
2153   return (0);
2154 }
2155
2156 static void
2157 _rl_macro_dumper_internal (print_readably, map, prefix)
2158      int print_readably;
2159      Keymap map;
2160      char *prefix;
2161 {
2162   register int key;
2163   char *keyname, *out;
2164   int prefix_len;
2165
2166   for (key = 0; key < KEYMAP_SIZE; key++)
2167     {
2168       switch (map[key].type)
2169         {
2170         case ISMACR:
2171           keyname = _rl_get_keyname (key);
2172           out = _rl_untranslate_macro_value ((char *)map[key].function);
2173
2174           if (print_readably)
2175             fprintf (rl_outstream, "\"%s%s\": \"%s\"\n", prefix ? prefix : "",
2176                                                          keyname,
2177                                                          out ? out : "");
2178           else
2179             fprintf (rl_outstream, "%s%s outputs %s\n", prefix ? prefix : "",
2180                                                         keyname,
2181                                                         out ? out : "");
2182           xfree (keyname);
2183           xfree (out);
2184           break;
2185         case ISFUNC:
2186           break;
2187         case ISKMAP:
2188           prefix_len = prefix ? strlen (prefix) : 0;
2189           if (key == ESC)
2190             {
2191               keyname = (char *)xmalloc (3 + prefix_len);
2192               if (prefix)
2193                 strcpy (keyname, prefix);
2194               keyname[prefix_len] = '\\';
2195               keyname[prefix_len + 1] = 'e';
2196               keyname[prefix_len + 2] = '\0';
2197             }
2198           else
2199             {
2200               keyname = _rl_get_keyname (key);
2201               if (prefix)
2202                 {
2203                   out = (char *)xmalloc (strlen (keyname) + prefix_len + 1);
2204                   strcpy (out, prefix);
2205                   strcpy (out + prefix_len, keyname);
2206                   xfree (keyname);
2207                   keyname = out;
2208                 }
2209             }
2210
2211           _rl_macro_dumper_internal (print_readably, FUNCTION_TO_KEYMAP (map, key), keyname);
2212           xfree (keyname);
2213           break;
2214         }
2215     }
2216 }
2217
2218 void
2219 rl_macro_dumper (print_readably)
2220      int print_readably;
2221 {
2222   _rl_macro_dumper_internal (print_readably, _rl_keymap, (char *)NULL);
2223 }
2224
2225 int
2226 rl_dump_macros (count, key)
2227      int count, key;
2228 {
2229   if (rl_dispatching)
2230     fprintf (rl_outstream, "\r\n");
2231   rl_macro_dumper (rl_explicit_arg);
2232   rl_on_new_line ();
2233   return (0);
2234 }
2235
2236 static char *
2237 _rl_get_string_variable_value (name)
2238      const char *name;
2239 {
2240   static char numbuf[32];
2241   char *ret;
2242
2243   if (_rl_stricmp (name, "bell-style") == 0)
2244     {
2245       switch (_rl_bell_preference)
2246         {
2247           case NO_BELL:
2248             return "none";
2249           case VISIBLE_BELL:
2250             return "visible";
2251           case AUDIBLE_BELL:
2252           default:
2253             return "audible";
2254         }
2255     }
2256   else if (_rl_stricmp (name, "comment-begin") == 0)
2257     return (_rl_comment_begin ? _rl_comment_begin : RL_COMMENT_BEGIN_DEFAULT);
2258   else if (_rl_stricmp (name, "completion-prefix-display-length") == 0)
2259     {
2260       sprintf (numbuf, "%d", _rl_completion_prefix_display_length);
2261       return (numbuf);
2262     }
2263   else if (_rl_stricmp (name, "completion-query-items") == 0)
2264     {
2265       sprintf (numbuf, "%d", rl_completion_query_items);
2266       return (numbuf);
2267     }
2268   else if (_rl_stricmp (name, "editing-mode") == 0)
2269     return (rl_get_keymap_name_from_edit_mode ());
2270   else if (_rl_stricmp (name, "history-size") == 0)
2271     {
2272       sprintf (numbuf, "%d", history_is_stifled() ? history_max_entries : 0);
2273       return (numbuf);
2274     }
2275   else if (_rl_stricmp (name, "isearch-terminators") == 0)
2276     {
2277       if (_rl_isearch_terminators == 0)
2278         return 0;
2279       ret = _rl_untranslate_macro_value (_rl_isearch_terminators);
2280       if (ret)
2281         {
2282           strncpy (numbuf, ret, sizeof (numbuf) - 1);
2283           xfree (ret);
2284           numbuf[sizeof(numbuf) - 1] = '\0';
2285         }
2286       else
2287         numbuf[0] = '\0';
2288       return numbuf;
2289     }
2290   else if (_rl_stricmp (name, "keymap") == 0)
2291     {
2292       ret = rl_get_keymap_name (_rl_keymap);
2293       if (ret == 0)
2294         ret = rl_get_keymap_name_from_edit_mode ();
2295       return (ret ? ret : "none");
2296     }
2297   else
2298     return (0);
2299 }
2300
2301 void
2302 rl_variable_dumper (print_readably)
2303      int print_readably;
2304 {
2305   int i;
2306   char *v;
2307
2308   for (i = 0; boolean_varlist[i].name; i++)
2309     {
2310       if (print_readably)
2311         fprintf (rl_outstream, "set %s %s\n", boolean_varlist[i].name,
2312                                *boolean_varlist[i].value ? "on" : "off");
2313       else
2314         fprintf (rl_outstream, "%s is set to `%s'\n", boolean_varlist[i].name,
2315                                *boolean_varlist[i].value ? "on" : "off");
2316     }
2317
2318   for (i = 0; string_varlist[i].name; i++)
2319     {
2320       v = _rl_get_string_variable_value (string_varlist[i].name);
2321       if (v == 0)       /* _rl_isearch_terminators can be NULL */
2322         continue;
2323       if (print_readably)
2324         fprintf (rl_outstream, "set %s %s\n", string_varlist[i].name, v);
2325       else
2326         fprintf (rl_outstream, "%s is set to `%s'\n", string_varlist[i].name, v);
2327     }
2328 }
2329
2330 /* Print all of the current variables and their values to
2331    rl_outstream.  If an explicit argument is given, then print
2332    the output in such a way that it can be read back in. */
2333 int
2334 rl_dump_variables (count, key)
2335      int count, key;
2336 {
2337   if (rl_dispatching)
2338     fprintf (rl_outstream, "\r\n");
2339   rl_variable_dumper (rl_explicit_arg);
2340   rl_on_new_line ();
2341   return (0);
2342 }
2343
2344 /* Return non-zero if any members of ARRAY are a substring in STRING. */
2345 static int
2346 substring_member_of_array (string, array)
2347      const char *string;
2348      const char * const *array;
2349 {
2350   while (*array)
2351     {
2352       if (_rl_strindex (string, *array))
2353         return (1);
2354       array++;
2355     }
2356   return (0);
2357 }