]> ncurses.scripts.mit.edu Git - ncurses.git/blob - progs/tic.c
ncurses 6.3 - patch 20220917
[ncurses.git] / progs / tic.c
1 /****************************************************************************
2  * Copyright 2018-2021,2022 Thomas E. Dickey                                *
3  * Copyright 1998-2017,2018 Free Software Foundation, Inc.                  *
4  *                                                                          *
5  * Permission is hereby granted, free of charge, to any person obtaining a  *
6  * copy of this software and associated documentation files (the            *
7  * "Software"), to deal in the Software without restriction, including      *
8  * without limitation the rights to use, copy, modify, merge, publish,      *
9  * distribute, distribute with modifications, sublicense, and/or sell       *
10  * copies of the Software, and to permit persons to whom the Software is    *
11  * furnished to do so, subject to the following conditions:                 *
12  *                                                                          *
13  * The above copyright notice and this permission notice shall be included  *
14  * in all copies or substantial portions of the Software.                   *
15  *                                                                          *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS  *
17  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF               *
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.   *
19  * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,   *
20  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR    *
21  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR    *
22  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.                               *
23  *                                                                          *
24  * Except as contained in this notice, the name(s) of the above copyright   *
25  * holders shall not be used in advertising or otherwise to promote the     *
26  * sale, use or other dealings in this Software without prior written       *
27  * authorization.                                                           *
28  ****************************************************************************/
29
30 /****************************************************************************
31  *  Author: Zeyd M. Ben-Halim <zmbenhal@netcom.com> 1992,1995               *
32  *     and: Eric S. Raymond <esr@snark.thyrsus.com>                         *
33  *     and: Thomas E. Dickey                        1996 on                 *
34  ****************************************************************************/
35
36 /*
37  *      tic.c --- Main program for terminfo compiler
38  *                      by Eric S. Raymond
39  *                      and Thomas E Dickey
40  *
41  */
42
43 #include <progs.priv.h>
44 #include <sys/stat.h>
45
46 #include <dump_entry.h>
47 #include <tparm_type.h>
48 #include <hashed_db.h>
49 #include <parametrized.h>
50 #include <transform.h>
51
52 MODULE_ID("$Id: tic.c,v 1.320 2022/09/17 18:55:28 tom Exp $")
53
54 #define STDIN_NAME "<stdin>"
55
56 const char *_nc_progname = "tic";
57
58 static FILE *log_fp;
59 static FILE *tmp_fp;
60 static bool capdump = FALSE;    /* running as infotocap? */
61 static bool infodump = FALSE;   /* running as captoinfo? */
62 static bool showsummary = FALSE;
63 static unsigned debug_level;
64 static char **namelst = 0;
65 static const char *to_remove;
66
67 #if NCURSES_XNAMES
68 static bool using_extensions = FALSE;
69 #endif
70
71 static void (*save_check_termtype) (TERMTYPE2 *, bool);
72 static void check_termtype(TERMTYPE2 *tt, bool);
73
74 static const char usage_string[] = "\
75 [-e names] \
76 [-o dir] \
77 [-R name] \
78 [-v[n]] \
79 [-V] \
80 [-w[n]] \
81 [-\
82 1\
83 a\
84 C\
85 D\
86 c\
87 f\
88 G\
89 g\
90 I\
91 K\
92 L\
93 N\
94 r\
95 s\
96 T\
97 t\
98 U\
99 x\
100 ] \
101 source-file\n";
102
103 #if NO_LEAKS
104 static void
105 free_namelist(char **src)
106 {
107     if (src != 0) {
108         int n;
109         for (n = 0; src[n] != 0; ++n)
110             free(src[n]);
111         free(src);
112     }
113 }
114 #endif
115
116 static void
117 cleanup(void)
118 {
119 #if NO_LEAKS
120     free_namelist(namelst);
121     _nc_leaks_dump_entry();
122 #endif
123     if (tmp_fp != 0)
124         fclose(tmp_fp);
125     if (to_remove != 0) {
126         int rc;
127
128 #if HAVE_REMOVE
129         rc = remove(to_remove);
130 #else
131         rc = unlink(to_remove);
132 #endif
133         if (rc != 0)
134             perror(to_remove);
135     }
136 }
137
138 static void
139 failed(const char *msg)
140 {
141     perror(msg);
142     ExitProgram(EXIT_FAILURE);
143 }
144
145 static void
146 usage(void)
147 {
148 #define DATA(s) s "\n"
149     static const char options_string[] =
150     {
151         DATA("Options:")
152         DATA("  -0         format translation output all capabilities on one line")
153         DATA("  -1         format translation output one capability per line")
154 #if NCURSES_XNAMES
155         DATA("  -a         retain commented-out capabilities (sets -x also)")
156 #endif
157         DATA("  -C         translate entries to termcap source form")
158         DATA("  -D         print list of tic's database locations (first must be writable)")
159         DATA("  -c         check only, validate input without compiling or translating")
160         DATA("  -e<names>  translate/compile only entries named by comma-separated list")
161         DATA("  -f         format complex strings for readability")
162         DATA("  -G         format %{number} to %'char'")
163         DATA("  -g         format %'char' to %{number}")
164         DATA("  -I         translate entries to terminfo source form")
165         DATA("  -K         translate entries to termcap source form with BSD syntax")
166         DATA("  -L         translate entries to full terminfo source form")
167         DATA("  -N         disable smart defaults for source translation")
168         DATA("  -o<dir>    set output directory for compiled entry writes")
169         DATA("  -Q[n]      dump compiled description")
170         DATA("  -q    brief listing, removes headers")
171         DATA("  -R<name>   restrict translation to given terminfo/termcap version")
172         DATA("  -r         force resolution of all use entries in source translation")
173         DATA("  -s         print summary statistics")
174         DATA("  -T         remove size-restrictions on compiled description")
175 #if NCURSES_XNAMES
176         DATA("  -t         suppress commented-out capabilities")
177 #endif
178         DATA("  -U         suppress post-processing of entries")
179         DATA("  -V         print version")
180         DATA("  -W         wrap long strings according to -w[n] option")
181         DATA("  -v[n]      set verbosity level")
182         DATA("  -w[n]      set format width for translation output")
183 #if NCURSES_XNAMES
184         DATA("  -x         treat unknown capabilities as user-defined")
185 #endif
186         DATA("")
187         DATA("Parameters:")
188         DATA("  <file>     file to translate or compile")
189     };
190 #undef DATA
191
192     fprintf(stderr, "Usage: %s %s\n", _nc_progname, usage_string);
193     fputs(options_string, stderr);
194     ExitProgram(EXIT_FAILURE);
195 }
196
197 #define L_BRACE '{'
198 #define R_BRACE '}'
199 #define S_QUOTE '\''
200
201 static void
202 write_it(ENTRY * ep)
203 {
204     unsigned n;
205     int ch;
206     char *s, *d, *t;
207     char result[MAX_ENTRY_SIZE];
208
209     /*
210      * Look for strings that contain %{number}, convert them to %'char',
211      * which is shorter and runs a little faster.
212      */
213     for (n = 0; n < STRCOUNT; n++) {
214         s = ep->tterm.Strings[n];
215         if (VALID_STRING(s)
216             && strchr(s, L_BRACE) != 0) {
217             d = result;
218             t = s;
219             while ((ch = *t++) != 0) {
220                 *d++ = (char) ch;
221                 if (ch == '\\') {
222                     if ((*d++ = *t++) == '\0')
223                         break;
224                 } else if ((ch == '%')
225                            && (*t == L_BRACE)) {
226                     char *v = 0;
227                     long value = strtol(t + 1, &v, 0);
228                     if (v != 0
229                         && *v == R_BRACE
230                         && value > 0
231                         && value != '\\'        /* FIXME */
232                         && value < 127
233                         && isprint((int) value)) {
234                         *d++ = S_QUOTE;
235                         *d++ = (char) value;
236                         *d++ = S_QUOTE;
237                         t = (v + 1);
238                     }
239                 }
240             }
241             *d = 0;
242             if (strlen(result) < strlen(s))
243                 _nc_STRCPY(s, result, strlen(s) + 1);
244         }
245     }
246
247     _nc_set_type(_nc_first_name(ep->tterm.term_names));
248     _nc_curr_line = (int) ep->startline;
249     _nc_write_entry(&ep->tterm);
250 }
251
252 static bool
253 immedhook(ENTRY * ep GCC_UNUSED)
254 /* write out entries with no use capabilities immediately to save storage */
255 {
256 #if !HAVE_BIG_CORE
257     /*
258      * This is strictly a core-economy kluge.  The really clean way to handle
259      * compilation is to slurp the whole file into core and then do all the
260      * name-collision checks and entry writes in one swell foop.  But the
261      * terminfo master file is large enough that some core-poor systems swap
262      * like crazy when you compile it this way...there have been reports of
263      * this process taking *three hours*, rather than the twenty seconds or
264      * less typical on my development box.
265      *
266      * So.  This hook *immediately* writes out the referenced entry if it
267      * has no use capabilities.  The compiler main loop refrains from
268      * adding the entry to the in-core list when this hook fires.  If some
269      * other entry later needs to reference an entry that got written
270      * immediately, that's OK; the resolution code will fetch it off disk
271      * when it can't find it in core.
272      *
273      * Name collisions will still be detected, just not as cleanly.  The
274      * write_entry() code complains before overwriting an entry that
275      * postdates the time of tic's first call to write_entry().  Thus
276      * it will complain about overwriting entries newly made during the
277      * tic run, but not about overwriting ones that predate it.
278      *
279      * The reason this is a hook, and not in line with the rest of the
280      * compiler code, is that the support for termcap fallback cannot assume
281      * it has anywhere to spool out these entries!
282      *
283      * The _nc_set_type() call here requires a compensating one in
284      * _nc_parse_entry().
285      *
286      * If you define HAVE_BIG_CORE, you'll disable this kluge.  This will
287      * make tic a bit faster (because the resolution code won't have to do
288      * disk I/O nearly as often).
289      */
290     if (ep->nuses == 0) {
291         int oldline = _nc_curr_line;
292
293         write_it(ep);
294         _nc_curr_line = oldline;
295         free(ep->tterm.str_table);
296         return (TRUE);
297     }
298 #endif /* HAVE_BIG_CORE */
299     return (FALSE);
300 }
301
302 static void
303 put_translate(int c)
304 /* emit a comment char, translating terminfo names to termcap names */
305 {
306     static bool in_name = FALSE;
307     static size_t used;
308
309     if (in_name) {
310         static size_t have;
311         static char *namebuf, *suffix;
312
313         if (used + 1 >= have) {
314             have += 132;
315             if ((namebuf = typeRealloc(char, have, namebuf)) == NULL)
316                   failed("put_translate namebuf");
317             if ((suffix = typeRealloc(char, have, suffix)) == NULL)
318                   failed("put_translate suffix");
319         }
320         if (c == '\n' || c == '@') {
321             namebuf[used++] = '\0';
322             (void) putchar('<');
323             (void) fputs(namebuf, stdout);
324             putchar(c);
325             in_name = FALSE;
326         } else if (c != '>') {
327             namebuf[used++] = (char) c;
328         } else {                /* ah! candidate name! */
329             char *up;
330             NCURSES_CONST char *tp;
331
332             namebuf[used++] = '\0';
333             in_name = FALSE;
334
335             suffix[0] = '\0';
336             if ((up = strchr(namebuf, '#')) != 0
337                 || (up = strchr(namebuf, '=')) != 0
338                 || ((up = strchr(namebuf, '@')) != 0 && up[1] == '>')) {
339                 _nc_STRCPY(suffix, up, have);
340                 *up = '\0';
341             }
342
343             if ((tp = nametrans(namebuf)) != 0) {
344                 (void) putchar(':');
345                 (void) fputs(tp, stdout);
346                 (void) fputs(suffix, stdout);
347                 (void) putchar(':');
348             } else {
349                 /* couldn't find a translation, just dump the name */
350                 (void) putchar('<');
351                 (void) fputs(namebuf, stdout);
352                 (void) fputs(suffix, stdout);
353                 (void) putchar('>');
354             }
355         }
356     } else {
357         used = 0;
358         if (c == '<') {
359             in_name = TRUE;
360         } else {
361             putchar(c);
362         }
363     }
364 }
365
366 /* Returns a string, stripped of leading/trailing whitespace */
367 static char *
368 stripped(char *src)
369 {
370     char *dst = 0;
371
372     while (isspace(UChar(*src)))
373         src++;
374
375     if (*src != '\0') {
376         if ((dst = strdup(src)) == NULL) {
377             failed("strdup");
378         } else {
379             size_t len = strlen(dst);
380             while (--len != 0 && isspace(UChar(dst[len])))
381                 dst[len] = '\0';
382         }
383     }
384     return dst;
385 }
386
387 static FILE *
388 open_tempfile(char *filename)
389 {
390     FILE *result = 0;
391
392     _nc_STRCPY(filename, "/tmp/XXXXXX", PATH_MAX);
393 #if HAVE_MKSTEMP
394     {
395         int oldmask = (int) umask(077);
396         int fd = mkstemp(filename);
397         if (fd >= 0)
398             result = fdopen(fd, "w");
399         umask((mode_t) oldmask);
400     }
401 #else
402     if (tmpnam(filename) != 0)
403         result = safe_fopen(filename, "w");
404 #endif
405     return result;
406 }
407
408 static FILE *
409 copy_input(FILE *source, const char *filename, char *alt_file)
410 {
411     char my_altfile[PATH_MAX];
412     FILE *result = 0;
413     FILE *target;
414     int ch;
415
416     if (alt_file == NULL)
417         alt_file = my_altfile;
418
419     if (source == NULL) {
420         failed("copy_input (source)");
421     } else if ((target = open_tempfile(alt_file)) == NULL) {
422         failed("copy_input (target)");
423     } else {
424         clearerr(source);
425         for (;;) {
426             ch = fgetc(source);
427             if (feof(source)) {
428                 break;
429             } else if (ferror(source)) {
430                 failed(filename);
431             } else if (ch == 0) {
432                 /* don't loop in case someone wants to convert /dev/zero */
433                 fprintf(stderr, "%s: %s is not a text-file\n", _nc_progname, filename);
434                 ExitProgram(EXIT_FAILURE);
435             }
436             fputc(ch, target);
437         }
438         fclose(source);
439         /*
440          * rewind() does not force the target file's data to disk (not does
441          * fflush()...).  So open a second stream on the data and then close
442          * the one that we were writing on before starting to read from the
443          * second stream.
444          */
445         result = safe_fopen(alt_file, "r+");
446         fclose(target);
447         to_remove = strdup(alt_file);
448     }
449     return result;
450 }
451
452 static FILE *
453 open_input(const char *filename, char *alt_file)
454 {
455     FILE *fp;
456     struct stat sb;
457     int mode;
458
459     if (!strcmp(filename, "-")) {
460         fp = copy_input(stdin, STDIN_NAME, alt_file);
461     } else if (stat(filename, &sb) == -1) {
462         fprintf(stderr, "%s: %s %s\n", _nc_progname, filename, strerror(errno));
463         ExitProgram(EXIT_FAILURE);
464     } else if ((mode = (sb.st_mode & S_IFMT)) == S_IFDIR
465                || (mode != S_IFREG && mode != S_IFCHR && mode != S_IFIFO)) {
466         fprintf(stderr, "%s: %s is not a file\n", _nc_progname, filename);
467         ExitProgram(EXIT_FAILURE);
468     } else {
469         fp = safe_fopen(filename, "r");
470
471         if (fp == NULL) {
472             fprintf(stderr, "%s: Can't open %s\n", _nc_progname, filename);
473             ExitProgram(EXIT_FAILURE);
474         }
475         if (mode != S_IFREG) {
476             if (alt_file != 0) {
477                 FILE *fp2 = copy_input(fp, filename, alt_file);
478                 fp = fp2;
479             } else {
480                 fprintf(stderr, "%s: %s is not a file\n", _nc_progname, filename);
481                 ExitProgram(EXIT_FAILURE);
482             }
483         }
484     }
485     return fp;
486 }
487
488 /* Parse the "-e" option-value into a list of names */
489 static char **
490 make_namelist(char *src)
491 {
492     char **dst = 0;
493
494     char *s, *base;
495     unsigned pass, n, nn;
496     char buffer[BUFSIZ];
497
498     if (src == NULL) {
499         /* EMPTY */ ;
500     } else if (strchr(src, '/') != 0) {         /* a filename */
501         FILE *fp = open_input(src, (char *) 0);
502
503         for (pass = 1; pass <= 2; pass++) {
504             nn = 0;
505             while (fgets(buffer, sizeof(buffer), fp) != 0) {
506                 if ((s = stripped(buffer)) != 0) {
507                     if (dst != 0)
508                         dst[nn] = s;
509                     else
510                         free(s);
511                     nn++;
512                 }
513             }
514             if (pass == 1) {
515                 if ((dst = typeCalloc(char *, nn + 1)) == NULL)
516                       failed("make_namelist");
517                 rewind(fp);
518             }
519         }
520         fclose(fp);
521     } else {                    /* literal list of names */
522         for (pass = 1; pass <= 2; pass++) {
523             for (n = nn = 0, base = src;; n++) {
524                 int mark = src[n];
525                 if (mark == ',' || mark == '\0') {
526                     if (pass == 1) {
527                         nn++;
528                     } else {
529                         src[n] = '\0';
530                         if ((s = stripped(base)) != 0)
531                             dst[nn++] = s;
532                         base = &src[n + 1];
533                     }
534                 }
535                 if (mark == '\0')
536                     break;
537             }
538             if (pass == 1) {
539                 if ((dst = typeCalloc(char *, nn + 1)) == NULL)
540                       failed("make_namelist");
541             }
542         }
543     }
544     if (showsummary && (dst != 0)) {
545         fprintf(log_fp, "Entries that will be compiled:\n");
546         for (n = 0; dst[n] != 0; n++)
547             fprintf(log_fp, "%u:%s\n", n + 1, dst[n]);
548     }
549     return dst;
550 }
551
552 static bool
553 matches(char **needle, const char *haystack)
554 /* does entry in needle list match |-separated field in haystack? */
555 {
556     bool code = FALSE;
557
558     if (needle != 0) {
559         size_t n;
560
561         for (n = 0; needle[n] != 0; n++) {
562             if (_nc_name_match(haystack, needle[n], "|")) {
563                 code = TRUE;
564                 break;
565             }
566         }
567     } else
568         code = TRUE;
569     return (code);
570 }
571
572 static char *
573 valid_db_path(const char *nominal)
574 {
575     struct stat sb;
576 #if USE_HASHED_DB
577     char suffix[] = DBM_SUFFIX;
578     size_t need = strlen(nominal) + sizeof(suffix);
579     char *result = malloc(need);
580
581     if (result == NULL)
582         failed("valid_db_path");
583     _nc_STRCPY(result, nominal, need);
584     if (strcmp(result + need - sizeof(suffix), suffix)) {
585         _nc_STRCAT(result, suffix, need);
586     }
587 #else
588     char *result = strdup(nominal);
589 #endif
590
591     DEBUG(1, ("** stat(%s)", result));
592     if (stat(result, &sb) >= 0) {
593 #if USE_HASHED_DB
594         if (!S_ISREG(sb.st_mode)
595             || access(result, R_OK | W_OK) != 0) {
596             DEBUG(1, ("...not a writable file"));
597             free(result);
598             result = 0;
599         }
600 #else
601         if (!S_ISDIR(sb.st_mode)
602             || access(result, R_OK | W_OK | X_OK) != 0) {
603             DEBUG(1, ("...not a writable directory"));
604             free(result);
605             result = 0;
606         }
607 #endif
608     } else {
609         /* check if parent is directory and is writable */
610         unsigned leaf = _nc_pathlast(result);
611
612         DEBUG(1, ("...not found"));
613         if (leaf) {
614             char save = result[leaf];
615             result[leaf] = 0;
616             if (stat(result, &sb) >= 0
617                 && S_ISDIR(sb.st_mode)
618                 && access(result, R_OK | W_OK | X_OK) == 0) {
619                 result[leaf] = save;
620             } else {
621                 DEBUG(1, ("...parent directory %s is not writable", result));
622                 free(result);
623                 result = 0;
624             }
625         } else {
626             DEBUG(1, ("... no parent directory"));
627             free(result);
628             result = 0;
629         }
630     }
631     return result;
632 }
633
634 /*
635  * Show the databases to which tic could write.  The location to which it
636  * writes is always the first one.  If none are writable, print an error
637  * message.
638  */
639 static void
640 show_databases(const char *outdir)
641 {
642     bool specific = (outdir != 0) || getenv("TERMINFO") != 0;
643     char *result;
644     const char *tried = 0;
645
646     if (outdir == NULL) {
647         outdir = _nc_tic_dir(NULL);
648     }
649     if ((result = valid_db_path(outdir)) != 0) {
650         printf("%s\n", result);
651         free(result);
652     } else {
653         tried = outdir;
654     }
655
656     if ((outdir = _nc_home_terminfo())) {
657         if ((result = valid_db_path(outdir)) != 0) {
658             printf("%s\n", result);
659             free(result);
660         } else if (!specific) {
661             tried = outdir;
662         }
663     }
664
665     /*
666      * If we can write in neither location, give an error message.
667      */
668     if (tried) {
669         fflush(stdout);
670         fprintf(stderr, "%s: %s (no permission)\n", _nc_progname, tried);
671         ExitProgram(EXIT_FAILURE);
672     }
673 }
674
675 static void
676 add_digit(int *target, int source)
677 {
678     *target = (*target * 10) + (source - '0');
679 }
680
681 int
682 main(int argc, char *argv[])
683 {
684     char my_tmpname[PATH_MAX];
685     int v_opt = -1;
686     int smart_defaults = TRUE;
687     char *termcap;
688     ENTRY *qp;
689
690     int this_opt, last_opt = '?';
691
692     int outform = F_TERMINFO;   /* output format */
693     int sortmode = S_TERMINFO;  /* sort_mode */
694
695     int width = 60;
696     int height = 65535;
697     bool formatted = FALSE;     /* reformat complex strings? */
698     bool literal = FALSE;       /* suppress post-processing? */
699     int numbers = 0;            /* format "%'char'" to/from "%{number}" */
700     bool forceresolve = FALSE;  /* force resolution */
701     bool limited = TRUE;
702     char *tversion = (char *) NULL;
703     const char *source_file = "terminfo";
704     char *outdir = (char *) NULL;
705     bool check_only = FALSE;
706     bool suppress_untranslatable = FALSE;
707     int quickdump = 0;
708     bool quiet = FALSE;
709     bool wrap_strings = FALSE;
710
711     log_fp = stderr;
712
713     _nc_progname = _nc_rootname(argv[0]);
714     atexit(cleanup);
715
716     if ((infodump = same_program(_nc_progname, PROG_CAPTOINFO)) != FALSE) {
717         outform = F_TERMINFO;
718         sortmode = S_TERMINFO;
719     }
720     if ((capdump = same_program(_nc_progname, PROG_INFOTOCAP)) != FALSE) {
721         outform = F_TERMCAP;
722         sortmode = S_TERMCAP;
723     }
724 #if NCURSES_XNAMES
725     /* set this directly to avoid interaction with -v and -D options */
726     _nc_user_definable = FALSE;
727 #endif
728     _nc_strict_bsd = 0;
729
730     /*
731      * Processing arguments is a little complicated, since someone made a
732      * design decision to allow the numeric values for -w, -v options to
733      * be optional.
734      */
735     while ((this_opt = getopt(argc, argv,
736                               "0123456789CDIKLNQR:TUVWace:fGgo:qrstvwx")) != -1) {
737         if (isdigit(this_opt)) {
738             switch (last_opt) {
739             case 'Q':
740                 add_digit(&quickdump, this_opt);
741                 break;
742             case 'v':
743                 add_digit(&v_opt, this_opt);
744                 break;
745             case 'w':
746                 add_digit(&width, this_opt);
747                 break;
748             default:
749                 switch (this_opt) {
750                 case '0':
751                     last_opt = this_opt;
752                     width = 65535;
753                     height = 1;
754                     break;
755                 case '1':
756                     last_opt = this_opt;
757                     width = 0;
758                     break;
759                 default:
760                     usage();
761                 }
762             }
763             continue;
764         }
765         switch (this_opt) {
766         case 'K':
767             _nc_strict_bsd = 1;
768             /* the initial version of -K in 20110730 fell-thru here, but the
769              * same flag is useful when reading sources -TD
770              */
771             break;
772         case 'C':
773             capdump = TRUE;
774             outform = F_TERMCAP;
775             sortmode = S_TERMCAP;
776             break;
777         case 'D':
778             debug_level = VtoTrace(v_opt);
779             use_verbosity(debug_level);
780             show_databases(outdir);
781             ExitProgram(EXIT_SUCCESS);
782             break;
783         case 'I':
784             infodump = TRUE;
785             outform = F_TERMINFO;
786             sortmode = S_TERMINFO;
787             break;
788         case 'L':
789             infodump = TRUE;
790             outform = F_VARIABLE;
791             sortmode = S_VARIABLE;
792             break;
793         case 'N':
794             smart_defaults = FALSE;
795             literal = TRUE;
796             break;
797         case 'Q':
798             quickdump = 0;
799             break;
800         case 'R':
801             tversion = optarg;
802             break;
803         case 'T':
804             limited = FALSE;
805             break;
806         case 'U':
807             literal = TRUE;
808             break;
809         case 'V':
810             puts(curses_version());
811             ExitProgram(EXIT_SUCCESS);
812         case 'W':
813             wrap_strings = TRUE;
814             break;
815         case 'c':
816             check_only = TRUE;
817             break;
818         case 'e':
819             namelst = make_namelist(optarg);
820             break;
821         case 'f':
822             formatted = TRUE;
823             break;
824         case 'G':
825             numbers = 1;
826             break;
827         case 'g':
828             numbers = -1;
829             break;
830         case 'o':
831             outdir = optarg;
832             break;
833         case 'q':
834             quiet = TRUE;
835             break;
836         case 'r':
837             forceresolve = TRUE;
838             break;
839         case 's':
840             showsummary = TRUE;
841             break;
842         case 'v':
843             v_opt = 0;
844             break;
845         case 'w':
846             width = 0;
847             break;
848 #if NCURSES_XNAMES
849         case 't':
850             _nc_disable_period = FALSE;
851             suppress_untranslatable = TRUE;
852             break;
853         case 'a':
854             _nc_disable_period = TRUE;
855             /* FALLTHRU */
856         case 'x':
857             using_extensions = TRUE;
858             break;
859 #endif
860         default:
861             usage();
862         }
863         last_opt = this_opt;
864     }
865
866     /*
867      * If the -v option is set, it may override the $NCURSES_TRACE environment
868      * variable, e.g., for -v3 and up.
869      */
870     debug_level = VtoTrace(v_opt);
871     use_verbosity(debug_level);
872
873     /*
874      * Do this after setting debug_level, since the function calls START_TRACE,
875      * which uses the $NCURSES_TRACE environment variable if _nc_tracing bits
876      * for tracing are zero.
877      */
878 #if NCURSES_XNAMES
879     if (using_extensions) {
880         use_extended_names(TRUE);
881     }
882 #endif
883
884     if (_nc_tracing) {
885         save_check_termtype = _nc_check_termtype2;
886         _nc_check_termtype2 = check_termtype;
887     }
888 #if !HAVE_BIG_CORE
889     /*
890      * Aaargh! immedhook seriously hoses us!
891      *
892      * One problem with immedhook is it means we can't do -e.  Problem
893      * is that we can't guarantee that for each terminal listed, all the
894      * terminals it depends on will have been kept in core for reference
895      * resolution -- in fact it is certain the primitive types at the end
896      * of reference chains *won't* be in core unless they were explicitly
897      * in the select list themselves.
898      */
899     if (namelst && (!infodump && !capdump)) {
900         (void) fprintf(stderr,
901                        "%s: Sorry, -e can't be used without -I or -C\n",
902                        _nc_progname);
903         ExitProgram(EXIT_FAILURE);
904     }
905 #endif /* HAVE_BIG_CORE */
906
907     if (optind < argc) {
908         source_file = argv[optind++];
909         if (optind < argc) {
910             fprintf(stderr,
911                     "%s: Too many file names.  Usage:\n\t%s %s",
912                     _nc_progname,
913                     _nc_progname,
914                     usage_string);
915             ExitProgram(EXIT_FAILURE);
916         }
917     } else {
918         if (infodump == TRUE) {
919             /* captoinfo's no-argument case */
920             source_file = "/etc/termcap";
921             if ((termcap = getenv("TERMCAP")) != 0
922                 && (namelst = make_namelist(getenv("TERM"))) != 0) {
923                 if (access(termcap, F_OK) == 0) {
924                     /* file exists */
925                     source_file = termcap;
926                 } else {
927                     if ((tmp_fp = open_tempfile(my_tmpname)) != 0) {
928                         source_file = my_tmpname;
929                         fprintf(tmp_fp, "%s\n", termcap);
930                         fclose(tmp_fp);
931                         tmp_fp = open_input(source_file, (char *) 0);
932                         to_remove = source_file;
933                     } else {
934                         failed("tmpnam");
935                     }
936                 }
937             }
938         } else {
939             /* tic */
940             fprintf(stderr,
941                     "%s: File name needed.  Usage:\n\t%s %s",
942                     _nc_progname,
943                     _nc_progname,
944                     usage_string);
945             ExitProgram(EXIT_FAILURE);
946         }
947     }
948
949     if (tmp_fp == NULL) {
950         char my_altfile[PATH_MAX];
951         tmp_fp = open_input(source_file, my_altfile);
952         if (!strcmp(source_file, "-")) {
953             source_file = STDIN_NAME;
954         }
955     }
956
957     if (infodump || check_only) {
958         dump_init(tversion,
959                   (smart_defaults
960                    ? outform
961                    : F_LITERAL),
962                   sortmode,
963                   wrap_strings, width, height,
964                   debug_level, formatted || check_only, check_only, quickdump);
965     } else if (capdump) {
966         dump_init(tversion,
967                   outform,
968                   sortmode,
969                   wrap_strings, width, height,
970                   debug_level, FALSE, FALSE, FALSE);
971     }
972
973     /* parse entries out of the source file */
974     _nc_set_source(source_file);
975 #if !HAVE_BIG_CORE
976     if (!(check_only || infodump || capdump))
977         _nc_set_writedir(outdir);
978 #endif /* HAVE_BIG_CORE */
979     _nc_read_entry_source(tmp_fp, (char *) NULL,
980                           !smart_defaults || literal, FALSE,
981                           ((check_only || infodump || capdump)
982                            ? NULLHOOK
983                            : immedhook));
984
985     /* do use resolution */
986     if (check_only || (!infodump && !capdump) || forceresolve) {
987         if (!_nc_resolve_uses2(TRUE, literal) && !check_only) {
988             ExitProgram(EXIT_FAILURE);
989         }
990     }
991
992     /* length check */
993     if (check_only && limited && (capdump || infodump)) {
994         for_entry_list(qp) {
995             if (matches(namelst, qp->tterm.term_names)) {
996                 int len = fmt_entry(&qp->tterm, NULL, FALSE, TRUE, infodump, numbers);
997
998                 if (len > (infodump ? MAX_TERMINFO_LENGTH : MAX_TERMCAP_LENGTH))
999                     (void) fprintf(stderr,
1000                                    "%s: resolved %s entry is %d bytes long\n",
1001                                    _nc_progname,
1002                                    _nc_first_name(qp->tterm.term_names),
1003                                    len);
1004             }
1005         }
1006     }
1007
1008     /* write or dump all entries */
1009     if (check_only) {
1010         /* this is in case infotocap() generates warnings */
1011         _nc_curr_col = _nc_curr_line = -1;
1012
1013         for_entry_list(qp) {
1014             if (matches(namelst, qp->tterm.term_names)) {
1015                 /* this is in case infotocap() generates warnings */
1016                 _nc_set_type(_nc_first_name(qp->tterm.term_names));
1017                 _nc_curr_line = (int) qp->startline;
1018                 repair_acsc(&qp->tterm);
1019                 dump_entry(&qp->tterm, suppress_untranslatable,
1020                            limited, numbers, NULL);
1021             }
1022         }
1023     } else {
1024         if (!infodump && !capdump) {
1025             _nc_set_writedir(outdir);
1026             for_entry_list(qp) {
1027                 if (matches(namelst, qp->tterm.term_names))
1028                     write_it(qp);
1029             }
1030         } else {
1031             /* this is in case infotocap() generates warnings */
1032             _nc_curr_col = _nc_curr_line = -1;
1033
1034             for_entry_list(qp) {
1035                 if (matches(namelst, qp->tterm.term_names)) {
1036                     long j = qp->cend - qp->cstart;
1037                     int len = 0;
1038
1039                     /* this is in case infotocap() generates warnings */
1040                     _nc_set_type(_nc_first_name(qp->tterm.term_names));
1041
1042                     if (!quiet) {
1043                         (void) fseek(tmp_fp, qp->cstart, SEEK_SET);
1044                         while (j-- > 0) {
1045                             int ch = fgetc(tmp_fp);
1046                             if (ch == EOF || ferror(tmp_fp)) {
1047                                 break;
1048                             } else if (infodump) {
1049                                 (void) putchar(ch);
1050                             } else {
1051                                 put_translate(ch);
1052                             }
1053                         }
1054                     }
1055
1056                     repair_acsc(&qp->tterm);
1057                     dump_entry(&qp->tterm, suppress_untranslatable,
1058                                limited, numbers, NULL);
1059                     for (j = 0; j < (long) qp->nuses; j++)
1060                         dump_uses(qp->uses[j].name, !capdump);
1061                     len = show_entry();
1062                     if (debug_level != 0 && !limited)
1063                         printf("# length=%d\n", len);
1064                 }
1065             }
1066             if (!namelst && _nc_tail && !quiet) {
1067                 int c, oldc = '\0';
1068                 bool in_comment = FALSE;
1069                 bool trailing_comment = FALSE;
1070
1071                 (void) fseek(tmp_fp, _nc_tail->cend, SEEK_SET);
1072                 while ((c = fgetc(tmp_fp)) != EOF) {
1073                     if (oldc == '\n') {
1074                         if (c == '#') {
1075                             trailing_comment = TRUE;
1076                             in_comment = TRUE;
1077                         } else {
1078                             in_comment = FALSE;
1079                         }
1080                     }
1081                     if (trailing_comment
1082                         && (in_comment || (oldc == '\n' && c == '\n')))
1083                         putchar(c);
1084                     oldc = c;
1085                 }
1086             }
1087         }
1088     }
1089
1090     /* Show the directory into which entries were written, and the total
1091      * number of entries
1092      */
1093     if (showsummary
1094         && (!(check_only || infodump || capdump))) {
1095         int total = _nc_tic_written();
1096         if (total != 0)
1097             fprintf(log_fp, "%d entries written to %s\n",
1098                     total,
1099                     _nc_tic_dir(NULL));
1100         else
1101             fprintf(log_fp, "No entries written\n");
1102     }
1103     ExitProgram(EXIT_SUCCESS);
1104 }
1105
1106 /*
1107  * This bit of legerdemain turns all the terminfo variable names into
1108  * references to locations in the arrays Booleans, Numbers, and Strings ---
1109  * precisely what's needed (see comp_parse.c).
1110  */
1111 #undef CUR
1112 #define CUR tp->
1113
1114 /*
1115  * Check if the alternate character-set capabilities are consistent.
1116  */
1117 static void
1118 check_acs(TERMTYPE2 *tp)
1119 {
1120     int vt100_smacs = 0;
1121     int vt100_rmacs = 0;
1122     int vt100_enacs = 0;
1123
1124     /*
1125      * ena_acs is not always necessary, but if it is present, the enter/exit
1126      * capabilities should be.
1127      */
1128     ANDMISSING(ena_acs, enter_alt_charset_mode);
1129     ANDMISSING(ena_acs, exit_alt_charset_mode);
1130     PAIRED(exit_alt_charset_mode, exit_alt_charset_mode);
1131
1132     /*
1133      * vt100-like is frequently used, but perhaps ena_acs is missing, etc.
1134      */
1135     if (VALID_STRING(enter_alt_charset_mode)) {
1136         vt100_smacs = (!strcmp("\033(0", enter_alt_charset_mode)
1137                        ? 2
1138                        : (!strcmp("\016", enter_alt_charset_mode)
1139                           ? 1
1140                           : 0));
1141     }
1142     if (VALID_STRING(exit_alt_charset_mode)) {
1143         vt100_rmacs = (!strcmp("\033(B", exit_alt_charset_mode)
1144                        ? 2
1145                        : (!strcmp("\017", exit_alt_charset_mode)
1146                           ? 1
1147                           : 0));
1148     }
1149     if (VALID_STRING(ena_acs)) {
1150         vt100_enacs = (!strcmp("\033(B\033)0", ena_acs)
1151                        ? 2
1152                        : 0);
1153     }
1154     if (vt100_rmacs && vt100_smacs && (vt100_rmacs != vt100_smacs)) {
1155         _nc_warning("rmacs/smacs are inconsistent");
1156     }
1157     if ((vt100_rmacs == 2) && (vt100_smacs == 2) && vt100_enacs) {
1158         _nc_warning("rmacs/smacs make enacs redundant");
1159     }
1160     if ((vt100_rmacs == 1) && (vt100_smacs == 1) && !vt100_enacs) {
1161         _nc_warning("VT100-style rmacs/smacs require enacs");
1162     }
1163
1164     if (VALID_STRING(acs_chars)) {
1165         const char *boxes = "lmkjtuvwqxn";
1166         char mapped[256];
1167         char missing[256];
1168         const char *p;
1169         char *q;
1170
1171         memset(mapped, 0, sizeof(mapped));
1172         for (p = acs_chars; *p != '\0'; p += 2) {
1173             if (p[1] == '\0') {
1174                 _nc_warning("acsc has odd number of characters");
1175                 break;
1176             }
1177             mapped[UChar(p[0])] = p[1];
1178         }
1179
1180         if (mapped[UChar('I')] && !mapped[UChar('i')]) {
1181             _nc_warning("acsc refers to 'I', which is probably an error");
1182         }
1183
1184         for (p = boxes, q = missing; *p != '\0'; ++p) {
1185             if (!mapped[UChar(p[0])]) {
1186                 *q++ = p[0];
1187             }
1188         }
1189         *q = '\0';
1190
1191         assert(strlen(missing) <= strlen(boxes));
1192         if (*missing != '\0' && strcmp(missing, boxes)) {
1193             _nc_warning("acsc is missing some line-drawing mapping: %s", missing);
1194         }
1195     }
1196 }
1197
1198 static char *
1199 safe_strdup(const char *value)
1200 {
1201     if (value == NULL)
1202         value = "";
1203     return strdup(value);
1204 }
1205
1206 static bool
1207 same_color(NCURSES_CONST char *oldcap, NCURSES_CONST char *newcap, int limit)
1208 {
1209     bool result = FALSE;
1210     if (limit > 16)
1211         limit = 16;
1212     if (limit >= 8) {
1213         int n;
1214         int same;
1215         for (n = same = 0; n < limit; ++n) {
1216             char *oldvalue = safe_strdup(TIPARM_1(oldcap, n));
1217             char *newvalue = safe_strdup(TIPARM_1(newcap, n));
1218             same += !strcmp(oldvalue, newvalue);
1219             free(oldvalue);
1220             free(newvalue);
1221         }
1222         result = (same == limit);
1223     }
1224     return result;
1225 }
1226
1227 /*
1228  * Check if the color capabilities are consistent
1229  */
1230 static void
1231 check_colors(TERMTYPE2 *tp)
1232 {
1233     char *value;
1234
1235     if ((max_colors > 0) != (max_pairs > 0)
1236         || ((max_colors > max_pairs) && !VALID_STRING(initialize_pair)))
1237         _nc_warning("inconsistent values for max_colors (%d) and max_pairs (%d)",
1238                     max_colors, max_pairs);
1239
1240     PAIRED(set_foreground, set_background);
1241     PAIRED(set_a_foreground, set_a_background);
1242     PAIRED(set_color_pair, initialize_pair);
1243
1244     if (VALID_STRING(set_foreground)
1245         && VALID_STRING(set_a_foreground)) {
1246         if (!_nc_capcmp(set_foreground, set_a_foreground)) {
1247             _nc_warning("expected setf/setaf to be different");
1248         } else if (same_color(set_foreground, set_a_foreground, max_colors)) {
1249             _nc_warning("setf/setaf are equivalent");
1250         }
1251     }
1252
1253     if (VALID_STRING(set_background)
1254         && VALID_STRING(set_a_background)) {
1255         if (!_nc_capcmp(set_background, set_a_background)) {
1256             _nc_warning("expected setb/setab to be different");
1257         } else if (same_color(set_background, set_a_background, max_colors)) {
1258             _nc_warning("setb/setab are equivalent");
1259         }
1260     }
1261
1262     /* see: has_colors() */
1263     if (VALID_NUMERIC(max_colors) && VALID_NUMERIC(max_pairs)
1264         && ((VALID_STRING(set_foreground)
1265              && VALID_STRING(set_background))
1266             || (VALID_STRING(set_a_foreground)
1267                 && VALID_STRING(set_a_background))
1268             || set_color_pair)) {
1269         if (!VALID_STRING(orig_pair) && !VALID_STRING(orig_colors))
1270             _nc_warning("expected either op/oc string for resetting colors");
1271     }
1272     if (can_change) {
1273         if (!VALID_STRING(initialize_pair) &&
1274             !VALID_STRING(initialize_color)) {
1275             _nc_warning("expected initc or initp because ccc is given");
1276         }
1277     } else {
1278         if (VALID_STRING(initialize_pair) ||
1279             VALID_STRING(initialize_color)) {
1280             _nc_warning("expected ccc because initc is given");
1281         }
1282     }
1283     value = tigetstr("RGB");
1284     if (VALID_STRING(value)) {
1285         int r, g, b;
1286         char bad;
1287         int code = sscanf(value, "%d/%d/%d%c", &r, &g, &b, &bad);
1288         if (code != 3 || r <= 0 || g <= 0 || b <= 0) {
1289             _nc_warning("unexpected value for RGB capability: %s", value);
1290         }
1291     }
1292 }
1293
1294 static int
1295 csi_length(const char *value)
1296 {
1297     int result = 0;
1298
1299     if (value[0] == '\033' && value[1] == '[') {
1300         result = 2;
1301     } else if (UChar(value[0]) == 0x9a) {
1302         result = 1;
1303     }
1304     return result;
1305 }
1306
1307 static char
1308 keypad_final(const char *string)
1309 {
1310     char result = '\0';
1311
1312     if (VALID_STRING(string)
1313         && *string++ == '\033'
1314         && *string++ == 'O'
1315         && strlen(string) == 1) {
1316         result = *string;
1317     }
1318
1319     return result;
1320 }
1321
1322 static long
1323 keypad_index(const char *string)
1324 {
1325     int ch;
1326     long result = -1;
1327
1328     if ((ch = keypad_final(string)) != '\0') {
1329         const char *list = "PQRSwxymtuvlqrsPpn";        /* app-keypad except "Enter" */
1330         char *test = (strchr) (list, ch);
1331         if (test != 0)
1332             result = (long) (test - list);
1333     }
1334     return result;
1335 }
1336
1337 /*
1338  * list[] is down, up, left, right
1339  * "left" may be ^H rather than \E[D
1340  * "down" may be ^J rather than \E[B
1341  * But up/right are generally consistently escape sequences for ANSI terminals.
1342  */
1343 static void
1344 check_ansi_cursor(char *list[4])
1345 {
1346     int j, k;
1347     bool skip[4];
1348     bool repeated = FALSE;
1349
1350     for (j = 0; j < 4; ++j) {
1351         skip[j] = FALSE;
1352         for (k = 0; k < j; ++k) {
1353             if (j != k
1354                 && !strcmp(list[j], list[k])) {
1355                 char *value = _nc_tic_expand(list[k], TRUE, 0);
1356                 _nc_warning("repeated cursor control %s", value);
1357                 repeated = TRUE;
1358             }
1359         }
1360     }
1361     if (!repeated) {
1362         char *up = list[1];
1363         size_t prefix = (size_t) csi_length(up);
1364         size_t suffix;
1365
1366         if (prefix) {
1367             suffix = prefix;
1368             while (up[suffix] && isdigit(UChar(up[suffix])))
1369                 ++suffix;
1370         }
1371         if (prefix && up[suffix] == 'A') {
1372             skip[1] = TRUE;
1373             if (!strcmp(list[0], "\n"))
1374                 skip[0] = TRUE;
1375             if (!strcmp(list[2], "\b"))
1376                 skip[2] = TRUE;
1377
1378             for (j = 0; j < 4; ++j) {
1379                 int want;
1380
1381                 if (skip[j] || strlen(list[j]) == 1)
1382                     continue;
1383                 if (memcmp(list[j], up, prefix)) {
1384                     char *value = _nc_tic_expand(list[j], TRUE, 0);
1385                     _nc_warning("inconsistent prefix for %s", value);
1386                     continue;
1387                 }
1388                 if (strlen(list[j]) < suffix) {
1389                     char *value = _nc_tic_expand(list[j], TRUE, 0);
1390                     _nc_warning("inconsistent length for %s, expected %d",
1391                                 value, (int) suffix + 1);
1392                     continue;
1393                 }
1394                 want = "BADC"[j];
1395                 if (list[j][suffix] != want) {
1396                     char *value = _nc_tic_expand(list[j], TRUE, 0);
1397                     _nc_warning("inconsistent suffix for %s, expected %c, have %c",
1398                                 value, want, list[j][suffix]);
1399                 }
1400             }
1401         }
1402     }
1403 }
1404
1405 #define EXPECTED(name) if (!PRESENT(name)) _nc_warning("expected " #name)
1406 #define UNEXPECTED(name) if (PRESENT(name)) _nc_warning("unexpected " #name ", for %s", why)
1407
1408 static void
1409 check_noaddress(TERMTYPE2 *tp, const char *why)
1410 {
1411     UNEXPECTED(column_address);
1412     UNEXPECTED(cursor_address);
1413     UNEXPECTED(cursor_home);
1414     UNEXPECTED(cursor_mem_address);
1415     UNEXPECTED(cursor_to_ll);
1416     UNEXPECTED(row_address);
1417     UNEXPECTED(row_address);
1418 }
1419
1420 static void
1421 check_cursor(TERMTYPE2 *tp)
1422 {
1423     int count;
1424     char *list[4];
1425
1426     if (hard_copy) {
1427         check_noaddress(tp, "hard_copy");
1428     } else if (generic_type) {
1429         check_noaddress(tp, "generic_type");
1430     } else if (strchr(tp->term_names, '+') == NULL) {
1431         int y = 0;
1432         int x = 0;
1433         if (PRESENT(column_address))
1434             ++y;
1435         if (PRESENT(cursor_address))
1436             y = x = 10;
1437         if (PRESENT(cursor_home))
1438             ++y, ++x;
1439         if (PRESENT(cursor_mem_address))
1440             y = x = 10;
1441         if (PRESENT(cursor_to_ll))
1442             ++y, ++x;
1443         if (PRESENT(row_address))
1444             ++x;
1445         if (PRESENT(cursor_down))
1446             ++y;
1447         if (PRESENT(cursor_up))
1448             ++y;
1449         if (PRESENT(cursor_left))
1450             ++x;
1451         if (PRESENT(cursor_right))
1452             ++x;
1453         if (x < 2 && y < 2) {
1454             _nc_warning("terminal lacks cursor addressing");
1455         } else {
1456             if (x < 2)
1457                 _nc_warning("terminal lacks cursor column-addressing");
1458             if (y < 2)
1459                 _nc_warning("terminal lacks cursor row-addressing");
1460         }
1461     }
1462
1463     /* it is rare to have an insert-line feature without a matching delete */
1464     ANDMISSING(parm_insert_line, insert_line);
1465     ANDMISSING(parm_delete_line, delete_line);
1466     ANDMISSING(parm_insert_line, parm_delete_line);
1467
1468     /* if we have a parameterized form, then the non-parameterized is easy */
1469     ANDMISSING(parm_down_cursor, cursor_down);
1470     ANDMISSING(parm_up_cursor, cursor_up);
1471     ANDMISSING(parm_left_cursor, cursor_left);
1472     ANDMISSING(parm_right_cursor, cursor_right);
1473
1474     /* Given any of a set of cursor movement, the whole set should be present.
1475      * Technically this is not true (we could use cursor_address to fill in
1476      * unsupported controls), but it is likely.
1477      */
1478     count = 0;
1479     if (PRESENT(parm_down_cursor)) {
1480         list[count++] = parm_down_cursor;
1481     }
1482     if (PRESENT(parm_up_cursor)) {
1483         list[count++] = parm_up_cursor;
1484     }
1485     if (PRESENT(parm_left_cursor)) {
1486         list[count++] = parm_left_cursor;
1487     }
1488     if (PRESENT(parm_right_cursor)) {
1489         list[count++] = parm_right_cursor;
1490     }
1491     if (count == 4) {
1492         check_ansi_cursor(list);
1493     } else if (count != 0) {
1494         EXPECTED(parm_down_cursor);
1495         EXPECTED(parm_up_cursor);
1496         EXPECTED(parm_left_cursor);
1497         EXPECTED(parm_right_cursor);
1498     }
1499
1500     count = 0;
1501     if (PRESENT(cursor_down)) {
1502         list[count++] = cursor_down;
1503     }
1504     if (PRESENT(cursor_up)) {
1505         list[count++] = cursor_up;
1506     }
1507     if (PRESENT(cursor_left)) {
1508         list[count++] = cursor_left;
1509     }
1510     if (PRESENT(cursor_right)) {
1511         list[count++] = cursor_right;
1512     }
1513     if (count == 4) {
1514         check_ansi_cursor(list);
1515     } else if (count != 0) {
1516         count = 0;
1517         if (PRESENT(cursor_down) && strcmp(cursor_down, "\n"))
1518             ++count;
1519         if (PRESENT(cursor_left) && strcmp(cursor_left, "\b"))
1520             ++count;
1521         if (PRESENT(cursor_up) && strlen(cursor_up) > 1)
1522             ++count;
1523         if (PRESENT(cursor_right) && strlen(cursor_right) > 1)
1524             ++count;
1525         if (count) {
1526             EXPECTED(cursor_down);
1527             EXPECTED(cursor_up);
1528             EXPECTED(cursor_left);
1529             EXPECTED(cursor_right);
1530         }
1531     }
1532 }
1533
1534 #define MAX_KP 5
1535 /*
1536  * Do a quick sanity-check for vt100-style keypads to see if the 5-key keypad
1537  * is mapped inconsistently.
1538  */
1539 static void
1540 check_keypad(TERMTYPE2 *tp)
1541 {
1542     char show[80];
1543
1544     if (VALID_STRING(key_a1) &&
1545         VALID_STRING(key_a3) &&
1546         VALID_STRING(key_b2) &&
1547         VALID_STRING(key_c1) &&
1548         VALID_STRING(key_c3)) {
1549         char final[MAX_KP + 1];
1550         long list[MAX_KP];
1551         int increase = 0;
1552         int j;
1553
1554         final[0] = keypad_final(key_a1);
1555         final[1] = keypad_final(key_a3);
1556         final[2] = keypad_final(key_b2);
1557         final[3] = keypad_final(key_c1);
1558         final[4] = keypad_final(key_c3);
1559         final[5] = '\0';
1560
1561         /* special case: legacy coding using 1,2,3,0,. on the bottom */
1562         assert(strlen(final) <= MAX_KP);
1563         if (!strcmp(final, "qsrpn"))
1564             return;
1565
1566         list[0] = keypad_index(key_a1);
1567         list[1] = keypad_index(key_a3);
1568         list[2] = keypad_index(key_b2);
1569         list[3] = keypad_index(key_c1);
1570         list[4] = keypad_index(key_c3);
1571
1572         /* check that they're all vt100 keys */
1573         for (j = 0; j < MAX_KP; ++j) {
1574             if (list[j] < 0) {
1575                 return;
1576             }
1577         }
1578
1579         /* check if they're all in increasing order */
1580         for (j = 1; j < MAX_KP; ++j) {
1581             if (list[j] > list[j - 1]) {
1582                 ++increase;
1583             }
1584         }
1585
1586         if (increase != (MAX_KP - 1)) {
1587             long last;
1588
1589             show[0] = '\0';
1590
1591             for (j = 0, last = -1; j < MAX_KP; ++j) {
1592                 int k;
1593                 int kk;
1594                 long test;
1595
1596                 for (k = 0, kk = -1, test = 100; k < 5; ++k) {
1597                     if (list[k] > last &&
1598                         list[k] < test) {
1599                         test = list[k];
1600                         kk = k;
1601                     }
1602                 }
1603                 last = test;
1604                 assert(strlen(show) < (MAX_KP * 4));
1605                 switch (kk) {
1606                 case 0:
1607                     _nc_STRCAT(show, " ka1", sizeof(show));
1608                     break;
1609                 case 1:
1610                     _nc_STRCAT(show, " ka3", sizeof(show));
1611                     break;
1612                 case 2:
1613                     _nc_STRCAT(show, " kb2", sizeof(show));
1614                     break;
1615                 case 3:
1616                     _nc_STRCAT(show, " kc1", sizeof(show));
1617                     break;
1618                 case 4:
1619                     _nc_STRCAT(show, " kc3", sizeof(show));
1620                     break;
1621                 }
1622             }
1623
1624             _nc_warning("vt100 keypad order inconsistent: %s", show);
1625         }
1626
1627     } else if (VALID_STRING(key_a1) ||
1628                VALID_STRING(key_a3) ||
1629                VALID_STRING(key_b2) ||
1630                VALID_STRING(key_c1) ||
1631                VALID_STRING(key_c3)) {
1632         show[0] = '\0';
1633         if (keypad_index(key_a1) >= 0)
1634             _nc_STRCAT(show, " ka1", sizeof(show));
1635         if (keypad_index(key_a3) >= 0)
1636             _nc_STRCAT(show, " ka3", sizeof(show));
1637         if (keypad_index(key_b2) >= 0)
1638             _nc_STRCAT(show, " kb2", sizeof(show));
1639         if (keypad_index(key_c1) >= 0)
1640             _nc_STRCAT(show, " kc1", sizeof(show));
1641         if (keypad_index(key_c3) >= 0)
1642             _nc_STRCAT(show, " kc3", sizeof(show));
1643         if (*show != '\0')
1644             _nc_warning("vt100 keypad map incomplete:%s", show);
1645     }
1646
1647     /*
1648      * These warnings are useful for consistency checks - it is possible that
1649      * there are real terminals with mismatches in these
1650      */
1651     ANDMISSING(key_ic, key_dc);
1652 }
1653
1654 static void
1655 check_printer(TERMTYPE2 *tp)
1656 {
1657     (void) tp;
1658 #if defined(enter_doublewide_mode) && defined(exit_doublewide_mode)
1659     PAIRED(enter_doublewide_mode, exit_doublewide_mode);
1660 #endif
1661 #if defined(enter_italics_mode) && defined(exit_italics_mode)
1662     PAIRED(enter_italics_mode, exit_italics_mode);
1663 #endif
1664 #if defined(enter_leftward_mode) && defined(exit_leftward_mode)
1665     PAIRED(enter_leftward_mode, exit_leftward_mode);
1666 #endif
1667 #if defined(enter_micro_mode) && defined(exit_micro_mode)
1668     PAIRED(enter_micro_mode, exit_micro_mode);
1669 #endif
1670 #if defined(enter_shadow_mode) && defined(exit_shadow_mode)
1671     PAIRED(enter_shadow_mode, exit_shadow_mode);
1672 #endif
1673 #if defined(enter_subscript_mode) && defined(exit_subscript_mode)
1674     PAIRED(enter_subscript_mode, exit_subscript_mode);
1675 #endif
1676 #if defined(enter_superscript_mode) && defined(exit_superscript_mode)
1677     PAIRED(enter_superscript_mode, exit_superscript_mode);
1678 #endif
1679 #if defined(enter_upward_mode) && defined(exit_upward_mode)
1680     PAIRED(enter_upward_mode, exit_upward_mode);
1681 #endif
1682
1683 #if defined(start_char_set_def) && defined(stop_char_set_def)
1684     ANDMISSING(start_char_set_def, stop_char_set_def);
1685 #endif
1686
1687     /*
1688      * If we have a parameterized form, then the non-parameterized is easy.
1689      * note: parameterized/non-parameterized margin settings are unrelated.
1690      */
1691 #if defined(parm_down_micro) && defined(micro_down)
1692     ANDMISSING(parm_down_micro, micro_down);
1693 #endif
1694 #if defined(parm_left_micro) && defined(micro_left)
1695     ANDMISSING(parm_left_micro, micro_left);
1696 #endif
1697 #if defined(parm_right_micro) && defined(micro_right)
1698     ANDMISSING(parm_right_micro, micro_right);
1699 #endif
1700 #if defined(parm_up_micro) && defined(micro_up)
1701     ANDMISSING(parm_up_micro, micro_up);
1702 #endif
1703 }
1704
1705 #if NCURSES_XNAMES
1706 static bool
1707 uses_SGR_39_49(const char *value)
1708 {
1709     return (strstr(value, "39;49") != 0
1710             || strstr(value, "49;39") != 0);
1711 }
1712
1713 /*
1714  * Check consistency of termcap extensions related to "screen".
1715  */
1716 static void
1717 check_screen(TERMTYPE2 *tp)
1718 {
1719     if (_nc_user_definable) {
1720         int have_XT = tigetflag("XT");
1721         int have_XM = tigetflag("XM");
1722         int have_bce = back_color_erase;
1723         bool have_kmouse = FALSE;
1724         bool use_sgr_39_49 = FALSE;
1725         const char *name_39_49 = "orig_pair or orig_colors";
1726         char *name = _nc_first_name(tp->term_names);
1727         bool is_screen = !strncmp(name, "screen", 6);
1728         bool screen_base = (is_screen
1729                             && strchr(name, '.') == NULL);
1730
1731         if (!VALID_BOOLEAN(have_bce)) {
1732             have_bce = FALSE;
1733         }
1734         if (!VALID_BOOLEAN(have_XM)) {
1735             have_XM = FALSE;
1736         }
1737         if (!VALID_BOOLEAN(have_XT)) {
1738             have_XT = FALSE;
1739         }
1740         if (VALID_STRING(key_mouse)) {
1741             have_kmouse = !strcmp("\033[M", key_mouse);
1742         }
1743         if (have_bce) {
1744             if (VALID_STRING(orig_pair)) {
1745                 name_39_49 = "orig_pair";
1746                 use_sgr_39_49 = uses_SGR_39_49(orig_pair);
1747             }
1748             if (!use_sgr_39_49 && VALID_STRING(orig_colors)) {
1749                 name_39_49 = "orig_colors";
1750                 use_sgr_39_49 = uses_SGR_39_49(orig_colors);
1751             }
1752         }
1753
1754         if (have_XM && have_XT) {
1755             _nc_warning("screen's XT capability conflicts with XM");
1756         } else if (have_XT && screen_base) {
1757             _nc_warning("screen's \"screen\" entries should not have XT set");
1758         } else if (have_XT) {
1759             char *s;
1760
1761             if (!have_kmouse && is_screen) {
1762                 if (VALID_STRING(key_mouse)) {
1763                     _nc_warning("value of kmous inconsistent with screen's usage");
1764                 } else {
1765                     _nc_warning("expected kmous capability with XT");
1766                 }
1767             }
1768             if (max_colors > 0) {
1769                 if (!have_bce) {
1770                     _nc_warning("expected bce capability with XT");
1771                 } else if (!use_sgr_39_49) {
1772                     _nc_warning("expected %s capability with XT "
1773                                 "to have 39/49 parameters", name_39_49);
1774                 }
1775             }
1776             if (VALID_STRING(to_status_line)
1777                 && (s = strchr(to_status_line, ';')) != NULL
1778                 && *++s == '\0')
1779                 _nc_warning("\"tsl\" capability is redundant, given XT");
1780         } else {
1781             if (have_kmouse
1782                 && !have_XM
1783                 && !screen_base && strchr(name, '+') == NULL) {
1784                 _nc_warning("expected XT to be set, given kmous");
1785             }
1786         }
1787     }
1788 }
1789 #else
1790 #define check_screen(tp)        /* nothing */
1791 #endif
1792
1793 /*
1794  * Returns the expected number of parameters for the given capability.
1795  */
1796 static int
1797 expected_params(const char *name)
1798 {
1799 #define DATA(name,count) { { name }, count }
1800     /* *INDENT-OFF* */
1801     static const struct {
1802         const char name[9];
1803         int count;
1804     } table[] = {
1805         DATA( "S0",             1 ),    /* 'screen' extension */
1806         DATA( "birep",          2 ),
1807         DATA( "chr",            1 ),
1808         DATA( "colornm",        1 ),
1809         DATA( "cpi",            1 ),
1810         DATA( "csnm",           1 ),
1811         DATA( "csr",            2 ),
1812         DATA( "cub",            1 ),
1813         DATA( "cud",            1 ),
1814         DATA( "cuf",            1 ),
1815         DATA( "cup",            2 ),
1816         DATA( "cuu",            1 ),
1817         DATA( "cvr",            1 ),
1818         DATA( "cwin",           5 ),
1819         DATA( "dch",            1 ),
1820         DATA( "defc",           3 ),
1821         DATA( "dial",           1 ),
1822         DATA( "dispc",          1 ),
1823         DATA( "dl",             1 ),
1824         DATA( "ech",            1 ),
1825         DATA( "getm",           1 ),
1826         DATA( "hpa",            1 ),
1827         DATA( "ich",            1 ),
1828         DATA( "il",             1 ),
1829         DATA( "indn",           1 ),
1830         DATA( "initc",          4 ),
1831         DATA( "initp",          7 ),
1832         DATA( "lpi",            1 ),
1833         DATA( "mc5p",           1 ),
1834         DATA( "mrcup",          2 ),
1835         DATA( "mvpa",           1 ),
1836         DATA( "pfkey",          2 ),
1837         DATA( "pfloc",          2 ),
1838         DATA( "pfx",            2 ),
1839         DATA( "pfxl",           3 ),
1840         DATA( "pln",            2 ),
1841         DATA( "qdial",          1 ),
1842         DATA( "rcsd",           1 ),
1843         DATA( "rep",            2 ),
1844         DATA( "rin",            1 ),
1845         DATA( "sclk",           3 ),
1846         DATA( "scp",            1 ),
1847         DATA( "scs",            1 ),
1848         DATA( "scsd",           2 ),
1849         DATA( "setab",          1 ),
1850         DATA( "setaf",          1 ),
1851         DATA( "setb",           1 ),
1852         DATA( "setcolor",       1 ),
1853         DATA( "setf",           1 ),
1854         DATA( "sgr",            9 ),
1855         DATA( "sgr1",           6 ),
1856         DATA( "slength",        1 ),
1857         DATA( "slines",         1 ),
1858         DATA( "smgbp",          1 ),    /* 2 if smgtp is not given */
1859         DATA( "smglp",          1 ),
1860         DATA( "smglr",          2 ),
1861         DATA( "smgrp",          1 ),
1862         DATA( "smgtb",          2 ),
1863         DATA( "smgtp",          1 ),
1864         DATA( "tsl",            1 ),
1865         DATA( "u6",             -1 ),
1866         DATA( "vpa",            1 ),
1867         DATA( "wind",           4 ),
1868         DATA( "wingo",          1 ),
1869     };
1870     /* *INDENT-ON* */
1871 #undef DATA
1872
1873     unsigned n;
1874     int result = 0;             /* function-keys, etc., use none */
1875
1876     for (n = 0; n < SIZEOF(table); n++) {
1877         if (!strcmp(name, table[n].name)) {
1878             result = table[n].count;
1879             break;
1880         }
1881     }
1882
1883     return result;
1884 }
1885
1886 /*
1887  * Check for user-capabilities that happen to be used in ncurses' terminal
1888  * database.
1889  */
1890 #if NCURSES_XNAMES
1891 static struct user_table_entry const *
1892 lookup_user_capability(const char *name)
1893 {
1894     struct user_table_entry const *result = 0;
1895     if (*name != 'k') {
1896         result = _nc_find_user_entry(name);
1897     }
1898     return result;
1899 }
1900 #endif
1901
1902 /*
1903  * If a given name is likely to be a user-capability, return the number of
1904  * parameters it would be used with.  If not, return -1.
1905  *
1906  * ncurses assumes that u6 could be used for getting the cursor-position, but
1907  * that is not implemented.  Make a special case for that, to quiet needless
1908  * warnings.
1909  *
1910  * The other string-capability extensions (see terminfo.src) which could have
1911  * parameters such as "Ss", "%u", are not used by ncurses.  But we check those
1912  * anyway, to validate the terminfo database.
1913  */
1914 static int
1915 is_user_capability(const char *name)
1916 {
1917     int result = -1;
1918     if (name[0] == 'u' &&
1919         (name[1] >= '0' && name[1] <= '9') &&
1920         name[2] == '\0') {
1921         result = (name[1] == '6') ? 2 : 0;
1922     }
1923 #if NCURSES_XNAMES
1924     else if (using_extensions) {
1925         struct user_table_entry const *p = lookup_user_capability(name);
1926         if (p != 0) {
1927             result = (int) p->ute_argc;
1928         }
1929     }
1930 #endif
1931     return result;
1932 }
1933
1934 static bool
1935 line_capability(const char *name)
1936 {
1937     bool result = FALSE;
1938     static const char *table[] =
1939     {
1940         "csr",                  /* change_scroll_region          */
1941         "clear",                /* clear_screen                  */
1942         "ed",                   /* clr_eos                       */
1943         "cwin",                 /* create_window                 */
1944         "cup",                  /* cursor_address                */
1945         "cud1",                 /* cursor_down                   */
1946         "home",                 /* cursor_home                   */
1947         "mrcup",                /* cursor_mem_address            */
1948         "ll",                   /* cursor_to_ll                  */
1949         "cuu1",                 /* cursor_up                     */
1950         "dl1",                  /* delete_line                   */
1951         "hd",                   /* down_half_line                */
1952         "flash",                /* flash_screen                  */
1953         "ff",                   /* form_feed                     */
1954         "il1",                  /* insert_line                   */
1955         "nel",                  /* newline                       */
1956         "dl",                   /* parm_delete_line              */
1957         "cud",                  /* parm_down_cursor              */
1958         "indn",                 /* parm_index                    */
1959         "il",                   /* parm_insert_line              */
1960         "rin",                  /* parm_rindex                   */
1961         "cuu",                  /* parm_up_cursor                */
1962         "mc0",                  /* print_screen                  */
1963         "vpa",                  /* row_address                   */
1964         "ind",                  /* scroll_forward                */
1965         "ri",                   /* scroll_reverse                */
1966         "hu",                   /* up_half_line                  */
1967     };
1968     size_t n;
1969     for (n = 0; n < SIZEOF(table); ++n) {
1970         if (!strcmp(name, table[n])) {
1971             result = TRUE;
1972             break;
1973         }
1974     }
1975     return result;
1976 }
1977
1978 /*
1979  * Make a quick sanity check for the parameters which are used in the given
1980  * strings.  If there are no "%p" tokens, then there should be no other "%"
1981  * markers.
1982  */
1983 static void
1984 check_params(TERMTYPE2 *tp, const char *name, const char *value, int extended)
1985 {
1986     int expected = expected_params(name);
1987     int actual = 0;
1988     int n;
1989     bool params[1 + NUM_PARM];
1990     const char *s = value;
1991
1992 #ifdef set_left_margin_parm
1993     if (!strcmp(name, "smgrp")
1994         && !VALID_STRING(set_left_margin_parm))
1995         expected = 2;
1996 #endif
1997 #ifdef set_right_margin_parm
1998     if (!strcmp(name, "smglp")
1999         && !VALID_STRING(set_right_margin_parm))
2000         expected = 2;
2001 #endif
2002 #ifdef set_top_margin_parm
2003     if (!strcmp(name, "smgbp")
2004         && !VALID_STRING(set_top_margin_parm))
2005         expected = 2;
2006 #endif
2007 #ifdef set_bottom_margin_parm
2008     if (!strcmp(name, "smgtp")
2009         && !VALID_STRING(set_bottom_margin_parm))
2010         expected = 2;
2011 #endif
2012
2013     for (n = 0; n <= NUM_PARM; n++)
2014         params[n] = FALSE;
2015
2016     while (*s != 0) {
2017         if (*s == '%') {
2018             if (*++s == '\0') {
2019                 _nc_warning("expected character after %% in %s", name);
2020                 break;
2021             } else if (*s == 'p') {
2022                 if (*++s == '\0' || !isdigit((int) *s)) {
2023                     _nc_warning("expected digit after %%p in %s", name);
2024                     return;
2025                 } else {
2026                     n = (*s - '0');
2027                     if (n > actual)
2028                         actual = n;
2029                     params[n] = TRUE;
2030                 }
2031             }
2032         }
2033         s++;
2034     }
2035
2036 #if NCURSES_XNAMES
2037     if (extended) {
2038         int check = is_user_capability(name);
2039         if (check != actual && (check >= 0 && actual >= 0)) {
2040             _nc_warning("extended %s capability has %d parameters, expected %d",
2041                         name, actual, check);
2042         } else if (debug_level > 1) {
2043             _nc_warning("extended %s capability has %d parameters, as expected",
2044                         name, actual);
2045         }
2046         expected = actual;
2047     }
2048 #else
2049     (void) extended;
2050 #endif
2051
2052     if (params[0]) {
2053         _nc_warning("%s refers to parameter 0 (%%p0), which is not allowed", name);
2054     }
2055     if (value == set_attributes || expected < 0) {
2056         ;
2057     } else if (expected != actual) {
2058         _nc_warning("%s uses %d parameters, expected %d", name,
2059                     actual, expected);
2060         for (n = 1; n < actual; n++) {
2061             if (!params[n])
2062                 _nc_warning("%s omits parameter %d", name, n);
2063         }
2064     }
2065
2066     /*
2067      * Counting "%p" markers does not account for termcap expressions which
2068      * may not have been fully translated.  Also, tparm does its own analysis.
2069      * Report differences here.
2070      */
2071     _nc_reset_tparm(NULL);
2072     if (actual >= 0) {
2073         char *p_is_s[NUM_PARM];
2074         int popcount;
2075         int analyzed = _nc_tparm_analyze(NULL, value, p_is_s, &popcount);
2076         if (analyzed < popcount) {
2077             analyzed = popcount;
2078         }
2079         if (actual != analyzed && expected != analyzed) {
2080 #if NCURSES_XNAMES
2081             int user_cap = is_user_capability(name);
2082             if ((user_cap == analyzed) && using_extensions) {
2083                 ;               /* ignore */
2084             } else if (user_cap >= 0) {
2085                 _nc_warning("tparm will use %d parameters for %s, expected %d",
2086                             analyzed, name, user_cap);
2087             } else
2088 #endif
2089             {
2090                 _nc_warning("tparm analyzed %d parameters for %s, expected %d",
2091                             analyzed, name, actual);
2092             }
2093         } else if (expected > 0
2094                    && actual == expected
2095                    && guess_tparm_type(expected, p_is_s) == Numbers) {
2096             int limit = 1;
2097
2098             if (!strcmp(name, "setf")
2099                 || !strcmp(name, "setb")
2100                 || !strcmp(name, "setaf")
2101                 || !strcmp(name, "setab")) {
2102                 if ((limit = max_colors) > 256)
2103                     limit = 256;
2104             } else if (line_capability(name)) {
2105                 limit = 24;
2106             } else if (is_user_capability(name) < 0) {
2107                 limit = 80;
2108             }
2109             for (n = 0; n < limit; ++n) {
2110                 _nc_reset_tparm(NULL);
2111                 (void) TPARM_9(value, n, n, n, n, n, n, n, n, n);
2112                 if (_nc_tparm_err) {
2113                     _nc_warning("problem%s in tparm(%s, %d, ...)",
2114                                 (_nc_tparm_err == 1) ? "" : "s",
2115                                 name, n);
2116                     if (debug_level < 2)
2117                         break;
2118                 }
2119             }
2120         }
2121     }
2122 }
2123
2124 /*
2125  * Check for DEC VT100 private mode for reverse video.
2126  */
2127 static const char *
2128 skip_DECSCNM(const char *value, int *flag)
2129 {
2130     *flag = -1;
2131     if (value != 0) {
2132         int skip = csi_length(value);
2133         if (skip > 0 &&
2134             value[skip++] == '?' &&
2135             value[skip++] == '5') {
2136             if (value[skip] == 'h') {
2137                 *flag = 1;
2138             } else if (value[skip] == 'l') {
2139                 *flag = 0;
2140             }
2141             value += skip + 1;
2142         }
2143     }
2144     return value;
2145 }
2146
2147 static void
2148 check_delays(TERMTYPE2 *tp, const char *name, const char *value)
2149 {
2150     const char *p, *q;
2151     const char *first = 0;
2152     const char *last = 0;
2153
2154     for (p = value; *p != '\0'; ++p) {
2155         if (p[0] == '$' && p[1] == '<') {
2156             const char *base = p + 2;
2157             const char *mark = 0;
2158             bool mixed = FALSE;
2159             int proportional = 0;
2160             int mandatory = 0;
2161
2162             first = p;
2163
2164             for (q = base; *q != '\0'; ++q) {
2165                 if (*q == '>') {
2166                     if (mark == NULL)
2167                         mark = q;
2168                     break;
2169                 } else if (*q == '*' || *q == '/') {
2170                     if (*q == '*')
2171                         ++proportional;
2172                     if (*q == '/')
2173                         ++mandatory;
2174                     if (mark == NULL)
2175                         mark = q;
2176                 } else if (!(isalnum(UChar(*q)) || strchr("+-.", *q) != 0)) {
2177                     break;
2178                 } else if (proportional || mandatory) {
2179                     mixed = TRUE;
2180                 }
2181             }
2182             last = *q ? (q + 1) : q;
2183             if (*q != '\0') {
2184                 float check_f;
2185                 char check_c;
2186                 int rc = sscanf(base, "%f%c", &check_f, &check_c);
2187                 if ((rc != 2) || (mark != NULL && (check_c != *mark)) || mixed) {
2188                     _nc_warning("syntax error in %s delay '%.*s'", name,
2189                                 (int) (q - base), base);
2190                 } else if (*name == 'k') {
2191                     _nc_warning("function-key %s has delay", name);
2192                 } else if (proportional && !line_capability(name)) {
2193                     _nc_warning("non-line capability using proportional delay: %s", name);
2194                 } else if (!xon_xoff &&
2195                            !mandatory &&
2196                            strchr(_nc_first_name(tp->term_names), '+') == NULL) {
2197                     _nc_warning("%s in %s is used since no xon/xoff",
2198                                 (proportional
2199                                  ? "proportional delay"
2200                                  : "delay"),
2201                                 name);
2202                 }
2203             } else {
2204                 p = q - 1;      /* restart scan */
2205             }
2206         }
2207     }
2208
2209     if (!strcmp(name, "flash") ||
2210         !strcmp(name, "beep")) {
2211
2212         if (first != 0) {
2213             if (first == value || *last == 0) {
2214                 /*
2215                  * Delay is on one end or the other.
2216                  */
2217                 _nc_warning("expected delay embedded within %s", name);
2218             }
2219         } else {
2220             int flag;
2221
2222             /*
2223              * Check for missing delay when using VT100 reverse-video.
2224              * A real VT100 might not need this, but terminal emulators do.
2225              */
2226             if ((p = skip_DECSCNM(value, &flag)) != 0 &&
2227                 flag > 0 &&
2228                 skip_DECSCNM(p, &flag) != 0 &&
2229                 flag == 0) {
2230                 _nc_warning("expected a delay in %s", name);
2231             }
2232         }
2233     }
2234 }
2235
2236 static char *
2237 check_1_infotocap(const char *name, NCURSES_CONST char *value, int count)
2238 {
2239     int k;
2240     int ignored;
2241     long numbers[1 + NUM_PARM];
2242     char *strings[1 + NUM_PARM];
2243     char *p_is_s[NUM_PARM];
2244     char *result;
2245     char blob[NUM_PARM * 10];
2246     char *next = blob;
2247     TParams expect;
2248     TParams actual;
2249     int nparam;
2250
2251     *next++ = '\0';
2252     for (k = 1; k <= NUM_PARM; k++) {
2253         numbers[k] = count;
2254         _nc_SPRINTF(next,
2255                     _nc_SLIMIT(sizeof(blob) - (size_t) (next - blob))
2256                     "XYZ%d", count);
2257         strings[k] = next;
2258         next += strlen(next) + 1;
2259     }
2260
2261     _nc_reset_tparm(NULL);
2262     expect = tparm_type(name);
2263     nparam = _nc_tparm_analyze(NULL, value, p_is_s, &ignored);
2264     actual = guess_tparm_type(nparam, p_is_s);
2265
2266     if (expect != actual) {
2267         _nc_warning("%s has mismatched parameters", name);
2268         actual = Other;
2269     }
2270
2271     _nc_reset_tparm(NULL);
2272     switch (actual) {
2273     case Num_Str:
2274         result = TPARM_2(value, numbers[1], strings[2]);
2275         break;
2276     case Num_Str_Str:
2277         result = TPARM_3(value, numbers[1], strings[2], strings[3]);
2278         break;
2279     case Numbers:
2280 #define myParam(n) numbers[n]
2281         result = TIPARM_9(value,
2282                           myParam(1),
2283                           myParam(2),
2284                           myParam(3),
2285                           myParam(4),
2286                           myParam(5),
2287                           myParam(6),
2288                           myParam(7),
2289                           myParam(8),
2290                           myParam(9));
2291 #undef myParam
2292         break;
2293     case Other:
2294     default:
2295 #define myParam(n) (p_is_s[n - 1] != 0 ? ((TPARM_ARG) strings[n]) : numbers[n])
2296         result = TPARM_9(value,
2297                          myParam(1),
2298                          myParam(2),
2299                          myParam(3),
2300                          myParam(4),
2301                          myParam(5),
2302                          myParam(6),
2303                          myParam(7),
2304                          myParam(8),
2305                          myParam(9));
2306 #undef myParam
2307         break;
2308     }
2309     return strdup(result);
2310 }
2311
2312 #define IsDelay(ch) ((ch) == '.' || isdigit(UChar(ch)))
2313
2314 static const char *
2315 parse_delay_value(const char *src, double *delays, int *always)
2316 {
2317     int star = 0;
2318
2319     *delays = 0.0;
2320     if (always)
2321         *always = 0;
2322
2323     while (isdigit(UChar(*src))) {
2324         (*delays) = (*delays) * 10 + (*src++ - '0');
2325     }
2326     if (*src == '.') {
2327         int gotdot = 1;
2328
2329         ++src;
2330         while (isdigit(UChar(*src))) {
2331             gotdot *= 10;
2332             (*delays) += (*src++ - '0') / gotdot;
2333         }
2334     }
2335     while (*src == '*' || *src == '/') {
2336         if (always == NULL && *src == '/')
2337             break;
2338         if (*src++ == '*') {
2339             star = 1;
2340         } else {
2341             *always = 1;
2342         }
2343     }
2344     if (star)
2345         *delays = -(*delays);
2346     return src;
2347 }
2348
2349 static const char *
2350 parse_ti_delay(const char *ti, double *delays)
2351 {
2352     *delays = 0.0;
2353     while (*ti != '\0') {
2354         if (*ti == '\\') {
2355             ++ti;
2356         }
2357         if (ti[0] == '$'
2358             && ti[1] == '<'
2359             && IsDelay(UChar(ti[2]))) {
2360             int ignored;
2361             const char *last = parse_delay_value(ti + 2, delays, &ignored);
2362             if (*last == '>') {
2363                 ti = last;
2364             }
2365         } else {
2366             ++ti;
2367         }
2368     }
2369     return ti;
2370 }
2371
2372 static const char *
2373 parse_tc_delay(const char *tc, double *delays)
2374 {
2375     return parse_delay_value(tc, delays, (int *) 0);
2376 }
2377
2378 /*
2379  * Compare terminfo- and termcap-strings, factoring out delays.
2380  */
2381 static bool
2382 same_ti_tc(const char *ti, const char *tc, bool * embedded)
2383 {
2384     bool same = TRUE;
2385     double ti_delay = 0.0;
2386     double tc_delay = 0.0;
2387     const char *ti_last;
2388
2389     *embedded = FALSE;
2390     ti_last = parse_ti_delay(ti, &ti_delay);
2391     tc = parse_tc_delay(tc, &tc_delay);
2392
2393     while ((ti < ti_last) && *tc) {
2394         if (*ti == '\\' && ispunct(UChar(ti[1]))) {
2395             ++ti;
2396             if ((*ti == '^') && !strncmp(tc, "\\136", 4)) {
2397                 ti += 1;
2398                 tc += 4;
2399                 continue;
2400             }
2401         } else if (ti[0] == '$' && ti[1] == '<') {
2402             double no_delay;
2403             const char *ss = parse_ti_delay(ti, &no_delay);
2404             if (ss != ti) {
2405                 *embedded = TRUE;
2406                 ti = ss;
2407                 continue;
2408             }
2409         }
2410         if (*tc == '\\' && ispunct(UChar(tc[1]))) {
2411             ++tc;
2412         }
2413         if (*ti++ != *tc++) {
2414             same = FALSE;
2415             break;
2416         }
2417     }
2418
2419     if (*embedded) {
2420         if (same) {
2421             same = FALSE;
2422         } else {
2423             *embedded = FALSE;  /* report only one problem */
2424         }
2425     }
2426
2427     return same;
2428 }
2429
2430 /*
2431  * Check terminfo to termcap translation.
2432  */
2433 static void
2434 check_infotocap(TERMTYPE2 *tp, int i, const char *value)
2435 {
2436     const char *name = ExtStrname(tp, i, strnames);
2437     int params = ((i < (int) SIZEOF(parametrized))
2438                   ? parametrized[i]
2439                   : ((*value == 'k')
2440                      ? 0
2441                      : has_params(value, FALSE)));
2442     char *ti_value = NULL;
2443     char *tc_value;
2444     bool embedded;
2445
2446     assert(SIZEOF(parametrized) == STRCOUNT);
2447     if (!VALID_STRING(value) || (ti_value = strdup(value)) == NULL) {
2448         _nc_warning("tic-expansion of %s failed", name);
2449     } else if ((tc_value = _nc_infotocap(name, ti_value, params)) == ABSENT_STRING) {
2450         _nc_warning("tic-conversion of %s failed", name);
2451     } else if (params > 0) {
2452         int limit = 5;
2453         int count;
2454         bool first = TRUE;
2455
2456         if (!strcmp(name, "setf")
2457             || !strcmp(name, "setb")
2458             || !strcmp(name, "setaf")
2459             || !strcmp(name, "setab")) {
2460             if ((limit = max_colors) > 256)
2461                 limit = 256;
2462         }
2463         for (count = 0; count < limit; ++count) {
2464             char *ti_check = check_1_infotocap(name, ti_value, count);
2465             char *tc_check = check_1_infotocap(name, tc_value, count);
2466
2467             if (strcmp(ti_check, tc_check)) {
2468                 if (first) {
2469                     fprintf(stderr, "check_infotocap(%s)\n", name);
2470                     fprintf(stderr, "...ti '%s'\n", _nc_visbuf2(0, ti_value));
2471                     fprintf(stderr, "...tc '%s'\n", _nc_visbuf2(0, tc_value));
2472                     first = FALSE;
2473                 }
2474                 _nc_warning("tparm-conversion of %s(%d) differs between\n\tterminfo %s\n\ttermcap  %s",
2475                             name, count,
2476                             _nc_visbuf2(0, ti_check),
2477                             _nc_visbuf2(1, tc_check));
2478             }
2479             free(ti_check);
2480             free(tc_check);
2481         }
2482     } else if (params == 0 && !same_ti_tc(ti_value, tc_value, &embedded)) {
2483         if (embedded) {
2484             _nc_warning("termcap equivalent of %s cannot use embedded delay", name);
2485         } else {
2486             _nc_warning("tic-conversion of %s changed value\n\tfrom %s\n\tto   %s",
2487                         name, ti_value, tc_value);
2488         }
2489     }
2490     free(ti_value);
2491 }
2492
2493 static char *
2494 skip_delay(char *s)
2495 {
2496     while (*s == '/' || isdigit(UChar(*s)))
2497         ++s;
2498     return s;
2499 }
2500
2501 /*
2502  * Skip a delay altogether, e.g., when comparing a simple string to sgr,
2503  * the latter may have a worst-case delay on the end.
2504  */
2505 static char *
2506 ignore_delays(char *s)
2507 {
2508     int delaying = 0;
2509
2510     do {
2511         switch (*s) {
2512         case '$':
2513             if (delaying == 0)
2514                 delaying = 1;
2515             break;
2516         case '<':
2517             if (delaying == 1)
2518                 delaying = 2;
2519             break;
2520         case '\0':
2521             delaying = 0;
2522             break;
2523         default:
2524             if (delaying) {
2525                 s = skip_delay(s);
2526                 if (*s == '>')
2527                     ++s;
2528                 delaying = 0;
2529             }
2530             break;
2531         }
2532         if (delaying)
2533             ++s;
2534     } while (delaying);
2535     return s;
2536 }
2537
2538 #define DATA(name) { #name }
2539 static const char sgr_names[][11] =
2540 {
2541     DATA(none),
2542     DATA(standout),
2543     DATA(underline),
2544     DATA(reverse),
2545     DATA(blink),
2546     DATA(dim),
2547     DATA(bold),
2548     DATA(invis),
2549     DATA(protect),
2550     DATA(altcharset),
2551     ""
2552 };
2553 #undef DATA
2554
2555 /*
2556  * An sgr string may contain several settings other than the one we're
2557  * interested in, essentially sgr0 + rmacs + whatever.  As long as the
2558  * "whatever" is contained in the sgr string, that is close enough for our
2559  * sanity check.
2560  */
2561 static bool
2562 similar_sgr(int num, char *a, char *b)
2563 {
2564     char *base_a = a;
2565     char *base_b = b;
2566     int delaying = 0;
2567
2568     while (*b != 0) {
2569         while (*a != *b) {
2570             if (*a == 0) {
2571                 if (num < 0) {
2572                     ;
2573                 } else if (b[0] == '$'
2574                            && b[1] == '<') {
2575                     _nc_warning("did not find delay %s", _nc_visbuf(b));
2576                 } else {
2577                     _nc_warning("checking sgr(%s) %s\n\tcompare to %s\n\tunmatched %s",
2578                                 sgr_names[num], _nc_visbuf2(1, base_a),
2579                                 _nc_visbuf2(2, base_b),
2580                                 _nc_visbuf2(3, b));
2581                 }
2582                 return FALSE;
2583             } else if (delaying) {
2584                 a = skip_delay(a);
2585                 b = skip_delay(b);
2586             } else if ((*b == '0' || (*b == ';')) && *a == 'm') {
2587                 b++;
2588             } else {
2589                 a++;
2590             }
2591         }
2592         switch (*a) {
2593         case '$':
2594             if (delaying == 0)
2595                 delaying = 1;
2596             break;
2597         case '<':
2598             if (delaying == 1)
2599                 delaying = 2;
2600             break;
2601         default:
2602             delaying = 0;
2603             break;
2604         }
2605         a++;
2606         b++;
2607     }
2608     /* ignore delays on the end of the string */
2609     a = ignore_delays(a);
2610     return ((num != 0) || (*a == 0));
2611 }
2612
2613 static void
2614 check_tparm_err(int num)
2615 {
2616     if (_nc_tparm_err)
2617         _nc_warning("tparam error in sgr(%d): %s", num, sgr_names[num]);
2618 }
2619
2620 static char *
2621 check_sgr(TERMTYPE2 *tp, char *zero, int num, char *cap, const char *name)
2622 {
2623     char *test;
2624
2625     _nc_tparm_err = 0;
2626     test = TIPARM_9(set_attributes,
2627                     num == 1,
2628                     num == 2,
2629                     num == 3,
2630                     num == 4,
2631                     num == 5,
2632                     num == 6,
2633                     num == 7,
2634                     num == 8,
2635                     num == 9);
2636     if (test != 0) {
2637         if (PRESENT(cap)) {
2638             if (!similar_sgr(num, test, cap)) {
2639                 _nc_warning("%s differs from sgr(%d)\n\t%s=%s\n\tsgr(%d)=%s",
2640                             name, num,
2641                             name, _nc_visbuf2(1, cap),
2642                             num, _nc_visbuf2(2, test));
2643             }
2644         } else if (_nc_capcmp(test, zero)) {
2645             _nc_warning("sgr(%d) present, but not %s", num, name);
2646         }
2647     } else if (PRESENT(cap)) {
2648         _nc_warning("sgr(%d) missing, but %s present", num, name);
2649     }
2650     check_tparm_err(num);
2651     return test;
2652 }
2653
2654 #define CHECK_SGR(num,name) check_sgr(tp, zero, num, name, #name)
2655
2656 #ifdef TRACE
2657 /*
2658  * If tic is compiled with TRACE, we'll be able to see the output from the
2659  * DEBUG() macro.  But since it doesn't use traceon(), it always goes to
2660  * the standard error.  Use this function to make it simpler to follow the
2661  * resulting debug traces.
2662  */
2663 static void
2664 show_where(unsigned level)
2665 {
2666     if (_nc_tracing >= DEBUG_LEVEL(level)) {
2667         char my_name[MAX_NAME_SIZE];
2668         _nc_get_type(my_name);
2669         _tracef("\"%s\", line %d, '%s'",
2670                 _nc_get_source(),
2671                 _nc_curr_line, my_name);
2672     }
2673 }
2674
2675 #else
2676 #define show_where(level)       /* nothing */
2677 #endif
2678
2679 typedef struct {
2680     int keycode;
2681     const char *name;
2682     const char *value;
2683 } NAME_VALUE;
2684
2685 static NAME_VALUE *
2686 get_fkey_list(TERMTYPE2 *tp)
2687 {
2688     NAME_VALUE *result = typeMalloc(NAME_VALUE, NUM_STRINGS(tp) + 1);
2689     const struct tinfo_fkeys *all_fkeys = _nc_tinfo_fkeys;
2690     int used = 0;
2691     unsigned j;
2692
2693     if (result == NULL)
2694         failed("get_fkey_list");
2695
2696     for (j = 0; all_fkeys[j].code; j++) {
2697         char *a = tp->Strings[all_fkeys[j].offset];
2698         if (VALID_STRING(a)) {
2699             result[used].keycode = (int) all_fkeys[j].code;
2700             result[used].name = strnames[all_fkeys[j].offset];
2701             result[used].value = a;
2702             ++used;
2703         }
2704     }
2705 #if NCURSES_XNAMES
2706     for (j = STRCOUNT; j < NUM_STRINGS(tp); ++j) {
2707         const char *name = ExtStrname(tp, (int) j, strnames);
2708         if (*name == 'k') {
2709             result[used].keycode = -1;
2710             result[used].name = name;
2711             result[used].value = tp->Strings[j];
2712             ++used;
2713         }
2714     }
2715 #endif
2716     result[used].keycode = 0;
2717     return result;
2718 }
2719
2720 static void
2721 show_fkey_name(NAME_VALUE * data)
2722 {
2723     if (data->keycode > 0) {
2724         fprintf(stderr, " %s", keyname(data->keycode));
2725         fprintf(stderr, " (capability \"%s\")", data->name);
2726     } else {
2727         fprintf(stderr, " capability \"%s\"", data->name);
2728     }
2729 }
2730
2731 /*
2732  * A terminal entry may contain more than one keycode assigned to a given
2733  * string (e.g., KEY_END and KEY_LL).  But curses will only return one (the
2734  * last one assigned).
2735  */
2736 static void
2737 check_conflict(TERMTYPE2 *tp)
2738 {
2739     if (!(_nc_syntax == SYN_TERMCAP && capdump)) {
2740         char *check = calloc((size_t) (NUM_STRINGS(tp) + 1), sizeof(char));
2741         NAME_VALUE *given = get_fkey_list(tp);
2742         unsigned j, k;
2743         bool conflict = FALSE;
2744
2745         if (check == NULL)
2746             failed("check_conflict");
2747
2748         for (j = 0; given[j].keycode; ++j) {
2749             const char *a = given[j].value;
2750             bool first = TRUE;
2751
2752             if (!VALID_STRING(a))
2753                 continue;
2754
2755             for (k = j + 1; given[k].keycode; k++) {
2756                 const char *b = given[k].value;
2757
2758                 if (!VALID_STRING(b))
2759                     continue;
2760                 if (check[k])
2761                     continue;
2762
2763                 if (!_nc_capcmp(a, b)) {
2764                     check[j] = 1;
2765                     check[k] = 1;
2766                     if (first) {
2767                         if (!conflict) {
2768                             _nc_warning("conflicting key definitions (using the last)");
2769                             conflict = TRUE;
2770                         }
2771                         fprintf(stderr, "...");
2772                         show_fkey_name(given + j);
2773                         fprintf(stderr, " is the same as");
2774                         show_fkey_name(given + k);
2775                         first = FALSE;
2776                     } else {
2777                         fprintf(stderr, ", ");
2778                         show_fkey_name(given + k);
2779                     }
2780                 }
2781             }
2782             if (!first)
2783                 fprintf(stderr, "\n");
2784         }
2785 #if NCURSES_XNAMES
2786         if (using_extensions) {
2787             /* *INDENT-OFF* */
2788             static struct {
2789                 const char *xcurses;
2790                 const char *shifted;
2791             } table[] = {
2792                 { "kDC",  NULL },
2793                 { "kDN",  "kind" },
2794                 { "kEND", NULL },
2795                 { "kHOM", NULL },
2796                 { "kLFT", NULL },
2797                 { "kNXT", NULL },
2798                 { "kPRV", NULL },
2799                 { "kRIT", NULL },
2800                 { "kUP",  "kri" },
2801                 { NULL,   NULL },
2802             };
2803             /* *INDENT-ON* */
2804             /*
2805              * SVr4 curses defines the "xcurses" names listed above except for
2806              * the special cases in the "shifted" column.  When using these
2807              * names for xterm's extensions, that was confusing, and resulted
2808              * in adding extended capabilities with "2" (shift) suffix.  This
2809              * check warns about unnecessary use of extensions for this quirk.
2810              */
2811             for (j = 0; given[j].keycode; ++j) {
2812                 const char *find = given[j].name;
2813                 int value;
2814                 char ch;
2815
2816                 if (!VALID_STRING(given[j].value))
2817                     continue;
2818
2819                 for (k = 0; table[k].xcurses; ++k) {
2820                     const char *test = table[k].xcurses;
2821                     size_t size = strlen(test);
2822
2823                     if (!strncmp(find, test, size) && strcmp(find, test)) {
2824                         switch (sscanf(find + size, "%d%c", &value, &ch)) {
2825                         case 1:
2826                             if (value == 2) {
2827                                 _nc_warning("expected '%s' rather than '%s'",
2828                                             (table[k].shifted
2829                                              ? table[k].shifted
2830                                              : test), find);
2831                             } else if (value < 2 || value > 15) {
2832                                 _nc_warning("expected numeric 2..15 '%s'", find);
2833                             }
2834                             break;
2835                         default:
2836                             _nc_warning("expected numeric suffix for '%s'", find);
2837                             break;
2838                         }
2839                         break;
2840                     }
2841                 }
2842             }
2843         }
2844 #endif
2845         free(given);
2846         free(check);
2847     }
2848 }
2849
2850 /*
2851  * Exiting a video mode should not duplicate sgr0
2852  */
2853 static void
2854 check_exit_attribute(const char *name, char *test, char *trimmed, char *untrimmed)
2855 {
2856     if (VALID_STRING(test) && (trimmed != 0)) {
2857         if (similar_sgr(-1, trimmed, test) ||
2858             similar_sgr(-1, untrimmed, test)) {
2859             _nc_warning("%s matches exit_attribute_mode", name);
2860         }
2861     }
2862 }
2863
2864 /*
2865  * Returns true if the string looks like a standard SGR string.
2866  */
2867 static bool
2868 is_sgr_string(char *value)
2869 {
2870     bool result = FALSE;
2871
2872     if (VALID_STRING(value)) {
2873         int skip = csi_length(value);
2874
2875         if (skip) {
2876             int ch;
2877
2878             result = TRUE;
2879             value += skip;
2880             while ((ch = UChar(*value++)) != '\0') {
2881                 if (isdigit(ch) || ch == ';') {
2882                     ;
2883                 } else if (ch == 'm' && *value == '\0') {
2884                     ;
2885                 } else {
2886                     result = FALSE;
2887                     break;
2888                 }
2889             }
2890         }
2891     }
2892     return result;
2893 }
2894
2895 /*
2896  * Check if the given capability contains a given SGR attribute.
2897  */
2898 static void
2899 check_sgr_param(TERMTYPE2 *tp, int code, const char *name, char *value)
2900 {
2901     if (VALID_STRING(value)) {
2902         int ncv = ((code != 0) ? (1 << (code - 1)) : 0);
2903         char *test = tgoto(value, 0, 0);
2904         if (is_sgr_string(test)) {
2905             int param = 0;
2906             int count = 0;
2907             int skips = 0;
2908             int color = (value == set_a_foreground ||
2909                          value == set_a_background ||
2910                          value == set_foreground ||
2911                          value == set_background);
2912             while (*test != 0) {
2913                 if (isdigit(UChar(*test))) {
2914                     param = 10 * param + (*test - '0');
2915                     ++count;
2916                 } else {
2917                     if (count) {
2918                         /*
2919                          * Avoid unnecessary warning for xterm 256color codes.
2920                          */
2921                         if (color && (param == 38 || param == 48))
2922                             skips = 3;
2923                         if ((skips-- <= 0) && (param == code))
2924                             break;
2925                     }
2926                     count = 0;
2927                     param = 0;
2928                 }
2929                 ++test;
2930             }
2931             if (count != 0 && param == code) {
2932                 if (code == 0 ||
2933                     no_color_video < 0 ||
2934                     !(no_color_video & ncv)) {
2935                     _nc_warning("\"%s\" SGR-attribute used in %s",
2936                                 sgr_names[code],
2937                                 name);
2938                 }
2939             }
2940         }
2941     }
2942 }
2943
2944 #if NCURSES_XNAMES
2945 static int
2946 standard_type(const char *name)
2947 {
2948     int result = -1;
2949     const struct name_table_entry *np;
2950
2951     if ((np = _nc_find_entry(name, _nc_get_hash_table(0))) != 0) {
2952         result = np->nte_type;
2953     }
2954     return result;
2955 }
2956
2957 static const char *
2958 name_of_type(int type)
2959 {
2960     const char *result = "unknown";
2961     switch (type) {
2962     case BOOLEAN:
2963         result = "boolean";
2964         break;
2965     case NUMBER:
2966         result = "number";
2967         break;
2968     case STRING:
2969         result = "string";
2970         break;
2971     }
2972     return result;
2973 }
2974
2975 static void
2976 check_user_capability_type(const char *name, int actual)
2977 {
2978     if (lookup_user_capability(name) == 0) {
2979         int expected = standard_type(name);
2980         if (expected >= 0) {
2981             _nc_warning("expected %s to be %s, but actually %s",
2982                         name,
2983                         name_of_type(actual),
2984                         name_of_type(expected)
2985                 );
2986         } else if (*name != 'k') {
2987             _nc_warning("undocumented %s capability %s",
2988                         name_of_type(actual),
2989                         name);
2990         }
2991     }
2992 }
2993 #endif
2994
2995 #define IN_DELAY "0123456789*/."
2996
2997 static bool
2998 check_ANSI_cap(const char *value, int nparams, char final)
2999 {
3000     bool result = FALSE;
3001     if (VALID_STRING(value) && csi_length(value) > 0) {
3002         char *p_is_s[NUM_PARM];
3003         int popcount;
3004         int analyzed = _nc_tparm_analyze(NULL, value, p_is_s, &popcount);
3005         if (analyzed < popcount) {
3006             analyzed = popcount;
3007         }
3008         if (analyzed == nparams) {
3009             bool numbers = TRUE;
3010             int p;
3011             for (p = 0; p < nparams; ++p) {
3012                 if (p_is_s[p]) {
3013                     numbers = FALSE;
3014                     break;
3015                 }
3016             }
3017             if (numbers) {
3018                 int in_delay = 0;
3019                 p = (int) strlen(value);
3020                 while (p-- > 0) {
3021                     char ch = value[p];
3022                     if (ch == final) {
3023                         result = TRUE;
3024                         break;
3025                     }
3026                     switch (in_delay) {
3027                     case 0:
3028                         if (ch == '>')
3029                             in_delay = 1;
3030                         break;
3031                     case 1:
3032                         if (strchr(IN_DELAY, value[p]) != NULL)
3033                             break;
3034                         if (ch != '<')
3035                             p = 0;
3036                         in_delay = 2;
3037                         break;
3038                     case 2:
3039                         if (ch != '$')
3040                             p = 0;
3041                         in_delay = 0;
3042                         break;
3043                     }
3044                 }
3045             }
3046         }
3047     }
3048     return result;
3049 }
3050
3051 static const char *
3052 skip_Delay(const char *value)
3053 {
3054     const char *result = value;
3055
3056     if (*value == '$') {
3057         ++result;
3058         if (*result++ == '<') {
3059             while (strchr(IN_DELAY, *result) != NULL)
3060                 ++result;
3061             if (*result++ != '>') {
3062                 result = value;
3063             }
3064         } else {
3065             result = value;
3066         }
3067     }
3068     return result;
3069 }
3070
3071 static bool
3072 isValidString(const char *value, const char *expect)
3073 {
3074     bool result = FALSE;
3075     if (VALID_STRING(value)) {
3076         if (!strcmp(value, expect))
3077             result = TRUE;
3078     }
3079     return result;
3080 }
3081
3082 static bool
3083 isValidEscape(const char *value, const char *expect)
3084 {
3085     bool result = FALSE;
3086     if (VALID_STRING(value)) {
3087         if (*value == '\033') {
3088             size_t need = strlen(expect);
3089             size_t have = strlen(value) - 1;
3090             if (have >= need && !strncmp(value + 1, expect, need)) {
3091                 if (*skip_Delay(value + need + 1) == '\0') {
3092                     result = TRUE;
3093                 }
3094             }
3095         }
3096     }
3097     return result;
3098 }
3099
3100 static int
3101 guess_ANSI_VTxx(TERMTYPE2 *tp)
3102 {
3103     int result = -1;
3104     int checks = 0;
3105
3106     /* VT100s have scrolling region, but ANSI (ECMA-48) does not specify */
3107     if (check_ANSI_cap(change_scroll_region, 2, 'r') &&
3108         (isValidEscape(scroll_forward, "D") ||
3109          isValidString(scroll_forward, "\n") ||
3110          isValidEscape(scroll_forward, "6")) &&
3111         (isValidEscape(scroll_reverse, "M") ||
3112          isValidEscape(scroll_reverse, "9"))) {
3113         checks |= 2;
3114     }
3115     if (check_ANSI_cap(cursor_address, 2, 'H') &&
3116         check_ANSI_cap(cursor_up, 0, 'A') &&
3117         (check_ANSI_cap(cursor_down, 0, 'B') ||
3118          isValidString(cursor_down, "\n")) &&
3119         check_ANSI_cap(cursor_right, 0, 'C') &&
3120         (check_ANSI_cap(cursor_left, 0, 'D') ||
3121          isValidString(cursor_left, "\b")) &&
3122         check_ANSI_cap(clr_eos, 0, 'J') &&
3123         check_ANSI_cap(clr_bol, 0, 'K') &&
3124         check_ANSI_cap(clr_eol, 0, 'K')) {
3125         checks |= 1;
3126     }
3127     if (checks == 3)
3128         result = 1;
3129     if (checks == 1)
3130         result = 0;
3131     return result;
3132 }
3133
3134 /*
3135  * u6/u7 and u8/u9 are query/response extensions which most terminals support.
3136  * In particular, any ECMA-48 terminal should support these, though the details
3137  * for u9 are implementation dependent.
3138  */
3139 static void
3140 check_user_6789(TERMTYPE2 *tp)
3141 {
3142     /*
3143      * Check if the terminal is known to not 
3144      */
3145 #define NO_QUERY(longname,shortname) \
3146         if (PRESENT(longname)) _nc_warning(#shortname " is not supported")
3147     if (tigetflag("NQ") > 0) {
3148         NO_QUERY(user6, u6);
3149         NO_QUERY(user7, u7);
3150         NO_QUERY(user8, u8);
3151         NO_QUERY(user9, u9);
3152         return;
3153     }
3154
3155     PAIRED(user6, user7);
3156     PAIRED(user8, user9);
3157
3158     if (strchr(tp->term_names, '+') != NULL)
3159         return;
3160
3161     switch (guess_ANSI_VTxx(tp)) {
3162     case 1:
3163         if (!PRESENT(user8)) {
3164             _nc_warning("expected u8/u9 for device-attributes");
3165         }
3166         /* FALLTHRU */
3167     case 0:
3168         if (!PRESENT(user6)) {
3169             _nc_warning("expected u6/u7 for cursor-position");
3170         }
3171         break;
3172     }
3173 }
3174
3175 /* other sanity-checks (things that we don't want in the normal
3176  * logic that reads a terminfo entry)
3177  */
3178 static void
3179 check_termtype(TERMTYPE2 *tp, bool literal)
3180 {
3181     unsigned j;
3182
3183     check_conflict(tp);
3184
3185     for_each_string(j, tp) {
3186         char *a = tp->Strings[j];
3187         if (VALID_STRING(a)) {
3188             const char *name = ExtStrname(tp, (int) j, strnames);
3189             /*
3190              * If we expect parameters, or if there might be parameters,
3191              * check for consistent number of parameters.
3192              */
3193             if (j >= SIZEOF(parametrized) ||
3194                 is_user_capability(name) >= 0 ||
3195                 parametrized[j] > 0) {
3196                 check_params(tp, name, a, (j >= STRCOUNT));
3197             }
3198             check_delays(tp, ExtStrname(tp, (int) j, strnames), a);
3199             if (capdump) {
3200                 check_infotocap(tp, (int) j, a);
3201             }
3202         }
3203     }
3204 #if NCURSES_XNAMES
3205     /* in extended mode, verify that each extension is expected type */
3206     for_each_ext_boolean(j, tp) {
3207         check_user_capability_type(ExtBoolname(tp, (int) j, strnames), BOOLEAN);
3208     }
3209     for_each_ext_number(j, tp) {
3210         check_user_capability_type(ExtNumname(tp, (int) j, strnames), NUMBER);
3211     }
3212     for_each_ext_string(j, tp) {
3213         check_user_capability_type(ExtStrname(tp, (int) j, strnames), STRING);
3214     }
3215 #endif /* NCURSES_XNAMES */
3216
3217     check_acs(tp);
3218     check_colors(tp);
3219     check_cursor(tp);
3220     check_keypad(tp);
3221     check_printer(tp);
3222     check_screen(tp);
3223     check_user_6789(tp);
3224
3225     /*
3226      * These are probably both or none.
3227      */
3228     PAIRED(parm_index, parm_rindex);
3229     PAIRED(parm_ich, parm_dch);
3230
3231     /*
3232      * These may be mismatched because the terminal description relies on
3233      * restoring the cursor visibility by resetting it.
3234      */
3235     ANDMISSING(cursor_invisible, cursor_normal);
3236     ANDMISSING(cursor_visible, cursor_normal);
3237
3238     if (PRESENT(cursor_visible) && PRESENT(cursor_normal)
3239         && !_nc_capcmp(cursor_visible, cursor_normal))
3240         _nc_warning("cursor_visible is same as cursor_normal");
3241
3242     /*
3243      * From XSI & O'Reilly, we gather that sc/rc are required if csr is
3244      * given, because the cursor position after the scrolling operation is
3245      * performed is undefined.
3246      */
3247     ANDMISSING(change_scroll_region, save_cursor);
3248     ANDMISSING(change_scroll_region, restore_cursor);
3249
3250     /*
3251      * If we can clear tabs, we should be able to initialize them.
3252      */
3253     ANDMISSING(clear_all_tabs, set_tab);
3254
3255     if (PRESENT(set_attributes)) {
3256         char *zero = 0;
3257
3258         _nc_tparm_err = 0;
3259         if (PRESENT(exit_attribute_mode)) {
3260             zero = strdup(CHECK_SGR(0, exit_attribute_mode));
3261         } else {
3262             zero = strdup(TIPARM_9(set_attributes, 0, 0, 0, 0, 0, 0, 0, 0, 0));
3263         }
3264         check_tparm_err(0);
3265
3266         if (zero != 0) {
3267             CHECK_SGR(1, enter_standout_mode);
3268             CHECK_SGR(2, enter_underline_mode);
3269             CHECK_SGR(3, enter_reverse_mode);
3270             CHECK_SGR(4, enter_blink_mode);
3271             CHECK_SGR(5, enter_dim_mode);
3272             CHECK_SGR(6, enter_bold_mode);
3273             CHECK_SGR(7, enter_secure_mode);
3274             CHECK_SGR(8, enter_protected_mode);
3275             CHECK_SGR(9, enter_alt_charset_mode);
3276             free(zero);
3277         } else {
3278             _nc_warning("sgr(0) did not return a value");
3279         }
3280     } else if (PRESENT(exit_attribute_mode) &&
3281                set_attributes != CANCELLED_STRING) {
3282         if (_nc_syntax == SYN_TERMINFO)
3283             _nc_warning("missing sgr string");
3284     }
3285 #define CHECK_SGR0(name) check_exit_attribute(#name, name, check_sgr0, exit_attribute_mode)
3286     if (PRESENT(exit_attribute_mode)) {
3287         char *check_sgr0 = _nc_trim_sgr0(tp);
3288
3289         if (check_sgr0 == NULL || *check_sgr0 == '\0') {
3290             _nc_warning("trimmed sgr0 is empty");
3291         } else {
3292             show_where(2);
3293             if (check_sgr0 != exit_attribute_mode) {
3294                 DEBUG(2,
3295                       ("will trim sgr0\n\toriginal sgr0=%s\n\ttrimmed  sgr0=%s",
3296                        _nc_visbuf2(1, exit_attribute_mode),
3297                        _nc_visbuf2(2, check_sgr0)));
3298             } else {
3299                 DEBUG(2,
3300                       ("will not trim sgr0\n\toriginal sgr0=%s",
3301                        _nc_visbuf(exit_attribute_mode)));
3302             }
3303         }
3304 #if defined(exit_italics_mode)
3305         CHECK_SGR0(exit_italics_mode);
3306 #endif
3307         CHECK_SGR0(exit_standout_mode);
3308         CHECK_SGR0(exit_underline_mode);
3309         if (check_sgr0 != exit_attribute_mode) {
3310             free(check_sgr0);
3311         }
3312     }
3313 #define CHECK_SGR_PARAM(code, name) check_sgr_param(tp, (int)code, #name, name)
3314     for (j = 0; *sgr_names[j] != '\0'; ++j) {
3315         CHECK_SGR_PARAM(j, set_a_foreground);
3316         CHECK_SGR_PARAM(j, set_a_background);
3317         CHECK_SGR_PARAM(j, set_foreground);
3318         CHECK_SGR_PARAM(j, set_background);
3319     }
3320 #ifdef TRACE
3321     show_where(2);
3322     if (!auto_right_margin) {
3323         DEBUG(2,
3324               ("can write to lower-right directly"));
3325     } else if (PRESENT(enter_am_mode) && PRESENT(exit_am_mode)) {
3326         DEBUG(2,
3327               ("can write to lower-right by suppressing automargin"));
3328     } else if ((PRESENT(enter_insert_mode) && PRESENT(exit_insert_mode))
3329                || PRESENT(insert_character) || PRESENT(parm_ich)) {
3330         DEBUG(2,
3331               ("can write to lower-right by using inserts"));
3332     } else {
3333         DEBUG(2,
3334               ("cannot write to lower-right"));
3335     }
3336 #endif
3337
3338     /*
3339      * Some standard applications (e.g., vi) and some non-curses
3340      * applications (e.g., jove) get confused if we have both ich1 and
3341      * smir/rmir.  Let's be nice and warn about that, too, even though
3342      * ncurses handles it.
3343      */
3344     if ((PRESENT(enter_insert_mode) || PRESENT(exit_insert_mode))
3345         && PRESENT(insert_character)) {
3346         _nc_warning("non-curses applications may be confused by ich1 with smir/rmir");
3347     }
3348
3349     /*
3350      * Finally, do the non-verbose checks
3351      */
3352     if (save_check_termtype != 0)
3353         save_check_termtype(tp, literal);
3354 }