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