]> ncurses.scripts.mit.edu Git - ncurses.git/blob - progs/tic.c
ncurses 5.9 - patch 20111112
[ncurses.git] / progs / tic.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 /*
36  *      tic.c --- Main program for terminfo compiler
37  *                      by Eric S. Raymond
38  *
39  */
40
41 #include <progs.priv.h>
42 #include <sys/stat.h>
43
44 #include <dump_entry.h>
45 #include <transform.h>
46
47 MODULE_ID("$Id: tic.c,v 1.153 2011/09/26 23:50:46 tom Exp $")
48
49 const char *_nc_progname = "tic";
50
51 static FILE *log_fp;
52 static FILE *tmp_fp;
53 static bool capdump = FALSE;    /* running as infotocap? */
54 static bool infodump = FALSE;   /* running as captoinfo? */
55 static bool showsummary = FALSE;
56 static const char *to_remove;
57
58 static void (*save_check_termtype) (TERMTYPE *, bool);
59 static void check_termtype(TERMTYPE *tt, bool);
60
61 static const char usage_string[] = "\
62 [-e names] \
63 [-o dir] \
64 [-R name] \
65 [-v[n]] \
66 [-V] \
67 [-w[n]] \
68 [-\
69 1\
70 a\
71 C\
72 c\
73 f\
74 G\
75 g\
76 I\
77 K\
78 L\
79 N\
80 r\
81 s\
82 T\
83 t\
84 U\
85 x\
86 ] \
87 source-file\n";
88
89 #if NO_LEAKS
90 static void
91 free_namelist(char **src)
92 {
93     if (src != 0) {
94         int n;
95         for (n = 0; src[n] != 0; ++n)
96             free(src[n]);
97         free(src);
98     }
99 }
100 #endif
101
102 static void
103 cleanup(char **namelst GCC_UNUSED)
104 {
105 #if NO_LEAKS
106     free_namelist(namelst);
107 #endif
108     if (tmp_fp != 0)
109         fclose(tmp_fp);
110     if (to_remove != 0) {
111 #if HAVE_REMOVE
112         remove(to_remove);
113 #else
114         unlink(to_remove);
115 #endif
116     }
117 }
118
119 static void
120 failed(const char *msg)
121 {
122     perror(msg);
123     cleanup((char **) 0);
124     ExitProgram(EXIT_FAILURE);
125 }
126
127 static void
128 usage(void)
129 {
130     static const char *const tbl[] =
131     {
132         "Options:",
133         "  -1         format translation output one capability per line",
134 #if NCURSES_XNAMES
135         "  -a         retain commented-out capabilities (sets -x also)",
136 #endif
137         "  -K         translate entries to termcap source form with BSD syntax",
138         "  -C         translate entries to termcap source form",
139         "  -c         check only, validate input without compiling or translating",
140         "  -e<names>  translate/compile only entries named by comma-separated list",
141         "  -f         format complex strings for readability",
142         "  -G         format %{number} to %'char'",
143         "  -g         format %'char' to %{number}",
144         "  -I         translate entries to terminfo source form",
145         "  -L         translate entries to full terminfo source form",
146         "  -N         disable smart defaults for source translation",
147         "  -o<dir>    set output directory for compiled entry writes",
148         "  -R<name>   restrict translation to given terminfo/termcap version",
149         "  -r         force resolution of all use entries in source translation",
150         "  -s         print summary statistics",
151         "  -T         remove size-restrictions on compiled description",
152 #if NCURSES_XNAMES
153         "  -t         suppress commented-out capabilities",
154 #endif
155         "  -U         suppress post-processing of entries",
156         "  -V         print version",
157         "  -v[n]      set verbosity level",
158         "  -w[n]      set format width for translation output",
159 #if NCURSES_XNAMES
160         "  -x         treat unknown capabilities as user-defined",
161 #endif
162         "",
163         "Parameters:",
164         "  <file>     file to translate or compile"
165     };
166     size_t j;
167
168     fprintf(stderr, "Usage: %s %s\n", _nc_progname, usage_string);
169     for (j = 0; j < SIZEOF(tbl); j++) {
170         fputs(tbl[j], stderr);
171         putc('\n', stderr);
172     }
173     ExitProgram(EXIT_FAILURE);
174 }
175
176 #define L_BRACE '{'
177 #define R_BRACE '}'
178 #define S_QUOTE '\'';
179
180 static void
181 write_it(ENTRY * ep)
182 {
183     unsigned n;
184     int ch;
185     char *s, *d, *t;
186     char result[MAX_ENTRY_SIZE];
187
188     /*
189      * Look for strings that contain %{number}, convert them to %'char',
190      * which is shorter and runs a little faster.
191      */
192     for (n = 0; n < STRCOUNT; n++) {
193         s = ep->tterm.Strings[n];
194         if (VALID_STRING(s)
195             && strchr(s, L_BRACE) != 0) {
196             d = result;
197             t = s;
198             while ((ch = *t++) != 0) {
199                 *d++ = (char) ch;
200                 if (ch == '\\') {
201                     *d++ = *t++;
202                 } else if ((ch == '%')
203                            && (*t == L_BRACE)) {
204                     char *v = 0;
205                     long value = strtol(t + 1, &v, 0);
206                     if (v != 0
207                         && *v == R_BRACE
208                         && value > 0
209                         && value != '\\'        /* FIXME */
210                         && value < 127
211                         && isprint((int) value)) {
212                         *d++ = S_QUOTE;
213                         *d++ = (char) value;
214                         *d++ = S_QUOTE;
215                         t = (v + 1);
216                     }
217                 }
218             }
219             *d = 0;
220             if (strlen(result) < strlen(s))
221                 strcpy(s, result);
222         }
223     }
224
225     _nc_set_type(_nc_first_name(ep->tterm.term_names));
226     _nc_curr_line = (int) ep->startline;
227     _nc_write_entry(&ep->tterm);
228 }
229
230 static bool
231 immedhook(ENTRY * ep GCC_UNUSED)
232 /* write out entries with no use capabilities immediately to save storage */
233 {
234 #if !HAVE_BIG_CORE
235     /*
236      * This is strictly a core-economy kluge.  The really clean way to handle
237      * compilation is to slurp the whole file into core and then do all the
238      * name-collision checks and entry writes in one swell foop.  But the
239      * terminfo master file is large enough that some core-poor systems swap
240      * like crazy when you compile it this way...there have been reports of
241      * this process taking *three hours*, rather than the twenty seconds or
242      * less typical on my development box.
243      *
244      * So.  This hook *immediately* writes out the referenced entry if it
245      * has no use capabilities.  The compiler main loop refrains from
246      * adding the entry to the in-core list when this hook fires.  If some
247      * other entry later needs to reference an entry that got written
248      * immediately, that's OK; the resolution code will fetch it off disk
249      * when it can't find it in core.
250      *
251      * Name collisions will still be detected, just not as cleanly.  The
252      * write_entry() code complains before overwriting an entry that
253      * postdates the time of tic's first call to write_entry().  Thus
254      * it will complain about overwriting entries newly made during the
255      * tic run, but not about overwriting ones that predate it.
256      *
257      * The reason this is a hook, and not in line with the rest of the
258      * compiler code, is that the support for termcap fallback cannot assume
259      * it has anywhere to spool out these entries!
260      *
261      * The _nc_set_type() call here requires a compensating one in
262      * _nc_parse_entry().
263      *
264      * If you define HAVE_BIG_CORE, you'll disable this kluge.  This will
265      * make tic a bit faster (because the resolution code won't have to do
266      * disk I/O nearly as often).
267      */
268     if (ep->nuses == 0) {
269         int oldline = _nc_curr_line;
270
271         write_it(ep);
272         _nc_curr_line = oldline;
273         free(ep->tterm.str_table);
274         return (TRUE);
275     }
276 #endif /* HAVE_BIG_CORE */
277     return (FALSE);
278 }
279
280 static void
281 put_translate(int c)
282 /* emit a comment char, translating terminfo names to termcap names */
283 {
284     static bool in_name = FALSE;
285     static size_t have, used;
286     static char *namebuf, *suffix;
287
288     if (in_name) {
289         if (used + 1 >= have) {
290             have += 132;
291             namebuf = typeRealloc(char, have, namebuf);
292             suffix = typeRealloc(char, have, suffix);
293         }
294         if (c == '\n' || c == '@') {
295             namebuf[used++] = '\0';
296             (void) putchar('<');
297             (void) fputs(namebuf, stdout);
298             putchar(c);
299             in_name = FALSE;
300         } else if (c != '>') {
301             namebuf[used++] = (char) c;
302         } else {                /* ah! candidate name! */
303             char *up;
304             NCURSES_CONST char *tp;
305
306             namebuf[used++] = '\0';
307             in_name = FALSE;
308
309             suffix[0] = '\0';
310             if ((up = strchr(namebuf, '#')) != 0
311                 || (up = strchr(namebuf, '=')) != 0
312                 || ((up = strchr(namebuf, '@')) != 0 && up[1] == '>')) {
313                 (void) strcpy(suffix, up);
314                 *up = '\0';
315             }
316
317             if ((tp = nametrans(namebuf)) != 0) {
318                 (void) putchar(':');
319                 (void) fputs(tp, stdout);
320                 (void) fputs(suffix, stdout);
321                 (void) putchar(':');
322             } else {
323                 /* couldn't find a translation, just dump the name */
324                 (void) putchar('<');
325                 (void) fputs(namebuf, stdout);
326                 (void) fputs(suffix, stdout);
327                 (void) putchar('>');
328             }
329         }
330     } else {
331         used = 0;
332         if (c == '<') {
333             in_name = TRUE;
334         } else {
335             putchar(c);
336         }
337     }
338 }
339
340 /* Returns a string, stripped of leading/trailing whitespace */
341 static char *
342 stripped(char *src)
343 {
344     char *dst = 0;
345
346     while (isspace(UChar(*src)))
347         src++;
348
349     if (*src != '\0') {
350         size_t len;
351
352         if ((dst = strdup(src)) == NULL) {
353             failed("strdup");
354         } else {
355             len = strlen(dst);
356             while (--len != 0 && isspace(UChar(dst[len])))
357                 dst[len] = '\0';
358         }
359     }
360     return dst;
361 }
362
363 static FILE *
364 open_input(const char *filename)
365 {
366     FILE *fp = fopen(filename, "r");
367     struct stat sb;
368
369     if (fp == 0) {
370         fprintf(stderr, "%s: Can't open %s\n", _nc_progname, filename);
371         ExitProgram(EXIT_FAILURE);
372     }
373     if (fstat(fileno(fp), &sb) < 0
374         || (sb.st_mode & S_IFMT) != S_IFREG) {
375         fprintf(stderr, "%s: %s is not a file\n", _nc_progname, filename);
376         ExitProgram(EXIT_FAILURE);
377     }
378     return fp;
379 }
380
381 /* Parse the "-e" option-value into a list of names */
382 static char **
383 make_namelist(char *src)
384 {
385     char **dst = 0;
386
387     char *s, *base;
388     unsigned pass, n, nn;
389     char buffer[BUFSIZ];
390
391     if (src == 0) {
392         /* EMPTY */ ;
393     } else if (strchr(src, '/') != 0) {         /* a filename */
394         FILE *fp = open_input(src);
395
396         for (pass = 1; pass <= 2; pass++) {
397             nn = 0;
398             while (fgets(buffer, sizeof(buffer), fp) != 0) {
399                 if ((s = stripped(buffer)) != 0) {
400                     if (dst != 0)
401                         dst[nn] = s;
402                     else
403                         free(s);
404                     nn++;
405                 }
406             }
407             if (pass == 1) {
408                 dst = typeCalloc(char *, nn + 1);
409                 rewind(fp);
410             }
411         }
412         fclose(fp);
413     } else {                    /* literal list of names */
414         for (pass = 1; pass <= 2; pass++) {
415             for (n = nn = 0, base = src;; n++) {
416                 int mark = src[n];
417                 if (mark == ',' || mark == '\0') {
418                     if (pass == 1) {
419                         nn++;
420                     } else {
421                         src[n] = '\0';
422                         if ((s = stripped(base)) != 0)
423                             dst[nn++] = s;
424                         base = &src[n + 1];
425                     }
426                 }
427                 if (mark == '\0')
428                     break;
429             }
430             if (pass == 1)
431                 dst = typeCalloc(char *, nn + 1);
432         }
433     }
434     if (showsummary && (dst != 0)) {
435         fprintf(log_fp, "Entries that will be compiled:\n");
436         for (n = 0; dst[n] != 0; n++)
437             fprintf(log_fp, "%u:%s\n", n + 1, dst[n]);
438     }
439     return dst;
440 }
441
442 static bool
443 matches(char **needle, const char *haystack)
444 /* does entry in needle list match |-separated field in haystack? */
445 {
446     bool code = FALSE;
447     size_t n;
448
449     if (needle != 0) {
450         for (n = 0; needle[n] != 0; n++) {
451             if (_nc_name_match(haystack, needle[n], "|")) {
452                 code = TRUE;
453                 break;
454             }
455         }
456     } else
457         code = TRUE;
458     return (code);
459 }
460
461 static FILE *
462 open_tempfile(char *name)
463 {
464     FILE *result = 0;
465 #if HAVE_MKSTEMP
466     int fd = mkstemp(name);
467     if (fd >= 0)
468         result = fdopen(fd, "w");
469 #else
470     if (tmpnam(name) != 0)
471         result = fopen(name, "w");
472 #endif
473     return result;
474 }
475
476 int
477 main(int argc, char *argv[])
478 {
479     char my_tmpname[PATH_MAX];
480     int v_opt = -1;
481     unsigned debug_level;
482     int smart_defaults = TRUE;
483     char *termcap;
484     ENTRY *qp;
485
486     int this_opt, last_opt = '?';
487
488     int outform = F_TERMINFO;   /* output format */
489     int sortmode = S_TERMINFO;  /* sort_mode */
490
491     int width = 60;
492     int height = 65535;
493     bool formatted = FALSE;     /* reformat complex strings? */
494     bool literal = FALSE;       /* suppress post-processing? */
495     int numbers = 0;            /* format "%'char'" to/from "%{number}" */
496     bool forceresolve = FALSE;  /* force resolution */
497     bool limited = TRUE;
498     char *tversion = (char *) NULL;
499     const char *source_file = "terminfo";
500     char **namelst = 0;
501     char *outdir = (char *) NULL;
502     bool check_only = FALSE;
503     bool suppress_untranslatable = FALSE;
504
505     log_fp = stderr;
506
507     _nc_progname = _nc_rootname(argv[0]);
508
509     if ((infodump = same_program(_nc_progname, PROG_CAPTOINFO)) != FALSE) {
510         outform = F_TERMINFO;
511         sortmode = S_TERMINFO;
512     }
513     if ((capdump = same_program(_nc_progname, PROG_INFOTOCAP)) != FALSE) {
514         outform = F_TERMCAP;
515         sortmode = S_TERMCAP;
516     }
517 #if NCURSES_XNAMES
518     use_extended_names(FALSE);
519 #endif
520     _nc_strict_bsd = 0;
521
522     /*
523      * Processing arguments is a little complicated, since someone made a
524      * design decision to allow the numeric values for -w, -v options to
525      * be optional.
526      */
527     while ((this_opt = getopt(argc, argv,
528                               "0123456789CIKLNR:TUVace:fGgo:rstvwx")) != -1) {
529         if (isdigit(this_opt)) {
530             switch (last_opt) {
531             case 'v':
532                 v_opt = (v_opt * 10) + (this_opt - '0');
533                 break;
534             case 'w':
535                 width = (width * 10) + (this_opt - '0');
536                 break;
537             default:
538                 switch (this_opt) {
539                 case '0':
540                     last_opt = this_opt;
541                     width = 65535;
542                     height = 1;
543                     break;
544                 case '1':
545                     last_opt = this_opt;
546                     width = 0;
547                     break;
548                 default:
549                     usage();
550                 }
551             }
552             continue;
553         }
554         switch (this_opt) {
555         case 'K':
556             _nc_strict_bsd = 1;
557             /* the initial version of -K in 20110730 fell-thru here, but the
558              * same flag is useful when reading sources -TD
559              */
560             break;
561         case 'C':
562             capdump = TRUE;
563             outform = F_TERMCAP;
564             sortmode = S_TERMCAP;
565             break;
566         case 'I':
567             infodump = TRUE;
568             outform = F_TERMINFO;
569             sortmode = S_TERMINFO;
570             break;
571         case 'L':
572             infodump = TRUE;
573             outform = F_VARIABLE;
574             sortmode = S_VARIABLE;
575             break;
576         case 'N':
577             smart_defaults = FALSE;
578             literal = TRUE;
579             break;
580         case 'R':
581             tversion = optarg;
582             break;
583         case 'T':
584             limited = FALSE;
585             break;
586         case 'U':
587             literal = TRUE;
588             break;
589         case 'V':
590             puts(curses_version());
591             cleanup(namelst);
592             ExitProgram(EXIT_SUCCESS);
593         case 'c':
594             check_only = TRUE;
595             break;
596         case 'e':
597             namelst = make_namelist(optarg);
598             break;
599         case 'f':
600             formatted = TRUE;
601             break;
602         case 'G':
603             numbers = 1;
604             break;
605         case 'g':
606             numbers = -1;
607             break;
608         case 'o':
609             outdir = optarg;
610             break;
611         case 'r':
612             forceresolve = TRUE;
613             break;
614         case 's':
615             showsummary = TRUE;
616             break;
617         case 'v':
618             v_opt = 0;
619             break;
620         case 'w':
621             width = 0;
622             break;
623 #if NCURSES_XNAMES
624         case 't':
625             _nc_disable_period = FALSE;
626             suppress_untranslatable = TRUE;
627             break;
628         case 'a':
629             _nc_disable_period = TRUE;
630             /* FALLTHRU */
631         case 'x':
632             use_extended_names(TRUE);
633             break;
634 #endif
635         default:
636             usage();
637         }
638         last_opt = this_opt;
639     }
640
641     debug_level = (unsigned) ((v_opt > 0) ? v_opt : (v_opt == 0));
642     set_trace_level(debug_level);
643
644     if (_nc_tracing) {
645         save_check_termtype = _nc_check_termtype2;
646         _nc_check_termtype2 = check_termtype;
647     }
648 #if !HAVE_BIG_CORE
649     /*
650      * Aaargh! immedhook seriously hoses us!
651      *
652      * One problem with immedhook is it means we can't do -e.  Problem
653      * is that we can't guarantee that for each terminal listed, all the
654      * terminals it depends on will have been kept in core for reference
655      * resolution -- in fact it's certain the primitive types at the end
656      * of reference chains *won't* be in core unless they were explicitly
657      * in the select list themselves.
658      */
659     if (namelst && (!infodump && !capdump)) {
660         (void) fprintf(stderr,
661                        "Sorry, -e can't be used without -I or -C\n");
662         cleanup(namelst);
663         ExitProgram(EXIT_FAILURE);
664     }
665 #endif /* HAVE_BIG_CORE */
666
667     if (optind < argc) {
668         source_file = argv[optind++];
669         if (optind < argc) {
670             fprintf(stderr,
671                     "%s: Too many file names.  Usage:\n\t%s %s",
672                     _nc_progname,
673                     _nc_progname,
674                     usage_string);
675             ExitProgram(EXIT_FAILURE);
676         }
677     } else {
678         if (infodump == TRUE) {
679             /* captoinfo's no-argument case */
680             source_file = "/etc/termcap";
681             if ((termcap = getenv("TERMCAP")) != 0
682                 && (namelst = make_namelist(getenv("TERM"))) != 0) {
683                 if (access(termcap, F_OK) == 0) {
684                     /* file exists */
685                     source_file = termcap;
686                 } else if ((tmp_fp = open_tempfile(strcpy(my_tmpname,
687                                                           "/tmp/XXXXXX")))
688                            != 0) {
689                     source_file = my_tmpname;
690                     fprintf(tmp_fp, "%s\n", termcap);
691                     fclose(tmp_fp);
692                     tmp_fp = open_input(source_file);
693                     to_remove = source_file;
694                 } else {
695                     failed("tmpnam");
696                 }
697             }
698         } else {
699             /* tic */
700             fprintf(stderr,
701                     "%s: File name needed.  Usage:\n\t%s %s",
702                     _nc_progname,
703                     _nc_progname,
704                     usage_string);
705             cleanup(namelst);
706             ExitProgram(EXIT_FAILURE);
707         }
708     }
709
710     if (tmp_fp == 0)
711         tmp_fp = open_input(source_file);
712
713     if (infodump)
714         dump_init(tversion,
715                   smart_defaults
716                   ? outform
717                   : F_LITERAL,
718                   sortmode, width, height, debug_level, formatted);
719     else if (capdump)
720         dump_init(tversion,
721                   outform,
722                   sortmode, width, height, debug_level, FALSE);
723
724     /* parse entries out of the source file */
725     _nc_set_source(source_file);
726 #if !HAVE_BIG_CORE
727     if (!(check_only || infodump || capdump))
728         _nc_set_writedir(outdir);
729 #endif /* HAVE_BIG_CORE */
730     _nc_read_entry_source(tmp_fp, (char *) NULL,
731                           !smart_defaults || literal, FALSE,
732                           ((check_only || infodump || capdump)
733                            ? NULLHOOK
734                            : immedhook));
735
736     /* do use resolution */
737     if (check_only || (!infodump && !capdump) || forceresolve) {
738         if (!_nc_resolve_uses2(TRUE, literal) && !check_only) {
739             cleanup(namelst);
740             ExitProgram(EXIT_FAILURE);
741         }
742     }
743
744     /* length check */
745     if (check_only && (capdump || infodump)) {
746         for_entry_list(qp) {
747             if (matches(namelst, qp->tterm.term_names)) {
748                 int len = fmt_entry(&qp->tterm, NULL, FALSE, TRUE, infodump, numbers);
749
750                 if (len > (infodump ? MAX_TERMINFO_LENGTH : MAX_TERMCAP_LENGTH))
751                     (void) fprintf(stderr,
752                                    "warning: resolved %s entry is %d bytes long\n",
753                                    _nc_first_name(qp->tterm.term_names),
754                                    len);
755             }
756         }
757     }
758
759     /* write or dump all entries */
760     if (!check_only) {
761         if (!infodump && !capdump) {
762             _nc_set_writedir(outdir);
763             for_entry_list(qp) {
764                 if (matches(namelst, qp->tterm.term_names))
765                     write_it(qp);
766             }
767         } else {
768             /* this is in case infotocap() generates warnings */
769             _nc_curr_col = _nc_curr_line = -1;
770
771             for_entry_list(qp) {
772                 if (matches(namelst, qp->tterm.term_names)) {
773                     long j = qp->cend - qp->cstart;
774                     int len = 0;
775
776                     /* this is in case infotocap() generates warnings */
777                     _nc_set_type(_nc_first_name(qp->tterm.term_names));
778
779                     (void) fseek(tmp_fp, qp->cstart, SEEK_SET);
780                     while (j-- > 0) {
781                         if (infodump)
782                             (void) putchar(fgetc(tmp_fp));
783                         else
784                             put_translate(fgetc(tmp_fp));
785                     }
786
787                     repair_acsc(&qp->tterm);
788                     dump_entry(&qp->tterm, suppress_untranslatable,
789                                limited, numbers, NULL);
790                     for (j = 0; j < (long) qp->nuses; j++)
791                         dump_uses(qp->uses[j].name, !capdump);
792                     len = show_entry();
793                     if (debug_level != 0 && !limited)
794                         printf("# length=%d\n", len);
795                 }
796             }
797             if (!namelst && _nc_tail) {
798                 int c, oldc = '\0';
799                 bool in_comment = FALSE;
800                 bool trailing_comment = FALSE;
801
802                 (void) fseek(tmp_fp, _nc_tail->cend, SEEK_SET);
803                 while ((c = fgetc(tmp_fp)) != EOF) {
804                     if (oldc == '\n') {
805                         if (c == '#') {
806                             trailing_comment = TRUE;
807                             in_comment = TRUE;
808                         } else {
809                             in_comment = FALSE;
810                         }
811                     }
812                     if (trailing_comment
813                         && (in_comment || (oldc == '\n' && c == '\n')))
814                         putchar(c);
815                     oldc = c;
816                 }
817             }
818         }
819     }
820
821     /* Show the directory into which entries were written, and the total
822      * number of entries
823      */
824     if (showsummary
825         && (!(check_only || infodump || capdump))) {
826         int total = _nc_tic_written();
827         if (total != 0)
828             fprintf(log_fp, "%d entries written to %s\n",
829                     total,
830                     _nc_tic_dir((char *) 0));
831         else
832             fprintf(log_fp, "No entries written\n");
833     }
834     cleanup(namelst);
835     ExitProgram(EXIT_SUCCESS);
836 }
837
838 /*
839  * This bit of legerdemain turns all the terminfo variable names into
840  * references to locations in the arrays Booleans, Numbers, and Strings ---
841  * precisely what's needed (see comp_parse.c).
842  */
843 #undef CUR
844 #define CUR tp->
845
846 /*
847  * Check if the alternate character-set capabilities are consistent.
848  */
849 static void
850 check_acs(TERMTYPE *tp)
851 {
852     if (VALID_STRING(acs_chars)) {
853         const char *boxes = "lmkjtuvwqxn";
854         char mapped[256];
855         char missing[256];
856         const char *p;
857         char *q;
858
859         memset(mapped, 0, sizeof(mapped));
860         for (p = acs_chars; *p != '\0'; p += 2) {
861             if (p[1] == '\0') {
862                 _nc_warning("acsc has odd number of characters");
863                 break;
864             }
865             mapped[UChar(p[0])] = p[1];
866         }
867
868         if (mapped[UChar('I')] && !mapped[UChar('i')]) {
869             _nc_warning("acsc refers to 'I', which is probably an error");
870         }
871
872         for (p = boxes, q = missing; *p != '\0'; ++p) {
873             if (!mapped[UChar(p[0])]) {
874                 *q++ = p[0];
875             }
876         }
877         *q = '\0';
878
879         assert(strlen(missing) <= strlen(boxes));
880         if (*missing != '\0' && strcmp(missing, boxes)) {
881             _nc_warning("acsc is missing some line-drawing mapping: %s", missing);
882         }
883     }
884 }
885
886 /*
887  * Check if the color capabilities are consistent
888  */
889 static void
890 check_colors(TERMTYPE *tp)
891 {
892     if ((max_colors > 0) != (max_pairs > 0)
893         || ((max_colors > max_pairs) && (initialize_pair == 0)))
894         _nc_warning("inconsistent values for max_colors (%d) and max_pairs (%d)",
895                     max_colors, max_pairs);
896
897     PAIRED(set_foreground, set_background);
898     PAIRED(set_a_foreground, set_a_background);
899     PAIRED(set_color_pair, initialize_pair);
900
901     if (VALID_STRING(set_foreground)
902         && VALID_STRING(set_a_foreground)
903         && !_nc_capcmp(set_foreground, set_a_foreground))
904         _nc_warning("expected setf/setaf to be different");
905
906     if (VALID_STRING(set_background)
907         && VALID_STRING(set_a_background)
908         && !_nc_capcmp(set_background, set_a_background))
909         _nc_warning("expected setb/setab to be different");
910
911     /* see: has_colors() */
912     if (VALID_NUMERIC(max_colors) && VALID_NUMERIC(max_pairs)
913         && (((set_foreground != NULL)
914              && (set_background != NULL))
915             || ((set_a_foreground != NULL)
916                 && (set_a_background != NULL))
917             || set_color_pair)) {
918         if (!VALID_STRING(orig_pair) && !VALID_STRING(orig_colors))
919             _nc_warning("expected either op/oc string for resetting colors");
920     }
921 }
922
923 static char
924 keypad_final(const char *string)
925 {
926     char result = '\0';
927
928     if (VALID_STRING(string)
929         && *string++ == '\033'
930         && *string++ == 'O'
931         && strlen(string) == 1) {
932         result = *string;
933     }
934
935     return result;
936 }
937
938 static long
939 keypad_index(const char *string)
940 {
941     char *test;
942     const char *list = "PQRSwxymtuvlqrsPpn";    /* app-keypad except "Enter" */
943     int ch;
944     long result = -1;
945
946     if ((ch = keypad_final(string)) != '\0') {
947         test = strchr(list, ch);
948         if (test != 0)
949             result = (long) (test - list);
950     }
951     return result;
952 }
953
954 /*
955  * list[] is down, up, left, right
956  * "left" may be ^H rather than \E[D
957  * "down" may be ^J rather than \E[B
958  * But up/right are generally consistently escape sequences for ANSI terminals.
959  */
960 static void
961 check_ansi_cursor(char *list[4])
962 {
963     int j, k;
964     int want;
965     size_t prefix = 0;
966     size_t suffix;
967     bool skip[4];
968     bool repeated = FALSE;
969
970     for (j = 0; j < 4; ++j) {
971         skip[j] = FALSE;
972         for (k = 0; k < j; ++k) {
973             if (j != k
974                 && !strcmp(list[j], list[k])) {
975                 char *value = _nc_tic_expand(list[k], TRUE, 0);
976                 _nc_warning("repeated cursor control %s\n", value);
977                 repeated = TRUE;
978             }
979         }
980     }
981     if (!repeated) {
982         char *up = list[1];
983
984         if (UChar(up[0]) == '\033') {
985             if (up[1] == '[') {
986                 prefix = 2;
987             } else {
988                 prefix = 1;
989             }
990         } else if (UChar(up[0]) == UChar('\233')) {
991             prefix = 1;
992         }
993         if (prefix) {
994             suffix = prefix;
995             while (up[suffix] && isdigit(UChar(up[suffix])))
996                 ++suffix;
997         }
998         if (prefix && up[suffix] == 'A') {
999             skip[1] = TRUE;
1000             if (!strcmp(list[0], "\n"))
1001                 skip[0] = TRUE;
1002             if (!strcmp(list[2], "\b"))
1003                 skip[2] = TRUE;
1004
1005             for (j = 0; j < 4; ++j) {
1006                 if (skip[j] || strlen(list[j]) == 1)
1007                     continue;
1008                 if (memcmp(list[j], up, prefix)) {
1009                     char *value = _nc_tic_expand(list[j], TRUE, 0);
1010                     _nc_warning("inconsistent prefix for %s\n", value);
1011                     continue;
1012                 }
1013                 if (strlen(list[j]) < suffix) {
1014                     char *value = _nc_tic_expand(list[j], TRUE, 0);
1015                     _nc_warning("inconsistent length for %s, expected %d\n",
1016                                 value, (int) suffix + 1);
1017                     continue;
1018                 }
1019                 want = "BADC"[j];
1020                 if (list[j][suffix] != want) {
1021                     char *value = _nc_tic_expand(list[j], TRUE, 0);
1022                     _nc_warning("inconsistent suffix for %s, expected %c, have %c\n",
1023                                 value, want, list[j][suffix]);
1024                 }
1025             }
1026         }
1027     }
1028 }
1029
1030 #define EXPECTED(name) if (!PRESENT(name)) _nc_warning("expected " #name)
1031
1032 static void
1033 check_cursor(TERMTYPE *tp)
1034 {
1035     int count;
1036     char *list[4];
1037
1038     /* if we have a parameterized form, then the non-parameterized is easy */
1039     ANDMISSING(parm_down_cursor, cursor_down);
1040     ANDMISSING(parm_up_cursor, cursor_up);
1041     ANDMISSING(parm_left_cursor, cursor_left);
1042     ANDMISSING(parm_right_cursor, cursor_right);
1043
1044     /* Given any of a set of cursor movement, the whole set should be present. 
1045      * Technically this is not true (we could use cursor_address to fill in
1046      * unsupported controls), but it is likely.
1047      */
1048     count = 0;
1049     if (PRESENT(parm_down_cursor)) {
1050         list[count++] = parm_down_cursor;
1051     }
1052     if (PRESENT(parm_up_cursor)) {
1053         list[count++] = parm_up_cursor;
1054     }
1055     if (PRESENT(parm_left_cursor)) {
1056         list[count++] = parm_left_cursor;
1057     }
1058     if (PRESENT(parm_right_cursor)) {
1059         list[count++] = parm_right_cursor;
1060     }
1061     if (count == 4) {
1062         check_ansi_cursor(list);
1063     } else if (count != 0) {
1064         EXPECTED(parm_down_cursor);
1065         EXPECTED(parm_up_cursor);
1066         EXPECTED(parm_left_cursor);
1067         EXPECTED(parm_right_cursor);
1068     }
1069
1070     count = 0;
1071     if (PRESENT(cursor_down)) {
1072         list[count++] = cursor_down;
1073     }
1074     if (PRESENT(cursor_up)) {
1075         list[count++] = cursor_up;
1076     }
1077     if (PRESENT(cursor_left)) {
1078         list[count++] = cursor_left;
1079     }
1080     if (PRESENT(cursor_right)) {
1081         list[count++] = cursor_right;
1082     }
1083     if (count == 4) {
1084         check_ansi_cursor(list);
1085     } else if (count != 0) {
1086         count = 0;
1087         if (PRESENT(cursor_down) && strcmp(cursor_down, "\n"))
1088             ++count;
1089         if (PRESENT(cursor_left) && strcmp(cursor_left, "\b"))
1090             ++count;
1091         if (PRESENT(cursor_up) && strlen(cursor_up) > 1)
1092             ++count;
1093         if (PRESENT(cursor_right) && strlen(cursor_right) > 1)
1094             ++count;
1095         if (count) {
1096             EXPECTED(cursor_down);
1097             EXPECTED(cursor_up);
1098             EXPECTED(cursor_left);
1099             EXPECTED(cursor_right);
1100         }
1101     }
1102 }
1103
1104 #define MAX_KP 5
1105 /*
1106  * Do a quick sanity-check for vt100-style keypads to see if the 5-key keypad
1107  * is mapped inconsistently.
1108  */
1109 static void
1110 check_keypad(TERMTYPE *tp)
1111 {
1112     char show[80];
1113
1114     if (VALID_STRING(key_a1) &&
1115         VALID_STRING(key_a3) &&
1116         VALID_STRING(key_b2) &&
1117         VALID_STRING(key_c1) &&
1118         VALID_STRING(key_c3)) {
1119         char final[MAX_KP + 1];
1120         long list[MAX_KP];
1121         int increase = 0;
1122         int j, k, kk;
1123         long last;
1124         long test;
1125
1126         final[0] = keypad_final(key_a1);
1127         final[1] = keypad_final(key_a3);
1128         final[2] = keypad_final(key_b2);
1129         final[3] = keypad_final(key_c1);
1130         final[4] = keypad_final(key_c3);
1131         final[5] = '\0';
1132
1133         /* special case: legacy coding using 1,2,3,0,. on the bottom */
1134         assert(strlen(final) <= MAX_KP);
1135         if (!strcmp(final, "qsrpn"))
1136             return;
1137
1138         list[0] = keypad_index(key_a1);
1139         list[1] = keypad_index(key_a3);
1140         list[2] = keypad_index(key_b2);
1141         list[3] = keypad_index(key_c1);
1142         list[4] = keypad_index(key_c3);
1143
1144         /* check that they're all vt100 keys */
1145         for (j = 0; j < MAX_KP; ++j) {
1146             if (list[j] < 0) {
1147                 return;
1148             }
1149         }
1150
1151         /* check if they're all in increasing order */
1152         for (j = 1; j < MAX_KP; ++j) {
1153             if (list[j] > list[j - 1]) {
1154                 ++increase;
1155             }
1156         }
1157         if (increase != (MAX_KP - 1)) {
1158             show[0] = '\0';
1159
1160             for (j = 0, last = -1; j < MAX_KP; ++j) {
1161                 for (k = 0, kk = -1, test = 100; k < 5; ++k) {
1162                     if (list[k] > last &&
1163                         list[k] < test) {
1164                         test = list[k];
1165                         kk = k;
1166                     }
1167                 }
1168                 last = test;
1169                 assert(strlen(show) < (MAX_KP * 4));
1170                 switch (kk) {
1171                 case 0:
1172                     strcat(show, " ka1");
1173                     break;
1174                 case 1:
1175                     strcat(show, " ka3");
1176                     break;
1177                 case 2:
1178                     strcat(show, " kb2");
1179                     break;
1180                 case 3:
1181                     strcat(show, " kc1");
1182                     break;
1183                 case 4:
1184                     strcat(show, " kc3");
1185                     break;
1186                 }
1187             }
1188
1189             _nc_warning("vt100 keypad order inconsistent: %s", show);
1190         }
1191
1192     } else if (VALID_STRING(key_a1) ||
1193                VALID_STRING(key_a3) ||
1194                VALID_STRING(key_b2) ||
1195                VALID_STRING(key_c1) ||
1196                VALID_STRING(key_c3)) {
1197         show[0] = '\0';
1198         if (keypad_index(key_a1) >= 0)
1199             strcat(show, " ka1");
1200         if (keypad_index(key_a3) >= 0)
1201             strcat(show, " ka3");
1202         if (keypad_index(key_b2) >= 0)
1203             strcat(show, " kb2");
1204         if (keypad_index(key_c1) >= 0)
1205             strcat(show, " kc1");
1206         if (keypad_index(key_c3) >= 0)
1207             strcat(show, " kc3");
1208         if (*show != '\0')
1209             _nc_warning("vt100 keypad map incomplete:%s", show);
1210     }
1211 }
1212
1213 static void
1214 check_printer(TERMTYPE *tp)
1215 {
1216     PAIRED(enter_doublewide_mode, exit_doublewide_mode);
1217     PAIRED(enter_italics_mode, exit_italics_mode);
1218     PAIRED(enter_leftward_mode, exit_leftward_mode);
1219     PAIRED(enter_micro_mode, exit_micro_mode);
1220     PAIRED(enter_shadow_mode, exit_shadow_mode);
1221     PAIRED(enter_subscript_mode, exit_subscript_mode);
1222     PAIRED(enter_superscript_mode, exit_superscript_mode);
1223     PAIRED(enter_upward_mode, exit_upward_mode);
1224
1225     ANDMISSING(start_char_set_def, stop_char_set_def);
1226
1227     /* if we have a parameterized form, then the non-parameterized is easy */
1228     ANDMISSING(set_bottom_margin_parm, set_bottom_margin);
1229     ANDMISSING(set_left_margin_parm, set_left_margin);
1230     ANDMISSING(set_right_margin_parm, set_right_margin);
1231     ANDMISSING(set_top_margin_parm, set_top_margin);
1232
1233     ANDMISSING(parm_down_micro, micro_down);
1234     ANDMISSING(parm_left_micro, micro_left);
1235     ANDMISSING(parm_right_micro, micro_right);
1236     ANDMISSING(parm_up_micro, micro_up);
1237 }
1238
1239 /*
1240  * Returns the expected number of parameters for the given capability.
1241  */
1242 static int
1243 expected_params(const char *name)
1244 {
1245     /* *INDENT-OFF* */
1246     static const struct {
1247         const char *name;
1248         int count;
1249     } table[] = {
1250         { "S0",                 1 },    /* 'screen' extension */
1251         { "birep",              2 },
1252         { "chr",                1 },
1253         { "colornm",            1 },
1254         { "cpi",                1 },
1255         { "csnm",               1 },
1256         { "csr",                2 },
1257         { "cub",                1 },
1258         { "cud",                1 },
1259         { "cuf",                1 },
1260         { "cup",                2 },
1261         { "cuu",                1 },
1262         { "cvr",                1 },
1263         { "cwin",               5 },
1264         { "dch",                1 },
1265         { "defc",               3 },
1266         { "dial",               1 },
1267         { "dispc",              1 },
1268         { "dl",                 1 },
1269         { "ech",                1 },
1270         { "getm",               1 },
1271         { "hpa",                1 },
1272         { "ich",                1 },
1273         { "il",                 1 },
1274         { "indn",               1 },
1275         { "initc",              4 },
1276         { "initp",              7 },
1277         { "lpi",                1 },
1278         { "mc5p",               1 },
1279         { "mrcup",              2 },
1280         { "mvpa",               1 },
1281         { "pfkey",              2 },
1282         { "pfloc",              2 },
1283         { "pfx",                2 },
1284         { "pfxl",               3 },
1285         { "pln",                2 },
1286         { "qdial",              1 },
1287         { "rcsd",               1 },
1288         { "rep",                2 },
1289         { "rin",                1 },
1290         { "sclk",               3 },
1291         { "scp",                1 },
1292         { "scs",                1 },
1293         { "scsd",               2 },
1294         { "setab",              1 },
1295         { "setaf",              1 },
1296         { "setb",               1 },
1297         { "setcolor",           1 },
1298         { "setf",               1 },
1299         { "sgr",                9 },
1300         { "sgr1",               6 },
1301         { "slength",            1 },
1302         { "slines",             1 },
1303         { "smgbp",              1 },    /* 2 if smgtp is not given */
1304         { "smglp",              1 },
1305         { "smglr",              2 },
1306         { "smgrp",              1 },
1307         { "smgtb",              2 },
1308         { "smgtp",              1 },
1309         { "tsl",                1 },
1310         { "u6",                 -1 },
1311         { "vpa",                1 },
1312         { "wind",               4 },
1313         { "wingo",              1 },
1314     };
1315     /* *INDENT-ON* */
1316
1317     unsigned n;
1318     int result = 0;             /* function-keys, etc., use none */
1319
1320     for (n = 0; n < SIZEOF(table); n++) {
1321         if (!strcmp(name, table[n].name)) {
1322             result = table[n].count;
1323             break;
1324         }
1325     }
1326
1327     return result;
1328 }
1329
1330 /*
1331  * Make a quick sanity check for the parameters which are used in the given
1332  * strings.  If there are no "%p" tokens, then there should be no other "%"
1333  * markers.
1334  */
1335 static void
1336 check_params(TERMTYPE *tp, const char *name, char *value)
1337 {
1338     int expected = expected_params(name);
1339     int actual = 0;
1340     int n;
1341     bool params[10];
1342     char *s = value;
1343
1344 #ifdef set_top_margin_parm
1345     if (!strcmp(name, "smgbp")
1346         && set_top_margin_parm == 0)
1347         expected = 2;
1348 #endif
1349
1350     for (n = 0; n < 10; n++)
1351         params[n] = FALSE;
1352
1353     while (*s != 0) {
1354         if (*s == '%') {
1355             if (*++s == '\0') {
1356                 _nc_warning("expected character after %% in %s", name);
1357                 break;
1358             } else if (*s == 'p') {
1359                 if (*++s == '\0' || !isdigit((int) *s)) {
1360                     _nc_warning("expected digit after %%p in %s", name);
1361                     return;
1362                 } else {
1363                     n = (*s - '0');
1364                     if (n > actual)
1365                         actual = n;
1366                     params[n] = TRUE;
1367                 }
1368             }
1369         }
1370         s++;
1371     }
1372
1373     if (params[0]) {
1374         _nc_warning("%s refers to parameter 0 (%%p0), which is not allowed", name);
1375     }
1376     if (value == set_attributes || expected < 0) {
1377         ;
1378     } else if (expected != actual) {
1379         _nc_warning("%s uses %d parameters, expected %d", name,
1380                     actual, expected);
1381         for (n = 1; n < actual; n++) {
1382             if (!params[n])
1383                 _nc_warning("%s omits parameter %d", name, n);
1384         }
1385     }
1386 }
1387
1388 static char *
1389 skip_delay(char *s)
1390 {
1391     while (*s == '/' || isdigit(UChar(*s)))
1392         ++s;
1393     return s;
1394 }
1395
1396 /*
1397  * Skip a delay altogether, e.g., when comparing a simple string to sgr,
1398  * the latter may have a worst-case delay on the end.
1399  */
1400 static char *
1401 ignore_delays(char *s)
1402 {
1403     int delaying = 0;
1404
1405     do {
1406         switch (*s) {
1407         case '$':
1408             if (delaying == 0)
1409                 delaying = 1;
1410             break;
1411         case '<':
1412             if (delaying == 1)
1413                 delaying = 2;
1414             break;
1415         case '\0':
1416             delaying = 0;
1417             break;
1418         default:
1419             if (delaying) {
1420                 s = skip_delay(s);
1421                 if (*s == '>')
1422                     ++s;
1423                 delaying = 0;
1424             }
1425             break;
1426         }
1427         if (delaying)
1428             ++s;
1429     } while (delaying);
1430     return s;
1431 }
1432
1433 /*
1434  * An sgr string may contain several settings other than the one we're
1435  * interested in, essentially sgr0 + rmacs + whatever.  As long as the
1436  * "whatever" is contained in the sgr string, that is close enough for our
1437  * sanity check.
1438  */
1439 static bool
1440 similar_sgr(int num, char *a, char *b)
1441 {
1442     static const char *names[] =
1443     {
1444         "none"
1445         ,"standout"
1446         ,"underline"
1447         ,"reverse"
1448         ,"blink"
1449         ,"dim"
1450         ,"bold"
1451         ,"invis"
1452         ,"protect"
1453         ,"altcharset"
1454     };
1455     char *base_a = a;
1456     char *base_b = b;
1457     int delaying = 0;
1458
1459     while (*b != 0) {
1460         while (*a != *b) {
1461             if (*a == 0) {
1462                 if (b[0] == '$'
1463                     && b[1] == '<') {
1464                     _nc_warning("Did not find delay %s", _nc_visbuf(b));
1465                 } else {
1466                     _nc_warning("checking sgr(%s) %s\n\tcompare to %s\n\tunmatched %s",
1467                                 names[num], _nc_visbuf2(1, base_a),
1468                                 _nc_visbuf2(2, base_b),
1469                                 _nc_visbuf2(3, b));
1470                 }
1471                 return FALSE;
1472             } else if (delaying) {
1473                 a = skip_delay(a);
1474                 b = skip_delay(b);
1475             } else if ((*b == '0' || (*b == ';')) && *a == 'm') {
1476                 b++;
1477             } else {
1478                 a++;
1479             }
1480         }
1481         switch (*a) {
1482         case '$':
1483             if (delaying == 0)
1484                 delaying = 1;
1485             break;
1486         case '<':
1487             if (delaying == 1)
1488                 delaying = 2;
1489             break;
1490         default:
1491             delaying = 0;
1492             break;
1493         }
1494         a++;
1495         b++;
1496     }
1497     /* ignore delays on the end of the string */
1498     a = ignore_delays(a);
1499     return ((num != 0) || (*a == 0));
1500 }
1501
1502 static char *
1503 check_sgr(TERMTYPE *tp, char *zero, int num, char *cap, const char *name)
1504 {
1505     char *test;
1506
1507     _nc_tparm_err = 0;
1508     test = TPARM_9(set_attributes,
1509                    num == 1,
1510                    num == 2,
1511                    num == 3,
1512                    num == 4,
1513                    num == 5,
1514                    num == 6,
1515                    num == 7,
1516                    num == 8,
1517                    num == 9);
1518     if (test != 0) {
1519         if (PRESENT(cap)) {
1520             if (!similar_sgr(num, test, cap)) {
1521                 _nc_warning("%s differs from sgr(%d)\n\t%s=%s\n\tsgr(%d)=%s",
1522                             name, num,
1523                             name, _nc_visbuf2(1, cap),
1524                             num, _nc_visbuf2(2, test));
1525             }
1526         } else if (_nc_capcmp(test, zero)) {
1527             _nc_warning("sgr(%d) present, but not %s", num, name);
1528         }
1529     } else if (PRESENT(cap)) {
1530         _nc_warning("sgr(%d) missing, but %s present", num, name);
1531     }
1532     if (_nc_tparm_err)
1533         _nc_warning("stack error in sgr(%d) string", num);
1534     return test;
1535 }
1536
1537 #define CHECK_SGR(num,name) check_sgr(tp, zero, num, name, #name)
1538
1539 #ifdef TRACE
1540 /*
1541  * If tic is compiled with TRACE, we'll be able to see the output from the
1542  * DEBUG() macro.  But since it doesn't use traceon(), it always goes to
1543  * the standard error.  Use this function to make it simpler to follow the
1544  * resulting debug traces.
1545  */
1546 static void
1547 show_where(unsigned level)
1548 {
1549     if (_nc_tracing >= DEBUG_LEVEL(level)) {
1550         char my_name[256];
1551         _nc_get_type(my_name);
1552         _tracef("\"%s\", line %d, '%s'",
1553                 _nc_get_source(),
1554                 _nc_curr_line, my_name);
1555     }
1556 }
1557
1558 #else
1559 #define show_where(level)       /* nothing */
1560 #endif
1561
1562 /* other sanity-checks (things that we don't want in the normal
1563  * logic that reads a terminfo entry)
1564  */
1565 static void
1566 check_termtype(TERMTYPE *tp, bool literal)
1567 {
1568     bool conflict = FALSE;
1569     unsigned j, k;
1570     char fkeys[STRCOUNT];
1571
1572     /*
1573      * A terminal entry may contain more than one keycode assigned to
1574      * a given string (e.g., KEY_END and KEY_LL).  But curses will only
1575      * return one (the last one assigned).
1576      */
1577     if (!(_nc_syntax == SYN_TERMCAP && capdump)) {
1578         memset(fkeys, 0, sizeof(fkeys));
1579         for (j = 0; _nc_tinfo_fkeys[j].code; j++) {
1580             char *a = tp->Strings[_nc_tinfo_fkeys[j].offset];
1581             bool first = TRUE;
1582             if (!VALID_STRING(a))
1583                 continue;
1584             for (k = j + 1; _nc_tinfo_fkeys[k].code; k++) {
1585                 char *b = tp->Strings[_nc_tinfo_fkeys[k].offset];
1586                 if (!VALID_STRING(b)
1587                     || fkeys[k])
1588                     continue;
1589                 if (!_nc_capcmp(a, b)) {
1590                     fkeys[j] = 1;
1591                     fkeys[k] = 1;
1592                     if (first) {
1593                         if (!conflict) {
1594                             _nc_warning("Conflicting key definitions (using the last)");
1595                             conflict = TRUE;
1596                         }
1597                         fprintf(stderr, "... %s is the same as %s",
1598                                 keyname((int) _nc_tinfo_fkeys[j].code),
1599                                 keyname((int) _nc_tinfo_fkeys[k].code));
1600                         first = FALSE;
1601                     } else {
1602                         fprintf(stderr, ", %s",
1603                                 keyname((int) _nc_tinfo_fkeys[k].code));
1604                     }
1605                 }
1606             }
1607             if (!first)
1608                 fprintf(stderr, "\n");
1609         }
1610     }
1611
1612     for (j = 0; j < NUM_STRINGS(tp); j++) {
1613         char *a = tp->Strings[j];
1614         if (VALID_STRING(a))
1615             check_params(tp, ExtStrname(tp, (int) j, strnames), a);
1616     }
1617
1618     check_acs(tp);
1619     check_colors(tp);
1620     check_cursor(tp);
1621     check_keypad(tp);
1622     check_printer(tp);
1623
1624     /*
1625      * These may be mismatched because the terminal description relies on
1626      * restoring the cursor visibility by resetting it.
1627      */
1628     ANDMISSING(cursor_invisible, cursor_normal);
1629     ANDMISSING(cursor_visible, cursor_normal);
1630
1631     if (PRESENT(cursor_visible) && PRESENT(cursor_normal)
1632         && !_nc_capcmp(cursor_visible, cursor_normal))
1633         _nc_warning("cursor_visible is same as cursor_normal");
1634
1635     /*
1636      * From XSI & O'Reilly, we gather that sc/rc are required if csr is
1637      * given, because the cursor position after the scrolling operation is
1638      * performed is undefined.
1639      */
1640     ANDMISSING(change_scroll_region, save_cursor);
1641     ANDMISSING(change_scroll_region, restore_cursor);
1642
1643     /*
1644      * If we can clear tabs, we should be able to initialize them.
1645      */
1646     ANDMISSING(clear_all_tabs, set_tab);
1647
1648     if (PRESENT(set_attributes)) {
1649         char *zero = 0;
1650
1651         _nc_tparm_err = 0;
1652         if (PRESENT(exit_attribute_mode)) {
1653             zero = strdup(CHECK_SGR(0, exit_attribute_mode));
1654         } else {
1655             zero = strdup(TPARM_9(set_attributes, 0, 0, 0, 0, 0, 0, 0, 0, 0));
1656         }
1657         if (_nc_tparm_err)
1658             _nc_warning("stack error in sgr(0) string");
1659
1660         if (zero != 0) {
1661             CHECK_SGR(1, enter_standout_mode);
1662             CHECK_SGR(2, enter_underline_mode);
1663             CHECK_SGR(3, enter_reverse_mode);
1664             CHECK_SGR(4, enter_blink_mode);
1665             CHECK_SGR(5, enter_dim_mode);
1666             CHECK_SGR(6, enter_bold_mode);
1667             CHECK_SGR(7, enter_secure_mode);
1668             CHECK_SGR(8, enter_protected_mode);
1669             CHECK_SGR(9, enter_alt_charset_mode);
1670             free(zero);
1671         } else {
1672             _nc_warning("sgr(0) did not return a value");
1673         }
1674     } else if (PRESENT(exit_attribute_mode) &&
1675                set_attributes != CANCELLED_STRING) {
1676         if (_nc_syntax == SYN_TERMINFO)
1677             _nc_warning("missing sgr string");
1678     }
1679
1680     if (PRESENT(exit_attribute_mode)) {
1681         char *check_sgr0 = _nc_trim_sgr0(tp);
1682
1683         if (check_sgr0 == 0 || *check_sgr0 == '\0') {
1684             _nc_warning("trimmed sgr0 is empty");
1685         } else {
1686             show_where(2);
1687             if (check_sgr0 != exit_attribute_mode) {
1688                 DEBUG(2,
1689                       ("will trim sgr0\n\toriginal sgr0=%s\n\ttrimmed  sgr0=%s",
1690                        _nc_visbuf2(1, exit_attribute_mode),
1691                        _nc_visbuf2(2, check_sgr0)));
1692                 free(check_sgr0);
1693             } else {
1694                 DEBUG(2,
1695                       ("will not trim sgr0\n\toriginal sgr0=%s",
1696                        _nc_visbuf(exit_attribute_mode)));
1697             }
1698         }
1699     }
1700 #ifdef TRACE
1701     show_where(2);
1702     if (!auto_right_margin) {
1703         DEBUG(2,
1704               ("can write to lower-right directly"));
1705     } else if (PRESENT(enter_am_mode) && PRESENT(exit_am_mode)) {
1706         DEBUG(2,
1707               ("can write to lower-right by suppressing automargin"));
1708     } else if ((PRESENT(enter_insert_mode) && PRESENT(exit_insert_mode))
1709                || PRESENT(insert_character) || PRESENT(parm_ich)) {
1710         DEBUG(2,
1711               ("can write to lower-right by using inserts"));
1712     } else {
1713         DEBUG(2,
1714               ("cannot write to lower-right"));
1715     }
1716 #endif
1717
1718     /*
1719      * Some standard applications (e.g., vi) and some non-curses
1720      * applications (e.g., jove) get confused if we have both ich1 and
1721      * smir/rmir.  Let's be nice and warn about that, too, even though
1722      * ncurses handles it.
1723      */
1724     if ((PRESENT(enter_insert_mode) || PRESENT(exit_insert_mode))
1725         && PRESENT(parm_ich)) {
1726         _nc_warning("non-curses applications may be confused by ich1 with smir/rmir");
1727     }
1728
1729     /*
1730      * Finally, do the non-verbose checks
1731      */
1732     if (save_check_termtype != 0)
1733         save_check_termtype(tp, literal);
1734 }