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