Home | History | Annotate | Line # | Download | only in libedit
terminal.c revision 1.21
      1 /*	$NetBSD: terminal.c,v 1.21 2016/02/16 15:53:48 christos Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1992, 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * This code is derived from software contributed to Berkeley by
      8  * Christos Zoulas of Cornell University.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  * 3. Neither the name of the University nor the names of its contributors
     19  *    may be used to endorse or promote products derived from this software
     20  *    without specific prior written permission.
     21  *
     22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     32  * SUCH DAMAGE.
     33  */
     34 
     35 #include "config.h"
     36 #if !defined(lint) && !defined(SCCSID)
     37 #if 0
     38 static char sccsid[] = "@(#)term.c	8.2 (Berkeley) 4/30/95";
     39 #else
     40 __RCSID("$NetBSD: terminal.c,v 1.21 2016/02/16 15:53:48 christos Exp $");
     41 #endif
     42 #endif /* not lint && not SCCSID */
     43 
     44 /*
     45  * terminal.c: Editor/termcap-curses interface
     46  *	       We have to declare a static variable here, since the
     47  *	       termcap putchar routine does not take an argument!
     48  */
     49 #include <stdio.h>
     50 #include <signal.h>
     51 #include <string.h>
     52 #include <stdlib.h>
     53 #include <unistd.h>
     54 #include <limits.h>
     55 #ifdef HAVE_TERMCAP_H
     56 #include <termcap.h>
     57 #endif
     58 #ifdef HAVE_CURSES_H
     59 #include <curses.h>
     60 #elif HAVE_NCURSES_H
     61 #include <ncurses.h>
     62 #endif
     63 
     64 /* Solaris's term.h does horrid things. */
     65 #if defined(HAVE_TERM_H) && !defined(__sun) && !defined(HAVE_TERMCAP_H)
     66 #include <term.h>
     67 #endif
     68 
     69 #include <sys/types.h>
     70 #include <sys/ioctl.h>
     71 
     72 #ifdef _REENTRANT
     73 #include <pthread.h>
     74 #endif
     75 
     76 #include "el.h"
     77 
     78 /*
     79  * IMPORTANT NOTE: these routines are allowed to look at the current screen
     80  * and the current position assuming that it is correct.  If this is not
     81  * true, then the update will be WRONG!  This is (should be) a valid
     82  * assumption...
     83  */
     84 
     85 #define	TC_BUFSIZE	((size_t)2048)
     86 
     87 #define	GoodStr(a)	(el->el_terminal.t_str[a] != NULL && \
     88 			    el->el_terminal.t_str[a][0] != '\0')
     89 #define	Str(a)		el->el_terminal.t_str[a]
     90 #define	Val(a)		el->el_terminal.t_val[a]
     91 
     92 private const struct termcapstr {
     93 	const char *name;
     94 	const char *long_name;
     95 } tstr[] = {
     96 #define	T_al	0
     97 	{ "al", "add new blank line" },
     98 #define	T_bl	1
     99 	{ "bl", "audible bell" },
    100 #define	T_cd	2
    101 	{ "cd", "clear to bottom" },
    102 #define	T_ce	3
    103 	{ "ce", "clear to end of line" },
    104 #define	T_ch	4
    105 	{ "ch", "cursor to horiz pos" },
    106 #define	T_cl	5
    107 	{ "cl", "clear screen" },
    108 #define	T_dc	6
    109 	{ "dc", "delete a character" },
    110 #define	T_dl	7
    111 	{ "dl", "delete a line" },
    112 #define	T_dm	8
    113 	{ "dm", "start delete mode" },
    114 #define	T_ed	9
    115 	{ "ed", "end delete mode" },
    116 #define	T_ei	10
    117 	{ "ei", "end insert mode" },
    118 #define	T_fs	11
    119 	{ "fs", "cursor from status line" },
    120 #define	T_ho	12
    121 	{ "ho", "home cursor" },
    122 #define	T_ic	13
    123 	{ "ic", "insert character" },
    124 #define	T_im	14
    125 	{ "im", "start insert mode" },
    126 #define	T_ip	15
    127 	{ "ip", "insert padding" },
    128 #define	T_kd	16
    129 	{ "kd", "sends cursor down" },
    130 #define	T_kl	17
    131 	{ "kl", "sends cursor left" },
    132 #define	T_kr	18
    133 	{ "kr", "sends cursor right" },
    134 #define	T_ku	19
    135 	{ "ku", "sends cursor up" },
    136 #define	T_md	20
    137 	{ "md", "begin bold" },
    138 #define	T_me	21
    139 	{ "me", "end attributes" },
    140 #define	T_nd	22
    141 	{ "nd", "non destructive space" },
    142 #define	T_se	23
    143 	{ "se", "end standout" },
    144 #define	T_so	24
    145 	{ "so", "begin standout" },
    146 #define	T_ts	25
    147 	{ "ts", "cursor to status line" },
    148 #define	T_up	26
    149 	{ "up", "cursor up one" },
    150 #define	T_us	27
    151 	{ "us", "begin underline" },
    152 #define	T_ue	28
    153 	{ "ue", "end underline" },
    154 #define	T_vb	29
    155 	{ "vb", "visible bell" },
    156 #define	T_DC	30
    157 	{ "DC", "delete multiple chars" },
    158 #define	T_DO	31
    159 	{ "DO", "cursor down multiple" },
    160 #define	T_IC	32
    161 	{ "IC", "insert multiple chars" },
    162 #define	T_LE	33
    163 	{ "LE", "cursor left multiple" },
    164 #define	T_RI	34
    165 	{ "RI", "cursor right multiple" },
    166 #define	T_UP	35
    167 	{ "UP", "cursor up multiple" },
    168 #define	T_kh	36
    169 	{ "kh", "send cursor home" },
    170 #define	T_at7	37
    171 	{ "@7", "send cursor end" },
    172 #define	T_kD	38
    173 	{ "kD", "send cursor delete" },
    174 #define	T_str	39
    175 	{ NULL, NULL }
    176 };
    177 
    178 private const struct termcapval {
    179 	const char *name;
    180 	const char *long_name;
    181 } tval[] = {
    182 #define	T_am	0
    183 	{ "am", "has automatic margins" },
    184 #define	T_pt	1
    185 	{ "pt", "has physical tabs" },
    186 #define	T_li	2
    187 	{ "li", "Number of lines" },
    188 #define	T_co	3
    189 	{ "co", "Number of columns" },
    190 #define	T_km	4
    191 	{ "km", "Has meta key" },
    192 #define	T_xt	5
    193 	{ "xt", "Tab chars destructive" },
    194 #define	T_xn	6
    195 	{ "xn", "newline ignored at right margin" },
    196 #define	T_MT	7
    197 	{ "MT", "Has meta key" },			/* XXX? */
    198 #define	T_val	8
    199 	{ NULL, NULL, }
    200 };
    201 /* do two or more of the attributes use me */
    202 
    203 private void	terminal_setflags(EditLine *);
    204 private int	terminal_rebuffer_display(EditLine *);
    205 private void	terminal_free_display(EditLine *);
    206 private int	terminal_alloc_display(EditLine *);
    207 private void	terminal_alloc(EditLine *, const struct termcapstr *,
    208     const char *);
    209 private void	terminal_init_arrow(EditLine *);
    210 private void	terminal_reset_arrow(EditLine *);
    211 private int	terminal_putc(int);
    212 private void	terminal_tputs(EditLine *, const char *, int);
    213 
    214 #ifdef _REENTRANT
    215 private pthread_mutex_t terminal_mutex = PTHREAD_MUTEX_INITIALIZER;
    216 #endif
    217 private FILE *terminal_outfile = NULL;
    218 
    219 
    220 /* terminal_setflags():
    221  *	Set the terminal capability flags
    222  */
    223 private void
    224 terminal_setflags(EditLine *el)
    225 {
    226 	EL_FLAGS = 0;
    227 	if (el->el_tty.t_tabs)
    228 		EL_FLAGS |= (Val(T_pt) && !Val(T_xt)) ? TERM_CAN_TAB : 0;
    229 
    230 	EL_FLAGS |= (Val(T_km) || Val(T_MT)) ? TERM_HAS_META : 0;
    231 	EL_FLAGS |= GoodStr(T_ce) ? TERM_CAN_CEOL : 0;
    232 	EL_FLAGS |= (GoodStr(T_dc) || GoodStr(T_DC)) ? TERM_CAN_DELETE : 0;
    233 	EL_FLAGS |= (GoodStr(T_im) || GoodStr(T_ic) || GoodStr(T_IC)) ?
    234 	    TERM_CAN_INSERT : 0;
    235 	EL_FLAGS |= (GoodStr(T_up) || GoodStr(T_UP)) ? TERM_CAN_UP : 0;
    236 	EL_FLAGS |= Val(T_am) ? TERM_HAS_AUTO_MARGINS : 0;
    237 	EL_FLAGS |= Val(T_xn) ? TERM_HAS_MAGIC_MARGINS : 0;
    238 
    239 	if (GoodStr(T_me) && GoodStr(T_ue))
    240 		EL_FLAGS |= (strcmp(Str(T_me), Str(T_ue)) == 0) ?
    241 		    TERM_CAN_ME : 0;
    242 	else
    243 		EL_FLAGS &= ~TERM_CAN_ME;
    244 	if (GoodStr(T_me) && GoodStr(T_se))
    245 		EL_FLAGS |= (strcmp(Str(T_me), Str(T_se)) == 0) ?
    246 		    TERM_CAN_ME : 0;
    247 
    248 
    249 #ifdef DEBUG_SCREEN
    250 	if (!EL_CAN_UP) {
    251 		(void) fprintf(el->el_errfile,
    252 		    "WARNING: Your terminal cannot move up.\n");
    253 		(void) fprintf(el->el_errfile,
    254 		    "Editing may be odd for long lines.\n");
    255 	}
    256 	if (!EL_CAN_CEOL)
    257 		(void) fprintf(el->el_errfile, "no clear EOL capability.\n");
    258 	if (!EL_CAN_DELETE)
    259 		(void) fprintf(el->el_errfile, "no delete char capability.\n");
    260 	if (!EL_CAN_INSERT)
    261 		(void) fprintf(el->el_errfile, "no insert char capability.\n");
    262 #endif /* DEBUG_SCREEN */
    263 }
    264 
    265 /* terminal_init():
    266  *	Initialize the terminal stuff
    267  */
    268 protected int
    269 terminal_init(EditLine *el)
    270 {
    271 
    272 	el->el_terminal.t_buf = el_malloc(TC_BUFSIZE *
    273 	    sizeof(*el->el_terminal.t_buf));
    274 	if (el->el_terminal.t_buf == NULL)
    275 		goto fail1;
    276 	el->el_terminal.t_cap = el_malloc(TC_BUFSIZE *
    277 	    sizeof(*el->el_terminal.t_cap));
    278 	if (el->el_terminal.t_cap == NULL)
    279 		goto fail2;
    280 	el->el_terminal.t_fkey = el_malloc(A_K_NKEYS *
    281 	    sizeof(*el->el_terminal.t_fkey));
    282 	if (el->el_terminal.t_fkey == NULL)
    283 		goto fail3;
    284 	el->el_terminal.t_loc = 0;
    285 	el->el_terminal.t_str = el_malloc(T_str *
    286 	    sizeof(*el->el_terminal.t_str));
    287 	if (el->el_terminal.t_str == NULL)
    288 		goto fail4;
    289 	(void) memset(el->el_terminal.t_str, 0, T_str *
    290 	    sizeof(*el->el_terminal.t_str));
    291 	el->el_terminal.t_val = el_malloc(T_val *
    292 	    sizeof(*el->el_terminal.t_val));
    293 	if (el->el_terminal.t_val == NULL)
    294 		goto fail5;
    295 	(void) memset(el->el_terminal.t_val, 0, T_val *
    296 	    sizeof(*el->el_terminal.t_val));
    297 	(void) terminal_set(el, NULL);
    298 	terminal_init_arrow(el);
    299 	return 0;
    300 fail5:
    301 	free(el->el_terminal.t_str);
    302 	el->el_terminal.t_str = NULL;
    303 fail4:
    304 	free(el->el_terminal.t_fkey);
    305 	el->el_terminal.t_fkey = NULL;
    306 fail3:
    307 	free(el->el_terminal.t_cap);
    308 	el->el_terminal.t_cap = NULL;
    309 fail2:
    310 	free(el->el_terminal.t_buf);
    311 	el->el_terminal.t_buf = NULL;
    312 fail1:
    313 	return -1;
    314 }
    315 
    316 /* terminal_end():
    317  *	Clean up the terminal stuff
    318  */
    319 protected void
    320 terminal_end(EditLine *el)
    321 {
    322 
    323 	el_free(el->el_terminal.t_buf);
    324 	el->el_terminal.t_buf = NULL;
    325 	el_free(el->el_terminal.t_cap);
    326 	el->el_terminal.t_cap = NULL;
    327 	el->el_terminal.t_loc = 0;
    328 	el_free(el->el_terminal.t_str);
    329 	el->el_terminal.t_str = NULL;
    330 	el_free(el->el_terminal.t_val);
    331 	el->el_terminal.t_val = NULL;
    332 	el_free(el->el_terminal.t_fkey);
    333 	el->el_terminal.t_fkey = NULL;
    334 	terminal_free_display(el);
    335 }
    336 
    337 
    338 /* terminal_alloc():
    339  *	Maintain a string pool for termcap strings
    340  */
    341 private void
    342 terminal_alloc(EditLine *el, const struct termcapstr *t, const char *cap)
    343 {
    344 	char termbuf[TC_BUFSIZE];
    345 	size_t tlen, clen;
    346 	char **tlist = el->el_terminal.t_str;
    347 	char **tmp, **str = &tlist[t - tstr];
    348 
    349 	(void) memset(termbuf, 0, sizeof(termbuf));
    350 	if (cap == NULL || *cap == '\0') {
    351 		*str = NULL;
    352 		return;
    353 	} else
    354 		clen = strlen(cap);
    355 
    356 	tlen = *str == NULL ? 0 : strlen(*str);
    357 
    358 	/*
    359          * New string is shorter; no need to allocate space
    360          */
    361 	if (clen <= tlen) {
    362 		if (*str)
    363 			(void) strcpy(*str, cap);	/* XXX strcpy is safe */
    364 		return;
    365 	}
    366 	/*
    367          * New string is longer; see if we have enough space to append
    368          */
    369 	if (el->el_terminal.t_loc + 3 < TC_BUFSIZE) {
    370 						/* XXX strcpy is safe */
    371 		(void) strcpy(*str = &el->el_terminal.t_buf[
    372 		    el->el_terminal.t_loc], cap);
    373 		el->el_terminal.t_loc += clen + 1;	/* one for \0 */
    374 		return;
    375 	}
    376 	/*
    377          * Compact our buffer; no need to check compaction, cause we know it
    378          * fits...
    379          */
    380 	tlen = 0;
    381 	for (tmp = tlist; tmp < &tlist[T_str]; tmp++)
    382 		if (*tmp != NULL && *tmp != '\0' && *tmp != *str) {
    383 			char *ptr;
    384 
    385 			for (ptr = *tmp; *ptr != '\0'; termbuf[tlen++] = *ptr++)
    386 				continue;
    387 			termbuf[tlen++] = '\0';
    388 		}
    389 	memcpy(el->el_terminal.t_buf, termbuf, TC_BUFSIZE);
    390 	el->el_terminal.t_loc = tlen;
    391 	if (el->el_terminal.t_loc + 3 >= TC_BUFSIZE) {
    392 		(void) fprintf(el->el_errfile,
    393 		    "Out of termcap string space.\n");
    394 		return;
    395 	}
    396 					/* XXX strcpy is safe */
    397 	(void) strcpy(*str = &el->el_terminal.t_buf[el->el_terminal.t_loc],
    398 	    cap);
    399 	el->el_terminal.t_loc += (size_t)clen + 1;	/* one for \0 */
    400 	return;
    401 }
    402 
    403 
    404 /* terminal_rebuffer_display():
    405  *	Rebuffer the display after the screen changed size
    406  */
    407 private int
    408 terminal_rebuffer_display(EditLine *el)
    409 {
    410 	coord_t *c = &el->el_terminal.t_size;
    411 
    412 	terminal_free_display(el);
    413 
    414 	c->h = Val(T_co);
    415 	c->v = Val(T_li);
    416 
    417 	if (terminal_alloc_display(el) == -1)
    418 		return -1;
    419 	return 0;
    420 }
    421 
    422 
    423 /* terminal_alloc_display():
    424  *	Allocate a new display.
    425  */
    426 private int
    427 terminal_alloc_display(EditLine *el)
    428 {
    429 	int i;
    430 	Char **b;
    431 	coord_t *c = &el->el_terminal.t_size;
    432 
    433 	b =  el_malloc(sizeof(*b) * (size_t)(c->v + 1));
    434 	if (b == NULL)
    435 		goto done;
    436 	for (i = 0; i < c->v; i++) {
    437 		b[i] = el_malloc(sizeof(**b) * (size_t)(c->h + 1));
    438 		if (b[i] == NULL) {
    439 			while (--i >= 0)
    440 				el_free(b[i]);
    441 			el_free(b);
    442 			goto done;
    443 		}
    444 	}
    445 	b[c->v] = NULL;
    446 	el->el_display = b;
    447 
    448 	b = el_malloc(sizeof(*b) * (size_t)(c->v + 1));
    449 	if (b == NULL)
    450 		goto done;
    451 	for (i = 0; i < c->v; i++) {
    452 		b[i] = el_malloc(sizeof(**b) * (size_t)(c->h + 1));
    453 		if (b[i] == NULL) {
    454 			while (--i >= 0)
    455 				el_free(b[i]);
    456 			el_free(b);
    457 			goto done;
    458 		}
    459 	}
    460 	b[c->v] = NULL;
    461 	el->el_vdisplay = b;
    462 	return 0;
    463 done:
    464 	terminal_free_display(el);
    465 	return -1;
    466 }
    467 
    468 
    469 /* terminal_free_display():
    470  *	Free the display buffers
    471  */
    472 private void
    473 terminal_free_display(EditLine *el)
    474 {
    475 	Char **b;
    476 	Char **bufp;
    477 
    478 	b = el->el_display;
    479 	el->el_display = NULL;
    480 	if (b != NULL) {
    481 		for (bufp = b; *bufp != NULL; bufp++)
    482 			el_free(*bufp);
    483 		el_free(b);
    484 	}
    485 	b = el->el_vdisplay;
    486 	el->el_vdisplay = NULL;
    487 	if (b != NULL) {
    488 		for (bufp = b; *bufp != NULL; bufp++)
    489 			el_free(*bufp);
    490 		el_free(b);
    491 	}
    492 }
    493 
    494 
    495 /* terminal_move_to_line():
    496  *	move to line <where> (first line == 0)
    497  * 	as efficiently as possible
    498  */
    499 protected void
    500 terminal_move_to_line(EditLine *el, int where)
    501 {
    502 	int del;
    503 
    504 	if (where == el->el_cursor.v)
    505 		return;
    506 
    507 	if (where > el->el_terminal.t_size.v) {
    508 #ifdef DEBUG_SCREEN
    509 		(void) fprintf(el->el_errfile,
    510 		    "%s: where is ridiculous: %d\r\n", __func__, where);
    511 #endif /* DEBUG_SCREEN */
    512 		return;
    513 	}
    514 	if ((del = where - el->el_cursor.v) > 0) {
    515 		while (del > 0) {
    516 			if (EL_HAS_AUTO_MARGINS &&
    517 			    el->el_display[el->el_cursor.v][0] != '\0') {
    518                                 size_t h = (size_t)
    519 				    (el->el_terminal.t_size.h - 1);
    520 #ifdef WIDECHAR
    521                                 for (; h > 0 &&
    522                                          el->el_display[el->el_cursor.v][h] ==
    523                                                  MB_FILL_CHAR;
    524                                          h--)
    525                                                 continue;
    526 #endif
    527 				/* move without newline */
    528 				terminal_move_to_char(el, (int)h);
    529 				terminal_overwrite(el, &el->el_display
    530 				    [el->el_cursor.v][el->el_cursor.h],
    531 				    (size_t)(el->el_terminal.t_size.h -
    532 				    el->el_cursor.h));
    533 				/* updates Cursor */
    534 				del--;
    535 			} else {
    536 				if ((del > 1) && GoodStr(T_DO)) {
    537 					terminal_tputs(el, tgoto(Str(T_DO), del,
    538 					    del), del);
    539 					del = 0;
    540 				} else {
    541 					for (; del > 0; del--)
    542 						terminal__putc(el, '\n');
    543 					/* because the \n will become \r\n */
    544 					el->el_cursor.h = 0;
    545 				}
    546 			}
    547 		}
    548 	} else {		/* del < 0 */
    549 		if (GoodStr(T_UP) && (-del > 1 || !GoodStr(T_up)))
    550 			terminal_tputs(el, tgoto(Str(T_UP), -del, -del), -del);
    551 		else {
    552 			if (GoodStr(T_up))
    553 				for (; del < 0; del++)
    554 					terminal_tputs(el, Str(T_up), 1);
    555 		}
    556 	}
    557 	el->el_cursor.v = where;/* now where is here */
    558 }
    559 
    560 
    561 /* terminal_move_to_char():
    562  *	Move to the character position specified
    563  */
    564 protected void
    565 terminal_move_to_char(EditLine *el, int where)
    566 {
    567 	int del, i;
    568 
    569 mc_again:
    570 	if (where == el->el_cursor.h)
    571 		return;
    572 
    573 	if (where > el->el_terminal.t_size.h) {
    574 #ifdef DEBUG_SCREEN
    575 		(void) fprintf(el->el_errfile,
    576 		    "%s: where is ridiculous: %d\r\n", __func__, where);
    577 #endif /* DEBUG_SCREEN */
    578 		return;
    579 	}
    580 	if (!where) {		/* if where is first column */
    581 		terminal__putc(el, '\r');	/* do a CR */
    582 		el->el_cursor.h = 0;
    583 		return;
    584 	}
    585 	del = where - el->el_cursor.h;
    586 
    587 	if ((del < -4 || del > 4) && GoodStr(T_ch))
    588 		/* go there directly */
    589 		terminal_tputs(el, tgoto(Str(T_ch), where, where), where);
    590 	else {
    591 		if (del > 0) {	/* moving forward */
    592 			if ((del > 4) && GoodStr(T_RI))
    593 				terminal_tputs(el, tgoto(Str(T_RI), del, del),
    594 				    del);
    595 			else {
    596 					/* if I can do tabs, use them */
    597 				if (EL_CAN_TAB) {
    598 					if ((el->el_cursor.h & 0370) !=
    599 					    (where & ~0x7)
    600 #ifdef WIDECHAR
    601 					    && (el->el_display[
    602 					    el->el_cursor.v][where & 0370] !=
    603 					    MB_FILL_CHAR)
    604 #endif
    605 					    ) {
    606 						/* if not within tab stop */
    607 						for (i =
    608 						    (el->el_cursor.h & 0370);
    609 						    i < (where & ~0x7);
    610 						    i += 8)
    611 							terminal__putc(el,
    612 							    '\t');
    613 							/* then tab over */
    614 						el->el_cursor.h = where & ~0x7;
    615 					}
    616 				}
    617 				/*
    618 				 * it's usually cheaper to just write the
    619 				 * chars, so we do.
    620 				 */
    621 				/*
    622 				 * NOTE THAT terminal_overwrite() WILL CHANGE
    623 				 * el->el_cursor.h!!!
    624 				 */
    625 				terminal_overwrite(el, &el->el_display[
    626 				    el->el_cursor.v][el->el_cursor.h],
    627 				    (size_t)(where - el->el_cursor.h));
    628 
    629 			}
    630 		} else {	/* del < 0 := moving backward */
    631 			if ((-del > 4) && GoodStr(T_LE))
    632 				terminal_tputs(el, tgoto(Str(T_LE), -del, -del),
    633 				    -del);
    634 			else {	/* can't go directly there */
    635 				/*
    636 				 * if the "cost" is greater than the "cost"
    637 				 * from col 0
    638 				 */
    639 				if (EL_CAN_TAB ?
    640 				    ((unsigned int)-del >
    641 				    (((unsigned int) where >> 3) +
    642 				     (where & 07)))
    643 				    : (-del > where)) {
    644 					terminal__putc(el, '\r');/* do a CR */
    645 					el->el_cursor.h = 0;
    646 					goto mc_again;	/* and try again */
    647 				}
    648 				for (i = 0; i < -del; i++)
    649 					terminal__putc(el, '\b');
    650 			}
    651 		}
    652 	}
    653 	el->el_cursor.h = where;		/* now where is here */
    654 }
    655 
    656 
    657 /* terminal_overwrite():
    658  *	Overstrike num characters
    659  *	Assumes MB_FILL_CHARs are present to keep the column count correct
    660  */
    661 protected void
    662 terminal_overwrite(EditLine *el, const Char *cp, size_t n)
    663 {
    664 	if (n == 0)
    665 		return;
    666 
    667 	if (n > (size_t)el->el_terminal.t_size.h) {
    668 #ifdef DEBUG_SCREEN
    669 		(void) fprintf(el->el_errfile,
    670 		    "%s: n is ridiculous: %d\r\n", __func__, n);
    671 #endif /* DEBUG_SCREEN */
    672 		return;
    673 	}
    674 
    675         do {
    676                 /* terminal__putc() ignores any MB_FILL_CHARs */
    677                 terminal__putc(el, *cp++);
    678                 el->el_cursor.h++;
    679         } while (--n);
    680 
    681 	if (el->el_cursor.h >= el->el_terminal.t_size.h) {	/* wrap? */
    682 		if (EL_HAS_AUTO_MARGINS) {	/* yes */
    683 			el->el_cursor.h = 0;
    684 			el->el_cursor.v++;
    685 			if (EL_HAS_MAGIC_MARGINS) {
    686 				/* force the wrap to avoid the "magic"
    687 				 * situation */
    688 				Char c;
    689 				if ((c = el->el_display[el->el_cursor.v]
    690 				    [el->el_cursor.h]) != '\0') {
    691 					terminal_overwrite(el, &c, (size_t)1);
    692 #ifdef WIDECHAR
    693 					while (el->el_display[el->el_cursor.v]
    694 					    [el->el_cursor.h] == MB_FILL_CHAR)
    695 						el->el_cursor.h++;
    696 #endif
    697 				} else {
    698 					terminal__putc(el, ' ');
    699 					el->el_cursor.h = 1;
    700 				}
    701 			}
    702 		} else		/* no wrap, but cursor stays on screen */
    703 			el->el_cursor.h = el->el_terminal.t_size.h - 1;
    704 	}
    705 }
    706 
    707 
    708 /* terminal_deletechars():
    709  *	Delete num characters
    710  */
    711 protected void
    712 terminal_deletechars(EditLine *el, int num)
    713 {
    714 	if (num <= 0)
    715 		return;
    716 
    717 	if (!EL_CAN_DELETE) {
    718 #ifdef DEBUG_EDIT
    719 		(void) fprintf(el->el_errfile, "   ERROR: cannot delete   \n");
    720 #endif /* DEBUG_EDIT */
    721 		return;
    722 	}
    723 	if (num > el->el_terminal.t_size.h) {
    724 #ifdef DEBUG_SCREEN
    725 		(void) fprintf(el->el_errfile,
    726 		    "%s: num is ridiculous: %d\r\n", __func__, num);
    727 #endif /* DEBUG_SCREEN */
    728 		return;
    729 	}
    730 	if (GoodStr(T_DC))	/* if I have multiple delete */
    731 		if ((num > 1) || !GoodStr(T_dc)) {	/* if dc would be more
    732 							 * expen. */
    733 			terminal_tputs(el, tgoto(Str(T_DC), num, num), num);
    734 			return;
    735 		}
    736 	if (GoodStr(T_dm))	/* if I have delete mode */
    737 		terminal_tputs(el, Str(T_dm), 1);
    738 
    739 	if (GoodStr(T_dc))	/* else do one at a time */
    740 		while (num--)
    741 			terminal_tputs(el, Str(T_dc), 1);
    742 
    743 	if (GoodStr(T_ed))	/* if I have delete mode */
    744 		terminal_tputs(el, Str(T_ed), 1);
    745 }
    746 
    747 
    748 /* terminal_insertwrite():
    749  *	Puts terminal in insert character mode or inserts num
    750  *	characters in the line
    751  *      Assumes MB_FILL_CHARs are present to keep column count correct
    752  */
    753 protected void
    754 terminal_insertwrite(EditLine *el, Char *cp, int num)
    755 {
    756 	if (num <= 0)
    757 		return;
    758 	if (!EL_CAN_INSERT) {
    759 #ifdef DEBUG_EDIT
    760 		(void) fprintf(el->el_errfile, "   ERROR: cannot insert   \n");
    761 #endif /* DEBUG_EDIT */
    762 		return;
    763 	}
    764 	if (num > el->el_terminal.t_size.h) {
    765 #ifdef DEBUG_SCREEN
    766 		(void) fprintf(el->el_errfile,
    767 		    "%s: num is ridiculous: %d\r\n", __func__, num);
    768 #endif /* DEBUG_SCREEN */
    769 		return;
    770 	}
    771 	if (GoodStr(T_IC))	/* if I have multiple insert */
    772 		if ((num > 1) || !GoodStr(T_ic)) {
    773 				/* if ic would be more expensive */
    774 			terminal_tputs(el, tgoto(Str(T_IC), num, num), num);
    775 			terminal_overwrite(el, cp, (size_t)num);
    776 				/* this updates el_cursor.h */
    777 			return;
    778 		}
    779 	if (GoodStr(T_im) && GoodStr(T_ei)) {	/* if I have insert mode */
    780 		terminal_tputs(el, Str(T_im), 1);
    781 
    782 		el->el_cursor.h += num;
    783 		do
    784 			terminal__putc(el, *cp++);
    785 		while (--num);
    786 
    787 		if (GoodStr(T_ip))	/* have to make num chars insert */
    788 			terminal_tputs(el, Str(T_ip), 1);
    789 
    790 		terminal_tputs(el, Str(T_ei), 1);
    791 		return;
    792 	}
    793 	do {
    794 		if (GoodStr(T_ic))	/* have to make num chars insert */
    795 			terminal_tputs(el, Str(T_ic), 1);
    796 
    797 		terminal__putc(el, *cp++);
    798 
    799 		el->el_cursor.h++;
    800 
    801 		if (GoodStr(T_ip))	/* have to make num chars insert */
    802 			terminal_tputs(el, Str(T_ip), 1);
    803 					/* pad the inserted char */
    804 
    805 	} while (--num);
    806 }
    807 
    808 
    809 /* terminal_clear_EOL():
    810  *	clear to end of line.  There are num characters to clear
    811  */
    812 protected void
    813 terminal_clear_EOL(EditLine *el, int num)
    814 {
    815 	int i;
    816 
    817 	if (EL_CAN_CEOL && GoodStr(T_ce))
    818 		terminal_tputs(el, Str(T_ce), 1);
    819 	else {
    820 		for (i = 0; i < num; i++)
    821 			terminal__putc(el, ' ');
    822 		el->el_cursor.h += num;	/* have written num spaces */
    823 	}
    824 }
    825 
    826 
    827 /* terminal_clear_screen():
    828  *	Clear the screen
    829  */
    830 protected void
    831 terminal_clear_screen(EditLine *el)
    832 {				/* clear the whole screen and home */
    833 
    834 	if (GoodStr(T_cl))
    835 		/* send the clear screen code */
    836 		terminal_tputs(el, Str(T_cl), Val(T_li));
    837 	else if (GoodStr(T_ho) && GoodStr(T_cd)) {
    838 		terminal_tputs(el, Str(T_ho), Val(T_li));	/* home */
    839 		/* clear to bottom of screen */
    840 		terminal_tputs(el, Str(T_cd), Val(T_li));
    841 	} else {
    842 		terminal__putc(el, '\r');
    843 		terminal__putc(el, '\n');
    844 	}
    845 }
    846 
    847 
    848 /* terminal_beep():
    849  *	Beep the way the terminal wants us
    850  */
    851 protected void
    852 terminal_beep(EditLine *el)
    853 {
    854 	if (GoodStr(T_bl))
    855 		/* what termcap says we should use */
    856 		terminal_tputs(el, Str(T_bl), 1);
    857 	else
    858 		terminal__putc(el, '\007');	/* an ASCII bell; ^G */
    859 }
    860 
    861 
    862 protected void
    863 terminal_get(EditLine *el, const char **term)
    864 {
    865 	*term = el->el_terminal.t_name;
    866 }
    867 
    868 
    869 /* terminal_set():
    870  *	Read in the terminal capabilities from the requested terminal
    871  */
    872 protected int
    873 terminal_set(EditLine *el, const char *term)
    874 {
    875 	int i;
    876 	char buf[TC_BUFSIZE];
    877 	char *area;
    878 	const struct termcapstr *t;
    879 	sigset_t oset, nset;
    880 	int lins, cols;
    881 
    882 	(void) sigemptyset(&nset);
    883 	(void) sigaddset(&nset, SIGWINCH);
    884 	(void) sigprocmask(SIG_BLOCK, &nset, &oset);
    885 
    886 	area = buf;
    887 
    888 
    889 	if (term == NULL)
    890 		term = getenv("TERM");
    891 
    892 	if (!term || !term[0])
    893 		term = "dumb";
    894 
    895 	if (strcmp(term, "emacs") == 0)
    896 		el->el_flags |= EDIT_DISABLED;
    897 
    898 	(void) memset(el->el_terminal.t_cap, 0, TC_BUFSIZE);
    899 
    900 	i = tgetent(el->el_terminal.t_cap, term);
    901 
    902 	if (i <= 0) {
    903 		if (i == -1)
    904 			(void) fprintf(el->el_errfile,
    905 			    "Cannot read termcap database;\n");
    906 		else if (i == 0)
    907 			(void) fprintf(el->el_errfile,
    908 			    "No entry for terminal type \"%s\";\n", term);
    909 		(void) fprintf(el->el_errfile,
    910 		    "using dumb terminal settings.\n");
    911 		Val(T_co) = 80;	/* do a dumb terminal */
    912 		Val(T_pt) = Val(T_km) = Val(T_li) = 0;
    913 		Val(T_xt) = Val(T_MT);
    914 		for (t = tstr; t->name != NULL; t++)
    915 			terminal_alloc(el, t, NULL);
    916 	} else {
    917 		/* auto/magic margins */
    918 		Val(T_am) = tgetflag("am");
    919 		Val(T_xn) = tgetflag("xn");
    920 		/* Can we tab */
    921 		Val(T_pt) = tgetflag("pt");
    922 		Val(T_xt) = tgetflag("xt");
    923 		/* do we have a meta? */
    924 		Val(T_km) = tgetflag("km");
    925 		Val(T_MT) = tgetflag("MT");
    926 		/* Get the size */
    927 		Val(T_co) = tgetnum("co");
    928 		Val(T_li) = tgetnum("li");
    929 		for (t = tstr; t->name != NULL; t++) {
    930 			/* XXX: some systems' tgetstr needs non const */
    931 			terminal_alloc(el, t, tgetstr(strchr(t->name, *t->name),
    932 			    &area));
    933 		}
    934 	}
    935 
    936 	if (Val(T_co) < 2)
    937 		Val(T_co) = 80;	/* just in case */
    938 	if (Val(T_li) < 1)
    939 		Val(T_li) = 24;
    940 
    941 	el->el_terminal.t_size.v = Val(T_co);
    942 	el->el_terminal.t_size.h = Val(T_li);
    943 
    944 	terminal_setflags(el);
    945 
    946 				/* get the correct window size */
    947 	(void) terminal_get_size(el, &lins, &cols);
    948 	if (terminal_change_size(el, lins, cols) == -1)
    949 		return -1;
    950 	(void) sigprocmask(SIG_SETMASK, &oset, NULL);
    951 	terminal_bind_arrow(el);
    952 	el->el_terminal.t_name = term;
    953 	return i <= 0 ? -1 : 0;
    954 }
    955 
    956 
    957 /* terminal_get_size():
    958  *	Return the new window size in lines and cols, and
    959  *	true if the size was changed.
    960  */
    961 protected int
    962 terminal_get_size(EditLine *el, int *lins, int *cols)
    963 {
    964 
    965 	*cols = Val(T_co);
    966 	*lins = Val(T_li);
    967 
    968 #ifdef TIOCGWINSZ
    969 	{
    970 		struct winsize ws;
    971 		if (ioctl(el->el_infd, TIOCGWINSZ, &ws) != -1) {
    972 			if (ws.ws_col)
    973 				*cols = ws.ws_col;
    974 			if (ws.ws_row)
    975 				*lins = ws.ws_row;
    976 		}
    977 	}
    978 #endif
    979 #ifdef TIOCGSIZE
    980 	{
    981 		struct ttysize ts;
    982 		if (ioctl(el->el_infd, TIOCGSIZE, &ts) != -1) {
    983 			if (ts.ts_cols)
    984 				*cols = ts.ts_cols;
    985 			if (ts.ts_lines)
    986 				*lins = ts.ts_lines;
    987 		}
    988 	}
    989 #endif
    990 	return Val(T_co) != *cols || Val(T_li) != *lins;
    991 }
    992 
    993 
    994 /* terminal_change_size():
    995  *	Change the size of the terminal
    996  */
    997 protected int
    998 terminal_change_size(EditLine *el, int lins, int cols)
    999 {
   1000 	/*
   1001          * Just in case
   1002          */
   1003 	Val(T_co) = (cols < 2) ? 80 : cols;
   1004 	Val(T_li) = (lins < 1) ? 24 : lins;
   1005 
   1006 	/* re-make display buffers */
   1007 	if (terminal_rebuffer_display(el) == -1)
   1008 		return -1;
   1009 	re_clear_display(el);
   1010 	return 0;
   1011 }
   1012 
   1013 
   1014 /* terminal_init_arrow():
   1015  *	Initialize the arrow key bindings from termcap
   1016  */
   1017 private void
   1018 terminal_init_arrow(EditLine *el)
   1019 {
   1020 	funckey_t *arrow = el->el_terminal.t_fkey;
   1021 
   1022 	arrow[A_K_DN].name = STR("down");
   1023 	arrow[A_K_DN].key = T_kd;
   1024 	arrow[A_K_DN].fun.cmd = ED_NEXT_HISTORY;
   1025 	arrow[A_K_DN].type = XK_CMD;
   1026 
   1027 	arrow[A_K_UP].name = STR("up");
   1028 	arrow[A_K_UP].key = T_ku;
   1029 	arrow[A_K_UP].fun.cmd = ED_PREV_HISTORY;
   1030 	arrow[A_K_UP].type = XK_CMD;
   1031 
   1032 	arrow[A_K_LT].name = STR("left");
   1033 	arrow[A_K_LT].key = T_kl;
   1034 	arrow[A_K_LT].fun.cmd = ED_PREV_CHAR;
   1035 	arrow[A_K_LT].type = XK_CMD;
   1036 
   1037 	arrow[A_K_RT].name = STR("right");
   1038 	arrow[A_K_RT].key = T_kr;
   1039 	arrow[A_K_RT].fun.cmd = ED_NEXT_CHAR;
   1040 	arrow[A_K_RT].type = XK_CMD;
   1041 
   1042 	arrow[A_K_HO].name = STR("home");
   1043 	arrow[A_K_HO].key = T_kh;
   1044 	arrow[A_K_HO].fun.cmd = ED_MOVE_TO_BEG;
   1045 	arrow[A_K_HO].type = XK_CMD;
   1046 
   1047 	arrow[A_K_EN].name = STR("end");
   1048 	arrow[A_K_EN].key = T_at7;
   1049 	arrow[A_K_EN].fun.cmd = ED_MOVE_TO_END;
   1050 	arrow[A_K_EN].type = XK_CMD;
   1051 
   1052 	arrow[A_K_DE].name = STR("delete");
   1053 	arrow[A_K_DE].key = T_kD;
   1054 	arrow[A_K_DE].fun.cmd = ED_DELETE_NEXT_CHAR;
   1055 	arrow[A_K_DE].type = XK_CMD;
   1056 }
   1057 
   1058 
   1059 /* terminal_reset_arrow():
   1060  *	Reset arrow key bindings
   1061  */
   1062 private void
   1063 terminal_reset_arrow(EditLine *el)
   1064 {
   1065 	funckey_t *arrow = el->el_terminal.t_fkey;
   1066 	static const Char strA[] = {033, '[', 'A', '\0'};
   1067 	static const Char strB[] = {033, '[', 'B', '\0'};
   1068 	static const Char strC[] = {033, '[', 'C', '\0'};
   1069 	static const Char strD[] = {033, '[', 'D', '\0'};
   1070 	static const Char strH[] = {033, '[', 'H', '\0'};
   1071 	static const Char strF[] = {033, '[', 'F', '\0'};
   1072 	static const Char stOA[] = {033, 'O', 'A', '\0'};
   1073 	static const Char stOB[] = {033, 'O', 'B', '\0'};
   1074 	static const Char stOC[] = {033, 'O', 'C', '\0'};
   1075 	static const Char stOD[] = {033, 'O', 'D', '\0'};
   1076 	static const Char stOH[] = {033, 'O', 'H', '\0'};
   1077 	static const Char stOF[] = {033, 'O', 'F', '\0'};
   1078 
   1079 	keymacro_add(el, strA, &arrow[A_K_UP].fun, arrow[A_K_UP].type);
   1080 	keymacro_add(el, strB, &arrow[A_K_DN].fun, arrow[A_K_DN].type);
   1081 	keymacro_add(el, strC, &arrow[A_K_RT].fun, arrow[A_K_RT].type);
   1082 	keymacro_add(el, strD, &arrow[A_K_LT].fun, arrow[A_K_LT].type);
   1083 	keymacro_add(el, strH, &arrow[A_K_HO].fun, arrow[A_K_HO].type);
   1084 	keymacro_add(el, strF, &arrow[A_K_EN].fun, arrow[A_K_EN].type);
   1085 	keymacro_add(el, stOA, &arrow[A_K_UP].fun, arrow[A_K_UP].type);
   1086 	keymacro_add(el, stOB, &arrow[A_K_DN].fun, arrow[A_K_DN].type);
   1087 	keymacro_add(el, stOC, &arrow[A_K_RT].fun, arrow[A_K_RT].type);
   1088 	keymacro_add(el, stOD, &arrow[A_K_LT].fun, arrow[A_K_LT].type);
   1089 	keymacro_add(el, stOH, &arrow[A_K_HO].fun, arrow[A_K_HO].type);
   1090 	keymacro_add(el, stOF, &arrow[A_K_EN].fun, arrow[A_K_EN].type);
   1091 
   1092 	if (el->el_map.type != MAP_VI)
   1093 		return;
   1094 	keymacro_add(el, &strA[1], &arrow[A_K_UP].fun, arrow[A_K_UP].type);
   1095 	keymacro_add(el, &strB[1], &arrow[A_K_DN].fun, arrow[A_K_DN].type);
   1096 	keymacro_add(el, &strC[1], &arrow[A_K_RT].fun, arrow[A_K_RT].type);
   1097 	keymacro_add(el, &strD[1], &arrow[A_K_LT].fun, arrow[A_K_LT].type);
   1098 	keymacro_add(el, &strH[1], &arrow[A_K_HO].fun, arrow[A_K_HO].type);
   1099 	keymacro_add(el, &strF[1], &arrow[A_K_EN].fun, arrow[A_K_EN].type);
   1100 	keymacro_add(el, &stOA[1], &arrow[A_K_UP].fun, arrow[A_K_UP].type);
   1101 	keymacro_add(el, &stOB[1], &arrow[A_K_DN].fun, arrow[A_K_DN].type);
   1102 	keymacro_add(el, &stOC[1], &arrow[A_K_RT].fun, arrow[A_K_RT].type);
   1103 	keymacro_add(el, &stOD[1], &arrow[A_K_LT].fun, arrow[A_K_LT].type);
   1104 	keymacro_add(el, &stOH[1], &arrow[A_K_HO].fun, arrow[A_K_HO].type);
   1105 	keymacro_add(el, &stOF[1], &arrow[A_K_EN].fun, arrow[A_K_EN].type);
   1106 }
   1107 
   1108 
   1109 /* terminal_set_arrow():
   1110  *	Set an arrow key binding
   1111  */
   1112 protected int
   1113 terminal_set_arrow(EditLine *el, const Char *name, keymacro_value_t *fun,
   1114     int type)
   1115 {
   1116 	funckey_t *arrow = el->el_terminal.t_fkey;
   1117 	int i;
   1118 
   1119 	for (i = 0; i < A_K_NKEYS; i++)
   1120 		if (Strcmp(name, arrow[i].name) == 0) {
   1121 			arrow[i].fun = *fun;
   1122 			arrow[i].type = type;
   1123 			return 0;
   1124 		}
   1125 	return -1;
   1126 }
   1127 
   1128 
   1129 /* terminal_clear_arrow():
   1130  *	Clear an arrow key binding
   1131  */
   1132 protected int
   1133 terminal_clear_arrow(EditLine *el, const Char *name)
   1134 {
   1135 	funckey_t *arrow = el->el_terminal.t_fkey;
   1136 	int i;
   1137 
   1138 	for (i = 0; i < A_K_NKEYS; i++)
   1139 		if (Strcmp(name, arrow[i].name) == 0) {
   1140 			arrow[i].type = XK_NOD;
   1141 			return 0;
   1142 		}
   1143 	return -1;
   1144 }
   1145 
   1146 
   1147 /* terminal_print_arrow():
   1148  *	Print the arrow key bindings
   1149  */
   1150 protected void
   1151 terminal_print_arrow(EditLine *el, const Char *name)
   1152 {
   1153 	int i;
   1154 	funckey_t *arrow = el->el_terminal.t_fkey;
   1155 
   1156 	for (i = 0; i < A_K_NKEYS; i++)
   1157 		if (*name == '\0' || Strcmp(name, arrow[i].name) == 0)
   1158 			if (arrow[i].type != XK_NOD)
   1159 				keymacro_kprint(el, arrow[i].name,
   1160 				    &arrow[i].fun, arrow[i].type);
   1161 }
   1162 
   1163 
   1164 /* terminal_bind_arrow():
   1165  *	Bind the arrow keys
   1166  */
   1167 protected void
   1168 terminal_bind_arrow(EditLine *el)
   1169 {
   1170 	el_action_t *map;
   1171 	const el_action_t *dmap;
   1172 	int i, j;
   1173 	char *p;
   1174 	funckey_t *arrow = el->el_terminal.t_fkey;
   1175 
   1176 	/* Check if the components needed are initialized */
   1177 	if (el->el_terminal.t_buf == NULL || el->el_map.key == NULL)
   1178 		return;
   1179 
   1180 	map = el->el_map.type == MAP_VI ? el->el_map.alt : el->el_map.key;
   1181 	dmap = el->el_map.type == MAP_VI ? el->el_map.vic : el->el_map.emacs;
   1182 
   1183 	terminal_reset_arrow(el);
   1184 
   1185 	for (i = 0; i < A_K_NKEYS; i++) {
   1186 		Char wt_str[VISUAL_WIDTH_MAX];
   1187 		Char *px;
   1188 		size_t n;
   1189 
   1190 		p = el->el_terminal.t_str[arrow[i].key];
   1191 		if (!p || !*p)
   1192 			continue;
   1193 		for (n = 0; n < VISUAL_WIDTH_MAX && p[n]; ++n)
   1194 			wt_str[n] = p[n];
   1195 		while (n < VISUAL_WIDTH_MAX)
   1196 			wt_str[n++] = '\0';
   1197 		px = wt_str;
   1198 		j = (unsigned char) *p;
   1199 		/*
   1200 		 * Assign the arrow keys only if:
   1201 		 *
   1202 		 * 1. They are multi-character arrow keys and the user
   1203 		 *    has not re-assigned the leading character, or
   1204 		 *    has re-assigned the leading character to be
   1205 		 *	  ED_SEQUENCE_LEAD_IN
   1206 		 * 2. They are single arrow keys pointing to an
   1207 		 *    unassigned key.
   1208 		 */
   1209 		if (arrow[i].type == XK_NOD)
   1210 			keymacro_clear(el, map, px);
   1211 		else {
   1212 			if (p[1] && (dmap[j] == map[j] ||
   1213 				map[j] == ED_SEQUENCE_LEAD_IN)) {
   1214 				keymacro_add(el, px, &arrow[i].fun,
   1215 				    arrow[i].type);
   1216 				map[j] = ED_SEQUENCE_LEAD_IN;
   1217 			} else if (map[j] == ED_UNASSIGNED) {
   1218 				keymacro_clear(el, map, px);
   1219 				if (arrow[i].type == XK_CMD)
   1220 					map[j] = arrow[i].fun.cmd;
   1221 				else
   1222 					keymacro_add(el, px, &arrow[i].fun,
   1223 					    arrow[i].type);
   1224 			}
   1225 		}
   1226 	}
   1227 }
   1228 
   1229 /* terminal_putc():
   1230  *	Add a character
   1231  */
   1232 private int
   1233 terminal_putc(int c)
   1234 {
   1235 	if (terminal_outfile == NULL)
   1236 		return -1;
   1237 	return fputc(c, terminal_outfile);
   1238 }
   1239 
   1240 private void
   1241 terminal_tputs(EditLine *el, const char *cap, int affcnt)
   1242 {
   1243 #ifdef _REENTRANT
   1244 	pthread_mutex_lock(&terminal_mutex);
   1245 #endif
   1246 	terminal_outfile = el->el_outfile;
   1247 	(void)tputs(cap, affcnt, terminal_putc);
   1248 #ifdef _REENTRANT
   1249 	pthread_mutex_unlock(&terminal_mutex);
   1250 #endif
   1251 }
   1252 
   1253 /* terminal__putc():
   1254  *	Add a character
   1255  */
   1256 protected int
   1257 terminal__putc(EditLine *el, wint_t c)
   1258 {
   1259 	char buf[MB_LEN_MAX +1];
   1260 	ssize_t i;
   1261 	if (c == (wint_t)MB_FILL_CHAR)
   1262 		return 0;
   1263 	i = ct_encode_char(buf, (size_t)MB_LEN_MAX, (Char)c);
   1264 	if (i <= 0)
   1265 		return (int)i;
   1266 	buf[i] = '\0';
   1267 	return fputs(buf, el->el_outfile);
   1268 }
   1269 
   1270 /* terminal__flush():
   1271  *	Flush output
   1272  */
   1273 protected void
   1274 terminal__flush(EditLine *el)
   1275 {
   1276 
   1277 	(void) fflush(el->el_outfile);
   1278 }
   1279 
   1280 /* terminal_writec():
   1281  *	Write the given character out, in a human readable form
   1282  */
   1283 protected void
   1284 terminal_writec(EditLine *el, wint_t c)
   1285 {
   1286 	Char visbuf[VISUAL_WIDTH_MAX +1];
   1287 	ssize_t vcnt = ct_visual_char(visbuf, VISUAL_WIDTH_MAX, (Char)c);
   1288 	if (vcnt < 0)
   1289 		vcnt = 0;
   1290 	visbuf[vcnt] = '\0';
   1291 	terminal_overwrite(el, visbuf, (size_t)vcnt);
   1292 	terminal__flush(el);
   1293 }
   1294 
   1295 
   1296 /* terminal_telltc():
   1297  *	Print the current termcap characteristics
   1298  */
   1299 protected int
   1300 /*ARGSUSED*/
   1301 terminal_telltc(EditLine *el, int argc __attribute__((__unused__)),
   1302     const Char **argv __attribute__((__unused__)))
   1303 {
   1304 	const struct termcapstr *t;
   1305 	char **ts;
   1306 
   1307 	(void) fprintf(el->el_outfile, "\n\tYour terminal has the\n");
   1308 	(void) fprintf(el->el_outfile, "\tfollowing characteristics:\n\n");
   1309 	(void) fprintf(el->el_outfile, "\tIt has %d columns and %d lines\n",
   1310 	    Val(T_co), Val(T_li));
   1311 	(void) fprintf(el->el_outfile,
   1312 	    "\tIt has %s meta key\n", EL_HAS_META ? "a" : "no");
   1313 	(void) fprintf(el->el_outfile,
   1314 	    "\tIt can%suse tabs\n", EL_CAN_TAB ? " " : "not ");
   1315 	(void) fprintf(el->el_outfile, "\tIt %s automatic margins\n",
   1316 	    EL_HAS_AUTO_MARGINS ? "has" : "does not have");
   1317 	if (EL_HAS_AUTO_MARGINS)
   1318 		(void) fprintf(el->el_outfile, "\tIt %s magic margins\n",
   1319 		    EL_HAS_MAGIC_MARGINS ? "has" : "does not have");
   1320 
   1321 	for (t = tstr, ts = el->el_terminal.t_str; t->name != NULL; t++, ts++) {
   1322 		const char *ub;
   1323 		if (*ts && **ts) {
   1324 			ub = ct_encode_string(ct_visual_string(
   1325 			    ct_decode_string(*ts, &el->el_scratch)),
   1326 			    &el->el_scratch);
   1327 		} else {
   1328 			ub = "(empty)";
   1329 		}
   1330 		(void) fprintf(el->el_outfile, "\t%25s (%s) == %s\n",
   1331 		    t->long_name, t->name, ub);
   1332 	}
   1333 	(void) fputc('\n', el->el_outfile);
   1334 	return 0;
   1335 }
   1336 
   1337 
   1338 /* terminal_settc():
   1339  *	Change the current terminal characteristics
   1340  */
   1341 protected int
   1342 /*ARGSUSED*/
   1343 terminal_settc(EditLine *el, int argc __attribute__((__unused__)),
   1344     const Char **argv)
   1345 {
   1346 	const struct termcapstr *ts;
   1347 	const struct termcapval *tv;
   1348 	char what[8], how[8];
   1349 
   1350 	if (argv == NULL || argv[1] == NULL || argv[2] == NULL)
   1351 		return -1;
   1352 
   1353 	strncpy(what, ct_encode_string(argv[1], &el->el_scratch), sizeof(what));
   1354 	what[sizeof(what) - 1] = '\0';
   1355 	strncpy(how,  ct_encode_string(argv[2], &el->el_scratch), sizeof(how));
   1356 	how[sizeof(how) - 1] = '\0';
   1357 
   1358 	/*
   1359          * Do the strings first
   1360          */
   1361 	for (ts = tstr; ts->name != NULL; ts++)
   1362 		if (strcmp(ts->name, what) == 0)
   1363 			break;
   1364 
   1365 	if (ts->name != NULL) {
   1366 		terminal_alloc(el, ts, how);
   1367 		terminal_setflags(el);
   1368 		return 0;
   1369 	}
   1370 	/*
   1371          * Do the numeric ones second
   1372          */
   1373 	for (tv = tval; tv->name != NULL; tv++)
   1374 		if (strcmp(tv->name, what) == 0)
   1375 			break;
   1376 
   1377 	if (tv->name != NULL)
   1378 		return -1;
   1379 
   1380 	if (tv == &tval[T_pt] || tv == &tval[T_km] ||
   1381 	    tv == &tval[T_am] || tv == &tval[T_xn]) {
   1382 		if (strcmp(how, "yes") == 0)
   1383 			el->el_terminal.t_val[tv - tval] = 1;
   1384 		else if (strcmp(how, "no") == 0)
   1385 			el->el_terminal.t_val[tv - tval] = 0;
   1386 		else {
   1387 			(void) fprintf(el->el_errfile,
   1388 			    "" FSTR ": Bad value `%s'.\n", argv[0], how);
   1389 			return -1;
   1390 		}
   1391 		terminal_setflags(el);
   1392 		if (terminal_change_size(el, Val(T_li), Val(T_co)) == -1)
   1393 			return -1;
   1394 		return 0;
   1395 	} else {
   1396 		long i;
   1397 		char *ep;
   1398 
   1399 		i = strtol(how, &ep, 10);
   1400 		if (*ep != '\0') {
   1401 			(void) fprintf(el->el_errfile,
   1402 			    "" FSTR ": Bad value `%s'.\n", argv[0], how);
   1403 			return -1;
   1404 		}
   1405 		el->el_terminal.t_val[tv - tval] = (int) i;
   1406 		el->el_terminal.t_size.v = Val(T_co);
   1407 		el->el_terminal.t_size.h = Val(T_li);
   1408 		if (tv == &tval[T_co] || tv == &tval[T_li])
   1409 			if (terminal_change_size(el, Val(T_li), Val(T_co))
   1410 			    == -1)
   1411 				return -1;
   1412 		return 0;
   1413 	}
   1414 }
   1415 
   1416 
   1417 /* terminal_gettc():
   1418  *	Get the current terminal characteristics
   1419  */
   1420 protected int
   1421 /*ARGSUSED*/
   1422 terminal_gettc(EditLine *el, int argc __attribute__((__unused__)), char **argv)
   1423 {
   1424 	const struct termcapstr *ts;
   1425 	const struct termcapval *tv;
   1426 	char *what;
   1427 	void *how;
   1428 
   1429 	if (argv == NULL || argv[1] == NULL || argv[2] == NULL)
   1430 		return -1;
   1431 
   1432 	what = argv[1];
   1433 	how = argv[2];
   1434 
   1435 	/*
   1436          * Do the strings first
   1437          */
   1438 	for (ts = tstr; ts->name != NULL; ts++)
   1439 		if (strcmp(ts->name, what) == 0)
   1440 			break;
   1441 
   1442 	if (ts->name != NULL) {
   1443 		*(char **)how = el->el_terminal.t_str[ts - tstr];
   1444 		return 0;
   1445 	}
   1446 	/*
   1447          * Do the numeric ones second
   1448          */
   1449 	for (tv = tval; tv->name != NULL; tv++)
   1450 		if (strcmp(tv->name, what) == 0)
   1451 			break;
   1452 
   1453 	if (tv->name == NULL)
   1454 		return -1;
   1455 
   1456 	if (tv == &tval[T_pt] || tv == &tval[T_km] ||
   1457 	    tv == &tval[T_am] || tv == &tval[T_xn]) {
   1458 		static char yes[] = "yes";
   1459 		static char no[] = "no";
   1460 		if (el->el_terminal.t_val[tv - tval])
   1461 			*(char **)how = yes;
   1462 		else
   1463 			*(char **)how = no;
   1464 		return 0;
   1465 	} else {
   1466 		*(int *)how = el->el_terminal.t_val[tv - tval];
   1467 		return 0;
   1468 	}
   1469 }
   1470 
   1471 /* terminal_echotc():
   1472  *	Print the termcap string out with variable substitution
   1473  */
   1474 protected int
   1475 /*ARGSUSED*/
   1476 terminal_echotc(EditLine *el, int argc __attribute__((__unused__)),
   1477     const Char **argv)
   1478 {
   1479 	char *cap, *scap;
   1480 	Char *ep;
   1481 	int arg_need, arg_cols, arg_rows;
   1482 	int verbose = 0, silent = 0;
   1483 	char *area;
   1484 	static const char fmts[] = "%s\n", fmtd[] = "%d\n";
   1485 	const struct termcapstr *t;
   1486 	char buf[TC_BUFSIZE];
   1487 	long i;
   1488 
   1489 	area = buf;
   1490 
   1491 	if (argv == NULL || argv[1] == NULL)
   1492 		return -1;
   1493 	argv++;
   1494 
   1495 	if (argv[0][0] == '-') {
   1496 		switch (argv[0][1]) {
   1497 		case 'v':
   1498 			verbose = 1;
   1499 			break;
   1500 		case 's':
   1501 			silent = 1;
   1502 			break;
   1503 		default:
   1504 			/* stderror(ERR_NAME | ERR_TCUSAGE); */
   1505 			break;
   1506 		}
   1507 		argv++;
   1508 	}
   1509 	if (!*argv || *argv[0] == '\0')
   1510 		return 0;
   1511 	if (Strcmp(*argv, STR("tabs")) == 0) {
   1512 		(void) fprintf(el->el_outfile, fmts, EL_CAN_TAB ? "yes" : "no");
   1513 		return 0;
   1514 	} else if (Strcmp(*argv, STR("meta")) == 0) {
   1515 		(void) fprintf(el->el_outfile, fmts, Val(T_km) ? "yes" : "no");
   1516 		return 0;
   1517 	} else if (Strcmp(*argv, STR("xn")) == 0) {
   1518 		(void) fprintf(el->el_outfile, fmts, EL_HAS_MAGIC_MARGINS ?
   1519 		    "yes" : "no");
   1520 		return 0;
   1521 	} else if (Strcmp(*argv, STR("am")) == 0) {
   1522 		(void) fprintf(el->el_outfile, fmts, EL_HAS_AUTO_MARGINS ?
   1523 		    "yes" : "no");
   1524 		return 0;
   1525 	} else if (Strcmp(*argv, STR("baud")) == 0) {
   1526 		(void) fprintf(el->el_outfile, fmtd, (int)el->el_tty.t_speed);
   1527 		return 0;
   1528 	} else if (Strcmp(*argv, STR("rows")) == 0 ||
   1529                    Strcmp(*argv, STR("lines")) == 0) {
   1530 		(void) fprintf(el->el_outfile, fmtd, Val(T_li));
   1531 		return 0;
   1532 	} else if (Strcmp(*argv, STR("cols")) == 0) {
   1533 		(void) fprintf(el->el_outfile, fmtd, Val(T_co));
   1534 		return 0;
   1535 	}
   1536 	/*
   1537          * Try to use our local definition first
   1538          */
   1539 	scap = NULL;
   1540 	for (t = tstr; t->name != NULL; t++)
   1541 		if (strcmp(t->name,
   1542 		    ct_encode_string(*argv, &el->el_scratch)) == 0) {
   1543 			scap = el->el_terminal.t_str[t - tstr];
   1544 			break;
   1545 		}
   1546 	if (t->name == NULL) {
   1547 		/* XXX: some systems' tgetstr needs non const */
   1548                 scap = tgetstr(ct_encode_string(*argv, &el->el_scratch), &area);
   1549 	}
   1550 	if (!scap || scap[0] == '\0') {
   1551 		if (!silent)
   1552 			(void) fprintf(el->el_errfile,
   1553 			    "echotc: Termcap parameter `" FSTR "' not found.\n",
   1554 			    *argv);
   1555 		return -1;
   1556 	}
   1557 	/*
   1558          * Count home many values we need for this capability.
   1559          */
   1560 	for (cap = scap, arg_need = 0; *cap; cap++)
   1561 		if (*cap == '%')
   1562 			switch (*++cap) {
   1563 			case 'd':
   1564 			case '2':
   1565 			case '3':
   1566 			case '.':
   1567 			case '+':
   1568 				arg_need++;
   1569 				break;
   1570 			case '%':
   1571 			case '>':
   1572 			case 'i':
   1573 			case 'r':
   1574 			case 'n':
   1575 			case 'B':
   1576 			case 'D':
   1577 				break;
   1578 			default:
   1579 				/*
   1580 				 * hpux has lot's of them...
   1581 				 */
   1582 				if (verbose)
   1583 					(void) fprintf(el->el_errfile,
   1584 				"echotc: Warning: unknown termcap %% `%c'.\n",
   1585 					    *cap);
   1586 				/* This is bad, but I won't complain */
   1587 				break;
   1588 			}
   1589 
   1590 	switch (arg_need) {
   1591 	case 0:
   1592 		argv++;
   1593 		if (*argv && *argv[0]) {
   1594 			if (!silent)
   1595 				(void) fprintf(el->el_errfile,
   1596 				    "echotc: Warning: Extra argument `" FSTR "'.\n",
   1597 				    *argv);
   1598 			return -1;
   1599 		}
   1600 		terminal_tputs(el, scap, 1);
   1601 		break;
   1602 	case 1:
   1603 		argv++;
   1604 		if (!*argv || *argv[0] == '\0') {
   1605 			if (!silent)
   1606 				(void) fprintf(el->el_errfile,
   1607 				    "echotc: Warning: Missing argument.\n");
   1608 			return -1;
   1609 		}
   1610 		arg_cols = 0;
   1611 		i = Strtol(*argv, &ep, 10);
   1612 		if (*ep != '\0' || i < 0) {
   1613 			if (!silent)
   1614 				(void) fprintf(el->el_errfile,
   1615 				    "echotc: Bad value `" FSTR "' for rows.\n",
   1616 				    *argv);
   1617 			return -1;
   1618 		}
   1619 		arg_rows = (int) i;
   1620 		argv++;
   1621 		if (*argv && *argv[0]) {
   1622 			if (!silent)
   1623 				(void) fprintf(el->el_errfile,
   1624 				    "echotc: Warning: Extra argument `" FSTR
   1625 				    "'.\n", *argv);
   1626 			return -1;
   1627 		}
   1628 		terminal_tputs(el, tgoto(scap, arg_cols, arg_rows), 1);
   1629 		break;
   1630 	default:
   1631 		/* This is wrong, but I will ignore it... */
   1632 		if (verbose)
   1633 			(void) fprintf(el->el_errfile,
   1634 			 "echotc: Warning: Too many required arguments (%d).\n",
   1635 			    arg_need);
   1636 		/* FALLTHROUGH */
   1637 	case 2:
   1638 		argv++;
   1639 		if (!*argv || *argv[0] == '\0') {
   1640 			if (!silent)
   1641 				(void) fprintf(el->el_errfile,
   1642 				    "echotc: Warning: Missing argument.\n");
   1643 			return -1;
   1644 		}
   1645 		i = Strtol(*argv, &ep, 10);
   1646 		if (*ep != '\0' || i < 0) {
   1647 			if (!silent)
   1648 				(void) fprintf(el->el_errfile,
   1649 				    "echotc: Bad value `" FSTR "' for cols.\n",
   1650 				    *argv);
   1651 			return -1;
   1652 		}
   1653 		arg_cols = (int) i;
   1654 		argv++;
   1655 		if (!*argv || *argv[0] == '\0') {
   1656 			if (!silent)
   1657 				(void) fprintf(el->el_errfile,
   1658 				    "echotc: Warning: Missing argument.\n");
   1659 			return -1;
   1660 		}
   1661 		i = Strtol(*argv, &ep, 10);
   1662 		if (*ep != '\0' || i < 0) {
   1663 			if (!silent)
   1664 				(void) fprintf(el->el_errfile,
   1665 				    "echotc: Bad value `" FSTR "' for rows.\n",
   1666 				    *argv);
   1667 			return -1;
   1668 		}
   1669 		arg_rows = (int) i;
   1670 		if (*ep != '\0') {
   1671 			if (!silent)
   1672 				(void) fprintf(el->el_errfile,
   1673 				    "echotc: Bad value `" FSTR "'.\n", *argv);
   1674 			return -1;
   1675 		}
   1676 		argv++;
   1677 		if (*argv && *argv[0]) {
   1678 			if (!silent)
   1679 				(void) fprintf(el->el_errfile,
   1680 				    "echotc: Warning: Extra argument `" FSTR
   1681 				    "'.\n", *argv);
   1682 			return -1;
   1683 		}
   1684 		terminal_tputs(el, tgoto(scap, arg_cols, arg_rows), arg_rows);
   1685 		break;
   1686 	}
   1687 	return 0;
   1688 }
   1689