xref: /openbsd/usr.bin/vi/common/key.c (revision 404b540a)
1 /*	$OpenBSD: key.c,v 1.9 2006/01/08 21:08:27 miod Exp $	*/
2 
3 /*-
4  * Copyright (c) 1991, 1993, 1994
5  *	The Regents of the University of California.  All rights reserved.
6  * Copyright (c) 1991, 1993, 1994, 1995, 1996
7  *	Keith Bostic.  All rights reserved.
8  *
9  * See the LICENSE file for redistribution information.
10  */
11 
12 #include "config.h"
13 
14 #ifndef lint
15 static const char sccsid[] = "@(#)key.c	10.33 (Berkeley) 9/24/96";
16 #endif /* not lint */
17 
18 #include <sys/param.h>
19 #include <sys/queue.h>
20 #include <sys/time.h>
21 
22 #include <bitstring.h>
23 #include <ctype.h>
24 #include <errno.h>
25 #include <limits.h>
26 #include <locale.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <unistd.h>
31 
32 #include "common.h"
33 #include "../vi/vi.h"
34 
35 static int	v_event_append(SCR *, EVENT *);
36 static int	v_event_grow(SCR *, int);
37 static int	v_key_cmp(const void *, const void *);
38 static void	v_keyval(SCR *, int, scr_keyval_t);
39 static void	v_sync(SCR *, int);
40 
41 /*
42  * !!!
43  * Historic vi always used:
44  *
45  *	^D: autoindent deletion
46  *	^H: last character deletion
47  *	^W: last word deletion
48  *	^Q: quote the next character (if not used in flow control).
49  *	^V: quote the next character
50  *
51  * regardless of the user's choices for these characters.  The user's erase
52  * and kill characters worked in addition to these characters.  Nvi wires
53  * down the above characters, but in addition permits the VEOF, VERASE, VKILL
54  * and VWERASE characters described by the user's termios structure.
55  *
56  * Ex was not consistent with this scheme, as it historically ran in tty
57  * cooked mode.  This meant that the scroll command and autoindent erase
58  * characters were mapped to the user's EOF character, and the character
59  * and word deletion characters were the user's tty character and word
60  * deletion characters.  This implementation makes it all consistent, as
61  * described above for vi.
62  *
63  * !!!
64  * This means that all screens share a special key set.
65  */
66 KEYLIST keylist[] = {
67 	{K_BACKSLASH,	  '\\'},	/*  \ */
68 	{K_CARAT,	   '^'},	/*  ^ */
69 	{K_CNTRLD,	'\004'},	/* ^D */
70 	{K_CNTRLR,	'\022'},	/* ^R */
71 	{K_CNTRLT,	'\024'},	/* ^T */
72 	{K_CNTRLZ,	'\032'},	/* ^Z */
73 	{K_COLON,	   ':'},	/*  : */
74 	{K_CR,		  '\r'},	/* \r */
75 	{K_ESCAPE,	'\033'},	/* ^[ */
76 	{K_FORMFEED,	  '\f'},	/* \f */
77 	{K_HEXCHAR,	'\030'},	/* ^X */
78 	{K_NL,		  '\n'},	/* \n */
79 	{K_RIGHTBRACE,	   '}'},	/*  } */
80 	{K_RIGHTPAREN,	   ')'},	/*  ) */
81 	{K_TAB,		  '\t'},	/* \t */
82 	{K_VERASE,	  '\b'},	/* \b */
83 	{K_VKILL,	'\025'},	/* ^U */
84 	{K_VLNEXT,	'\021'},	/* ^Q */
85 	{K_VLNEXT,	'\026'},	/* ^V */
86 	{K_VWERASE,	'\027'},	/* ^W */
87 	{K_ZERO,	   '0'},	/*  0 */
88 
89 #define	ADDITIONAL_CHARACTERS	4
90 	{K_NOTUSED, 0},			/* VEOF, VERASE, VKILL, VWERASE */
91 	{K_NOTUSED, 0},
92 	{K_NOTUSED, 0},
93 	{K_NOTUSED, 0},
94 };
95 static int nkeylist =
96     (sizeof(keylist) / sizeof(keylist[0])) - ADDITIONAL_CHARACTERS;
97 
98 /*
99  * v_key_init --
100  *	Initialize the special key lookup table.
101  *
102  * PUBLIC: int v_key_init(SCR *);
103  */
104 int
105 v_key_init(sp)
106 	SCR *sp;
107 {
108 	u_int ch;
109 	GS *gp;
110 	KEYLIST *kp;
111 	int cnt;
112 
113 	gp = sp->gp;
114 
115 	/*
116 	 * XXX
117 	 * 8-bit only, for now.  Recompilation should get you any 8-bit
118 	 * character set, as long as nul isn't a character.
119 	 */
120 	(void)setlocale(LC_ALL, "");
121 #if __linux__
122 	/*
123 	 * In libc 4.5.26, setlocale(LC_ALL, ""), doesn't setup the table
124 	 * for ctype(3c) correctly.  This bug is fixed in libc 4.6.x.
125 	 *
126 	 * This code works around this problem for libc 4.5.x users.
127 	 * Note that this code is harmless if you're using libc 4.6.x.
128 	 */
129 	(void)setlocale(LC_CTYPE, "");
130 #endif
131 	v_key_ilookup(sp);
132 
133 	v_keyval(sp, K_CNTRLD, KEY_VEOF);
134 	v_keyval(sp, K_VERASE, KEY_VERASE);
135 	v_keyval(sp, K_VKILL, KEY_VKILL);
136 	v_keyval(sp, K_VWERASE, KEY_VWERASE);
137 
138 	/* Sort the special key list. */
139 	qsort(keylist, nkeylist, sizeof(keylist[0]), v_key_cmp);
140 
141 	/* Initialize the fast lookup table. */
142 	for (gp->max_special = 0, kp = keylist, cnt = nkeylist; cnt--; ++kp) {
143 		if (gp->max_special < kp->value)
144 			gp->max_special = kp->value;
145 		if (kp->ch <= MAX_FAST_KEY)
146 			gp->special_key[kp->ch] = kp->value;
147 	}
148 
149 	/* Find a non-printable character to use as a message separator. */
150 	for (ch = 1; ch <= MAX_CHAR_T; ++ch)
151 		if (!isprint(ch)) {
152 			gp->noprint = ch;
153 			break;
154 		}
155 	if (ch != gp->noprint) {
156 		msgq(sp, M_ERR, "079|No non-printable character found");
157 		return (1);
158 	}
159 	return (0);
160 }
161 
162 /*
163  * v_keyval --
164  *	Set key values.
165  *
166  * We've left some open slots in the keylist table, and if these values exist,
167  * we put them into place.  Note, they may reset (or duplicate) values already
168  * in the table, so we check for that first.
169  */
170 static void
171 v_keyval(sp, val, name)
172 	SCR *sp;
173 	int val;
174 	scr_keyval_t name;
175 {
176 	KEYLIST *kp;
177 	CHAR_T ch;
178 	int dne;
179 
180 	/* Get the key's value from the screen. */
181 	if (sp->gp->scr_keyval(sp, name, &ch, &dne))
182 		return;
183 	if (dne)
184 		return;
185 
186 	/* Check for duplication. */
187 	for (kp = keylist; kp->value != K_NOTUSED; ++kp)
188 		if (kp->ch == ch) {
189 			kp->value = val;
190 			return;
191 		}
192 
193 	/* Add a new entry. */
194 	if (kp->value == K_NOTUSED) {
195 		keylist[nkeylist].ch = ch;
196 		keylist[nkeylist].value = val;
197 		++nkeylist;
198 	}
199 }
200 
201 /*
202  * v_key_ilookup --
203  *	Build the fast-lookup key display array.
204  *
205  * PUBLIC: void v_key_ilookup(SCR *);
206  */
207 void
208 v_key_ilookup(sp)
209 	SCR *sp;
210 {
211 	CHAR_T ch, *p, *t;
212 	GS *gp;
213 	size_t len;
214 
215 	for (gp = sp->gp, ch = 0; ch <= MAX_FAST_KEY; ++ch)
216 		for (p = gp->cname[ch].name, t = v_key_name(sp, ch),
217 		    len = gp->cname[ch].len = sp->clen; len--;)
218 			*p++ = *t++;
219 }
220 
221 /*
222  * v_key_len --
223  *	Return the length of the string that will display the key.
224  *	This routine is the backup for the KEY_LEN() macro.
225  *
226  * PUBLIC: size_t v_key_len(SCR *, ARG_CHAR_T);
227  */
228 size_t
229 v_key_len(sp, ch)
230 	SCR *sp;
231 	ARG_CHAR_T ch;
232 {
233 	(void)v_key_name(sp, ch);
234 	return (sp->clen);
235 }
236 
237 /*
238  * v_key_name --
239  *	Return the string that will display the key.  This routine
240  *	is the backup for the KEY_NAME() macro.
241  *
242  * PUBLIC: CHAR_T *v_key_name(SCR *, ARG_CHAR_T);
243  */
244 CHAR_T *
245 v_key_name(sp, ach)
246 	SCR *sp;
247 	ARG_CHAR_T ach;
248 {
249 	static const CHAR_T hexdigit[] = "0123456789abcdef";
250 	static const CHAR_T octdigit[] = "01234567";
251 	CHAR_T ch, *chp, mask;
252 	size_t len;
253 	int cnt, shift;
254 
255 	ch = ach;
256 
257 	/* See if the character was explicitly declared printable or not. */
258 	if ((chp = O_STR(sp, O_PRINT)) != NULL)
259 		for (; *chp != '\0'; ++chp)
260 			if (*chp == ch)
261 				goto pr;
262 	if ((chp = O_STR(sp, O_NOPRINT)) != NULL)
263 		for (; *chp != '\0'; ++chp)
264 			if (*chp == ch)
265 				goto nopr;
266 
267 	/*
268 	 * Historical (ARPA standard) mappings.  Printable characters are left
269 	 * alone.  Control characters less than 0x20 are represented as '^'
270 	 * followed by the character offset from the '@' character in the ASCII
271 	 * character set.  Del (0x7f) is represented as '^' followed by '?'.
272 	 *
273 	 * XXX
274 	 * The following code depends on the current locale being identical to
275 	 * the ASCII map from 0x40 to 0x5f (since 0x1f + 0x40 == 0x5f).  I'm
276 	 * told that this is a reasonable assumption...
277 	 *
278 	 * XXX
279 	 * This code will only work with CHAR_T's that are multiples of 8-bit
280 	 * bytes.
281 	 *
282 	 * XXX
283 	 * NB: There's an assumption here that all printable characters take
284 	 * up a single column on the screen.  This is not always correct.
285 	 */
286 	if (isprint(ch)) {
287 pr:		sp->cname[0] = ch;
288 		len = 1;
289 		goto done;
290 	}
291 nopr:	if (iscntrl(ch) && (ch < 0x20 || ch == 0x7f)) {
292 		sp->cname[0] = '^';
293 		sp->cname[1] = ch == 0x7f ? '?' : '@' + ch;
294 		len = 2;
295 	} else if (O_ISSET(sp, O_OCTAL)) {
296 #define	BITS	(sizeof(CHAR_T) * 8)
297 #define	SHIFT	(BITS - BITS % 3)
298 #define	TOPMASK	(BITS % 3 == 2 ? 3 : 1) << (BITS - BITS % 3)
299 		sp->cname[0] = '\\';
300 		sp->cname[1] = octdigit[(ch & TOPMASK) >> SHIFT];
301 		shift = SHIFT - 3;
302 		for (len = 2, mask = 7 << (SHIFT - 3),
303 		    cnt = BITS / 3; cnt-- > 0; mask >>= 3, shift -= 3)
304 			sp->cname[len++] = octdigit[(ch & mask) >> shift];
305 	} else {
306 		sp->cname[0] = '\\';
307 		sp->cname[1] = 'x';
308 		for (len = 2, chp = (u_int8_t *)&ch,
309 		    cnt = sizeof(CHAR_T); cnt-- > 0; ++chp) {
310 			sp->cname[len++] = hexdigit[(*chp & 0xf0) >> 4];
311 			sp->cname[len++] = hexdigit[*chp & 0x0f];
312 		}
313 	}
314 done:	sp->cname[sp->clen = len] = '\0';
315 	return (sp->cname);
316 }
317 
318 /*
319  * v_key_val --
320  *	Fill in the value for a key.  This routine is the backup
321  *	for the KEY_VAL() macro.
322  *
323  * PUBLIC: int v_key_val(SCR *, ARG_CHAR_T);
324  */
325 int
326 v_key_val(sp, ch)
327 	SCR *sp;
328 	ARG_CHAR_T ch;
329 {
330 	KEYLIST k, *kp;
331 
332 	k.ch = ch;
333 	kp = bsearch(&k, keylist, nkeylist, sizeof(keylist[0]), v_key_cmp);
334 	return (kp == NULL ? K_NOTUSED : kp->value);
335 }
336 
337 /*
338  * v_event_push --
339  *	Push events/keys onto the front of the buffer.
340  *
341  * There is a single input buffer in ex/vi.  Characters are put onto the
342  * end of the buffer by the terminal input routines, and pushed onto the
343  * front of the buffer by various other functions in ex/vi.  Each key has
344  * an associated flag value, which indicates if it has already been quoted,
345  * and if it is the result of a mapping or an abbreviation.
346  *
347  * PUBLIC: int v_event_push(SCR *, EVENT *, CHAR_T *, size_t, u_int);
348  */
349 int
350 v_event_push(sp, p_evp, p_s, nitems, flags)
351 	SCR *sp;
352 	EVENT *p_evp;			/* Push event. */
353 	CHAR_T *p_s;			/* Push characters. */
354 	size_t nitems;			/* Number of items to push. */
355 	u_int flags;			/* CH_* flags. */
356 {
357 	EVENT *evp;
358 	GS *gp;
359 	size_t total;
360 
361 	/* If we have room, stuff the items into the buffer. */
362 	gp = sp->gp;
363 	if (nitems <= gp->i_next ||
364 	    (gp->i_event != NULL && gp->i_cnt == 0 && nitems <= gp->i_nelem)) {
365 		if (gp->i_cnt != 0)
366 			gp->i_next -= nitems;
367 		goto copy;
368 	}
369 
370 	/*
371 	 * If there are currently items in the queue, shift them up,
372 	 * leaving some extra room.  Get enough space plus a little
373 	 * extra.
374 	 */
375 #define	TERM_PUSH_SHIFT	30
376 	total = gp->i_cnt + gp->i_next + nitems + TERM_PUSH_SHIFT;
377 	if (total >= gp->i_nelem && v_event_grow(sp, MAX(total, 64)))
378 		return (1);
379 	if (gp->i_cnt)
380 		MEMMOVE(gp->i_event + TERM_PUSH_SHIFT + nitems,
381 		    gp->i_event + gp->i_next, gp->i_cnt);
382 	gp->i_next = TERM_PUSH_SHIFT;
383 
384 	/* Put the new items into the queue. */
385 copy:	gp->i_cnt += nitems;
386 	for (evp = gp->i_event + gp->i_next; nitems--; ++evp) {
387 		if (p_evp != NULL)
388 			*evp = *p_evp++;
389 		else {
390 			evp->e_event = E_CHARACTER;
391 			evp->e_c = *p_s++;
392 			evp->e_value = KEY_VAL(sp, evp->e_c);
393 			F_INIT(&evp->e_ch, flags);
394 		}
395 	}
396 	return (0);
397 }
398 
399 /*
400  * v_event_append --
401  *	Append events onto the tail of the buffer.
402  */
403 static int
404 v_event_append(sp, argp)
405 	SCR *sp;
406 	EVENT *argp;
407 {
408 	CHAR_T *s;			/* Characters. */
409 	EVENT *evp;
410 	GS *gp;
411 	size_t nevents;			/* Number of events. */
412 
413 	/* Grow the buffer as necessary. */
414 	nevents = argp->e_event == E_STRING ? argp->e_len : 1;
415 	gp = sp->gp;
416 	if (gp->i_event == NULL ||
417 	    nevents > gp->i_nelem - (gp->i_next + gp->i_cnt))
418 		v_event_grow(sp, MAX(nevents, 64));
419 	evp = gp->i_event + gp->i_next + gp->i_cnt;
420 	gp->i_cnt += nevents;
421 
422 	/* Transform strings of characters into single events. */
423 	if (argp->e_event == E_STRING)
424 		for (s = argp->e_csp; nevents--; ++evp) {
425 			evp->e_event = E_CHARACTER;
426 			evp->e_c = *s++;
427 			evp->e_value = KEY_VAL(sp, evp->e_c);
428 			evp->e_flags = 0;
429 		}
430 	else
431 		*evp = *argp;
432 	return (0);
433 }
434 
435 /* Remove events from the queue. */
436 #define	QREM(len) {							\
437 	if ((gp->i_cnt -= (len)) == 0)					\
438 		gp->i_next = 0;						\
439 	else								\
440 		gp->i_next += (len);					\
441 }
442 
443 /*
444  * v_event_get --
445  *	Return the next event.
446  *
447  * !!!
448  * The flag EC_NODIGIT probably needs some explanation.  First, the idea of
449  * mapping keys is that one or more keystrokes act like a function key.
450  * What's going on is that vi is reading a number, and the character following
451  * the number may or may not be mapped (EC_MAPCOMMAND).  For example, if the
452  * user is entering the z command, a valid command is "z40+", and we don't want
453  * to map the '+', i.e. if '+' is mapped to "xxx", we don't want to change it
454  * into "z40xxx".  However, if the user enters "35x", we want to put all of the
455  * characters through the mapping code.
456  *
457  * Historical practice is a bit muddled here.  (Surprise!)  It always permitted
458  * mapping digits as long as they weren't the first character of the map, e.g.
459  * ":map ^A1 xxx" was okay.  It also permitted the mapping of the digits 1-9
460  * (the digit 0 was a special case as it doesn't indicate the start of a count)
461  * as the first character of the map, but then ignored those mappings.  While
462  * it's probably stupid to map digits, vi isn't your mother.
463  *
464  * The way this works is that the EC_MAPNODIGIT causes term_key to return the
465  * end-of-digit without "looking" at the next character, i.e. leaving it as the
466  * user entered it.  Presumably, the next term_key call will tell us how the
467  * user wants it handled.
468  *
469  * There is one more complication.  Users might map keys to digits, and, as
470  * it's described above, the commands:
471  *
472  *	:map g 1G
473  *	d2g
474  *
475  * would return the keys "d2<end-of-digits>1G", when the user probably wanted
476  * "d21<end-of-digits>G".  So, if a map starts off with a digit we continue as
477  * before, otherwise, we pretend we haven't mapped the character, and return
478  * <end-of-digits>.
479  *
480  * Now that that's out of the way, let's talk about Energizer Bunny macros.
481  * It's easy to create macros that expand to a loop, e.g. map x 3x.  It's
482  * fairly easy to detect this example, because it's all internal to term_key.
483  * If we're expanding a macro and it gets big enough, at some point we can
484  * assume it's looping and kill it.  The examples that are tough are the ones
485  * where the parser is involved, e.g. map x "ayyx"byy.  We do an expansion
486  * on 'x', and get "ayyx"byy.  We then return the first 4 characters, and then
487  * find the looping macro again.  There is no way that we can detect this
488  * without doing a full parse of the command, because the character that might
489  * cause the loop (in this case 'x') may be a literal character, e.g. the map
490  * map x "ayy"xyy"byy is perfectly legal and won't cause a loop.
491  *
492  * Historic vi tried to detect looping macros by disallowing obvious cases in
493  * the map command, maps that that ended with the same letter as they started
494  * (which wrongly disallowed "map x 'x"), and detecting macros that expanded
495  * too many times before keys were returned to the command parser.  It didn't
496  * get many (most?) of the tricky cases right, however, and it was certainly
497  * possible to create macros that ran forever.  And, even if it did figure out
498  * what was going on, the user was usually tossed into ex mode.  Finally, any
499  * changes made before vi realized that the macro was recursing were left in
500  * place.  We recover gracefully, but the only recourse the user has in an
501  * infinite macro loop is to interrupt.
502  *
503  * !!!
504  * It is historic practice that mapping characters to themselves as the first
505  * part of the mapped string was legal, and did not cause infinite loops, i.e.
506  * ":map! { {^M^T" and ":map n nz." were known to work.  The initial, matching
507  * characters were returned instead of being remapped.
508  *
509  * !!!
510  * It is also historic practice that the macro "map ] ]]^" caused a single ]
511  * keypress to behave as the command ]] (the ^ got the map past the vi check
512  * for "tail recursion").  Conversely, the mapping "map n nn^" went recursive.
513  * What happened was that, in the historic vi, maps were expanded as the keys
514  * were retrieved, but not all at once and not centrally.  So, the keypress ]
515  * pushed ]]^ on the stack, and then the first ] from the stack was passed to
516  * the ]] command code.  The ]] command then retrieved a key without entering
517  * the mapping code.  This could bite us anytime a user has a map that depends
518  * on secondary keys NOT being mapped.  I can't see any possible way to make
519  * this work in here without the complete abandonment of Rationality Itself.
520  *
521  * XXX
522  * The final issue is recovery.  It would be possible to undo all of the work
523  * that was done by the macro if we entered a record into the log so that we
524  * knew when the macro started, and, in fact, this might be worth doing at some
525  * point.  Given that this might make the log grow unacceptably (consider that
526  * cursor keys are done with maps), for now we leave any changes made in place.
527  *
528  * PUBLIC: int v_event_get(SCR *, EVENT *, int, u_int32_t);
529  */
530 int
531 v_event_get(sp, argp, timeout, flags)
532 	SCR *sp;
533 	EVENT *argp;
534 	int timeout;
535 	u_int32_t flags;
536 {
537 	EVENT *evp, ev;
538 	GS *gp;
539 	SEQ *qp;
540 	int init_nomap, ispartial, istimeout, remap_cnt;
541 
542 	gp = sp->gp;
543 
544 	/* If simply checking for interrupts, argp may be NULL. */
545 	if (argp == NULL)
546 		argp = &ev;
547 
548 retry:	istimeout = remap_cnt = 0;
549 
550 	/*
551 	 * If the queue isn't empty and we're timing out for characters,
552 	 * return immediately.
553 	 */
554 	if (gp->i_cnt != 0 && LF_ISSET(EC_TIMEOUT))
555 		return (0);
556 
557 	/*
558 	 * If the queue is empty, we're checking for interrupts, or we're
559 	 * timing out for characters, get more events.
560 	 */
561 	if (gp->i_cnt == 0 || LF_ISSET(EC_INTERRUPT | EC_TIMEOUT)) {
562 		/*
563 		 * If we're reading new characters, check any scripting
564 		 * windows for input.
565 		 */
566 		if (F_ISSET(gp, G_SCRWIN) && sscr_input(sp))
567 			return (1);
568 loop:		if (gp->scr_event(sp, argp,
569 		    LF_ISSET(EC_INTERRUPT | EC_QUOTED | EC_RAW), timeout))
570 			return (1);
571 		switch (argp->e_event) {
572 		case E_ERR:
573 		case E_SIGHUP:
574 		case E_SIGTERM:
575 			/*
576 			 * Fatal conditions cause the file to be synced to
577 			 * disk immediately.
578 			 */
579 			v_sync(sp, RCV_ENDSESSION | RCV_PRESERVE |
580 			    (argp->e_event == E_SIGTERM ? 0: RCV_EMAIL));
581 			return (1);
582 		case E_TIMEOUT:
583 			istimeout = 1;
584 			break;
585 		case E_INTERRUPT:
586 			/* Set the global interrupt flag. */
587 			F_SET(sp->gp, G_INTERRUPTED);
588 
589 			/*
590 			 * If the caller was interested in interrupts, return
591 			 * immediately.
592 			 */
593 			if (LF_ISSET(EC_INTERRUPT))
594 				return (0);
595 			goto append;
596 		default:
597 append:			if (v_event_append(sp, argp))
598 				return (1);
599 			break;
600 		}
601 	}
602 
603 	/*
604 	 * If the caller was only interested in interrupts or timeouts, return
605 	 * immediately.  (We may have gotten characters, and that's okay, they
606 	 * were queued up for later use.)
607 	 */
608 	if (LF_ISSET(EC_INTERRUPT | EC_TIMEOUT))
609 		return (0);
610 
611 newmap:	evp = &gp->i_event[gp->i_next];
612 
613 	/*
614 	 * If the next event in the queue isn't a character event, return
615 	 * it, we're done.
616 	 */
617 	if (evp->e_event != E_CHARACTER) {
618 		*argp = *evp;
619 		QREM(1);
620 		return (0);
621 	}
622 
623 	/*
624 	 * If the key isn't mappable because:
625 	 *
626 	 *	+ ... the timeout has expired
627 	 *	+ ... it's not a mappable key
628 	 *	+ ... neither the command or input map flags are set
629 	 *	+ ... there are no maps that can apply to it
630 	 *
631 	 * return it forthwith.
632 	 */
633 	if (istimeout || F_ISSET(&evp->e_ch, CH_NOMAP) ||
634 	    !LF_ISSET(EC_MAPCOMMAND | EC_MAPINPUT) ||
635 	    (evp->e_c < MAX_BIT_SEQ && !bit_test(gp->seqb, evp->e_c)))
636 		goto nomap;
637 
638 	/* Search the map. */
639 	qp = seq_find(sp, NULL, evp, NULL, gp->i_cnt,
640 	    LF_ISSET(EC_MAPCOMMAND) ? SEQ_COMMAND : SEQ_INPUT, &ispartial);
641 
642 	/*
643 	 * If get a partial match, get more characters and retry the map.
644 	 * If time out without further characters, return the characters
645 	 * unmapped.
646 	 *
647 	 * !!!
648 	 * <escape> characters are a problem.  Cursor keys start with <escape>
649 	 * characters, so there's almost always a map in place that begins with
650 	 * an <escape> character.  If we timeout <escape> keys in the same way
651 	 * that we timeout other keys, the user will get a noticeable pause as
652 	 * they enter <escape> to terminate input mode.  If key timeout is set
653 	 * for a slow link, users will get an even longer pause.  Nvi used to
654 	 * simply timeout <escape> characters at 1/10th of a second, but this
655 	 * loses over PPP links where the latency is greater than 100Ms.
656 	 */
657 	if (ispartial) {
658 		if (O_ISSET(sp, O_TIMEOUT))
659 			timeout = (evp->e_value == K_ESCAPE ?
660 			    O_VAL(sp, O_ESCAPETIME) :
661 			    O_VAL(sp, O_KEYTIME)) * 100;
662 		else
663 			timeout = 0;
664 		goto loop;
665 	}
666 
667 	/* If no map, return the character. */
668 	if (qp == NULL) {
669 nomap:		if (!isdigit(evp->e_c) && LF_ISSET(EC_MAPNODIGIT))
670 			goto not_digit;
671 		*argp = *evp;
672 		QREM(1);
673 		return (0);
674 	}
675 
676 	/*
677 	 * If looking for the end of a digit string, and the first character
678 	 * of the map is it, pretend we haven't seen the character.
679 	 */
680 	if (LF_ISSET(EC_MAPNODIGIT) &&
681 	    qp->output != NULL && !isdigit(qp->output[0])) {
682 not_digit:	argp->e_c = CH_NOT_DIGIT;
683 		argp->e_value = K_NOTUSED;
684 		argp->e_event = E_CHARACTER;
685 		F_INIT(&argp->e_ch, 0);
686 		return (0);
687 	}
688 
689 	/* Find out if the initial segments are identical. */
690 	init_nomap = !e_memcmp(qp->output, &gp->i_event[gp->i_next], qp->ilen);
691 
692 	/* Delete the mapped characters from the queue. */
693 	QREM(qp->ilen);
694 
695 	/* If keys mapped to nothing, go get more. */
696 	if (qp->output == NULL)
697 		goto retry;
698 
699 	/* If remapping characters... */
700 	if (O_ISSET(sp, O_REMAP)) {
701 		/*
702 		 * Periodically check for interrupts.  Always check the first
703 		 * time through, because it's possible to set up a map that
704 		 * will return a character every time, but will expand to more,
705 		 * e.g. "map! a aaaa" will always return a 'a', but we'll never
706 		 * get anywhere useful.
707 		 */
708 		if ((++remap_cnt == 1 || remap_cnt % 10 == 0) &&
709 		    (gp->scr_event(sp, &ev,
710 		    EC_INTERRUPT, 0) || ev.e_event == E_INTERRUPT)) {
711 			F_SET(sp->gp, G_INTERRUPTED);
712 			argp->e_event = E_INTERRUPT;
713 			return (0);
714 		}
715 
716 		/*
717 		 * If an initial part of the characters mapped, they are not
718 		 * further remapped -- return the first one.  Push the rest
719 		 * of the characters, or all of the characters if no initial
720 		 * part mapped, back on the queue.
721 		 */
722 		if (init_nomap) {
723 			if (v_event_push(sp, NULL, qp->output + qp->ilen,
724 			    qp->olen - qp->ilen, CH_MAPPED))
725 				return (1);
726 			if (v_event_push(sp, NULL,
727 			    qp->output, qp->ilen, CH_NOMAP | CH_MAPPED))
728 				return (1);
729 			evp = &gp->i_event[gp->i_next];
730 			goto nomap;
731 		}
732 		if (v_event_push(sp, NULL, qp->output, qp->olen, CH_MAPPED))
733 			return (1);
734 		goto newmap;
735 	}
736 
737 	/* Else, push the characters on the queue and return one. */
738 	if (v_event_push(sp, NULL, qp->output, qp->olen, CH_MAPPED | CH_NOMAP))
739 		return (1);
740 
741 	goto nomap;
742 }
743 
744 /*
745  * v_sync --
746  *	Walk the screen lists, sync'ing files to their backup copies.
747  */
748 static void
749 v_sync(sp, flags)
750 	SCR *sp;
751 	int flags;
752 {
753 	GS *gp;
754 
755 	gp = sp->gp;
756 	CIRCLEQ_FOREACH(sp, &gp->dq, q)
757 		rcv_sync(sp, flags);
758 	CIRCLEQ_FOREACH(sp, &gp->hq, q)
759 		rcv_sync(sp, flags);
760 }
761 
762 /*
763  * v_event_err --
764  *	Unexpected event.
765  *
766  * PUBLIC: void v_event_err(SCR *, EVENT *);
767  */
768 void
769 v_event_err(sp, evp)
770 	SCR *sp;
771 	EVENT *evp;
772 {
773 	switch (evp->e_event) {
774 	case E_CHARACTER:
775 		msgq(sp, M_ERR, "276|Unexpected character event");
776 		break;
777 	case E_EOF:
778 		msgq(sp, M_ERR, "277|Unexpected end-of-file event");
779 		break;
780 	case E_INTERRUPT:
781 		msgq(sp, M_ERR, "279|Unexpected interrupt event");
782 		break;
783 	case E_QUIT:
784 		msgq(sp, M_ERR, "280|Unexpected quit event");
785 		break;
786 	case E_REPAINT:
787 		msgq(sp, M_ERR, "281|Unexpected repaint event");
788 		break;
789 	case E_STRING:
790 		msgq(sp, M_ERR, "285|Unexpected string event");
791 		break;
792 	case E_TIMEOUT:
793 		msgq(sp, M_ERR, "286|Unexpected timeout event");
794 		break;
795 	case E_WRESIZE:
796 		msgq(sp, M_ERR, "316|Unexpected resize event");
797 		break;
798 	case E_WRITE:
799 		msgq(sp, M_ERR, "287|Unexpected write event");
800 		break;
801 
802 	/*
803 	 * Theoretically, none of these can occur, as they're handled at the
804 	 * top editor level.
805 	 */
806 	case E_ERR:
807 	case E_SIGHUP:
808 	case E_SIGTERM:
809 	default:
810 		abort();
811 	}
812 
813 	/* Free any allocated memory. */
814 	if (evp->e_asp != NULL)
815 		free(evp->e_asp);
816 }
817 
818 /*
819  * v_event_flush --
820  *	Flush any flagged keys, returning if any keys were flushed.
821  *
822  * PUBLIC: int v_event_flush(SCR *, u_int);
823  */
824 int
825 v_event_flush(sp, flags)
826 	SCR *sp;
827 	u_int flags;
828 {
829 	GS *gp;
830 	int rval;
831 
832 	for (rval = 0, gp = sp->gp; gp->i_cnt != 0 &&
833 	    F_ISSET(&gp->i_event[gp->i_next].e_ch, flags); rval = 1)
834 		QREM(1);
835 	return (rval);
836 }
837 
838 /*
839  * v_event_grow --
840  *	Grow the terminal queue.
841  */
842 static int
843 v_event_grow(sp, add)
844 	SCR *sp;
845 	int add;
846 {
847 	GS *gp;
848 	size_t new_nelem, olen;
849 
850 	gp = sp->gp;
851 	new_nelem = gp->i_nelem + add;
852 	olen = gp->i_nelem * sizeof(gp->i_event[0]);
853 	BINC_RET(sp, gp->i_event, olen, new_nelem * sizeof(gp->i_event[0]));
854 	gp->i_nelem = olen / sizeof(gp->i_event[0]);
855 	return (0);
856 }
857 
858 /*
859  * v_key_cmp --
860  *	Compare two keys for sorting.
861  */
862 static int
863 v_key_cmp(ap, bp)
864 	const void *ap, *bp;
865 {
866 	return (((KEYLIST *)ap)->ch - ((KEYLIST *)bp)->ch);
867 }
868