]> ncurses.scripts.mit.edu Git - ncurses.git/blob - progs/tic.c
ncurses 6.0 - patch 20170311
[ncurses.git] / progs / tic.c
1 /****************************************************************************
2  * Copyright (c) 1998-2015,2016 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 <tparm_type.h>
47 #include <hashed_db.h>
48 #include <parametrized.h>
49 #include <transform.h>
50
51 MODULE_ID("$Id: tic.c,v 1.230 2016/12/31 12:24:00 tom Exp $")
52
53 #define STDIN_NAME "<stdin>"
54
55 const char *_nc_progname = "tic";
56
57 static FILE *log_fp;
58 static FILE *tmp_fp;
59 static bool capdump = FALSE;    /* running as infotocap? */
60 static bool infodump = FALSE;   /* running as captoinfo? */
61 static bool showsummary = FALSE;
62 static char **namelst = 0;
63 static const char *to_remove;
64
65 static void (*save_check_termtype) (TERMTYPE *, bool);
66 static void check_termtype(TERMTYPE *tt, bool);
67
68 static const char usage_string[] = "\
69 [-e names] \
70 [-o dir] \
71 [-R name] \
72 [-v[n]] \
73 [-V] \
74 [-w[n]] \
75 [-\
76 1\
77 a\
78 C\
79 D\
80 c\
81 f\
82 G\
83 g\
84 I\
85 K\
86 L\
87 N\
88 r\
89 s\
90 T\
91 t\
92 U\
93 x\
94 ] \
95 source-file\n";
96
97 #if NO_LEAKS
98 static void
99 free_namelist(char **src)
100 {
101     if (src != 0) {
102         int n;
103         for (n = 0; src[n] != 0; ++n)
104             free(src[n]);
105         free(src);
106     }
107 }
108 #endif
109
110 static void
111 cleanup(void)
112 {
113     int rc;
114
115 #if NO_LEAKS
116     free_namelist(namelst);
117 #endif
118     if (tmp_fp != 0)
119         fclose(tmp_fp);
120     if (to_remove != 0) {
121 #if HAVE_REMOVE
122         rc = remove(to_remove);
123 #else
124         rc = unlink(to_remove);
125 #endif
126         if (rc != 0)
127             perror(to_remove);
128     }
129 }
130
131 static void
132 failed(const char *msg)
133 {
134     perror(msg);
135     ExitProgram(EXIT_FAILURE);
136 }
137
138 static void
139 usage(void)
140 {
141 #define DATA(s) s "\n"
142     static const char options_string[] =
143     {
144         DATA("Options:")
145         DATA("  -0         format translation output all capabilities on one line")
146         DATA("  -1         format translation output one capability per line")
147 #if NCURSES_XNAMES
148         DATA("  -a         retain commented-out capabilities (sets -x also)")
149 #endif
150         DATA("  -C         translate entries to termcap source form")
151         DATA("  -D         print list of tic's database locations (first must be writable)")
152         DATA("  -c         check only, validate input without compiling or translating")
153         DATA("  -e<names>  translate/compile only entries named by comma-separated list")
154         DATA("  -f         format complex strings for readability")
155         DATA("  -G         format %{number} to %'char'")
156         DATA("  -g         format %'char' to %{number}")
157         DATA("  -I         translate entries to terminfo source form")
158         DATA("  -K         translate entries to termcap source form with BSD syntax")
159         DATA("  -L         translate entries to full terminfo source form")
160         DATA("  -N         disable smart defaults for source translation")
161         DATA("  -o<dir>    set output directory for compiled entry writes")
162         DATA("  -Q[n]      dump compiled description")
163         DATA("  -q    brief listing, removes headers")
164         DATA("  -R<name>   restrict translation to given terminfo/termcap version")
165         DATA("  -r         force resolution of all use entries in source translation")
166         DATA("  -s         print summary statistics")
167         DATA("  -T         remove size-restrictions on compiled description")
168 #if NCURSES_XNAMES
169         DATA("  -t         suppress commented-out capabilities")
170 #endif
171         DATA("  -U         suppress post-processing of entries")
172         DATA("  -V         print version")
173         DATA("  -W         wrap long strings according to -w[n] option")
174         DATA("  -v[n]      set verbosity level")
175         DATA("  -w[n]      set format width for translation output")
176 #if NCURSES_XNAMES
177         DATA("  -x         treat unknown capabilities as user-defined")
178 #endif
179         DATA("")
180         DATA("Parameters:")
181         DATA("  <file>     file to translate or compile")
182     };
183 #undef DATA
184
185     fprintf(stderr, "Usage: %s %s\n", _nc_progname, usage_string);
186     fputs(options_string, stderr);
187     ExitProgram(EXIT_FAILURE);
188 }
189
190 #define L_BRACE '{'
191 #define R_BRACE '}'
192 #define S_QUOTE '\''
193
194 static void
195 write_it(ENTRY * ep)
196 {
197     unsigned n;
198     int ch;
199     char *s, *d, *t;
200     char result[MAX_ENTRY_SIZE];
201
202     /*
203      * Look for strings that contain %{number}, convert them to %'char',
204      * which is shorter and runs a little faster.
205      */
206     for (n = 0; n < STRCOUNT; n++) {
207         s = ep->tterm.Strings[n];
208         if (VALID_STRING(s)
209             && strchr(s, L_BRACE) != 0) {
210             d = result;
211             t = s;
212             while ((ch = *t++) != 0) {
213                 *d++ = (char) ch;
214                 if (ch == '\\') {
215                     *d++ = *t++;
216                 } else if ((ch == '%')
217                            && (*t == L_BRACE)) {
218                     char *v = 0;
219                     long value = strtol(t + 1, &v, 0);
220                     if (v != 0
221                         && *v == R_BRACE
222                         && value > 0
223                         && value != '\\'        /* FIXME */
224                         && value < 127
225                         && isprint((int) value)) {
226                         *d++ = S_QUOTE;
227                         *d++ = (char) value;
228                         *d++ = S_QUOTE;
229                         t = (v + 1);
230                     }
231                 }
232             }
233             *d = 0;
234             if (strlen(result) < strlen(s))
235                 _nc_STRCPY(s, result, strlen(s) + 1);
236         }
237     }
238
239     _nc_set_type(_nc_first_name(ep->tterm.term_names));
240     _nc_curr_line = (int) ep->startline;
241     _nc_write_entry(&ep->tterm);
242 }
243
244 static bool
245 immedhook(ENTRY * ep GCC_UNUSED)
246 /* write out entries with no use capabilities immediately to save storage */
247 {
248 #if !HAVE_BIG_CORE
249     /*
250      * This is strictly a core-economy kluge.  The really clean way to handle
251      * compilation is to slurp the whole file into core and then do all the
252      * name-collision checks and entry writes in one swell foop.  But the
253      * terminfo master file is large enough that some core-poor systems swap
254      * like crazy when you compile it this way...there have been reports of
255      * this process taking *three hours*, rather than the twenty seconds or
256      * less typical on my development box.
257      *
258      * So.  This hook *immediately* writes out the referenced entry if it
259      * has no use capabilities.  The compiler main loop refrains from
260      * adding the entry to the in-core list when this hook fires.  If some
261      * other entry later needs to reference an entry that got written
262      * immediately, that's OK; the resolution code will fetch it off disk
263      * when it can't find it in core.
264      *
265      * Name collisions will still be detected, just not as cleanly.  The
266      * write_entry() code complains before overwriting an entry that
267      * postdates the time of tic's first call to write_entry().  Thus
268      * it will complain about overwriting entries newly made during the
269      * tic run, but not about overwriting ones that predate it.
270      *
271      * The reason this is a hook, and not in line with the rest of the
272      * compiler code, is that the support for termcap fallback cannot assume
273      * it has anywhere to spool out these entries!
274      *
275      * The _nc_set_type() call here requires a compensating one in
276      * _nc_parse_entry().
277      *
278      * If you define HAVE_BIG_CORE, you'll disable this kluge.  This will
279      * make tic a bit faster (because the resolution code won't have to do
280      * disk I/O nearly as often).
281      */
282     if (ep->nuses == 0) {
283         int oldline = _nc_curr_line;
284
285         write_it(ep);
286         _nc_curr_line = oldline;
287         free(ep->tterm.str_table);
288         return (TRUE);
289     }
290 #endif /* HAVE_BIG_CORE */
291     return (FALSE);
292 }
293
294 static void
295 put_translate(int c)
296 /* emit a comment char, translating terminfo names to termcap names */
297 {
298     static bool in_name = FALSE;
299     static size_t have, used;
300     static char *namebuf, *suffix;
301
302     if (in_name) {
303         if (used + 1 >= have) {
304             have += 132;
305             if ((namebuf = typeRealloc(char, have, namebuf)) == 0)
306                   failed("put_translate namebuf");
307             if ((suffix = typeRealloc(char, have, suffix)) == 0)
308                   failed("put_translate suffix");
309         }
310         if (c == '\n' || c == '@') {
311             namebuf[used++] = '\0';
312             (void) putchar('<');
313             (void) fputs(namebuf, stdout);
314             putchar(c);
315             in_name = FALSE;
316         } else if (c != '>') {
317             namebuf[used++] = (char) c;
318         } else {                /* ah! candidate name! */
319             char *up;
320             NCURSES_CONST char *tp;
321
322             namebuf[used++] = '\0';
323             in_name = FALSE;
324
325             suffix[0] = '\0';
326             if ((up = strchr(namebuf, '#')) != 0
327                 || (up = strchr(namebuf, '=')) != 0
328                 || ((up = strchr(namebuf, '@')) != 0 && up[1] == '>')) {
329                 _nc_STRCPY(suffix, up, have);
330                 *up = '\0';
331             }
332
333             if ((tp = nametrans(namebuf)) != 0) {
334                 (void) putchar(':');
335                 (void) fputs(tp, stdout);
336                 (void) fputs(suffix, stdout);
337                 (void) putchar(':');
338             } else {
339                 /* couldn't find a translation, just dump the name */
340                 (void) putchar('<');
341                 (void) fputs(namebuf, stdout);
342                 (void) fputs(suffix, stdout);
343                 (void) putchar('>');
344             }
345         }
346     } else {
347         used = 0;
348         if (c == '<') {
349             in_name = TRUE;
350         } else {
351             putchar(c);
352         }
353     }
354 }
355
356 /* Returns a string, stripped of leading/trailing whitespace */
357 static char *
358 stripped(char *src)
359 {
360     char *dst = 0;
361
362     while (isspace(UChar(*src)))
363         src++;
364
365     if (*src != '\0') {
366         size_t len;
367
368         if ((dst = strdup(src)) == NULL) {
369             failed("strdup");
370         } else {
371             len = strlen(dst);
372             while (--len != 0 && isspace(UChar(dst[len])))
373                 dst[len] = '\0';
374         }
375     }
376     return dst;
377 }
378
379 static FILE *
380 open_tempfile(char *filename)
381 {
382     FILE *result = 0;
383
384     _nc_STRCPY(filename, "/tmp/XXXXXX", PATH_MAX);
385 #if HAVE_MKSTEMP
386     {
387         int oldmask = (int) umask(077);
388         int fd = mkstemp(filename);
389         if (fd >= 0)
390             result = fdopen(fd, "w");
391         umask((mode_t) oldmask);
392     }
393 #else
394     if (tmpnam(filename) != 0)
395         result = fopen(filename, "w");
396 #endif
397     return result;
398 }
399
400 static FILE *
401 copy_input(FILE *source, const char *filename, char *alt_file)
402 {
403     char my_altfile[PATH_MAX];
404     FILE *result = 0;
405     FILE *target = 0;
406     int ch;
407
408     if (alt_file == 0)
409         alt_file = my_altfile;
410
411     if (source == 0) {
412         failed("copy_input (source)");
413     } else if ((target = open_tempfile(alt_file)) == 0) {
414         failed("copy_input (target)");
415     } else {
416         clearerr(source);
417         for (;;) {
418             ch = fgetc(source);
419             if (feof(source)) {
420                 break;
421             } else if (ferror(source)) {
422                 failed(filename);
423             } else if (ch == 0) {
424                 /* don't loop in case someone wants to convert /dev/zero */
425                 fprintf(stderr, "%s: %s is not a text-file\n", _nc_progname, filename);
426                 ExitProgram(EXIT_FAILURE);
427             }
428             fputc(ch, target);
429         }
430         fclose(source);
431         /*
432          * rewind() does not force the target file's data to disk (not does
433          * fflush()...).  So open a second stream on the data and then close
434          * the one that we were writing on before starting to read from the
435          * second stream.
436          */
437         result = fopen(alt_file, "r+");
438         fclose(target);
439         to_remove = strdup(alt_file);
440     }
441     return result;
442 }
443
444 static FILE *
445 open_input(const char *filename, char *alt_file)
446 {
447     FILE *fp;
448     struct stat sb;
449     int mode;
450
451     if (!strcmp(filename, "-")) {
452         fp = copy_input(stdin, STDIN_NAME, alt_file);
453     } else if (stat(filename, &sb) < 0) {
454         fprintf(stderr, "%s: %s %s\n", _nc_progname, filename, strerror(errno));
455         ExitProgram(EXIT_FAILURE);
456     } else if ((mode = (sb.st_mode & S_IFMT)) == S_IFDIR
457                || (mode != S_IFREG && mode != S_IFCHR && mode != S_IFIFO)) {
458         fprintf(stderr, "%s: %s is not a file\n", _nc_progname, filename);
459         ExitProgram(EXIT_FAILURE);
460     } else {
461         fp = fopen(filename, "r");
462
463         if (fp == 0) {
464             fprintf(stderr, "%s: Can't open %s\n", _nc_progname, filename);
465             ExitProgram(EXIT_FAILURE);
466         }
467         if (mode != S_IFREG) {
468             if (alt_file != 0) {
469                 FILE *fp2 = copy_input(fp, filename, alt_file);
470                 fp = fp2;
471             } else {
472                 fprintf(stderr, "%s: %s is not a file\n", _nc_progname, filename);
473                 ExitProgram(EXIT_FAILURE);
474             }
475         }
476     }
477     return fp;
478 }
479
480 /* Parse the "-e" option-value into a list of names */
481 static char **
482 make_namelist(char *src)
483 {
484     char **dst = 0;
485
486     char *s, *base;
487     unsigned pass, n, nn;
488     char buffer[BUFSIZ];
489
490     if (src == 0) {
491         /* EMPTY */ ;
492     } else if (strchr(src, '/') != 0) {         /* a filename */
493         FILE *fp = open_input(src, (char *) 0);
494
495         for (pass = 1; pass <= 2; pass++) {
496             nn = 0;
497             while (fgets(buffer, sizeof(buffer), fp) != 0) {
498                 if ((s = stripped(buffer)) != 0) {
499                     if (dst != 0)
500                         dst[nn] = s;
501                     else
502                         free(s);
503                     nn++;
504                 }
505             }
506             if (pass == 1) {
507                 if ((dst = typeCalloc(char *, nn + 1)) == 0)
508                       failed("make_namelist");
509                 rewind(fp);
510             }
511         }
512         fclose(fp);
513     } else {                    /* literal list of names */
514         for (pass = 1; pass <= 2; pass++) {
515             for (n = nn = 0, base = src;; n++) {
516                 int mark = src[n];
517                 if (mark == ',' || mark == '\0') {
518                     if (pass == 1) {
519                         nn++;
520                     } else {
521                         src[n] = '\0';
522                         if ((s = stripped(base)) != 0)
523                             dst[nn++] = s;
524                         base = &src[n + 1];
525                     }
526                 }
527                 if (mark == '\0')
528                     break;
529             }
530             if (pass == 1) {
531                 if ((dst = typeCalloc(char *, nn + 1)) == 0)
532                       failed("make_namelist");
533             }
534         }
535     }
536     if (showsummary && (dst != 0)) {
537         fprintf(log_fp, "Entries that will be compiled:\n");
538         for (n = 0; dst[n] != 0; n++)
539             fprintf(log_fp, "%u:%s\n", n + 1, dst[n]);
540     }
541     return dst;
542 }
543
544 static bool
545 matches(char **needle, const char *haystack)
546 /* does entry in needle list match |-separated field in haystack? */
547 {
548     bool code = FALSE;
549     size_t n;
550
551     if (needle != 0) {
552         for (n = 0; needle[n] != 0; n++) {
553             if (_nc_name_match(haystack, needle[n], "|")) {
554                 code = TRUE;
555                 break;
556             }
557         }
558     } else
559         code = TRUE;
560     return (code);
561 }
562
563 static char *
564 valid_db_path(const char *nominal)
565 {
566     struct stat sb;
567 #if USE_HASHED_DB
568     char suffix[] = DBM_SUFFIX;
569     size_t need = strlen(nominal) + sizeof(suffix);
570     char *result = malloc(need);
571
572     if (result == 0)
573         failed("valid_db_path");
574     _nc_STRCPY(result, nominal, need);
575     if (strcmp(result + need - sizeof(suffix), suffix)) {
576         _nc_STRCAT(result, suffix, need);
577     }
578 #else
579     char *result = strdup(nominal);
580 #endif
581
582     DEBUG(1, ("** stat(%s)", result));
583     if (stat(result, &sb) >= 0) {
584 #if USE_HASHED_DB
585         if (!S_ISREG(sb.st_mode)
586             || access(result, R_OK | W_OK) != 0) {
587             DEBUG(1, ("...not a writable file"));
588             free(result);
589             result = 0;
590         }
591 #else
592         if (!S_ISDIR(sb.st_mode)
593             || access(result, R_OK | W_OK | X_OK) != 0) {
594             DEBUG(1, ("...not a writable directory"));
595             free(result);
596             result = 0;
597         }
598 #endif
599     } else {
600         /* check if parent is directory and is writable */
601         unsigned leaf = _nc_pathlast(result);
602
603         DEBUG(1, ("...not found"));
604         if (leaf) {
605             char save = result[leaf];
606             result[leaf] = 0;
607             if (stat(result, &sb) >= 0
608                 && S_ISDIR(sb.st_mode)
609                 && access(result, R_OK | W_OK | X_OK) == 0) {
610                 result[leaf] = save;
611             } else {
612                 DEBUG(1, ("...parent directory %s is not writable", result));
613                 free(result);
614                 result = 0;
615             }
616         } else {
617             DEBUG(1, ("... no parent directory"));
618             free(result);
619             result = 0;
620         }
621     }
622     return result;
623 }
624
625 /*
626  * Show the databases to which tic could write.  The location to which it
627  * writes is always the first one.  If none are writable, print an error
628  * message.
629  */
630 static void
631 show_databases(const char *outdir)
632 {
633     bool specific = (outdir != 0) || getenv("TERMINFO") != 0;
634     char *result;
635     const char *tried = 0;
636
637     if (outdir == 0) {
638         outdir = _nc_tic_dir(0);
639     }
640     if ((result = valid_db_path(outdir)) != 0) {
641         printf("%s\n", result);
642         free(result);
643     } else {
644         tried = outdir;
645     }
646
647     if ((outdir = _nc_home_terminfo())) {
648         if ((result = valid_db_path(outdir)) != 0) {
649             printf("%s\n", result);
650             free(result);
651         } else if (!specific) {
652             tried = outdir;
653         }
654     }
655
656     /*
657      * If we can write in neither location, give an error message.
658      */
659     if (tried) {
660         fflush(stdout);
661         fprintf(stderr, "%s: %s (no permission)\n", _nc_progname, tried);
662         ExitProgram(EXIT_FAILURE);
663     }
664 }
665
666 static void
667 add_digit(int *target, int source)
668 {
669     *target = (*target * 10) + (source - '0');
670 }
671
672 #define VtoTrace(opt) (unsigned) ((opt > 0) ? opt : (opt == 0))
673
674 int
675 main(int argc, char *argv[])
676 {
677     char my_tmpname[PATH_MAX];
678     char my_altfile[PATH_MAX];
679     int v_opt = -1;
680     unsigned debug_level;
681     int smart_defaults = TRUE;
682     char *termcap;
683     ENTRY *qp;
684
685     int this_opt, last_opt = '?';
686
687     int outform = F_TERMINFO;   /* output format */
688     int sortmode = S_TERMINFO;  /* sort_mode */
689
690     int width = 60;
691     int height = 65535;
692     bool formatted = FALSE;     /* reformat complex strings? */
693     bool literal = FALSE;       /* suppress post-processing? */
694     int numbers = 0;            /* format "%'char'" to/from "%{number}" */
695     bool forceresolve = FALSE;  /* force resolution */
696     bool limited = TRUE;
697     char *tversion = (char *) NULL;
698     const char *source_file = "terminfo";
699     char *outdir = (char *) NULL;
700     bool check_only = FALSE;
701     bool suppress_untranslatable = FALSE;
702     int quickdump = 0;
703     bool quiet = FALSE;
704     bool wrap_strings = FALSE;
705
706     log_fp = stderr;
707
708     _nc_progname = _nc_rootname(argv[0]);
709     atexit(cleanup);
710
711     if ((infodump = same_program(_nc_progname, PROG_CAPTOINFO)) != FALSE) {
712         outform = F_TERMINFO;
713         sortmode = S_TERMINFO;
714     }
715     if ((capdump = same_program(_nc_progname, PROG_INFOTOCAP)) != FALSE) {
716         outform = F_TERMCAP;
717         sortmode = S_TERMCAP;
718     }
719 #if NCURSES_XNAMES
720     use_extended_names(FALSE);
721 #endif
722     _nc_strict_bsd = 0;
723
724     /*
725      * Processing arguments is a little complicated, since someone made a
726      * design decision to allow the numeric values for -w, -v options to
727      * be optional.
728      */
729     while ((this_opt = getopt(argc, argv,
730                               "0123456789CDIKLNQR:TUVWace:fGgo:qrstvwx")) != -1) {
731         if (isdigit(this_opt)) {
732             switch (last_opt) {
733             case 'Q':
734                 add_digit(&quickdump, this_opt);
735                 break;
736             case 'v':
737                 add_digit(&v_opt, this_opt);
738                 break;
739             case 'w':
740                 add_digit(&width, this_opt);
741                 break;
742             default:
743                 switch (this_opt) {
744                 case '0':
745                     last_opt = this_opt;
746                     width = 65535;
747                     height = 1;
748                     break;
749                 case '1':
750                     last_opt = this_opt;
751                     width = 0;
752                     break;
753                 default:
754                     usage();
755                 }
756             }
757             continue;
758         }
759         switch (this_opt) {
760         case 'K':
761             _nc_strict_bsd = 1;
762             /* the initial version of -K in 20110730 fell-thru here, but the
763              * same flag is useful when reading sources -TD
764              */
765             break;
766         case 'C':
767             capdump = TRUE;
768             outform = F_TERMCAP;
769             sortmode = S_TERMCAP;
770             break;
771         case 'D':
772             debug_level = VtoTrace(v_opt);
773             set_trace_level(debug_level);
774             show_databases(outdir);
775             ExitProgram(EXIT_SUCCESS);
776             break;
777         case 'I':
778             infodump = TRUE;
779             outform = F_TERMINFO;
780             sortmode = S_TERMINFO;
781             break;
782         case 'L':
783             infodump = TRUE;
784             outform = F_VARIABLE;
785             sortmode = S_VARIABLE;
786             break;
787         case 'N':
788             smart_defaults = FALSE;
789             literal = TRUE;
790             break;
791         case 'Q':
792             quickdump = 0;
793             break;
794         case 'R':
795             tversion = optarg;
796             break;
797         case 'T':
798             limited = FALSE;
799             break;
800         case 'U':
801             literal = TRUE;
802             break;
803         case 'V':
804             puts(curses_version());
805             ExitProgram(EXIT_SUCCESS);
806         case 'W':
807             wrap_strings = TRUE;
808             break;
809         case 'c':
810             check_only = TRUE;
811             break;
812         case 'e':
813             namelst = make_namelist(optarg);
814             break;
815         case 'f':
816             formatted = TRUE;
817             break;
818         case 'G':
819             numbers = 1;
820             break;
821         case 'g':
822             numbers = -1;
823             break;
824         case 'o':
825             outdir = optarg;
826             break;
827         case 'q':
828             quiet = TRUE;
829             break;
830         case 'r':
831             forceresolve = TRUE;
832             break;
833         case 's':
834             showsummary = TRUE;
835             break;
836         case 'v':
837             v_opt = 0;
838             break;
839         case 'w':
840             width = 0;
841             break;
842 #if NCURSES_XNAMES
843         case 't':
844             _nc_disable_period = FALSE;
845             suppress_untranslatable = TRUE;
846             break;
847         case 'a':
848             _nc_disable_period = TRUE;
849             /* FALLTHRU */
850         case 'x':
851             use_extended_names(TRUE);
852             break;
853 #endif
854         default:
855             usage();
856         }
857         last_opt = this_opt;
858     }
859
860     debug_level = VtoTrace(v_opt);
861     set_trace_level(debug_level);
862
863     if (_nc_tracing) {
864         save_check_termtype = _nc_check_termtype2;
865         _nc_check_termtype2 = check_termtype;
866     }
867 #if !HAVE_BIG_CORE
868     /*
869      * Aaargh! immedhook seriously hoses us!
870      *
871      * One problem with immedhook is it means we can't do -e.  Problem
872      * is that we can't guarantee that for each terminal listed, all the
873      * terminals it depends on will have been kept in core for reference
874      * resolution -- in fact it's certain the primitive types at the end
875      * of reference chains *won't* be in core unless they were explicitly
876      * in the select list themselves.
877      */
878     if (namelst && (!infodump && !capdump)) {
879         (void) fprintf(stderr,
880                        "%s: Sorry, -e can't be used without -I or -C\n",
881                        _nc_progname);
882         ExitProgram(EXIT_FAILURE);
883     }
884 #endif /* HAVE_BIG_CORE */
885
886     if (optind < argc) {
887         source_file = argv[optind++];
888         if (optind < argc) {
889             fprintf(stderr,
890                     "%s: Too many file names.  Usage:\n\t%s %s",
891                     _nc_progname,
892                     _nc_progname,
893                     usage_string);
894             ExitProgram(EXIT_FAILURE);
895         }
896     } else {
897         if (infodump == TRUE) {
898             /* captoinfo's no-argument case */
899             source_file = "/etc/termcap";
900             if ((termcap = getenv("TERMCAP")) != 0
901                 && (namelst = make_namelist(getenv("TERM"))) != 0) {
902                 if (access(termcap, F_OK) == 0) {
903                     /* file exists */
904                     source_file = termcap;
905                 } else {
906                     if ((tmp_fp = open_tempfile(my_tmpname)) != 0) {
907                         source_file = my_tmpname;
908                         fprintf(tmp_fp, "%s\n", termcap);
909                         fclose(tmp_fp);
910                         tmp_fp = open_input(source_file, (char *) 0);
911                         to_remove = source_file;
912                     } else {
913                         failed("tmpnam");
914                     }
915                 }
916             }
917         } else {
918             /* tic */
919             fprintf(stderr,
920                     "%s: File name needed.  Usage:\n\t%s %s",
921                     _nc_progname,
922                     _nc_progname,
923                     usage_string);
924             ExitProgram(EXIT_FAILURE);
925         }
926     }
927
928     if (tmp_fp == 0) {
929         tmp_fp = open_input(source_file, my_altfile);
930         if (!strcmp(source_file, "-")) {
931             source_file = STDIN_NAME;
932         }
933     }
934
935     if (infodump || check_only) {
936         dump_init(tversion,
937                   (smart_defaults
938                    ? outform
939                    : F_LITERAL),
940                   sortmode,
941                   wrap_strings, width, height,
942                   debug_level, formatted || check_only, check_only, quickdump);
943     } else if (capdump) {
944         dump_init(tversion,
945                   outform,
946                   sortmode,
947                   wrap_strings, width, height,
948                   debug_level, FALSE, FALSE, FALSE);
949     }
950
951     /* parse entries out of the source file */
952     _nc_set_source(source_file);
953 #if !HAVE_BIG_CORE
954     if (!(check_only || infodump || capdump))
955         _nc_set_writedir(outdir);
956 #endif /* HAVE_BIG_CORE */
957     _nc_read_entry_source(tmp_fp, (char *) NULL,
958                           !smart_defaults || literal, FALSE,
959                           ((check_only || infodump || capdump)
960                            ? NULLHOOK
961                            : immedhook));
962
963     /* do use resolution */
964     if (check_only || (!infodump && !capdump) || forceresolve) {
965         if (!_nc_resolve_uses2(TRUE, literal) && !check_only) {
966             ExitProgram(EXIT_FAILURE);
967         }
968     }
969
970     /* length check */
971     if (check_only && limited && (capdump || infodump)) {
972         for_entry_list(qp) {
973             if (matches(namelst, qp->tterm.term_names)) {
974                 int len = fmt_entry(&qp->tterm, NULL, FALSE, TRUE, infodump, numbers);
975
976                 if (len > (infodump ? MAX_TERMINFO_LENGTH : MAX_TERMCAP_LENGTH))
977                     (void) fprintf(stderr,
978                                    "warning: resolved %s entry is %d bytes long\n",
979                                    _nc_first_name(qp->tterm.term_names),
980                                    len);
981             }
982         }
983     }
984
985     /* write or dump all entries */
986     if (check_only) {
987         /* this is in case infotocap() generates warnings */
988         _nc_curr_col = _nc_curr_line = -1;
989
990         for_entry_list(qp) {
991             if (matches(namelst, qp->tterm.term_names)) {
992                 /* this is in case infotocap() generates warnings */
993                 _nc_set_type(_nc_first_name(qp->tterm.term_names));
994                 _nc_curr_line = (int) qp->startline;
995                 repair_acsc(&qp->tterm);
996                 dump_entry(&qp->tterm, suppress_untranslatable,
997                            limited, numbers, NULL);
998             }
999         }
1000     } else {
1001         if (!infodump && !capdump) {
1002             _nc_set_writedir(outdir);
1003             for_entry_list(qp) {
1004                 if (matches(namelst, qp->tterm.term_names))
1005                     write_it(qp);
1006             }
1007         } else {
1008             /* this is in case infotocap() generates warnings */
1009             _nc_curr_col = _nc_curr_line = -1;
1010
1011             for_entry_list(qp) {
1012                 if (matches(namelst, qp->tterm.term_names)) {
1013                     long j = qp->cend - qp->cstart;
1014                     int len = 0;
1015
1016                     /* this is in case infotocap() generates warnings */
1017                     _nc_set_type(_nc_first_name(qp->tterm.term_names));
1018
1019                     if (!quiet) {
1020                         (void) fseek(tmp_fp, qp->cstart, SEEK_SET);
1021                         while (j-- > 0) {
1022                             if (infodump)
1023                                 (void) putchar(fgetc(tmp_fp));
1024                             else
1025                                 put_translate(fgetc(tmp_fp));
1026                         }
1027                     }
1028
1029                     repair_acsc(&qp->tterm);
1030                     dump_entry(&qp->tterm, suppress_untranslatable,
1031                                limited, numbers, NULL);
1032                     for (j = 0; j < (long) qp->nuses; j++)
1033                         dump_uses(qp->uses[j].name, !capdump);
1034                     len = show_entry();
1035                     if (debug_level != 0 && !limited)
1036                         printf("# length=%d\n", len);
1037                 }
1038             }
1039             if (!namelst && _nc_tail && !quiet) {
1040                 int c, oldc = '\0';
1041                 bool in_comment = FALSE;
1042                 bool trailing_comment = FALSE;
1043
1044                 (void) fseek(tmp_fp, _nc_tail->cend, SEEK_SET);
1045                 while ((c = fgetc(tmp_fp)) != EOF) {
1046                     if (oldc == '\n') {
1047                         if (c == '#') {
1048                             trailing_comment = TRUE;
1049                             in_comment = TRUE;
1050                         } else {
1051                             in_comment = FALSE;
1052                         }
1053                     }
1054                     if (trailing_comment
1055                         && (in_comment || (oldc == '\n' && c == '\n')))
1056                         putchar(c);
1057                     oldc = c;
1058                 }
1059             }
1060         }
1061     }
1062
1063     /* Show the directory into which entries were written, and the total
1064      * number of entries
1065      */
1066     if (showsummary
1067         && (!(check_only || infodump || capdump))) {
1068         int total = _nc_tic_written();
1069         if (total != 0)
1070             fprintf(log_fp, "%d entries written to %s\n",
1071                     total,
1072                     _nc_tic_dir((char *) 0));
1073         else
1074             fprintf(log_fp, "No entries written\n");
1075     }
1076     ExitProgram(EXIT_SUCCESS);
1077 }
1078
1079 /*
1080  * This bit of legerdemain turns all the terminfo variable names into
1081  * references to locations in the arrays Booleans, Numbers, and Strings ---
1082  * precisely what's needed (see comp_parse.c).
1083  */
1084 #undef CUR
1085 #define CUR tp->
1086
1087 /*
1088  * Check if the alternate character-set capabilities are consistent.
1089  */
1090 static void
1091 check_acs(TERMTYPE *tp)
1092 {
1093     if (VALID_STRING(acs_chars)) {
1094         const char *boxes = "lmkjtuvwqxn";
1095         char mapped[256];
1096         char missing[256];
1097         const char *p;
1098         char *q;
1099
1100         memset(mapped, 0, sizeof(mapped));
1101         for (p = acs_chars; *p != '\0'; p += 2) {
1102             if (p[1] == '\0') {
1103                 _nc_warning("acsc has odd number of characters");
1104                 break;
1105             }
1106             mapped[UChar(p[0])] = p[1];
1107         }
1108
1109         if (mapped[UChar('I')] && !mapped[UChar('i')]) {
1110             _nc_warning("acsc refers to 'I', which is probably an error");
1111         }
1112
1113         for (p = boxes, q = missing; *p != '\0'; ++p) {
1114             if (!mapped[UChar(p[0])]) {
1115                 *q++ = p[0];
1116             }
1117         }
1118         *q = '\0';
1119
1120         assert(strlen(missing) <= strlen(boxes));
1121         if (*missing != '\0' && strcmp(missing, boxes)) {
1122             _nc_warning("acsc is missing some line-drawing mapping: %s", missing);
1123         }
1124     }
1125 }
1126
1127 /*
1128  * Check if the color capabilities are consistent
1129  */
1130 static void
1131 check_colors(TERMTYPE *tp)
1132 {
1133     if ((max_colors > 0) != (max_pairs > 0)
1134         || ((max_colors > max_pairs) && (initialize_pair == 0)))
1135         _nc_warning("inconsistent values for max_colors (%d) and max_pairs (%d)",
1136                     max_colors, max_pairs);
1137
1138     PAIRED(set_foreground, set_background);
1139     PAIRED(set_a_foreground, set_a_background);
1140     PAIRED(set_color_pair, initialize_pair);
1141
1142     if (VALID_STRING(set_foreground)
1143         && VALID_STRING(set_a_foreground)
1144         && !_nc_capcmp(set_foreground, set_a_foreground))
1145         _nc_warning("expected setf/setaf to be different");
1146
1147     if (VALID_STRING(set_background)
1148         && VALID_STRING(set_a_background)
1149         && !_nc_capcmp(set_background, set_a_background))
1150         _nc_warning("expected setb/setab to be different");
1151
1152     /* see: has_colors() */
1153     if (VALID_NUMERIC(max_colors) && VALID_NUMERIC(max_pairs)
1154         && (((set_foreground != NULL)
1155              && (set_background != NULL))
1156             || ((set_a_foreground != NULL)
1157                 && (set_a_background != NULL))
1158             || set_color_pair)) {
1159         if (!VALID_STRING(orig_pair) && !VALID_STRING(orig_colors))
1160             _nc_warning("expected either op/oc string for resetting colors");
1161     }
1162     if (can_change) {
1163         if (!VALID_STRING(initialize_pair) &&
1164             !VALID_STRING(initialize_color)) {
1165             _nc_warning("expected initc or initp because ccc is given");
1166         }
1167     } else {
1168         if (VALID_STRING(initialize_pair) ||
1169             VALID_STRING(initialize_color)) {
1170             _nc_warning("expected ccc because initc is given");
1171         }
1172     }
1173 }
1174
1175 static int
1176 csi_length(const char *value)
1177 {
1178     int result = 0;
1179
1180     if (value[0] == '\033' && value[1] == '[') {
1181         result = 2;
1182     } else if (UChar(value[0]) == 0x9a) {
1183         result = 1;
1184     }
1185     return result;
1186 }
1187
1188 static char
1189 keypad_final(const char *string)
1190 {
1191     char result = '\0';
1192
1193     if (VALID_STRING(string)
1194         && *string++ == '\033'
1195         && *string++ == 'O'
1196         && strlen(string) == 1) {
1197         result = *string;
1198     }
1199
1200     return result;
1201 }
1202
1203 static long
1204 keypad_index(const char *string)
1205 {
1206     char *test;
1207     const char *list = "PQRSwxymtuvlqrsPpn";    /* app-keypad except "Enter" */
1208     int ch;
1209     long result = -1;
1210
1211     if ((ch = keypad_final(string)) != '\0') {
1212         test = (strchr) (list, ch);
1213         if (test != 0)
1214             result = (long) (test - list);
1215     }
1216     return result;
1217 }
1218
1219 /*
1220  * list[] is down, up, left, right
1221  * "left" may be ^H rather than \E[D
1222  * "down" may be ^J rather than \E[B
1223  * But up/right are generally consistently escape sequences for ANSI terminals.
1224  */
1225 static void
1226 check_ansi_cursor(char *list[4])
1227 {
1228     int j, k;
1229     int want;
1230     size_t suffix;
1231     bool skip[4];
1232     bool repeated = FALSE;
1233
1234     for (j = 0; j < 4; ++j) {
1235         skip[j] = FALSE;
1236         for (k = 0; k < j; ++k) {
1237             if (j != k
1238                 && !strcmp(list[j], list[k])) {
1239                 char *value = _nc_tic_expand(list[k], TRUE, 0);
1240                 _nc_warning("repeated cursor control %s\n", value);
1241                 repeated = TRUE;
1242             }
1243         }
1244     }
1245     if (!repeated) {
1246         char *up = list[1];
1247         size_t prefix = (size_t) csi_length(up);
1248
1249         if (prefix) {
1250             suffix = prefix;
1251             while (up[suffix] && isdigit(UChar(up[suffix])))
1252                 ++suffix;
1253         }
1254         if (prefix && up[suffix] == 'A') {
1255             skip[1] = TRUE;
1256             if (!strcmp(list[0], "\n"))
1257                 skip[0] = TRUE;
1258             if (!strcmp(list[2], "\b"))
1259                 skip[2] = TRUE;
1260
1261             for (j = 0; j < 4; ++j) {
1262                 if (skip[j] || strlen(list[j]) == 1)
1263                     continue;
1264                 if (memcmp(list[j], up, prefix)) {
1265                     char *value = _nc_tic_expand(list[j], TRUE, 0);
1266                     _nc_warning("inconsistent prefix for %s\n", value);
1267                     continue;
1268                 }
1269                 if (strlen(list[j]) < suffix) {
1270                     char *value = _nc_tic_expand(list[j], TRUE, 0);
1271                     _nc_warning("inconsistent length for %s, expected %d\n",
1272                                 value, (int) suffix + 1);
1273                     continue;
1274                 }
1275                 want = "BADC"[j];
1276                 if (list[j][suffix] != want) {
1277                     char *value = _nc_tic_expand(list[j], TRUE, 0);
1278                     _nc_warning("inconsistent suffix for %s, expected %c, have %c\n",
1279                                 value, want, list[j][suffix]);
1280                 }
1281             }
1282         }
1283     }
1284 }
1285
1286 #define EXPECTED(name) if (!PRESENT(name)) _nc_warning("expected " #name)
1287 #define UNEXPECTED(name) if (PRESENT(name)) _nc_warning("unexpected " #name ", for %s", why)
1288
1289 static void
1290 check_noaddress(TERMTYPE *tp, const char *why)
1291 {
1292     UNEXPECTED(column_address);
1293     UNEXPECTED(cursor_address);
1294     UNEXPECTED(cursor_home);
1295     UNEXPECTED(cursor_mem_address);
1296     UNEXPECTED(cursor_to_ll);
1297     UNEXPECTED(row_address);
1298     UNEXPECTED(row_address);
1299 }
1300
1301 static void
1302 check_cursor(TERMTYPE *tp)
1303 {
1304     int count;
1305     char *list[4];
1306
1307     if (hard_copy) {
1308         check_noaddress(tp, "hard_copy");
1309     } else if (generic_type) {
1310         check_noaddress(tp, "generic_type");
1311     } else if (strchr(tp->term_names, '+') == 0) {
1312         int y = 0;
1313         int x = 0;
1314         if (PRESENT(column_address))
1315             ++y;
1316         if (PRESENT(cursor_address))
1317             y = x = 10;
1318         if (PRESENT(cursor_home))
1319             ++y, ++x;
1320         if (PRESENT(cursor_mem_address))
1321             y = x = 10;
1322         if (PRESENT(cursor_to_ll))
1323             ++y, ++x;
1324         if (PRESENT(row_address))
1325             ++x;
1326         if (PRESENT(cursor_down))
1327             ++y;
1328         if (PRESENT(cursor_up))
1329             ++y;
1330         if (PRESENT(cursor_left))
1331             ++x;
1332         if (PRESENT(cursor_right))
1333             ++x;
1334         if (x < 2 && y < 2) {
1335             _nc_warning("terminal lacks cursor addressing");
1336         } else {
1337             if (x < 2)
1338                 _nc_warning("terminal lacks cursor column-addressing");
1339             if (y < 2)
1340                 _nc_warning("terminal lacks cursor row-addressing");
1341         }
1342     }
1343
1344     /* it is rare to have an insert-line feature without a matching delete */
1345     ANDMISSING(parm_insert_line, insert_line);
1346     ANDMISSING(parm_delete_line, delete_line);
1347     ANDMISSING(parm_insert_line, parm_delete_line);
1348
1349     /* if we have a parameterized form, then the non-parameterized is easy */
1350     ANDMISSING(parm_down_cursor, cursor_down);
1351     ANDMISSING(parm_up_cursor, cursor_up);
1352     ANDMISSING(parm_left_cursor, cursor_left);
1353     ANDMISSING(parm_right_cursor, cursor_right);
1354
1355     /* Given any of a set of cursor movement, the whole set should be present.
1356      * Technically this is not true (we could use cursor_address to fill in
1357      * unsupported controls), but it is likely.
1358      */
1359     count = 0;
1360     if (PRESENT(parm_down_cursor)) {
1361         list[count++] = parm_down_cursor;
1362     }
1363     if (PRESENT(parm_up_cursor)) {
1364         list[count++] = parm_up_cursor;
1365     }
1366     if (PRESENT(parm_left_cursor)) {
1367         list[count++] = parm_left_cursor;
1368     }
1369     if (PRESENT(parm_right_cursor)) {
1370         list[count++] = parm_right_cursor;
1371     }
1372     if (count == 4) {
1373         check_ansi_cursor(list);
1374     } else if (count != 0) {
1375         EXPECTED(parm_down_cursor);
1376         EXPECTED(parm_up_cursor);
1377         EXPECTED(parm_left_cursor);
1378         EXPECTED(parm_right_cursor);
1379     }
1380
1381     count = 0;
1382     if (PRESENT(cursor_down)) {
1383         list[count++] = cursor_down;
1384     }
1385     if (PRESENT(cursor_up)) {
1386         list[count++] = cursor_up;
1387     }
1388     if (PRESENT(cursor_left)) {
1389         list[count++] = cursor_left;
1390     }
1391     if (PRESENT(cursor_right)) {
1392         list[count++] = cursor_right;
1393     }
1394     if (count == 4) {
1395         check_ansi_cursor(list);
1396     } else if (count != 0) {
1397         count = 0;
1398         if (PRESENT(cursor_down) && strcmp(cursor_down, "\n"))
1399             ++count;
1400         if (PRESENT(cursor_left) && strcmp(cursor_left, "\b"))
1401             ++count;
1402         if (PRESENT(cursor_up) && strlen(cursor_up) > 1)
1403             ++count;
1404         if (PRESENT(cursor_right) && strlen(cursor_right) > 1)
1405             ++count;
1406         if (count) {
1407             EXPECTED(cursor_down);
1408             EXPECTED(cursor_up);
1409             EXPECTED(cursor_left);
1410             EXPECTED(cursor_right);
1411         }
1412     }
1413 }
1414
1415 #define MAX_KP 5
1416 /*
1417  * Do a quick sanity-check for vt100-style keypads to see if the 5-key keypad
1418  * is mapped inconsistently.
1419  */
1420 static void
1421 check_keypad(TERMTYPE *tp)
1422 {
1423     char show[80];
1424
1425     if (VALID_STRING(key_a1) &&
1426         VALID_STRING(key_a3) &&
1427         VALID_STRING(key_b2) &&
1428         VALID_STRING(key_c1) &&
1429         VALID_STRING(key_c3)) {
1430         char final[MAX_KP + 1];
1431         long list[MAX_KP];
1432         int increase = 0;
1433         int j, k, kk;
1434         long last;
1435         long test;
1436
1437         final[0] = keypad_final(key_a1);
1438         final[1] = keypad_final(key_a3);
1439         final[2] = keypad_final(key_b2);
1440         final[3] = keypad_final(key_c1);
1441         final[4] = keypad_final(key_c3);
1442         final[5] = '\0';
1443
1444         /* special case: legacy coding using 1,2,3,0,. on the bottom */
1445         assert(strlen(final) <= MAX_KP);
1446         if (!strcmp(final, "qsrpn"))
1447             return;
1448
1449         list[0] = keypad_index(key_a1);
1450         list[1] = keypad_index(key_a3);
1451         list[2] = keypad_index(key_b2);
1452         list[3] = keypad_index(key_c1);
1453         list[4] = keypad_index(key_c3);
1454
1455         /* check that they're all vt100 keys */
1456         for (j = 0; j < MAX_KP; ++j) {
1457             if (list[j] < 0) {
1458                 return;
1459             }
1460         }
1461
1462         /* check if they're all in increasing order */
1463         for (j = 1; j < MAX_KP; ++j) {
1464             if (list[j] > list[j - 1]) {
1465                 ++increase;
1466             }
1467         }
1468         if (increase != (MAX_KP - 1)) {
1469             show[0] = '\0';
1470
1471             for (j = 0, last = -1; j < MAX_KP; ++j) {
1472                 for (k = 0, kk = -1, test = 100; k < 5; ++k) {
1473                     if (list[k] > last &&
1474                         list[k] < test) {
1475                         test = list[k];
1476                         kk = k;
1477                     }
1478                 }
1479                 last = test;
1480                 assert(strlen(show) < (MAX_KP * 4));
1481                 switch (kk) {
1482                 case 0:
1483                     _nc_STRCAT(show, " ka1", sizeof(show));
1484                     break;
1485                 case 1:
1486                     _nc_STRCAT(show, " ka3", sizeof(show));
1487                     break;
1488                 case 2:
1489                     _nc_STRCAT(show, " kb2", sizeof(show));
1490                     break;
1491                 case 3:
1492                     _nc_STRCAT(show, " kc1", sizeof(show));
1493                     break;
1494                 case 4:
1495                     _nc_STRCAT(show, " kc3", sizeof(show));
1496                     break;
1497                 }
1498             }
1499
1500             _nc_warning("vt100 keypad order inconsistent: %s", show);
1501         }
1502
1503     } else if (VALID_STRING(key_a1) ||
1504                VALID_STRING(key_a3) ||
1505                VALID_STRING(key_b2) ||
1506                VALID_STRING(key_c1) ||
1507                VALID_STRING(key_c3)) {
1508         show[0] = '\0';
1509         if (keypad_index(key_a1) >= 0)
1510             _nc_STRCAT(show, " ka1", sizeof(show));
1511         if (keypad_index(key_a3) >= 0)
1512             _nc_STRCAT(show, " ka3", sizeof(show));
1513         if (keypad_index(key_b2) >= 0)
1514             _nc_STRCAT(show, " kb2", sizeof(show));
1515         if (keypad_index(key_c1) >= 0)
1516             _nc_STRCAT(show, " kc1", sizeof(show));
1517         if (keypad_index(key_c3) >= 0)
1518             _nc_STRCAT(show, " kc3", sizeof(show));
1519         if (*show != '\0')
1520             _nc_warning("vt100 keypad map incomplete:%s", show);
1521     }
1522
1523     /*
1524      * These warnings are useful for consistency checks - it is possible that
1525      * there are real terminals with mismatches in these
1526      */
1527     ANDMISSING(key_ic, key_dc);
1528 }
1529
1530 static void
1531 check_printer(TERMTYPE *tp)
1532 {
1533     PAIRED(enter_doublewide_mode, exit_doublewide_mode);
1534     PAIRED(enter_italics_mode, exit_italics_mode);
1535     PAIRED(enter_leftward_mode, exit_leftward_mode);
1536     PAIRED(enter_micro_mode, exit_micro_mode);
1537     PAIRED(enter_shadow_mode, exit_shadow_mode);
1538     PAIRED(enter_subscript_mode, exit_subscript_mode);
1539     PAIRED(enter_superscript_mode, exit_superscript_mode);
1540     PAIRED(enter_upward_mode, exit_upward_mode);
1541
1542     ANDMISSING(start_char_set_def, stop_char_set_def);
1543
1544     /* if we have a parameterized form, then the non-parameterized is easy */
1545     ANDMISSING(set_bottom_margin_parm, set_bottom_margin);
1546     ANDMISSING(set_left_margin_parm, set_left_margin);
1547     ANDMISSING(set_right_margin_parm, set_right_margin);
1548     ANDMISSING(set_top_margin_parm, set_top_margin);
1549
1550     ANDMISSING(parm_down_micro, micro_down);
1551     ANDMISSING(parm_left_micro, micro_left);
1552     ANDMISSING(parm_right_micro, micro_right);
1553     ANDMISSING(parm_up_micro, micro_up);
1554 }
1555
1556 static bool
1557 uses_SGR_39_49(const char *value)
1558 {
1559     return (strstr(value, "39;49") != 0
1560             || strstr(value, "49;39") != 0);
1561 }
1562
1563 /*
1564  * Check consistency of termcap extensions related to "screen".
1565  */
1566 static void
1567 check_screen(TERMTYPE *tp)
1568 {
1569 #if NCURSES_XNAMES
1570     if (_nc_user_definable) {
1571         int have_XT = tigetflag("XT");
1572         int have_XM = tigetflag("XM");
1573         int have_bce = back_color_erase;
1574         bool have_kmouse = FALSE;
1575         bool use_sgr_39_49 = FALSE;
1576         char *name = _nc_first_name(tp->term_names);
1577
1578         if (!VALID_BOOLEAN(have_bce)) {
1579             have_bce = FALSE;
1580         }
1581         if (!VALID_BOOLEAN(have_XM)) {
1582             have_XM = FALSE;
1583         }
1584         if (!VALID_BOOLEAN(have_XT)) {
1585             have_XT = FALSE;
1586         }
1587         if (VALID_STRING(key_mouse)) {
1588             have_kmouse = !strcmp("\033[M", key_mouse);
1589         }
1590         if (VALID_STRING(orig_colors)) {
1591             use_sgr_39_49 = uses_SGR_39_49(orig_colors);
1592         } else if (VALID_STRING(orig_pair)) {
1593             use_sgr_39_49 = uses_SGR_39_49(orig_pair);
1594         }
1595
1596         if (have_XM && have_XT) {
1597             _nc_warning("Screen's XT capability conflicts with XM");
1598         } else if (have_XT
1599                    && strstr(name, "screen") != 0
1600                    && strchr(name, '.') != 0) {
1601             _nc_warning("Screen's \"screen\" entries should not have XT set");
1602         } else if (have_XT) {
1603             if (!have_kmouse && have_bce) {
1604                 if (VALID_STRING(key_mouse)) {
1605                     _nc_warning("Value of kmous inconsistent with screen's usage");
1606                 } else {
1607                     _nc_warning("Expected kmous capability with XT");
1608                 }
1609             }
1610             if (!have_bce && max_colors > 0)
1611                 _nc_warning("Expected bce capability with XT");
1612             if (!use_sgr_39_49 && have_bce && max_colors > 0)
1613                 _nc_warning("Expected orig_colors capability with XT to have 39/49 parameters");
1614             if (VALID_STRING(to_status_line))
1615                 _nc_warning("\"tsl\" capability is redundant, given XT");
1616         } else {
1617             if (have_kmouse && !have_XM)
1618                 _nc_warning("Expected XT to be set, given kmous");
1619         }
1620     }
1621 #endif
1622 }
1623
1624 /*
1625  * Returns the expected number of parameters for the given capability.
1626  */
1627 static int
1628 expected_params(const char *name)
1629 {
1630 #define DATA(name,count) { { name }, count }
1631     /* *INDENT-OFF* */
1632     static const struct {
1633         const char name[9];
1634         int count;
1635     } table[] = {
1636         DATA( "S0",             1 ),    /* 'screen' extension */
1637         DATA( "birep",          2 ),
1638         DATA( "chr",            1 ),
1639         DATA( "colornm",        1 ),
1640         DATA( "cpi",            1 ),
1641         DATA( "csnm",           1 ),
1642         DATA( "csr",            2 ),
1643         DATA( "cub",            1 ),
1644         DATA( "cud",            1 ),
1645         DATA( "cuf",            1 ),
1646         DATA( "cup",            2 ),
1647         DATA( "cuu",            1 ),
1648         DATA( "cvr",            1 ),
1649         DATA( "cwin",           5 ),
1650         DATA( "dch",            1 ),
1651         DATA( "defc",           3 ),
1652         DATA( "dial",           1 ),
1653         DATA( "dispc",          1 ),
1654         DATA( "dl",             1 ),
1655         DATA( "ech",            1 ),
1656         DATA( "getm",           1 ),
1657         DATA( "hpa",            1 ),
1658         DATA( "ich",            1 ),
1659         DATA( "il",             1 ),
1660         DATA( "indn",           1 ),
1661         DATA( "initc",          4 ),
1662         DATA( "initp",          7 ),
1663         DATA( "lpi",            1 ),
1664         DATA( "mc5p",           1 ),
1665         DATA( "mrcup",          2 ),
1666         DATA( "mvpa",           1 ),
1667         DATA( "pfkey",          2 ),
1668         DATA( "pfloc",          2 ),
1669         DATA( "pfx",            2 ),
1670         DATA( "pfxl",           3 ),
1671         DATA( "pln",            2 ),
1672         DATA( "qdial",          1 ),
1673         DATA( "rcsd",           1 ),
1674         DATA( "rep",            2 ),
1675         DATA( "rin",            1 ),
1676         DATA( "sclk",           3 ),
1677         DATA( "scp",            1 ),
1678         DATA( "scs",            1 ),
1679         DATA( "scsd",           2 ),
1680         DATA( "setab",          1 ),
1681         DATA( "setaf",          1 ),
1682         DATA( "setb",           1 ),
1683         DATA( "setcolor",       1 ),
1684         DATA( "setf",           1 ),
1685         DATA( "sgr",            9 ),
1686         DATA( "sgr1",           6 ),
1687         DATA( "slength",        1 ),
1688         DATA( "slines",         1 ),
1689         DATA( "smgbp",          1 ),    /* 2 if smgtp is not given */
1690         DATA( "smglp",          1 ),
1691         DATA( "smglr",          2 ),
1692         DATA( "smgrp",          1 ),
1693         DATA( "smgtb",          2 ),
1694         DATA( "smgtp",          1 ),
1695         DATA( "tsl",            1 ),
1696         DATA( "u6",             -1 ),
1697         DATA( "vpa",            1 ),
1698         DATA( "wind",           4 ),
1699         DATA( "wingo",          1 ),
1700     };
1701     /* *INDENT-ON* */
1702
1703 #undef DATA
1704
1705     unsigned n;
1706     int result = 0;             /* function-keys, etc., use none */
1707
1708     for (n = 0; n < SIZEOF(table); n++) {
1709         if (!strcmp(name, table[n].name)) {
1710             result = table[n].count;
1711             break;
1712         }
1713     }
1714
1715     return result;
1716 }
1717
1718 /*
1719  * Make a quick sanity check for the parameters which are used in the given
1720  * strings.  If there are no "%p" tokens, then there should be no other "%"
1721  * markers.
1722  */
1723 static void
1724 check_params(TERMTYPE *tp, const char *name, char *value)
1725 {
1726     int expected = expected_params(name);
1727     int actual = 0;
1728     int n;
1729     bool params[NUM_PARM];
1730     char *s = value;
1731
1732 #ifdef set_top_margin_parm
1733     if (!strcmp(name, "smgbp")
1734         && set_top_margin_parm == 0)
1735         expected = 2;
1736 #endif
1737
1738     for (n = 0; n < NUM_PARM; n++)
1739         params[n] = FALSE;
1740
1741     while (*s != 0) {
1742         if (*s == '%') {
1743             if (*++s == '\0') {
1744                 _nc_warning("expected character after %% in %s", name);
1745                 break;
1746             } else if (*s == 'p') {
1747                 if (*++s == '\0' || !isdigit((int) *s)) {
1748                     _nc_warning("expected digit after %%p in %s", name);
1749                     return;
1750                 } else {
1751                     n = (*s - '0');
1752                     if (n > actual)
1753                         actual = n;
1754                     params[n] = TRUE;
1755                 }
1756             }
1757         }
1758         s++;
1759     }
1760
1761     if (params[0]) {
1762         _nc_warning("%s refers to parameter 0 (%%p0), which is not allowed", name);
1763     }
1764     if (value == set_attributes || expected < 0) {
1765         ;
1766     } else if (expected != actual) {
1767         _nc_warning("%s uses %d parameters, expected %d", name,
1768                     actual, expected);
1769         for (n = 1; n < actual; n++) {
1770             if (!params[n])
1771                 _nc_warning("%s omits parameter %d", name, n);
1772         }
1773     }
1774 }
1775
1776 static bool
1777 line_capability(const char *name)
1778 {
1779     bool result = FALSE;
1780     static const char *table[] =
1781     {
1782         "csr",                  /* change_scroll_region          */
1783         "clear",                /* clear_screen                  */
1784         "ed",                   /* clr_eos                       */
1785         "cwin",                 /* create_window                 */
1786         "cup",                  /* cursor_address                */
1787         "cud1",                 /* cursor_down                   */
1788         "home",                 /* cursor_home                   */
1789         "mrcup",                /* cursor_mem_address            */
1790         "ll",                   /* cursor_to_ll                  */
1791         "cuu1",                 /* cursor_up                     */
1792         "dl1",                  /* delete_line                   */
1793         "hd",                   /* down_half_line                */
1794         "flash",                /* flash_screen                  */
1795         "ff",                   /* form_feed                     */
1796         "il1",                  /* insert_line                   */
1797         "nel",                  /* newline                       */
1798         "dl",                   /* parm_delete_line              */
1799         "cud",                  /* parm_down_cursor              */
1800         "indn",                 /* parm_index                    */
1801         "il",                   /* parm_insert_line              */
1802         "rin",                  /* parm_rindex                   */
1803         "cuu",                  /* parm_up_cursor                */
1804         "mc0",                  /* print_screen                  */
1805         "vpa",                  /* row_address                   */
1806         "ind",                  /* scroll_forward                */
1807         "ri",                   /* scroll_reverse                */
1808         "hu",                   /* up_half_line                  */
1809     };
1810     size_t n;
1811     for (n = 0; n < SIZEOF(table); ++n) {
1812         if (!strcmp(name, table[n])) {
1813             result = TRUE;
1814             break;
1815         }
1816     }
1817     return result;
1818 }
1819
1820 /*
1821  * Check for DEC VT100 private mode for reverse video.
1822  */
1823 static const char *
1824 skip_DECSCNM(const char *value, int *flag)
1825 {
1826     *flag = -1;
1827     if (value != 0) {
1828         int skip = csi_length(value);
1829         if (skip > 0 &&
1830             value[skip++] == '?' &&
1831             value[skip++] == '5') {
1832             if (value[skip] == 'h') {
1833                 *flag = 1;
1834             } else if (value[skip] == 'l') {
1835                 *flag = 0;
1836             }
1837             value += skip + 1;
1838         }
1839     }
1840     return value;
1841 }
1842
1843 static void
1844 check_delays(const char *name, const char *value)
1845 {
1846     const char *p, *q;
1847     const char *first = 0;
1848     const char *last = 0;
1849
1850     for (p = value; *p != '\0'; ++p) {
1851         if (p[0] == '$' && p[1] == '<') {
1852             const char *base = p + 2;
1853             const char *mark = 0;
1854             bool maybe = TRUE;
1855             bool mixed = FALSE;
1856             int proportional = 0;
1857             int mandatory = 0;
1858
1859             first = p;
1860
1861             for (q = base; *q != '\0'; ++q) {
1862                 if (*q == '>') {
1863                     if (mark == 0)
1864                         mark = q;
1865                     break;
1866                 } else if (*q == '*' || *q == '/') {
1867                     if (*q == '*')
1868                         ++proportional;
1869                     if (*q == '/')
1870                         ++mandatory;
1871                     if (mark == 0)
1872                         mark = q;
1873                 } else if (!(isalnum(UChar(*q)) || strchr("+-.", *q) != 0)) {
1874                     maybe = FALSE;
1875                     break;
1876                 } else if (proportional || mandatory) {
1877                     mixed = TRUE;
1878                 }
1879             }
1880             last = *q ? (q + 1) : q;
1881             if (*q == '\0') {
1882                 maybe = FALSE;  /* just an isolated "$<" */
1883             } else if (maybe) {
1884                 float check_f;
1885                 char check_c;
1886                 int rc = sscanf(base, "%f%c", &check_f, &check_c);
1887                 if ((rc != 2) || (check_c != *mark) || mixed) {
1888                     _nc_warning("syntax error in %s delay '%.*s'", name,
1889                                 (int) (q - base), base);
1890                 } else if (*name == 'k') {
1891                     _nc_warning("function-key %s has delay", name);
1892                 } else if (proportional && !line_capability(name)) {
1893                     _nc_warning("non-line capability using proportional delay: %s", name);
1894                 }
1895             } else {
1896                 p = q - 1;      /* restart scan */
1897             }
1898         }
1899     }
1900
1901     if (!strcmp(name, "flash") ||
1902         !strcmp(name, "beep")) {
1903
1904         if (first != 0) {
1905             if (first == value || *last == 0) {
1906                 /*
1907                  * Delay is on one end or the other.
1908                  */
1909                 _nc_warning("expected delay embedded within %s", name);
1910             }
1911         } else {
1912             int flag;
1913
1914             /*
1915              * Check for missing delay when using VT100 reverse-video.
1916              * A real VT100 might not need this, but terminal emulators do.
1917              */
1918             if ((p = skip_DECSCNM(value, &flag)) != 0 &&
1919                 flag > 0 &&
1920                 (q = skip_DECSCNM(p, &flag)) != 0 &&
1921                 flag == 0) {
1922                 _nc_warning("expected a delay in %s", name);
1923             }
1924         }
1925     }
1926 }
1927
1928 static char *
1929 check_1_infotocap(const char *name, NCURSES_CONST char *value, int count)
1930 {
1931     int k;
1932     int ignored;
1933     long numbers[1 + NUM_PARM];
1934     char *strings[1 + NUM_PARM];
1935     char *p_is_s[NUM_PARM];
1936     char *result;
1937     char blob[NUM_PARM * 10];
1938     char *next = blob;
1939
1940     *next++ = '\0';
1941     for (k = 1; k <= NUM_PARM; k++) {
1942         numbers[k] = count;
1943         _nc_SPRINTF(next,
1944                     _nc_SLIMIT(sizeof(blob) - (next - blob))
1945                     "XYZ%d", count);
1946         strings[k] = next;
1947         next += strlen(next) + 1;
1948     }
1949
1950     switch (tparm_type(name)) {
1951     case Num_Str:
1952         result = TPARM_2(value, numbers[1], strings[2]);
1953         break;
1954     case Num_Str_Str:
1955         result = TPARM_3(value, numbers[1], strings[2], strings[3]);
1956         break;
1957     case Numbers:
1958     default:
1959         (void) _nc_tparm_analyze(value, p_is_s, &ignored);
1960 #define myParam(n) (p_is_s[n - 1] != 0 ? ((TPARM_ARG) strings[n]) : numbers[n])
1961         result = TPARM_9(value,
1962                          myParam(1),
1963                          myParam(2),
1964                          myParam(3),
1965                          myParam(4),
1966                          myParam(5),
1967                          myParam(6),
1968                          myParam(7),
1969                          myParam(8),
1970                          myParam(9));
1971         break;
1972     }
1973     return result;
1974 }
1975
1976 #define IsDelay(ch) ((ch) == '.' || isdigit(UChar(ch)))
1977
1978 static const char *
1979 parse_delay_value(const char *src, double *delays, int *always)
1980 {
1981     int star = 0;
1982
1983     *delays = 0.0;
1984     if (always)
1985         *always = 0;
1986
1987     while (isdigit(UChar(*src))) {
1988         (*delays) = (*delays) * 10 + (*src++ - '0');
1989     }
1990     if (*src == '.') {
1991         int gotdot = 1;
1992
1993         ++src;
1994         while (isdigit(UChar(*src))) {
1995             gotdot *= 10;
1996             (*delays) += (*src++ - '0') / gotdot;
1997         }
1998     }
1999     while (*src == '*' || *src == '/') {
2000         if (always == 0 && *src == '/')
2001             break;
2002         if (*src++ == '*') {
2003             star = 1;
2004         } else {
2005             *always = 1;
2006         }
2007     }
2008     if (star)
2009         *delays = -(*delays);
2010     return src;
2011 }
2012
2013 static const char *
2014 parse_ti_delay(const char *ti, double *delays)
2015 {
2016     *delays = 0.0;
2017     while (*ti != '\0') {
2018         if (*ti == '\\') {
2019             ++ti;
2020         }
2021         if (ti[0] == '$'
2022             && ti[1] == '<'
2023             && IsDelay(UChar(ti[2]))) {
2024             int ignored;
2025             const char *last = parse_delay_value(ti + 2, delays, &ignored);
2026             if (*last == '>') {
2027                 ti = last;
2028             }
2029         } else {
2030             ++ti;
2031         }
2032     }
2033     return ti;
2034 }
2035
2036 static const char *
2037 parse_tc_delay(const char *tc, double *delays)
2038 {
2039     return parse_delay_value(tc, delays, (int *) 0);
2040 }
2041
2042 /*
2043  * Compare terminfo- and termcap-strings, factoring out delays.
2044  */
2045 static bool
2046 same_ti_tc(const char *ti, const char *tc, bool * embedded)
2047 {
2048     bool same = TRUE;
2049     double ti_delay = 0.0;
2050     double tc_delay = 0.0;
2051     const char *ti_last;
2052
2053     *embedded = FALSE;
2054     ti_last = parse_ti_delay(ti, &ti_delay);
2055     tc = parse_tc_delay(tc, &tc_delay);
2056
2057     while ((ti < ti_last) && *tc) {
2058         if (*ti == '\\' && ispunct(UChar(ti[1]))) {
2059             ++ti;
2060             if ((*ti == '^') && !strncmp(tc, "\\136", 4)) {
2061                 ti += 1;
2062                 tc += 4;
2063                 continue;
2064             }
2065         } else if (ti[0] == '$' && ti[1] == '<') {
2066             double no_delay;
2067             const char *ss = parse_ti_delay(ti, &no_delay);
2068             if (ss != ti) {
2069                 *embedded = TRUE;
2070                 ti = ss;
2071                 continue;
2072             }
2073         }
2074         if (*tc == '\\' && ispunct(UChar(tc[1]))) {
2075             ++tc;
2076         }
2077         if (*ti++ != *tc++) {
2078             same = FALSE;
2079             break;
2080         }
2081     }
2082
2083     if (*embedded) {
2084         if (same) {
2085             same = FALSE;
2086         } else {
2087             *embedded = FALSE;  /* report only one problem */
2088         }
2089     }
2090
2091     return same;
2092 }
2093
2094 /*
2095  * Check terminfo to termcap translation.
2096  */
2097 static void
2098 check_infotocap(TERMTYPE *tp, int i, const char *value)
2099 {
2100     const char *name = ExtStrname(tp, i, strnames);
2101     int params = (((i < (int) SIZEOF(parametrized)) &&
2102                    (i < STRCOUNT))
2103                   ? parametrized[i]
2104                   : ((*value == 'k')
2105                      ? 0
2106                      : has_params(value)));
2107     int to_char = 0;
2108     char *ti_value;
2109     char *tc_value;
2110     bool embedded;
2111
2112     if ((ti_value = _nc_tic_expand(value, TRUE, to_char)) == ABSENT_STRING) {
2113         _nc_warning("tic-expansion of %s failed", name);
2114     } else if ((tc_value = _nc_infotocap(name, ti_value, params)) == ABSENT_STRING) {
2115         _nc_warning("tic-conversion of %s failed", name);
2116     } else if (params > 0) {
2117         int limit = 5;
2118         int count;
2119         bool first = TRUE;
2120
2121         if (!strcmp(name, "setf")
2122             || !strcmp(name, "setb")
2123             || !strcmp(name, "setaf")
2124             || !strcmp(name, "setab")) {
2125             limit = max_colors;
2126         }
2127         for (count = 0; count < limit; ++count) {
2128             char *ti_check = check_1_infotocap(name, ti_value, count);
2129             char *tc_check = check_1_infotocap(name, tc_value, count);
2130
2131             if (strcmp(ti_check, tc_check)) {
2132                 if (first) {
2133                     fprintf(stderr, "check_infotocap(%s)\n", name);
2134                     fprintf(stderr, "...ti '%s'\n", ti_value);
2135                     fprintf(stderr, "...tc '%s'\n", tc_value);
2136                     first = FALSE;
2137                 }
2138                 _nc_warning("tparm-conversion of %s(%d) differs between\n\tterminfo %s\n\ttermcap  %s",
2139                             name, count, ti_check, tc_check);
2140             }
2141         }
2142     } else if (params == 0 && !same_ti_tc(ti_value, tc_value, &embedded)) {
2143         if (embedded) {
2144             _nc_warning("termcap equivalent of %s cannot use embedded delay", name);
2145         } else {
2146             _nc_warning("tic-conversion of %s changed value\n\tfrom %s\n\tto   %s",
2147                         name, ti_value, tc_value);
2148         }
2149     }
2150 }
2151
2152 static char *
2153 skip_delay(char *s)
2154 {
2155     while (*s == '/' || isdigit(UChar(*s)))
2156         ++s;
2157     return s;
2158 }
2159
2160 /*
2161  * Skip a delay altogether, e.g., when comparing a simple string to sgr,
2162  * the latter may have a worst-case delay on the end.
2163  */
2164 static char *
2165 ignore_delays(char *s)
2166 {
2167     int delaying = 0;
2168
2169     do {
2170         switch (*s) {
2171         case '$':
2172             if (delaying == 0)
2173                 delaying = 1;
2174             break;
2175         case '<':
2176             if (delaying == 1)
2177                 delaying = 2;
2178             break;
2179         case '\0':
2180             delaying = 0;
2181             break;
2182         default:
2183             if (delaying) {
2184                 s = skip_delay(s);
2185                 if (*s == '>')
2186                     ++s;
2187                 delaying = 0;
2188             }
2189             break;
2190         }
2191         if (delaying)
2192             ++s;
2193     } while (delaying);
2194     return s;
2195 }
2196
2197 #define DATA(name) { #name }
2198 static const char sgr_names[][11] =
2199 {
2200     DATA(none),
2201     DATA(standout),
2202     DATA(underline),
2203     DATA(reverse),
2204     DATA(blink),
2205     DATA(dim),
2206     DATA(bold),
2207     DATA(invis),
2208     DATA(protect),
2209     DATA(altcharset),
2210     ""
2211 };
2212 #undef DATA
2213
2214 /*
2215  * An sgr string may contain several settings other than the one we're
2216  * interested in, essentially sgr0 + rmacs + whatever.  As long as the
2217  * "whatever" is contained in the sgr string, that is close enough for our
2218  * sanity check.
2219  */
2220 static bool
2221 similar_sgr(int num, char *a, char *b)
2222 {
2223     char *base_a = a;
2224     char *base_b = b;
2225     int delaying = 0;
2226
2227     while (*b != 0) {
2228         while (*a != *b) {
2229             if (*a == 0) {
2230                 if (num < 0) {
2231                     ;
2232                 } else if (b[0] == '$'
2233                            && b[1] == '<') {
2234                     _nc_warning("Did not find delay %s", _nc_visbuf(b));
2235                 } else {
2236                     _nc_warning("checking sgr(%s) %s\n\tcompare to %s\n\tunmatched %s",
2237                                 sgr_names[num], _nc_visbuf2(1, base_a),
2238                                 _nc_visbuf2(2, base_b),
2239                                 _nc_visbuf2(3, b));
2240                 }
2241                 return FALSE;
2242             } else if (delaying) {
2243                 a = skip_delay(a);
2244                 b = skip_delay(b);
2245             } else if ((*b == '0' || (*b == ';')) && *a == 'm') {
2246                 b++;
2247             } else {
2248                 a++;
2249             }
2250         }
2251         switch (*a) {
2252         case '$':
2253             if (delaying == 0)
2254                 delaying = 1;
2255             break;
2256         case '<':
2257             if (delaying == 1)
2258                 delaying = 2;
2259             break;
2260         default:
2261             delaying = 0;
2262             break;
2263         }
2264         a++;
2265         b++;
2266     }
2267     /* ignore delays on the end of the string */
2268     a = ignore_delays(a);
2269     return ((num != 0) || (*a == 0));
2270 }
2271
2272 static char *
2273 check_sgr(TERMTYPE *tp, char *zero, int num, char *cap, const char *name)
2274 {
2275     char *test;
2276
2277     _nc_tparm_err = 0;
2278     test = TPARM_9(set_attributes,
2279                    num == 1,
2280                    num == 2,
2281                    num == 3,
2282                    num == 4,
2283                    num == 5,
2284                    num == 6,
2285                    num == 7,
2286                    num == 8,
2287                    num == 9);
2288     if (test != 0) {
2289         if (PRESENT(cap)) {
2290             if (!similar_sgr(num, test, cap)) {
2291                 _nc_warning("%s differs from sgr(%d)\n\t%s=%s\n\tsgr(%d)=%s",
2292                             name, num,
2293                             name, _nc_visbuf2(1, cap),
2294                             num, _nc_visbuf2(2, test));
2295             }
2296         } else if (_nc_capcmp(test, zero)) {
2297             _nc_warning("sgr(%d) present, but not %s", num, name);
2298         }
2299     } else if (PRESENT(cap)) {
2300         _nc_warning("sgr(%d) missing, but %s present", num, name);
2301     }
2302     if (_nc_tparm_err)
2303         _nc_warning("stack error in sgr(%d) string", num);
2304     return test;
2305 }
2306
2307 #define CHECK_SGR(num,name) check_sgr(tp, zero, num, name, #name)
2308
2309 #ifdef TRACE
2310 /*
2311  * If tic is compiled with TRACE, we'll be able to see the output from the
2312  * DEBUG() macro.  But since it doesn't use traceon(), it always goes to
2313  * the standard error.  Use this function to make it simpler to follow the
2314  * resulting debug traces.
2315  */
2316 static void
2317 show_where(unsigned level)
2318 {
2319     if (_nc_tracing >= DEBUG_LEVEL(level)) {
2320         char my_name[MAX_NAME_SIZE];
2321         _nc_get_type(my_name);
2322         _tracef("\"%s\", line %d, '%s'",
2323                 _nc_get_source(),
2324                 _nc_curr_line, my_name);
2325     }
2326 }
2327
2328 #else
2329 #define show_where(level)       /* nothing */
2330 #endif
2331
2332 typedef struct {
2333     int keycode;
2334     const char *name;
2335     const char *value;
2336 } NAME_VALUE;
2337
2338 static NAME_VALUE *
2339 get_fkey_list(TERMTYPE *tp)
2340 {
2341     NAME_VALUE *result = typeMalloc(NAME_VALUE, NUM_STRINGS(tp) + 1);
2342     const struct tinfo_fkeys *all_fkeys = _nc_tinfo_fkeys;
2343     int used = 0;
2344     unsigned j;
2345
2346     if (result == 0)
2347         failed("get_fkey_list");
2348
2349     for (j = 0; all_fkeys[j].code; j++) {
2350         char *a = tp->Strings[all_fkeys[j].offset];
2351         if (VALID_STRING(a)) {
2352             result[used].keycode = (int) all_fkeys[j].code;
2353             result[used].name = strnames[all_fkeys[j].offset];
2354             result[used].value = a;
2355             ++used;
2356         }
2357     }
2358 #if NCURSES_XNAMES
2359     for (j = STRCOUNT; j < NUM_STRINGS(tp); ++j) {
2360         const char *name = ExtStrname(tp, (int) j, strnames);
2361         if (*name == 'k') {
2362             result[used].keycode = -1;
2363             result[used].name = name;
2364             result[used].value = tp->Strings[j];
2365             ++used;
2366         }
2367     }
2368 #endif
2369     result[used].keycode = 0;
2370     return result;
2371 }
2372
2373 static void
2374 show_fkey_name(NAME_VALUE * data)
2375 {
2376     if (data->keycode > 0) {
2377         fprintf(stderr, " %s", keyname(data->keycode));
2378         fprintf(stderr, " (capability \"%s\")", data->name);
2379     } else {
2380         fprintf(stderr, " capability \"%s\"", data->name);
2381     }
2382 }
2383
2384 /*
2385  * A terminal entry may contain more than one keycode assigned to a given
2386  * string (e.g., KEY_END and KEY_LL).  But curses will only return one (the
2387  * last one assigned).
2388  */
2389 static void
2390 check_conflict(TERMTYPE *tp)
2391 {
2392     bool conflict = FALSE;
2393     unsigned j, k;
2394
2395     if (!(_nc_syntax == SYN_TERMCAP && capdump)) {
2396         char *check = calloc((size_t) (NUM_STRINGS(tp) + 1), sizeof(char));
2397         NAME_VALUE *given = get_fkey_list(tp);
2398
2399         if (check == 0)
2400             failed("check_termtype");
2401
2402         for (j = 0; given[j].keycode; ++j) {
2403             const char *a = given[j].value;
2404             bool first = TRUE;
2405
2406             for (k = j + 1; given[k].keycode; k++) {
2407                 const char *b = given[k].value;
2408                 if (check[k])
2409                     continue;
2410                 if (!_nc_capcmp(a, b)) {
2411                     check[j] = 1;
2412                     check[k] = 1;
2413                     if (first) {
2414                         if (!conflict) {
2415                             _nc_warning("Conflicting key definitions (using the last)");
2416                             conflict = TRUE;
2417                         }
2418                         fprintf(stderr, "...");
2419                         show_fkey_name(given + j);
2420                         fprintf(stderr, " is the same as");
2421                         show_fkey_name(given + k);
2422                         first = FALSE;
2423                     } else {
2424                         fprintf(stderr, ", ");
2425                         show_fkey_name(given + k);
2426                     }
2427                 }
2428             }
2429             if (!first)
2430                 fprintf(stderr, "\n");
2431         }
2432         free(given);
2433         free(check);
2434     }
2435 }
2436
2437 /*
2438  * Exiting a video mode should not duplicate sgr0
2439  */
2440 static void
2441 check_exit_attribute(const char *name, char *test, char *trimmed, char *untrimmed)
2442 {
2443     if (VALID_STRING(test) && (trimmed != 0)) {
2444         if (similar_sgr(-1, trimmed, test) ||
2445             similar_sgr(-1, untrimmed, test)) {
2446             _nc_warning("%s matches exit_attribute_mode", name);
2447         }
2448     }
2449 }
2450
2451 /*
2452  * Returns true if the string looks like a standard SGR string.
2453  */
2454 static bool
2455 is_sgr_string(char *value)
2456 {
2457     bool result = FALSE;
2458
2459     if (VALID_STRING(value)) {
2460         int skip = csi_length(value);
2461
2462         if (skip) {
2463             int ch;
2464
2465             result = TRUE;
2466             value += skip;
2467             while ((ch = UChar(*value++)) != '\0') {
2468                 if (isdigit(ch) || ch == ';') {
2469                     ;
2470                 } else if (ch == 'm' && *value == '\0') {
2471                     ;
2472                 } else {
2473                     result = FALSE;
2474                     break;
2475                 }
2476             }
2477         }
2478     }
2479     return result;
2480 }
2481
2482 /*
2483  * Check if the given capability contains a given SGR attribute.
2484  */
2485 static void
2486 check_sgr_param(TERMTYPE *tp, int code, const char *name, char *value)
2487 {
2488     if (VALID_STRING(value)) {
2489         int ncv = ((code != 0) ? (1 << (code - 1)) : 0);
2490         char *test = tgoto(value, 0, 0);
2491         if (is_sgr_string(test)) {
2492             int param = 0;
2493             int count = 0;
2494             int skips = 0;
2495             int color = (value == set_a_foreground ||
2496                          value == set_a_background ||
2497                          value == set_foreground ||
2498                          value == set_background);
2499             while (*test != 0) {
2500                 if (isdigit(UChar(*test))) {
2501                     param = 10 * param + (*test - '0');
2502                     ++count;
2503                 } else {
2504                     if (count) {
2505                         /*
2506                          * Avoid unnecessary warning for xterm 256color codes.
2507                          */
2508                         if (color && (param == 38 || param == 48))
2509                             skips = 3;
2510                         if ((skips-- <= 0) && (param == code))
2511                             break;
2512                     }
2513                     count = 0;
2514                     param = 0;
2515                 }
2516                 ++test;
2517             }
2518             if (count != 0 && param == code) {
2519                 if (code == 0 ||
2520                     no_color_video < 0 ||
2521                     !(no_color_video & ncv)) {
2522                     _nc_warning("\"%s\" SGR-attribute used in %s",
2523                                 sgr_names[code],
2524                                 name);
2525                 }
2526             }
2527         }
2528     }
2529 }
2530
2531 /* other sanity-checks (things that we don't want in the normal
2532  * logic that reads a terminfo entry)
2533  */
2534 static void
2535 check_termtype(TERMTYPE *tp, bool literal)
2536 {
2537     unsigned j;
2538
2539     check_conflict(tp);
2540
2541     for_each_string(j, tp) {
2542         char *a = tp->Strings[j];
2543         if (VALID_STRING(a)) {
2544             check_params(tp, ExtStrname(tp, (int) j, strnames), a);
2545             check_delays(ExtStrname(tp, (int) j, strnames), a);
2546             if (capdump) {
2547                 check_infotocap(tp, (int) j, a);
2548             }
2549         }
2550     }
2551
2552     check_acs(tp);
2553     check_colors(tp);
2554     check_cursor(tp);
2555     check_keypad(tp);
2556     check_printer(tp);
2557     check_screen(tp);
2558
2559     /*
2560      * These may be mismatched because the terminal description relies on
2561      * restoring the cursor visibility by resetting it.
2562      */
2563     ANDMISSING(cursor_invisible, cursor_normal);
2564     ANDMISSING(cursor_visible, cursor_normal);
2565
2566     if (PRESENT(cursor_visible) && PRESENT(cursor_normal)
2567         && !_nc_capcmp(cursor_visible, cursor_normal))
2568         _nc_warning("cursor_visible is same as cursor_normal");
2569
2570     /*
2571      * From XSI & O'Reilly, we gather that sc/rc are required if csr is
2572      * given, because the cursor position after the scrolling operation is
2573      * performed is undefined.
2574      */
2575     ANDMISSING(change_scroll_region, save_cursor);
2576     ANDMISSING(change_scroll_region, restore_cursor);
2577
2578     /*
2579      * If we can clear tabs, we should be able to initialize them.
2580      */
2581     ANDMISSING(clear_all_tabs, set_tab);
2582
2583     if (PRESENT(set_attributes)) {
2584         char *zero = 0;
2585
2586         _nc_tparm_err = 0;
2587         if (PRESENT(exit_attribute_mode)) {
2588             zero = strdup(CHECK_SGR(0, exit_attribute_mode));
2589         } else {
2590             zero = strdup(TPARM_9(set_attributes, 0, 0, 0, 0, 0, 0, 0, 0, 0));
2591         }
2592         if (_nc_tparm_err)
2593             _nc_warning("stack error in sgr(0) string");
2594
2595         if (zero != 0) {
2596             CHECK_SGR(1, enter_standout_mode);
2597             CHECK_SGR(2, enter_underline_mode);
2598             CHECK_SGR(3, enter_reverse_mode);
2599             CHECK_SGR(4, enter_blink_mode);
2600             CHECK_SGR(5, enter_dim_mode);
2601             CHECK_SGR(6, enter_bold_mode);
2602             CHECK_SGR(7, enter_secure_mode);
2603             CHECK_SGR(8, enter_protected_mode);
2604             CHECK_SGR(9, enter_alt_charset_mode);
2605             free(zero);
2606         } else {
2607             _nc_warning("sgr(0) did not return a value");
2608         }
2609     } else if (PRESENT(exit_attribute_mode) &&
2610                set_attributes != CANCELLED_STRING) {
2611         if (_nc_syntax == SYN_TERMINFO)
2612             _nc_warning("missing sgr string");
2613     }
2614 #define CHECK_SGR0(name) check_exit_attribute(#name, name, check_sgr0, exit_attribute_mode)
2615     if (PRESENT(exit_attribute_mode)) {
2616         char *check_sgr0 = _nc_trim_sgr0(tp);
2617
2618         if (check_sgr0 == 0 || *check_sgr0 == '\0') {
2619             _nc_warning("trimmed sgr0 is empty");
2620         } else {
2621             show_where(2);
2622             if (check_sgr0 != exit_attribute_mode) {
2623                 DEBUG(2,
2624                       ("will trim sgr0\n\toriginal sgr0=%s\n\ttrimmed  sgr0=%s",
2625                        _nc_visbuf2(1, exit_attribute_mode),
2626                        _nc_visbuf2(2, check_sgr0)));
2627             } else {
2628                 DEBUG(2,
2629                       ("will not trim sgr0\n\toriginal sgr0=%s",
2630                        _nc_visbuf(exit_attribute_mode)));
2631             }
2632         }
2633         CHECK_SGR0(exit_italics_mode);
2634         CHECK_SGR0(exit_standout_mode);
2635         CHECK_SGR0(exit_underline_mode);
2636         if (check_sgr0 != exit_attribute_mode) {
2637             free(check_sgr0);
2638         }
2639     }
2640 #define CHECK_SGR_PARAM(code, name) check_sgr_param(tp, (int)code, #name, name)
2641     for (j = 0; *sgr_names[j] != '\0'; ++j) {
2642         CHECK_SGR_PARAM(j, set_a_foreground);
2643         CHECK_SGR_PARAM(j, set_a_background);
2644         CHECK_SGR_PARAM(j, set_foreground);
2645         CHECK_SGR_PARAM(j, set_background);
2646     }
2647 #ifdef TRACE
2648     show_where(2);
2649     if (!auto_right_margin) {
2650         DEBUG(2,
2651               ("can write to lower-right directly"));
2652     } else if (PRESENT(enter_am_mode) && PRESENT(exit_am_mode)) {
2653         DEBUG(2,
2654               ("can write to lower-right by suppressing automargin"));
2655     } else if ((PRESENT(enter_insert_mode) && PRESENT(exit_insert_mode))
2656                || PRESENT(insert_character) || PRESENT(parm_ich)) {
2657         DEBUG(2,
2658               ("can write to lower-right by using inserts"));
2659     } else {
2660         DEBUG(2,
2661               ("cannot write to lower-right"));
2662     }
2663 #endif
2664
2665     /*
2666      * Some standard applications (e.g., vi) and some non-curses
2667      * applications (e.g., jove) get confused if we have both ich1 and
2668      * smir/rmir.  Let's be nice and warn about that, too, even though
2669      * ncurses handles it.
2670      */
2671     if ((PRESENT(enter_insert_mode) || PRESENT(exit_insert_mode))
2672         && PRESENT(parm_ich)) {
2673         _nc_warning("non-curses applications may be confused by ich1 with smir/rmir");
2674     }
2675
2676     /*
2677      * Finally, do the non-verbose checks
2678      */
2679     if (save_check_termtype != 0)
2680         save_check_termtype(tp, literal);
2681 }