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