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