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