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