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