xref: /freebsd/contrib/libedit/terminal.c (revision cc68614da8232d8baaca0ae0d0dd8f890f06623e)
1 /*	$NetBSD: terminal.c,v 1.44 2021/09/09 20:24:07 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.44 2021/09/09 20:24:07 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 <sys/types.h>
50 #include <sys/ioctl.h>
51 #include <limits.h>
52 #include <signal.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <unistd.h>
57 #ifdef HAVE_TERMCAP_H
58 #include <termcap.h>
59 #endif
60 #ifdef HAVE_CURSES_H
61 #include <curses.h>
62 #elif HAVE_NCURSES_H
63 #include <ncurses.h>
64 #endif
65 
66 /* Solaris's term.h does horrid things. */
67 #if defined(HAVE_TERM_H) && !defined(__sun) && !defined(HAVE_TERMCAP_H)
68 #include <term.h>
69 #endif
70 
71 #ifdef _REENTRANT
72 #include <pthread.h>
73 #endif
74 
75 #include "el.h"
76 #include "fcns.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 static 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 static 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 static void	terminal_setflags(EditLine *);
204 static int	terminal_rebuffer_display(EditLine *);
205 static void	terminal_free_display(EditLine *);
206 static int	terminal_alloc_display(EditLine *);
207 static void	terminal_alloc(EditLine *, const struct termcapstr *,
208     const char *);
209 static void	terminal_init_arrow(EditLine *);
210 static void	terminal_reset_arrow(EditLine *);
211 static int	terminal_putc(int);
212 static void	terminal_tputs(EditLine *, const char *, int);
213 
214 #ifdef _REENTRANT
215 static pthread_mutex_t terminal_mutex = PTHREAD_MUTEX_INITIALIZER;
216 #endif
217 static FILE *terminal_outfile = NULL;
218 
219 
220 /* terminal_setflags():
221  *	Set the terminal capability flags
222  */
223 static 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 libedit_private int
269 terminal_init(EditLine *el)
270 {
271 
272 	el->el_terminal.t_buf = el_calloc(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_calloc(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_calloc(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_calloc(T_str,
286 	    sizeof(*el->el_terminal.t_str));
287 	if (el->el_terminal.t_str == NULL)
288 		goto fail4;
289 	el->el_terminal.t_val = el_calloc(T_val,
290 	    sizeof(*el->el_terminal.t_val));
291 	if (el->el_terminal.t_val == NULL)
292 		goto fail5;
293 	(void) terminal_set(el, NULL);
294 	terminal_init_arrow(el);
295 	return 0;
296 fail5:
297 	free(el->el_terminal.t_str);
298 	el->el_terminal.t_str = NULL;
299 fail4:
300 	free(el->el_terminal.t_fkey);
301 	el->el_terminal.t_fkey = NULL;
302 fail3:
303 	free(el->el_terminal.t_cap);
304 	el->el_terminal.t_cap = NULL;
305 fail2:
306 	free(el->el_terminal.t_buf);
307 	el->el_terminal.t_buf = NULL;
308 fail1:
309 	return -1;
310 }
311 
312 /* terminal_end():
313  *	Clean up the terminal stuff
314  */
315 libedit_private void
316 terminal_end(EditLine *el)
317 {
318 
319 	el_free(el->el_terminal.t_buf);
320 	el->el_terminal.t_buf = NULL;
321 	el_free(el->el_terminal.t_cap);
322 	el->el_terminal.t_cap = NULL;
323 	el->el_terminal.t_loc = 0;
324 	el_free(el->el_terminal.t_str);
325 	el->el_terminal.t_str = NULL;
326 	el_free(el->el_terminal.t_val);
327 	el->el_terminal.t_val = NULL;
328 	el_free(el->el_terminal.t_fkey);
329 	el->el_terminal.t_fkey = NULL;
330 	terminal_free_display(el);
331 }
332 
333 
334 /* terminal_alloc():
335  *	Maintain a string pool for termcap strings
336  */
337 static void
338 terminal_alloc(EditLine *el, const struct termcapstr *t, const char *cap)
339 {
340 	char termbuf[TC_BUFSIZE];
341 	size_t tlen, clen;
342 	char **tlist = el->el_terminal.t_str;
343 	char **tmp, **str = &tlist[t - tstr];
344 
345 	(void) memset(termbuf, 0, sizeof(termbuf));
346 	if (cap == NULL || *cap == '\0') {
347 		*str = NULL;
348 		return;
349 	} else
350 		clen = strlen(cap);
351 
352 	tlen = *str == NULL ? 0 : strlen(*str);
353 
354 	/*
355          * New string is shorter; no need to allocate space
356          */
357 	if (clen <= tlen) {
358 		if (*str)
359 			(void) strcpy(*str, cap);	/* XXX strcpy is safe */
360 		return;
361 	}
362 	/*
363          * New string is longer; see if we have enough space to append
364          */
365 	if (el->el_terminal.t_loc + 3 < TC_BUFSIZE) {
366 						/* XXX strcpy is safe */
367 		(void) strcpy(*str = &el->el_terminal.t_buf[
368 		    el->el_terminal.t_loc], cap);
369 		el->el_terminal.t_loc += clen + 1;	/* one for \0 */
370 		return;
371 	}
372 	/*
373          * Compact our buffer; no need to check compaction, cause we know it
374          * fits...
375          */
376 	tlen = 0;
377 	for (tmp = tlist; tmp < &tlist[T_str]; tmp++)
378 		if (*tmp != NULL && **tmp != '\0' && *tmp != *str) {
379 			char *ptr;
380 
381 			for (ptr = *tmp; *ptr != '\0'; termbuf[tlen++] = *ptr++)
382 				continue;
383 			termbuf[tlen++] = '\0';
384 		}
385 	memcpy(el->el_terminal.t_buf, termbuf, TC_BUFSIZE);
386 	el->el_terminal.t_loc = tlen;
387 	if (el->el_terminal.t_loc + 3 >= TC_BUFSIZE) {
388 		(void) fprintf(el->el_errfile,
389 		    "Out of termcap string space.\n");
390 		return;
391 	}
392 					/* XXX strcpy is safe */
393 	(void) strcpy(*str = &el->el_terminal.t_buf[el->el_terminal.t_loc],
394 	    cap);
395 	el->el_terminal.t_loc += (size_t)clen + 1;	/* one for \0 */
396 	return;
397 }
398 
399 
400 /* terminal_rebuffer_display():
401  *	Rebuffer the display after the screen changed size
402  */
403 static int
404 terminal_rebuffer_display(EditLine *el)
405 {
406 	coord_t *c = &el->el_terminal.t_size;
407 
408 	terminal_free_display(el);
409 
410 	c->h = Val(T_co);
411 	c->v = Val(T_li);
412 
413 	if (terminal_alloc_display(el) == -1)
414 		return -1;
415 	return 0;
416 }
417 
418 static wint_t **
419 terminal_alloc_buffer(EditLine *el)
420 {
421 	wint_t **b;
422 	coord_t *c = &el->el_terminal.t_size;
423 	int i;
424 
425 	b =  el_calloc((size_t)(c->v + 1), sizeof(*b));
426 	if (b == NULL)
427 		return NULL;
428 	for (i = 0; i < c->v; i++) {
429 		b[i] = el_calloc((size_t)(c->h + 1), sizeof(**b));
430 		if (b[i] == NULL) {
431 			while (--i >= 0)
432 				el_free(b[i]);
433 			el_free(b);
434 			return NULL;
435 		}
436 	}
437 	b[c->v] = NULL;
438 	return b;
439 }
440 
441 static void
442 terminal_free_buffer(wint_t ***bp)
443 {
444 	wint_t **b;
445 	wint_t **bufp;
446 
447 	if (*bp == NULL)
448 		return;
449 
450 	b = *bp;
451 	*bp = NULL;
452 
453 	for (bufp = b; *bufp != NULL; bufp++)
454 		el_free(*bufp);
455 	el_free(b);
456 }
457 
458 /* terminal_alloc_display():
459  *	Allocate a new display.
460  */
461 static int
462 terminal_alloc_display(EditLine *el)
463 {
464 	el->el_display = terminal_alloc_buffer(el);
465 	if (el->el_display == NULL)
466 		goto done;
467 	el->el_vdisplay = terminal_alloc_buffer(el);
468 	if (el->el_vdisplay == NULL)
469 		goto done;
470 	return 0;
471 done:
472 	terminal_free_display(el);
473 	return -1;
474 }
475 
476 
477 /* terminal_free_display():
478  *	Free the display buffers
479  */
480 static void
481 terminal_free_display(EditLine *el)
482 {
483 	terminal_free_buffer(&el->el_display);
484 	terminal_free_buffer(&el->el_vdisplay);
485 }
486 
487 
488 /* terminal_move_to_line():
489  *	move to line <where> (first line == 0)
490  *	as efficiently as possible
491  */
492 libedit_private void
493 terminal_move_to_line(EditLine *el, int where)
494 {
495 	int del;
496 
497 	if (where == el->el_cursor.v)
498 		return;
499 
500 	if (where >= el->el_terminal.t_size.v) {
501 #ifdef DEBUG_SCREEN
502 		(void) fprintf(el->el_errfile,
503 		    "%s: where is ridiculous: %d\r\n", __func__, where);
504 #endif /* DEBUG_SCREEN */
505 		return;
506 	}
507 	if ((del = where - el->el_cursor.v) > 0) {
508 		/*
509 		 * We don't use DO here because some terminals are buggy
510 		 * if the destination is beyond bottom of the screen.
511 		 */
512 		for (; del > 0; del--)
513 			terminal__putc(el, '\n');
514 		/* because the \n will become \r\n */
515 		el->el_cursor.h = 0;
516 	} else {		/* del < 0 */
517 		if (GoodStr(T_UP) && (-del > 1 || !GoodStr(T_up)))
518 			terminal_tputs(el, tgoto(Str(T_UP), -del, -del), -del);
519 		else {
520 			if (GoodStr(T_up))
521 				for (; del < 0; del++)
522 					terminal_tputs(el, Str(T_up), 1);
523 		}
524 	}
525 	el->el_cursor.v = where;/* now where is here */
526 }
527 
528 
529 /* terminal_move_to_char():
530  *	Move to the character position specified
531  */
532 libedit_private void
533 terminal_move_to_char(EditLine *el, int where)
534 {
535 	int del, i;
536 
537 mc_again:
538 	if (where == el->el_cursor.h)
539 		return;
540 
541 	if (where > el->el_terminal.t_size.h) {
542 #ifdef DEBUG_SCREEN
543 		(void) fprintf(el->el_errfile,
544 		    "%s: where is ridiculous: %d\r\n", __func__, where);
545 #endif /* DEBUG_SCREEN */
546 		return;
547 	}
548 	if (!where) {		/* if where is first column */
549 		terminal__putc(el, '\r');	/* do a CR */
550 		el->el_cursor.h = 0;
551 		return;
552 	}
553 	del = where - el->el_cursor.h;
554 
555 	if ((del < -4 || del > 4) && GoodStr(T_ch))
556 		/* go there directly */
557 		terminal_tputs(el, tgoto(Str(T_ch), where, where), where);
558 	else {
559 		if (del > 0) {	/* moving forward */
560 			if ((del > 4) && GoodStr(T_RI))
561 				terminal_tputs(el, tgoto(Str(T_RI), del, del),
562 				    del);
563 			else {
564 					/* if I can do tabs, use them */
565 				if (EL_CAN_TAB) {
566 					if ((el->el_cursor.h & 0370) !=
567 					    (where & ~0x7)
568 					    && (el->el_display[
569 					    el->el_cursor.v][where & 0370] !=
570 					    MB_FILL_CHAR)
571 					    ) {
572 						/* if not within tab stop */
573 						for (i =
574 						    (el->el_cursor.h & 0370);
575 						    i < (where & ~0x7);
576 						    i += 8)
577 							terminal__putc(el,
578 							    '\t');
579 							/* then tab over */
580 						el->el_cursor.h = where & ~0x7;
581 					}
582 				}
583 				/*
584 				 * it's usually cheaper to just write the
585 				 * chars, so we do.
586 				 */
587 				/*
588 				 * NOTE THAT terminal_overwrite() WILL CHANGE
589 				 * el->el_cursor.h!!!
590 				 */
591 				terminal_overwrite(el,
592 				    (wchar_t *)&el->el_display[
593 				    el->el_cursor.v][el->el_cursor.h],
594 				    (size_t)(where - el->el_cursor.h));
595 
596 			}
597 		} else {	/* del < 0 := moving backward */
598 			if ((-del > 4) && GoodStr(T_LE))
599 				terminal_tputs(el, tgoto(Str(T_LE), -del, -del),
600 				    -del);
601 			else {	/* can't go directly there */
602 				/*
603 				 * if the "cost" is greater than the "cost"
604 				 * from col 0
605 				 */
606 				if (EL_CAN_TAB ?
607 				    ((unsigned int)-del >
608 				    (((unsigned int) where >> 3) +
609 				     (where & 07)))
610 				    : (-del > where)) {
611 					terminal__putc(el, '\r');/* do a CR */
612 					el->el_cursor.h = 0;
613 					goto mc_again;	/* and try again */
614 				}
615 				for (i = 0; i < -del; i++)
616 					terminal__putc(el, '\b');
617 			}
618 		}
619 	}
620 	el->el_cursor.h = where;		/* now where is here */
621 }
622 
623 
624 /* terminal_overwrite():
625  *	Overstrike num characters
626  *	Assumes MB_FILL_CHARs are present to keep the column count correct
627  */
628 libedit_private void
629 terminal_overwrite(EditLine *el, const wchar_t *cp, size_t n)
630 {
631 	if (n == 0)
632 		return;
633 
634 	if (n > (size_t)el->el_terminal.t_size.h) {
635 #ifdef DEBUG_SCREEN
636 		(void) fprintf(el->el_errfile,
637 		    "%s: n is ridiculous: %zu\r\n", __func__, n);
638 #endif /* DEBUG_SCREEN */
639 		return;
640 	}
641 
642         do {
643                 /* terminal__putc() ignores any MB_FILL_CHARs */
644                 terminal__putc(el, *cp++);
645                 el->el_cursor.h++;
646         } while (--n);
647 
648 	if (el->el_cursor.h >= el->el_terminal.t_size.h) {	/* wrap? */
649 		if (EL_HAS_AUTO_MARGINS) {	/* yes */
650 			el->el_cursor.h = 0;
651 			if (el->el_cursor.v + 1 < el->el_terminal.t_size.v)
652 				el->el_cursor.v++;
653 			if (EL_HAS_MAGIC_MARGINS) {
654 				/* force the wrap to avoid the "magic"
655 				 * situation */
656 				wchar_t c;
657 				if ((c = el->el_display[el->el_cursor.v]
658 				    [el->el_cursor.h]) != '\0') {
659 					terminal_overwrite(el, &c, (size_t)1);
660 					while (el->el_display[el->el_cursor.v]
661 					    [el->el_cursor.h] == MB_FILL_CHAR)
662 						el->el_cursor.h++;
663 				} else {
664 					terminal__putc(el, ' ');
665 					el->el_cursor.h = 1;
666 				}
667 			}
668 		} else		/* no wrap, but cursor stays on screen */
669 			el->el_cursor.h = el->el_terminal.t_size.h - 1;
670 	}
671 }
672 
673 
674 /* terminal_deletechars():
675  *	Delete num characters
676  */
677 libedit_private void
678 terminal_deletechars(EditLine *el, int num)
679 {
680 	if (num <= 0)
681 		return;
682 
683 	if (!EL_CAN_DELETE) {
684 #ifdef DEBUG_EDIT
685 		(void) fprintf(el->el_errfile, "   ERROR: cannot delete   \n");
686 #endif /* DEBUG_EDIT */
687 		return;
688 	}
689 	if (num > el->el_terminal.t_size.h) {
690 #ifdef DEBUG_SCREEN
691 		(void) fprintf(el->el_errfile,
692 		    "%s: num is ridiculous: %d\r\n", __func__, num);
693 #endif /* DEBUG_SCREEN */
694 		return;
695 	}
696 	if (GoodStr(T_DC))	/* if I have multiple delete */
697 		if ((num > 1) || !GoodStr(T_dc)) {	/* if dc would be more
698 							 * expen. */
699 			terminal_tputs(el, tgoto(Str(T_DC), num, num), num);
700 			return;
701 		}
702 	if (GoodStr(T_dm))	/* if I have delete mode */
703 		terminal_tputs(el, Str(T_dm), 1);
704 
705 	if (GoodStr(T_dc))	/* else do one at a time */
706 		while (num--)
707 			terminal_tputs(el, Str(T_dc), 1);
708 
709 	if (GoodStr(T_ed))	/* if I have delete mode */
710 		terminal_tputs(el, Str(T_ed), 1);
711 }
712 
713 
714 /* terminal_insertwrite():
715  *	Puts terminal in insert character mode or inserts num
716  *	characters in the line
717  *      Assumes MB_FILL_CHARs are present to keep column count correct
718  */
719 libedit_private void
720 terminal_insertwrite(EditLine *el, wchar_t *cp, int num)
721 {
722 	if (num <= 0)
723 		return;
724 	if (!EL_CAN_INSERT) {
725 #ifdef DEBUG_EDIT
726 		(void) fprintf(el->el_errfile, "   ERROR: cannot insert   \n");
727 #endif /* DEBUG_EDIT */
728 		return;
729 	}
730 	if (num > el->el_terminal.t_size.h) {
731 #ifdef DEBUG_SCREEN
732 		(void) fprintf(el->el_errfile,
733 		    "%s: num is ridiculous: %d\r\n", __func__, num);
734 #endif /* DEBUG_SCREEN */
735 		return;
736 	}
737 	if (GoodStr(T_IC))	/* if I have multiple insert */
738 		if ((num > 1) || !GoodStr(T_ic)) {
739 				/* if ic would be more expensive */
740 			terminal_tputs(el, tgoto(Str(T_IC), num, num), num);
741 			terminal_overwrite(el, cp, (size_t)num);
742 				/* this updates el_cursor.h */
743 			return;
744 		}
745 	if (GoodStr(T_im) && GoodStr(T_ei)) {	/* if I have insert mode */
746 		terminal_tputs(el, Str(T_im), 1);
747 
748 		el->el_cursor.h += num;
749 		do
750 			terminal__putc(el, *cp++);
751 		while (--num);
752 
753 		if (GoodStr(T_ip))	/* have to make num chars insert */
754 			terminal_tputs(el, Str(T_ip), 1);
755 
756 		terminal_tputs(el, Str(T_ei), 1);
757 		return;
758 	}
759 	do {
760 		if (GoodStr(T_ic))	/* have to make num chars insert */
761 			terminal_tputs(el, Str(T_ic), 1);
762 
763 		terminal__putc(el, *cp++);
764 
765 		el->el_cursor.h++;
766 
767 		if (GoodStr(T_ip))	/* have to make num chars insert */
768 			terminal_tputs(el, Str(T_ip), 1);
769 					/* pad the inserted char */
770 
771 	} while (--num);
772 }
773 
774 
775 /* terminal_clear_EOL():
776  *	clear to end of line.  There are num characters to clear
777  */
778 libedit_private void
779 terminal_clear_EOL(EditLine *el, int num)
780 {
781 	int i;
782 
783 	if (EL_CAN_CEOL && GoodStr(T_ce))
784 		terminal_tputs(el, Str(T_ce), 1);
785 	else {
786 		for (i = 0; i < num; i++)
787 			terminal__putc(el, ' ');
788 		el->el_cursor.h += num;	/* have written num spaces */
789 	}
790 }
791 
792 
793 /* terminal_clear_screen():
794  *	Clear the screen
795  */
796 libedit_private void
797 terminal_clear_screen(EditLine *el)
798 {				/* clear the whole screen and home */
799 
800 	if (GoodStr(T_cl))
801 		/* send the clear screen code */
802 		terminal_tputs(el, Str(T_cl), Val(T_li));
803 	else if (GoodStr(T_ho) && GoodStr(T_cd)) {
804 		terminal_tputs(el, Str(T_ho), Val(T_li));	/* home */
805 		/* clear to bottom of screen */
806 		terminal_tputs(el, Str(T_cd), Val(T_li));
807 	} else {
808 		terminal__putc(el, '\r');
809 		terminal__putc(el, '\n');
810 	}
811 }
812 
813 
814 /* terminal_beep():
815  *	Beep the way the terminal wants us
816  */
817 libedit_private void
818 terminal_beep(EditLine *el)
819 {
820 	if (GoodStr(T_bl))
821 		/* what termcap says we should use */
822 		terminal_tputs(el, Str(T_bl), 1);
823 	else
824 		terminal__putc(el, '\007');	/* an ASCII bell; ^G */
825 }
826 
827 
828 libedit_private void
829 terminal_get(EditLine *el, const char **term)
830 {
831 	*term = el->el_terminal.t_name;
832 }
833 
834 
835 /* terminal_set():
836  *	Read in the terminal capabilities from the requested terminal
837  */
838 libedit_private int
839 terminal_set(EditLine *el, const char *term)
840 {
841 	int i;
842 	char buf[TC_BUFSIZE];
843 	char *area;
844 	const struct termcapstr *t;
845 	sigset_t oset, nset;
846 	int lins, cols;
847 
848 	(void) sigemptyset(&nset);
849 	(void) sigaddset(&nset, SIGWINCH);
850 	(void) sigprocmask(SIG_BLOCK, &nset, &oset);
851 
852 	area = buf;
853 
854 
855 	if (term == NULL)
856 		term = getenv("TERM");
857 
858 	if (!term || !term[0])
859 		term = "dumb";
860 
861 	if (strcmp(term, "emacs") == 0)
862 		el->el_flags |= EDIT_DISABLED;
863 
864 	(void) memset(el->el_terminal.t_cap, 0, TC_BUFSIZE);
865 
866 	i = tgetent(el->el_terminal.t_cap, term);
867 
868 	if (i <= 0) {
869 		if (i == -1)
870 			(void) fprintf(el->el_errfile,
871 			    "Cannot read termcap database;\n");
872 		else if (i == 0)
873 			(void) fprintf(el->el_errfile,
874 			    "No entry for terminal type \"%s\";\n", term);
875 		(void) fprintf(el->el_errfile,
876 		    "using dumb terminal settings.\n");
877 		Val(T_co) = 80;	/* do a dumb terminal */
878 		Val(T_pt) = Val(T_km) = Val(T_li) = 0;
879 		Val(T_xt) = Val(T_MT);
880 		for (t = tstr; t->name != NULL; t++)
881 			terminal_alloc(el, t, NULL);
882 	} else {
883 		/* auto/magic margins */
884 		Val(T_am) = tgetflag("am");
885 		Val(T_xn) = tgetflag("xn");
886 		/* Can we tab */
887 		Val(T_pt) = tgetflag("pt");
888 		Val(T_xt) = tgetflag("xt");
889 		/* do we have a meta? */
890 		Val(T_km) = tgetflag("km");
891 		Val(T_MT) = tgetflag("MT");
892 		/* Get the size */
893 		Val(T_co) = tgetnum("co");
894 		Val(T_li) = tgetnum("li");
895 		for (t = tstr; t->name != NULL; t++) {
896 			/* XXX: some systems' tgetstr needs non const */
897 			terminal_alloc(el, t, tgetstr(strchr(t->name, *t->name),
898 			    &area));
899 		}
900 	}
901 
902 	if (Val(T_co) < 2)
903 		Val(T_co) = 80;	/* just in case */
904 	if (Val(T_li) < 1)
905 		Val(T_li) = 24;
906 
907 	el->el_terminal.t_size.v = Val(T_co);
908 	el->el_terminal.t_size.h = Val(T_li);
909 
910 	terminal_setflags(el);
911 
912 				/* get the correct window size */
913 	(void) terminal_get_size(el, &lins, &cols);
914 	if (terminal_change_size(el, lins, cols) == -1)
915 		return -1;
916 	(void) sigprocmask(SIG_SETMASK, &oset, NULL);
917 	terminal_bind_arrow(el);
918 	el->el_terminal.t_name = term;
919 	return i <= 0 ? -1 : 0;
920 }
921 
922 
923 /* terminal_get_size():
924  *	Return the new window size in lines and cols, and
925  *	true if the size was changed.
926  */
927 libedit_private int
928 terminal_get_size(EditLine *el, int *lins, int *cols)
929 {
930 
931 	*cols = Val(T_co);
932 	*lins = Val(T_li);
933 
934 #ifdef TIOCGWINSZ
935 	{
936 		struct winsize ws;
937 		if (ioctl(el->el_infd, TIOCGWINSZ, &ws) != -1) {
938 			if (ws.ws_col)
939 				*cols = ws.ws_col;
940 			if (ws.ws_row)
941 				*lins = ws.ws_row;
942 		}
943 	}
944 #endif
945 #ifdef TIOCGSIZE
946 	{
947 		struct ttysize ts;
948 		if (ioctl(el->el_infd, TIOCGSIZE, &ts) != -1) {
949 			if (ts.ts_cols)
950 				*cols = ts.ts_cols;
951 			if (ts.ts_lines)
952 				*lins = ts.ts_lines;
953 		}
954 	}
955 #endif
956 	return Val(T_co) != *cols || Val(T_li) != *lins;
957 }
958 
959 
960 /* terminal_change_size():
961  *	Change the size of the terminal
962  */
963 libedit_private int
964 terminal_change_size(EditLine *el, int lins, int cols)
965 {
966 	coord_t cur = el->el_cursor;
967 	/*
968 	 * Just in case
969 	 */
970 	Val(T_co) = (cols < 2) ? 80 : cols;
971 	Val(T_li) = (lins < 1) ? 24 : lins;
972 
973 	/* re-make display buffers */
974 	if (terminal_rebuffer_display(el) == -1)
975 		return -1;
976 	re_clear_display(el);
977 	el->el_cursor = cur;
978 	return 0;
979 }
980 
981 
982 /* terminal_init_arrow():
983  *	Initialize the arrow key bindings from termcap
984  */
985 static void
986 terminal_init_arrow(EditLine *el)
987 {
988 	funckey_t *arrow = el->el_terminal.t_fkey;
989 
990 	arrow[A_K_DN].name = L"down";
991 	arrow[A_K_DN].key = T_kd;
992 	arrow[A_K_DN].fun.cmd = ED_NEXT_HISTORY;
993 	arrow[A_K_DN].type = XK_CMD;
994 
995 	arrow[A_K_UP].name = L"up";
996 	arrow[A_K_UP].key = T_ku;
997 	arrow[A_K_UP].fun.cmd = ED_PREV_HISTORY;
998 	arrow[A_K_UP].type = XK_CMD;
999 
1000 	arrow[A_K_LT].name = L"left";
1001 	arrow[A_K_LT].key = T_kl;
1002 	arrow[A_K_LT].fun.cmd = ED_PREV_CHAR;
1003 	arrow[A_K_LT].type = XK_CMD;
1004 
1005 	arrow[A_K_RT].name = L"right";
1006 	arrow[A_K_RT].key = T_kr;
1007 	arrow[A_K_RT].fun.cmd = ED_NEXT_CHAR;
1008 	arrow[A_K_RT].type = XK_CMD;
1009 
1010 	arrow[A_K_HO].name = L"home";
1011 	arrow[A_K_HO].key = T_kh;
1012 	arrow[A_K_HO].fun.cmd = ED_MOVE_TO_BEG;
1013 	arrow[A_K_HO].type = XK_CMD;
1014 
1015 	arrow[A_K_EN].name = L"end";
1016 	arrow[A_K_EN].key = T_at7;
1017 	arrow[A_K_EN].fun.cmd = ED_MOVE_TO_END;
1018 	arrow[A_K_EN].type = XK_CMD;
1019 
1020 	arrow[A_K_DE].name = L"delete";
1021 	arrow[A_K_DE].key = T_kD;
1022 	arrow[A_K_DE].fun.cmd = ED_DELETE_NEXT_CHAR;
1023 	arrow[A_K_DE].type = XK_CMD;
1024 }
1025 
1026 
1027 /* terminal_reset_arrow():
1028  *	Reset arrow key bindings
1029  */
1030 static void
1031 terminal_reset_arrow(EditLine *el)
1032 {
1033 	funckey_t *arrow = el->el_terminal.t_fkey;
1034 	static const wchar_t strA[] = L"\033[A";
1035 	static const wchar_t strB[] = L"\033[B";
1036 	static const wchar_t strC[] = L"\033[C";
1037 	static const wchar_t strD[] = L"\033[D";
1038 	static const wchar_t strH[] = L"\033[H";
1039 	static const wchar_t strF[] = L"\033[F";
1040 	static const wchar_t stOA[] = L"\033OA";
1041 	static const wchar_t stOB[] = L"\033OB";
1042 	static const wchar_t stOC[] = L"\033OC";
1043 	static const wchar_t stOD[] = L"\033OD";
1044 	static const wchar_t stOH[] = L"\033OH";
1045 	static const wchar_t stOF[] = L"\033OF";
1046 
1047 	keymacro_add(el, strA, &arrow[A_K_UP].fun, arrow[A_K_UP].type);
1048 	keymacro_add(el, strB, &arrow[A_K_DN].fun, arrow[A_K_DN].type);
1049 	keymacro_add(el, strC, &arrow[A_K_RT].fun, arrow[A_K_RT].type);
1050 	keymacro_add(el, strD, &arrow[A_K_LT].fun, arrow[A_K_LT].type);
1051 	keymacro_add(el, strH, &arrow[A_K_HO].fun, arrow[A_K_HO].type);
1052 	keymacro_add(el, strF, &arrow[A_K_EN].fun, arrow[A_K_EN].type);
1053 	keymacro_add(el, stOA, &arrow[A_K_UP].fun, arrow[A_K_UP].type);
1054 	keymacro_add(el, stOB, &arrow[A_K_DN].fun, arrow[A_K_DN].type);
1055 	keymacro_add(el, stOC, &arrow[A_K_RT].fun, arrow[A_K_RT].type);
1056 	keymacro_add(el, stOD, &arrow[A_K_LT].fun, arrow[A_K_LT].type);
1057 	keymacro_add(el, stOH, &arrow[A_K_HO].fun, arrow[A_K_HO].type);
1058 	keymacro_add(el, stOF, &arrow[A_K_EN].fun, arrow[A_K_EN].type);
1059 
1060 	if (el->el_map.type != MAP_VI)
1061 		return;
1062 	keymacro_add(el, &strA[1], &arrow[A_K_UP].fun, arrow[A_K_UP].type);
1063 	keymacro_add(el, &strB[1], &arrow[A_K_DN].fun, arrow[A_K_DN].type);
1064 	keymacro_add(el, &strC[1], &arrow[A_K_RT].fun, arrow[A_K_RT].type);
1065 	keymacro_add(el, &strD[1], &arrow[A_K_LT].fun, arrow[A_K_LT].type);
1066 	keymacro_add(el, &strH[1], &arrow[A_K_HO].fun, arrow[A_K_HO].type);
1067 	keymacro_add(el, &strF[1], &arrow[A_K_EN].fun, arrow[A_K_EN].type);
1068 	keymacro_add(el, &stOA[1], &arrow[A_K_UP].fun, arrow[A_K_UP].type);
1069 	keymacro_add(el, &stOB[1], &arrow[A_K_DN].fun, arrow[A_K_DN].type);
1070 	keymacro_add(el, &stOC[1], &arrow[A_K_RT].fun, arrow[A_K_RT].type);
1071 	keymacro_add(el, &stOD[1], &arrow[A_K_LT].fun, arrow[A_K_LT].type);
1072 	keymacro_add(el, &stOH[1], &arrow[A_K_HO].fun, arrow[A_K_HO].type);
1073 	keymacro_add(el, &stOF[1], &arrow[A_K_EN].fun, arrow[A_K_EN].type);
1074 }
1075 
1076 
1077 /* terminal_set_arrow():
1078  *	Set an arrow key binding
1079  */
1080 libedit_private int
1081 terminal_set_arrow(EditLine *el, const wchar_t *name, keymacro_value_t *fun,
1082     int type)
1083 {
1084 	funckey_t *arrow = el->el_terminal.t_fkey;
1085 	int i;
1086 
1087 	for (i = 0; i < A_K_NKEYS; i++)
1088 		if (wcscmp(name, arrow[i].name) == 0) {
1089 			arrow[i].fun = *fun;
1090 			arrow[i].type = type;
1091 			return 0;
1092 		}
1093 	return -1;
1094 }
1095 
1096 
1097 /* terminal_clear_arrow():
1098  *	Clear an arrow key binding
1099  */
1100 libedit_private int
1101 terminal_clear_arrow(EditLine *el, const wchar_t *name)
1102 {
1103 	funckey_t *arrow = el->el_terminal.t_fkey;
1104 	int i;
1105 
1106 	for (i = 0; i < A_K_NKEYS; i++)
1107 		if (wcscmp(name, arrow[i].name) == 0) {
1108 			arrow[i].type = XK_NOD;
1109 			return 0;
1110 		}
1111 	return -1;
1112 }
1113 
1114 
1115 /* terminal_print_arrow():
1116  *	Print the arrow key bindings
1117  */
1118 libedit_private void
1119 terminal_print_arrow(EditLine *el, const wchar_t *name)
1120 {
1121 	int i;
1122 	funckey_t *arrow = el->el_terminal.t_fkey;
1123 
1124 	for (i = 0; i < A_K_NKEYS; i++)
1125 		if (*name == '\0' || wcscmp(name, arrow[i].name) == 0)
1126 			if (arrow[i].type != XK_NOD)
1127 				keymacro_kprint(el, arrow[i].name,
1128 				    &arrow[i].fun, arrow[i].type);
1129 }
1130 
1131 
1132 /* terminal_bind_arrow():
1133  *	Bind the arrow keys
1134  */
1135 libedit_private void
1136 terminal_bind_arrow(EditLine *el)
1137 {
1138 	el_action_t *map;
1139 	const el_action_t *dmap;
1140 	int i, j;
1141 	char *p;
1142 	funckey_t *arrow = el->el_terminal.t_fkey;
1143 
1144 	/* Check if the components needed are initialized */
1145 	if (el->el_terminal.t_buf == NULL || el->el_map.key == NULL)
1146 		return;
1147 
1148 	map = el->el_map.type == MAP_VI ? el->el_map.alt : el->el_map.key;
1149 	dmap = el->el_map.type == MAP_VI ? el->el_map.vic : el->el_map.emacs;
1150 
1151 	terminal_reset_arrow(el);
1152 
1153 	for (i = 0; i < A_K_NKEYS; i++) {
1154 		wchar_t wt_str[VISUAL_WIDTH_MAX];
1155 		wchar_t *px;
1156 		size_t n;
1157 
1158 		p = el->el_terminal.t_str[arrow[i].key];
1159 		if (!p || !*p)
1160 			continue;
1161 		for (n = 0; n < VISUAL_WIDTH_MAX && p[n]; ++n)
1162 			wt_str[n] = p[n];
1163 		while (n < VISUAL_WIDTH_MAX)
1164 			wt_str[n++] = '\0';
1165 		px = wt_str;
1166 		j = (unsigned char) *p;
1167 		/*
1168 		 * Assign the arrow keys only if:
1169 		 *
1170 		 * 1. They are multi-character arrow keys and the user
1171 		 *    has not re-assigned the leading character, or
1172 		 *    has re-assigned the leading character to be
1173 		 *	  ED_SEQUENCE_LEAD_IN
1174 		 * 2. They are single arrow keys pointing to an
1175 		 *    unassigned key.
1176 		 */
1177 		if (arrow[i].type == XK_NOD)
1178 			keymacro_clear(el, map, px);
1179 		else {
1180 			if (p[1] && (dmap[j] == map[j] ||
1181 				map[j] == ED_SEQUENCE_LEAD_IN)) {
1182 				keymacro_add(el, px, &arrow[i].fun,
1183 				    arrow[i].type);
1184 				map[j] = ED_SEQUENCE_LEAD_IN;
1185 			} else if (map[j] == ED_UNASSIGNED) {
1186 				keymacro_clear(el, map, px);
1187 				if (arrow[i].type == XK_CMD)
1188 					map[j] = arrow[i].fun.cmd;
1189 				else
1190 					keymacro_add(el, px, &arrow[i].fun,
1191 					    arrow[i].type);
1192 			}
1193 		}
1194 	}
1195 }
1196 
1197 /* terminal_putc():
1198  *	Add a character
1199  */
1200 static int
1201 terminal_putc(int c)
1202 {
1203 	if (terminal_outfile == NULL)
1204 		return -1;
1205 	return fputc(c, terminal_outfile);
1206 }
1207 
1208 static void
1209 terminal_tputs(EditLine *el, const char *cap, int affcnt)
1210 {
1211 #ifdef _REENTRANT
1212 	pthread_mutex_lock(&terminal_mutex);
1213 #endif
1214 	terminal_outfile = el->el_outfile;
1215 	(void)tputs(cap, affcnt, terminal_putc);
1216 #ifdef _REENTRANT
1217 	pthread_mutex_unlock(&terminal_mutex);
1218 #endif
1219 }
1220 
1221 /* terminal__putc():
1222  *	Add a character
1223  */
1224 libedit_private int
1225 terminal__putc(EditLine *el, wint_t c)
1226 {
1227 	char buf[MB_LEN_MAX +1];
1228 	ssize_t i;
1229 	if (c == MB_FILL_CHAR)
1230 		return 0;
1231 	if (c & EL_LITERAL)
1232 		return fputs(literal_get(el, c), el->el_outfile);
1233 	i = ct_encode_char(buf, (size_t)MB_LEN_MAX, c);
1234 	if (i <= 0)
1235 		return (int)i;
1236 	buf[i] = '\0';
1237 	return fputs(buf, el->el_outfile);
1238 }
1239 
1240 /* terminal__flush():
1241  *	Flush output
1242  */
1243 libedit_private void
1244 terminal__flush(EditLine *el)
1245 {
1246 
1247 	(void) fflush(el->el_outfile);
1248 }
1249 
1250 /* terminal_writec():
1251  *	Write the given character out, in a human readable form
1252  */
1253 libedit_private void
1254 terminal_writec(EditLine *el, wint_t c)
1255 {
1256 	wchar_t visbuf[VISUAL_WIDTH_MAX +1];
1257 	ssize_t vcnt = ct_visual_char(visbuf, VISUAL_WIDTH_MAX, c);
1258 	if (vcnt < 0)
1259 		vcnt = 0;
1260 	visbuf[vcnt] = '\0';
1261 	terminal_overwrite(el, visbuf, (size_t)vcnt);
1262 	terminal__flush(el);
1263 }
1264 
1265 
1266 /* terminal_telltc():
1267  *	Print the current termcap characteristics
1268  */
1269 libedit_private int
1270 /*ARGSUSED*/
1271 terminal_telltc(EditLine *el, int argc __attribute__((__unused__)),
1272     const wchar_t **argv __attribute__((__unused__)))
1273 {
1274 	const struct termcapstr *t;
1275 	char **ts;
1276 
1277 	(void) fprintf(el->el_outfile, "\n\tYour terminal has the\n");
1278 	(void) fprintf(el->el_outfile, "\tfollowing characteristics:\n\n");
1279 	(void) fprintf(el->el_outfile, "\tIt has %d columns and %d lines\n",
1280 	    Val(T_co), Val(T_li));
1281 	(void) fprintf(el->el_outfile,
1282 	    "\tIt has %s meta key\n", EL_HAS_META ? "a" : "no");
1283 	(void) fprintf(el->el_outfile,
1284 	    "\tIt can%suse tabs\n", EL_CAN_TAB ? " " : "not ");
1285 	(void) fprintf(el->el_outfile, "\tIt %s automatic margins\n",
1286 	    EL_HAS_AUTO_MARGINS ? "has" : "does not have");
1287 	if (EL_HAS_AUTO_MARGINS)
1288 		(void) fprintf(el->el_outfile, "\tIt %s magic margins\n",
1289 		    EL_HAS_MAGIC_MARGINS ? "has" : "does not have");
1290 
1291 	for (t = tstr, ts = el->el_terminal.t_str; t->name != NULL; t++, ts++) {
1292 		const char *ub;
1293 		if (*ts && **ts) {
1294 			ub = ct_encode_string(ct_visual_string(
1295 			    ct_decode_string(*ts, &el->el_scratch),
1296 			    &el->el_visual), &el->el_scratch);
1297 		} else {
1298 			ub = "(empty)";
1299 		}
1300 		(void) fprintf(el->el_outfile, "\t%25s (%s) == %s\n",
1301 		    t->long_name, t->name, ub);
1302 	}
1303 	(void) fputc('\n', el->el_outfile);
1304 	return 0;
1305 }
1306 
1307 
1308 /* terminal_settc():
1309  *	Change the current terminal characteristics
1310  */
1311 libedit_private int
1312 /*ARGSUSED*/
1313 terminal_settc(EditLine *el, int argc __attribute__((__unused__)),
1314     const wchar_t **argv)
1315 {
1316 	const struct termcapstr *ts;
1317 	const struct termcapval *tv;
1318 	char what[8], how[8];
1319 	long i;
1320 	char *ep;
1321 
1322 	if (argv == NULL || argv[1] == NULL || argv[2] == NULL)
1323 		return -1;
1324 
1325 	strlcpy(what, ct_encode_string(argv[1], &el->el_scratch), sizeof(what));
1326 	strlcpy(how,  ct_encode_string(argv[2], &el->el_scratch), sizeof(how));
1327 
1328 	/*
1329          * Do the strings first
1330          */
1331 	for (ts = tstr; ts->name != NULL; ts++)
1332 		if (strcmp(ts->name, what) == 0)
1333 			break;
1334 
1335 	if (ts->name != NULL) {
1336 		terminal_alloc(el, ts, how);
1337 		terminal_setflags(el);
1338 		return 0;
1339 	}
1340 	/*
1341          * Do the numeric ones second
1342          */
1343 	for (tv = tval; tv->name != NULL; tv++)
1344 		if (strcmp(tv->name, what) == 0)
1345 			break;
1346 
1347 	if (tv->name == NULL) {
1348 		(void) fprintf(el->el_errfile,
1349 		    "%ls: Bad capability `%s'.\n", argv[0], what);
1350 		return -1;
1351 	}
1352 
1353 	if (tv == &tval[T_pt] || tv == &tval[T_km] ||
1354 	    tv == &tval[T_am] || tv == &tval[T_xn]) {
1355 		/*
1356 		 * Booleans
1357 		 */
1358 		if (strcmp(how, "yes") == 0)
1359 			el->el_terminal.t_val[tv - tval] = 1;
1360 		else if (strcmp(how, "no") == 0)
1361 			el->el_terminal.t_val[tv - tval] = 0;
1362 		else {
1363 			(void) fprintf(el->el_errfile,
1364 			    "%ls: Bad value `%s'.\n", argv[0], how);
1365 			return -1;
1366 		}
1367 		terminal_setflags(el);
1368 		return 0;
1369 	}
1370 
1371 	/*
1372 	 * Numerics
1373 	 */
1374 	i = strtol(how, &ep, 10);
1375 	if (*ep != '\0') {
1376 		(void) fprintf(el->el_errfile,
1377 		    "%ls: Bad value `%s'.\n", argv[0], how);
1378 		return -1;
1379 	}
1380 	el->el_terminal.t_val[tv - tval] = (int) i;
1381 	i = 0;
1382 	if (tv == &tval[T_co]) {
1383 		el->el_terminal.t_size.v = Val(T_co);
1384 		i++;
1385 	} else if (tv == &tval[T_li]) {
1386 		el->el_terminal.t_size.h = Val(T_li);
1387 		i++;
1388 	}
1389 	if (i && terminal_change_size(el, Val(T_li), Val(T_co)) == -1)
1390 		return -1;
1391 	return 0;
1392 }
1393 
1394 
1395 /* terminal_gettc():
1396  *	Get the current terminal characteristics
1397  */
1398 libedit_private int
1399 /*ARGSUSED*/
1400 terminal_gettc(EditLine *el, int argc __attribute__((__unused__)), char **argv)
1401 {
1402 	const struct termcapstr *ts;
1403 	const struct termcapval *tv;
1404 	char *what;
1405 	void *how;
1406 
1407 	if (argv == NULL || argv[1] == NULL || argv[2] == NULL)
1408 		return -1;
1409 
1410 	what = argv[1];
1411 	how = argv[2];
1412 
1413 	/*
1414          * Do the strings first
1415          */
1416 	for (ts = tstr; ts->name != NULL; ts++)
1417 		if (strcmp(ts->name, what) == 0)
1418 			break;
1419 
1420 	if (ts->name != NULL) {
1421 		*(char **)how = el->el_terminal.t_str[ts - tstr];
1422 		return 0;
1423 	}
1424 	/*
1425          * Do the numeric ones second
1426          */
1427 	for (tv = tval; tv->name != NULL; tv++)
1428 		if (strcmp(tv->name, what) == 0)
1429 			break;
1430 
1431 	if (tv->name == NULL)
1432 		return -1;
1433 
1434 	if (tv == &tval[T_pt] || tv == &tval[T_km] ||
1435 	    tv == &tval[T_am] || tv == &tval[T_xn]) {
1436 		static char yes[] = "yes";
1437 		static char no[] = "no";
1438 		if (el->el_terminal.t_val[tv - tval])
1439 			*(char **)how = yes;
1440 		else
1441 			*(char **)how = no;
1442 		return 0;
1443 	} else {
1444 		*(int *)how = el->el_terminal.t_val[tv - tval];
1445 		return 0;
1446 	}
1447 }
1448 
1449 /* terminal_echotc():
1450  *	Print the termcap string out with variable substitution
1451  */
1452 libedit_private int
1453 /*ARGSUSED*/
1454 terminal_echotc(EditLine *el, int argc __attribute__((__unused__)),
1455     const wchar_t **argv)
1456 {
1457 	char *cap, *scap;
1458 	wchar_t *ep;
1459 	int arg_need, arg_cols, arg_rows;
1460 	int verbose = 0, silent = 0;
1461 	char *area;
1462 	static const char fmts[] = "%s\n", fmtd[] = "%d\n";
1463 	const struct termcapstr *t;
1464 	char buf[TC_BUFSIZE];
1465 	long i;
1466 
1467 	area = buf;
1468 
1469 	if (argv == NULL || argv[1] == NULL)
1470 		return -1;
1471 	argv++;
1472 
1473 	if (argv[0][0] == '-') {
1474 		switch (argv[0][1]) {
1475 		case 'v':
1476 			verbose = 1;
1477 			break;
1478 		case 's':
1479 			silent = 1;
1480 			break;
1481 		default:
1482 			/* stderror(ERR_NAME | ERR_TCUSAGE); */
1483 			break;
1484 		}
1485 		argv++;
1486 	}
1487 	if (!*argv || *argv[0] == '\0')
1488 		return 0;
1489 	if (wcscmp(*argv, L"tabs") == 0) {
1490 		(void) fprintf(el->el_outfile, fmts, EL_CAN_TAB ? "yes" : "no");
1491 		return 0;
1492 	} else if (wcscmp(*argv, L"meta") == 0) {
1493 		(void) fprintf(el->el_outfile, fmts, Val(T_km) ? "yes" : "no");
1494 		return 0;
1495 	} else if (wcscmp(*argv, L"xn") == 0) {
1496 		(void) fprintf(el->el_outfile, fmts, EL_HAS_MAGIC_MARGINS ?
1497 		    "yes" : "no");
1498 		return 0;
1499 	} else if (wcscmp(*argv, L"am") == 0) {
1500 		(void) fprintf(el->el_outfile, fmts, EL_HAS_AUTO_MARGINS ?
1501 		    "yes" : "no");
1502 		return 0;
1503 	} else if (wcscmp(*argv, L"baud") == 0) {
1504 		(void) fprintf(el->el_outfile, fmtd, (int)el->el_tty.t_speed);
1505 		return 0;
1506 	} else if (wcscmp(*argv, L"rows") == 0 ||
1507                    wcscmp(*argv, L"lines") == 0) {
1508 		(void) fprintf(el->el_outfile, fmtd, Val(T_li));
1509 		return 0;
1510 	} else if (wcscmp(*argv, L"cols") == 0) {
1511 		(void) fprintf(el->el_outfile, fmtd, Val(T_co));
1512 		return 0;
1513 	}
1514 	/*
1515          * Try to use our local definition first
1516          */
1517 	scap = NULL;
1518 	for (t = tstr; t->name != NULL; t++)
1519 		if (strcmp(t->name,
1520 		    ct_encode_string(*argv, &el->el_scratch)) == 0) {
1521 			scap = el->el_terminal.t_str[t - tstr];
1522 			break;
1523 		}
1524 	if (t->name == NULL) {
1525 		/* XXX: some systems' tgetstr needs non const */
1526                 scap = tgetstr(ct_encode_string(*argv, &el->el_scratch), &area);
1527 	}
1528 	if (!scap || scap[0] == '\0') {
1529 		if (!silent)
1530 			(void) fprintf(el->el_errfile,
1531 			    "echotc: Termcap parameter `%ls' not found.\n",
1532 			    *argv);
1533 		return -1;
1534 	}
1535 	/*
1536          * Count home many values we need for this capability.
1537          */
1538 	for (cap = scap, arg_need = 0; *cap; cap++)
1539 		if (*cap == '%')
1540 			switch (*++cap) {
1541 			case 'd':
1542 			case '2':
1543 			case '3':
1544 			case '.':
1545 			case '+':
1546 				arg_need++;
1547 				break;
1548 			case '%':
1549 			case '>':
1550 			case 'i':
1551 			case 'r':
1552 			case 'n':
1553 			case 'B':
1554 			case 'D':
1555 				break;
1556 			default:
1557 				/*
1558 				 * hpux has lot's of them...
1559 				 */
1560 				if (verbose)
1561 					(void) fprintf(el->el_errfile,
1562 				"echotc: Warning: unknown termcap %% `%c'.\n",
1563 					    *cap);
1564 				/* This is bad, but I won't complain */
1565 				break;
1566 			}
1567 
1568 	switch (arg_need) {
1569 	case 0:
1570 		argv++;
1571 		if (*argv && *argv[0]) {
1572 			if (!silent)
1573 				(void) fprintf(el->el_errfile,
1574 				    "echotc: Warning: Extra argument `%ls'.\n",
1575 				    *argv);
1576 			return -1;
1577 		}
1578 		terminal_tputs(el, scap, 1);
1579 		break;
1580 	case 1:
1581 		argv++;
1582 		if (!*argv || *argv[0] == '\0') {
1583 			if (!silent)
1584 				(void) fprintf(el->el_errfile,
1585 				    "echotc: Warning: Missing argument.\n");
1586 			return -1;
1587 		}
1588 		arg_cols = 0;
1589 		i = wcstol(*argv, &ep, 10);
1590 		if (*ep != '\0' || i < 0) {
1591 			if (!silent)
1592 				(void) fprintf(el->el_errfile,
1593 				    "echotc: Bad value `%ls' for rows.\n",
1594 				    *argv);
1595 			return -1;
1596 		}
1597 		arg_rows = (int) i;
1598 		argv++;
1599 		if (*argv && *argv[0]) {
1600 			if (!silent)
1601 				(void) fprintf(el->el_errfile,
1602 				    "echotc: Warning: Extra argument `%ls"
1603 				    "'.\n", *argv);
1604 			return -1;
1605 		}
1606 		terminal_tputs(el, tgoto(scap, arg_cols, arg_rows), 1);
1607 		break;
1608 	default:
1609 		/* This is wrong, but I will ignore it... */
1610 		if (verbose)
1611 			(void) fprintf(el->el_errfile,
1612 			 "echotc: Warning: Too many required arguments (%d).\n",
1613 			    arg_need);
1614 		/* FALLTHROUGH */
1615 	case 2:
1616 		argv++;
1617 		if (!*argv || *argv[0] == '\0') {
1618 			if (!silent)
1619 				(void) fprintf(el->el_errfile,
1620 				    "echotc: Warning: Missing argument.\n");
1621 			return -1;
1622 		}
1623 		i = wcstol(*argv, &ep, 10);
1624 		if (*ep != '\0' || i < 0) {
1625 			if (!silent)
1626 				(void) fprintf(el->el_errfile,
1627 				    "echotc: Bad value `%ls' for cols.\n",
1628 				    *argv);
1629 			return -1;
1630 		}
1631 		arg_cols = (int) i;
1632 		argv++;
1633 		if (!*argv || *argv[0] == '\0') {
1634 			if (!silent)
1635 				(void) fprintf(el->el_errfile,
1636 				    "echotc: Warning: Missing argument.\n");
1637 			return -1;
1638 		}
1639 		i = wcstol(*argv, &ep, 10);
1640 		if (*ep != '\0' || i < 0) {
1641 			if (!silent)
1642 				(void) fprintf(el->el_errfile,
1643 				    "echotc: Bad value `%ls' for rows.\n",
1644 				    *argv);
1645 			return -1;
1646 		}
1647 		arg_rows = (int) i;
1648 		if (*ep != '\0') {
1649 			if (!silent)
1650 				(void) fprintf(el->el_errfile,
1651 				    "echotc: Bad value `%ls'.\n", *argv);
1652 			return -1;
1653 		}
1654 		argv++;
1655 		if (*argv && *argv[0]) {
1656 			if (!silent)
1657 				(void) fprintf(el->el_errfile,
1658 				    "echotc: Warning: Extra argument `%ls"
1659 				    "'.\n", *argv);
1660 			return -1;
1661 		}
1662 		terminal_tputs(el, tgoto(scap, arg_cols, arg_rows), arg_rows);
1663 		break;
1664 	}
1665 	return 0;
1666 }
1667