This commit was generated by cvs2svn to track changes on a CVS vendor
[external/binutils.git] / readline / bind.c
1 /* bind.c -- key binding and startup file support for the readline library. */
2
3 /* Copyright (C) 1987, 1989, 1992 Free Software Foundation, Inc.
4
5    This file is part of the GNU Readline Library, a library for
6    reading lines of text with interactive input and history editing.
7
8    The GNU Readline Library is free software; you can redistribute it
9    and/or modify it under the terms of the GNU General Public License
10    as published by the Free Software Foundation; either version 1, or
11    (at your option) any later version.
12
13    The GNU Readline Library is distributed in the hope that it will be
14    useful, but WITHOUT ANY WARRANTY; without even the implied warranty
15    of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    The GNU General Public License is often shipped with GNU software, and
19    is generally kept in a file called COPYING or LICENSE.  If you do not
20    have a copy of the license, write to the Free Software Foundation,
21    675 Mass Ave, Cambridge, MA 02139, USA. */
22
23 #include "sysdep.h"
24 #include <stdio.h>
25 #include <sys/types.h>
26 #include <fcntl.h>
27 #ifndef NO_SYS_FILE
28 #include <sys/file.h>
29 #endif
30
31 #include <errno.h>
32 /* Not all systems declare ERRNO in errno.h... and some systems #define it! */
33 #if !defined (errno)
34 extern int errno;
35 #endif /* !errno */
36
37 /* System-specific feature definitions and include files. */
38 #include "rldefs.h"
39
40 /* Some standard library routines. */
41 #include "readline.h"
42 #include "history.h"
43
44 #if !defined (strchr) && !defined (__STDC__)
45 extern char *strchr (), *strrchr ();
46 #endif /* !strchr && !__STDC__ */
47
48 extern char *tilde_expand ();
49
50 extern int _rl_horizontal_scroll_mode;
51 extern int _rl_mark_modified_lines;
52 extern int _rl_prefer_visible_bell;
53 extern int _rl_meta_flag;
54 extern int rl_blink_matching_paren;
55 extern int _rl_convert_meta_chars_to_ascii;
56 #if defined (VISIBLE_STATS)
57 extern int rl_visible_stats;
58 #endif /* VISIBLE_STATS */
59 extern int rl_complete_with_tilde_expansion;
60 extern int rl_completion_query_items;
61
62 extern int rl_explicit_arg;
63 extern int rl_editing_mode;
64 extern unsigned short _rl_parsing_conditionalized_out;
65 extern Keymap _rl_keymap;
66
67 extern char *possible_control_prefixes[], *possible_meta_prefixes[];
68
69 extern char **rl_funmap_names ();
70
71 static void rl_generic_bind ();
72 static int glean_key_from_name ();
73 static int stricmp (), strnicmp ();
74
75 #if defined (STATIC_MALLOC)
76 static char *xmalloc (), *xrealloc ();
77 #else
78 extern char *xmalloc (), *xrealloc ();
79 #endif /* STATIC_MALLOC */
80
81 /* **************************************************************** */
82 /*                                                                  */
83 /*                      Binding keys                                */
84 /*                                                                  */
85 /* **************************************************************** */
86
87 /* rl_add_defun (char *name, Function *function, int key)
88    Add NAME to the list of named functions.  Make FUNCTION be the function
89    that gets called.  If KEY is not -1, then bind it. */
90 rl_add_defun (name, function, key)
91      char *name;
92      Function *function;
93      int key;
94 {
95   if (key != -1)
96     rl_bind_key (key, function);
97   rl_add_funmap_entry (name, function);
98 }
99
100 /* Bind KEY to FUNCTION.  Returns non-zero if KEY is out of range. */
101 int
102 rl_bind_key (key, function)
103      int key;
104      Function *function;
105 {
106   if (key < 0)
107     return (key);
108
109   if (META_CHAR (key) && _rl_convert_meta_chars_to_ascii)
110     {
111       if (_rl_keymap[ESC].type == ISKMAP)
112         {
113           Keymap escmap = (Keymap)_rl_keymap[ESC].function;
114
115           key = UNMETA (key);
116           escmap[key].type = ISFUNC;
117           escmap[key].function = function;
118           return (0);
119         }
120       return (key);
121     }
122
123   _rl_keymap[key].type = ISFUNC;
124   _rl_keymap[key].function = function;
125   return (0);
126 }
127
128 /* Bind KEY to FUNCTION in MAP.  Returns non-zero in case of invalid
129    KEY. */
130 int
131 rl_bind_key_in_map (key, function, map)
132      int key;
133      Function *function;
134      Keymap map;
135 {
136   int result;
137   Keymap oldmap = _rl_keymap;
138
139   _rl_keymap = map;
140   result = rl_bind_key (key, function);
141   _rl_keymap = oldmap;
142   return (result);
143 }
144
145 /* Make KEY do nothing in the currently selected keymap.
146    Returns non-zero in case of error. */
147 int
148 rl_unbind_key (key)
149      int key;
150 {
151   return (rl_bind_key (key, (Function *)NULL));
152 }
153
154 /* Make KEY do nothing in MAP.
155    Returns non-zero in case of error. */
156 int
157 rl_unbind_key_in_map (key, map)
158      int key;
159      Keymap map;
160 {
161   return (rl_bind_key_in_map (key, (Function *)NULL, map));
162 }
163
164 /* Bind the key sequence represented by the string KEYSEQ to
165    FUNCTION.  This makes new keymaps as necessary.  The initial
166    place to do bindings is in MAP. */
167 rl_set_key (keyseq, function, map)
168      char *keyseq;
169      Function *function;
170      Keymap map;
171 {
172   rl_generic_bind (ISFUNC, keyseq, function, map);
173 }
174
175 /* Bind the key sequence represented by the string KEYSEQ to
176    the string of characters MACRO.  This makes new keymaps as
177    necessary.  The initial place to do bindings is in MAP. */
178 rl_macro_bind (keyseq, macro, map)
179      char *keyseq, *macro;
180      Keymap map;
181 {
182   char *macro_keys;
183   int macro_keys_len;
184
185   macro_keys = (char *)xmalloc ((2 * strlen (macro)) + 1);
186
187   if (rl_translate_keyseq (macro, macro_keys, &macro_keys_len))
188     {
189       free (macro_keys);
190       return;
191     }
192   rl_generic_bind (ISMACR, keyseq, macro_keys, map);
193 }
194
195 /* Bind the key sequence represented by the string KEYSEQ to
196    the arbitrary pointer DATA.  TYPE says what kind of data is
197    pointed to by DATA, right now this can be a function (ISFUNC),
198    a macro (ISMACR), or a keymap (ISKMAP).  This makes new keymaps
199    as necessary.  The initial place to do bindings is in MAP. */
200
201 static void
202 rl_generic_bind (type, keyseq, data, map)
203      int type;
204      char *keyseq, *data;
205      Keymap map;
206 {
207   char *keys;
208   int keys_len;
209   register int i;
210
211   /* If no keys to bind to, exit right away. */
212   if (!keyseq || !*keyseq)
213     {
214       if (type == ISMACR)
215         free (data);
216       return;
217     }
218
219   keys = (char *)alloca (1 + (2 * strlen (keyseq)));
220
221   /* Translate the ASCII representation of KEYSEQ into an array of
222      characters.  Stuff the characters into KEYS, and the length of
223      KEYS into KEYS_LEN. */
224   if (rl_translate_keyseq (keyseq, keys, &keys_len))
225     return;
226
227   /* Bind keys, making new keymaps as necessary. */
228   for (i = 0; i < keys_len; i++)
229     {
230       int ic = (int) ((unsigned char)keys[i]);
231
232       if (_rl_convert_meta_chars_to_ascii && META_CHAR (ic))
233         {
234           ic = UNMETA (ic);
235           if (map[ESC].type == ISKMAP)
236             map = (Keymap) map[ESC].function;
237         }
238
239       if ((i + 1) < keys_len)
240         {
241           if (map[ic].type != ISKMAP)
242             {
243               if (map[ic].type == ISMACR)
244                 free ((char *)map[ic].function);
245
246               map[ic].type = ISKMAP;
247               map[ic].function = (Function *)rl_make_bare_keymap ();
248             }
249           map = (Keymap)map[ic].function;
250         }
251       else
252         {
253           if (map[ic].type == ISMACR)
254             free ((char *)map[ic].function);
255
256           map[ic].function = (Function *)data;
257           map[ic].type = type;
258         }
259     }
260 }
261
262 /* Translate the ASCII representation of SEQ, stuffing the values into ARRAY,
263    an array of characters.  LEN gets the final length of ARRAY.  Return
264    non-zero if there was an error parsing SEQ. */
265 rl_translate_keyseq (seq, array, len)
266      char *seq, *array;
267      int *len;
268 {
269   register int i, c, l = 0;
270
271   for (i = 0; c = seq[i]; i++)
272     {
273       if (c == '\\')
274         {
275           c = seq[++i];
276
277           if (!c)
278             break;
279
280           if (((c == 'C' || c == 'M') &&  seq[i + 1] == '-') ||
281               (c == 'e'))
282             {
283               /* Handle special case of backwards define. */
284               if (strncmp (&seq[i], "C-\\M-", 5) == 0)
285                 {
286                   array[l++] = ESC;
287                   i += 5;
288                   array[l++] = CTRL (to_upper (seq[i]));
289                   if (!seq[i])
290                     i--;
291                   continue;
292                 }
293
294               switch (c)
295                 {
296                 case 'M':
297                   i++;
298                   array[l++] = ESC;
299                   break;
300
301                 case 'C':
302                   i += 2;
303                   /* Special hack for C-?... */
304                   if (seq[i] == '?')
305                     array[l++] = RUBOUT;
306                   else
307                     array[l++] = CTRL (to_upper (seq[i]));
308                   break;
309
310                 case 'e':
311                   array[l++] = ESC;
312                 }
313
314               continue;
315             }
316         }
317       array[l++] = c;
318     }
319
320   *len = l;
321   array[l] = '\0';
322   return (0);
323 }
324
325 /* Return a pointer to the function that STRING represents.
326    If STRING doesn't have a matching function, then a NULL pointer
327    is returned. */
328 Function *
329 rl_named_function (string)
330      char *string;
331 {
332   register int i;
333
334   rl_initialize_funmap ();
335
336   for (i = 0; funmap[i]; i++)
337     if (stricmp (funmap[i]->name, string) == 0)
338       return (funmap[i]->function);
339   return ((Function *)NULL);
340 }
341
342 /* Return the function (or macro) definition which would be invoked via
343    KEYSEQ if executed in MAP.  If MAP is NULL, then the current keymap is
344    used.  TYPE, if non-NULL, is a pointer to an int which will receive the
345    type of the object pointed to.  One of ISFUNC (function), ISKMAP (keymap),
346    or ISMACR (macro). */
347 Function *
348 rl_function_of_keyseq (keyseq, map, type)
349      char *keyseq;
350      Keymap map;
351      int *type;
352 {
353   register int i;
354
355   if (!map)
356     map = _rl_keymap;
357
358   for (i = 0; keyseq && keyseq[i]; i++)
359     {
360       int ic = keyseq[i];
361
362       if (META_CHAR (ic) && _rl_convert_meta_chars_to_ascii)
363         {
364           if (map[ESC].type != ISKMAP)
365             {
366               if (type)
367                 *type = map[ESC].type;
368
369               return (map[ESC].function);
370             }
371           else
372             {
373               map = (Keymap)map[ESC].function;
374               ic = UNMETA (ic);
375             }
376         }
377
378       if (map[ic].type == ISKMAP)
379         {
380           /* If this is the last key in the key sequence, return the
381              map. */
382           if (!keyseq[i + 1])
383             {
384               if (type)
385                 *type = ISKMAP;
386
387               return (map[ic].function);
388             }
389           else
390             map = (Keymap)map[ic].function;
391         }
392       else
393         {
394           if (type)
395             *type = map[ic].type;
396
397           return (map[ic].function);
398         }
399     }
400 }
401
402 /* The last key bindings file read. */
403 static char *last_readline_init_file = (char *)NULL;
404
405 /* Re-read the current keybindings file. */
406 rl_re_read_init_file (count, ignore)
407      int count, ignore;
408 {
409   rl_read_init_file ((char *)NULL);
410 }
411
412 /* The final, last-ditch effort file name for an init file. */
413 #ifdef __MSDOS__
414 /* Don't know what to do, but this is a guess */
415 #define DEFAULT_INPUTRC "/INPUTRC";
416 #else
417 #define DEFAULT_INPUTRC "~/.inputrc"
418 #endif
419
420 /* Do key bindings from a file.  If FILENAME is NULL it defaults
421    to `~/.inputrc'.  If the file existed and could be opened and
422    read, 0 is returned, otherwise errno is returned. */
423 int
424 rl_read_init_file (filename)
425      char *filename;
426 {
427   register int i;
428   char *buffer, *openname, *line, *end;
429   struct stat finfo;
430   int file;
431
432   /* Default the filename. */
433   if (!filename)
434     {
435       if (last_readline_init_file)
436         filename = last_readline_init_file;
437       else
438         filename = DEFAULT_INPUTRC;
439     }
440
441   openname = tilde_expand (filename);
442
443   if (!openname || *openname == '\000')
444     return ENOENT;
445
446   if ((stat (openname, &finfo) < 0) ||
447       (file = open (openname, O_RDONLY, 0666)) < 0)
448     {
449       free (openname);
450       return (errno);
451     }
452   else
453     free (openname);
454
455   if (last_readline_init_file)
456     free (last_readline_init_file);
457
458   last_readline_init_file = savestring (filename);
459
460   /* Read the file into BUFFER. */
461   buffer = (char *)xmalloc ((int)finfo.st_size + 1);
462   i = read (file, buffer, finfo.st_size);
463   close (file);
464
465   if (i != finfo.st_size)
466     return (errno);
467
468   /* Loop over the lines in the file.  Lines that start with `#' are
469      comments; all other lines are commands for readline initialization. */
470   line = buffer;
471   end = buffer + finfo.st_size;
472   while (line < end)
473     {
474       /* Find the end of this line. */
475       for (i = 0; line + i != end && line[i] != '\n'; i++);
476
477       /* Mark end of line. */
478       line[i] = '\0';
479
480       /* If the line is not a comment, then parse it. */
481       if (*line && *line != '#')
482         rl_parse_and_bind (line);
483
484       /* Move to the next line. */
485       line += i + 1;
486     }
487   free (buffer);
488   return (0);
489 }
490
491 /* **************************************************************** */
492 /*                                                                  */
493 /*                      Parser Directives                           */
494 /*                                                                  */
495 /* **************************************************************** */
496
497 /* Conditionals. */
498
499 /* Calling programs set this to have their argv[0]. */
500 char *rl_readline_name = "other";
501
502 /* Stack of previous values of parsing_conditionalized_out. */
503 static unsigned char *if_stack = (unsigned char *)NULL;
504 static int if_stack_depth = 0;
505 static int if_stack_size = 0;
506
507 /* Push _rl_parsing_conditionalized_out, and set parser state based
508    on ARGS. */
509 static int
510 parser_if (args)
511      char *args;
512 {
513   register int i;
514
515   /* Push parser state. */
516   if (if_stack_depth + 1 >= if_stack_size)
517     {
518       if (!if_stack)
519         if_stack = (unsigned char *)xmalloc (if_stack_size = 20);
520       else
521         if_stack = (unsigned char *)xrealloc (if_stack, if_stack_size += 20);
522     }
523   if_stack[if_stack_depth++] = _rl_parsing_conditionalized_out;
524
525   /* If parsing is turned off, then nothing can turn it back on except
526      for finding the matching endif.  In that case, return right now. */
527   if (_rl_parsing_conditionalized_out)
528     return 0;
529
530   /* Isolate first argument. */
531   for (i = 0; args[i] && !whitespace (args[i]); i++);
532
533   if (args[i])
534     args[i++] = '\0';
535
536   /* Handle "if term=foo" and "if mode=emacs" constructs.  If this
537      isn't term=foo, or mode=emacs, then check to see if the first
538      word in ARGS is the same as the value stored in rl_readline_name. */
539   if (rl_terminal_name && strnicmp (args, "term=", 5) == 0)
540     {
541       char *tem, *tname;
542
543       /* Terminals like "aaa-60" are equivalent to "aaa". */
544       tname = savestring (rl_terminal_name);
545       tem = (char*) strrchr (tname, '-');
546       if (tem)
547         *tem = '\0';
548
549       /* Test the `long' and `short' forms of the terminal name so that
550          if someone has a `sun-cmd' and does not want to have bindings
551          that will be executed if the terminal is a `sun', they can put
552          `$if term=sun-cmd' into their .inputrc. */
553       if ((stricmp (args + 5, tname) == 0) ||
554           (stricmp (args + 5, rl_terminal_name) == 0))
555         _rl_parsing_conditionalized_out = 0;
556       else
557         _rl_parsing_conditionalized_out = 1;
558
559       free (tname);
560     }
561 #if defined (VI_MODE)
562   else if (strnicmp (args, "mode=", 5) == 0)
563     {
564       int mode;
565
566       if (stricmp (args + 5, "emacs") == 0)
567         mode = emacs_mode;
568       else if (stricmp (args + 5, "vi") == 0)
569         mode = vi_mode;
570       else
571         mode = no_mode;
572
573       if (mode == rl_editing_mode)
574         _rl_parsing_conditionalized_out = 0;
575       else
576         _rl_parsing_conditionalized_out = 1;
577     }
578 #endif /* VI_MODE */
579   /* Check to see if the first word in ARGS is the same as the
580      value stored in rl_readline_name. */
581   else if (stricmp (args, rl_readline_name) == 0)
582     _rl_parsing_conditionalized_out = 0;
583   else
584     _rl_parsing_conditionalized_out = 1;
585   return 0;
586 }
587
588 /* Invert the current parser state if there is anything on the stack. */
589 static int
590 parser_else (args)
591      char *args;
592 {
593   register int i;
594
595   if (!if_stack_depth)
596     {
597       /* Error message? */
598       return 0;
599     }
600
601   /* Check the previous (n - 1) levels of the stack to make sure that
602      we haven't previously turned off parsing. */
603   for (i = 0; i < if_stack_depth - 1; i++)
604     if (if_stack[i] == 1)
605       return 0;
606
607   /* Invert the state of parsing if at top level. */
608   _rl_parsing_conditionalized_out = !_rl_parsing_conditionalized_out;
609   return 0;
610 }
611
612 /* Terminate a conditional, popping the value of
613    _rl_parsing_conditionalized_out from the stack. */
614 static int
615 parser_endif (args)
616      char *args;
617 {
618   if (if_stack_depth)
619     _rl_parsing_conditionalized_out = if_stack[--if_stack_depth];
620   else
621     {
622       /* *** What, no error message? *** */
623     }
624   return 0;
625 }
626
627 /* Associate textual names with actual functions. */
628 static struct {
629   char *name;
630   Function *function;
631 } parser_directives [] = {
632   { "if", parser_if },
633   { "endif", parser_endif },
634   { "else", parser_else },
635   { (char *)0x0, (Function *)0x0 }
636 };
637
638 /* Handle a parser directive.  STATEMENT is the line of the directive
639    without any leading `$'. */
640 static int
641 handle_parser_directive (statement)
642      char *statement;
643 {
644   register int i;
645   char *directive, *args;
646
647   /* Isolate the actual directive. */
648
649   /* Skip whitespace. */
650   for (i = 0; whitespace (statement[i]); i++);
651
652   directive = &statement[i];
653
654   for (; statement[i] && !whitespace (statement[i]); i++);
655
656   if (statement[i])
657     statement[i++] = '\0';
658
659   for (; statement[i] && whitespace (statement[i]); i++);
660
661   args = &statement[i];
662
663   /* Lookup the command, and act on it. */
664   for (i = 0; parser_directives[i].name; i++)
665     if (stricmp (directive, parser_directives[i].name) == 0)
666       {
667         (*parser_directives[i].function) (args);
668         return (0);
669       }
670
671   /* *** Should an error message be output? */
672   return (1);
673 }
674
675 /* Ugly but working hack for binding prefix meta. */
676 #define PREFIX_META_HACK
677
678 static int substring_member_of_array ();
679
680 /* Read the binding command from STRING and perform it.
681    A key binding command looks like: Keyname: function-name\0,
682    a variable binding command looks like: set variable value.
683    A new-style keybinding looks like "\C-x\C-x": exchange-point-and-mark. */
684 rl_parse_and_bind (string)
685      char *string;
686 {
687   char *funname, *kname;
688   register int c, i;
689   int key, equivalency;
690
691   while (string && whitespace (*string))
692     string++;
693
694   if (!string || !*string || *string == '#')
695     return;
696
697   /* If this is a parser directive, act on it. */
698   if (*string == '$')
699     {
700       handle_parser_directive (&string[1]);
701       return;
702     }
703
704   /* If we aren't supposed to be parsing right now, then we're done. */
705   if (_rl_parsing_conditionalized_out)
706     return;
707
708   i = 0;
709   /* If this keyname is a complex key expression surrounded by quotes,
710      advance to after the matching close quote.  This code allows the
711      backslash to quote characters in the key expression. */
712   if (*string == '"')
713     {
714       int passc = 0;
715
716       for (i = 1; c = string[i]; i++)
717         {
718           if (passc)
719             {
720               passc = 0;
721               continue;
722             }
723
724           if (c == '\\')
725             {
726               passc++;
727               continue;
728             }
729
730           if (c == '"')
731             break;
732         }
733     }
734
735   /* Advance to the colon (:) or whitespace which separates the two objects. */
736   for (; (c = string[i]) && c != ':' && c != ' ' && c != '\t'; i++ );
737
738   equivalency = (c == ':' && string[i + 1] == '=');
739
740   /* Mark the end of the command (or keyname). */
741   if (string[i])
742     string[i++] = '\0';
743
744   /* If doing assignment, skip the '=' sign as well. */
745   if (equivalency)
746     string[i++] = '\0';
747
748   /* If this is a command to set a variable, then do that. */
749   if (stricmp (string, "set") == 0)
750     {
751       char *var = string + i;
752       char *value;
753
754       /* Make VAR point to start of variable name. */
755       while (*var && whitespace (*var)) var++;
756
757       /* Make value point to start of value string. */
758       value = var;
759       while (*value && !whitespace (*value)) value++;
760       if (*value)
761         *value++ = '\0';
762       while (*value && whitespace (*value)) value++;
763
764       rl_variable_bind (var, value);
765       return;
766     }
767
768   /* Skip any whitespace between keyname and funname. */
769   for (; string[i] && whitespace (string[i]); i++);
770   funname = &string[i];
771
772   /* Now isolate funname.
773      For straight function names just look for whitespace, since
774      that will signify the end of the string.  But this could be a
775      macro definition.  In that case, the string is quoted, so skip
776      to the matching delimiter.  We allow the backslash to quote the
777      delimiter characters in the macro body. */
778   /* This code exists to allow whitespace in macro expansions, which
779      would otherwise be gobbled up by the next `for' loop.*/
780   /* XXX - it may be desirable to allow backslash quoting only if " is
781      the quoted string delimiter, like the shell. */
782   if (*funname == '\'' || *funname == '"')
783     {
784       int delimiter = string[i++];
785       int passc = 0;
786
787       for (; c = string[i]; i++)
788         {
789           if (passc)
790             {
791               passc = 0;
792               continue;
793             }
794
795           if (c == '\\')
796             {
797               passc = 1;
798               continue;
799             }
800
801           if (c == delimiter)
802             break;
803         }
804       if (c)
805         i++;
806     }
807
808   /* Advance to the end of the string.  */
809   for (; string[i] && !whitespace (string[i]); i++);
810
811   /* No extra whitespace at the end of the string. */
812   string[i] = '\0';
813
814   /* Handle equivalency bindings here.  Make the left-hand side be exactly
815      whatever the right-hand evaluates to, including keymaps. */
816   if (equivalency)
817     {
818       return;
819     }
820
821   /* If this is a new-style key-binding, then do the binding with
822      rl_set_key ().  Otherwise, let the older code deal with it. */
823   if (*string == '"')
824     {
825       char *seq = (char *)alloca (1 + strlen (string));
826       register int j, k = 0;
827       int passc = 0;
828
829       for (j = 1; string[j]; j++)
830         {
831           /* Allow backslash to quote characters, but leave them in place.
832              This allows a string to end with a backslash quoting another
833              backslash, or with a backslash quoting a double quote.  The
834              backslashes are left in place for rl_translate_keyseq (). */
835           if (passc || (string[j] == '\\'))
836             {
837               seq[k++] = string[j];
838               passc = !passc;
839               continue;
840             }
841
842           if (string[j] == '"')
843             break;
844
845           seq[k++] = string[j];
846         }
847       seq[k] = '\0';
848
849       /* Binding macro? */
850       if (*funname == '\'' || *funname == '"')
851         {
852           j = strlen (funname);
853
854           /* Remove the delimiting quotes from each end of FUNNAME. */
855           if (j && funname[j - 1] == *funname)
856             funname[j - 1] = '\0';
857
858           rl_macro_bind (seq, &funname[1], _rl_keymap);
859         }
860       else
861         rl_set_key (seq, rl_named_function (funname), _rl_keymap);
862
863       return;
864     }
865
866   /* Get the actual character we want to deal with. */
867   kname = (char*) strrchr (string, '-');
868   if (!kname)
869     kname = string;
870   else
871     kname++;
872
873   key = glean_key_from_name (kname);
874
875   /* Add in control and meta bits. */
876   if (substring_member_of_array (string, possible_control_prefixes))
877     key = CTRL (to_upper (key));
878
879   if (substring_member_of_array (string, possible_meta_prefixes))
880     key = META (key);
881
882   /* Temporary.  Handle old-style keyname with macro-binding. */
883   if (*funname == '\'' || *funname == '"')
884     {
885       char seq[2];
886       int fl = strlen (funname);
887
888       seq[0] = key; seq[1] = '\0';
889       if (fl && funname[fl - 1] == *funname)
890         funname[fl - 1] = '\0';
891
892       rl_macro_bind (seq, &funname[1], _rl_keymap);
893     }
894 #if defined (PREFIX_META_HACK)
895   /* Ugly, but working hack to keep prefix-meta around. */
896   else if (stricmp (funname, "prefix-meta") == 0)
897     {
898       char seq[2];
899
900       seq[0] = key;
901       seq[1] = '\0';
902       rl_generic_bind (ISKMAP, seq, (char *)emacs_meta_keymap, _rl_keymap);
903     }
904 #endif /* PREFIX_META_HACK */
905   else
906     rl_bind_key (key, rl_named_function (funname));
907 }
908
909 /* Simple structure for boolean readline variables (i.e., those that can
910    have one of two values; either "On" or 1 for truth, or "Off" or 0 for
911    false. */
912
913 static struct {
914   char *name;
915   int *value;
916 } boolean_varlist [] = {
917   { "horizontal-scroll-mode",   &_rl_horizontal_scroll_mode },
918   { "mark-modified-lines",      &_rl_mark_modified_lines },
919   { "prefer-visible-bell",      &_rl_prefer_visible_bell },
920   { "meta-flag",                &_rl_meta_flag },
921   { "blink-matching-paren",     &rl_blink_matching_paren },
922   { "convert-meta",             &_rl_convert_meta_chars_to_ascii },
923 #if defined (VISIBLE_STATS)
924   { "visible-stats",            &rl_visible_stats },
925 #endif /* VISIBLE_STATS */
926   { "expand-tilde",             &rl_complete_with_tilde_expansion },
927   { (char *)NULL, (int *)NULL }
928 };
929
930 rl_variable_bind (name, value)
931      char *name, *value;
932 {
933   register int i;
934
935   /* Check for simple variables first. */
936   for (i = 0; boolean_varlist[i].name; i++)
937     {
938       if (stricmp (name, boolean_varlist[i].name) == 0)
939         {
940           /* A variable is TRUE if the "value" is "on", "1" or "". */
941           if ((!*value) ||
942               (stricmp (value, "On") == 0) ||
943               (value[0] == '1' && value[1] == '\0'))
944             *boolean_varlist[i].value = 1;
945           else
946             *boolean_varlist[i].value = 0;
947           return;
948         }
949     }
950
951   /* Not a boolean variable, so check for specials. */
952
953   /* Editing mode change? */
954   if (stricmp (name, "editing-mode") == 0)
955     {
956       if (strnicmp (value, "vi", 2) == 0)
957         {
958 #if defined (VI_MODE)
959           _rl_keymap = vi_insertion_keymap;
960           rl_editing_mode = vi_mode;
961 #else
962 #if defined (NOTDEF)
963           /* What state is the terminal in?  I'll tell you:
964              non-determinate!  That means we cannot do any output. */
965           ding ();
966 #endif /* NOTDEF */
967 #endif /* VI_MODE */
968         }
969       else if (strnicmp (value, "emacs", 5) == 0)
970         {
971           _rl_keymap = emacs_standard_keymap;
972           rl_editing_mode = emacs_mode;
973         }
974     }
975
976   /* Comment string change? */
977   else if (stricmp (name, "comment-begin") == 0)
978     {
979 #if defined (VI_MODE)
980       extern char *rl_vi_comment_begin;
981
982       if (*value)
983         {
984           if (rl_vi_comment_begin)
985             free (rl_vi_comment_begin);
986
987           rl_vi_comment_begin = savestring (value);
988         }
989 #endif /* VI_MODE */
990     }
991   else if (stricmp (name, "completion-query-items") == 0)
992     {
993       int nval = 100;
994       if (*value)
995         {
996           nval = atoi (value);
997           if (nval < 0)
998             nval = 0;
999         }
1000       rl_completion_query_items = nval;
1001     }
1002 }
1003
1004 /* Return the character which matches NAME.
1005    For example, `Space' returns ' '. */
1006
1007 typedef struct {
1008   char *name;
1009   int value;
1010 } assoc_list;
1011
1012 static assoc_list name_key_alist[] = {
1013   { "DEL", 0x7f },
1014   { "ESC", '\033' },
1015   { "Escape", '\033' },
1016   { "LFD", '\n' },
1017   { "Newline", '\n' },
1018   { "RET", '\r' },
1019   { "Return", '\r' },
1020   { "Rubout", 0x7f },
1021   { "SPC", ' ' },
1022   { "Space", ' ' },
1023   { "Tab", 0x09 },
1024   { (char *)0x0, 0 }
1025 };
1026
1027 static int
1028 glean_key_from_name (name)
1029      char *name;
1030 {
1031   register int i;
1032
1033   for (i = 0; name_key_alist[i].name; i++)
1034     if (stricmp (name, name_key_alist[i].name) == 0)
1035       return (name_key_alist[i].value);
1036
1037   return (*(unsigned char *)name);      /* XXX was return (*name) */
1038 }
1039
1040 /* Auxiliary functions to manage keymaps. */
1041 static struct {
1042   char *name;
1043   Keymap map;
1044 } keymap_names[] = {
1045   { "emacs", emacs_standard_keymap },
1046   { "emacs-standard", emacs_standard_keymap },
1047   { "emacs-meta", emacs_meta_keymap },
1048   { "emacs-ctlx", emacs_ctlx_keymap },
1049 #if defined (VI_MODE)
1050   { "vi", vi_movement_keymap },
1051   { "vi-move", vi_movement_keymap },
1052   { "vi-command", vi_movement_keymap },
1053   { "vi-insert", vi_insertion_keymap },
1054 #endif /* VI_MODE */
1055   { (char *)0x0, (Keymap)0x0 }
1056 };
1057
1058 Keymap
1059 rl_get_keymap_by_name (name)
1060      char *name;
1061 {
1062   register int i;
1063
1064   for (i = 0; keymap_names[i].name; i++)
1065     if (strcmp (name, keymap_names[i].name) == 0)
1066       return (keymap_names[i].map);
1067   return ((Keymap) NULL);
1068 }
1069
1070 void
1071 rl_set_keymap (map)
1072      Keymap map;
1073 {
1074   if (map)
1075     _rl_keymap = map;
1076 }
1077
1078 Keymap
1079 rl_get_keymap ()
1080 {
1081   return (_rl_keymap);
1082 }
1083
1084 void
1085 rl_set_keymap_from_edit_mode ()
1086 {
1087   if (rl_editing_mode == emacs_mode)
1088     _rl_keymap = emacs_standard_keymap;
1089   else if (rl_editing_mode == vi_mode)
1090     _rl_keymap = vi_insertion_keymap;
1091 }
1092 \f
1093 /* **************************************************************** */
1094 /*                                                                  */
1095 /*                Key Binding and Function Information              */
1096 /*                                                                  */
1097 /* **************************************************************** */
1098
1099 /* Each of the following functions produces information about the
1100    state of keybindings and functions known to Readline.  The info
1101    is always printed to rl_outstream, and in such a way that it can
1102    be read back in (i.e., passed to rl_parse_and_bind (). */
1103
1104 /* Print the names of functions known to Readline. */
1105 void
1106 rl_list_funmap_names (ignore)
1107      int ignore;
1108 {
1109   register int i;
1110   char **funmap_names;
1111
1112   funmap_names = rl_funmap_names ();
1113
1114   if (!funmap_names)
1115     return;
1116
1117   for (i = 0; funmap_names[i]; i++)
1118     fprintf (rl_outstream, "%s\n", funmap_names[i]);
1119
1120   free (funmap_names);
1121 }
1122
1123 /* Return a NULL terminated array of strings which represent the key
1124    sequences that are used to invoke FUNCTION in MAP. */
1125 static char **
1126 invoking_keyseqs_in_map (function, map)
1127      Function *function;
1128      Keymap map;
1129 {
1130   register int key;
1131   char **result;
1132   int result_index, result_size;
1133
1134   result = (char **)NULL;
1135   result_index = result_size = 0;
1136
1137   for (key = 0; key < 128; key++)
1138     {
1139       switch (map[key].type)
1140         {
1141         case ISMACR:
1142           /* Macros match, if, and only if, the pointers are identical.
1143              Thus, they are treated exactly like functions in here. */
1144         case ISFUNC:
1145           /* If the function in the keymap is the one we are looking for,
1146              then add the current KEY to the list of invoking keys. */
1147           if (map[key].function == function)
1148             {
1149               char *keyname = (char *)xmalloc (5);
1150
1151               if (CTRL_P (key))
1152                 sprintf (keyname, "\\C-%c", to_lower (UNCTRL (key)));
1153               else if (key == RUBOUT)
1154                 sprintf (keyname, "\\C-?");
1155               else if (key == '\\' || key == '"')
1156                 {
1157                   keyname[0] = '\\';
1158                   keyname[1] = (char) key;
1159                   keyname[2] = '\0';
1160                 }
1161               else
1162                 {
1163                   keyname[0] = (char) key;
1164                   keyname[1] = '\0';
1165                 }
1166
1167               if (result_index + 2 > result_size)
1168                 result = (char **) xrealloc
1169                   (result, (result_size += 10) * sizeof (char *));
1170
1171               result[result_index++] = keyname;
1172               result[result_index] = (char *)NULL;
1173             }
1174           break;
1175
1176         case ISKMAP:
1177           {
1178             char **seqs = (char **)NULL;
1179
1180             /* Find the list of keyseqs in this map which have FUNCTION as
1181                their target.  Add the key sequences found to RESULT. */
1182             if (map[key].function)
1183               seqs =
1184                 invoking_keyseqs_in_map (function, (Keymap)map[key].function);
1185
1186             if (seqs)
1187               {
1188                 register int i;
1189
1190                 for (i = 0; seqs[i]; i++)
1191                   {
1192                     char *keyname = (char *)xmalloc (6 + strlen (seqs[i]));
1193
1194                     if (key == ESC)
1195                       sprintf (keyname, "\\e");
1196                     else if (CTRL_P (key))
1197                       sprintf (keyname, "\\C-%c", to_lower (UNCTRL (key)));
1198                     else if (key == RUBOUT)
1199                       sprintf (keyname, "\\C-?");
1200                     else if (key == '\\' || key == '"')
1201                       {
1202                         keyname[0] = '\\';
1203                         keyname[1] = (char) key;
1204                         keyname[2] = '\0';
1205                       }
1206                     else
1207                       {
1208                         keyname[0] = (char) key;
1209                         keyname[1] = '\0';
1210                       }
1211
1212                     strcat (keyname, seqs[i]);
1213
1214                     if (result_index + 2 > result_size)
1215                       result = (char **) xrealloc
1216                         (result, (result_size += 10) * sizeof (char *));
1217
1218                     result[result_index++] = keyname;
1219                     result[result_index] = (char *)NULL;
1220                   }
1221               }
1222           }
1223           break;
1224         }
1225     }
1226   return (result);
1227 }
1228
1229 /* Return a NULL terminated array of strings which represent the key
1230    sequences that can be used to invoke FUNCTION using the current keymap. */
1231 char **
1232 rl_invoking_keyseqs (function)
1233      Function *function;
1234 {
1235   return (invoking_keyseqs_in_map (function, _rl_keymap));
1236 }
1237
1238 /* Print all of the current functions and their bindings to
1239    rl_outstream.  If an explicit argument is given, then print
1240    the output in such a way that it can be read back in. */
1241 int
1242 rl_dump_functions (count)
1243      int count;
1244 {
1245   void rl_function_dumper ();
1246
1247   rl_function_dumper (rl_explicit_arg);
1248   rl_on_new_line ();
1249   return (0);
1250 }
1251
1252 /* Print all of the functions and their bindings to rl_outstream.  If
1253    PRINT_READABLY is non-zero, then print the output in such a way
1254    that it can be read back in. */
1255 void
1256 rl_function_dumper (print_readably)
1257      int print_readably;
1258 {
1259   register int i;
1260   char **names;
1261   char *name;
1262
1263   names = rl_funmap_names ();
1264
1265   fprintf (rl_outstream, "\n");
1266
1267   for (i = 0; name = names[i]; i++)
1268     {
1269       Function *function;
1270       char **invokers;
1271
1272       function = rl_named_function (name);
1273       invokers = invoking_keyseqs_in_map (function, _rl_keymap);
1274
1275       if (print_readably)
1276         {
1277           if (!invokers)
1278             fprintf (rl_outstream, "# %s (not bound)\n", name);
1279           else
1280             {
1281               register int j;
1282
1283               for (j = 0; invokers[j]; j++)
1284                 {
1285                   fprintf (rl_outstream, "\"%s\": %s\n",
1286                            invokers[j], name);
1287                   free (invokers[j]);
1288                 }
1289
1290               free (invokers);
1291             }
1292         }
1293       else
1294         {
1295           if (!invokers)
1296             fprintf (rl_outstream, "%s is not bound to any keys\n",
1297                      name);
1298           else
1299             {
1300               register int j;
1301
1302               fprintf (rl_outstream, "%s can be found on ", name);
1303
1304               for (j = 0; invokers[j] && j < 5; j++)
1305                 {
1306                   fprintf (rl_outstream, "\"%s\"%s", invokers[j],
1307                            invokers[j + 1] ? ", " : ".\n");
1308                 }
1309
1310               if (j == 5 && invokers[j])
1311                 fprintf (rl_outstream, "...\n");
1312
1313               for (j = 0; invokers[j]; j++)
1314                 free (invokers[j]);
1315
1316               free (invokers);
1317             }
1318         }
1319     }
1320 }
1321
1322 \f
1323 /* **************************************************************** */
1324 /*                                                                  */
1325 /*                      String Utility Functions                    */
1326 /*                                                                  */
1327 /* **************************************************************** */
1328
1329 static char *strindex ();
1330
1331 /* Return non-zero if any members of ARRAY are a substring in STRING. */
1332 static int
1333 substring_member_of_array (string, array)
1334      char *string, **array;
1335 {
1336   while (*array)
1337     {
1338       if (strindex (string, *array))
1339         return (1);
1340       array++;
1341     }
1342   return (0);
1343 }
1344
1345 /* Whoops, Unix doesn't have strnicmp. */
1346
1347 /* Compare at most COUNT characters from string1 to string2.  Case
1348    doesn't matter. */
1349 static int
1350 strnicmp (string1, string2, count)
1351      char *string1, *string2;
1352 {
1353   register char ch1, ch2;
1354
1355   while (count)
1356     {
1357       ch1 = *string1++;
1358       ch2 = *string2++;
1359       if (to_upper(ch1) == to_upper(ch2))
1360         count--;
1361       else break;
1362     }
1363   return (count);
1364 }
1365
1366 /* strcmp (), but caseless. */
1367 static int
1368 stricmp (string1, string2)
1369      char *string1, *string2;
1370 {
1371   register char ch1, ch2;
1372
1373   while (*string1 && *string2)
1374     {
1375       ch1 = *string1++;
1376       ch2 = *string2++;
1377       if (to_upper(ch1) != to_upper(ch2))
1378         return (1);
1379     }
1380   return (*string1 | *string2);
1381 }
1382
1383 /* Determine if s2 occurs in s1.  If so, return a pointer to the
1384    match in s1.  The compare is case insensitive. */
1385 static char *
1386 strindex (s1, s2)
1387      register char *s1, *s2;
1388 {
1389   register int i, l = strlen (s2);
1390   register int len = strlen (s1);
1391
1392   for (i = 0; (len - i) >= l; i++)
1393     if (strnicmp (&s1[i], s2, l) == 0)
1394       return (s1 + i);
1395   return ((char *)NULL);
1396 }