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