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