prettiness police
[nvi.git] / common / key.c
blob9cdc27b2f93030fc52175bf3b9078b7192b6fd58
1 /*-
2 * Copyright (c) 1991, 1993
3 * The Regents of the University of California. All rights reserved.
5 * %sccs.include.redist.c%
6 */
8 #ifndef lint
9 static char sccsid[] = "$Id: key.c,v 8.32 1993/12/02 10:33:52 bostic Exp $ (Berkeley) $Date: 1993/12/02 10:33:52 $";
10 #endif /* not lint */
12 #include <sys/types.h>
13 #include <sys/time.h>
15 #include <ctype.h>
16 #include <curses.h>
17 #include <errno.h>
18 #include <stdlib.h>
19 #include <string.h>
20 #include <unistd.h>
22 #include "vi.h"
23 #include "seq.h"
25 static int keycmp __P((const void *, const void *));
28 * If we're reading less than 20 characters, up the size of the tty buffer.
29 * This shouldn't ever happen, other than the first time through, but it's
30 * possible if a map is large enough.
32 #define term_read_grow(sp, tty) \
33 (tty)->len - (tty)->cnt >= 20 ? 0 : __term_read_grow(sp, tty)
34 static int __term_read_grow __P((SCR *, IBUF *));
37 * XXX
38 * THIS REQUIRES THAT ALL SCREENS SHARE A TERMINAL TYPE.
40 typedef struct _tklist {
41 char *ts; /* Key's termcap string. */
42 char *output; /* Corresponding vi command. */
43 char *name; /* Name. */
44 } TKLIST;
45 static TKLIST const tklist[] = {
46 {"kA", "O", "insert line"},
47 {"kD", "x", "delete character"},
48 {"kd", "j", "cursor down"},
49 {"kE", "D", "delete to eol"},
50 {"kF", "\004", "scroll down"},
51 {"kH", "$", "go to eol"},
52 {"kh", "^", "go to sol"},
53 {"kI", "i", "insert at cursor"},
54 {"kL", "dd", "delete line"},
55 {"kl", "h", "cursor left"},
56 {"kN", "\006", "page down"},
57 {"kP", "\002", "page up"},
58 {"kR", "\025", "scroll up"},
59 {"kS", "dG", "delete to end of screen"},
60 {"kr", "l", "cursor right"},
61 {"ku", "k", "cursor up"},
62 {NULL},
66 * XXX
67 * THIS REQUIRES THAT ALL SCREENS SHARE A SPECIAL KEY SET.
69 typedef struct _keylist {
70 u_char value; /* Special value. */
71 CHAR_T ch; /* Key. */
72 } KEYLIST;
73 static KEYLIST keylist[] = {
74 {K_CARAT, '^'},
75 {K_CNTRLR, '\022'},
76 {K_CNTRLT, '\024'},
77 {K_CNTRLZ, '\032'},
78 {K_COLON, ':'},
79 {K_CR, '\r'},
80 {K_ESCAPE, '\033'},
81 {K_FORMFEED, '\f'},
82 {K_NL, '\n'},
83 {K_RIGHTBRACE, '}'},
84 {K_RIGHTPAREN, ')'},
85 {K_TAB, '\t'},
86 {K_VEOF, '\004'},
87 {K_VERASE, '\b'},
88 {K_VKILL, '\025'},
89 {K_VLNEXT, '\026'},
90 {K_VWERASE, '\027'},
91 {K_ZERO, '0'},
95 * term_init --
96 * Initialize the special key lookup table, and the special keys
97 * defined by the terminal's termcap entry.
99 int
100 term_init(sp)
101 SCR *sp;
103 extern CHNAME const asciiname[]; /* XXX */
104 GS *gp;
105 KEYLIST *kp;
106 TKLIST const *tkp;
107 cc_t ch;
108 int cnt;
109 char *sbp, *t, buf[2 * 1024], sbuf[128];
112 * XXX
113 * 8-bit, ASCII only, for now. Recompilation should get you
114 * any 8-bit character set, as long as nul isn't a character.
116 gp = sp->gp;
117 gp->cname = asciiname; /* XXX */
119 /* Set keys found in the termios structure. */
120 #define TERMSET(name, val) { \
121 if ((ch = gp->original_termios.c_cc[name]) != _POSIX_VDISABLE) \
122 for (kp = keylist;; ++kp) \
123 if (kp->value == (val)) { \
124 kp->ch = ch; \
125 break; \
129 * VEOF, VERASE, VKILL are required by POSIX 1003.1-1990,
130 * VWERASE is a 4.4BSD extension.
132 #ifdef VEOF
133 TERMSET(VEOF, K_VEOF);
134 #endif
135 #ifdef VERASE
136 TERMSET(VERASE, K_VERASE);
137 #endif
138 #ifdef VKILL
139 TERMSET(VKILL, K_VKILL);
140 #endif
141 #ifdef VWERASE
142 TERMSET(VWERASE, K_VWERASE);
143 #endif
145 /* Sort the special key list. */
146 qsort(keylist,
147 sizeof(keylist) / sizeof(keylist[0]), sizeof(keylist[0]), keycmp);
149 /* Initialize the fast lookup table. */
150 if ((gp->special_key =
151 calloc(MAX_FAST_KEY + 1, sizeof(u_char))) == NULL) {
152 msgq(sp, M_SYSERR, NULL);
153 return (1);
155 for (gp->max_special = 0, kp = keylist,
156 cnt = sizeof(keylist) / sizeof(keylist[0]); cnt--; ++kp) {
157 if (gp->max_special < kp->value)
158 gp->max_special = kp->value;
159 if (kp->ch <= MAX_FAST_KEY)
160 gp->special_key[kp->ch] = kp->value;
163 /* Set key sequences found in the termcap entry. */
164 switch (tgetent(buf, O_STR(sp, O_TERM))) {
165 case -1:
166 msgq(sp, M_ERR, "%s tgetent: %s.",
167 O_STR(sp, O_TERM), strerror(errno));
168 return (1);
169 case 0:
170 msgq(sp, M_ERR, "%s: unknown terminal type.",
171 O_STR(sp, O_TERM), strerror(errno));
172 return (1);
175 for (tkp = tklist; tkp->name != NULL; ++tkp) {
176 sbp = sbuf;
177 if ((t = tgetstr(tkp->ts, &sbp)) == NULL)
178 continue;
179 if (seq_set(sp, tkp->name, strlen(tkp->name), t, strlen(t),
180 tkp->output, strlen(tkp->output), SEQ_COMMAND, 0))
181 return (1);
183 return (0);
187 * term_push --
188 * Push keys onto the front of a buffer.
190 * There is a single input buffer in ex/vi. Characters are read onto the
191 * end of the buffer by the terminal input routines, and pushed onto the
192 * front of the buffer various other functions in ex/vi. Each key has an
193 * associated flag value, which indicates if it has already been quoted,
194 * if it is the result of a mapping or an abbreviation.
197 term_push(sp, s, len, cmap, flags)
198 SCR *sp;
199 CHAR_T *s; /* Characters. */
200 size_t len; /* Number of chars. */
201 u_int cmap; /* Map count. */
202 u_int flags; /* CH_* flags. */
204 IBUF *tty;
205 size_t nlen;
207 /* If we have room, stuff the keys into the buffer. */
208 tty = sp->gp->tty;
209 if (len <= tty->next || tty->cnt == 0) {
210 if (tty->cnt != 0)
211 tty->next -= len;
212 tty->cnt += len;
213 memmove(tty->ch + tty->next, s, len * sizeof(CHAR_T));
214 memset(tty->chf + tty->next, flags, len);
215 memset(tty->cmap + tty->next, cmap, len);
216 return (0);
219 /* Get enough space plus a little extra. */
220 nlen = tty->cnt + len;
221 if (nlen > tty->len) {
222 nlen += 64;
223 BINC(sp,
224 tty->ch, tty->len, nlen * sizeof(tty->ch[0]));
225 BINC(sp,
226 tty->chf, tty->len, nlen * sizeof(tty->chf[0]));
227 BINC(sp,
228 tty->cmap, tty->len, nlen * sizeof(tty->cmap[0]));
232 * If there are currently characters in the queue, shift them up,
233 * leaving some extra room.
235 #define TERM_PUSH_SHIFT 30
236 if (tty->cnt) {
237 memmove(tty->ch + TERM_PUSH_SHIFT + len,
238 tty->ch + tty->next, tty->cnt * sizeof(tty->ch[0]));
239 memmove(tty->chf + TERM_PUSH_SHIFT + len,
240 tty->chf + tty->next, tty->cnt * sizeof(tty->chf[0]));
241 memmove(tty->cmap + TERM_PUSH_SHIFT + len,
242 tty->cmap + tty->next, tty->cnt * sizeof(tty->cmap[0]));
245 /* Put the new characters into the queue. */
246 tty->next = TERM_PUSH_SHIFT;
247 tty->cnt += len;
248 memmove(tty->ch + TERM_PUSH_SHIFT, s, len * sizeof(tty->ch[0]));
249 memset(tty->chf + TERM_PUSH_SHIFT, flags, len * sizeof(tty->chf[0]));
250 memset(tty->cmap + TERM_PUSH_SHIFT, cmap, len * sizeof(tty->cmap[0]));
251 return (0);
255 * Remove characters from the queue, simultaneously clearing the
256 * flag and map counts.
258 #define QREM_HEAD(q, len) { \
259 size_t __off = (q)->next; \
260 if (len == 1) { \
261 tty->chf[__off] = 0; \
262 tty->cmap[__off] = 0; \
263 } else { \
264 memset(tty->chf + __off, 0, len); \
265 memset(tty->cmap + __off, 0, len); \
267 if (((q)->cnt -= len) == 0) \
268 (q)->next = 0; \
269 else \
270 (q)->next += len; \
272 #define QREM_TAIL(q, len) { \
273 size_t __off = (q)->next + (q)->cnt - 1; \
274 if (len == 1) { \
275 tty->chf[__off] = 0; \
276 tty->cmap[__off] = 0; \
277 } else { \
278 memset(tty->chf + __off, 0, len); \
279 memset(tty->cmap + __off, 0, len); \
281 if (((q)->cnt -= len) == 0) \
282 (q)->next = 0; \
286 * term_key --
287 * Get the next key.
289 * !!!
290 * The flag TXT_MAPNODIGIT probably needs some explanation. First, the idea
291 * of mapping keys is that one or more keystrokes act like a function key.
292 * What's going on is that vi is reading a number, and the character following
293 * the number may or may not be mapped (TXT_MAPCOMMAND). For example, if the
294 * user is entering the z command, a valid command is "z40+", and we don't want
295 * to map the '+', i.e. if '+' is mapped to "xxx", we don't want to change it
296 * into "z40xxx". However, if the user enters "35x", we want to put all of the
297 * characters through the mapping code.
299 * Historical practice is a bit muddled here. (Surprise!) It always permitted
300 * mapping digits as long as they weren't the first character of the map, e.g.
301 * ":map ^A1 xxx" was okay. It also permitted the mapping of the digits 1-9
302 * (the digit 0 was a special case as it doesn't indicate the start of a count)
303 * as the first character of the map, but then ignored those mappings. While
304 * it's probably stupid to map digits, vi isn't your mother.
306 * The way this works is that the TXT_MAPNODIGIT causes term_key to return the
307 * end-of-digit without "looking" at the next character, i.e. leaving it as the
308 * user entered it. Presumably, the next term_key call will tell us how the
309 * user wants it handled.
311 * There is one more complication. Users might map keys to digits, and, as
312 * it's described above, the commands "map g 1G|d2g" would return the keys
313 * "d2<end-of-digits>1G", when the user probably wanted "d21<end-of-digits>G".
314 * So, if a map starts off with a digit we continue as before, otherwise, we
315 * pretend that we haven't mapped the character and return <end-of-digits>.
317 * Now that that's out of the way, let's talk about Energizer Bunny macros.
318 * It's easy to create macros that expand to a loop, e.g. map x 3x. It's
319 * fairly easy to detect this example, because it's all internal to term_key.
320 * If we're expanding a macro and it gets big enough, at some point we can
321 * assume it's looping and kill it. The examples that are tough are the ones
322 * where the parser is involved, e.g. map x "ayyx"byy. We do an expansion
323 * on 'x', and get "ayyx"byy. We then return the first 4 characters, and then
324 * find the looping macro again. There is no way that we can detect this
325 * without doing a full parse of the command, because the character that might
326 * cause the loop (in this case 'x') may be a literal character, e.g. the map
327 * map x "ayy"xyy"byy is perfectly legal and won't cause a loop.
329 * Historic vi tried to detect looping macros by disallowing obvious cases in
330 * the map command, maps that that ended with the same letter as they started
331 * (which wrongly disallowed "map x 'x"), and detecting macros that expanded
332 * too many times before keys were returned to the command parser. It didn't
333 * get many (most?) of the tricky cases right, however, and it was certainly
334 * possible to create macros that ran forever. And, even if it did figure out
335 * what was going on, the user was usually tossed into ex mode. Finally, any
336 * changes made before vi realized that the macro was recursing were left in
337 * place. This implementation counts how many times each input character has
338 * been mapped. If it reaches some arbitrary value, we flush all mapped keys
339 * and return an error.
341 * XXX
342 * The final issue is recovery. It would be possible to undo all of the work
343 * that was done by the macro if we entered a record into the log so that we
344 * knew when the macro started, and, in fact, this might be worth doing at some
345 * point. Given that this might make the log grow unacceptably (consider that
346 * cursor keys are done with maps), for now we leave any changes made in place.
348 enum input
349 term_key(sp, chp, flags)
350 SCR *sp;
351 CH *chp;
352 u_int flags;
354 enum input rval;
355 struct timeval t;
356 CHAR_T ch;
357 GS *gp;
358 IBUF *tty;
359 SEQ *qp;
360 int cmap, ispartial, nr;
362 gp = sp->gp;
363 tty = gp->tty;
366 * If the queue is empty, read more keys in. Since no timeout is
367 * requested, s_key_read will either return an error or will read
368 * some number of characters.
370 loop: if (tty->cnt == 0) {
371 if (term_read_grow(sp, tty))
372 return (INP_ERR);
373 if (rval = sp->s_key_read(sp, &nr, NULL))
374 return (rval);
376 * If there's something on the mode line that we wanted
377 * the user to see, they just entered a character so we
378 * can presume they saw it.
380 if (F_ISSET(sp, S_UPDATE_MODE))
381 F_CLR(sp, S_UPDATE_MODE);
384 /* If the key is mappable and should be mapped, look it up. */
385 if (!(tty->chf[tty->next] & CH_NOMAP) &&
386 LF_ISSET(TXT_MAPCOMMAND | TXT_MAPINPUT)) {
387 /* Set up timeout value. */
388 t.tv_sec = O_VAL(sp, O_KEYTIME) / 10;
389 t.tv_usec = (O_VAL(sp, O_KEYTIME) % 10) * 100000L;
391 /* Get the next key. */
392 newmap: ch = tty->ch[tty->next];
393 if (ch < MAX_BIT_SEQ && !bit_test(gp->seqb, ch))
394 goto nomap;
396 /* Search the map. */
397 remap: qp = seq_find(sp, NULL, &tty->ch[tty->next], tty->cnt,
398 LF_ISSET(TXT_MAPCOMMAND) ? SEQ_COMMAND : SEQ_INPUT,
399 &ispartial);
402 * If get a partial match, read more characters and retry
403 * the map. If no characters read, return the characters
404 * unmapped.
406 if (ispartial) {
407 if (term_read_grow(sp, tty))
408 return (INP_ERR);
409 if (rval = sp->s_key_read(sp, &nr, &t))
410 return (rval);
411 if (nr)
412 goto remap;
413 goto nomap;
416 /* If no map, return the character. */
417 if (qp == NULL)
418 goto nomap;
421 * If looking for the end of a digit string, and the first
422 * character of the map is it, pretend we haven't seen the
423 * character.
425 if (LF_ISSET(TXT_MAPNODIGIT) && !isdigit(qp->output[0]))
426 goto not_digit_ch;
429 * Only permit a character to be remapped a certain number
430 * of times before we figure that it's not going to finish.
432 if ((cmap = tty->cmap[tty->next]) > MAX_MAP_COUNT) {
433 term_map_flush(sp, "Character remapped too many times");
434 return (INP_ERR);
437 /* Delete the mapped characters from the queue. */
438 QREM_HEAD(tty, qp->ilen);
440 /* If remapping characters, push the character on the queue. */
441 if (O_ISSET(sp, O_REMAP)) {
442 if (term_push(sp, qp->output, qp->olen, ++cmap, 0))
443 return (INP_ERR);
444 goto newmap;
447 /* Else, push the characters on the queue and return one. */
448 if (term_push(sp, qp->output, qp->olen, 0, CH_NOMAP))
449 return (INP_ERR);
452 nomap: ch = tty->ch[tty->next];
453 if (LF_ISSET(TXT_MAPNODIGIT) && !isdigit(ch)) {
454 not_digit_ch: chp->ch = NOT_DIGIT_CH;
455 chp->value = 0;
456 chp->flags = 0;
457 return (INP_OK);
460 /* Fill in the return information. */
461 chp->ch = ch;
462 chp->flags = tty->chf[tty->next];
463 chp->value = term_key_val(sp, ch);
465 /* Delete the character from the queue. */
466 QREM_HEAD(tty, 1);
469 * O_BEAUTIFY eliminates all control characters except
470 * escape, form-feed, newline and tab.
472 if (isprint(ch) ||
473 !LF_ISSET(TXT_BEAUTIFY) || !O_ISSET(sp, O_BEAUTIFY) ||
474 chp->value == K_ESCAPE || chp->value == K_FORMFEED ||
475 chp->value == K_NL || chp->value == K_TAB)
476 return (INP_OK);
478 goto loop;
482 * term_ab_flush --
483 * Flush any abbreviated keys.
485 void
486 term_ab_flush(sp, msg)
487 SCR *sp;
488 char *msg;
490 IBUF *tty;
492 tty = sp->gp->tty;
493 if (!tty->cnt || !(tty->chf[tty->next] & CH_ABBREVIATED))
494 return;
495 do {
496 QREM_HEAD(tty, 1);
497 } while (tty->cnt && tty->chf[tty->next] & CH_ABBREVIATED);
498 msgq(sp, M_ERR, "%s: keys flushed.", msg);
502 * term_map_flush --
503 * Flush any mapped keys.
505 void
506 term_map_flush(sp, msg)
507 SCR *sp;
508 char *msg;
510 IBUF *tty;
512 tty = sp->gp->tty;
513 if (!tty->cnt || !tty->cmap[tty->next])
514 return;
515 do {
516 QREM_HEAD(tty, 1);
517 } while (tty->cnt && tty->cmap[tty->next]);
518 msgq(sp, M_ERR, "%s: keys flushed.", msg);
523 * term_user_key --
524 * Get the next key, but require the user enter one.
526 enum input
527 term_user_key(sp, chp)
528 SCR *sp;
529 CH *chp;
531 enum input rval;
532 struct timeval t;
533 IBUF *tty;
534 int nr;
537 * Read any keys the user has waiting. Make the race condition
538 * as short as possible.
540 t.tv_sec = 0;
541 t.tv_usec = 1;
542 tty = sp->gp->tty;
543 if (term_read_grow(sp, tty))
544 return (INP_ERR);
545 if (rval = sp->s_key_read(sp, &nr, &t))
546 return (rval);
548 /* Read another key. */
549 if (term_read_grow(sp, tty))
550 return (INP_ERR);
551 if (rval = sp->s_key_read(sp, &nr, NULL))
552 return (rval);
554 /* Fill in the return information. */
555 chp->ch = tty->ch[tty->next + (tty->cnt - 1)];
556 chp->flags = 0;
557 chp->value = term_key_val(sp, chp->ch);
559 QREM_TAIL(tty, 1);
560 return (INP_OK);
564 * term_key_ch --
565 * Fill in the key for a value.
568 term_key_ch(sp, val, chp)
569 SCR *sp;
570 int val;
571 CHAR_T *chp;
573 KEYLIST *kp;
575 for (kp = keylist;; ++kp)
576 if (kp->value == val) {
577 *chp = kp->ch;
578 return (0);
580 return (1);
584 * __term_key_val --
585 * Fill in the value for a key. This routine is the backup
586 * for the term_key_val() macro.
589 __term_key_val(sp, ch)
590 SCR *sp;
591 ARG_CHAR_T ch;
593 KEYLIST k, *kp;
595 k.ch = ch;
596 kp = bsearch(&k, keylist,
597 sizeof(keylist) / sizeof(keylist[0]), sizeof(keylist[0]), keycmp);
598 return (kp == NULL ? 0 : kp->value);
602 * __term_read_grow --
603 * Grow the terminal queue. This routine is the backup for
604 * the term_read_grow() macro.
606 static int
607 __term_read_grow(sp, tty)
608 SCR *sp;
609 IBUF *tty;
611 size_t alen, len, nlen;
613 nlen = tty->len + 64;
614 alen = tty->len - (tty->next + tty->cnt);
616 len = tty->len;
617 BINC(sp, tty->ch, len, nlen * sizeof(tty->ch[0]));
618 memset(tty->ch + tty->next + tty->cnt, 0, alen * sizeof(tty->ch[0]));
620 len = tty->len;
621 BINC(sp, tty->chf, len, nlen * sizeof(tty->chf[0]));
622 memset(tty->chf + tty->next + tty->cnt, 0, alen * sizeof(tty->chf[0]));
624 BINC(sp, tty->cmap, tty->len, nlen * sizeof(tty->cmap[0]));
625 memset(tty->cmap +
626 tty->next + tty->cnt, 0, alen * sizeof(tty->cmap[0]));
627 return (0);
630 static int
631 keycmp(ap, bp)
632 const void *ap, *bp;
634 return (((KEYLIST *)ap)->ch - ((KEYLIST *)bp)->ch);