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