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