]> ncurses.scripts.mit.edu Git - ncurses.git/blob - progs/dump_entry.c
ncurses 6.0 - patch 20170701
[ncurses.git] / progs / dump_entry.c
1 /****************************************************************************
2  * Copyright (c) 1998-2016,2017 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.154 2017/07/01 11:27:29 tom Exp $")
43
44 #define DISCARD(string) string = ABSENT_STRING
45 #define PRINTF (void) printf
46 #define WRAPPED 32
47
48 #define OkIndex(index,array) ((int)(index) >= 0 && (int)(index) < (int) SIZEOF(array))
49 #define TcOutput() (outform == F_TERMCAP || outform == F_TCONVERR)
50
51 typedef struct {
52     char *text;
53     size_t used;
54     size_t size;
55 } DYNBUF;
56
57 static int tversion;            /* terminfo version */
58 static int outform;             /* output format to use */
59 static int sortmode;            /* sort mode to use */
60 static int width = 60;          /* max line width for listings */
61 static int height = 65535;      /* max number of lines for listings */
62 static int column;              /* current column, limited by 'width' */
63 static int oldcol;              /* last value of column before wrap */
64 static bool pretty;             /* true if we format if-then-else strings */
65 static bool wrapped;            /* true if we wrap too-long strings */
66 static bool did_wrap;           /* true if last wrap_concat did wrapping */
67 static bool checking;           /* true if we are checking for tic */
68 static int quickdump;           /* true if we are dumping compiled data */
69
70 static char *save_sgr;
71
72 static DYNBUF outbuf;
73 static DYNBUF tmpbuf;
74
75 /* indirection pointers for implementing sort and display modes */
76 static const PredIdx *bool_indirect, *num_indirect, *str_indirect;
77 static NCURSES_CONST char *const *bool_names;
78 static NCURSES_CONST char *const *num_names;
79 static NCURSES_CONST char *const *str_names;
80
81 static const char *separator = "", *trailer = "";
82 static int indent = 8;
83
84 /* cover various ports and variants of terminfo */
85 #define V_ALLCAPS       0       /* all capabilities (SVr4, XSI, ncurses) */
86 #define V_SVR1          1       /* SVR1, Ultrix */
87 #define V_HPUX          2       /* HP/UX */
88 #define V_AIX           3       /* AIX */
89 #define V_BSD           4       /* BSD */
90
91 #if NCURSES_XNAMES
92 #define OBSOLETE(n) (!_nc_user_definable && (n[0] == 'O' && n[1] == 'T'))
93 #else
94 #define OBSOLETE(n) (n[0] == 'O' && n[1] == 'T')
95 #endif
96
97 #define isObsolete(f,n) ((f == F_TERMINFO || f == F_VARIABLE) && OBSOLETE(n))
98
99 #if NCURSES_XNAMES
100 #define BoolIndirect(j) ((j >= BOOLCOUNT) ? (j) : ((sortmode == S_NOSORT) ? j : bool_indirect[j]))
101 #define NumIndirect(j)  ((j >= NUMCOUNT)  ? (j) : ((sortmode == S_NOSORT) ? j : num_indirect[j]))
102 #define StrIndirect(j)  ((j >= STRCOUNT)  ? (j) : ((sortmode == S_NOSORT) ? j : str_indirect[j]))
103 #else
104 #define BoolIndirect(j) ((sortmode == S_NOSORT) ? (j) : bool_indirect[j])
105 #define NumIndirect(j)  ((sortmode == S_NOSORT) ? (j) : num_indirect[j])
106 #define StrIndirect(j)  ((sortmode == S_NOSORT) ? (j) : str_indirect[j])
107 #endif
108
109 static void failed(const char *) GCC_NORETURN;
110
111 static void
112 failed(const char *s)
113 {
114     perror(s);
115     ExitProgram(EXIT_FAILURE);
116 }
117
118 static void
119 strncpy_DYN(DYNBUF * dst, const char *src, size_t need)
120 {
121     size_t want = need + dst->used + 1;
122     if (want > dst->size) {
123         dst->size += (want + 1024);     /* be generous */
124         dst->text = typeRealloc(char, dst->size, dst->text);
125         if (dst->text == 0)
126             failed("strncpy_DYN");
127     }
128     _nc_STRNCPY(dst->text + dst->used, src, need + 1);
129     dst->used += need;
130     dst->text[dst->used] = 0;
131 }
132
133 static void
134 strcpy_DYN(DYNBUF * dst, const char *src)
135 {
136     if (src == 0) {
137         dst->used = 0;
138         strcpy_DYN(dst, "");
139     } else {
140         strncpy_DYN(dst, src, strlen(src));
141     }
142 }
143
144 #if NO_LEAKS
145 static void
146 free_DYN(DYNBUF * p)
147 {
148     if (p->text != 0)
149         free(p->text);
150     p->text = 0;
151     p->size = 0;
152     p->used = 0;
153 }
154
155 void
156 _nc_leaks_dump_entry(void)
157 {
158     free_DYN(&outbuf);
159     free_DYN(&tmpbuf);
160 }
161 #endif
162
163 #define NameTrans(check,result) \
164             if ((np->nte_index <= OK_ ## check) \
165                 && check[np->nte_index]) \
166                 return (result[np->nte_index])
167
168 NCURSES_CONST char *
169 nametrans(const char *name)
170 /* translate a capability name to termcap from terminfo */
171 {
172     const struct name_table_entry *np;
173
174     if ((np = _nc_find_entry(name, _nc_get_hash_table(0))) != 0) {
175         switch (np->nte_type) {
176         case BOOLEAN:
177             NameTrans(bool_from_termcap, boolcodes);
178             break;
179
180         case NUMBER:
181             NameTrans(num_from_termcap, numcodes);
182             break;
183
184         case STRING:
185             NameTrans(str_from_termcap, strcodes);
186             break;
187         }
188     }
189
190     return (0);
191 }
192
193 void
194 dump_init(const char *version,
195           int mode,
196           int sort,
197           bool wrap_strings,
198           int twidth,
199           int theight,
200           unsigned traceval,
201           bool formatted,
202           bool check,
203           int quick)
204 /* set up for entry display */
205 {
206     width = twidth;
207     height = theight;
208     pretty = formatted;
209     wrapped = wrap_strings;
210     checking = check;
211     quickdump = (quick & 3);
212
213     did_wrap = (width <= 0);
214
215     /* versions */
216     if (version == 0)
217         tversion = V_ALLCAPS;
218     else if (!strcmp(version, "SVr1") || !strcmp(version, "SVR1")
219              || !strcmp(version, "Ultrix"))
220         tversion = V_SVR1;
221     else if (!strcmp(version, "HP"))
222         tversion = V_HPUX;
223     else if (!strcmp(version, "AIX"))
224         tversion = V_AIX;
225     else if (!strcmp(version, "BSD"))
226         tversion = V_BSD;
227     else
228         tversion = V_ALLCAPS;
229
230     /* implement display modes */
231     switch (outform = mode) {
232     case F_LITERAL:
233     case F_TERMINFO:
234         bool_names = boolnames;
235         num_names = numnames;
236         str_names = strnames;
237         separator = (twidth > 0 && theight > 1) ? ", " : ",";
238         trailer = "\n\t";
239         break;
240
241     case F_VARIABLE:
242         bool_names = boolfnames;
243         num_names = numfnames;
244         str_names = strfnames;
245         separator = (twidth > 0 && theight > 1) ? ", " : ",";
246         trailer = "\n\t";
247         break;
248
249     case F_TERMCAP:
250     case F_TCONVERR:
251         bool_names = boolcodes;
252         num_names = numcodes;
253         str_names = strcodes;
254         separator = ":";
255         trailer = "\\\n\t:";
256         break;
257     }
258     indent = 8;
259
260     /* implement sort modes */
261     switch (sortmode = sort) {
262     case S_NOSORT:
263         if (traceval)
264             (void) fprintf(stderr,
265                            "%s: sorting by term structure order\n", _nc_progname);
266         break;
267
268     case S_TERMINFO:
269         if (traceval)
270             (void) fprintf(stderr,
271                            "%s: sorting by terminfo name order\n", _nc_progname);
272         bool_indirect = bool_terminfo_sort;
273         num_indirect = num_terminfo_sort;
274         str_indirect = str_terminfo_sort;
275         break;
276
277     case S_VARIABLE:
278         if (traceval)
279             (void) fprintf(stderr,
280                            "%s: sorting by C variable order\n", _nc_progname);
281         bool_indirect = bool_variable_sort;
282         num_indirect = num_variable_sort;
283         str_indirect = str_variable_sort;
284         break;
285
286     case S_TERMCAP:
287         if (traceval)
288             (void) fprintf(stderr,
289                            "%s: sorting by termcap name order\n", _nc_progname);
290         bool_indirect = bool_termcap_sort;
291         num_indirect = num_termcap_sort;
292         str_indirect = str_termcap_sort;
293         break;
294     }
295
296     if (traceval)
297         (void) fprintf(stderr,
298                        "%s: width = %d, tversion = %d, outform = %d\n",
299                        _nc_progname, width, tversion, outform);
300 }
301
302 static TERMTYPE2 *cur_type;
303
304 static int
305 dump_predicate(PredType type, PredIdx idx)
306 /* predicate function to use for ordinary decompilation */
307 {
308     switch (type) {
309     case BOOLEAN:
310         return (cur_type->Booleans[idx] == FALSE)
311             ? FAIL : cur_type->Booleans[idx];
312
313     case NUMBER:
314         return (cur_type->Numbers[idx] == ABSENT_NUMERIC)
315             ? FAIL : cur_type->Numbers[idx];
316
317     case STRING:
318         return (cur_type->Strings[idx] != ABSENT_STRING)
319             ? (int) TRUE : FAIL;
320     }
321
322     return (FALSE);             /* pacify compiler */
323 }
324
325 static void set_obsolete_termcaps(TERMTYPE2 *tp);
326
327 /* is this the index of a function key string? */
328 #define FNKEY(i) \
329     (((i) >= STR_IDX(key_f0) && \
330       (i) <= STR_IDX(key_f9)) || \
331      ((i) >= STR_IDX(key_f11) && \
332       (i) <= STR_IDX(key_f63)))
333
334 /*
335  * If we configure with a different Caps file, the offsets into the arrays
336  * will change.  So we use an address expression.
337  */
338 #define BOOL_IDX(name) (PredType) (&(name) - &(CUR Booleans[0]))
339 #define NUM_IDX(name)  (PredType) (&(name) - &(CUR Numbers[0]))
340 #define STR_IDX(name)  (PredType) (&(name) - &(CUR Strings[0]))
341
342 static bool
343 version_filter(PredType type, PredIdx idx)
344 /* filter out capabilities we may want to suppress */
345 {
346     switch (tversion) {
347     case V_ALLCAPS:             /* SVr4, XSI Curses */
348         return (TRUE);
349
350     case V_SVR1:                /* System V Release 1, Ultrix */
351         switch (type) {
352         case BOOLEAN:
353             return ((idx <= BOOL_IDX(xon_xoff)) ? TRUE : FALSE);
354         case NUMBER:
355             return ((idx <= NUM_IDX(width_status_line)) ? TRUE : FALSE);
356         case STRING:
357             return ((idx <= STR_IDX(prtr_non)) ? TRUE : FALSE);
358         }
359         break;
360
361     case V_HPUX:                /* Hewlett-Packard */
362         switch (type) {
363         case BOOLEAN:
364             return ((idx <= BOOL_IDX(xon_xoff)) ? TRUE : FALSE);
365         case NUMBER:
366             return ((idx <= NUM_IDX(label_width)) ? 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 if (idx == STR_IDX(plab_norm)
373                      || idx == STR_IDX(label_on)
374                      || idx == STR_IDX(label_off))
375                 return (TRUE);
376             else
377                 return (FALSE);
378         }
379         break;
380
381     case V_AIX:         /* AIX */
382         switch (type) {
383         case BOOLEAN:
384             return ((idx <= BOOL_IDX(xon_xoff)) ? TRUE : FALSE);
385         case NUMBER:
386             return ((idx <= NUM_IDX(width_status_line)) ? TRUE : FALSE);
387         case STRING:
388             if (idx <= STR_IDX(prtr_non))
389                 return (TRUE);
390             else if (FNKEY(idx))        /* function keys */
391                 return (TRUE);
392             else
393                 return (FALSE);
394         }
395         break;
396
397 #define is_termcap(type) (OkIndex(idx, type##_from_termcap) && \
398                           type##_from_termcap[idx])
399
400     case V_BSD:         /* BSD */
401         switch (type) {
402         case BOOLEAN:
403             return is_termcap(bool);
404         case NUMBER:
405             return is_termcap(num);
406         case STRING:
407             return is_termcap(str);
408         }
409         break;
410     }
411
412     return (FALSE);             /* pacify the compiler */
413 }
414
415 static void
416 trim_trailing(void)
417 {
418     while (outbuf.used > 0 && outbuf.text[outbuf.used - 1] == ' ')
419         outbuf.text[--outbuf.used] = '\0';
420 }
421
422 static void
423 force_wrap(void)
424 {
425     oldcol = column;
426     trim_trailing();
427     strcpy_DYN(&outbuf, trailer);
428     column = indent;
429 }
430
431 static int
432 op_length(const char *src, int offset)
433 {
434     int result = 0;
435     int ch;
436     if (offset > 0 && src[offset - 1] == '\\') {
437         result = 0;
438     } else {
439         result++;               /* for '%' mark */
440         ch = src[offset + result];
441         if (TcOutput()) {
442             if (ch == '>') {
443                 result += 3;
444             } else if (ch == '+') {
445                 result += 2;
446             } else {
447                 result++;
448             }
449         } else if (ch == '\'') {
450             result += 3;
451         } else if (ch == L_CURL[0]) {
452             int n = result;
453             while ((ch = src[offset + n]) != '\0') {
454                 if (ch == R_CURL[0]) {
455                     result = ++n;
456                     break;
457                 }
458                 n++;
459             }
460         } else if (strchr("pPg", ch) != 0) {
461             result += 2;
462         } else {
463             result++;           /* ordinary operator */
464         }
465     }
466     return result;
467 }
468
469 /*
470  * When wrapping too-long strings, avoid splitting a backslash sequence, or
471  * a terminfo '%' operator.  That will leave things a little ragged, but avoids
472  * a stray backslash at the end of the line, as well as making the result a
473  * little more readable.
474  */
475 static int
476 find_split(const char *src, int step, int size)
477 {
478     int result = size;
479     int n;
480     if (size > 0) {
481         /* check if that would split a backslash-sequence */
482         int mark = size;
483         for (n = size - 1; n > 0; --n) {
484             int ch = UChar(src[step + n]);
485             if (ch == '\\') {
486                 if (n > 0 && src[step + n - 1] == ch)
487                     --n;
488                 mark = n;
489                 break;
490             } else if (!isalnum(ch)) {
491                 break;
492             }
493         }
494         if (mark < size) {
495             result = mark;
496         } else {
497             /* check if that would split a backslash-sequence */
498             for (n = size - 1; n > 0; --n) {
499                 int ch = UChar(src[step + n]);
500                 if (ch == '%') {
501                     int need = op_length(src, step + n);
502                     if ((n + need) > size)
503                         mark = n;
504                     break;
505                 }
506             }
507             if (mark < size) {
508                 result = mark;
509             }
510         }
511     }
512     return result;
513 }
514
515 /*
516  * If we are going to wrap lines, we cannot leave literal spaces because that
517  * would be ambiguous if we split on that space.
518  */
519 static char *
520 fill_spaces(const char *src)
521 {
522     const char *fill = "\\s";
523     size_t need = strlen(src);
524     size_t size = strlen(fill);
525     char *result = 0;
526     int pass;
527     int s, d;
528     for (pass = 0; pass < 2; ++pass) {
529         for (s = d = 0; src[s] != '\0'; ++s) {
530             if (src[s] == ' ') {
531                 if (pass) {
532                     strcpy(&result[d], fill);
533                     d += (int) size;
534                 } else {
535                     need += size;
536                 }
537             } else {
538                 if (pass) {
539                     result[d++] = src[s];
540                 } else {
541                     ++d;
542                 }
543             }
544         }
545         if (pass) {
546             result[d] = '\0';
547         } else {
548             result = malloc(need + 1);
549             if (result == 0)
550                 failed("fill_spaces");
551         }
552     }
553     return result;
554 }
555
556 static void
557 wrap_concat(const char *src)
558 {
559     int need = (int) strlen(src);
560     int gaps = (int) strlen(separator);
561     int want = gaps + need;
562
563     did_wrap = (width <= 0);
564     if (column > indent
565         && column + want > width) {
566         force_wrap();
567     }
568     if (wrapped &&
569         (width >= 0) &&
570         (column + want) > width &&
571         (!TcOutput() || strncmp(src, "..", 2))) {
572         int step = 0;
573         int used = width > WRAPPED ? width : WRAPPED;
574         int size;
575         int base = 0;
576         char *p, align[9];
577         const char *my_t = trailer;
578         char *fill = fill_spaces(src);
579         int last = (int) strlen(fill);
580
581         need = last;
582
583         if (TcOutput())
584             trailer = "\\\n\t ";
585
586         if ((p = strchr(fill, '=')) != 0) {
587             base = (int) (p + 1 - fill);
588             if (base > 8)
589                 base = 8;
590             _nc_SPRINTF(align, _nc_SLIMIT(align) "%*s", base, " ");
591         } else {
592             align[base] = '\0';
593         }
594         /* "pretty" overrides wrapping if it already split the line */
595         if (!pretty || strchr(fill, '\n') == 0) {
596             while ((column + (need + gaps)) > used) {
597                 size = used;
598                 if (step) {
599                     strcpy_DYN(&outbuf, align);
600                     size -= base;
601                 }
602                 if (size > (last - step)) {
603                     size = (last - step);
604                 }
605                 size = find_split(fill, step, size);
606                 strncpy_DYN(&outbuf, fill + step, (size_t) size);
607                 step += size;
608                 need -= size;
609                 if (need > 0) {
610                     force_wrap();
611                     did_wrap = TRUE;
612                 }
613             }
614         }
615         if (need > 0) {
616             if (step)
617                 strcpy_DYN(&outbuf, align);
618             strcpy_DYN(&outbuf, fill + step);
619         }
620         strcpy_DYN(&outbuf, separator);
621         trailer = my_t;
622         force_wrap();
623
624         free(fill);
625     } else {
626         strcpy_DYN(&outbuf, src);
627         strcpy_DYN(&outbuf, separator);
628         column += need;
629     }
630 }
631
632 #define IGNORE_SEP_TRAIL(first,last,sep_trail) \
633         if ((size_t)(last - first) > sizeof(sep_trail)-1 \
634          && !strncmp(first, sep_trail, sizeof(sep_trail)-1)) \
635                 first += sizeof(sep_trail)-2
636
637 /* Returns the nominal length of the buffer assuming it is termcap format,
638  * i.e., the continuation sequence is treated as a single character ":".
639  *
640  * There are several implementations of termcap which read the text into a
641  * fixed-size buffer.  Generally they strip the newlines from the text, but may
642  * not do it until after the buffer is read.  Also, "tc=" resolution may be
643  * expanded in the same buffer.  This function is useful for measuring the size
644  * of the best fixed-buffer implementation; the worst case may be much worse.
645  */
646 #ifdef TEST_TERMCAP_LENGTH
647 static int
648 termcap_length(const char *src)
649 {
650     static const char pattern[] = ":\\\n\t:";
651
652     int len = 0;
653     const char *const t = src + strlen(src);
654
655     while (*src != '\0') {
656         IGNORE_SEP_TRAIL(src, t, pattern);
657         src++;
658         len++;
659     }
660     return len;
661 }
662 #else
663 #define termcap_length(src) strlen(src)
664 #endif
665
666 static void
667 indent_DYN(DYNBUF * buffer, int level)
668 {
669     int n;
670
671     for (n = 0; n < level; n++)
672         strncpy_DYN(buffer, "\t", (size_t) 1);
673 }
674
675 bool
676 has_params(const char *src)
677 {
678     bool result = FALSE;
679     int len = (int) strlen(src);
680     int n;
681     bool ifthen = FALSE;
682     bool params = FALSE;
683
684     for (n = 0; n < len - 1; ++n) {
685         if (!strncmp(src + n, "%p", (size_t) 2)) {
686             params = TRUE;
687         } else if (!strncmp(src + n, "%;", (size_t) 2)) {
688             ifthen = TRUE;
689             result = params;
690             break;
691         }
692     }
693     if (!ifthen) {
694         result = ((len > 50) && params);
695     }
696     return result;
697 }
698
699 static char *
700 fmt_complex(TERMTYPE2 *tterm, const char *capability, char *src, int level)
701 {
702     bool percent = FALSE;
703     bool params = has_params(src);
704
705     while (*src != '\0') {
706         switch (*src) {
707         case '^':
708             percent = FALSE;
709             strncpy_DYN(&tmpbuf, src++, (size_t) 1);
710             break;
711         case '\\':
712             percent = FALSE;
713             strncpy_DYN(&tmpbuf, src++, (size_t) 1);
714             break;
715         case '%':
716             percent = TRUE;
717             break;
718         case '?':               /* "if" */
719         case 't':               /* "then" */
720         case 'e':               /* "else" */
721             if (percent) {
722                 percent = FALSE;
723                 tmpbuf.text[tmpbuf.used - 1] = '\n';
724                 /* treat a "%e" as else-if, on the same level */
725                 if (*src == 'e') {
726                     indent_DYN(&tmpbuf, level);
727                     strncpy_DYN(&tmpbuf, "%", (size_t) 1);
728                     strncpy_DYN(&tmpbuf, src, (size_t) 1);
729                     src++;
730                     params = has_params(src);
731                     if (!params && *src != '\0' && *src != '%') {
732                         strncpy_DYN(&tmpbuf, "\n", (size_t) 1);
733                         indent_DYN(&tmpbuf, level + 1);
734                     }
735                 } else {
736                     indent_DYN(&tmpbuf, level + 1);
737                     strncpy_DYN(&tmpbuf, "%", (size_t) 1);
738                     strncpy_DYN(&tmpbuf, src, (size_t) 1);
739                     if (*src++ == '?') {
740                         src = fmt_complex(tterm, capability, src, level + 1);
741                         if (*src != '\0' && *src != '%') {
742                             strncpy_DYN(&tmpbuf, "\n", (size_t) 1);
743                             indent_DYN(&tmpbuf, level + 1);
744                         }
745                     } else if (level == 1) {
746                         if (checking)
747                             _nc_warning("%s: %%%c without %%? in %s",
748                                         _nc_first_name(tterm->term_names),
749                                         *src, capability);
750                     }
751                 }
752                 continue;
753             }
754             break;
755         case ';':               /* "endif" */
756             if (percent) {
757                 percent = FALSE;
758                 if (level > 1) {
759                     tmpbuf.text[tmpbuf.used - 1] = '\n';
760                     indent_DYN(&tmpbuf, level);
761                     strncpy_DYN(&tmpbuf, "%", (size_t) 1);
762                     strncpy_DYN(&tmpbuf, src++, (size_t) 1);
763                     if (src[0] == '%'
764                         && src[1] != '\0'
765                         && (strchr("?e;", src[1])) == 0) {
766                         tmpbuf.text[tmpbuf.used++] = '\n';
767                         indent_DYN(&tmpbuf, level);
768                     }
769                     return src;
770                 }
771                 if (checking)
772                     _nc_warning("%s: %%; without %%? in %s",
773                                 _nc_first_name(tterm->term_names),
774                                 capability);
775             }
776             break;
777         case 'p':
778             if (percent && params) {
779                 tmpbuf.text[tmpbuf.used - 1] = '\n';
780                 indent_DYN(&tmpbuf, level + 1);
781                 strncpy_DYN(&tmpbuf, "%", (size_t) 1);
782             }
783             params = FALSE;
784             percent = FALSE;
785             break;
786         case ' ':
787             strncpy_DYN(&tmpbuf, "\\s", (size_t) 2);
788             ++src;
789             continue;
790         default:
791             percent = FALSE;
792             break;
793         }
794         strncpy_DYN(&tmpbuf, src++, (size_t) 1);
795     }
796     return src;
797 }
798
799 /*
800  * Make "large" numbers a little easier to read by showing them in hexadecimal
801  * if they are "close" to a power of two.
802  */
803 static const char *
804 number_format(int value)
805 {
806     const char *result = "%d";
807     if ((outform != F_TERMCAP) && (value > 255)) {
808         unsigned long lv = (unsigned long) value;
809         unsigned long mm;
810         int bits = sizeof(unsigned long) * 8;
811         int nn;
812         for (nn = 8; nn < bits; ++nn) {
813             mm = 1UL << nn;
814             if ((mm - 16) <= lv && (mm + 16) > lv) {
815                 result = "%#x";
816                 break;
817             }
818         }
819     }
820     return result;
821 }
822
823 #define SAME_CAP(n,cap) (&tterm->Strings[n] == &cap)
824 #define EXTRA_CAP 20
825
826 int
827 fmt_entry(TERMTYPE2 *tterm,
828           PredFunc pred,
829           int content_only,
830           int suppress_untranslatable,
831           int infodump,
832           int numbers)
833 {
834     PredIdx i, j;
835     char buffer[MAX_TERMINFO_LENGTH + EXTRA_CAP];
836     char *capability;
837     NCURSES_CONST char *name;
838     int predval, len;
839     PredIdx num_bools = 0;
840     PredIdx num_values = 0;
841     PredIdx num_strings = 0;
842     bool outcount = 0;
843
844 #define WRAP_CONCAT1(s)         wrap_concat(s); outcount = TRUE
845 #define WRAP_CONCAT2(a,b)       wrap_concat(a); WRAP_CONCAT1(b)
846 #define WRAP_CONCAT3(a,b,c)     wrap_concat(a); WRAP_CONCAT2(b,c)
847 #define WRAP_CONCAT             WRAP_CONCAT1(buffer)
848
849     len = 12;                   /* terminfo file-header */
850
851     if (pred == 0) {
852         cur_type = tterm;
853         pred = dump_predicate;
854     }
855
856     strcpy_DYN(&outbuf, 0);
857     if (content_only) {
858         column = indent;        /* FIXME: workaround to prevent empty lines */
859     } else {
860         strcpy_DYN(&outbuf, tterm->term_names);
861
862         /*
863          * Colon is legal in terminfo descriptions, but not in termcap.
864          */
865         if (!infodump) {
866             char *p = outbuf.text;
867             while (*p) {
868                 if (*p == ':') {
869                     *p = '=';
870                 }
871                 ++p;
872             }
873         }
874         strcpy_DYN(&outbuf, separator);
875         column = (int) outbuf.used;
876         if (height > 1)
877             force_wrap();
878     }
879
880     for_each_boolean(j, tterm) {
881         i = BoolIndirect(j);
882         name = ExtBoolname(tterm, (int) i, bool_names);
883         assert(strlen(name) < sizeof(buffer) - EXTRA_CAP);
884
885         if (!version_filter(BOOLEAN, i))
886             continue;
887         else if (isObsolete(outform, name))
888             continue;
889
890         predval = pred(BOOLEAN, i);
891         if (predval != FAIL) {
892             _nc_STRCPY(buffer, name, sizeof(buffer));
893             if (predval <= 0)
894                 _nc_STRCAT(buffer, "@", sizeof(buffer));
895             else if (i + 1 > num_bools)
896                 num_bools = i + 1;
897             WRAP_CONCAT;
898         }
899     }
900
901     if (column != indent && height > 1)
902         force_wrap();
903
904     for_each_number(j, tterm) {
905         i = NumIndirect(j);
906         name = ExtNumname(tterm, (int) i, num_names);
907         assert(strlen(name) < sizeof(buffer) - EXTRA_CAP);
908
909         if (!version_filter(NUMBER, i))
910             continue;
911         else if (isObsolete(outform, name))
912             continue;
913
914         predval = pred(NUMBER, i);
915         if (predval != FAIL) {
916             if (tterm->Numbers[i] < 0) {
917                 _nc_SPRINTF(buffer, _nc_SLIMIT(sizeof(buffer))
918                             "%s@", name);
919             } else {
920                 size_t nn;
921                 _nc_SPRINTF(buffer, _nc_SLIMIT(sizeof(buffer))
922                             "%s#", name);
923                 nn = strlen(buffer);
924                 _nc_SPRINTF(buffer + nn, _nc_SLIMIT(sizeof(buffer) - nn)
925                             number_format(tterm->Numbers[i]),
926                             tterm->Numbers[i]);
927                 if (i + 1 > num_values)
928                     num_values = i + 1;
929             }
930             WRAP_CONCAT;
931         }
932     }
933
934     if (column != indent && height > 1)
935         force_wrap();
936
937     len += (int) (num_bools
938                   + num_values * 2
939                   + strlen(tterm->term_names) + 1);
940     if (len & 1)
941         len++;
942
943 #undef CUR
944 #define CUR tterm->
945     if (outform == F_TERMCAP) {
946         if (termcap_reset != ABSENT_STRING) {
947             if (init_3string != ABSENT_STRING
948                 && !strcmp(init_3string, termcap_reset))
949                 DISCARD(init_3string);
950
951             if (reset_2string != ABSENT_STRING
952                 && !strcmp(reset_2string, termcap_reset))
953                 DISCARD(reset_2string);
954         }
955     }
956
957     for_each_string(j, tterm) {
958         i = StrIndirect(j);
959         name = ExtStrname(tterm, (int) i, str_names);
960         assert(strlen(name) < sizeof(buffer) - EXTRA_CAP);
961
962         capability = tterm->Strings[i];
963
964         if (!version_filter(STRING, i))
965             continue;
966         else if (isObsolete(outform, name))
967             continue;
968
969 #if NCURSES_XNAMES
970         /*
971          * Extended names can be longer than 2 characters, but termcap programs
972          * cannot read those (filter them out).
973          */
974         if (outform == F_TERMCAP && (strlen(name) > 2))
975             continue;
976 #endif
977
978         if (outform == F_TERMCAP) {
979             /*
980              * Some older versions of vi want rmir/smir to be defined
981              * for ich/ich1 to work.  If they're not defined, force
982              * them to be output as defined and empty.
983              */
984             if (PRESENT(insert_character) || PRESENT(parm_ich)) {
985                 if (SAME_CAP(i, enter_insert_mode)
986                     && enter_insert_mode == ABSENT_STRING) {
987                     _nc_STRCPY(buffer, "im=", sizeof(buffer));
988                     WRAP_CONCAT;
989                     continue;
990                 }
991
992                 if (SAME_CAP(i, exit_insert_mode)
993                     && exit_insert_mode == ABSENT_STRING) {
994                     _nc_STRCPY(buffer, "ei=", sizeof(buffer));
995                     WRAP_CONCAT;
996                     continue;
997                 }
998             }
999             /*
1000              * termcap applications such as screen will be confused if sgr0
1001              * is translated to a string containing rmacs.  Filter that out.
1002              */
1003             if (PRESENT(exit_attribute_mode)) {
1004                 if (SAME_CAP(i, exit_attribute_mode)) {
1005                     char *trimmed_sgr0;
1006                     char *my_sgr = set_attributes;
1007
1008                     set_attributes = save_sgr;
1009
1010                     trimmed_sgr0 = _nc_trim_sgr0(tterm);
1011                     if (strcmp(capability, trimmed_sgr0)) {
1012                         capability = trimmed_sgr0;
1013                     } else {
1014                         if (trimmed_sgr0 != exit_attribute_mode)
1015                             free(trimmed_sgr0);
1016                     }
1017
1018                     set_attributes = my_sgr;
1019                 }
1020             }
1021         }
1022
1023         predval = pred(STRING, i);
1024         buffer[0] = '\0';
1025
1026         if (predval != FAIL) {
1027             if (capability != ABSENT_STRING
1028                 && i + 1 > num_strings)
1029                 num_strings = i + 1;
1030
1031             if (!VALID_STRING(capability)) {
1032                 _nc_SPRINTF(buffer, _nc_SLIMIT(sizeof(buffer))
1033                             "%s@", name);
1034                 WRAP_CONCAT;
1035             } else if (TcOutput()) {
1036                 char *srccap = _nc_tic_expand(capability, TRUE, numbers);
1037                 int params = (((i < (int) SIZEOF(parametrized)) &&
1038                                (i < STRCOUNT))
1039                               ? parametrized[i]
1040                               : ((*srccap == 'k')
1041                                  ? 0
1042                                  : has_params(srccap)));
1043                 char *cv = _nc_infotocap(name, srccap, params);
1044
1045                 if (cv == 0) {
1046                     if (outform == F_TCONVERR) {
1047                         _nc_SPRINTF(buffer, _nc_SLIMIT(sizeof(buffer))
1048                                     "%s=!!! %s WILL NOT CONVERT !!!",
1049                                     name, srccap);
1050                         WRAP_CONCAT;
1051                     } else if (suppress_untranslatable) {
1052                         continue;
1053                     } else {
1054                         char *s = srccap, *d = buffer;
1055                         WRAP_CONCAT3("..", name, "=");
1056                         while ((*d = *s++) != 0) {
1057                             if ((d - buffer - 1) >= (int) sizeof(buffer)) {
1058                                 fprintf(stderr,
1059                                         "%s: value for %s is too long\n",
1060                                         _nc_progname,
1061                                         name);
1062                                 *d = '\0';
1063                                 break;
1064                             }
1065                             if (*d == ':') {
1066                                 *d++ = '\\';
1067                                 *d = ':';
1068                             } else if (*d == '\\') {
1069                                 *++d = *s++;
1070                             }
1071                             d++;
1072                         }
1073                         WRAP_CONCAT;
1074                     }
1075                 } else {
1076                     WRAP_CONCAT3(name, "=", cv);
1077                 }
1078                 len += (int) strlen(capability) + 1;
1079             } else {
1080                 char *src = _nc_tic_expand(capability,
1081                                            outform == F_TERMINFO, numbers);
1082
1083                 strcpy_DYN(&tmpbuf, 0);
1084                 strcpy_DYN(&tmpbuf, name);
1085                 strcpy_DYN(&tmpbuf, "=");
1086                 if (pretty
1087                     && (outform == F_TERMINFO
1088                         || outform == F_VARIABLE)) {
1089                     fmt_complex(tterm, name, src, 1);
1090                 } else {
1091                     strcpy_DYN(&tmpbuf, src);
1092                 }
1093                 len += (int) strlen(capability) + 1;
1094                 WRAP_CONCAT1(tmpbuf.text);
1095             }
1096         }
1097         /* e.g., trimmed_sgr0 */
1098         if (capability != ABSENT_STRING &&
1099             capability != CANCELLED_STRING &&
1100             capability != tterm->Strings[i])
1101             free(capability);
1102     }
1103     len += (int) (num_strings * 2);
1104
1105     /*
1106      * This piece of code should be an effective inverse of the functions
1107      * postprocess_terminfo() and postprocess_terminfo() in parse_entry.c.
1108      * Much more work should be done on this to support dumping termcaps.
1109      */
1110     if (tversion == V_HPUX) {
1111         if (VALID_STRING(memory_lock)) {
1112             _nc_SPRINTF(buffer, _nc_SLIMIT(sizeof(buffer))
1113                         "meml=%s", memory_lock);
1114             WRAP_CONCAT;
1115         }
1116         if (VALID_STRING(memory_unlock)) {
1117             _nc_SPRINTF(buffer, _nc_SLIMIT(sizeof(buffer))
1118                         "memu=%s", memory_unlock);
1119             WRAP_CONCAT;
1120         }
1121     } else if (tversion == V_AIX) {
1122         if (VALID_STRING(acs_chars)) {
1123             bool box_ok = TRUE;
1124             const char *acstrans = "lqkxjmwuvtn";
1125             const char *cp;
1126             char *tp, *sp, boxchars[11];
1127
1128             tp = boxchars;
1129             for (cp = acstrans; *cp; cp++) {
1130                 sp = (strchr) (acs_chars, *cp);
1131                 if (sp)
1132                     *tp++ = sp[1];
1133                 else {
1134                     box_ok = FALSE;
1135                     break;
1136                 }
1137             }
1138             tp[0] = '\0';
1139
1140             if (box_ok) {
1141                 char *tmp = _nc_tic_expand(boxchars,
1142                                            (outform == F_TERMINFO),
1143                                            numbers);
1144                 _nc_STRCPY(buffer, "box1=", sizeof(buffer));
1145                 while (*tmp != '\0') {
1146                     size_t have = strlen(buffer);
1147                     size_t next = strlen(tmp);
1148                     size_t want = have + next + 1;
1149                     size_t last = next;
1150                     char save = '\0';
1151
1152                     /*
1153                      * If the expanded string is too long for the buffer,
1154                      * chop it off and save the location where we chopped it.
1155                      */
1156                     if (want >= sizeof(buffer)) {
1157                         save = tmp[last];
1158                         tmp[last] = '\0';
1159                     }
1160                     _nc_STRCAT(buffer, tmp, sizeof(buffer));
1161
1162                     /*
1163                      * If we chopped the buffer, replace the missing piece and
1164                      * shift everything to append the remainder.
1165                      */
1166                     if (save != '\0') {
1167                         next = 0;
1168                         tmp[last] = save;
1169                         while ((tmp[next] = tmp[last + next]) != '\0') {
1170                             ++next;
1171                         }
1172                     } else {
1173                         break;
1174                     }
1175                 }
1176                 WRAP_CONCAT;
1177             }
1178         }
1179     }
1180
1181     /*
1182      * kludge: trim off trailer to avoid an extra blank line
1183      * in infocmp -u output when there are no string differences
1184      */
1185     if (outcount) {
1186         bool trimmed = FALSE;
1187         j = (PredIdx) outbuf.used;
1188         if (wrapped && did_wrap) {
1189             /* EMPTY */ ;
1190         } else if (j >= 2
1191                    && outbuf.text[j - 1] == '\t'
1192                    && outbuf.text[j - 2] == '\n') {
1193             outbuf.used -= 2;
1194             trimmed = TRUE;
1195         } else if (j >= 4
1196                    && outbuf.text[j - 1] == ':'
1197                    && outbuf.text[j - 2] == '\t'
1198                    && outbuf.text[j - 3] == '\n'
1199                    && outbuf.text[j - 4] == '\\') {
1200             outbuf.used -= 4;
1201             trimmed = TRUE;
1202         }
1203         if (trimmed) {
1204             outbuf.text[outbuf.used] = '\0';
1205             column = oldcol;
1206             strcpy_DYN(&outbuf, " ");
1207         }
1208     }
1209 #if 0
1210     fprintf(stderr, "num_bools = %d\n", num_bools);
1211     fprintf(stderr, "num_values = %d\n", num_values);
1212     fprintf(stderr, "num_strings = %d\n", num_strings);
1213     fprintf(stderr, "term_names=%s, len=%d, strlen(outbuf)=%d, outbuf=%s\n",
1214             tterm->term_names, len, outbuf.used, outbuf.text);
1215 #endif
1216     /*
1217      * Here's where we use infodump to trigger a more stringent length check
1218      * for termcap-translation purposes.
1219      * Return the length of the raw entry, without tc= expansions,
1220      * It gives an idea of which entries are deadly to even *scan past*,
1221      * as opposed to *use*.
1222      */
1223     return (infodump ? len : (int) termcap_length(outbuf.text));
1224 }
1225
1226 static bool
1227 kill_string(TERMTYPE2 *tterm, char *cap)
1228 {
1229     unsigned n;
1230     for (n = 0; n < NUM_STRINGS(tterm); ++n) {
1231         if (cap == tterm->Strings[n]) {
1232             tterm->Strings[n] = ABSENT_STRING;
1233             return TRUE;
1234         }
1235     }
1236     return FALSE;
1237 }
1238
1239 static char *
1240 find_string(TERMTYPE2 *tterm, char *name)
1241 {
1242     PredIdx n;
1243     for (n = 0; n < NUM_STRINGS(tterm); ++n) {
1244         if (version_filter(STRING, n)
1245             && !strcmp(name, strnames[n])) {
1246             char *cap = tterm->Strings[n];
1247             if (VALID_STRING(cap)) {
1248                 return cap;
1249             }
1250             break;
1251         }
1252     }
1253     return ABSENT_STRING;
1254 }
1255
1256 /*
1257  * This is used to remove function-key labels from a termcap entry to
1258  * make it smaller.
1259  */
1260 static int
1261 kill_labels(TERMTYPE2 *tterm, int target)
1262 {
1263     int n;
1264     int result = 0;
1265     char *cap;
1266     char name[10];
1267
1268     for (n = 0; n <= 10; ++n) {
1269         _nc_SPRINTF(name, _nc_SLIMIT(sizeof(name)) "lf%d", n);
1270         if ((cap = find_string(tterm, name)) != ABSENT_STRING
1271             && kill_string(tterm, cap)) {
1272             target -= (int) (strlen(cap) + 5);
1273             ++result;
1274             if (target < 0)
1275                 break;
1276         }
1277     }
1278     return result;
1279 }
1280
1281 /*
1282  * This is used to remove function-key definitions from a termcap entry to
1283  * make it smaller.
1284  */
1285 static int
1286 kill_fkeys(TERMTYPE2 *tterm, int target)
1287 {
1288     int n;
1289     int result = 0;
1290     char *cap;
1291     char name[10];
1292
1293     for (n = 60; n >= 0; --n) {
1294         _nc_SPRINTF(name, _nc_SLIMIT(sizeof(name)) "kf%d", n);
1295         if ((cap = find_string(tterm, name)) != ABSENT_STRING
1296             && kill_string(tterm, cap)) {
1297             target -= (int) (strlen(cap) + 5);
1298             ++result;
1299             if (target < 0)
1300                 break;
1301         }
1302     }
1303     return result;
1304 }
1305
1306 /*
1307  * Check if the given acsc string is a 1-1 mapping, i.e., just-like-vt100.
1308  * Also, since this is for termcap, we only care about the line-drawing map.
1309  */
1310 #define isLine(c) (strchr("lmkjtuvwqxn", c) != 0)
1311
1312 static bool
1313 one_one_mapping(const char *mapping)
1314 {
1315     bool result = TRUE;
1316
1317     if (mapping != ABSENT_STRING) {
1318         int n = 0;
1319         while (mapping[n] != '\0') {
1320             if (isLine(mapping[n]) &&
1321                 mapping[n] != mapping[n + 1]) {
1322                 result = FALSE;
1323                 break;
1324             }
1325             n += 2;
1326         }
1327     }
1328     return result;
1329 }
1330
1331 #define FMT_ENTRY() \
1332                 fmt_entry(tterm, pred, \
1333                         0, \
1334                         suppress_untranslatable, \
1335                         infodump, numbers)
1336
1337 #define SHOW_WHY PRINTF
1338
1339 static bool
1340 purged_acs(TERMTYPE2 *tterm)
1341 {
1342     bool result = FALSE;
1343
1344     if (VALID_STRING(acs_chars)) {
1345         if (!one_one_mapping(acs_chars)) {
1346             enter_alt_charset_mode = ABSENT_STRING;
1347             exit_alt_charset_mode = ABSENT_STRING;
1348             SHOW_WHY("# (rmacs/smacs removed for consistency)\n");
1349         }
1350         result = TRUE;
1351     }
1352     return result;
1353 }
1354
1355 static void
1356 encode_b64(char *target, char *source, unsigned state, int *saved)
1357 {
1358     /* RFC-4648 */
1359     static const char data[] =
1360     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1361     "abcdefghijklmnopqrstuvwxyz"
1362     "0123456789" "-_";
1363     int ch = UChar(source[state]);
1364
1365     switch (state % 3) {
1366     case 0:
1367         *target++ = data[(ch >> 2) & 077];
1368         *saved = (ch << 4);
1369         break;
1370     case 1:
1371         *target++ = data[((ch >> 4) | *saved) & 077];
1372         *saved = (ch << 2);
1373         break;
1374     case 2:
1375         *target++ = data[((ch >> 6) | *saved) & 077];
1376         *target++ = data[ch & 077];
1377         *saved = 0;
1378         break;
1379     }
1380     *target = '\0';
1381 }
1382
1383 /*
1384  * Dump a single entry.
1385  */
1386 void
1387 dump_entry(TERMTYPE2 *tterm,
1388            int suppress_untranslatable,
1389            int limited,
1390            int numbers,
1391            PredFunc pred)
1392 {
1393     TERMTYPE2 save_tterm;
1394     int len, critlen;
1395     const char *legend;
1396     bool infodump;
1397
1398     if (quickdump) {
1399         char bigbuf[65536];
1400         unsigned n;
1401         unsigned offset = 0;
1402         separator = "";
1403         trailer = "\n";
1404         indent = 0;
1405         if (_nc_write_object(tterm, bigbuf, &offset, sizeof(bigbuf)) == OK) {
1406             char numbuf[80];
1407             if (quickdump & 1) {
1408                 if (outbuf.used)
1409                     wrap_concat("\n");
1410                 wrap_concat("hex:");
1411                 for (n = 0; n < offset; ++n) {
1412                     _nc_SPRINTF(numbuf, _nc_SLIMIT(sizeof(numbuf))
1413                                 "%02X", UChar(bigbuf[n]));
1414                     wrap_concat(numbuf);
1415                 }
1416             }
1417             if (quickdump & 2) {
1418                 static char padding[] =
1419                 {0, 0};
1420                 int value = 0;
1421                 if (outbuf.used)
1422                     wrap_concat("\n");
1423                 wrap_concat("b64:");
1424                 for (n = 0; n < offset; ++n) {
1425                     encode_b64(numbuf, bigbuf, n, &value);
1426                     wrap_concat(numbuf);
1427                 }
1428                 switch (n % 3) {
1429                 case 0:
1430                     break;
1431                 case 1:
1432                     encode_b64(numbuf, padding, 1, &value);
1433                     wrap_concat(numbuf);
1434                     wrap_concat("==");
1435                     break;
1436                 case 2:
1437                     encode_b64(numbuf, padding, 1, &value);
1438                     wrap_concat(numbuf);
1439                     wrap_concat("=");
1440                     break;
1441                 }
1442             }
1443         }
1444         return;
1445     }
1446
1447     if (TcOutput()) {
1448         critlen = MAX_TERMCAP_LENGTH;
1449         legend = "older termcap";
1450         infodump = FALSE;
1451         set_obsolete_termcaps(tterm);
1452     } else {
1453         critlen = MAX_TERMINFO_LENGTH;
1454         legend = "terminfo";
1455         infodump = TRUE;
1456     }
1457
1458     save_sgr = set_attributes;
1459
1460     if ((FMT_ENTRY() > critlen)
1461         && limited) {
1462
1463         save_tterm = *tterm;
1464         if (!suppress_untranslatable) {
1465             SHOW_WHY("# (untranslatable capabilities removed to fit entry within %d bytes)\n",
1466                      critlen);
1467             suppress_untranslatable = TRUE;
1468         }
1469         if (FMT_ENTRY() > critlen) {
1470             /*
1471              * We pick on sgr because it's a nice long string capability that
1472              * is really just an optimization hack.  Another good candidate is
1473              * acsc since it is both long and unused by BSD termcap.
1474              */
1475             bool changed = FALSE;
1476
1477 #if NCURSES_XNAMES
1478             /*
1479              * Extended names are most likely function-key definitions.  Drop
1480              * those first.
1481              */
1482             unsigned n;
1483             for (n = STRCOUNT; n < NUM_STRINGS(tterm); n++) {
1484                 const char *name = ExtStrname(tterm, (int) n, strnames);
1485
1486                 if (VALID_STRING(tterm->Strings[n])) {
1487                     set_attributes = ABSENT_STRING;
1488                     /* we remove long names anyway - only report the short */
1489                     if (strlen(name) <= 2) {
1490                         SHOW_WHY("# (%s removed to fit entry within %d bytes)\n",
1491                                  name,
1492                                  critlen);
1493                     }
1494                     changed = TRUE;
1495                     if (FMT_ENTRY() <= critlen)
1496                         break;
1497                 }
1498             }
1499 #endif
1500             if (VALID_STRING(set_attributes)) {
1501                 set_attributes = ABSENT_STRING;
1502                 SHOW_WHY("# (sgr removed to fit entry within %d bytes)\n",
1503                          critlen);
1504                 changed = TRUE;
1505             }
1506             if (!changed || (FMT_ENTRY() > critlen)) {
1507                 if (purged_acs(tterm)) {
1508                     acs_chars = ABSENT_STRING;
1509                     SHOW_WHY("# (acsc removed to fit entry within %d bytes)\n",
1510                              critlen);
1511                     changed = TRUE;
1512                 }
1513             }
1514             if (!changed || (FMT_ENTRY() > critlen)) {
1515                 int oldversion = tversion;
1516
1517                 tversion = V_BSD;
1518                 SHOW_WHY("# (terminfo-only capabilities suppressed to fit entry within %d bytes)\n",
1519                          critlen);
1520
1521                 len = FMT_ENTRY();
1522                 if (len > critlen
1523                     && kill_labels(tterm, len - critlen)) {
1524                     SHOW_WHY("# (some labels capabilities suppressed to fit entry within %d bytes)\n",
1525                              critlen);
1526                     len = FMT_ENTRY();
1527                 }
1528                 if (len > critlen
1529                     && kill_fkeys(tterm, len - critlen)) {
1530                     SHOW_WHY("# (some function-key capabilities suppressed to fit entry within %d bytes)\n",
1531                              critlen);
1532                     len = FMT_ENTRY();
1533                 }
1534                 if (len > critlen) {
1535                     (void) fprintf(stderr,
1536                                    "%s: %s entry is %d bytes long\n",
1537                                    _nc_progname,
1538                                    _nc_first_name(tterm->term_names),
1539                                    len);
1540                     SHOW_WHY("# WARNING: this entry, %d bytes long, may core-dump %s libraries!\n",
1541                              len, legend);
1542                 }
1543                 tversion = oldversion;
1544             }
1545             set_attributes = save_sgr;
1546             *tterm = save_tterm;
1547         }
1548     } else if (!version_filter(STRING, STR_IDX(acs_chars))) {
1549         save_tterm = *tterm;
1550         if (purged_acs(tterm)) {
1551             (void) FMT_ENTRY();
1552         }
1553         *tterm = save_tterm;
1554     }
1555 }
1556
1557 void
1558 dump_uses(const char *name, bool infodump)
1559 /* dump "use=" clauses in the appropriate format */
1560 {
1561     char buffer[MAX_TERMINFO_LENGTH];
1562
1563     if (TcOutput())
1564         trim_trailing();
1565     _nc_SPRINTF(buffer, _nc_SLIMIT(sizeof(buffer))
1566                 "%s%s", infodump ? "use=" : "tc=", name);
1567     wrap_concat(buffer);
1568 }
1569
1570 int
1571 show_entry(void)
1572 {
1573     /*
1574      * Trim any remaining whitespace.
1575      */
1576     if (outbuf.used != 0) {
1577         bool infodump = !TcOutput();
1578         char delim = (char) (infodump ? ',' : ':');
1579         int j;
1580
1581         for (j = (int) outbuf.used - 1; j > 0; --j) {
1582             char ch = outbuf.text[j];
1583             if (ch == '\n') {
1584                 ;
1585             } else if (isspace(UChar(ch))) {
1586                 outbuf.used = (size_t) j;
1587             } else if (!infodump && ch == '\\') {
1588                 outbuf.used = (size_t) j;
1589             } else if (ch == delim && (j == 0 || outbuf.text[j - 1] != '\\')) {
1590                 outbuf.used = (size_t) (j + 1);
1591             } else {
1592                 break;
1593             }
1594         }
1595         outbuf.text[outbuf.used] = '\0';
1596     }
1597     if (outbuf.text != 0) {
1598         (void) fputs(outbuf.text, stdout);
1599         putchar('\n');
1600     }
1601     return (int) outbuf.used;
1602 }
1603
1604 void
1605 compare_entry(PredHook hook,
1606               TERMTYPE2 *tp GCC_UNUSED,
1607               bool quiet)
1608 /* compare two entries */
1609 {
1610     PredIdx i, j;
1611     NCURSES_CONST char *name;
1612
1613     if (!quiet)
1614         fputs("    comparing booleans.\n", stdout);
1615     for_each_boolean(j, tp) {
1616         i = BoolIndirect(j);
1617         name = ExtBoolname(tp, (int) i, bool_names);
1618
1619         if (isObsolete(outform, name))
1620             continue;
1621
1622         (*hook) (CMP_BOOLEAN, i, name);
1623     }
1624
1625     if (!quiet)
1626         fputs("    comparing numbers.\n", stdout);
1627     for_each_number(j, tp) {
1628         i = NumIndirect(j);
1629         name = ExtNumname(tp, (int) i, num_names);
1630
1631         if (isObsolete(outform, name))
1632             continue;
1633
1634         (*hook) (CMP_NUMBER, i, name);
1635     }
1636
1637     if (!quiet)
1638         fputs("    comparing strings.\n", stdout);
1639     for_each_string(j, tp) {
1640         i = StrIndirect(j);
1641         name = ExtStrname(tp, (int) i, str_names);
1642
1643         if (isObsolete(outform, name))
1644             continue;
1645
1646         (*hook) (CMP_STRING, i, name);
1647     }
1648
1649     /* (void) fputs("    comparing use entries.\n", stdout); */
1650     (*hook) (CMP_USE, 0, "use");
1651
1652 }
1653
1654 #define NOTSET(s)       ((s) == 0)
1655
1656 /*
1657  * This bit of legerdemain turns all the terminfo variable names into
1658  * references to locations in the arrays Booleans, Numbers, and Strings ---
1659  * precisely what's needed.
1660  */
1661 #undef CUR
1662 #define CUR tp->
1663
1664 static void
1665 set_obsolete_termcaps(TERMTYPE2 *tp)
1666 {
1667 #include "capdefaults.c"
1668 }
1669
1670 /*
1671  * Convert an alternate-character-set string to canonical form: sorted and
1672  * unique.
1673  */
1674 void
1675 repair_acsc(TERMTYPE2 *tp)
1676 {
1677     if (VALID_STRING(acs_chars)) {
1678         size_t n, m;
1679         char mapped[256];
1680         char extra = 0;
1681         unsigned source;
1682         unsigned target;
1683         bool fix_needed = FALSE;
1684
1685         for (n = 0, source = 0; acs_chars[n] != 0; n++) {
1686             target = UChar(acs_chars[n]);
1687             if (source >= target) {
1688                 fix_needed = TRUE;
1689                 break;
1690             }
1691             source = target;
1692             if (acs_chars[n + 1])
1693                 n++;
1694         }
1695         if (fix_needed) {
1696             memset(mapped, 0, sizeof(mapped));
1697             for (n = 0; acs_chars[n] != 0; n++) {
1698                 source = UChar(acs_chars[n]);
1699                 if ((target = (unsigned char) acs_chars[n + 1]) != 0) {
1700                     mapped[source] = (char) target;
1701                     n++;
1702                 } else {
1703                     extra = (char) source;
1704                 }
1705             }
1706             for (n = m = 0; n < sizeof(mapped); n++) {
1707                 if (mapped[n]) {
1708                     acs_chars[m++] = (char) n;
1709                     acs_chars[m++] = mapped[n];
1710                 }
1711             }
1712             if (extra)
1713                 acs_chars[m++] = extra;         /* garbage in, garbage out */
1714             acs_chars[m] = 0;
1715         }
1716     }
1717 }