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