]> ncurses.scripts.mit.edu Git - ncurses.git/blob - progs/tic.c
cb7baf07715b98c60b323b2f5200e9a6b9fb9978
[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.318 2022/09/03 23:29:16 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     use_extended_names(FALSE);
726 #endif
727     _nc_strict_bsd = 0;
728
729     /*
730      * Processing arguments is a little complicated, since someone made a
731      * design decision to allow the numeric values for -w, -v options to
732      * be optional.
733      */
734     while ((this_opt = getopt(argc, argv,
735                               "0123456789CDIKLNQR:TUVWace:fGgo:qrstvwx")) != -1) {
736         if (isdigit(this_opt)) {
737             switch (last_opt) {
738             case 'Q':
739                 add_digit(&quickdump, this_opt);
740                 break;
741             case 'v':
742                 add_digit(&v_opt, this_opt);
743                 break;
744             case 'w':
745                 add_digit(&width, this_opt);
746                 break;
747             default:
748                 switch (this_opt) {
749                 case '0':
750                     last_opt = this_opt;
751                     width = 65535;
752                     height = 1;
753                     break;
754                 case '1':
755                     last_opt = this_opt;
756                     width = 0;
757                     break;
758                 default:
759                     usage();
760                 }
761             }
762             continue;
763         }
764         switch (this_opt) {
765         case 'K':
766             _nc_strict_bsd = 1;
767             /* the initial version of -K in 20110730 fell-thru here, but the
768              * same flag is useful when reading sources -TD
769              */
770             break;
771         case 'C':
772             capdump = TRUE;
773             outform = F_TERMCAP;
774             sortmode = S_TERMCAP;
775             break;
776         case 'D':
777             debug_level = VtoTrace(v_opt);
778             use_verbosity(debug_level);
779             show_databases(outdir);
780             ExitProgram(EXIT_SUCCESS);
781             break;
782         case 'I':
783             infodump = TRUE;
784             outform = F_TERMINFO;
785             sortmode = S_TERMINFO;
786             break;
787         case 'L':
788             infodump = TRUE;
789             outform = F_VARIABLE;
790             sortmode = S_VARIABLE;
791             break;
792         case 'N':
793             smart_defaults = FALSE;
794             literal = TRUE;
795             break;
796         case 'Q':
797             quickdump = 0;
798             break;
799         case 'R':
800             tversion = optarg;
801             break;
802         case 'T':
803             limited = FALSE;
804             break;
805         case 'U':
806             literal = TRUE;
807             break;
808         case 'V':
809             puts(curses_version());
810             ExitProgram(EXIT_SUCCESS);
811         case 'W':
812             wrap_strings = TRUE;
813             break;
814         case 'c':
815             check_only = TRUE;
816             break;
817         case 'e':
818             namelst = make_namelist(optarg);
819             break;
820         case 'f':
821             formatted = TRUE;
822             break;
823         case 'G':
824             numbers = 1;
825             break;
826         case 'g':
827             numbers = -1;
828             break;
829         case 'o':
830             outdir = optarg;
831             break;
832         case 'q':
833             quiet = TRUE;
834             break;
835         case 'r':
836             forceresolve = TRUE;
837             break;
838         case 's':
839             showsummary = TRUE;
840             break;
841         case 'v':
842             v_opt = 0;
843             break;
844         case 'w':
845             width = 0;
846             break;
847 #if NCURSES_XNAMES
848         case 't':
849             _nc_disable_period = FALSE;
850             suppress_untranslatable = TRUE;
851             break;
852         case 'a':
853             _nc_disable_period = TRUE;
854             /* FALLTHRU */
855         case 'x':
856             use_extended_names(TRUE);
857             using_extensions = TRUE;
858             break;
859 #endif
860         default:
861             usage();
862         }
863         last_opt = this_opt;
864     }
865
866     debug_level = VtoTrace(v_opt);
867     use_verbosity(debug_level);
868
869     if (_nc_tracing) {
870         save_check_termtype = _nc_check_termtype2;
871         _nc_check_termtype2 = check_termtype;
872     }
873 #if !HAVE_BIG_CORE
874     /*
875      * Aaargh! immedhook seriously hoses us!
876      *
877      * One problem with immedhook is it means we can't do -e.  Problem
878      * is that we can't guarantee that for each terminal listed, all the
879      * terminals it depends on will have been kept in core for reference
880      * resolution -- in fact it is certain the primitive types at the end
881      * of reference chains *won't* be in core unless they were explicitly
882      * in the select list themselves.
883      */
884     if (namelst && (!infodump && !capdump)) {
885         (void) fprintf(stderr,
886                        "%s: Sorry, -e can't be used without -I or -C\n",
887                        _nc_progname);
888         ExitProgram(EXIT_FAILURE);
889     }
890 #endif /* HAVE_BIG_CORE */
891
892     if (optind < argc) {
893         source_file = argv[optind++];
894         if (optind < argc) {
895             fprintf(stderr,
896                     "%s: Too many file names.  Usage:\n\t%s %s",
897                     _nc_progname,
898                     _nc_progname,
899                     usage_string);
900             ExitProgram(EXIT_FAILURE);
901         }
902     } else {
903         if (infodump == TRUE) {
904             /* captoinfo's no-argument case */
905             source_file = "/etc/termcap";
906             if ((termcap = getenv("TERMCAP")) != 0
907                 && (namelst = make_namelist(getenv("TERM"))) != 0) {
908                 if (access(termcap, F_OK) == 0) {
909                     /* file exists */
910                     source_file = termcap;
911                 } else {
912                     if ((tmp_fp = open_tempfile(my_tmpname)) != 0) {
913                         source_file = my_tmpname;
914                         fprintf(tmp_fp, "%s\n", termcap);
915                         fclose(tmp_fp);
916                         tmp_fp = open_input(source_file, (char *) 0);
917                         to_remove = source_file;
918                     } else {
919                         failed("tmpnam");
920                     }
921                 }
922             }
923         } else {
924             /* tic */
925             fprintf(stderr,
926                     "%s: File name needed.  Usage:\n\t%s %s",
927                     _nc_progname,
928                     _nc_progname,
929                     usage_string);
930             ExitProgram(EXIT_FAILURE);
931         }
932     }
933
934     if (tmp_fp == NULL) {
935         char my_altfile[PATH_MAX];
936         tmp_fp = open_input(source_file, my_altfile);
937         if (!strcmp(source_file, "-")) {
938             source_file = STDIN_NAME;
939         }
940     }
941
942     if (infodump || check_only) {
943         dump_init(tversion,
944                   (smart_defaults
945                    ? outform
946                    : F_LITERAL),
947                   sortmode,
948                   wrap_strings, width, height,
949                   debug_level, formatted || check_only, check_only, quickdump);
950     } else if (capdump) {
951         dump_init(tversion,
952                   outform,
953                   sortmode,
954                   wrap_strings, width, height,
955                   debug_level, FALSE, FALSE, FALSE);
956     }
957
958     /* parse entries out of the source file */
959     _nc_set_source(source_file);
960 #if !HAVE_BIG_CORE
961     if (!(check_only || infodump || capdump))
962         _nc_set_writedir(outdir);
963 #endif /* HAVE_BIG_CORE */
964     _nc_read_entry_source(tmp_fp, (char *) NULL,
965                           !smart_defaults || literal, FALSE,
966                           ((check_only || infodump || capdump)
967                            ? NULLHOOK
968                            : immedhook));
969
970     /* do use resolution */
971     if (check_only || (!infodump && !capdump) || forceresolve) {
972         if (!_nc_resolve_uses2(TRUE, literal) && !check_only) {
973             ExitProgram(EXIT_FAILURE);
974         }
975     }
976
977     /* length check */
978     if (check_only && limited && (capdump || infodump)) {
979         for_entry_list(qp) {
980             if (matches(namelst, qp->tterm.term_names)) {
981                 int len = fmt_entry(&qp->tterm, NULL, FALSE, TRUE, infodump, numbers);
982
983                 if (len > (infodump ? MAX_TERMINFO_LENGTH : MAX_TERMCAP_LENGTH))
984                     (void) fprintf(stderr,
985                                    "%s: resolved %s entry is %d bytes long\n",
986                                    _nc_progname,
987                                    _nc_first_name(qp->tterm.term_names),
988                                    len);
989             }
990         }
991     }
992
993     /* write or dump all entries */
994     if (check_only) {
995         /* this is in case infotocap() generates warnings */
996         _nc_curr_col = _nc_curr_line = -1;
997
998         for_entry_list(qp) {
999             if (matches(namelst, qp->tterm.term_names)) {
1000                 /* this is in case infotocap() generates warnings */
1001                 _nc_set_type(_nc_first_name(qp->tterm.term_names));
1002                 _nc_curr_line = (int) qp->startline;
1003                 repair_acsc(&qp->tterm);
1004                 dump_entry(&qp->tterm, suppress_untranslatable,
1005                            limited, numbers, NULL);
1006             }
1007         }
1008     } else {
1009         if (!infodump && !capdump) {
1010             _nc_set_writedir(outdir);
1011             for_entry_list(qp) {
1012                 if (matches(namelst, qp->tterm.term_names))
1013                     write_it(qp);
1014             }
1015         } else {
1016             /* this is in case infotocap() generates warnings */
1017             _nc_curr_col = _nc_curr_line = -1;
1018
1019             for_entry_list(qp) {
1020                 if (matches(namelst, qp->tterm.term_names)) {
1021                     long j = qp->cend - qp->cstart;
1022                     int len = 0;
1023
1024                     /* this is in case infotocap() generates warnings */
1025                     _nc_set_type(_nc_first_name(qp->tterm.term_names));
1026
1027                     if (!quiet) {
1028                         (void) fseek(tmp_fp, qp->cstart, SEEK_SET);
1029                         while (j-- > 0) {
1030                             int ch = fgetc(tmp_fp);
1031                             if (ch == EOF || ferror(tmp_fp)) {
1032                                 break;
1033                             } else if (infodump) {
1034                                 (void) putchar(ch);
1035                             } else {
1036                                 put_translate(ch);
1037                             }
1038                         }
1039                     }
1040
1041                     repair_acsc(&qp->tterm);
1042                     dump_entry(&qp->tterm, suppress_untranslatable,
1043                                limited, numbers, NULL);
1044                     for (j = 0; j < (long) qp->nuses; j++)
1045                         dump_uses(qp->uses[j].name, !capdump);
1046                     len = show_entry();
1047                     if (debug_level != 0 && !limited)
1048                         printf("# length=%d\n", len);
1049                 }
1050             }
1051             if (!namelst && _nc_tail && !quiet) {
1052                 int c, oldc = '\0';
1053                 bool in_comment = FALSE;
1054                 bool trailing_comment = FALSE;
1055
1056                 (void) fseek(tmp_fp, _nc_tail->cend, SEEK_SET);
1057                 while ((c = fgetc(tmp_fp)) != EOF) {
1058                     if (oldc == '\n') {
1059                         if (c == '#') {
1060                             trailing_comment = TRUE;
1061                             in_comment = TRUE;
1062                         } else {
1063                             in_comment = FALSE;
1064                         }
1065                     }
1066                     if (trailing_comment
1067                         && (in_comment || (oldc == '\n' && c == '\n')))
1068                         putchar(c);
1069                     oldc = c;
1070                 }
1071             }
1072         }
1073     }
1074
1075     /* Show the directory into which entries were written, and the total
1076      * number of entries
1077      */
1078     if (showsummary
1079         && (!(check_only || infodump || capdump))) {
1080         int total = _nc_tic_written();
1081         if (total != 0)
1082             fprintf(log_fp, "%d entries written to %s\n",
1083                     total,
1084                     _nc_tic_dir(NULL));
1085         else
1086             fprintf(log_fp, "No entries written\n");
1087     }
1088     ExitProgram(EXIT_SUCCESS);
1089 }
1090
1091 /*
1092  * This bit of legerdemain turns all the terminfo variable names into
1093  * references to locations in the arrays Booleans, Numbers, and Strings ---
1094  * precisely what's needed (see comp_parse.c).
1095  */
1096 #undef CUR
1097 #define CUR tp->
1098
1099 /*
1100  * Check if the alternate character-set capabilities are consistent.
1101  */
1102 static void
1103 check_acs(TERMTYPE2 *tp)
1104 {
1105     int vt100_smacs = 0;
1106     int vt100_rmacs = 0;
1107     int vt100_enacs = 0;
1108
1109     /*
1110      * ena_acs is not always necessary, but if it is present, the enter/exit
1111      * capabilities should be.
1112      */
1113     ANDMISSING(ena_acs, enter_alt_charset_mode);
1114     ANDMISSING(ena_acs, exit_alt_charset_mode);
1115     PAIRED(exit_alt_charset_mode, exit_alt_charset_mode);
1116
1117     /*
1118      * vt100-like is frequently used, but perhaps ena_acs is missing, etc.
1119      */
1120     if (VALID_STRING(enter_alt_charset_mode)) {
1121         vt100_smacs = (!strcmp("\033(0", enter_alt_charset_mode)
1122                        ? 2
1123                        : (!strcmp("\016", enter_alt_charset_mode)
1124                           ? 1
1125                           : 0));
1126     }
1127     if (VALID_STRING(exit_alt_charset_mode)) {
1128         vt100_rmacs = (!strcmp("\033(B", exit_alt_charset_mode)
1129                        ? 2
1130                        : (!strcmp("\017", exit_alt_charset_mode)
1131                           ? 1
1132                           : 0));
1133     }
1134     if (VALID_STRING(ena_acs)) {
1135         vt100_enacs = (!strcmp("\033(B\033)0", ena_acs)
1136                        ? 2
1137                        : 0);
1138     }
1139     if (vt100_rmacs && vt100_smacs && (vt100_rmacs != vt100_smacs)) {
1140         _nc_warning("rmacs/smacs are inconsistent");
1141     }
1142     if ((vt100_rmacs == 2) && (vt100_smacs == 2) && vt100_enacs) {
1143         _nc_warning("rmacs/smacs make enacs redundant");
1144     }
1145     if ((vt100_rmacs == 1) && (vt100_smacs == 1) && !vt100_enacs) {
1146         _nc_warning("VT100-style rmacs/smacs require enacs");
1147     }
1148
1149     if (VALID_STRING(acs_chars)) {
1150         const char *boxes = "lmkjtuvwqxn";
1151         char mapped[256];
1152         char missing[256];
1153         const char *p;
1154         char *q;
1155
1156         memset(mapped, 0, sizeof(mapped));
1157         for (p = acs_chars; *p != '\0'; p += 2) {
1158             if (p[1] == '\0') {
1159                 _nc_warning("acsc has odd number of characters");
1160                 break;
1161             }
1162             mapped[UChar(p[0])] = p[1];
1163         }
1164
1165         if (mapped[UChar('I')] && !mapped[UChar('i')]) {
1166             _nc_warning("acsc refers to 'I', which is probably an error");
1167         }
1168
1169         for (p = boxes, q = missing; *p != '\0'; ++p) {
1170             if (!mapped[UChar(p[0])]) {
1171                 *q++ = p[0];
1172             }
1173         }
1174         *q = '\0';
1175
1176         assert(strlen(missing) <= strlen(boxes));
1177         if (*missing != '\0' && strcmp(missing, boxes)) {
1178             _nc_warning("acsc is missing some line-drawing mapping: %s", missing);
1179         }
1180     }
1181 }
1182
1183 static char *
1184 safe_strdup(const char *value)
1185 {
1186     if (value == NULL)
1187         value = "";
1188     return strdup(value);
1189 }
1190
1191 static bool
1192 same_color(NCURSES_CONST char *oldcap, NCURSES_CONST char *newcap, int limit)
1193 {
1194     bool result = FALSE;
1195     if (limit > 16)
1196         limit = 16;
1197     if (limit >= 8) {
1198         int n;
1199         int same;
1200         for (n = same = 0; n < limit; ++n) {
1201             char *oldvalue = safe_strdup(TIPARM_1(oldcap, n));
1202             char *newvalue = safe_strdup(TIPARM_1(newcap, n));
1203             same += !strcmp(oldvalue, newvalue);
1204             free(oldvalue);
1205             free(newvalue);
1206         }
1207         result = (same == limit);
1208     }
1209     return result;
1210 }
1211
1212 /*
1213  * Check if the color capabilities are consistent
1214  */
1215 static void
1216 check_colors(TERMTYPE2 *tp)
1217 {
1218     char *value;
1219
1220     if ((max_colors > 0) != (max_pairs > 0)
1221         || ((max_colors > max_pairs) && !VALID_STRING(initialize_pair)))
1222         _nc_warning("inconsistent values for max_colors (%d) and max_pairs (%d)",
1223                     max_colors, max_pairs);
1224
1225     PAIRED(set_foreground, set_background);
1226     PAIRED(set_a_foreground, set_a_background);
1227     PAIRED(set_color_pair, initialize_pair);
1228
1229     if (VALID_STRING(set_foreground)
1230         && VALID_STRING(set_a_foreground)) {
1231         if (!_nc_capcmp(set_foreground, set_a_foreground)) {
1232             _nc_warning("expected setf/setaf to be different");
1233         } else if (same_color(set_foreground, set_a_foreground, max_colors)) {
1234             _nc_warning("setf/setaf are equivalent");
1235         }
1236     }
1237
1238     if (VALID_STRING(set_background)
1239         && VALID_STRING(set_a_background)) {
1240         if (!_nc_capcmp(set_background, set_a_background)) {
1241             _nc_warning("expected setb/setab to be different");
1242         } else if (same_color(set_background, set_a_background, max_colors)) {
1243             _nc_warning("setb/setab are equivalent");
1244         }
1245     }
1246
1247     /* see: has_colors() */
1248     if (VALID_NUMERIC(max_colors) && VALID_NUMERIC(max_pairs)
1249         && ((VALID_STRING(set_foreground)
1250              && VALID_STRING(set_background))
1251             || (VALID_STRING(set_a_foreground)
1252                 && VALID_STRING(set_a_background))
1253             || set_color_pair)) {
1254         if (!VALID_STRING(orig_pair) && !VALID_STRING(orig_colors))
1255             _nc_warning("expected either op/oc string for resetting colors");
1256     }
1257     if (can_change) {
1258         if (!VALID_STRING(initialize_pair) &&
1259             !VALID_STRING(initialize_color)) {
1260             _nc_warning("expected initc or initp because ccc is given");
1261         }
1262     } else {
1263         if (VALID_STRING(initialize_pair) ||
1264             VALID_STRING(initialize_color)) {
1265             _nc_warning("expected ccc because initc is given");
1266         }
1267     }
1268     value = tigetstr("RGB");
1269     if (VALID_STRING(value)) {
1270         int r, g, b;
1271         char bad;
1272         int code = sscanf(value, "%d/%d/%d%c", &r, &g, &b, &bad);
1273         if (code != 3 || r <= 0 || g <= 0 || b <= 0) {
1274             _nc_warning("unexpected value for RGB capability: %s", value);
1275         }
1276     }
1277 }
1278
1279 static int
1280 csi_length(const char *value)
1281 {
1282     int result = 0;
1283
1284     if (value[0] == '\033' && value[1] == '[') {
1285         result = 2;
1286     } else if (UChar(value[0]) == 0x9a) {
1287         result = 1;
1288     }
1289     return result;
1290 }
1291
1292 static char
1293 keypad_final(const char *string)
1294 {
1295     char result = '\0';
1296
1297     if (VALID_STRING(string)
1298         && *string++ == '\033'
1299         && *string++ == 'O'
1300         && strlen(string) == 1) {
1301         result = *string;
1302     }
1303
1304     return result;
1305 }
1306
1307 static long
1308 keypad_index(const char *string)
1309 {
1310     int ch;
1311     long result = -1;
1312
1313     if ((ch = keypad_final(string)) != '\0') {
1314         const char *list = "PQRSwxymtuvlqrsPpn";        /* app-keypad except "Enter" */
1315         char *test = (strchr) (list, ch);
1316         if (test != 0)
1317             result = (long) (test - list);
1318     }
1319     return result;
1320 }
1321
1322 /*
1323  * list[] is down, up, left, right
1324  * "left" may be ^H rather than \E[D
1325  * "down" may be ^J rather than \E[B
1326  * But up/right are generally consistently escape sequences for ANSI terminals.
1327  */
1328 static void
1329 check_ansi_cursor(char *list[4])
1330 {
1331     int j, k;
1332     bool skip[4];
1333     bool repeated = FALSE;
1334
1335     for (j = 0; j < 4; ++j) {
1336         skip[j] = FALSE;
1337         for (k = 0; k < j; ++k) {
1338             if (j != k
1339                 && !strcmp(list[j], list[k])) {
1340                 char *value = _nc_tic_expand(list[k], TRUE, 0);
1341                 _nc_warning("repeated cursor control %s", value);
1342                 repeated = TRUE;
1343             }
1344         }
1345     }
1346     if (!repeated) {
1347         char *up = list[1];
1348         size_t prefix = (size_t) csi_length(up);
1349         size_t suffix;
1350
1351         if (prefix) {
1352             suffix = prefix;
1353             while (up[suffix] && isdigit(UChar(up[suffix])))
1354                 ++suffix;
1355         }
1356         if (prefix && up[suffix] == 'A') {
1357             skip[1] = TRUE;
1358             if (!strcmp(list[0], "\n"))
1359                 skip[0] = TRUE;
1360             if (!strcmp(list[2], "\b"))
1361                 skip[2] = TRUE;
1362
1363             for (j = 0; j < 4; ++j) {
1364                 int want;
1365
1366                 if (skip[j] || strlen(list[j]) == 1)
1367                     continue;
1368                 if (memcmp(list[j], up, prefix)) {
1369                     char *value = _nc_tic_expand(list[j], TRUE, 0);
1370                     _nc_warning("inconsistent prefix for %s", value);
1371                     continue;
1372                 }
1373                 if (strlen(list[j]) < suffix) {
1374                     char *value = _nc_tic_expand(list[j], TRUE, 0);
1375                     _nc_warning("inconsistent length for %s, expected %d",
1376                                 value, (int) suffix + 1);
1377                     continue;
1378                 }
1379                 want = "BADC"[j];
1380                 if (list[j][suffix] != want) {
1381                     char *value = _nc_tic_expand(list[j], TRUE, 0);
1382                     _nc_warning("inconsistent suffix for %s, expected %c, have %c",
1383                                 value, want, list[j][suffix]);
1384                 }
1385             }
1386         }
1387     }
1388 }
1389
1390 #define EXPECTED(name) if (!PRESENT(name)) _nc_warning("expected " #name)
1391 #define UNEXPECTED(name) if (PRESENT(name)) _nc_warning("unexpected " #name ", for %s", why)
1392
1393 static void
1394 check_noaddress(TERMTYPE2 *tp, const char *why)
1395 {
1396     UNEXPECTED(column_address);
1397     UNEXPECTED(cursor_address);
1398     UNEXPECTED(cursor_home);
1399     UNEXPECTED(cursor_mem_address);
1400     UNEXPECTED(cursor_to_ll);
1401     UNEXPECTED(row_address);
1402     UNEXPECTED(row_address);
1403 }
1404
1405 static void
1406 check_cursor(TERMTYPE2 *tp)
1407 {
1408     int count;
1409     char *list[4];
1410
1411     if (hard_copy) {
1412         check_noaddress(tp, "hard_copy");
1413     } else if (generic_type) {
1414         check_noaddress(tp, "generic_type");
1415     } else if (strchr(tp->term_names, '+') == NULL) {
1416         int y = 0;
1417         int x = 0;
1418         if (PRESENT(column_address))
1419             ++y;
1420         if (PRESENT(cursor_address))
1421             y = x = 10;
1422         if (PRESENT(cursor_home))
1423             ++y, ++x;
1424         if (PRESENT(cursor_mem_address))
1425             y = x = 10;
1426         if (PRESENT(cursor_to_ll))
1427             ++y, ++x;
1428         if (PRESENT(row_address))
1429             ++x;
1430         if (PRESENT(cursor_down))
1431             ++y;
1432         if (PRESENT(cursor_up))
1433             ++y;
1434         if (PRESENT(cursor_left))
1435             ++x;
1436         if (PRESENT(cursor_right))
1437             ++x;
1438         if (x < 2 && y < 2) {
1439             _nc_warning("terminal lacks cursor addressing");
1440         } else {
1441             if (x < 2)
1442                 _nc_warning("terminal lacks cursor column-addressing");
1443             if (y < 2)
1444                 _nc_warning("terminal lacks cursor row-addressing");
1445         }
1446     }
1447
1448     /* it is rare to have an insert-line feature without a matching delete */
1449     ANDMISSING(parm_insert_line, insert_line);
1450     ANDMISSING(parm_delete_line, delete_line);
1451     ANDMISSING(parm_insert_line, parm_delete_line);
1452
1453     /* if we have a parameterized form, then the non-parameterized is easy */
1454     ANDMISSING(parm_down_cursor, cursor_down);
1455     ANDMISSING(parm_up_cursor, cursor_up);
1456     ANDMISSING(parm_left_cursor, cursor_left);
1457     ANDMISSING(parm_right_cursor, cursor_right);
1458
1459     /* Given any of a set of cursor movement, the whole set should be present.
1460      * Technically this is not true (we could use cursor_address to fill in
1461      * unsupported controls), but it is likely.
1462      */
1463     count = 0;
1464     if (PRESENT(parm_down_cursor)) {
1465         list[count++] = parm_down_cursor;
1466     }
1467     if (PRESENT(parm_up_cursor)) {
1468         list[count++] = parm_up_cursor;
1469     }
1470     if (PRESENT(parm_left_cursor)) {
1471         list[count++] = parm_left_cursor;
1472     }
1473     if (PRESENT(parm_right_cursor)) {
1474         list[count++] = parm_right_cursor;
1475     }
1476     if (count == 4) {
1477         check_ansi_cursor(list);
1478     } else if (count != 0) {
1479         EXPECTED(parm_down_cursor);
1480         EXPECTED(parm_up_cursor);
1481         EXPECTED(parm_left_cursor);
1482         EXPECTED(parm_right_cursor);
1483     }
1484
1485     count = 0;
1486     if (PRESENT(cursor_down)) {
1487         list[count++] = cursor_down;
1488     }
1489     if (PRESENT(cursor_up)) {
1490         list[count++] = cursor_up;
1491     }
1492     if (PRESENT(cursor_left)) {
1493         list[count++] = cursor_left;
1494     }
1495     if (PRESENT(cursor_right)) {
1496         list[count++] = cursor_right;
1497     }
1498     if (count == 4) {
1499         check_ansi_cursor(list);
1500     } else if (count != 0) {
1501         count = 0;
1502         if (PRESENT(cursor_down) && strcmp(cursor_down, "\n"))
1503             ++count;
1504         if (PRESENT(cursor_left) && strcmp(cursor_left, "\b"))
1505             ++count;
1506         if (PRESENT(cursor_up) && strlen(cursor_up) > 1)
1507             ++count;
1508         if (PRESENT(cursor_right) && strlen(cursor_right) > 1)
1509             ++count;
1510         if (count) {
1511             EXPECTED(cursor_down);
1512             EXPECTED(cursor_up);
1513             EXPECTED(cursor_left);
1514             EXPECTED(cursor_right);
1515         }
1516     }
1517 }
1518
1519 #define MAX_KP 5
1520 /*
1521  * Do a quick sanity-check for vt100-style keypads to see if the 5-key keypad
1522  * is mapped inconsistently.
1523  */
1524 static void
1525 check_keypad(TERMTYPE2 *tp)
1526 {
1527     char show[80];
1528
1529     if (VALID_STRING(key_a1) &&
1530         VALID_STRING(key_a3) &&
1531         VALID_STRING(key_b2) &&
1532         VALID_STRING(key_c1) &&
1533         VALID_STRING(key_c3)) {
1534         char final[MAX_KP + 1];
1535         long list[MAX_KP];
1536         int increase = 0;
1537         int j;
1538
1539         final[0] = keypad_final(key_a1);
1540         final[1] = keypad_final(key_a3);
1541         final[2] = keypad_final(key_b2);
1542         final[3] = keypad_final(key_c1);
1543         final[4] = keypad_final(key_c3);
1544         final[5] = '\0';
1545
1546         /* special case: legacy coding using 1,2,3,0,. on the bottom */
1547         assert(strlen(final) <= MAX_KP);
1548         if (!strcmp(final, "qsrpn"))
1549             return;
1550
1551         list[0] = keypad_index(key_a1);
1552         list[1] = keypad_index(key_a3);
1553         list[2] = keypad_index(key_b2);
1554         list[3] = keypad_index(key_c1);
1555         list[4] = keypad_index(key_c3);
1556
1557         /* check that they're all vt100 keys */
1558         for (j = 0; j < MAX_KP; ++j) {
1559             if (list[j] < 0) {
1560                 return;
1561             }
1562         }
1563
1564         /* check if they're all in increasing order */
1565         for (j = 1; j < MAX_KP; ++j) {
1566             if (list[j] > list[j - 1]) {
1567                 ++increase;
1568             }
1569         }
1570
1571         if (increase != (MAX_KP - 1)) {
1572             long last;
1573
1574             show[0] = '\0';
1575
1576             for (j = 0, last = -1; j < MAX_KP; ++j) {
1577                 int k;
1578                 int kk;
1579                 long test;
1580
1581                 for (k = 0, kk = -1, test = 100; k < 5; ++k) {
1582                     if (list[k] > last &&
1583                         list[k] < test) {
1584                         test = list[k];
1585                         kk = k;
1586                     }
1587                 }
1588                 last = test;
1589                 assert(strlen(show) < (MAX_KP * 4));
1590                 switch (kk) {
1591                 case 0:
1592                     _nc_STRCAT(show, " ka1", sizeof(show));
1593                     break;
1594                 case 1:
1595                     _nc_STRCAT(show, " ka3", sizeof(show));
1596                     break;
1597                 case 2:
1598                     _nc_STRCAT(show, " kb2", sizeof(show));
1599                     break;
1600                 case 3:
1601                     _nc_STRCAT(show, " kc1", sizeof(show));
1602                     break;
1603                 case 4:
1604                     _nc_STRCAT(show, " kc3", sizeof(show));
1605                     break;
1606                 }
1607             }
1608
1609             _nc_warning("vt100 keypad order inconsistent: %s", show);
1610         }
1611
1612     } else if (VALID_STRING(key_a1) ||
1613                VALID_STRING(key_a3) ||
1614                VALID_STRING(key_b2) ||
1615                VALID_STRING(key_c1) ||
1616                VALID_STRING(key_c3)) {
1617         show[0] = '\0';
1618         if (keypad_index(key_a1) >= 0)
1619             _nc_STRCAT(show, " ka1", sizeof(show));
1620         if (keypad_index(key_a3) >= 0)
1621             _nc_STRCAT(show, " ka3", sizeof(show));
1622         if (keypad_index(key_b2) >= 0)
1623             _nc_STRCAT(show, " kb2", sizeof(show));
1624         if (keypad_index(key_c1) >= 0)
1625             _nc_STRCAT(show, " kc1", sizeof(show));
1626         if (keypad_index(key_c3) >= 0)
1627             _nc_STRCAT(show, " kc3", sizeof(show));
1628         if (*show != '\0')
1629             _nc_warning("vt100 keypad map incomplete:%s", show);
1630     }
1631
1632     /*
1633      * These warnings are useful for consistency checks - it is possible that
1634      * there are real terminals with mismatches in these
1635      */
1636     ANDMISSING(key_ic, key_dc);
1637 }
1638
1639 static void
1640 check_printer(TERMTYPE2 *tp)
1641 {
1642     (void) tp;
1643 #if defined(enter_doublewide_mode) && defined(exit_doublewide_mode)
1644     PAIRED(enter_doublewide_mode, exit_doublewide_mode);
1645 #endif
1646 #if defined(enter_italics_mode) && defined(exit_italics_mode)
1647     PAIRED(enter_italics_mode, exit_italics_mode);
1648 #endif
1649 #if defined(enter_leftward_mode) && defined(exit_leftward_mode)
1650     PAIRED(enter_leftward_mode, exit_leftward_mode);
1651 #endif
1652 #if defined(enter_micro_mode) && defined(exit_micro_mode)
1653     PAIRED(enter_micro_mode, exit_micro_mode);
1654 #endif
1655 #if defined(enter_shadow_mode) && defined(exit_shadow_mode)
1656     PAIRED(enter_shadow_mode, exit_shadow_mode);
1657 #endif
1658 #if defined(enter_subscript_mode) && defined(exit_subscript_mode)
1659     PAIRED(enter_subscript_mode, exit_subscript_mode);
1660 #endif
1661 #if defined(enter_superscript_mode) && defined(exit_superscript_mode)
1662     PAIRED(enter_superscript_mode, exit_superscript_mode);
1663 #endif
1664 #if defined(enter_upward_mode) && defined(exit_upward_mode)
1665     PAIRED(enter_upward_mode, exit_upward_mode);
1666 #endif
1667
1668 #if defined(start_char_set_def) && defined(stop_char_set_def)
1669     ANDMISSING(start_char_set_def, stop_char_set_def);
1670 #endif
1671
1672     /*
1673      * If we have a parameterized form, then the non-parameterized is easy.
1674      * note: parameterized/non-parameterized margin settings are unrelated.
1675      */
1676 #if defined(parm_down_micro) && defined(micro_down)
1677     ANDMISSING(parm_down_micro, micro_down);
1678 #endif
1679 #if defined(parm_left_micro) && defined(micro_left)
1680     ANDMISSING(parm_left_micro, micro_left);
1681 #endif
1682 #if defined(parm_right_micro) && defined(micro_right)
1683     ANDMISSING(parm_right_micro, micro_right);
1684 #endif
1685 #if defined(parm_up_micro) && defined(micro_up)
1686     ANDMISSING(parm_up_micro, micro_up);
1687 #endif
1688 }
1689
1690 #if NCURSES_XNAMES
1691 static bool
1692 uses_SGR_39_49(const char *value)
1693 {
1694     return (strstr(value, "39;49") != 0
1695             || strstr(value, "49;39") != 0);
1696 }
1697
1698 /*
1699  * Check consistency of termcap extensions related to "screen".
1700  */
1701 static void
1702 check_screen(TERMTYPE2 *tp)
1703 {
1704     if (_nc_user_definable) {
1705         int have_XT = tigetflag("XT");
1706         int have_XM = tigetflag("XM");
1707         int have_bce = back_color_erase;
1708         bool have_kmouse = FALSE;
1709         bool use_sgr_39_49 = FALSE;
1710         const char *name_39_49 = "orig_pair or orig_colors";
1711         char *name = _nc_first_name(tp->term_names);
1712         bool is_screen = !strncmp(name, "screen", 6);
1713         bool screen_base = (is_screen
1714                             && strchr(name, '.') == NULL);
1715
1716         if (!VALID_BOOLEAN(have_bce)) {
1717             have_bce = FALSE;
1718         }
1719         if (!VALID_BOOLEAN(have_XM)) {
1720             have_XM = FALSE;
1721         }
1722         if (!VALID_BOOLEAN(have_XT)) {
1723             have_XT = FALSE;
1724         }
1725         if (VALID_STRING(key_mouse)) {
1726             have_kmouse = !strcmp("\033[M", key_mouse);
1727         }
1728         if (have_bce) {
1729             if (VALID_STRING(orig_pair)) {
1730                 name_39_49 = "orig_pair";
1731                 use_sgr_39_49 = uses_SGR_39_49(orig_pair);
1732             }
1733             if (!use_sgr_39_49 && VALID_STRING(orig_colors)) {
1734                 name_39_49 = "orig_colors";
1735                 use_sgr_39_49 = uses_SGR_39_49(orig_colors);
1736             }
1737         }
1738
1739         if (have_XM && have_XT) {
1740             _nc_warning("screen's XT capability conflicts with XM");
1741         } else if (have_XT && screen_base) {
1742             _nc_warning("screen's \"screen\" entries should not have XT set");
1743         } else if (have_XT) {
1744             char *s;
1745
1746             if (!have_kmouse && is_screen) {
1747                 if (VALID_STRING(key_mouse)) {
1748                     _nc_warning("value of kmous inconsistent with screen's usage");
1749                 } else {
1750                     _nc_warning("expected kmous capability with XT");
1751                 }
1752             }
1753             if (max_colors > 0) {
1754                 if (!have_bce) {
1755                     _nc_warning("expected bce capability with XT");
1756                 } else if (!use_sgr_39_49) {
1757                     _nc_warning("expected %s capability with XT "
1758                                 "to have 39/49 parameters", name_39_49);
1759                 }
1760             }
1761             if (VALID_STRING(to_status_line)
1762                 && (s = strchr(to_status_line, ';')) != NULL
1763                 && *++s == '\0')
1764                 _nc_warning("\"tsl\" capability is redundant, given XT");
1765         } else {
1766             if (have_kmouse
1767                 && !have_XM
1768                 && !screen_base && strchr(name, '+') == NULL) {
1769                 _nc_warning("expected XT to be set, given kmous");
1770             }
1771         }
1772     }
1773 }
1774 #else
1775 #define check_screen(tp)        /* nothing */
1776 #endif
1777
1778 /*
1779  * Returns the expected number of parameters for the given capability.
1780  */
1781 static int
1782 expected_params(const char *name)
1783 {
1784 #define DATA(name,count) { { name }, count }
1785     /* *INDENT-OFF* */
1786     static const struct {
1787         const char name[9];
1788         int count;
1789     } table[] = {
1790         DATA( "S0",             1 ),    /* 'screen' extension */
1791         DATA( "birep",          2 ),
1792         DATA( "chr",            1 ),
1793         DATA( "colornm",        1 ),
1794         DATA( "cpi",            1 ),
1795         DATA( "csnm",           1 ),
1796         DATA( "csr",            2 ),
1797         DATA( "cub",            1 ),
1798         DATA( "cud",            1 ),
1799         DATA( "cuf",            1 ),
1800         DATA( "cup",            2 ),
1801         DATA( "cuu",            1 ),
1802         DATA( "cvr",            1 ),
1803         DATA( "cwin",           5 ),
1804         DATA( "dch",            1 ),
1805         DATA( "defc",           3 ),
1806         DATA( "dial",           1 ),
1807         DATA( "dispc",          1 ),
1808         DATA( "dl",             1 ),
1809         DATA( "ech",            1 ),
1810         DATA( "getm",           1 ),
1811         DATA( "hpa",            1 ),
1812         DATA( "ich",            1 ),
1813         DATA( "il",             1 ),
1814         DATA( "indn",           1 ),
1815         DATA( "initc",          4 ),
1816         DATA( "initp",          7 ),
1817         DATA( "lpi",            1 ),
1818         DATA( "mc5p",           1 ),
1819         DATA( "mrcup",          2 ),
1820         DATA( "mvpa",           1 ),
1821         DATA( "pfkey",          2 ),
1822         DATA( "pfloc",          2 ),
1823         DATA( "pfx",            2 ),
1824         DATA( "pfxl",           3 ),
1825         DATA( "pln",            2 ),
1826         DATA( "qdial",          1 ),
1827         DATA( "rcsd",           1 ),
1828         DATA( "rep",            2 ),
1829         DATA( "rin",            1 ),
1830         DATA( "sclk",           3 ),
1831         DATA( "scp",            1 ),
1832         DATA( "scs",            1 ),
1833         DATA( "scsd",           2 ),
1834         DATA( "setab",          1 ),
1835         DATA( "setaf",          1 ),
1836         DATA( "setb",           1 ),
1837         DATA( "setcolor",       1 ),
1838         DATA( "setf",           1 ),
1839         DATA( "sgr",            9 ),
1840         DATA( "sgr1",           6 ),
1841         DATA( "slength",        1 ),
1842         DATA( "slines",         1 ),
1843         DATA( "smgbp",          1 ),    /* 2 if smgtp is not given */
1844         DATA( "smglp",          1 ),
1845         DATA( "smglr",          2 ),
1846         DATA( "smgrp",          1 ),
1847         DATA( "smgtb",          2 ),
1848         DATA( "smgtp",          1 ),
1849         DATA( "tsl",            1 ),
1850         DATA( "u6",             -1 ),
1851         DATA( "vpa",            1 ),
1852         DATA( "wind",           4 ),
1853         DATA( "wingo",          1 ),
1854     };
1855     /* *INDENT-ON* */
1856 #undef DATA
1857
1858     unsigned n;
1859     int result = 0;             /* function-keys, etc., use none */
1860
1861     for (n = 0; n < SIZEOF(table); n++) {
1862         if (!strcmp(name, table[n].name)) {
1863             result = table[n].count;
1864             break;
1865         }
1866     }
1867
1868     return result;
1869 }
1870
1871 /*
1872  * Check for user-capabilities that happen to be used in ncurses' terminal
1873  * database.
1874  */
1875 #if NCURSES_XNAMES
1876 static struct user_table_entry const *
1877 lookup_user_capability(const char *name)
1878 {
1879     struct user_table_entry const *result = 0;
1880     if (*name != 'k') {
1881         result = _nc_find_user_entry(name);
1882     }
1883     return result;
1884 }
1885 #endif
1886
1887 /*
1888  * If a given name is likely to be a user-capability, return the number of
1889  * parameters it would be used with.  If not, return -1.
1890  *
1891  * ncurses assumes that u6 could be used for getting the cursor-position, but
1892  * that is not implemented.  Make a special case for that, to quiet needless
1893  * warnings.
1894  *
1895  * The other string-capability extensions (see terminfo.src) which could have
1896  * parameters such as "Ss", "%u", are not used by ncurses.  But we check those
1897  * anyway, to validate the terminfo database.
1898  */
1899 static int
1900 is_user_capability(const char *name)
1901 {
1902     int result = -1;
1903     if (name[0] == 'u' &&
1904         (name[1] >= '0' && name[1] <= '9') &&
1905         name[2] == '\0') {
1906         result = (name[1] == '6') ? 2 : 0;
1907     }
1908 #if NCURSES_XNAMES
1909     else if (using_extensions) {
1910         struct user_table_entry const *p = lookup_user_capability(name);
1911         if (p != 0) {
1912             result = (int) p->ute_argc;
1913         }
1914     }
1915 #endif
1916     return result;
1917 }
1918
1919 static bool
1920 line_capability(const char *name)
1921 {
1922     bool result = FALSE;
1923     static const char *table[] =
1924     {
1925         "csr",                  /* change_scroll_region          */
1926         "clear",                /* clear_screen                  */
1927         "ed",                   /* clr_eos                       */
1928         "cwin",                 /* create_window                 */
1929         "cup",                  /* cursor_address                */
1930         "cud1",                 /* cursor_down                   */
1931         "home",                 /* cursor_home                   */
1932         "mrcup",                /* cursor_mem_address            */
1933         "ll",                   /* cursor_to_ll                  */
1934         "cuu1",                 /* cursor_up                     */
1935         "dl1",                  /* delete_line                   */
1936         "hd",                   /* down_half_line                */
1937         "flash",                /* flash_screen                  */
1938         "ff",                   /* form_feed                     */
1939         "il1",                  /* insert_line                   */
1940         "nel",                  /* newline                       */
1941         "dl",                   /* parm_delete_line              */
1942         "cud",                  /* parm_down_cursor              */
1943         "indn",                 /* parm_index                    */
1944         "il",                   /* parm_insert_line              */
1945         "rin",                  /* parm_rindex                   */
1946         "cuu",                  /* parm_up_cursor                */
1947         "mc0",                  /* print_screen                  */
1948         "vpa",                  /* row_address                   */
1949         "ind",                  /* scroll_forward                */
1950         "ri",                   /* scroll_reverse                */
1951         "hu",                   /* up_half_line                  */
1952     };
1953     size_t n;
1954     for (n = 0; n < SIZEOF(table); ++n) {
1955         if (!strcmp(name, table[n])) {
1956             result = TRUE;
1957             break;
1958         }
1959     }
1960     return result;
1961 }
1962
1963 /*
1964  * Make a quick sanity check for the parameters which are used in the given
1965  * strings.  If there are no "%p" tokens, then there should be no other "%"
1966  * markers.
1967  */
1968 static void
1969 check_params(TERMTYPE2 *tp, const char *name, const char *value, int extended)
1970 {
1971     int expected = expected_params(name);
1972     int actual = 0;
1973     int n;
1974     bool params[1 + NUM_PARM];
1975     const char *s = value;
1976
1977 #ifdef set_left_margin_parm
1978     if (!strcmp(name, "smgrp")
1979         && !VALID_STRING(set_left_margin_parm))
1980         expected = 2;
1981 #endif
1982 #ifdef set_right_margin_parm
1983     if (!strcmp(name, "smglp")
1984         && !VALID_STRING(set_right_margin_parm))
1985         expected = 2;
1986 #endif
1987 #ifdef set_top_margin_parm
1988     if (!strcmp(name, "smgbp")
1989         && !VALID_STRING(set_top_margin_parm))
1990         expected = 2;
1991 #endif
1992 #ifdef set_bottom_margin_parm
1993     if (!strcmp(name, "smgtp")
1994         && !VALID_STRING(set_bottom_margin_parm))
1995         expected = 2;
1996 #endif
1997
1998     for (n = 0; n <= NUM_PARM; n++)
1999         params[n] = FALSE;
2000
2001     while (*s != 0) {
2002         if (*s == '%') {
2003             if (*++s == '\0') {
2004                 _nc_warning("expected character after %% in %s", name);
2005                 break;
2006             } else if (*s == 'p') {
2007                 if (*++s == '\0' || !isdigit((int) *s)) {
2008                     _nc_warning("expected digit after %%p in %s", name);
2009                     return;
2010                 } else {
2011                     n = (*s - '0');
2012                     if (n > actual)
2013                         actual = n;
2014                     params[n] = TRUE;
2015                 }
2016             }
2017         }
2018         s++;
2019     }
2020
2021 #if NCURSES_XNAMES
2022     if (extended) {
2023         int check = is_user_capability(name);
2024         if (check != actual && (check >= 0 && actual >= 0)) {
2025             _nc_warning("extended %s capability has %d parameters, expected %d",
2026                         name, actual, check);
2027         } else if (debug_level > 1) {
2028             _nc_warning("extended %s capability has %d parameters, as expected",
2029                         name, actual);
2030         }
2031         expected = actual;
2032     }
2033 #else
2034     (void) extended;
2035 #endif
2036
2037     if (params[0]) {
2038         _nc_warning("%s refers to parameter 0 (%%p0), which is not allowed", name);
2039     }
2040     if (value == set_attributes || expected < 0) {
2041         ;
2042     } else if (expected != actual) {
2043         _nc_warning("%s uses %d parameters, expected %d", name,
2044                     actual, expected);
2045         for (n = 1; n < actual; n++) {
2046             if (!params[n])
2047                 _nc_warning("%s omits parameter %d", name, n);
2048         }
2049     }
2050
2051     /*
2052      * Counting "%p" markers does not account for termcap expressions which
2053      * may not have been fully translated.  Also, tparm does its own analysis.
2054      * Report differences here.
2055      */
2056     _nc_reset_tparm(NULL);
2057     if (actual >= 0) {
2058         char *p_is_s[NUM_PARM];
2059         int popcount;
2060         int analyzed = _nc_tparm_analyze(NULL, value, p_is_s, &popcount);
2061         if (analyzed < popcount) {
2062             analyzed = popcount;
2063         }
2064         if (actual != analyzed && expected != analyzed) {
2065 #if NCURSES_XNAMES
2066             int user_cap = is_user_capability(name);
2067             if ((user_cap == analyzed) && using_extensions) {
2068                 ;               /* ignore */
2069             } else if (user_cap >= 0) {
2070                 _nc_warning("tparm will use %d parameters for %s, expected %d",
2071                             analyzed, name, user_cap);
2072             } else
2073 #endif
2074             {
2075                 _nc_warning("tparm analyzed %d parameters for %s, expected %d",
2076                             analyzed, name, actual);
2077             }
2078         } else if (expected > 0
2079                    && actual == expected
2080                    && guess_tparm_type(expected, p_is_s) == Numbers) {
2081             int limit = 1;
2082
2083             if (!strcmp(name, "setf")
2084                 || !strcmp(name, "setb")
2085                 || !strcmp(name, "setaf")
2086                 || !strcmp(name, "setab")) {
2087                 if ((limit = max_colors) > 256)
2088                     limit = 256;
2089             } else if (line_capability(name)) {
2090                 limit = 24;
2091             } else if (is_user_capability(name) < 0) {
2092                 limit = 80;
2093             }
2094             for (n = 0; n < limit; ++n) {
2095                 _nc_reset_tparm(NULL);
2096                 (void) TPARM_9(value, n, n, n, n, n, n, n, n, n);
2097                 if (_nc_tparm_err) {
2098                     _nc_warning("problem%s in tparm(%s, %d, ...)",
2099                                 (_nc_tparm_err == 1) ? "" : "s",
2100                                 name, n);
2101                     if (debug_level < 2)
2102                         break;
2103                 }
2104             }
2105         }
2106     }
2107 }
2108
2109 /*
2110  * Check for DEC VT100 private mode for reverse video.
2111  */
2112 static const char *
2113 skip_DECSCNM(const char *value, int *flag)
2114 {
2115     *flag = -1;
2116     if (value != 0) {
2117         int skip = csi_length(value);
2118         if (skip > 0 &&
2119             value[skip++] == '?' &&
2120             value[skip++] == '5') {
2121             if (value[skip] == 'h') {
2122                 *flag = 1;
2123             } else if (value[skip] == 'l') {
2124                 *flag = 0;
2125             }
2126             value += skip + 1;
2127         }
2128     }
2129     return value;
2130 }
2131
2132 static void
2133 check_delays(TERMTYPE2 *tp, const char *name, const char *value)
2134 {
2135     const char *p, *q;
2136     const char *first = 0;
2137     const char *last = 0;
2138
2139     for (p = value; *p != '\0'; ++p) {
2140         if (p[0] == '$' && p[1] == '<') {
2141             const char *base = p + 2;
2142             const char *mark = 0;
2143             bool mixed = FALSE;
2144             int proportional = 0;
2145             int mandatory = 0;
2146
2147             first = p;
2148
2149             for (q = base; *q != '\0'; ++q) {
2150                 if (*q == '>') {
2151                     if (mark == NULL)
2152                         mark = q;
2153                     break;
2154                 } else if (*q == '*' || *q == '/') {
2155                     if (*q == '*')
2156                         ++proportional;
2157                     if (*q == '/')
2158                         ++mandatory;
2159                     if (mark == NULL)
2160                         mark = q;
2161                 } else if (!(isalnum(UChar(*q)) || strchr("+-.", *q) != 0)) {
2162                     break;
2163                 } else if (proportional || mandatory) {
2164                     mixed = TRUE;
2165                 }
2166             }
2167             last = *q ? (q + 1) : q;
2168             if (*q != '\0') {
2169                 float check_f;
2170                 char check_c;
2171                 int rc = sscanf(base, "%f%c", &check_f, &check_c);
2172                 if ((rc != 2) || (mark != NULL && (check_c != *mark)) || mixed) {
2173                     _nc_warning("syntax error in %s delay '%.*s'", name,
2174                                 (int) (q - base), base);
2175                 } else if (*name == 'k') {
2176                     _nc_warning("function-key %s has delay", name);
2177                 } else if (proportional && !line_capability(name)) {
2178                     _nc_warning("non-line capability using proportional delay: %s", name);
2179                 } else if (!xon_xoff &&
2180                            !mandatory &&
2181                            strchr(_nc_first_name(tp->term_names), '+') == NULL) {
2182                     _nc_warning("%s in %s is used since no xon/xoff",
2183                                 (proportional
2184                                  ? "proportional delay"
2185                                  : "delay"),
2186                                 name);
2187                 }
2188             } else {
2189                 p = q - 1;      /* restart scan */
2190             }
2191         }
2192     }
2193
2194     if (!strcmp(name, "flash") ||
2195         !strcmp(name, "beep")) {
2196
2197         if (first != 0) {
2198             if (first == value || *last == 0) {
2199                 /*
2200                  * Delay is on one end or the other.
2201                  */
2202                 _nc_warning("expected delay embedded within %s", name);
2203             }
2204         } else {
2205             int flag;
2206
2207             /*
2208              * Check for missing delay when using VT100 reverse-video.
2209              * A real VT100 might not need this, but terminal emulators do.
2210              */
2211             if ((p = skip_DECSCNM(value, &flag)) != 0 &&
2212                 flag > 0 &&
2213                 skip_DECSCNM(p, &flag) != 0 &&
2214                 flag == 0) {
2215                 _nc_warning("expected a delay in %s", name);
2216             }
2217         }
2218     }
2219 }
2220
2221 static char *
2222 check_1_infotocap(const char *name, NCURSES_CONST char *value, int count)
2223 {
2224     int k;
2225     int ignored;
2226     long numbers[1 + NUM_PARM];
2227     char *strings[1 + NUM_PARM];
2228     char *p_is_s[NUM_PARM];
2229     char *result;
2230     char blob[NUM_PARM * 10];
2231     char *next = blob;
2232     TParams expect;
2233     TParams actual;
2234     int nparam;
2235
2236     *next++ = '\0';
2237     for (k = 1; k <= NUM_PARM; k++) {
2238         numbers[k] = count;
2239         _nc_SPRINTF(next,
2240                     _nc_SLIMIT(sizeof(blob) - (size_t) (next - blob))
2241                     "XYZ%d", count);
2242         strings[k] = next;
2243         next += strlen(next) + 1;
2244     }
2245
2246     _nc_reset_tparm(NULL);
2247     expect = tparm_type(name);
2248     nparam = _nc_tparm_analyze(NULL, value, p_is_s, &ignored);
2249     actual = guess_tparm_type(nparam, p_is_s);
2250
2251     if (expect != actual) {
2252         _nc_warning("%s has mismatched parameters", name);
2253         actual = Other;
2254     }
2255
2256     _nc_reset_tparm(NULL);
2257     switch (actual) {
2258     case Num_Str:
2259         result = TPARM_2(value, numbers[1], strings[2]);
2260         break;
2261     case Num_Str_Str:
2262         result = TPARM_3(value, numbers[1], strings[2], strings[3]);
2263         break;
2264     case Numbers:
2265 #define myParam(n) numbers[n]
2266         result = TIPARM_9(value,
2267                           myParam(1),
2268                           myParam(2),
2269                           myParam(3),
2270                           myParam(4),
2271                           myParam(5),
2272                           myParam(6),
2273                           myParam(7),
2274                           myParam(8),
2275                           myParam(9));
2276 #undef myParam
2277         break;
2278     case Other:
2279     default:
2280 #define myParam(n) (p_is_s[n - 1] != 0 ? ((TPARM_ARG) strings[n]) : numbers[n])
2281         result = TPARM_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     }
2294     return strdup(result);
2295 }
2296
2297 #define IsDelay(ch) ((ch) == '.' || isdigit(UChar(ch)))
2298
2299 static const char *
2300 parse_delay_value(const char *src, double *delays, int *always)
2301 {
2302     int star = 0;
2303
2304     *delays = 0.0;
2305     if (always)
2306         *always = 0;
2307
2308     while (isdigit(UChar(*src))) {
2309         (*delays) = (*delays) * 10 + (*src++ - '0');
2310     }
2311     if (*src == '.') {
2312         int gotdot = 1;
2313
2314         ++src;
2315         while (isdigit(UChar(*src))) {
2316             gotdot *= 10;
2317             (*delays) += (*src++ - '0') / gotdot;
2318         }
2319     }
2320     while (*src == '*' || *src == '/') {
2321         if (always == NULL && *src == '/')
2322             break;
2323         if (*src++ == '*') {
2324             star = 1;
2325         } else {
2326             *always = 1;
2327         }
2328     }
2329     if (star)
2330         *delays = -(*delays);
2331     return src;
2332 }
2333
2334 static const char *
2335 parse_ti_delay(const char *ti, double *delays)
2336 {
2337     *delays = 0.0;
2338     while (*ti != '\0') {
2339         if (*ti == '\\') {
2340             ++ti;
2341         }
2342         if (ti[0] == '$'
2343             && ti[1] == '<'
2344             && IsDelay(UChar(ti[2]))) {
2345             int ignored;
2346             const char *last = parse_delay_value(ti + 2, delays, &ignored);
2347             if (*last == '>') {
2348                 ti = last;
2349             }
2350         } else {
2351             ++ti;
2352         }
2353     }
2354     return ti;
2355 }
2356
2357 static const char *
2358 parse_tc_delay(const char *tc, double *delays)
2359 {
2360     return parse_delay_value(tc, delays, (int *) 0);
2361 }
2362
2363 /*
2364  * Compare terminfo- and termcap-strings, factoring out delays.
2365  */
2366 static bool
2367 same_ti_tc(const char *ti, const char *tc, bool * embedded)
2368 {
2369     bool same = TRUE;
2370     double ti_delay = 0.0;
2371     double tc_delay = 0.0;
2372     const char *ti_last;
2373
2374     *embedded = FALSE;
2375     ti_last = parse_ti_delay(ti, &ti_delay);
2376     tc = parse_tc_delay(tc, &tc_delay);
2377
2378     while ((ti < ti_last) && *tc) {
2379         if (*ti == '\\' && ispunct(UChar(ti[1]))) {
2380             ++ti;
2381             if ((*ti == '^') && !strncmp(tc, "\\136", 4)) {
2382                 ti += 1;
2383                 tc += 4;
2384                 continue;
2385             }
2386         } else if (ti[0] == '$' && ti[1] == '<') {
2387             double no_delay;
2388             const char *ss = parse_ti_delay(ti, &no_delay);
2389             if (ss != ti) {
2390                 *embedded = TRUE;
2391                 ti = ss;
2392                 continue;
2393             }
2394         }
2395         if (*tc == '\\' && ispunct(UChar(tc[1]))) {
2396             ++tc;
2397         }
2398         if (*ti++ != *tc++) {
2399             same = FALSE;
2400             break;
2401         }
2402     }
2403
2404     if (*embedded) {
2405         if (same) {
2406             same = FALSE;
2407         } else {
2408             *embedded = FALSE;  /* report only one problem */
2409         }
2410     }
2411
2412     return same;
2413 }
2414
2415 /*
2416  * Check terminfo to termcap translation.
2417  */
2418 static void
2419 check_infotocap(TERMTYPE2 *tp, int i, const char *value)
2420 {
2421     const char *name = ExtStrname(tp, i, strnames);
2422     int params = ((i < (int) SIZEOF(parametrized))
2423                   ? parametrized[i]
2424                   : ((*value == 'k')
2425                      ? 0
2426                      : has_params(value, FALSE)));
2427     char *ti_value = NULL;
2428     char *tc_value;
2429     bool embedded;
2430
2431     assert(SIZEOF(parametrized) == STRCOUNT);
2432     if (!VALID_STRING(value) || (ti_value = strdup(value)) == NULL) {
2433         _nc_warning("tic-expansion of %s failed", name);
2434     } else if ((tc_value = _nc_infotocap(name, ti_value, params)) == ABSENT_STRING) {
2435         _nc_warning("tic-conversion of %s failed", name);
2436     } else if (params > 0) {
2437         int limit = 5;
2438         int count;
2439         bool first = TRUE;
2440
2441         if (!strcmp(name, "setf")
2442             || !strcmp(name, "setb")
2443             || !strcmp(name, "setaf")
2444             || !strcmp(name, "setab")) {
2445             if ((limit = max_colors) > 256)
2446                 limit = 256;
2447         }
2448         for (count = 0; count < limit; ++count) {
2449             char *ti_check = check_1_infotocap(name, ti_value, count);
2450             char *tc_check = check_1_infotocap(name, tc_value, count);
2451
2452             if (strcmp(ti_check, tc_check)) {
2453                 if (first) {
2454                     fprintf(stderr, "check_infotocap(%s)\n", name);
2455                     fprintf(stderr, "...ti '%s'\n", _nc_visbuf2(0, ti_value));
2456                     fprintf(stderr, "...tc '%s'\n", _nc_visbuf2(0, tc_value));
2457                     first = FALSE;
2458                 }
2459                 _nc_warning("tparm-conversion of %s(%d) differs between\n\tterminfo %s\n\ttermcap  %s",
2460                             name, count,
2461                             _nc_visbuf2(0, ti_check),
2462                             _nc_visbuf2(1, tc_check));
2463             }
2464             free(ti_check);
2465             free(tc_check);
2466         }
2467     } else if (params == 0 && !same_ti_tc(ti_value, tc_value, &embedded)) {
2468         if (embedded) {
2469             _nc_warning("termcap equivalent of %s cannot use embedded delay", name);
2470         } else {
2471             _nc_warning("tic-conversion of %s changed value\n\tfrom %s\n\tto   %s",
2472                         name, ti_value, tc_value);
2473         }
2474     }
2475     free(ti_value);
2476 }
2477
2478 static char *
2479 skip_delay(char *s)
2480 {
2481     while (*s == '/' || isdigit(UChar(*s)))
2482         ++s;
2483     return s;
2484 }
2485
2486 /*
2487  * Skip a delay altogether, e.g., when comparing a simple string to sgr,
2488  * the latter may have a worst-case delay on the end.
2489  */
2490 static char *
2491 ignore_delays(char *s)
2492 {
2493     int delaying = 0;
2494
2495     do {
2496         switch (*s) {
2497         case '$':
2498             if (delaying == 0)
2499                 delaying = 1;
2500             break;
2501         case '<':
2502             if (delaying == 1)
2503                 delaying = 2;
2504             break;
2505         case '\0':
2506             delaying = 0;
2507             break;
2508         default:
2509             if (delaying) {
2510                 s = skip_delay(s);
2511                 if (*s == '>')
2512                     ++s;
2513                 delaying = 0;
2514             }
2515             break;
2516         }
2517         if (delaying)
2518             ++s;
2519     } while (delaying);
2520     return s;
2521 }
2522
2523 #define DATA(name) { #name }
2524 static const char sgr_names[][11] =
2525 {
2526     DATA(none),
2527     DATA(standout),
2528     DATA(underline),
2529     DATA(reverse),
2530     DATA(blink),
2531     DATA(dim),
2532     DATA(bold),
2533     DATA(invis),
2534     DATA(protect),
2535     DATA(altcharset),
2536     ""
2537 };
2538 #undef DATA
2539
2540 /*
2541  * An sgr string may contain several settings other than the one we're
2542  * interested in, essentially sgr0 + rmacs + whatever.  As long as the
2543  * "whatever" is contained in the sgr string, that is close enough for our
2544  * sanity check.
2545  */
2546 static bool
2547 similar_sgr(int num, char *a, char *b)
2548 {
2549     char *base_a = a;
2550     char *base_b = b;
2551     int delaying = 0;
2552
2553     while (*b != 0) {
2554         while (*a != *b) {
2555             if (*a == 0) {
2556                 if (num < 0) {
2557                     ;
2558                 } else if (b[0] == '$'
2559                            && b[1] == '<') {
2560                     _nc_warning("did not find delay %s", _nc_visbuf(b));
2561                 } else {
2562                     _nc_warning("checking sgr(%s) %s\n\tcompare to %s\n\tunmatched %s",
2563                                 sgr_names[num], _nc_visbuf2(1, base_a),
2564                                 _nc_visbuf2(2, base_b),
2565                                 _nc_visbuf2(3, b));
2566                 }
2567                 return FALSE;
2568             } else if (delaying) {
2569                 a = skip_delay(a);
2570                 b = skip_delay(b);
2571             } else if ((*b == '0' || (*b == ';')) && *a == 'm') {
2572                 b++;
2573             } else {
2574                 a++;
2575             }
2576         }
2577         switch (*a) {
2578         case '$':
2579             if (delaying == 0)
2580                 delaying = 1;
2581             break;
2582         case '<':
2583             if (delaying == 1)
2584                 delaying = 2;
2585             break;
2586         default:
2587             delaying = 0;
2588             break;
2589         }
2590         a++;
2591         b++;
2592     }
2593     /* ignore delays on the end of the string */
2594     a = ignore_delays(a);
2595     return ((num != 0) || (*a == 0));
2596 }
2597
2598 static void
2599 check_tparm_err(int num)
2600 {
2601     if (_nc_tparm_err)
2602         _nc_warning("tparam error in sgr(%d): %s", num, sgr_names[num]);
2603 }
2604
2605 static char *
2606 check_sgr(TERMTYPE2 *tp, char *zero, int num, char *cap, const char *name)
2607 {
2608     char *test;
2609
2610     _nc_tparm_err = 0;
2611     test = TIPARM_9(set_attributes,
2612                     num == 1,
2613                     num == 2,
2614                     num == 3,
2615                     num == 4,
2616                     num == 5,
2617                     num == 6,
2618                     num == 7,
2619                     num == 8,
2620                     num == 9);
2621     if (test != 0) {
2622         if (PRESENT(cap)) {
2623             if (!similar_sgr(num, test, cap)) {
2624                 _nc_warning("%s differs from sgr(%d)\n\t%s=%s\n\tsgr(%d)=%s",
2625                             name, num,
2626                             name, _nc_visbuf2(1, cap),
2627                             num, _nc_visbuf2(2, test));
2628             }
2629         } else if (_nc_capcmp(test, zero)) {
2630             _nc_warning("sgr(%d) present, but not %s", num, name);
2631         }
2632     } else if (PRESENT(cap)) {
2633         _nc_warning("sgr(%d) missing, but %s present", num, name);
2634     }
2635     check_tparm_err(num);
2636     return test;
2637 }
2638
2639 #define CHECK_SGR(num,name) check_sgr(tp, zero, num, name, #name)
2640
2641 #ifdef TRACE
2642 /*
2643  * If tic is compiled with TRACE, we'll be able to see the output from the
2644  * DEBUG() macro.  But since it doesn't use traceon(), it always goes to
2645  * the standard error.  Use this function to make it simpler to follow the
2646  * resulting debug traces.
2647  */
2648 static void
2649 show_where(unsigned level)
2650 {
2651     if (_nc_tracing >= DEBUG_LEVEL(level)) {
2652         char my_name[MAX_NAME_SIZE];
2653         _nc_get_type(my_name);
2654         _tracef("\"%s\", line %d, '%s'",
2655                 _nc_get_source(),
2656                 _nc_curr_line, my_name);
2657     }
2658 }
2659
2660 #else
2661 #define show_where(level)       /* nothing */
2662 #endif
2663
2664 typedef struct {
2665     int keycode;
2666     const char *name;
2667     const char *value;
2668 } NAME_VALUE;
2669
2670 static NAME_VALUE *
2671 get_fkey_list(TERMTYPE2 *tp)
2672 {
2673     NAME_VALUE *result = typeMalloc(NAME_VALUE, NUM_STRINGS(tp) + 1);
2674     const struct tinfo_fkeys *all_fkeys = _nc_tinfo_fkeys;
2675     int used = 0;
2676     unsigned j;
2677
2678     if (result == NULL)
2679         failed("get_fkey_list");
2680
2681     for (j = 0; all_fkeys[j].code; j++) {
2682         char *a = tp->Strings[all_fkeys[j].offset];
2683         if (VALID_STRING(a)) {
2684             result[used].keycode = (int) all_fkeys[j].code;
2685             result[used].name = strnames[all_fkeys[j].offset];
2686             result[used].value = a;
2687             ++used;
2688         }
2689     }
2690 #if NCURSES_XNAMES
2691     for (j = STRCOUNT; j < NUM_STRINGS(tp); ++j) {
2692         const char *name = ExtStrname(tp, (int) j, strnames);
2693         if (*name == 'k') {
2694             result[used].keycode = -1;
2695             result[used].name = name;
2696             result[used].value = tp->Strings[j];
2697             ++used;
2698         }
2699     }
2700 #endif
2701     result[used].keycode = 0;
2702     return result;
2703 }
2704
2705 static void
2706 show_fkey_name(NAME_VALUE * data)
2707 {
2708     if (data->keycode > 0) {
2709         fprintf(stderr, " %s", keyname(data->keycode));
2710         fprintf(stderr, " (capability \"%s\")", data->name);
2711     } else {
2712         fprintf(stderr, " capability \"%s\"", data->name);
2713     }
2714 }
2715
2716 /*
2717  * A terminal entry may contain more than one keycode assigned to a given
2718  * string (e.g., KEY_END and KEY_LL).  But curses will only return one (the
2719  * last one assigned).
2720  */
2721 static void
2722 check_conflict(TERMTYPE2 *tp)
2723 {
2724     if (!(_nc_syntax == SYN_TERMCAP && capdump)) {
2725         char *check = calloc((size_t) (NUM_STRINGS(tp) + 1), sizeof(char));
2726         NAME_VALUE *given = get_fkey_list(tp);
2727         unsigned j, k;
2728         bool conflict = FALSE;
2729
2730         if (check == NULL)
2731             failed("check_conflict");
2732
2733         for (j = 0; given[j].keycode; ++j) {
2734             const char *a = given[j].value;
2735             bool first = TRUE;
2736
2737             if (!VALID_STRING(a))
2738                 continue;
2739
2740             for (k = j + 1; given[k].keycode; k++) {
2741                 const char *b = given[k].value;
2742
2743                 if (!VALID_STRING(b))
2744                     continue;
2745                 if (check[k])
2746                     continue;
2747
2748                 if (!_nc_capcmp(a, b)) {
2749                     check[j] = 1;
2750                     check[k] = 1;
2751                     if (first) {
2752                         if (!conflict) {
2753                             _nc_warning("conflicting key definitions (using the last)");
2754                             conflict = TRUE;
2755                         }
2756                         fprintf(stderr, "...");
2757                         show_fkey_name(given + j);
2758                         fprintf(stderr, " is the same as");
2759                         show_fkey_name(given + k);
2760                         first = FALSE;
2761                     } else {
2762                         fprintf(stderr, ", ");
2763                         show_fkey_name(given + k);
2764                     }
2765                 }
2766             }
2767             if (!first)
2768                 fprintf(stderr, "\n");
2769         }
2770 #if NCURSES_XNAMES
2771         if (using_extensions) {
2772             /* *INDENT-OFF* */
2773             static struct {
2774                 const char *xcurses;
2775                 const char *shifted;
2776             } table[] = {
2777                 { "kDC",  NULL },
2778                 { "kDN",  "kind" },
2779                 { "kEND", NULL },
2780                 { "kHOM", NULL },
2781                 { "kLFT", NULL },
2782                 { "kNXT", NULL },
2783                 { "kPRV", NULL },
2784                 { "kRIT", NULL },
2785                 { "kUP",  "kri" },
2786                 { NULL,   NULL },
2787             };
2788             /* *INDENT-ON* */
2789             /*
2790              * SVr4 curses defines the "xcurses" names listed above except for
2791              * the special cases in the "shifted" column.  When using these
2792              * names for xterm's extensions, that was confusing, and resulted
2793              * in adding extended capabilities with "2" (shift) suffix.  This
2794              * check warns about unnecessary use of extensions for this quirk.
2795              */
2796             for (j = 0; given[j].keycode; ++j) {
2797                 const char *find = given[j].name;
2798                 int value;
2799                 char ch;
2800
2801                 if (!VALID_STRING(given[j].value))
2802                     continue;
2803
2804                 for (k = 0; table[k].xcurses; ++k) {
2805                     const char *test = table[k].xcurses;
2806                     size_t size = strlen(test);
2807
2808                     if (!strncmp(find, test, size) && strcmp(find, test)) {
2809                         switch (sscanf(find + size, "%d%c", &value, &ch)) {
2810                         case 1:
2811                             if (value == 2) {
2812                                 _nc_warning("expected '%s' rather than '%s'",
2813                                             (table[k].shifted
2814                                              ? table[k].shifted
2815                                              : test), find);
2816                             } else if (value < 2 || value > 15) {
2817                                 _nc_warning("expected numeric 2..15 '%s'", find);
2818                             }
2819                             break;
2820                         default:
2821                             _nc_warning("expected numeric suffix for '%s'", find);
2822                             break;
2823                         }
2824                         break;
2825                     }
2826                 }
2827             }
2828         }
2829 #endif
2830         free(given);
2831         free(check);
2832     }
2833 }
2834
2835 /*
2836  * Exiting a video mode should not duplicate sgr0
2837  */
2838 static void
2839 check_exit_attribute(const char *name, char *test, char *trimmed, char *untrimmed)
2840 {
2841     if (VALID_STRING(test) && (trimmed != 0)) {
2842         if (similar_sgr(-1, trimmed, test) ||
2843             similar_sgr(-1, untrimmed, test)) {
2844             _nc_warning("%s matches exit_attribute_mode", name);
2845         }
2846     }
2847 }
2848
2849 /*
2850  * Returns true if the string looks like a standard SGR string.
2851  */
2852 static bool
2853 is_sgr_string(char *value)
2854 {
2855     bool result = FALSE;
2856
2857     if (VALID_STRING(value)) {
2858         int skip = csi_length(value);
2859
2860         if (skip) {
2861             int ch;
2862
2863             result = TRUE;
2864             value += skip;
2865             while ((ch = UChar(*value++)) != '\0') {
2866                 if (isdigit(ch) || ch == ';') {
2867                     ;
2868                 } else if (ch == 'm' && *value == '\0') {
2869                     ;
2870                 } else {
2871                     result = FALSE;
2872                     break;
2873                 }
2874             }
2875         }
2876     }
2877     return result;
2878 }
2879
2880 /*
2881  * Check if the given capability contains a given SGR attribute.
2882  */
2883 static void
2884 check_sgr_param(TERMTYPE2 *tp, int code, const char *name, char *value)
2885 {
2886     if (VALID_STRING(value)) {
2887         int ncv = ((code != 0) ? (1 << (code - 1)) : 0);
2888         char *test = tgoto(value, 0, 0);
2889         if (is_sgr_string(test)) {
2890             int param = 0;
2891             int count = 0;
2892             int skips = 0;
2893             int color = (value == set_a_foreground ||
2894                          value == set_a_background ||
2895                          value == set_foreground ||
2896                          value == set_background);
2897             while (*test != 0) {
2898                 if (isdigit(UChar(*test))) {
2899                     param = 10 * param + (*test - '0');
2900                     ++count;
2901                 } else {
2902                     if (count) {
2903                         /*
2904                          * Avoid unnecessary warning for xterm 256color codes.
2905                          */
2906                         if (color && (param == 38 || param == 48))
2907                             skips = 3;
2908                         if ((skips-- <= 0) && (param == code))
2909                             break;
2910                     }
2911                     count = 0;
2912                     param = 0;
2913                 }
2914                 ++test;
2915             }
2916             if (count != 0 && param == code) {
2917                 if (code == 0 ||
2918                     no_color_video < 0 ||
2919                     !(no_color_video & ncv)) {
2920                     _nc_warning("\"%s\" SGR-attribute used in %s",
2921                                 sgr_names[code],
2922                                 name);
2923                 }
2924             }
2925         }
2926     }
2927 }
2928
2929 #if NCURSES_XNAMES
2930 static int
2931 standard_type(const char *name)
2932 {
2933     int result = -1;
2934     const struct name_table_entry *np;
2935
2936     if ((np = _nc_find_entry(name, _nc_get_hash_table(0))) != 0) {
2937         result = np->nte_type;
2938     }
2939     return result;
2940 }
2941
2942 static const char *
2943 name_of_type(int type)
2944 {
2945     const char *result = "unknown";
2946     switch (type) {
2947     case BOOLEAN:
2948         result = "boolean";
2949         break;
2950     case NUMBER:
2951         result = "number";
2952         break;
2953     case STRING:
2954         result = "string";
2955         break;
2956     }
2957     return result;
2958 }
2959
2960 static void
2961 check_user_capability_type(const char *name, int actual)
2962 {
2963     if (lookup_user_capability(name) == 0) {
2964         int expected = standard_type(name);
2965         if (expected >= 0) {
2966             _nc_warning("expected %s to be %s, but actually %s",
2967                         name,
2968                         name_of_type(actual),
2969                         name_of_type(expected)
2970                 );
2971         } else if (*name != 'k') {
2972             _nc_warning("undocumented %s capability %s",
2973                         name_of_type(actual),
2974                         name);
2975         }
2976     }
2977 }
2978 #endif
2979
2980 #define IN_DELAY "0123456789*/."
2981
2982 static bool
2983 check_ANSI_cap(const char *value, int nparams, char final)
2984 {
2985     bool result = FALSE;
2986     if (VALID_STRING(value) && csi_length(value) > 0) {
2987         char *p_is_s[NUM_PARM];
2988         int popcount;
2989         int analyzed = _nc_tparm_analyze(NULL, value, p_is_s, &popcount);
2990         if (analyzed < popcount) {
2991             analyzed = popcount;
2992         }
2993         if (analyzed == nparams) {
2994             bool numbers = TRUE;
2995             int p;
2996             for (p = 0; p < nparams; ++p) {
2997                 if (p_is_s[p]) {
2998                     numbers = FALSE;
2999                     break;
3000                 }
3001             }
3002             if (numbers) {
3003                 int in_delay = 0;
3004                 p = (int) strlen(value);
3005                 while (p-- > 0) {
3006                     char ch = value[p];
3007                     if (ch == final) {
3008                         result = TRUE;
3009                         break;
3010                     }
3011                     switch (in_delay) {
3012                     case 0:
3013                         if (ch == '>')
3014                             in_delay = 1;
3015                         break;
3016                     case 1:
3017                         if (strchr(IN_DELAY, value[p]) != NULL)
3018                             break;
3019                         if (ch != '<')
3020                             p = 0;
3021                         in_delay = 2;
3022                         break;
3023                     case 2:
3024                         if (ch != '$')
3025                             p = 0;
3026                         in_delay = 0;
3027                         break;
3028                     }
3029                 }
3030             }
3031         }
3032     }
3033     return result;
3034 }
3035
3036 static const char *
3037 skip_Delay(const char *value)
3038 {
3039     const char *result = value;
3040
3041     if (*value == '$') {
3042         ++result;
3043         if (*result++ == '<') {
3044             while (strchr(IN_DELAY, *result) != NULL)
3045                 ++result;
3046             if (*result++ != '>') {
3047                 result = value;
3048             }
3049         } else {
3050             result = value;
3051         }
3052     }
3053     return result;
3054 }
3055
3056 static bool
3057 isValidString(const char *value, const char *expect)
3058 {
3059     bool result = FALSE;
3060     if (VALID_STRING(value)) {
3061         if (!strcmp(value, expect))
3062             result = TRUE;
3063     }
3064     return result;
3065 }
3066
3067 static bool
3068 isValidEscape(const char *value, const char *expect)
3069 {
3070     bool result = FALSE;
3071     if (VALID_STRING(value)) {
3072         if (*value == '\033') {
3073             size_t need = strlen(expect);
3074             size_t have = strlen(value) - 1;
3075             if (have >= need && !strncmp(value + 1, expect, need)) {
3076                 if (*skip_Delay(value + need + 1) == '\0') {
3077                     result = TRUE;
3078                 }
3079             }
3080         }
3081     }
3082     return result;
3083 }
3084
3085 static int
3086 guess_ANSI_VTxx(TERMTYPE2 *tp)
3087 {
3088     int result = -1;
3089     int checks = 0;
3090
3091     /* VT100s have scrolling region, but ANSI (ECMA-48) does not specify */
3092     if (check_ANSI_cap(change_scroll_region, 2, 'r') &&
3093         (isValidEscape(scroll_forward, "D") ||
3094          isValidString(scroll_forward, "\n") ||
3095          isValidEscape(scroll_forward, "6")) &&
3096         (isValidEscape(scroll_reverse, "M") ||
3097          isValidEscape(scroll_reverse, "9"))) {
3098         checks |= 2;
3099     }
3100     if (check_ANSI_cap(cursor_address, 2, 'H') &&
3101         check_ANSI_cap(cursor_up, 0, 'A') &&
3102         (check_ANSI_cap(cursor_down, 0, 'B') ||
3103          isValidString(cursor_down, "\n")) &&
3104         check_ANSI_cap(cursor_right, 0, 'C') &&
3105         (check_ANSI_cap(cursor_left, 0, 'D') ||
3106          isValidString(cursor_left, "\b")) &&
3107         check_ANSI_cap(clr_eos, 0, 'J') &&
3108         check_ANSI_cap(clr_bol, 0, 'K') &&
3109         check_ANSI_cap(clr_eol, 0, 'K')) {
3110         checks |= 1;
3111     }
3112     if (checks == 3)
3113         result = 1;
3114     if (checks == 1)
3115         result = 0;
3116     return result;
3117 }
3118
3119 /*
3120  * u6/u7 and u8/u9 are query/response extensions which most terminals support.
3121  * In particular, any ECMA-48 terminal should support these, though the details
3122  * for u9 are implementation dependent.
3123  */
3124 static void
3125 check_user_6789(TERMTYPE2 *tp)
3126 {
3127     /*
3128      * Check if the terminal is known to not 
3129      */
3130 #define NO_QUERY(longname,shortname) \
3131         if (PRESENT(longname)) _nc_warning(#shortname " is not supported")
3132     if (tigetflag("NQ") > 0) {
3133         NO_QUERY(user6, u6);
3134         NO_QUERY(user7, u7);
3135         NO_QUERY(user8, u8);
3136         NO_QUERY(user9, u9);
3137         return;
3138     }
3139
3140     PAIRED(user6, user7);
3141     PAIRED(user8, user9);
3142
3143     if (strchr(tp->term_names, '+') != NULL)
3144         return;
3145
3146     switch (guess_ANSI_VTxx(tp)) {
3147     case 1:
3148         if (!PRESENT(user8)) {
3149             _nc_warning("expected u8/u9 for device-attributes");
3150         }
3151         /* FALLTHRU */
3152     case 0:
3153         if (!PRESENT(user6)) {
3154             _nc_warning("expected u6/u7 for cursor-position");
3155         }
3156         break;
3157     }
3158 }
3159
3160 /* other sanity-checks (things that we don't want in the normal
3161  * logic that reads a terminfo entry)
3162  */
3163 static void
3164 check_termtype(TERMTYPE2 *tp, bool literal)
3165 {
3166     unsigned j;
3167
3168     check_conflict(tp);
3169
3170     for_each_string(j, tp) {
3171         char *a = tp->Strings[j];
3172         if (VALID_STRING(a)) {
3173             const char *name = ExtStrname(tp, (int) j, strnames);
3174             /*
3175              * If we expect parameters, or if there might be parameters,
3176              * check for consistent number of parameters.
3177              */
3178             if (j >= SIZEOF(parametrized) ||
3179                 is_user_capability(name) >= 0 ||
3180                 parametrized[j] > 0) {
3181                 check_params(tp, name, a, (j >= STRCOUNT));
3182             }
3183             check_delays(tp, ExtStrname(tp, (int) j, strnames), a);
3184             if (capdump) {
3185                 check_infotocap(tp, (int) j, a);
3186             }
3187         }
3188     }
3189 #if NCURSES_XNAMES
3190     /* in extended mode, verify that each extension is expected type */
3191     for_each_ext_boolean(j, tp) {
3192         check_user_capability_type(ExtBoolname(tp, (int) j, strnames), BOOLEAN);
3193     }
3194     for_each_ext_number(j, tp) {
3195         check_user_capability_type(ExtNumname(tp, (int) j, strnames), NUMBER);
3196     }
3197     for_each_ext_string(j, tp) {
3198         check_user_capability_type(ExtStrname(tp, (int) j, strnames), STRING);
3199     }
3200 #endif /* NCURSES_XNAMES */
3201
3202     check_acs(tp);
3203     check_colors(tp);
3204     check_cursor(tp);
3205     check_keypad(tp);
3206     check_printer(tp);
3207     check_screen(tp);
3208     check_user_6789(tp);
3209
3210     /*
3211      * These are probably both or none.
3212      */
3213     PAIRED(parm_index, parm_rindex);
3214     PAIRED(parm_ich, parm_dch);
3215
3216     /*
3217      * These may be mismatched because the terminal description relies on
3218      * restoring the cursor visibility by resetting it.
3219      */
3220     ANDMISSING(cursor_invisible, cursor_normal);
3221     ANDMISSING(cursor_visible, cursor_normal);
3222
3223     if (PRESENT(cursor_visible) && PRESENT(cursor_normal)
3224         && !_nc_capcmp(cursor_visible, cursor_normal))
3225         _nc_warning("cursor_visible is same as cursor_normal");
3226
3227     /*
3228      * From XSI & O'Reilly, we gather that sc/rc are required if csr is
3229      * given, because the cursor position after the scrolling operation is
3230      * performed is undefined.
3231      */
3232     ANDMISSING(change_scroll_region, save_cursor);
3233     ANDMISSING(change_scroll_region, restore_cursor);
3234
3235     /*
3236      * If we can clear tabs, we should be able to initialize them.
3237      */
3238     ANDMISSING(clear_all_tabs, set_tab);
3239
3240     if (PRESENT(set_attributes)) {
3241         char *zero = 0;
3242
3243         _nc_tparm_err = 0;
3244         if (PRESENT(exit_attribute_mode)) {
3245             zero = strdup(CHECK_SGR(0, exit_attribute_mode));
3246         } else {
3247             zero = strdup(TIPARM_9(set_attributes, 0, 0, 0, 0, 0, 0, 0, 0, 0));
3248         }
3249         check_tparm_err(0);
3250
3251         if (zero != 0) {
3252             CHECK_SGR(1, enter_standout_mode);
3253             CHECK_SGR(2, enter_underline_mode);
3254             CHECK_SGR(3, enter_reverse_mode);
3255             CHECK_SGR(4, enter_blink_mode);
3256             CHECK_SGR(5, enter_dim_mode);
3257             CHECK_SGR(6, enter_bold_mode);
3258             CHECK_SGR(7, enter_secure_mode);
3259             CHECK_SGR(8, enter_protected_mode);
3260             CHECK_SGR(9, enter_alt_charset_mode);
3261             free(zero);
3262         } else {
3263             _nc_warning("sgr(0) did not return a value");
3264         }
3265     } else if (PRESENT(exit_attribute_mode) &&
3266                set_attributes != CANCELLED_STRING) {
3267         if (_nc_syntax == SYN_TERMINFO)
3268             _nc_warning("missing sgr string");
3269     }
3270 #define CHECK_SGR0(name) check_exit_attribute(#name, name, check_sgr0, exit_attribute_mode)
3271     if (PRESENT(exit_attribute_mode)) {
3272         char *check_sgr0 = _nc_trim_sgr0(tp);
3273
3274         if (check_sgr0 == NULL || *check_sgr0 == '\0') {
3275             _nc_warning("trimmed sgr0 is empty");
3276         } else {
3277             show_where(2);
3278             if (check_sgr0 != exit_attribute_mode) {
3279                 DEBUG(2,
3280                       ("will trim sgr0\n\toriginal sgr0=%s\n\ttrimmed  sgr0=%s",
3281                        _nc_visbuf2(1, exit_attribute_mode),
3282                        _nc_visbuf2(2, check_sgr0)));
3283             } else {
3284                 DEBUG(2,
3285                       ("will not trim sgr0\n\toriginal sgr0=%s",
3286                        _nc_visbuf(exit_attribute_mode)));
3287             }
3288         }
3289 #if defined(exit_italics_mode)
3290         CHECK_SGR0(exit_italics_mode);
3291 #endif
3292         CHECK_SGR0(exit_standout_mode);
3293         CHECK_SGR0(exit_underline_mode);
3294         if (check_sgr0 != exit_attribute_mode) {
3295             free(check_sgr0);
3296         }
3297     }
3298 #define CHECK_SGR_PARAM(code, name) check_sgr_param(tp, (int)code, #name, name)
3299     for (j = 0; *sgr_names[j] != '\0'; ++j) {
3300         CHECK_SGR_PARAM(j, set_a_foreground);
3301         CHECK_SGR_PARAM(j, set_a_background);
3302         CHECK_SGR_PARAM(j, set_foreground);
3303         CHECK_SGR_PARAM(j, set_background);
3304     }
3305 #ifdef TRACE
3306     show_where(2);
3307     if (!auto_right_margin) {
3308         DEBUG(2,
3309               ("can write to lower-right directly"));
3310     } else if (PRESENT(enter_am_mode) && PRESENT(exit_am_mode)) {
3311         DEBUG(2,
3312               ("can write to lower-right by suppressing automargin"));
3313     } else if ((PRESENT(enter_insert_mode) && PRESENT(exit_insert_mode))
3314                || PRESENT(insert_character) || PRESENT(parm_ich)) {
3315         DEBUG(2,
3316               ("can write to lower-right by using inserts"));
3317     } else {
3318         DEBUG(2,
3319               ("cannot write to lower-right"));
3320     }
3321 #endif
3322
3323     /*
3324      * Some standard applications (e.g., vi) and some non-curses
3325      * applications (e.g., jove) get confused if we have both ich1 and
3326      * smir/rmir.  Let's be nice and warn about that, too, even though
3327      * ncurses handles it.
3328      */
3329     if ((PRESENT(enter_insert_mode) || PRESENT(exit_insert_mode))
3330         && PRESENT(insert_character)) {
3331         _nc_warning("non-curses applications may be confused by ich1 with smir/rmir");
3332     }
3333
3334     /*
3335      * Finally, do the non-verbose checks
3336      */
3337     if (save_check_termtype != 0)
3338         save_check_termtype(tp, literal);
3339 }