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