]> ncurses.scripts.mit.edu Git - ncurses.git/blob - progs/dump_entry.c
ncurses 5.9 - patch 20130427
[ncurses.git] / progs / dump_entry.c
1 /****************************************************************************
2  * Copyright (c) 1998-2012,2013 Free Software Foundation, Inc.              *
3  *                                                                          *
4  * Permission is hereby granted, free of charge, to any person obtaining a  *
5  * copy of this software and associated documentation files (the            *
6  * "Software"), to deal in the Software without restriction, including      *
7  * without limitation the rights to use, copy, modify, merge, publish,      *
8  * distribute, distribute with modifications, sublicense, and/or sell       *
9  * copies of the Software, and to permit persons to whom the Software is    *
10  * furnished to do so, subject to the following conditions:                 *
11  *                                                                          *
12  * The above copyright notice and this permission notice shall be included  *
13  * in all copies or substantial portions of the Software.                   *
14  *                                                                          *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS  *
16  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF               *
17  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.   *
18  * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,   *
19  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR    *
20  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR    *
21  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.                               *
22  *                                                                          *
23  * Except as contained in this notice, the name(s) of the above copyright   *
24  * holders shall not be used in advertising or otherwise to promote the     *
25  * sale, use or other dealings in this Software without prior written       *
26  * authorization.                                                           *
27  ****************************************************************************/
28
29 /****************************************************************************
30  *  Author: Zeyd M. Ben-Halim <zmbenhal@netcom.com> 1992,1995               *
31  *     and: Eric S. Raymond <esr@snark.thyrsus.com>                         *
32  *     and: Thomas E. Dickey                        1996 on                 *
33  ****************************************************************************/
34
35 #define __INTERNAL_CAPS_VISIBLE
36 #include <progs.priv.h>
37
38 #include "dump_entry.h"
39 #include "termsort.c"           /* this C file is generated */
40 #include <parametrized.h>       /* so is this */
41
42 MODULE_ID("$Id: dump_entry.c,v 1.108 2013/04/27 21:45:19 tom Exp $")
43
44 #define INDENT                  8
45 #define DISCARD(string) string = ABSENT_STRING
46 #define PRINTF (void) printf
47
48 #define OkIndex(index,array) ((int)(index) >= 0 && (int)(index) < (int) SIZEOF(array))
49
50 typedef struct {
51     char *text;
52     size_t used;
53     size_t size;
54 } DYNBUF;
55
56 static int tversion;            /* terminfo version */
57 static int outform;             /* output format to use */
58 static int sortmode;            /* sort mode to use */
59 static int width = 60;          /* max line width for listings */
60 static int height = 65535;      /* max number of lines for listings */
61 static int column;              /* current column, limited by 'width' */
62 static int oldcol;              /* last value of column before wrap */
63 static bool pretty;             /* true if we format if-then-else strings */
64
65 static char *save_sgr;
66
67 static DYNBUF outbuf;
68 static DYNBUF tmpbuf;
69
70 /* indirection pointers for implementing sort and display modes */
71 static const PredIdx *bool_indirect, *num_indirect, *str_indirect;
72 static NCURSES_CONST char *const *bool_names;
73 static NCURSES_CONST char *const *num_names;
74 static NCURSES_CONST char *const *str_names;
75
76 static const char *separator = "", *trailer = "";
77
78 /* cover various ports and variants of terminfo */
79 #define V_ALLCAPS       0       /* all capabilities (SVr4, XSI, ncurses) */
80 #define V_SVR1          1       /* SVR1, Ultrix */
81 #define V_HPUX          2       /* HP/UX */
82 #define V_AIX           3       /* AIX */
83 #define V_BSD           4       /* BSD */
84
85 #if NCURSES_XNAMES
86 #define OBSOLETE(n) (!_nc_user_definable && (n[0] == 'O' && n[1] == 'T'))
87 #else
88 #define OBSOLETE(n) (n[0] == 'O' && n[1] == 'T')
89 #endif
90
91 #define isObsolete(f,n) ((f == F_TERMINFO || f == F_VARIABLE) && OBSOLETE(n))
92
93 #if NCURSES_XNAMES
94 #define BoolIndirect(j) ((j >= BOOLCOUNT) ? (j) : ((sortmode == S_NOSORT) ? j : bool_indirect[j]))
95 #define NumIndirect(j)  ((j >= NUMCOUNT)  ? (j) : ((sortmode == S_NOSORT) ? j : num_indirect[j]))
96 #define StrIndirect(j)  ((j >= STRCOUNT)  ? (j) : ((sortmode == S_NOSORT) ? j : str_indirect[j]))
97 #else
98 #define BoolIndirect(j) ((sortmode == S_NOSORT) ? (j) : bool_indirect[j])
99 #define NumIndirect(j)  ((sortmode == S_NOSORT) ? (j) : num_indirect[j])
100 #define StrIndirect(j)  ((sortmode == S_NOSORT) ? (j) : str_indirect[j])
101 #endif
102
103 static void failed(const char *) GCC_NORETURN;
104
105 static void
106 failed(const char *s)
107 {
108     perror(s);
109     ExitProgram(EXIT_FAILURE);
110 }
111
112 static void
113 strncpy_DYN(DYNBUF * dst, const char *src, size_t need)
114 {
115     size_t want = need + dst->used + 1;
116     if (want > dst->size) {
117         dst->size += (want + 1024);     /* be generous */
118         dst->text = typeRealloc(char, dst->size, dst->text);
119         if (dst->text == 0)
120             failed("strncpy_DYN");
121     }
122     (void) strncpy(dst->text + dst->used, src, need);
123     dst->used += need;
124     dst->text[dst->used] = 0;
125 }
126
127 static void
128 strcpy_DYN(DYNBUF * dst, const char *src)
129 {
130     if (src == 0) {
131         dst->used = 0;
132         strcpy_DYN(dst, "");
133     } else {
134         strncpy_DYN(dst, src, strlen(src));
135     }
136 }
137
138 #if NO_LEAKS
139 static void
140 free_DYN(DYNBUF * p)
141 {
142     if (p->text != 0)
143         free(p->text);
144     p->text = 0;
145     p->size = 0;
146     p->used = 0;
147 }
148
149 void
150 _nc_leaks_dump_entry(void)
151 {
152     free_DYN(&outbuf);
153     free_DYN(&tmpbuf);
154 }
155 #endif
156
157 #define NameTrans(check,result) \
158             if (OkIndex(np->nte_index, check) \
159                 && check[np->nte_index]) \
160                 return (result[np->nte_index])
161
162 NCURSES_CONST char *
163 nametrans(const char *name)
164 /* translate a capability name from termcap to terminfo */
165 {
166     const struct name_table_entry *np;
167
168     if ((np = _nc_find_entry(name, _nc_get_hash_table(0))) != 0)
169         switch (np->nte_type) {
170         case BOOLEAN:
171             NameTrans(bool_from_termcap, boolcodes);
172             break;
173
174         case NUMBER:
175             NameTrans(num_from_termcap, numcodes);
176             break;
177
178         case STRING:
179             NameTrans(str_from_termcap, strcodes);
180             break;
181         }
182
183     return (0);
184 }
185
186 void
187 dump_init(const char *version,
188           int mode,
189           int sort,
190           int twidth,
191           int theight,
192           unsigned traceval,
193           bool formatted)
194 /* set up for entry display */
195 {
196     width = twidth;
197     height = theight;
198     pretty = formatted;
199
200     /* versions */
201     if (version == 0)
202         tversion = V_ALLCAPS;
203     else if (!strcmp(version, "SVr1") || !strcmp(version, "SVR1")
204              || !strcmp(version, "Ultrix"))
205         tversion = V_SVR1;
206     else if (!strcmp(version, "HP"))
207         tversion = V_HPUX;
208     else if (!strcmp(version, "AIX"))
209         tversion = V_AIX;
210     else if (!strcmp(version, "BSD"))
211         tversion = V_BSD;
212     else
213         tversion = V_ALLCAPS;
214
215     /* implement display modes */
216     switch (outform = mode) {
217     case F_LITERAL:
218     case F_TERMINFO:
219         bool_names = boolnames;
220         num_names = numnames;
221         str_names = strnames;
222         separator = (twidth > 0 && theight > 1) ? ", " : ",";
223         trailer = "\n\t";
224         break;
225
226     case F_VARIABLE:
227         bool_names = boolfnames;
228         num_names = numfnames;
229         str_names = strfnames;
230         separator = (twidth > 0 && theight > 1) ? ", " : ",";
231         trailer = "\n\t";
232         break;
233
234     case F_TERMCAP:
235     case F_TCONVERR:
236         bool_names = boolcodes;
237         num_names = numcodes;
238         str_names = strcodes;
239         separator = ":";
240         trailer = "\\\n\t:";
241         break;
242     }
243
244     /* implement sort modes */
245     switch (sortmode = sort) {
246     case S_NOSORT:
247         if (traceval)
248             (void) fprintf(stderr,
249                            "%s: sorting by term structure order\n", _nc_progname);
250         break;
251
252     case S_TERMINFO:
253         if (traceval)
254             (void) fprintf(stderr,
255                            "%s: sorting by terminfo name order\n", _nc_progname);
256         bool_indirect = bool_terminfo_sort;
257         num_indirect = num_terminfo_sort;
258         str_indirect = str_terminfo_sort;
259         break;
260
261     case S_VARIABLE:
262         if (traceval)
263             (void) fprintf(stderr,
264                            "%s: sorting by C variable order\n", _nc_progname);
265         bool_indirect = bool_variable_sort;
266         num_indirect = num_variable_sort;
267         str_indirect = str_variable_sort;
268         break;
269
270     case S_TERMCAP:
271         if (traceval)
272             (void) fprintf(stderr,
273                            "%s: sorting by termcap name order\n", _nc_progname);
274         bool_indirect = bool_termcap_sort;
275         num_indirect = num_termcap_sort;
276         str_indirect = str_termcap_sort;
277         break;
278     }
279
280     if (traceval)
281         (void) fprintf(stderr,
282                        "%s: width = %d, tversion = %d, outform = %d\n",
283                        _nc_progname, width, tversion, outform);
284 }
285
286 static TERMTYPE *cur_type;
287
288 static int
289 dump_predicate(PredType type, PredIdx idx)
290 /* predicate function to use for ordinary decompilation */
291 {
292     switch (type) {
293     case BOOLEAN:
294         return (cur_type->Booleans[idx] == FALSE)
295             ? FAIL : cur_type->Booleans[idx];
296
297     case NUMBER:
298         return (cur_type->Numbers[idx] == ABSENT_NUMERIC)
299             ? FAIL : cur_type->Numbers[idx];
300
301     case STRING:
302         return (cur_type->Strings[idx] != ABSENT_STRING)
303             ? (int) TRUE : FAIL;
304     }
305
306     return (FALSE);             /* pacify compiler */
307 }
308
309 static void set_obsolete_termcaps(TERMTYPE *tp);
310
311 /* is this the index of a function key string? */
312 #define FNKEY(i)        (((i)<= 65 && (i)>= 75) || ((i)<= 216 && (i)>= 268))
313
314 /*
315  * If we configure with a different Caps file, the offsets into the arrays
316  * will change.  So we use an address expression.
317  */
318 #define BOOL_IDX(name) (PredType) (&(name) - &(CUR Booleans[0]))
319 #define NUM_IDX(name)  (PredType) (&(name) - &(CUR Numbers[0]))
320 #define STR_IDX(name)  (PredType) (&(name) - &(CUR Strings[0]))
321
322 static bool
323 version_filter(PredType type, PredIdx idx)
324 /* filter out capabilities we may want to suppress */
325 {
326     switch (tversion) {
327     case V_ALLCAPS:             /* SVr4, XSI Curses */
328         return (TRUE);
329
330     case V_SVR1:                /* System V Release 1, Ultrix */
331         switch (type) {
332         case BOOLEAN:
333             return ((idx <= BOOL_IDX(xon_xoff)) ? TRUE : FALSE);
334         case NUMBER:
335             return ((idx <= NUM_IDX(width_status_line)) ? TRUE : FALSE);
336         case STRING:
337             return ((idx <= STR_IDX(prtr_non)) ? TRUE : FALSE);
338         }
339         break;
340
341     case V_HPUX:                /* Hewlett-Packard */
342         switch (type) {
343         case BOOLEAN:
344             return ((idx <= BOOL_IDX(xon_xoff)) ? TRUE : FALSE);
345         case NUMBER:
346             return ((idx <= NUM_IDX(label_width)) ? TRUE : FALSE);
347         case STRING:
348             if (idx <= STR_IDX(prtr_non))
349                 return (TRUE);
350             else if (FNKEY(idx))        /* function keys */
351                 return (TRUE);
352             else if (idx == STR_IDX(plab_norm)
353                      || idx == STR_IDX(label_on)
354                      || idx == STR_IDX(label_off))
355                 return (TRUE);
356             else
357                 return (FALSE);
358         }
359         break;
360
361     case V_AIX:         /* AIX */
362         switch (type) {
363         case BOOLEAN:
364             return ((idx <= BOOL_IDX(xon_xoff)) ? TRUE : FALSE);
365         case NUMBER:
366             return ((idx <= NUM_IDX(width_status_line)) ? TRUE : FALSE);
367         case STRING:
368             if (idx <= STR_IDX(prtr_non))
369                 return (TRUE);
370             else if (FNKEY(idx))        /* function keys */
371                 return (TRUE);
372             else
373                 return (FALSE);
374         }
375         break;
376
377 #define is_termcap(type) (OkIndex(idx, type##_from_termcap) && \
378                           type##_from_termcap[idx])
379
380     case V_BSD:         /* BSD */
381         switch (type) {
382         case BOOLEAN:
383             return is_termcap(bool);
384         case NUMBER:
385             return is_termcap(num);
386         case STRING:
387             return is_termcap(str);
388         }
389         break;
390     }
391
392     return (FALSE);             /* pacify the compiler */
393 }
394
395 static void
396 trim_trailing(void)
397 {
398     while (outbuf.used > 0 && outbuf.text[outbuf.used - 1] == ' ')
399         outbuf.text[--outbuf.used] = '\0';
400 }
401
402 static void
403 force_wrap(void)
404 {
405     oldcol = column;
406     trim_trailing();
407     strcpy_DYN(&outbuf, trailer);
408     column = INDENT;
409 }
410
411 static void
412 wrap_concat(const char *src)
413 {
414     size_t need = strlen(src);
415     size_t want = strlen(separator) + need;
416
417     if (column > INDENT
418         && column + (int) want > width) {
419         force_wrap();
420     }
421     strcpy_DYN(&outbuf, src);
422     strcpy_DYN(&outbuf, separator);
423     column += (int) need;
424 }
425
426 #define IGNORE_SEP_TRAIL(first,last,sep_trail) \
427         if ((size_t)(last - first) > sizeof(sep_trail)-1 \
428          && !strncmp(first, sep_trail, sizeof(sep_trail)-1)) \
429                 first += sizeof(sep_trail)-2
430
431 /* Returns the nominal length of the buffer assuming it is termcap format,
432  * i.e., the continuation sequence is treated as a single character ":".
433  *
434  * There are several implementations of termcap which read the text into a
435  * fixed-size buffer.  Generally they strip the newlines from the text, but may
436  * not do it until after the buffer is read.  Also, "tc=" resolution may be
437  * expanded in the same buffer.  This function is useful for measuring the size
438  * of the best fixed-buffer implementation; the worst case may be much worse.
439  */
440 #ifdef TEST_TERMCAP_LENGTH
441 static int
442 termcap_length(const char *src)
443 {
444     static const char pattern[] = ":\\\n\t:";
445
446     int len = 0;
447     const char *const t = src + strlen(src);
448
449     while (*src != '\0') {
450         IGNORE_SEP_TRAIL(src, t, pattern);
451         src++;
452         len++;
453     }
454     return len;
455 }
456 #else
457 #define termcap_length(src) strlen(src)
458 #endif
459
460 static void
461 indent_DYN(DYNBUF * buffer, int level)
462 {
463     int n;
464
465     for (n = 0; n < level; n++)
466         strncpy_DYN(buffer, "\t", 1);
467 }
468
469 static bool
470 has_params(const char *src)
471 {
472     bool result = FALSE;
473     int len = (int) strlen(src);
474     int n;
475     bool ifthen = FALSE;
476     bool params = FALSE;
477
478     for (n = 0; n < len - 1; ++n) {
479         if (!strncmp(src + n, "%p", 2)) {
480             params = TRUE;
481         } else if (!strncmp(src + n, "%;", 2)) {
482             ifthen = TRUE;
483             result = params;
484             break;
485         }
486     }
487     if (!ifthen) {
488         result = ((len > 50) && params);
489     }
490     return result;
491 }
492
493 static char *
494 fmt_complex(TERMTYPE *tterm, const char *capability, char *src, int level)
495 {
496     bool percent = FALSE;
497     bool params = has_params(src);
498
499     while (*src != '\0') {
500         switch (*src) {
501         case '\\':
502             percent = FALSE;
503             strncpy_DYN(&tmpbuf, src++, 1);
504             break;
505         case '%':
506             percent = TRUE;
507             break;
508         case '?':               /* "if" */
509         case 't':               /* "then" */
510         case 'e':               /* "else" */
511             if (percent) {
512                 percent = FALSE;
513                 tmpbuf.text[tmpbuf.used - 1] = '\n';
514                 /* treat a "%e" as else-if, on the same level */
515                 if (*src == 'e') {
516                     indent_DYN(&tmpbuf, level);
517                     strncpy_DYN(&tmpbuf, "%", 1);
518                     strncpy_DYN(&tmpbuf, src, 1);
519                     src++;
520                     params = has_params(src);
521                     if (!params && *src != '\0' && *src != '%') {
522                         strncpy_DYN(&tmpbuf, "\n", 1);
523                         indent_DYN(&tmpbuf, level + 1);
524                     }
525                 } else {
526                     indent_DYN(&tmpbuf, level + 1);
527                     strncpy_DYN(&tmpbuf, "%", 1);
528                     strncpy_DYN(&tmpbuf, src, 1);
529                     if (*src++ == '?') {
530                         src = fmt_complex(tterm, capability, src, level + 1);
531                         if (*src != '\0' && *src != '%') {
532                             strncpy_DYN(&tmpbuf, "\n", 1);
533                             indent_DYN(&tmpbuf, level + 1);
534                         }
535                     } else if (level == 1) {
536                         _nc_warning("%s: %%%c without %%? in %s",
537                                     _nc_first_name(tterm->term_names),
538                                     *src, capability);
539                     }
540                 }
541                 continue;
542             }
543             break;
544         case ';':               /* "endif" */
545             if (percent) {
546                 percent = FALSE;
547                 if (level > 1) {
548                     tmpbuf.text[tmpbuf.used - 1] = '\n';
549                     indent_DYN(&tmpbuf, level);
550                     strncpy_DYN(&tmpbuf, "%", 1);
551                     strncpy_DYN(&tmpbuf, src++, 1);
552                     if (src[0] == '%'
553                         && src[1] != '\0'
554                         && (strchr("?e;", src[1])) == 0) {
555                         tmpbuf.text[tmpbuf.used++] = '\n';
556                         indent_DYN(&tmpbuf, level);
557                     }
558                     return src;
559                 }
560                 _nc_warning("%s: %%; without %%? in %s",
561                             _nc_first_name(tterm->term_names),
562                             capability);
563             }
564             break;
565         case 'p':
566             if (percent && params) {
567                 tmpbuf.text[tmpbuf.used - 1] = '\n';
568                 indent_DYN(&tmpbuf, level + 1);
569                 strncpy_DYN(&tmpbuf, "%", 1);
570             }
571             params = FALSE;
572             percent = FALSE;
573             break;
574         case ' ':
575             strncpy_DYN(&tmpbuf, "\\s", 2);
576             ++src;
577             continue;
578         default:
579             percent = FALSE;
580             break;
581         }
582         strncpy_DYN(&tmpbuf, src++, 1);
583     }
584     return src;
585 }
586
587 #define SAME_CAP(n,cap) (&tterm->Strings[n] == &cap)
588 #define EXTRA_CAP 20
589
590 int
591 fmt_entry(TERMTYPE *tterm,
592           PredFunc pred,
593           bool content_only,
594           bool suppress_untranslatable,
595           bool infodump,
596           int numbers)
597 {
598     PredIdx i, j;
599     char buffer[MAX_TERMINFO_LENGTH + EXTRA_CAP];
600     char *capability;
601     NCURSES_CONST char *name;
602     int predval, len;
603     PredIdx num_bools = 0;
604     PredIdx num_values = 0;
605     PredIdx num_strings = 0;
606     bool outcount = 0;
607
608 #define WRAP_CONCAT     \
609         wrap_concat(buffer); \
610         outcount = TRUE
611
612     len = 12;                   /* terminfo file-header */
613
614     if (pred == 0) {
615         cur_type = tterm;
616         pred = dump_predicate;
617     }
618
619     strcpy_DYN(&outbuf, 0);
620     if (content_only) {
621         column = INDENT;        /* FIXME: workaround to prevent empty lines */
622     } else {
623         strcpy_DYN(&outbuf, tterm->term_names);
624
625         /*
626          * Colon is legal in terminfo descriptions, but not in termcap.
627          */
628         if (!infodump) {
629             char *p = outbuf.text;
630             while (*p) {
631                 if (*p == ':') {
632                     *p = '=';
633                 }
634                 ++p;
635             }
636         }
637         strcpy_DYN(&outbuf, separator);
638         column = (int) outbuf.used;
639         if (height > 1)
640             force_wrap();
641     }
642
643     for_each_boolean(j, tterm) {
644         i = BoolIndirect(j);
645         name = ExtBoolname(tterm, (int) i, bool_names);
646         assert(strlen(name) < sizeof(buffer) - EXTRA_CAP);
647
648         if (!version_filter(BOOLEAN, i))
649             continue;
650         else if (isObsolete(outform, name))
651             continue;
652
653         predval = pred(BOOLEAN, i);
654         if (predval != FAIL) {
655             _nc_STRCPY(buffer, name, sizeof(buffer));
656             if (predval <= 0)
657                 _nc_STRCAT(buffer, "@", sizeof(buffer));
658             else if (i + 1 > num_bools)
659                 num_bools = i + 1;
660             WRAP_CONCAT;
661         }
662     }
663
664     if (column != INDENT && height > 1)
665         force_wrap();
666
667     for_each_number(j, tterm) {
668         i = NumIndirect(j);
669         name = ExtNumname(tterm, (int) i, num_names);
670         assert(strlen(name) < sizeof(buffer) - EXTRA_CAP);
671
672         if (!version_filter(NUMBER, i))
673             continue;
674         else if (isObsolete(outform, name))
675             continue;
676
677         predval = pred(NUMBER, i);
678         if (predval != FAIL) {
679             if (tterm->Numbers[i] < 0) {
680                 _nc_SPRINTF(buffer, _nc_SLIMIT(sizeof(buffer))
681                             "%s@", name);
682             } else {
683                 _nc_SPRINTF(buffer, _nc_SLIMIT(sizeof(buffer))
684                             "%s#%d", name, tterm->Numbers[i]);
685                 if (i + 1 > num_values)
686                     num_values = i + 1;
687             }
688             WRAP_CONCAT;
689         }
690     }
691
692     if (column != INDENT && height > 1)
693         force_wrap();
694
695     len += (int) (num_bools
696                   + num_values * 2
697                   + strlen(tterm->term_names) + 1);
698     if (len & 1)
699         len++;
700
701 #undef CUR
702 #define CUR tterm->
703     if (outform == F_TERMCAP) {
704         if (termcap_reset != ABSENT_STRING) {
705             if (init_3string != ABSENT_STRING
706                 && !strcmp(init_3string, termcap_reset))
707                 DISCARD(init_3string);
708
709             if (reset_2string != ABSENT_STRING
710                 && !strcmp(reset_2string, termcap_reset))
711                 DISCARD(reset_2string);
712         }
713     }
714
715     for_each_string(j, tterm) {
716         i = StrIndirect(j);
717         name = ExtStrname(tterm, (int) i, str_names);
718         assert(strlen(name) < sizeof(buffer) - EXTRA_CAP);
719
720         capability = tterm->Strings[i];
721
722         if (!version_filter(STRING, i))
723             continue;
724         else if (isObsolete(outform, name))
725             continue;
726
727 #if NCURSES_XNAMES
728         /*
729          * Extended names can be longer than 2 characters, but termcap programs
730          * cannot read those (filter them out).
731          */
732         if (outform == F_TERMCAP && (strlen(name) > 2))
733             continue;
734 #endif
735
736         if (outform == F_TERMCAP) {
737             /*
738              * Some older versions of vi want rmir/smir to be defined
739              * for ich/ich1 to work.  If they're not defined, force
740              * them to be output as defined and empty.
741              */
742             if (PRESENT(insert_character) || PRESENT(parm_ich)) {
743                 if (SAME_CAP(i, enter_insert_mode)
744                     && enter_insert_mode == ABSENT_STRING) {
745                     _nc_STRCPY(buffer, "im=", sizeof(buffer));
746                     WRAP_CONCAT;
747                     continue;
748                 }
749
750                 if (SAME_CAP(i, exit_insert_mode)
751                     && exit_insert_mode == ABSENT_STRING) {
752                     _nc_STRCPY(buffer, "ei=", sizeof(buffer));
753                     WRAP_CONCAT;
754                     continue;
755                 }
756             }
757             /*
758              * termcap applications such as screen will be confused if sgr0
759              * is translated to a string containing rmacs.  Filter that out.
760              */
761             if (PRESENT(exit_attribute_mode)) {
762                 if (SAME_CAP(i, exit_attribute_mode)) {
763                     char *trimmed_sgr0;
764                     char *my_sgr = set_attributes;
765
766                     set_attributes = save_sgr;
767
768                     trimmed_sgr0 = _nc_trim_sgr0(tterm);
769                     if (strcmp(capability, trimmed_sgr0))
770                         capability = trimmed_sgr0;
771
772                     set_attributes = my_sgr;
773                 }
774             }
775         }
776
777         predval = pred(STRING, i);
778         buffer[0] = '\0';
779
780         if (predval != FAIL) {
781             if (capability != ABSENT_STRING
782                 && i + 1 > num_strings)
783                 num_strings = i + 1;
784
785             if (!VALID_STRING(capability)) {
786                 _nc_SPRINTF(buffer, _nc_SLIMIT(sizeof(buffer))
787                             "%s@", name);
788                 WRAP_CONCAT;
789             } else if (outform == F_TERMCAP || outform == F_TCONVERR) {
790                 int params = ((i < (int) SIZEOF(parametrized))
791                               ? parametrized[i]
792                               : 0);
793                 char *srccap = _nc_tic_expand(capability, TRUE, numbers);
794                 char *cv = _nc_infotocap(name, srccap, params);
795
796                 if (cv == 0) {
797                     if (outform == F_TCONVERR) {
798                         _nc_SPRINTF(buffer, _nc_SLIMIT(sizeof(buffer))
799                                     "%s=!!! %s WILL NOT CONVERT !!!",
800                                     name, srccap);
801                     } else if (suppress_untranslatable) {
802                         continue;
803                     } else {
804                         char *s = srccap, *d = buffer;
805                         _nc_SPRINTF(d, _nc_SLIMIT(sizeof(buffer)) "..%s=", name);
806                         d += strlen(d);
807                         while ((*d = *s++) != 0) {
808                             if (*d == ':') {
809                                 *d++ = '\\';
810                                 *d = ':';
811                             } else if (*d == '\\') {
812                                 *++d = *s++;
813                             }
814                             d++;
815                         }
816                     }
817                 } else {
818                     _nc_SPRINTF(buffer, _nc_SLIMIT(sizeof(buffer))
819                                 "%s=%s", name, cv);
820                 }
821                 len += (int) strlen(capability) + 1;
822                 WRAP_CONCAT;
823             } else {
824                 char *src = _nc_tic_expand(capability,
825                                            outform == F_TERMINFO, numbers);
826
827                 strcpy_DYN(&tmpbuf, 0);
828                 strcpy_DYN(&tmpbuf, name);
829                 strcpy_DYN(&tmpbuf, "=");
830                 if (pretty
831                     && (outform == F_TERMINFO
832                         || outform == F_VARIABLE)) {
833                     fmt_complex(tterm, name, src, 1);
834                 } else {
835                     strcpy_DYN(&tmpbuf, src);
836                 }
837                 len += (int) strlen(capability) + 1;
838                 wrap_concat(tmpbuf.text);
839                 outcount = TRUE;
840             }
841         }
842         /* e.g., trimmed_sgr0 */
843         if (capability != ABSENT_STRING &&
844             capability != CANCELLED_STRING &&
845             capability != tterm->Strings[i])
846             free(capability);
847     }
848     len += (int) (num_strings * 2);
849
850     /*
851      * This piece of code should be an effective inverse of the functions
852      * postprocess_terminfo() and postprocess_terminfo() in parse_entry.c.
853      * Much more work should be done on this to support dumping termcaps.
854      */
855     if (tversion == V_HPUX) {
856         if (VALID_STRING(memory_lock)) {
857             _nc_SPRINTF(buffer, _nc_SLIMIT(sizeof(buffer))
858                         "meml=%s", memory_lock);
859             WRAP_CONCAT;
860         }
861         if (VALID_STRING(memory_unlock)) {
862             _nc_SPRINTF(buffer, _nc_SLIMIT(sizeof(buffer))
863                         "memu=%s", memory_unlock);
864             WRAP_CONCAT;
865         }
866     } else if (tversion == V_AIX) {
867         if (VALID_STRING(acs_chars)) {
868             bool box_ok = TRUE;
869             const char *acstrans = "lqkxjmwuvtn";
870             const char *cp;
871             char *tp, *sp, boxchars[11];
872
873             tp = boxchars;
874             for (cp = acstrans; *cp; cp++) {
875                 sp = strchr(acs_chars, *cp);
876                 if (sp)
877                     *tp++ = sp[1];
878                 else {
879                     box_ok = FALSE;
880                     break;
881                 }
882             }
883             tp[0] = '\0';
884
885             if (box_ok) {
886                 char *tmp = _nc_tic_expand(boxchars,
887                                            (outform == F_TERMINFO),
888                                            numbers);
889                 _nc_STRCPY(buffer, "box1=", sizeof(buffer));
890                 while (*tmp != '\0') {
891                     size_t have = strlen(buffer);
892                     size_t next = strlen(tmp);
893                     size_t want = have + next + 1;
894                     size_t last = next;
895                     char save = '\0';
896
897                     /*
898                      * If the expanded string is too long for the buffer,
899                      * chop it off and save the location where we chopped it.
900                      */
901                     if (want >= sizeof(buffer)) {
902                         save = tmp[last];
903                         tmp[last] = '\0';
904                     }
905                     _nc_STRCAT(buffer, tmp, sizeof(buffer));
906
907                     /*
908                      * If we chopped the buffer, replace the missing piece and
909                      * shift everything to append the remainder.
910                      */
911                     if (save != '\0') {
912                         next = 0;
913                         tmp[last] = save;
914                         while ((tmp[next] = tmp[last + next]) != '\0') {
915                             ++next;
916                         }
917                     } else {
918                         break;
919                     }
920                 }
921                 WRAP_CONCAT;
922             }
923         }
924     }
925
926     /*
927      * kludge: trim off trailer to avoid an extra blank line
928      * in infocmp -u output when there are no string differences
929      */
930     if (outcount) {
931         bool trimmed = FALSE;
932         j = (PredIdx) outbuf.used;
933         if (j >= 2
934             && outbuf.text[j - 1] == '\t'
935             && outbuf.text[j - 2] == '\n') {
936             outbuf.used -= 2;
937             trimmed = TRUE;
938         } else if (j >= 4
939                    && outbuf.text[j - 1] == ':'
940                    && outbuf.text[j - 2] == '\t'
941                    && outbuf.text[j - 3] == '\n'
942                    && outbuf.text[j - 4] == '\\') {
943             outbuf.used -= 4;
944             trimmed = TRUE;
945         }
946         if (trimmed) {
947             outbuf.text[outbuf.used] = '\0';
948             column = oldcol;
949             strcpy_DYN(&outbuf, " ");
950         }
951     }
952 #if 0
953     fprintf(stderr, "num_bools = %d\n", num_bools);
954     fprintf(stderr, "num_values = %d\n", num_values);
955     fprintf(stderr, "num_strings = %d\n", num_strings);
956     fprintf(stderr, "term_names=%s, len=%d, strlen(outbuf)=%d, outbuf=%s\n",
957             tterm->term_names, len, outbuf.used, outbuf.text);
958 #endif
959     /*
960      * Here's where we use infodump to trigger a more stringent length check
961      * for termcap-translation purposes.
962      * Return the length of the raw entry, without tc= expansions,
963      * It gives an idea of which entries are deadly to even *scan past*,
964      * as opposed to *use*.
965      */
966     return (infodump ? len : (int) termcap_length(outbuf.text));
967 }
968
969 static bool
970 kill_string(TERMTYPE *tterm, char *cap)
971 {
972     unsigned n;
973     for (n = 0; n < NUM_STRINGS(tterm); ++n) {
974         if (cap == tterm->Strings[n]) {
975             tterm->Strings[n] = ABSENT_STRING;
976             return TRUE;
977         }
978     }
979     return FALSE;
980 }
981
982 static char *
983 find_string(TERMTYPE *tterm, char *name)
984 {
985     PredIdx n;
986     for (n = 0; n < NUM_STRINGS(tterm); ++n) {
987         if (version_filter(STRING, n)
988             && !strcmp(name, strnames[n])) {
989             char *cap = tterm->Strings[n];
990             if (VALID_STRING(cap)) {
991                 return cap;
992             }
993             break;
994         }
995     }
996     return ABSENT_STRING;
997 }
998
999 /*
1000  * This is used to remove function-key labels from a termcap entry to
1001  * make it smaller.
1002  */
1003 static int
1004 kill_labels(TERMTYPE *tterm, int target)
1005 {
1006     int n;
1007     int result = 0;
1008     char *cap;
1009     char name[10];
1010
1011     for (n = 0; n <= 10; ++n) {
1012         _nc_SPRINTF(name, _nc_SLIMIT(sizeof(name)) "lf%d", n);
1013         if ((cap = find_string(tterm, name)) != ABSENT_STRING
1014             && kill_string(tterm, cap)) {
1015             target -= (int) (strlen(cap) + 5);
1016             ++result;
1017             if (target < 0)
1018                 break;
1019         }
1020     }
1021     return result;
1022 }
1023
1024 /*
1025  * This is used to remove function-key definitions from a termcap entry to
1026  * make it smaller.
1027  */
1028 static int
1029 kill_fkeys(TERMTYPE *tterm, int target)
1030 {
1031     int n;
1032     int result = 0;
1033     char *cap;
1034     char name[10];
1035
1036     for (n = 60; n >= 0; --n) {
1037         _nc_SPRINTF(name, _nc_SLIMIT(sizeof(name)) "kf%d", n);
1038         if ((cap = find_string(tterm, name)) != ABSENT_STRING
1039             && kill_string(tterm, cap)) {
1040             target -= (int) (strlen(cap) + 5);
1041             ++result;
1042             if (target < 0)
1043                 break;
1044         }
1045     }
1046     return result;
1047 }
1048
1049 /*
1050  * Check if the given acsc string is a 1-1 mapping, i.e., just-like-vt100.
1051  * Also, since this is for termcap, we only care about the line-drawing map.
1052  */
1053 #define isLine(c) (strchr("lmkjtuvwqxn", c) != 0)
1054
1055 static bool
1056 one_one_mapping(const char *mapping)
1057 {
1058     bool result = TRUE;
1059
1060     if (mapping != ABSENT_STRING) {
1061         int n = 0;
1062         while (mapping[n] != '\0') {
1063             if (isLine(mapping[n]) &&
1064                 mapping[n] != mapping[n + 1]) {
1065                 result = FALSE;
1066                 break;
1067             }
1068             n += 2;
1069         }
1070     }
1071     return result;
1072 }
1073
1074 #define FMT_ENTRY() \
1075                 fmt_entry(tterm, pred, \
1076                         0, \
1077                         suppress_untranslatable, \
1078                         infodump, numbers)
1079
1080 #define SHOW_WHY PRINTF
1081
1082 static bool
1083 purged_acs(TERMTYPE *tterm)
1084 {
1085     bool result = FALSE;
1086
1087     if (VALID_STRING(acs_chars)) {
1088         if (!one_one_mapping(acs_chars)) {
1089             enter_alt_charset_mode = ABSENT_STRING;
1090             exit_alt_charset_mode = ABSENT_STRING;
1091             SHOW_WHY("# (rmacs/smacs removed for consistency)\n");
1092         }
1093         result = TRUE;
1094     }
1095     return result;
1096 }
1097
1098 /*
1099  * Dump a single entry.
1100  */
1101 void
1102 dump_entry(TERMTYPE *tterm,
1103            bool suppress_untranslatable,
1104            bool limited,
1105            int numbers,
1106            PredFunc pred)
1107 {
1108     TERMTYPE save_tterm;
1109     int len, critlen;
1110     const char *legend;
1111     bool infodump;
1112
1113     if (outform == F_TERMCAP || outform == F_TCONVERR) {
1114         critlen = MAX_TERMCAP_LENGTH;
1115         legend = "older termcap";
1116         infodump = FALSE;
1117         set_obsolete_termcaps(tterm);
1118     } else {
1119         critlen = MAX_TERMINFO_LENGTH;
1120         legend = "terminfo";
1121         infodump = TRUE;
1122     }
1123
1124     save_sgr = set_attributes;
1125
1126     if ((FMT_ENTRY() > critlen)
1127         && limited) {
1128
1129         save_tterm = *tterm;
1130         if (!suppress_untranslatable) {
1131             SHOW_WHY("# (untranslatable capabilities removed to fit entry within %d bytes)\n",
1132                      critlen);
1133             suppress_untranslatable = TRUE;
1134         }
1135         if (FMT_ENTRY() > critlen) {
1136             /*
1137              * We pick on sgr because it's a nice long string capability that
1138              * is really just an optimization hack.  Another good candidate is
1139              * acsc since it is both long and unused by BSD termcap.
1140              */
1141             bool changed = FALSE;
1142
1143 #if NCURSES_XNAMES
1144             /*
1145              * Extended names are most likely function-key definitions.  Drop
1146              * those first.
1147              */
1148             unsigned n;
1149             for (n = STRCOUNT; n < NUM_STRINGS(tterm); n++) {
1150                 const char *name = ExtStrname(tterm, (int) n, strnames);
1151
1152                 if (VALID_STRING(tterm->Strings[n])) {
1153                     set_attributes = ABSENT_STRING;
1154                     /* we remove long names anyway - only report the short */
1155                     if (strlen(name) <= 2) {
1156                         SHOW_WHY("# (%s removed to fit entry within %d bytes)\n",
1157                                  name,
1158                                  critlen);
1159                     }
1160                     changed = TRUE;
1161                     if (FMT_ENTRY() <= critlen)
1162                         break;
1163                 }
1164             }
1165 #endif
1166             if (VALID_STRING(set_attributes)) {
1167                 set_attributes = ABSENT_STRING;
1168                 SHOW_WHY("# (sgr removed to fit entry within %d bytes)\n",
1169                          critlen);
1170                 changed = TRUE;
1171             }
1172             if (!changed || (FMT_ENTRY() > critlen)) {
1173                 if (purged_acs(tterm)) {
1174                     acs_chars = ABSENT_STRING;
1175                     SHOW_WHY("# (acsc removed to fit entry within %d bytes)\n",
1176                              critlen);
1177                     changed = TRUE;
1178                 }
1179             }
1180             if (!changed || (FMT_ENTRY() > critlen)) {
1181                 int oldversion = tversion;
1182
1183                 tversion = V_BSD;
1184                 SHOW_WHY("# (terminfo-only capabilities suppressed to fit entry within %d bytes)\n",
1185                          critlen);
1186
1187                 len = FMT_ENTRY();
1188                 if (len > critlen
1189                     && kill_labels(tterm, len - critlen)) {
1190                     SHOW_WHY("# (some labels capabilities suppressed to fit entry within %d bytes)\n",
1191                              critlen);
1192                     len = FMT_ENTRY();
1193                 }
1194                 if (len > critlen
1195                     && kill_fkeys(tterm, len - critlen)) {
1196                     SHOW_WHY("# (some function-key capabilities suppressed to fit entry within %d bytes)\n",
1197                              critlen);
1198                     len = FMT_ENTRY();
1199                 }
1200                 if (len > critlen) {
1201                     (void) fprintf(stderr,
1202                                    "warning: %s entry is %d bytes long\n",
1203                                    _nc_first_name(tterm->term_names),
1204                                    len);
1205                     SHOW_WHY("# WARNING: this entry, %d bytes long, may core-dump %s libraries!\n",
1206                              len, legend);
1207                 }
1208                 tversion = oldversion;
1209             }
1210             set_attributes = save_sgr;
1211             *tterm = save_tterm;
1212         }
1213     } else if (!version_filter(STRING, STR_IDX(acs_chars))) {
1214         save_tterm = *tterm;
1215         if (purged_acs(tterm)) {
1216             (void) FMT_ENTRY();
1217         }
1218         *tterm = save_tterm;
1219     }
1220 }
1221
1222 void
1223 dump_uses(const char *name, bool infodump)
1224 /* dump "use=" clauses in the appropriate format */
1225 {
1226     char buffer[MAX_TERMINFO_LENGTH];
1227
1228     if (outform == F_TERMCAP || outform == F_TCONVERR)
1229         trim_trailing();
1230     _nc_SPRINTF(buffer, _nc_SLIMIT(sizeof(buffer))
1231                 "%s%s", infodump ? "use=" : "tc=", name);
1232     wrap_concat(buffer);
1233 }
1234
1235 int
1236 show_entry(void)
1237 {
1238     /*
1239      * Trim any remaining whitespace.
1240      */
1241     if (outbuf.used != 0) {
1242         bool infodump = (outform != F_TERMCAP && outform != F_TCONVERR);
1243         char delim = (char) (infodump ? ',' : ':');
1244         int j;
1245
1246         for (j = (int) outbuf.used - 1; j > 0; --j) {
1247             char ch = outbuf.text[j];
1248             if (ch == '\n') {
1249                 ;
1250             } else if (isspace(UChar(ch))) {
1251                 outbuf.used = (size_t) j;
1252             } else if (!infodump && ch == '\\') {
1253                 outbuf.used = (size_t) j;
1254             } else if (ch == delim && (j == 0 || outbuf.text[j - 1] != '\\')) {
1255                 outbuf.used = (size_t) (j + 1);
1256             } else {
1257                 break;
1258             }
1259         }
1260         outbuf.text[outbuf.used] = '\0';
1261     }
1262     (void) fputs(outbuf.text, stdout);
1263     putchar('\n');
1264     return (int) outbuf.used;
1265 }
1266
1267 void
1268 compare_entry(PredHook hook,
1269               TERMTYPE *tp GCC_UNUSED,
1270               bool quiet)
1271 /* compare two entries */
1272 {
1273     PredIdx i, j;
1274     NCURSES_CONST char *name;
1275
1276     if (!quiet)
1277         fputs("    comparing booleans.\n", stdout);
1278     for_each_boolean(j, tp) {
1279         i = BoolIndirect(j);
1280         name = ExtBoolname(tp, (int) i, bool_names);
1281
1282         if (isObsolete(outform, name))
1283             continue;
1284
1285         (*hook) (CMP_BOOLEAN, i, name);
1286     }
1287
1288     if (!quiet)
1289         fputs("    comparing numbers.\n", stdout);
1290     for_each_number(j, tp) {
1291         i = NumIndirect(j);
1292         name = ExtNumname(tp, (int) i, num_names);
1293
1294         if (isObsolete(outform, name))
1295             continue;
1296
1297         (*hook) (CMP_NUMBER, i, name);
1298     }
1299
1300     if (!quiet)
1301         fputs("    comparing strings.\n", stdout);
1302     for_each_string(j, tp) {
1303         i = StrIndirect(j);
1304         name = ExtStrname(tp, (int) i, str_names);
1305
1306         if (isObsolete(outform, name))
1307             continue;
1308
1309         (*hook) (CMP_STRING, i, name);
1310     }
1311
1312     /* (void) fputs("    comparing use entries.\n", stdout); */
1313     (*hook) (CMP_USE, 0, "use");
1314
1315 }
1316
1317 #define NOTSET(s)       ((s) == 0)
1318
1319 /*
1320  * This bit of legerdemain turns all the terminfo variable names into
1321  * references to locations in the arrays Booleans, Numbers, and Strings ---
1322  * precisely what's needed.
1323  */
1324 #undef CUR
1325 #define CUR tp->
1326
1327 static void
1328 set_obsolete_termcaps(TERMTYPE *tp)
1329 {
1330 #include "capdefaults.c"
1331 }
1332
1333 /*
1334  * Convert an alternate-character-set string to canonical form: sorted and
1335  * unique.
1336  */
1337 void
1338 repair_acsc(TERMTYPE *tp)
1339 {
1340     if (VALID_STRING(acs_chars)) {
1341         size_t n, m;
1342         char mapped[256];
1343         char extra = 0;
1344         unsigned source;
1345         unsigned target;
1346         bool fix_needed = FALSE;
1347
1348         for (n = 0, source = 0; acs_chars[n] != 0; n++) {
1349             target = UChar(acs_chars[n]);
1350             if (source >= target) {
1351                 fix_needed = TRUE;
1352                 break;
1353             }
1354             source = target;
1355             if (acs_chars[n + 1])
1356                 n++;
1357         }
1358         if (fix_needed) {
1359             memset(mapped, 0, sizeof(mapped));
1360             for (n = 0; acs_chars[n] != 0; n++) {
1361                 source = UChar(acs_chars[n]);
1362                 if ((target = (unsigned char) acs_chars[n + 1]) != 0) {
1363                     mapped[source] = (char) target;
1364                     n++;
1365                 } else {
1366                     extra = (char) source;
1367                 }
1368             }
1369             for (n = m = 0; n < sizeof(mapped); n++) {
1370                 if (mapped[n]) {
1371                     acs_chars[m++] = (char) n;
1372                     acs_chars[m++] = mapped[n];
1373                 }
1374             }
1375             if (extra)
1376                 acs_chars[m++] = extra;         /* garbage in, garbage out */
1377             acs_chars[m] = 0;
1378         }
1379     }
1380 }