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