]> ncurses.scripts.mit.edu Git - ncurses.git/blob - progs/tic.c
ncurses 5.9 - patch 20110730
[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.151 2011/07/30 21:49:32 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     bool formatted = FALSE;     /* reformat complex strings? */
493     bool literal = FALSE;       /* suppress post-processing? */
494     int numbers = 0;            /* format "%'char'" to/from "%{number}" */
495     bool forceresolve = FALSE;  /* force resolution */
496     bool limited = TRUE;
497     char *tversion = (char *) NULL;
498     const char *source_file = "terminfo";
499     char **namelst = 0;
500     char *outdir = (char *) NULL;
501     bool check_only = FALSE;
502     bool suppress_untranslatable = FALSE;
503
504     log_fp = stderr;
505
506     _nc_progname = _nc_rootname(argv[0]);
507
508     if ((infodump = same_program(_nc_progname, PROG_CAPTOINFO)) != FALSE) {
509         outform = F_TERMINFO;
510         sortmode = S_TERMINFO;
511     }
512     if ((capdump = same_program(_nc_progname, PROG_INFOTOCAP)) != FALSE) {
513         outform = F_TERMCAP;
514         sortmode = S_TERMCAP;
515     }
516 #if NCURSES_XNAMES
517     use_extended_names(FALSE);
518 #endif
519     _nc_strict_bsd = 0;
520
521     /*
522      * Processing arguments is a little complicated, since someone made a
523      * design decision to allow the numeric values for -w, -v options to
524      * be optional.
525      */
526     while ((this_opt = getopt(argc, argv,
527                               "0123456789CIKLNR:TUVace:fGgo:rstvwx")) != -1) {
528         if (isdigit(this_opt)) {
529             switch (last_opt) {
530             case 'v':
531                 v_opt = (v_opt * 10) + (this_opt - '0');
532                 break;
533             case 'w':
534                 width = (width * 10) + (this_opt - '0');
535                 break;
536             default:
537                 if (this_opt != '1')
538                     usage();
539                 last_opt = this_opt;
540                 width = 0;
541             }
542             continue;
543         }
544         switch (this_opt) {
545         case 'K':
546             _nc_strict_bsd = 1;
547             /* FALLTHRU */
548         case 'C':
549             capdump = TRUE;
550             outform = F_TERMCAP;
551             sortmode = S_TERMCAP;
552             break;
553         case 'I':
554             infodump = TRUE;
555             outform = F_TERMINFO;
556             sortmode = S_TERMINFO;
557             break;
558         case 'L':
559             infodump = TRUE;
560             outform = F_VARIABLE;
561             sortmode = S_VARIABLE;
562             break;
563         case 'N':
564             smart_defaults = FALSE;
565             literal = TRUE;
566             break;
567         case 'R':
568             tversion = optarg;
569             break;
570         case 'T':
571             limited = FALSE;
572             break;
573         case 'U':
574             literal = TRUE;
575             break;
576         case 'V':
577             puts(curses_version());
578             cleanup(namelst);
579             ExitProgram(EXIT_SUCCESS);
580         case 'c':
581             check_only = TRUE;
582             break;
583         case 'e':
584             namelst = make_namelist(optarg);
585             break;
586         case 'f':
587             formatted = TRUE;
588             break;
589         case 'G':
590             numbers = 1;
591             break;
592         case 'g':
593             numbers = -1;
594             break;
595         case 'o':
596             outdir = optarg;
597             break;
598         case 'r':
599             forceresolve = TRUE;
600             break;
601         case 's':
602             showsummary = TRUE;
603             break;
604         case 'v':
605             v_opt = 0;
606             break;
607         case 'w':
608             width = 0;
609             break;
610 #if NCURSES_XNAMES
611         case 't':
612             _nc_disable_period = FALSE;
613             suppress_untranslatable = TRUE;
614             break;
615         case 'a':
616             _nc_disable_period = TRUE;
617             /* FALLTHRU */
618         case 'x':
619             use_extended_names(TRUE);
620             break;
621 #endif
622         default:
623             usage();
624         }
625         last_opt = this_opt;
626     }
627
628     debug_level = (unsigned) ((v_opt > 0) ? v_opt : (v_opt == 0));
629     set_trace_level(debug_level);
630
631     if (_nc_tracing) {
632         save_check_termtype = _nc_check_termtype2;
633         _nc_check_termtype2 = check_termtype;
634     }
635 #if !HAVE_BIG_CORE
636     /*
637      * Aaargh! immedhook seriously hoses us!
638      *
639      * One problem with immedhook is it means we can't do -e.  Problem
640      * is that we can't guarantee that for each terminal listed, all the
641      * terminals it depends on will have been kept in core for reference
642      * resolution -- in fact it's certain the primitive types at the end
643      * of reference chains *won't* be in core unless they were explicitly
644      * in the select list themselves.
645      */
646     if (namelst && (!infodump && !capdump)) {
647         (void) fprintf(stderr,
648                        "Sorry, -e can't be used without -I or -C\n");
649         cleanup(namelst);
650         ExitProgram(EXIT_FAILURE);
651     }
652 #endif /* HAVE_BIG_CORE */
653
654     if (optind < argc) {
655         source_file = argv[optind++];
656         if (optind < argc) {
657             fprintf(stderr,
658                     "%s: Too many file names.  Usage:\n\t%s %s",
659                     _nc_progname,
660                     _nc_progname,
661                     usage_string);
662             ExitProgram(EXIT_FAILURE);
663         }
664     } else {
665         if (infodump == TRUE) {
666             /* captoinfo's no-argument case */
667             source_file = "/etc/termcap";
668             if ((termcap = getenv("TERMCAP")) != 0
669                 && (namelst = make_namelist(getenv("TERM"))) != 0) {
670                 if (access(termcap, F_OK) == 0) {
671                     /* file exists */
672                     source_file = termcap;
673                 } else if ((tmp_fp = open_tempfile(strcpy(my_tmpname,
674                                                           "/tmp/XXXXXX")))
675                            != 0) {
676                     source_file = my_tmpname;
677                     fprintf(tmp_fp, "%s\n", termcap);
678                     fclose(tmp_fp);
679                     tmp_fp = open_input(source_file);
680                     to_remove = source_file;
681                 } else {
682                     failed("tmpnam");
683                 }
684             }
685         } else {
686             /* tic */
687             fprintf(stderr,
688                     "%s: File name needed.  Usage:\n\t%s %s",
689                     _nc_progname,
690                     _nc_progname,
691                     usage_string);
692             cleanup(namelst);
693             ExitProgram(EXIT_FAILURE);
694         }
695     }
696
697     if (tmp_fp == 0)
698         tmp_fp = open_input(source_file);
699
700     if (infodump)
701         dump_init(tversion,
702                   smart_defaults
703                   ? outform
704                   : F_LITERAL,
705                   sortmode, width, debug_level, formatted);
706     else if (capdump)
707         dump_init(tversion,
708                   outform,
709                   sortmode, width, debug_level, FALSE);
710
711     /* parse entries out of the source file */
712     _nc_set_source(source_file);
713 #if !HAVE_BIG_CORE
714     if (!(check_only || infodump || capdump))
715         _nc_set_writedir(outdir);
716 #endif /* HAVE_BIG_CORE */
717     _nc_read_entry_source(tmp_fp, (char *) NULL,
718                           !smart_defaults || literal, FALSE,
719                           ((check_only || infodump || capdump)
720                            ? NULLHOOK
721                            : immedhook));
722
723     /* do use resolution */
724     if (check_only || (!infodump && !capdump) || forceresolve) {
725         if (!_nc_resolve_uses2(TRUE, literal) && !check_only) {
726             cleanup(namelst);
727             ExitProgram(EXIT_FAILURE);
728         }
729     }
730
731     /* length check */
732     if (check_only && (capdump || infodump)) {
733         for_entry_list(qp) {
734             if (matches(namelst, qp->tterm.term_names)) {
735                 int len = fmt_entry(&qp->tterm, NULL, FALSE, TRUE, infodump, numbers);
736
737                 if (len > (infodump ? MAX_TERMINFO_LENGTH : MAX_TERMCAP_LENGTH))
738                     (void) fprintf(stderr,
739                                    "warning: resolved %s entry is %d bytes long\n",
740                                    _nc_first_name(qp->tterm.term_names),
741                                    len);
742             }
743         }
744     }
745
746     /* write or dump all entries */
747     if (!check_only) {
748         if (!infodump && !capdump) {
749             _nc_set_writedir(outdir);
750             for_entry_list(qp) {
751                 if (matches(namelst, qp->tterm.term_names))
752                     write_it(qp);
753             }
754         } else {
755             /* this is in case infotocap() generates warnings */
756             _nc_curr_col = _nc_curr_line = -1;
757
758             for_entry_list(qp) {
759                 if (matches(namelst, qp->tterm.term_names)) {
760                     long j = qp->cend - qp->cstart;
761                     int len = 0;
762
763                     /* this is in case infotocap() generates warnings */
764                     _nc_set_type(_nc_first_name(qp->tterm.term_names));
765
766                     (void) fseek(tmp_fp, qp->cstart, SEEK_SET);
767                     while (j-- > 0) {
768                         if (infodump)
769                             (void) putchar(fgetc(tmp_fp));
770                         else
771                             put_translate(fgetc(tmp_fp));
772                     }
773
774                     repair_acsc(&qp->tterm);
775                     dump_entry(&qp->tterm, suppress_untranslatable,
776                                limited, numbers, NULL);
777                     for (j = 0; j < (long) qp->nuses; j++)
778                         dump_uses(qp->uses[j].name, !capdump);
779                     len = show_entry();
780                     if (debug_level != 0 && !limited)
781                         printf("# length=%d\n", len);
782                 }
783             }
784             if (!namelst && _nc_tail) {
785                 int c, oldc = '\0';
786                 bool in_comment = FALSE;
787                 bool trailing_comment = FALSE;
788
789                 (void) fseek(tmp_fp, _nc_tail->cend, SEEK_SET);
790                 while ((c = fgetc(tmp_fp)) != EOF) {
791                     if (oldc == '\n') {
792                         if (c == '#') {
793                             trailing_comment = TRUE;
794                             in_comment = TRUE;
795                         } else {
796                             in_comment = FALSE;
797                         }
798                     }
799                     if (trailing_comment
800                         && (in_comment || (oldc == '\n' && c == '\n')))
801                         putchar(c);
802                     oldc = c;
803                 }
804             }
805         }
806     }
807
808     /* Show the directory into which entries were written, and the total
809      * number of entries
810      */
811     if (showsummary
812         && (!(check_only || infodump || capdump))) {
813         int total = _nc_tic_written();
814         if (total != 0)
815             fprintf(log_fp, "%d entries written to %s\n",
816                     total,
817                     _nc_tic_dir((char *) 0));
818         else
819             fprintf(log_fp, "No entries written\n");
820     }
821     cleanup(namelst);
822     ExitProgram(EXIT_SUCCESS);
823 }
824
825 /*
826  * This bit of legerdemain turns all the terminfo variable names into
827  * references to locations in the arrays Booleans, Numbers, and Strings ---
828  * precisely what's needed (see comp_parse.c).
829  */
830 #undef CUR
831 #define CUR tp->
832
833 /*
834  * Check if the alternate character-set capabilities are consistent.
835  */
836 static void
837 check_acs(TERMTYPE *tp)
838 {
839     if (VALID_STRING(acs_chars)) {
840         const char *boxes = "lmkjtuvwqxn";
841         char mapped[256];
842         char missing[256];
843         const char *p;
844         char *q;
845
846         memset(mapped, 0, sizeof(mapped));
847         for (p = acs_chars; *p != '\0'; p += 2) {
848             if (p[1] == '\0') {
849                 _nc_warning("acsc has odd number of characters");
850                 break;
851             }
852             mapped[UChar(p[0])] = p[1];
853         }
854
855         if (mapped[UChar('I')] && !mapped[UChar('i')]) {
856             _nc_warning("acsc refers to 'I', which is probably an error");
857         }
858
859         for (p = boxes, q = missing; *p != '\0'; ++p) {
860             if (!mapped[UChar(p[0])]) {
861                 *q++ = p[0];
862             }
863         }
864         *q = '\0';
865
866         assert(strlen(missing) <= strlen(boxes));
867         if (*missing != '\0' && strcmp(missing, boxes)) {
868             _nc_warning("acsc is missing some line-drawing mapping: %s", missing);
869         }
870     }
871 }
872
873 /*
874  * Check if the color capabilities are consistent
875  */
876 static void
877 check_colors(TERMTYPE *tp)
878 {
879     if ((max_colors > 0) != (max_pairs > 0)
880         || ((max_colors > max_pairs) && (initialize_pair == 0)))
881         _nc_warning("inconsistent values for max_colors (%d) and max_pairs (%d)",
882                     max_colors, max_pairs);
883
884     PAIRED(set_foreground, set_background);
885     PAIRED(set_a_foreground, set_a_background);
886     PAIRED(set_color_pair, initialize_pair);
887
888     if (VALID_STRING(set_foreground)
889         && VALID_STRING(set_a_foreground)
890         && !_nc_capcmp(set_foreground, set_a_foreground))
891         _nc_warning("expected setf/setaf to be different");
892
893     if (VALID_STRING(set_background)
894         && VALID_STRING(set_a_background)
895         && !_nc_capcmp(set_background, set_a_background))
896         _nc_warning("expected setb/setab to be different");
897
898     /* see: has_colors() */
899     if (VALID_NUMERIC(max_colors) && VALID_NUMERIC(max_pairs)
900         && (((set_foreground != NULL)
901              && (set_background != NULL))
902             || ((set_a_foreground != NULL)
903                 && (set_a_background != NULL))
904             || set_color_pair)) {
905         if (!VALID_STRING(orig_pair) && !VALID_STRING(orig_colors))
906             _nc_warning("expected either op/oc string for resetting colors");
907     }
908 }
909
910 static char
911 keypad_final(const char *string)
912 {
913     char result = '\0';
914
915     if (VALID_STRING(string)
916         && *string++ == '\033'
917         && *string++ == 'O'
918         && strlen(string) == 1) {
919         result = *string;
920     }
921
922     return result;
923 }
924
925 static long
926 keypad_index(const char *string)
927 {
928     char *test;
929     const char *list = "PQRSwxymtuvlqrsPpn";    /* app-keypad except "Enter" */
930     int ch;
931     long result = -1;
932
933     if ((ch = keypad_final(string)) != '\0') {
934         test = strchr(list, ch);
935         if (test != 0)
936             result = (long) (test - list);
937     }
938     return result;
939 }
940
941 /*
942  * list[] is down, up, left, right
943  * "left" may be ^H rather than \E[D
944  * "down" may be ^J rather than \E[B
945  * But up/right are generally consistently escape sequences for ANSI terminals.
946  */
947 static void
948 check_ansi_cursor(char *list[4])
949 {
950     int j, k;
951     int want;
952     size_t prefix = 0;
953     size_t suffix;
954     bool skip[4];
955     bool repeated = FALSE;
956
957     for (j = 0; j < 4; ++j) {
958         skip[j] = FALSE;
959         for (k = 0; k < j; ++k) {
960             if (j != k
961                 && !strcmp(list[j], list[k])) {
962                 char *value = _nc_tic_expand(list[k], TRUE, 0);
963                 _nc_warning("repeated cursor control %s\n", value);
964                 repeated = TRUE;
965             }
966         }
967     }
968     if (!repeated) {
969         char *up = list[1];
970
971         if (UChar(up[0]) == '\033') {
972             if (up[1] == '[') {
973                 prefix = 2;
974             } else {
975                 prefix = 1;
976             }
977         } else if (UChar(up[0]) == UChar('\233')) {
978             prefix = 1;
979         }
980         if (prefix) {
981             suffix = prefix;
982             while (up[suffix] && isdigit(UChar(up[suffix])))
983                 ++suffix;
984         }
985         if (prefix && up[suffix] == 'A') {
986             skip[1] = TRUE;
987             if (!strcmp(list[0], "\n"))
988                 skip[0] = TRUE;
989             if (!strcmp(list[2], "\b"))
990                 skip[2] = TRUE;
991
992             for (j = 0; j < 4; ++j) {
993                 if (skip[j] || strlen(list[j]) == 1)
994                     continue;
995                 if (memcmp(list[j], up, prefix)) {
996                     char *value = _nc_tic_expand(list[j], TRUE, 0);
997                     _nc_warning("inconsistent prefix for %s\n", value);
998                     continue;
999                 }
1000                 if (strlen(list[j]) < suffix) {
1001                     char *value = _nc_tic_expand(list[j], TRUE, 0);
1002                     _nc_warning("inconsistent length for %s, expected %d\n",
1003                                 value, (int) suffix + 1);
1004                     continue;
1005                 }
1006                 want = "BADC"[j];
1007                 if (list[j][suffix] != want) {
1008                     char *value = _nc_tic_expand(list[j], TRUE, 0);
1009                     _nc_warning("inconsistent suffix for %s, expected %c, have %c\n",
1010                                 value, want, list[j][suffix]);
1011                 }
1012             }
1013         }
1014     }
1015 }
1016
1017 #define EXPECTED(name) if (!PRESENT(name)) _nc_warning("expected " #name)
1018
1019 static void
1020 check_cursor(TERMTYPE *tp)
1021 {
1022     int count;
1023     char *list[4];
1024
1025     /* if we have a parameterized form, then the non-parameterized is easy */
1026     ANDMISSING(parm_down_cursor, cursor_down);
1027     ANDMISSING(parm_up_cursor, cursor_up);
1028     ANDMISSING(parm_left_cursor, cursor_left);
1029     ANDMISSING(parm_right_cursor, cursor_right);
1030
1031     /* Given any of a set of cursor movement, the whole set should be present. 
1032      * Technically this is not true (we could use cursor_address to fill in
1033      * unsupported controls), but it is likely.
1034      */
1035     count = 0;
1036     if (PRESENT(parm_down_cursor)) {
1037         list[count++] = parm_down_cursor;
1038     }
1039     if (PRESENT(parm_up_cursor)) {
1040         list[count++] = parm_up_cursor;
1041     }
1042     if (PRESENT(parm_left_cursor)) {
1043         list[count++] = parm_left_cursor;
1044     }
1045     if (PRESENT(parm_right_cursor)) {
1046         list[count++] = parm_right_cursor;
1047     }
1048     if (count == 4) {
1049         check_ansi_cursor(list);
1050     } else if (count != 0) {
1051         EXPECTED(parm_down_cursor);
1052         EXPECTED(parm_up_cursor);
1053         EXPECTED(parm_left_cursor);
1054         EXPECTED(parm_right_cursor);
1055     }
1056
1057     count = 0;
1058     if (PRESENT(cursor_down)) {
1059         list[count++] = cursor_down;
1060     }
1061     if (PRESENT(cursor_up)) {
1062         list[count++] = cursor_up;
1063     }
1064     if (PRESENT(cursor_left)) {
1065         list[count++] = cursor_left;
1066     }
1067     if (PRESENT(cursor_right)) {
1068         list[count++] = cursor_right;
1069     }
1070     if (count == 4) {
1071         check_ansi_cursor(list);
1072     } else if (count != 0) {
1073         count = 0;
1074         if (PRESENT(cursor_down) && strcmp(cursor_down, "\n"))
1075             ++count;
1076         if (PRESENT(cursor_left) && strcmp(cursor_left, "\b"))
1077             ++count;
1078         if (PRESENT(cursor_up) && strlen(cursor_up) > 1)
1079             ++count;
1080         if (PRESENT(cursor_right) && strlen(cursor_right) > 1)
1081             ++count;
1082         if (count) {
1083             EXPECTED(cursor_down);
1084             EXPECTED(cursor_up);
1085             EXPECTED(cursor_left);
1086             EXPECTED(cursor_right);
1087         }
1088     }
1089 }
1090
1091 #define MAX_KP 5
1092 /*
1093  * Do a quick sanity-check for vt100-style keypads to see if the 5-key keypad
1094  * is mapped inconsistently.
1095  */
1096 static void
1097 check_keypad(TERMTYPE *tp)
1098 {
1099     char show[80];
1100
1101     if (VALID_STRING(key_a1) &&
1102         VALID_STRING(key_a3) &&
1103         VALID_STRING(key_b2) &&
1104         VALID_STRING(key_c1) &&
1105         VALID_STRING(key_c3)) {
1106         char final[MAX_KP + 1];
1107         long list[MAX_KP];
1108         int increase = 0;
1109         int j, k, kk;
1110         long last;
1111         long test;
1112
1113         final[0] = keypad_final(key_a1);
1114         final[1] = keypad_final(key_a3);
1115         final[2] = keypad_final(key_b2);
1116         final[3] = keypad_final(key_c1);
1117         final[4] = keypad_final(key_c3);
1118         final[5] = '\0';
1119
1120         /* special case: legacy coding using 1,2,3,0,. on the bottom */
1121         assert(strlen(final) <= MAX_KP);
1122         if (!strcmp(final, "qsrpn"))
1123             return;
1124
1125         list[0] = keypad_index(key_a1);
1126         list[1] = keypad_index(key_a3);
1127         list[2] = keypad_index(key_b2);
1128         list[3] = keypad_index(key_c1);
1129         list[4] = keypad_index(key_c3);
1130
1131         /* check that they're all vt100 keys */
1132         for (j = 0; j < MAX_KP; ++j) {
1133             if (list[j] < 0) {
1134                 return;
1135             }
1136         }
1137
1138         /* check if they're all in increasing order */
1139         for (j = 1; j < MAX_KP; ++j) {
1140             if (list[j] > list[j - 1]) {
1141                 ++increase;
1142             }
1143         }
1144         if (increase != (MAX_KP - 1)) {
1145             show[0] = '\0';
1146
1147             for (j = 0, last = -1; j < MAX_KP; ++j) {
1148                 for (k = 0, kk = -1, test = 100; k < 5; ++k) {
1149                     if (list[k] > last &&
1150                         list[k] < test) {
1151                         test = list[k];
1152                         kk = k;
1153                     }
1154                 }
1155                 last = test;
1156                 assert(strlen(show) < (MAX_KP * 4));
1157                 switch (kk) {
1158                 case 0:
1159                     strcat(show, " ka1");
1160                     break;
1161                 case 1:
1162                     strcat(show, " ka3");
1163                     break;
1164                 case 2:
1165                     strcat(show, " kb2");
1166                     break;
1167                 case 3:
1168                     strcat(show, " kc1");
1169                     break;
1170                 case 4:
1171                     strcat(show, " kc3");
1172                     break;
1173                 }
1174             }
1175
1176             _nc_warning("vt100 keypad order inconsistent: %s", show);
1177         }
1178
1179     } else if (VALID_STRING(key_a1) ||
1180                VALID_STRING(key_a3) ||
1181                VALID_STRING(key_b2) ||
1182                VALID_STRING(key_c1) ||
1183                VALID_STRING(key_c3)) {
1184         show[0] = '\0';
1185         if (keypad_index(key_a1) >= 0)
1186             strcat(show, " ka1");
1187         if (keypad_index(key_a3) >= 0)
1188             strcat(show, " ka3");
1189         if (keypad_index(key_b2) >= 0)
1190             strcat(show, " kb2");
1191         if (keypad_index(key_c1) >= 0)
1192             strcat(show, " kc1");
1193         if (keypad_index(key_c3) >= 0)
1194             strcat(show, " kc3");
1195         if (*show != '\0')
1196             _nc_warning("vt100 keypad map incomplete:%s", show);
1197     }
1198 }
1199
1200 static void
1201 check_printer(TERMTYPE *tp)
1202 {
1203     PAIRED(enter_doublewide_mode, exit_doublewide_mode);
1204     PAIRED(enter_italics_mode, exit_italics_mode);
1205     PAIRED(enter_leftward_mode, exit_leftward_mode);
1206     PAIRED(enter_micro_mode, exit_micro_mode);
1207     PAIRED(enter_shadow_mode, exit_shadow_mode);
1208     PAIRED(enter_subscript_mode, exit_subscript_mode);
1209     PAIRED(enter_superscript_mode, exit_superscript_mode);
1210     PAIRED(enter_upward_mode, exit_upward_mode);
1211
1212     ANDMISSING(start_char_set_def, stop_char_set_def);
1213
1214     /* if we have a parameterized form, then the non-parameterized is easy */
1215     ANDMISSING(set_bottom_margin_parm, set_bottom_margin);
1216     ANDMISSING(set_left_margin_parm, set_left_margin);
1217     ANDMISSING(set_right_margin_parm, set_right_margin);
1218     ANDMISSING(set_top_margin_parm, set_top_margin);
1219
1220     ANDMISSING(parm_down_micro, micro_down);
1221     ANDMISSING(parm_left_micro, micro_left);
1222     ANDMISSING(parm_right_micro, micro_right);
1223     ANDMISSING(parm_up_micro, micro_up);
1224 }
1225
1226 /*
1227  * Returns the expected number of parameters for the given capability.
1228  */
1229 static int
1230 expected_params(const char *name)
1231 {
1232     /* *INDENT-OFF* */
1233     static const struct {
1234         const char *name;
1235         int count;
1236     } table[] = {
1237         { "S0",                 1 },    /* 'screen' extension */
1238         { "birep",              2 },
1239         { "chr",                1 },
1240         { "colornm",            1 },
1241         { "cpi",                1 },
1242         { "csnm",               1 },
1243         { "csr",                2 },
1244         { "cub",                1 },
1245         { "cud",                1 },
1246         { "cuf",                1 },
1247         { "cup",                2 },
1248         { "cuu",                1 },
1249         { "cvr",                1 },
1250         { "cwin",               5 },
1251         { "dch",                1 },
1252         { "defc",               3 },
1253         { "dial",               1 },
1254         { "dispc",              1 },
1255         { "dl",                 1 },
1256         { "ech",                1 },
1257         { "getm",               1 },
1258         { "hpa",                1 },
1259         { "ich",                1 },
1260         { "il",                 1 },
1261         { "indn",               1 },
1262         { "initc",              4 },
1263         { "initp",              7 },
1264         { "lpi",                1 },
1265         { "mc5p",               1 },
1266         { "mrcup",              2 },
1267         { "mvpa",               1 },
1268         { "pfkey",              2 },
1269         { "pfloc",              2 },
1270         { "pfx",                2 },
1271         { "pfxl",               3 },
1272         { "pln",                2 },
1273         { "qdial",              1 },
1274         { "rcsd",               1 },
1275         { "rep",                2 },
1276         { "rin",                1 },
1277         { "sclk",               3 },
1278         { "scp",                1 },
1279         { "scs",                1 },
1280         { "scsd",               2 },
1281         { "setab",              1 },
1282         { "setaf",              1 },
1283         { "setb",               1 },
1284         { "setcolor",           1 },
1285         { "setf",               1 },
1286         { "sgr",                9 },
1287         { "sgr1",               6 },
1288         { "slength",            1 },
1289         { "slines",             1 },
1290         { "smgbp",              1 },    /* 2 if smgtp is not given */
1291         { "smglp",              1 },
1292         { "smglr",              2 },
1293         { "smgrp",              1 },
1294         { "smgtb",              2 },
1295         { "smgtp",              1 },
1296         { "tsl",                1 },
1297         { "u6",                 -1 },
1298         { "vpa",                1 },
1299         { "wind",               4 },
1300         { "wingo",              1 },
1301     };
1302     /* *INDENT-ON* */
1303
1304     unsigned n;
1305     int result = 0;             /* function-keys, etc., use none */
1306
1307     for (n = 0; n < SIZEOF(table); n++) {
1308         if (!strcmp(name, table[n].name)) {
1309             result = table[n].count;
1310             break;
1311         }
1312     }
1313
1314     return result;
1315 }
1316
1317 /*
1318  * Make a quick sanity check for the parameters which are used in the given
1319  * strings.  If there are no "%p" tokens, then there should be no other "%"
1320  * markers.
1321  */
1322 static void
1323 check_params(TERMTYPE *tp, const char *name, char *value)
1324 {
1325     int expected = expected_params(name);
1326     int actual = 0;
1327     int n;
1328     bool params[10];
1329     char *s = value;
1330
1331 #ifdef set_top_margin_parm
1332     if (!strcmp(name, "smgbp")
1333         && set_top_margin_parm == 0)
1334         expected = 2;
1335 #endif
1336
1337     for (n = 0; n < 10; n++)
1338         params[n] = FALSE;
1339
1340     while (*s != 0) {
1341         if (*s == '%') {
1342             if (*++s == '\0') {
1343                 _nc_warning("expected character after %% in %s", name);
1344                 break;
1345             } else if (*s == 'p') {
1346                 if (*++s == '\0' || !isdigit((int) *s)) {
1347                     _nc_warning("expected digit after %%p in %s", name);
1348                     return;
1349                 } else {
1350                     n = (*s - '0');
1351                     if (n > actual)
1352                         actual = n;
1353                     params[n] = TRUE;
1354                 }
1355             }
1356         }
1357         s++;
1358     }
1359
1360     if (params[0]) {
1361         _nc_warning("%s refers to parameter 0 (%%p0), which is not allowed", name);
1362     }
1363     if (value == set_attributes || expected < 0) {
1364         ;
1365     } else if (expected != actual) {
1366         _nc_warning("%s uses %d parameters, expected %d", name,
1367                     actual, expected);
1368         for (n = 1; n < actual; n++) {
1369             if (!params[n])
1370                 _nc_warning("%s omits parameter %d", name, n);
1371         }
1372     }
1373 }
1374
1375 static char *
1376 skip_delay(char *s)
1377 {
1378     while (*s == '/' || isdigit(UChar(*s)))
1379         ++s;
1380     return s;
1381 }
1382
1383 /*
1384  * Skip a delay altogether, e.g., when comparing a simple string to sgr,
1385  * the latter may have a worst-case delay on the end.
1386  */
1387 static char *
1388 ignore_delays(char *s)
1389 {
1390     int delaying = 0;
1391
1392     do {
1393         switch (*s) {
1394         case '$':
1395             if (delaying == 0)
1396                 delaying = 1;
1397             break;
1398         case '<':
1399             if (delaying == 1)
1400                 delaying = 2;
1401             break;
1402         case '\0':
1403             delaying = 0;
1404             break;
1405         default:
1406             if (delaying) {
1407                 s = skip_delay(s);
1408                 if (*s == '>')
1409                     ++s;
1410                 delaying = 0;
1411             }
1412             break;
1413         }
1414         if (delaying)
1415             ++s;
1416     } while (delaying);
1417     return s;
1418 }
1419
1420 /*
1421  * An sgr string may contain several settings other than the one we're
1422  * interested in, essentially sgr0 + rmacs + whatever.  As long as the
1423  * "whatever" is contained in the sgr string, that is close enough for our
1424  * sanity check.
1425  */
1426 static bool
1427 similar_sgr(int num, char *a, char *b)
1428 {
1429     static const char *names[] =
1430     {
1431         "none"
1432         ,"standout"
1433         ,"underline"
1434         ,"reverse"
1435         ,"blink"
1436         ,"dim"
1437         ,"bold"
1438         ,"invis"
1439         ,"protect"
1440         ,"altcharset"
1441     };
1442     char *base_a = a;
1443     char *base_b = b;
1444     int delaying = 0;
1445
1446     while (*b != 0) {
1447         while (*a != *b) {
1448             if (*a == 0) {
1449                 if (b[0] == '$'
1450                     && b[1] == '<') {
1451                     _nc_warning("Did not find delay %s", _nc_visbuf(b));
1452                 } else {
1453                     _nc_warning("checking sgr(%s) %s\n\tcompare to %s\n\tunmatched %s",
1454                                 names[num], _nc_visbuf2(1, base_a),
1455                                 _nc_visbuf2(2, base_b),
1456                                 _nc_visbuf2(3, b));
1457                 }
1458                 return FALSE;
1459             } else if (delaying) {
1460                 a = skip_delay(a);
1461                 b = skip_delay(b);
1462             } else if ((*b == '0' || (*b == ';')) && *a == 'm') {
1463                 b++;
1464             } else {
1465                 a++;
1466             }
1467         }
1468         switch (*a) {
1469         case '$':
1470             if (delaying == 0)
1471                 delaying = 1;
1472             break;
1473         case '<':
1474             if (delaying == 1)
1475                 delaying = 2;
1476             break;
1477         default:
1478             delaying = 0;
1479             break;
1480         }
1481         a++;
1482         b++;
1483     }
1484     /* ignore delays on the end of the string */
1485     a = ignore_delays(a);
1486     return ((num != 0) || (*a == 0));
1487 }
1488
1489 static char *
1490 check_sgr(TERMTYPE *tp, char *zero, int num, char *cap, const char *name)
1491 {
1492     char *test;
1493
1494     _nc_tparm_err = 0;
1495     test = TPARM_9(set_attributes,
1496                    num == 1,
1497                    num == 2,
1498                    num == 3,
1499                    num == 4,
1500                    num == 5,
1501                    num == 6,
1502                    num == 7,
1503                    num == 8,
1504                    num == 9);
1505     if (test != 0) {
1506         if (PRESENT(cap)) {
1507             if (!similar_sgr(num, test, cap)) {
1508                 _nc_warning("%s differs from sgr(%d)\n\t%s=%s\n\tsgr(%d)=%s",
1509                             name, num,
1510                             name, _nc_visbuf2(1, cap),
1511                             num, _nc_visbuf2(2, test));
1512             }
1513         } else if (_nc_capcmp(test, zero)) {
1514             _nc_warning("sgr(%d) present, but not %s", num, name);
1515         }
1516     } else if (PRESENT(cap)) {
1517         _nc_warning("sgr(%d) missing, but %s present", num, name);
1518     }
1519     if (_nc_tparm_err)
1520         _nc_warning("stack error in sgr(%d) string", num);
1521     return test;
1522 }
1523
1524 #define CHECK_SGR(num,name) check_sgr(tp, zero, num, name, #name)
1525
1526 #ifdef TRACE
1527 /*
1528  * If tic is compiled with TRACE, we'll be able to see the output from the
1529  * DEBUG() macro.  But since it doesn't use traceon(), it always goes to
1530  * the standard error.  Use this function to make it simpler to follow the
1531  * resulting debug traces.
1532  */
1533 static void
1534 show_where(unsigned level)
1535 {
1536     if (_nc_tracing >= DEBUG_LEVEL(level)) {
1537         char my_name[256];
1538         _nc_get_type(my_name);
1539         _tracef("\"%s\", line %d, '%s'",
1540                 _nc_get_source(),
1541                 _nc_curr_line, my_name);
1542     }
1543 }
1544
1545 #else
1546 #define show_where(level)       /* nothing */
1547 #endif
1548
1549 /* other sanity-checks (things that we don't want in the normal
1550  * logic that reads a terminfo entry)
1551  */
1552 static void
1553 check_termtype(TERMTYPE *tp, bool literal)
1554 {
1555     bool conflict = FALSE;
1556     unsigned j, k;
1557     char fkeys[STRCOUNT];
1558
1559     /*
1560      * A terminal entry may contain more than one keycode assigned to
1561      * a given string (e.g., KEY_END and KEY_LL).  But curses will only
1562      * return one (the last one assigned).
1563      */
1564     if (!(_nc_syntax == SYN_TERMCAP && capdump)) {
1565         memset(fkeys, 0, sizeof(fkeys));
1566         for (j = 0; _nc_tinfo_fkeys[j].code; j++) {
1567             char *a = tp->Strings[_nc_tinfo_fkeys[j].offset];
1568             bool first = TRUE;
1569             if (!VALID_STRING(a))
1570                 continue;
1571             for (k = j + 1; _nc_tinfo_fkeys[k].code; k++) {
1572                 char *b = tp->Strings[_nc_tinfo_fkeys[k].offset];
1573                 if (!VALID_STRING(b)
1574                     || fkeys[k])
1575                     continue;
1576                 if (!_nc_capcmp(a, b)) {
1577                     fkeys[j] = 1;
1578                     fkeys[k] = 1;
1579                     if (first) {
1580                         if (!conflict) {
1581                             _nc_warning("Conflicting key definitions (using the last)");
1582                             conflict = TRUE;
1583                         }
1584                         fprintf(stderr, "... %s is the same as %s",
1585                                 keyname((int) _nc_tinfo_fkeys[j].code),
1586                                 keyname((int) _nc_tinfo_fkeys[k].code));
1587                         first = FALSE;
1588                     } else {
1589                         fprintf(stderr, ", %s",
1590                                 keyname((int) _nc_tinfo_fkeys[k].code));
1591                     }
1592                 }
1593             }
1594             if (!first)
1595                 fprintf(stderr, "\n");
1596         }
1597     }
1598
1599     for (j = 0; j < NUM_STRINGS(tp); j++) {
1600         char *a = tp->Strings[j];
1601         if (VALID_STRING(a))
1602             check_params(tp, ExtStrname(tp, (int) j, strnames), a);
1603     }
1604
1605     check_acs(tp);
1606     check_colors(tp);
1607     check_cursor(tp);
1608     check_keypad(tp);
1609     check_printer(tp);
1610
1611     /*
1612      * These may be mismatched because the terminal description relies on
1613      * restoring the cursor visibility by resetting it.
1614      */
1615     ANDMISSING(cursor_invisible, cursor_normal);
1616     ANDMISSING(cursor_visible, cursor_normal);
1617
1618     if (PRESENT(cursor_visible) && PRESENT(cursor_normal)
1619         && !_nc_capcmp(cursor_visible, cursor_normal))
1620         _nc_warning("cursor_visible is same as cursor_normal");
1621
1622     /*
1623      * From XSI & O'Reilly, we gather that sc/rc are required if csr is
1624      * given, because the cursor position after the scrolling operation is
1625      * performed is undefined.
1626      */
1627     ANDMISSING(change_scroll_region, save_cursor);
1628     ANDMISSING(change_scroll_region, restore_cursor);
1629
1630     /*
1631      * If we can clear tabs, we should be able to initialize them.
1632      */
1633     ANDMISSING(clear_all_tabs, set_tab);
1634
1635     if (PRESENT(set_attributes)) {
1636         char *zero = 0;
1637
1638         _nc_tparm_err = 0;
1639         if (PRESENT(exit_attribute_mode)) {
1640             zero = strdup(CHECK_SGR(0, exit_attribute_mode));
1641         } else {
1642             zero = strdup(TPARM_9(set_attributes, 0, 0, 0, 0, 0, 0, 0, 0, 0));
1643         }
1644         if (_nc_tparm_err)
1645             _nc_warning("stack error in sgr(0) string");
1646
1647         if (zero != 0) {
1648             CHECK_SGR(1, enter_standout_mode);
1649             CHECK_SGR(2, enter_underline_mode);
1650             CHECK_SGR(3, enter_reverse_mode);
1651             CHECK_SGR(4, enter_blink_mode);
1652             CHECK_SGR(5, enter_dim_mode);
1653             CHECK_SGR(6, enter_bold_mode);
1654             CHECK_SGR(7, enter_secure_mode);
1655             CHECK_SGR(8, enter_protected_mode);
1656             CHECK_SGR(9, enter_alt_charset_mode);
1657             free(zero);
1658         } else {
1659             _nc_warning("sgr(0) did not return a value");
1660         }
1661     } else if (PRESENT(exit_attribute_mode) &&
1662                set_attributes != CANCELLED_STRING) {
1663         if (_nc_syntax == SYN_TERMINFO)
1664             _nc_warning("missing sgr string");
1665     }
1666
1667     if (PRESENT(exit_attribute_mode)) {
1668         char *check_sgr0 = _nc_trim_sgr0(tp);
1669
1670         if (check_sgr0 == 0 || *check_sgr0 == '\0') {
1671             _nc_warning("trimmed sgr0 is empty");
1672         } else {
1673             show_where(2);
1674             if (check_sgr0 != exit_attribute_mode) {
1675                 DEBUG(2,
1676                       ("will trim sgr0\n\toriginal sgr0=%s\n\ttrimmed  sgr0=%s",
1677                        _nc_visbuf2(1, exit_attribute_mode),
1678                        _nc_visbuf2(2, check_sgr0)));
1679                 free(check_sgr0);
1680             } else {
1681                 DEBUG(2,
1682                       ("will not trim sgr0\n\toriginal sgr0=%s",
1683                        _nc_visbuf(exit_attribute_mode)));
1684             }
1685         }
1686     }
1687 #ifdef TRACE
1688     show_where(2);
1689     if (!auto_right_margin) {
1690         DEBUG(2,
1691               ("can write to lower-right directly"));
1692     } else if (PRESENT(enter_am_mode) && PRESENT(exit_am_mode)) {
1693         DEBUG(2,
1694               ("can write to lower-right by suppressing automargin"));
1695     } else if ((PRESENT(enter_insert_mode) && PRESENT(exit_insert_mode))
1696                || PRESENT(insert_character) || PRESENT(parm_ich)) {
1697         DEBUG(2,
1698               ("can write to lower-right by using inserts"));
1699     } else {
1700         DEBUG(2,
1701               ("cannot write to lower-right"));
1702     }
1703 #endif
1704
1705     /*
1706      * Some standard applications (e.g., vi) and some non-curses
1707      * applications (e.g., jove) get confused if we have both ich1 and
1708      * smir/rmir.  Let's be nice and warn about that, too, even though
1709      * ncurses handles it.
1710      */
1711     if ((PRESENT(enter_insert_mode) || PRESENT(exit_insert_mode))
1712         && PRESENT(parm_ich)) {
1713         _nc_warning("non-curses applications may be confused by ich1 with smir/rmir");
1714     }
1715
1716     /*
1717      * Finally, do the non-verbose checks
1718      */
1719     if (save_check_termtype != 0)
1720         save_check_termtype(tp, literal);
1721 }