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