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