Add the DragonFly cvs id and perform general cleanups on cvs/rcs/sccs ids. Most
[dragonfly.git] / lib / libedit / key.c
1 /*-
2  * Copyright (c) 1992, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Christos Zoulas of Cornell University.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *      This product includes software developed by the University of
19  *      California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  * @(#)key.c    8.1 (Berkeley) 6/4/93
37  */
38
39 /*
40  * key.c: This module contains the procedures for maintaining
41  *        the extended-key map.
42  *
43  *      An extended-key (key) is a sequence of keystrokes introduced
44  *      with an sequence introducer and consisting of an arbitrary
45  *      number of characters.  This module maintains a map (the el->el_key.map)
46  *      to convert these extended-key sequences into input strs
47  *      (XK_STR), editor functions (XK_CMD), or unix commands (XK_EXE).
48  *
49  *      Warning:
50  *        If key is a substr of some other keys, then the longer
51  *        keys are lost!!  That is, if the keys "abcd" and "abcef"
52  *        are in el->el_key.map, adding the key "abc" will cause the first two
53  *        definitions to be lost.
54  *
55  *      Restrictions:
56  *      -------------
57  *      1) It is not possible to have one key that is a
58  *         substr of another.
59  */
60 #include "sys.h"
61 #include <string.h>
62 #include <stdlib.h>
63
64 #include "el.h"
65
66 /*
67  * The Nodes of the el->el_key.map.  The el->el_key.map is a linked list
68  * of these node elements
69  */
70 struct key_node_t {
71     char        ch;             /* single character of key              */
72     int         type;           /* node type                            */
73     key_value_t val;            /* command code or pointer to str,      */
74                                 /* if this is a leaf                    */
75     struct key_node_t *next;    /* ptr to next char of this key         */
76     struct key_node_t *sibling; /* ptr to another key with same prefix  */
77 };
78
79 private int            node_trav        __P((EditLine *, key_node_t *, char *,
80                                              key_value_t *));
81 private int            node__try        __P((key_node_t *, char *,
82                                              key_value_t *, int));
83 private key_node_t    *node__get        __P((int));
84 private void           node__put        __P((key_node_t *));
85 private int            node__delete     __P((key_node_t **, char *));
86 private int            node_lookup      __P((EditLine *, char *, key_node_t *,
87                                              int));
88 private int            node_enum        __P((EditLine *, key_node_t *, int));
89 private int            key__decode_char __P((char *, int, int));
90
91 #define KEY_BUFSIZ      EL_BUFSIZ
92
93
94 /* key_init():
95  *      Initialize the key maps
96  */
97 protected int
98 key_init(el)
99     EditLine *el;
100 {
101     el->el_key.buf = (char *) el_malloc(KEY_BUFSIZ);
102     el->el_key.map = NULL;
103     key_reset(el);
104     return 0;
105 }
106
107
108 /* key_end():
109  *      Free the key maps
110  */
111 protected void
112 key_end(el)
113     EditLine *el;
114 {
115     el_free((ptr_t) el->el_key.buf);
116     el->el_key.buf = NULL;
117     /* XXX: provide a function to clear the keys */
118     el->el_key.map = NULL;
119 }
120
121
122 /* key_map_cmd():
123  *      Associate cmd with a key value
124  */
125 protected key_value_t *
126 key_map_cmd(el, cmd)
127     EditLine *el;
128     int cmd;
129 {
130     el->el_key.val.cmd = (el_action_t) cmd;
131     return &el->el_key.val;
132 }
133
134
135 /* key_map_str():
136  *      Associate str with a key value
137  */
138 protected key_value_t *
139 key_map_str(el, str)
140     EditLine *el;
141     char  *str;
142 {
143     el->el_key.val.str = str;
144     return &el->el_key.val;
145 }
146
147
148 /* key_reset():
149  *      Takes all nodes on el->el_key.map and puts them on free list.  Then
150  *      initializes el->el_key.map with arrow keys
151  *      [Always bind the ansi arrow keys?]
152  */
153 protected void
154 key_reset(el)
155     EditLine *el;
156 {
157     node__put(el->el_key.map);
158     el->el_key.map = NULL;
159     return;
160 }
161
162
163 /* key_get():
164  *      Calls the recursive function with entry point el->el_key.map
165  *      Looks up *ch in map and then reads characters until a
166  *      complete match is found or a mismatch occurs. Returns the
167  *      type of the match found (XK_STR, XK_CMD, or XK_EXE).
168  *      Returns NULL in val.str and XK_STR for no match.
169  *      The last character read is returned in *ch.
170  */
171 protected int
172 key_get(el, ch, val)
173     EditLine    *el;
174     char        *ch;
175     key_value_t *val;
176 {
177     return node_trav(el, el->el_key.map, ch, val);
178 }
179
180
181
182 /* key_add():
183  *      Adds key to the el->el_key.map and associates the value in val with it.
184  *      If key is already is in el->el_key.map, the new code is applied to the
185  *      existing key. Ntype specifies if code is a command, an
186  *      out str or a unix command.
187  */
188 protected void
189 key_add(el, key, val, ntype)
190     EditLine    *el;
191     char        *key;
192     key_value_t *val;
193     int          ntype;
194 {
195     if (key[0] == '\0') {
196         (void) fprintf(el->el_errfile,
197                        "key_add: Null extended-key not allowed.\n");
198         return;
199     }
200
201     if (ntype == XK_CMD && val->cmd == ED_SEQUENCE_LEAD_IN) {
202         (void) fprintf(el->el_errfile,
203                        "key_add: sequence-lead-in command not allowed\n");
204         return;
205     }
206
207     if (el->el_key.map == NULL)
208         /* tree is initially empty.  Set up new node to match key[0] */
209         el->el_key.map = node__get(key[0]);     /* it is properly initialized */
210
211     /* Now recurse through el->el_key.map */
212     (void) node__try(el->el_key.map, key, val, ntype);
213     return;
214 }
215
216
217 /* key_clear():
218  *
219  */
220 protected void
221 key_clear(el, map, in)
222     EditLine *el;
223     el_action_t *map;
224     char   *in;
225 {
226     if ((map[(unsigned char) *in] == ED_SEQUENCE_LEAD_IN) &&
227         ((map == el->el_map.key &&
228           el->el_map.alt[(unsigned char) *in] != ED_SEQUENCE_LEAD_IN) ||
229          (map == el->el_map.alt &&
230           el->el_map.key[(unsigned char) *in] != ED_SEQUENCE_LEAD_IN)))
231         (void) key_delete(el, in);
232 }
233
234
235 /* key_delete():
236  *      Delete the key and all longer keys staring with key, if
237  *      they exists.
238  */
239 protected int
240 key_delete(el, key)
241     EditLine *el;
242     char   *key;
243 {
244     if (key[0] == '\0') {
245         (void) fprintf(el->el_errfile,
246                        "key_delete: Null extended-key not allowed.\n");
247         return -1;
248     }
249
250     if (el->el_key.map == NULL)
251         return 0;
252
253     (void) node__delete(&el->el_key.map, key);
254     return 0;
255 }
256
257
258 /* key_print():
259  *      Print the binding associated with key key.
260  *      Print entire el->el_key.map if null
261  */
262 protected void
263 key_print(el, key)
264     EditLine *el;
265     char   *key;
266 {
267     /* do nothing if el->el_key.map is empty and null key specified */
268     if (el->el_key.map == NULL && *key == 0)
269         return;
270
271     el->el_key.buf[0] =  '"';
272     if (node_lookup(el, key, el->el_key.map, 1) <= -1)
273         /* key is not bound */
274         (void) fprintf(el->el_errfile, "Unbound extended key \"%s\"\n", key);
275     return;
276 }
277
278
279 /* node_trav():
280  *      recursively traverses node in tree until match or mismatch is
281  *      found.  May read in more characters.
282  */
283 private int
284 node_trav(el, ptr, ch, val)
285     EditLine     *el;
286     key_node_t   *ptr;
287     char         *ch;
288     key_value_t  *val;
289 {
290     if (ptr->ch == *ch) {
291         /* match found */
292         if (ptr->next) {
293             /* key not complete so get next char */
294             if (el_getc(el, ch) != 1) { /* if EOF or error */
295                 val->cmd = ED_END_OF_FILE;
296                 return XK_CMD;/* PWP: Pretend we just read an end-of-file */
297             }
298             return node_trav(el, ptr->next, ch, val);
299         }
300         else {
301             *val = ptr->val;
302             if (ptr->type != XK_CMD)
303                 *ch = '\0';
304             return ptr->type;
305         }
306     }
307     else {
308         /* no match found here */
309         if (ptr->sibling) {
310             /* try next sibling */
311             return node_trav(el, ptr->sibling, ch, val);
312         }
313         else {
314             /* no next sibling -- mismatch */
315             val->str = NULL;
316             return XK_STR;
317         }
318     }
319 }
320
321
322 /* node__try():
323  *      Find a node that matches *str or allocate a new one
324  */
325 private int
326 node__try(ptr, str, val, ntype)
327     key_node_t   *ptr;
328     char         *str;
329     key_value_t  *val;
330     int           ntype;
331 {
332     if (ptr->ch != *str) {
333         key_node_t *xm;
334
335         for (xm = ptr; xm->sibling != NULL; xm = xm->sibling)
336             if (xm->sibling->ch == *str)
337                 break;
338         if (xm->sibling == NULL)
339             xm->sibling = node__get(*str);      /* setup new node */
340         ptr = xm->sibling;
341     }
342
343     if (*++str == '\0') {
344         /* we're there */
345         if (ptr->next != NULL) {
346             node__put(ptr->next);       /* lose longer keys with this prefix */
347             ptr->next = NULL;
348         }
349         switch (ptr->type) {
350         case XK_CMD:
351         case XK_NOD:
352             break;
353         case XK_STR:
354         case XK_EXE:
355             if (ptr->val.str)
356                 el_free((ptr_t) ptr->val.str);
357             break;
358         default:
359             abort();
360             break;
361         }
362
363         switch (ptr->type = ntype) {
364         case XK_CMD:
365             ptr->val = *val;
366             break;
367         case XK_STR:
368         case XK_EXE:
369             ptr->val.str = strdup(val->str);
370             break;
371         default:
372             abort();
373             break;
374         }
375     }
376     else {
377         /* still more chars to go */
378         if (ptr->next == NULL)
379             ptr->next = node__get(*str);        /* setup new node */
380         (void) node__try(ptr->next, str, val, ntype);
381     }
382     return 0;
383 }
384
385
386 /* node__delete():
387  *      Delete node that matches str
388  */
389 private int
390 node__delete(inptr, str)
391     key_node_t **inptr;
392     char   *str;
393 {
394     key_node_t *ptr;
395     key_node_t *prev_ptr = NULL;
396
397     ptr = *inptr;
398
399     if (ptr->ch != *str) {
400         key_node_t *xm;
401
402         for (xm = ptr; xm->sibling != NULL; xm = xm->sibling)
403             if (xm->sibling->ch == *str)
404                 break;
405         if (xm->sibling == NULL)
406             return 0;
407         prev_ptr = xm;
408         ptr = xm->sibling;
409     }
410
411     if (*++str == '\0') {
412         /* we're there */
413         if (prev_ptr == NULL)
414             *inptr = ptr->sibling;
415         else
416             prev_ptr->sibling = ptr->sibling;
417         ptr->sibling = NULL;
418         node__put(ptr);
419         return 1;
420     }
421     else if (ptr->next != NULL && node__delete(&ptr->next, str) == 1) {
422         if (ptr->next != NULL)
423             return 0;
424         if (prev_ptr == NULL)
425             *inptr = ptr->sibling;
426         else
427             prev_ptr->sibling = ptr->sibling;
428         ptr->sibling = NULL;
429         node__put(ptr);
430         return 1;
431     }
432     else {
433         return 0;
434     }
435 }
436
437 /* node__put():
438  *      Puts a tree of nodes onto free list using free(3).
439  */
440 private void
441 node__put(ptr)
442     key_node_t *ptr;
443 {
444     if (ptr == NULL)
445         return;
446
447     if (ptr->next != NULL) {
448         node__put(ptr->next);
449         ptr->next = NULL;
450     }
451
452     node__put(ptr->sibling);
453
454     switch (ptr->type) {
455     case XK_CMD:
456     case XK_NOD:
457         break;
458     case XK_EXE:
459     case XK_STR:
460         if (ptr->val.str != NULL)
461             el_free((ptr_t) ptr->val.str);
462         break;
463     default:
464         abort();
465         break;
466     }
467     el_free((ptr_t) ptr);
468 }
469
470
471 /* node__get():
472  *      Returns pointer to an key_node_t for ch.
473  */
474 private key_node_t *
475 node__get(ch)
476     int    ch;
477 {
478     key_node_t *ptr;
479
480     ptr = (key_node_t *) el_malloc((size_t) sizeof(key_node_t));
481     ptr->ch = ch;
482     ptr->type = XK_NOD;
483     ptr->val.str = NULL;
484     ptr->next = NULL;
485     ptr->sibling = NULL;
486     return ptr;
487 }
488
489
490
491 /* node_lookup():
492  *      look for the str starting at node ptr.
493  *      Print if last node
494  */
495 private int
496 node_lookup(el, str, ptr, cnt)
497     EditLine   *el;
498     char       *str;
499     key_node_t *ptr;
500     int         cnt;
501 {
502     int     ncnt;
503
504     if (ptr == NULL)
505         return -1;              /* cannot have null ptr */
506
507     if (*str == 0) {
508         /* no more chars in str.  node_enum from here. */
509         (void) node_enum(el, ptr, cnt);
510         return 0;
511     }
512     else {
513         /* If match put this char into el->el_key.buf.  Recurse */
514         if (ptr->ch == *str) {
515             /* match found */
516             ncnt = key__decode_char(el->el_key.buf, cnt,
517                                     (unsigned char) ptr->ch);
518             if (ptr->next != NULL)
519                 /* not yet at leaf */
520                 return node_lookup(el, str + 1, ptr->next, ncnt + 1);
521             else {
522                 /* next node is null so key should be complete */
523                 if (str[1] == 0) {
524                     el->el_key.buf[ncnt + 1] = '"';
525                     el->el_key.buf[ncnt + 2] = '\0';
526                     key_kprint(el, el->el_key.buf, &ptr->val, ptr->type);
527                     return 0;
528                 }
529                 else
530                     return -1;/* mismatch -- str still has chars */
531             }
532         }
533         else {
534             /* no match found try sibling */
535             if (ptr->sibling)
536                 return node_lookup(el, str, ptr->sibling, cnt);
537             else
538                 return -1;
539         }
540     }
541 }
542
543
544 /* node_enum():
545  *      Traverse the node printing the characters it is bound in buffer
546  */
547 private int
548 node_enum(el, ptr, cnt)
549     EditLine *el;
550     key_node_t *ptr;
551     int     cnt;
552 {
553     int     ncnt;
554
555     if (cnt >= KEY_BUFSIZ - 5) {        /* buffer too small */
556         el->el_key.buf[++cnt] = '"';
557         el->el_key.buf[++cnt] = '\0';
558         (void) fprintf(el->el_errfile,
559                     "Some extended keys too long for internal print buffer");
560         (void) fprintf(el->el_errfile, " \"%s...\"\n", el->el_key.buf);
561         return 0;
562     }
563
564     if (ptr == NULL) {
565 #ifdef DEBUG_EDIT
566         (void) fprintf(el->el_errfile, "node_enum: BUG!! Null ptr passed\n!");
567 #endif
568         return -1;
569     }
570
571     /* put this char at end of str */
572     ncnt = key__decode_char(el->el_key.buf, cnt, (unsigned char) ptr->ch);
573     if (ptr->next == NULL) {
574         /* print this key and function */
575         el->el_key.buf[ncnt + 1] = '"';
576         el->el_key.buf[ncnt + 2] = '\0';
577         key_kprint(el, el->el_key.buf, &ptr->val, ptr->type);
578     }
579     else
580         (void) node_enum(el, ptr->next, ncnt + 1);
581
582     /* go to sibling if there is one */
583     if (ptr->sibling)
584         (void) node_enum(el, ptr->sibling, cnt);
585     return 0;
586 }
587
588
589 /* key_kprint():
590  *      Print the specified key and its associated
591  *      function specified by val
592  */
593 protected void
594 key_kprint(el, key, val, ntype)
595     EditLine      *el;
596     char          *key;
597     key_value_t   *val;
598     int            ntype;
599 {
600     el_bindings_t *fp;
601     char unparsbuf[EL_BUFSIZ];
602     static char *fmt = "%-15s->  %s\n";
603
604     if (val != NULL)
605         switch (ntype) {
606         case XK_STR:
607         case XK_EXE:
608             (void) fprintf(el->el_errfile, fmt, key,
609                            key__decode_str(val->str, unparsbuf,
610                                               ntype == XK_STR ? "\"\"" : "[]"));
611             break;
612         case XK_CMD:
613             for (fp = el->el_map.help; fp->name; fp++)
614                 if (val->cmd == fp->func) {
615                     (void) fprintf(el->el_errfile, fmt, key, fp->name);
616                     break;
617                 }
618 #ifdef DEBUG_KEY
619             if (fp->name == NULL)
620                 (void) fprintf(el->el_errfile, "BUG! Command not found.\n");
621 #endif
622
623             break;
624         default:
625             abort();
626             break;
627         }
628     else
629         (void) fprintf(el->el_errfile, fmt, key, "no input");
630 }
631
632
633 /* key__decode_char():
634  *      Put a printable form of char in buf.
635  */
636 private int
637 key__decode_char(buf, cnt, ch)
638     char *buf;
639     int   cnt, ch;
640 {
641     ch = (unsigned char)ch;
642
643     if (ch == 0) {
644         buf[cnt++] = '^';
645         buf[cnt] = '@';
646         return cnt;
647     }
648
649     if (iscntrl(ch)) {
650         buf[cnt++] = '^';
651         if (ch == 0177)
652             buf[cnt] = '?';
653         else
654             buf[cnt] = toascii(ch) | 0100;
655     }
656     else if (ch == '^') {
657         buf[cnt++] = '\\';
658         buf[cnt] = '^';
659     }
660     else if (ch == '\\') {
661         buf[cnt++] = '\\';
662         buf[cnt] = '\\';
663     }
664     else if (ch == ' ' || (isprint(ch) && !isspace(ch))) {
665         buf[cnt] = ch;
666     }
667     else {
668         buf[cnt++] = '\\';
669         buf[cnt++] = ((ch >> 6) & 7) + '0';
670         buf[cnt++] = ((ch >> 3) & 7) + '0';
671         buf[cnt] = (ch & 7) + '0';
672     }
673     return cnt;
674 }
675
676 /* key__decode_str():
677  *      Make a printable version of the ey
678  */
679 protected char *
680 key__decode_str(str, buf, sep)
681     char   *str;
682     char   *buf;
683     char   *sep;
684 {
685     char *b, *p;
686
687     b = buf;
688     if (sep[0] != '\0')
689         *b++ = sep[0];
690     if (*str == 0) {
691         *b++ = '^';
692         *b++ = '@';
693         if (sep[0] != '\0' && sep[1] != '\0')
694             *b++ = sep[1];
695         *b++ = 0;
696         return buf;
697     }
698
699     for (p = str; *p != 0; p++) {
700         if (iscntrl((unsigned char) *p)) {
701             *b++ = '^';
702             if (*p == '\177')
703                 *b++ = '?';
704             else
705                 *b++ = toascii(*p) | 0100;
706         }
707         else if (*p == '^' || *p == '\\') {
708             *b++ = '\\';
709             *b++ = *p;
710         }
711         else if (*p == ' ' || (isprint((unsigned char) *p) &&
712                                !isspace((unsigned char) *p))) {
713             *b++ = *p;
714         }
715         else {
716             *b++ = '\\';
717             *b++ = ((*p >> 6) & 7) + '0';
718             *b++ = ((*p >> 3) & 7) + '0';
719             *b++ = (*p & 7) + '0';
720         }
721     }
722     if (sep[0] != '\0' && sep[1] != '\0')
723         *b++ = sep[1];
724     *b++ = 0;
725     return buf;                 /* should check for overflow */
726 }