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