]> ncurses.scripts.mit.edu Git - ncurses.git/blob - progs/tic.c
ncurses 6.1 - patch 20190420
[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.274 2019/04/20 20:28:19 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                             if (infodump)
1028                                 (void) putchar(fgetc(tmp_fp));
1029                             else
1030                                 put_translate(fgetc(tmp_fp));
1031                         }
1032                     }
1033
1034                     repair_acsc(&qp->tterm);
1035                     dump_entry(&qp->tterm, suppress_untranslatable,
1036                                limited, numbers, NULL);
1037                     for (j = 0; j < (long) qp->nuses; j++)
1038                         dump_uses(qp->uses[j].name, !capdump);
1039                     len = show_entry();
1040                     if (debug_level != 0 && !limited)
1041                         printf("# length=%d\n", len);
1042                 }
1043             }
1044             if (!namelst && _nc_tail && !quiet) {
1045                 int c, oldc = '\0';
1046                 bool in_comment = FALSE;
1047                 bool trailing_comment = FALSE;
1048
1049                 (void) fseek(tmp_fp, _nc_tail->cend, SEEK_SET);
1050                 while ((c = fgetc(tmp_fp)) != EOF) {
1051                     if (oldc == '\n') {
1052                         if (c == '#') {
1053                             trailing_comment = TRUE;
1054                             in_comment = TRUE;
1055                         } else {
1056                             in_comment = FALSE;
1057                         }
1058                     }
1059                     if (trailing_comment
1060                         && (in_comment || (oldc == '\n' && c == '\n')))
1061                         putchar(c);
1062                     oldc = c;
1063                 }
1064             }
1065         }
1066     }
1067
1068     /* Show the directory into which entries were written, and the total
1069      * number of entries
1070      */
1071     if (showsummary
1072         && (!(check_only || infodump || capdump))) {
1073         int total = _nc_tic_written();
1074         if (total != 0)
1075             fprintf(log_fp, "%d entries written to %s\n",
1076                     total,
1077                     _nc_tic_dir((char *) 0));
1078         else
1079             fprintf(log_fp, "No entries written\n");
1080     }
1081     ExitProgram(EXIT_SUCCESS);
1082 }
1083
1084 /*
1085  * This bit of legerdemain turns all the terminfo variable names into
1086  * references to locations in the arrays Booleans, Numbers, and Strings ---
1087  * precisely what's needed (see comp_parse.c).
1088  */
1089 #undef CUR
1090 #define CUR tp->
1091
1092 /*
1093  * Check if the alternate character-set capabilities are consistent.
1094  */
1095 static void
1096 check_acs(TERMTYPE2 *tp)
1097 {
1098     int vt100_smacs = 0;
1099     int vt100_rmacs = 0;
1100     int vt100_enacs = 0;
1101
1102     /*
1103      * ena_acs is not always necessary, but if it is present, the enter/exit
1104      * capabilities should be.
1105      */
1106     ANDMISSING(ena_acs, enter_alt_charset_mode);
1107     ANDMISSING(ena_acs, exit_alt_charset_mode);
1108     PAIRED(exit_alt_charset_mode, exit_alt_charset_mode);
1109
1110     /*
1111      * vt100-like is frequently used, but perhaps ena_acs is missing, etc.
1112      */
1113     if (VALID_STRING(enter_alt_charset_mode)) {
1114         vt100_smacs = (!strcmp("\033(0", enter_alt_charset_mode)
1115                        ? 2
1116                        : (!strcmp("\016", enter_alt_charset_mode)
1117                           ? 1
1118                           : 0));
1119     }
1120     if (VALID_STRING(exit_alt_charset_mode)) {
1121         vt100_rmacs = (!strcmp("\033(B", exit_alt_charset_mode)
1122                        ? 2
1123                        : (!strcmp("\017", exit_alt_charset_mode)
1124                           ? 1
1125                           : 0));
1126     }
1127     if (VALID_STRING(ena_acs)) {
1128         vt100_enacs = (!strcmp("\033(B\033)0", ena_acs)
1129                        ? 2
1130                        : 0);
1131     }
1132     if (vt100_rmacs && vt100_smacs && (vt100_rmacs != vt100_smacs)) {
1133         _nc_warning("rmacs/smacs are inconsistent");
1134     }
1135     if ((vt100_rmacs == 2) && (vt100_smacs == 2) && vt100_enacs) {
1136         _nc_warning("rmacs/smacs make enacs redundant");
1137     }
1138     if ((vt100_rmacs == 1) && (vt100_smacs == 1) && !vt100_enacs) {
1139         _nc_warning("VT100-style rmacs/smacs require enacs");
1140     }
1141
1142     if (VALID_STRING(acs_chars)) {
1143         const char *boxes = "lmkjtuvwqxn";
1144         char mapped[256];
1145         char missing[256];
1146         const char *p;
1147         char *q;
1148
1149         memset(mapped, 0, sizeof(mapped));
1150         for (p = acs_chars; *p != '\0'; p += 2) {
1151             if (p[1] == '\0') {
1152                 _nc_warning("acsc has odd number of characters");
1153                 break;
1154             }
1155             mapped[UChar(p[0])] = p[1];
1156         }
1157
1158         if (mapped[UChar('I')] && !mapped[UChar('i')]) {
1159             _nc_warning("acsc refers to 'I', which is probably an error");
1160         }
1161
1162         for (p = boxes, q = missing; *p != '\0'; ++p) {
1163             if (!mapped[UChar(p[0])]) {
1164                 *q++ = p[0];
1165             }
1166         }
1167         *q = '\0';
1168
1169         assert(strlen(missing) <= strlen(boxes));
1170         if (*missing != '\0' && strcmp(missing, boxes)) {
1171             _nc_warning("acsc is missing some line-drawing mapping: %s", missing);
1172         }
1173     }
1174 }
1175
1176 static bool
1177 same_color(NCURSES_CONST char *oldcap, NCURSES_CONST char *newcap, int limit)
1178 {
1179     bool result = FALSE;
1180     if (limit > 16)
1181         limit = 16;
1182     if (limit >= 8) {
1183         int n;
1184         int same;
1185         for (n = same = 0; n < limit; ++n) {
1186             char *oldvalue = strdup(TPARM_1(oldcap, n));
1187             char *newvalue = strdup(TPARM_1(newcap, n));
1188             same += !strcmp(oldvalue, newvalue);
1189             free(oldvalue);
1190             free(newvalue);
1191         }
1192         result = (same == limit);
1193     }
1194     return result;
1195 }
1196
1197 /*
1198  * Check if the color capabilities are consistent
1199  */
1200 static void
1201 check_colors(TERMTYPE2 *tp)
1202 {
1203     if ((max_colors > 0) != (max_pairs > 0)
1204         || ((max_colors > max_pairs) && (initialize_pair == 0)))
1205         _nc_warning("inconsistent values for max_colors (%d) and max_pairs (%d)",
1206                     max_colors, max_pairs);
1207
1208     PAIRED(set_foreground, set_background);
1209     PAIRED(set_a_foreground, set_a_background);
1210     PAIRED(set_color_pair, initialize_pair);
1211
1212     if (VALID_STRING(set_foreground)
1213         && VALID_STRING(set_a_foreground)) {
1214         if (!_nc_capcmp(set_foreground, set_a_foreground)) {
1215             _nc_warning("expected setf/setaf to be different");
1216         } else if (same_color(set_foreground, set_a_foreground, max_colors)) {
1217             _nc_warning("setf/setaf are equivalent");
1218         }
1219     }
1220
1221     if (VALID_STRING(set_background)
1222         && VALID_STRING(set_a_background)) {
1223         if (!_nc_capcmp(set_background, set_a_background)) {
1224             _nc_warning("expected setb/setab to be different");
1225         } else if (same_color(set_background, set_a_background, max_colors)) {
1226             _nc_warning("setb/setab are equivalent");
1227         }
1228     }
1229
1230     /* see: has_colors() */
1231     if (VALID_NUMERIC(max_colors) && VALID_NUMERIC(max_pairs)
1232         && ((VALID_STRING(set_foreground)
1233              && VALID_STRING(set_background))
1234             || (VALID_STRING(set_a_foreground)
1235                 && VALID_STRING(set_a_background))
1236             || set_color_pair)) {
1237         if (!VALID_STRING(orig_pair) && !VALID_STRING(orig_colors))
1238             _nc_warning("expected either op/oc string for resetting colors");
1239     }
1240     if (can_change) {
1241         if (!VALID_STRING(initialize_pair) &&
1242             !VALID_STRING(initialize_color)) {
1243             _nc_warning("expected initc or initp because ccc is given");
1244         }
1245     } else {
1246         if (VALID_STRING(initialize_pair) ||
1247             VALID_STRING(initialize_color)) {
1248             _nc_warning("expected ccc because initc is given");
1249         }
1250     }
1251 }
1252
1253 static int
1254 csi_length(const char *value)
1255 {
1256     int result = 0;
1257
1258     if (value[0] == '\033' && value[1] == '[') {
1259         result = 2;
1260     } else if (UChar(value[0]) == 0x9a) {
1261         result = 1;
1262     }
1263     return result;
1264 }
1265
1266 static char
1267 keypad_final(const char *string)
1268 {
1269     char result = '\0';
1270
1271     if (VALID_STRING(string)
1272         && *string++ == '\033'
1273         && *string++ == 'O'
1274         && strlen(string) == 1) {
1275         result = *string;
1276     }
1277
1278     return result;
1279 }
1280
1281 static long
1282 keypad_index(const char *string)
1283 {
1284     char *test;
1285     const char *list = "PQRSwxymtuvlqrsPpn";    /* app-keypad except "Enter" */
1286     int ch;
1287     long result = -1;
1288
1289     if ((ch = keypad_final(string)) != '\0') {
1290         test = (strchr) (list, ch);
1291         if (test != 0)
1292             result = (long) (test - list);
1293     }
1294     return result;
1295 }
1296
1297 /*
1298  * list[] is down, up, left, right
1299  * "left" may be ^H rather than \E[D
1300  * "down" may be ^J rather than \E[B
1301  * But up/right are generally consistently escape sequences for ANSI terminals.
1302  */
1303 static void
1304 check_ansi_cursor(char *list[4])
1305 {
1306     int j, k;
1307     int want;
1308     size_t suffix;
1309     bool skip[4];
1310     bool repeated = FALSE;
1311
1312     for (j = 0; j < 4; ++j) {
1313         skip[j] = FALSE;
1314         for (k = 0; k < j; ++k) {
1315             if (j != k
1316                 && !strcmp(list[j], list[k])) {
1317                 char *value = _nc_tic_expand(list[k], TRUE, 0);
1318                 _nc_warning("repeated cursor control %s\n", value);
1319                 repeated = TRUE;
1320             }
1321         }
1322     }
1323     if (!repeated) {
1324         char *up = list[1];
1325         size_t prefix = (size_t) csi_length(up);
1326
1327         if (prefix) {
1328             suffix = prefix;
1329             while (up[suffix] && isdigit(UChar(up[suffix])))
1330                 ++suffix;
1331         }
1332         if (prefix && up[suffix] == 'A') {
1333             skip[1] = TRUE;
1334             if (!strcmp(list[0], "\n"))
1335                 skip[0] = TRUE;
1336             if (!strcmp(list[2], "\b"))
1337                 skip[2] = TRUE;
1338
1339             for (j = 0; j < 4; ++j) {
1340                 if (skip[j] || strlen(list[j]) == 1)
1341                     continue;
1342                 if (memcmp(list[j], up, prefix)) {
1343                     char *value = _nc_tic_expand(list[j], TRUE, 0);
1344                     _nc_warning("inconsistent prefix for %s\n", value);
1345                     continue;
1346                 }
1347                 if (strlen(list[j]) < suffix) {
1348                     char *value = _nc_tic_expand(list[j], TRUE, 0);
1349                     _nc_warning("inconsistent length for %s, expected %d\n",
1350                                 value, (int) suffix + 1);
1351                     continue;
1352                 }
1353                 want = "BADC"[j];
1354                 if (list[j][suffix] != want) {
1355                     char *value = _nc_tic_expand(list[j], TRUE, 0);
1356                     _nc_warning("inconsistent suffix for %s, expected %c, have %c\n",
1357                                 value, want, list[j][suffix]);
1358                 }
1359             }
1360         }
1361     }
1362 }
1363
1364 #define EXPECTED(name) if (!PRESENT(name)) _nc_warning("expected " #name)
1365 #define UNEXPECTED(name) if (PRESENT(name)) _nc_warning("unexpected " #name ", for %s", why)
1366
1367 static void
1368 check_noaddress(TERMTYPE2 *tp, const char *why)
1369 {
1370     UNEXPECTED(column_address);
1371     UNEXPECTED(cursor_address);
1372     UNEXPECTED(cursor_home);
1373     UNEXPECTED(cursor_mem_address);
1374     UNEXPECTED(cursor_to_ll);
1375     UNEXPECTED(row_address);
1376     UNEXPECTED(row_address);
1377 }
1378
1379 static void
1380 check_cursor(TERMTYPE2 *tp)
1381 {
1382     int count;
1383     char *list[4];
1384
1385     if (hard_copy) {
1386         check_noaddress(tp, "hard_copy");
1387     } else if (generic_type) {
1388         check_noaddress(tp, "generic_type");
1389     } else if (strchr(tp->term_names, '+') == 0) {
1390         int y = 0;
1391         int x = 0;
1392         if (PRESENT(column_address))
1393             ++y;
1394         if (PRESENT(cursor_address))
1395             y = x = 10;
1396         if (PRESENT(cursor_home))
1397             ++y, ++x;
1398         if (PRESENT(cursor_mem_address))
1399             y = x = 10;
1400         if (PRESENT(cursor_to_ll))
1401             ++y, ++x;
1402         if (PRESENT(row_address))
1403             ++x;
1404         if (PRESENT(cursor_down))
1405             ++y;
1406         if (PRESENT(cursor_up))
1407             ++y;
1408         if (PRESENT(cursor_left))
1409             ++x;
1410         if (PRESENT(cursor_right))
1411             ++x;
1412         if (x < 2 && y < 2) {
1413             _nc_warning("terminal lacks cursor addressing");
1414         } else {
1415             if (x < 2)
1416                 _nc_warning("terminal lacks cursor column-addressing");
1417             if (y < 2)
1418                 _nc_warning("terminal lacks cursor row-addressing");
1419         }
1420     }
1421
1422     /* it is rare to have an insert-line feature without a matching delete */
1423     ANDMISSING(parm_insert_line, insert_line);
1424     ANDMISSING(parm_delete_line, delete_line);
1425     ANDMISSING(parm_insert_line, parm_delete_line);
1426
1427     /* if we have a parameterized form, then the non-parameterized is easy */
1428     ANDMISSING(parm_down_cursor, cursor_down);
1429     ANDMISSING(parm_up_cursor, cursor_up);
1430     ANDMISSING(parm_left_cursor, cursor_left);
1431     ANDMISSING(parm_right_cursor, cursor_right);
1432
1433     /* Given any of a set of cursor movement, the whole set should be present.
1434      * Technically this is not true (we could use cursor_address to fill in
1435      * unsupported controls), but it is likely.
1436      */
1437     count = 0;
1438     if (PRESENT(parm_down_cursor)) {
1439         list[count++] = parm_down_cursor;
1440     }
1441     if (PRESENT(parm_up_cursor)) {
1442         list[count++] = parm_up_cursor;
1443     }
1444     if (PRESENT(parm_left_cursor)) {
1445         list[count++] = parm_left_cursor;
1446     }
1447     if (PRESENT(parm_right_cursor)) {
1448         list[count++] = parm_right_cursor;
1449     }
1450     if (count == 4) {
1451         check_ansi_cursor(list);
1452     } else if (count != 0) {
1453         EXPECTED(parm_down_cursor);
1454         EXPECTED(parm_up_cursor);
1455         EXPECTED(parm_left_cursor);
1456         EXPECTED(parm_right_cursor);
1457     }
1458
1459     count = 0;
1460     if (PRESENT(cursor_down)) {
1461         list[count++] = cursor_down;
1462     }
1463     if (PRESENT(cursor_up)) {
1464         list[count++] = cursor_up;
1465     }
1466     if (PRESENT(cursor_left)) {
1467         list[count++] = cursor_left;
1468     }
1469     if (PRESENT(cursor_right)) {
1470         list[count++] = cursor_right;
1471     }
1472     if (count == 4) {
1473         check_ansi_cursor(list);
1474     } else if (count != 0) {
1475         count = 0;
1476         if (PRESENT(cursor_down) && strcmp(cursor_down, "\n"))
1477             ++count;
1478         if (PRESENT(cursor_left) && strcmp(cursor_left, "\b"))
1479             ++count;
1480         if (PRESENT(cursor_up) && strlen(cursor_up) > 1)
1481             ++count;
1482         if (PRESENT(cursor_right) && strlen(cursor_right) > 1)
1483             ++count;
1484         if (count) {
1485             EXPECTED(cursor_down);
1486             EXPECTED(cursor_up);
1487             EXPECTED(cursor_left);
1488             EXPECTED(cursor_right);
1489         }
1490     }
1491 }
1492
1493 #define MAX_KP 5
1494 /*
1495  * Do a quick sanity-check for vt100-style keypads to see if the 5-key keypad
1496  * is mapped inconsistently.
1497  */
1498 static void
1499 check_keypad(TERMTYPE2 *tp)
1500 {
1501     char show[80];
1502
1503     if (VALID_STRING(key_a1) &&
1504         VALID_STRING(key_a3) &&
1505         VALID_STRING(key_b2) &&
1506         VALID_STRING(key_c1) &&
1507         VALID_STRING(key_c3)) {
1508         char final[MAX_KP + 1];
1509         long list[MAX_KP];
1510         int increase = 0;
1511         int j, k, kk;
1512         long last;
1513         long test;
1514
1515         final[0] = keypad_final(key_a1);
1516         final[1] = keypad_final(key_a3);
1517         final[2] = keypad_final(key_b2);
1518         final[3] = keypad_final(key_c1);
1519         final[4] = keypad_final(key_c3);
1520         final[5] = '\0';
1521
1522         /* special case: legacy coding using 1,2,3,0,. on the bottom */
1523         assert(strlen(final) <= MAX_KP);
1524         if (!strcmp(final, "qsrpn"))
1525             return;
1526
1527         list[0] = keypad_index(key_a1);
1528         list[1] = keypad_index(key_a3);
1529         list[2] = keypad_index(key_b2);
1530         list[3] = keypad_index(key_c1);
1531         list[4] = keypad_index(key_c3);
1532
1533         /* check that they're all vt100 keys */
1534         for (j = 0; j < MAX_KP; ++j) {
1535             if (list[j] < 0) {
1536                 return;
1537             }
1538         }
1539
1540         /* check if they're all in increasing order */
1541         for (j = 1; j < MAX_KP; ++j) {
1542             if (list[j] > list[j - 1]) {
1543                 ++increase;
1544             }
1545         }
1546         if (increase != (MAX_KP - 1)) {
1547             show[0] = '\0';
1548
1549             for (j = 0, last = -1; j < MAX_KP; ++j) {
1550                 for (k = 0, kk = -1, test = 100; k < 5; ++k) {
1551                     if (list[k] > last &&
1552                         list[k] < test) {
1553                         test = list[k];
1554                         kk = k;
1555                     }
1556                 }
1557                 last = test;
1558                 assert(strlen(show) < (MAX_KP * 4));
1559                 switch (kk) {
1560                 case 0:
1561                     _nc_STRCAT(show, " ka1", sizeof(show));
1562                     break;
1563                 case 1:
1564                     _nc_STRCAT(show, " ka3", sizeof(show));
1565                     break;
1566                 case 2:
1567                     _nc_STRCAT(show, " kb2", sizeof(show));
1568                     break;
1569                 case 3:
1570                     _nc_STRCAT(show, " kc1", sizeof(show));
1571                     break;
1572                 case 4:
1573                     _nc_STRCAT(show, " kc3", sizeof(show));
1574                     break;
1575                 }
1576             }
1577
1578             _nc_warning("vt100 keypad order inconsistent: %s", show);
1579         }
1580
1581     } else if (VALID_STRING(key_a1) ||
1582                VALID_STRING(key_a3) ||
1583                VALID_STRING(key_b2) ||
1584                VALID_STRING(key_c1) ||
1585                VALID_STRING(key_c3)) {
1586         show[0] = '\0';
1587         if (keypad_index(key_a1) >= 0)
1588             _nc_STRCAT(show, " ka1", sizeof(show));
1589         if (keypad_index(key_a3) >= 0)
1590             _nc_STRCAT(show, " ka3", sizeof(show));
1591         if (keypad_index(key_b2) >= 0)
1592             _nc_STRCAT(show, " kb2", sizeof(show));
1593         if (keypad_index(key_c1) >= 0)
1594             _nc_STRCAT(show, " kc1", sizeof(show));
1595         if (keypad_index(key_c3) >= 0)
1596             _nc_STRCAT(show, " kc3", sizeof(show));
1597         if (*show != '\0')
1598             _nc_warning("vt100 keypad map incomplete:%s", show);
1599     }
1600
1601     /*
1602      * These warnings are useful for consistency checks - it is possible that
1603      * there are real terminals with mismatches in these
1604      */
1605     ANDMISSING(key_ic, key_dc);
1606 }
1607
1608 static void
1609 check_printer(TERMTYPE2 *tp)
1610 {
1611     (void) tp;
1612 #if defined(enter_doublewide_mode) && defined(exit_doublewide_mode)
1613     PAIRED(enter_doublewide_mode, exit_doublewide_mode);
1614 #endif
1615 #if defined(enter_italics_mode) && defined(exit_italics_mode)
1616     PAIRED(enter_italics_mode, exit_italics_mode);
1617 #endif
1618 #if defined(enter_leftward_mode) && defined(exit_leftward_mode)
1619     PAIRED(enter_leftward_mode, exit_leftward_mode);
1620 #endif
1621 #if defined(enter_micro_mode) && defined(exit_micro_mode)
1622     PAIRED(enter_micro_mode, exit_micro_mode);
1623 #endif
1624 #if defined(enter_shadow_mode) && defined(exit_shadow_mode)
1625     PAIRED(enter_shadow_mode, exit_shadow_mode);
1626 #endif
1627 #if defined(enter_subscript_mode) && defined(exit_subscript_mode)
1628     PAIRED(enter_subscript_mode, exit_subscript_mode);
1629 #endif
1630 #if defined(enter_superscript_mode) && defined(exit_superscript_mode)
1631     PAIRED(enter_superscript_mode, exit_superscript_mode);
1632 #endif
1633 #if defined(enter_upward_mode) && defined(exit_upward_mode)
1634     PAIRED(enter_upward_mode, exit_upward_mode);
1635 #endif
1636
1637 #if defined(start_char_set_def) && defined(stop_char_set_def)
1638     ANDMISSING(start_char_set_def, stop_char_set_def);
1639 #endif
1640
1641     /* if we have a parameterized form, then the non-parameterized is easy */
1642 #if defined(set_bottom_margin_parm) && defined(set_bottom_margin)
1643     ANDMISSING(set_bottom_margin_parm, set_bottom_margin);
1644 #endif
1645 #if defined(set_left_margin_parm) && defined(set_left_margin)
1646     ANDMISSING(set_left_margin_parm, set_left_margin);
1647 #endif
1648 #if defined(set_right_margin_parm) && defined(set_right_margin)
1649     ANDMISSING(set_right_margin_parm, set_right_margin);
1650 #endif
1651 #if defined(set_top_margin_parm) && defined(set_top_margin)
1652     ANDMISSING(set_top_margin_parm, set_top_margin);
1653 #endif
1654
1655 #if defined(parm_down_micro) && defined(micro_down)
1656     ANDMISSING(parm_down_micro, micro_down);
1657 #endif
1658 #if defined(parm_left_micro) && defined(micro_left)
1659     ANDMISSING(parm_left_micro, micro_left);
1660 #endif
1661 #if defined(parm_right_micro) && defined(micro_right)
1662     ANDMISSING(parm_right_micro, micro_right);
1663 #endif
1664 #if defined(parm_up_micro) && defined(micro_up)
1665     ANDMISSING(parm_up_micro, micro_up);
1666 #endif
1667 }
1668
1669 #if NCURSES_XNAMES
1670 static bool
1671 uses_SGR_39_49(const char *value)
1672 {
1673     return (strstr(value, "39;49") != 0
1674             || strstr(value, "49;39") != 0);
1675 }
1676
1677 /*
1678  * Check consistency of termcap extensions related to "screen".
1679  */
1680 static void
1681 check_screen(TERMTYPE2 *tp)
1682 {
1683     if (_nc_user_definable) {
1684         int have_XT = tigetflag("XT");
1685         int have_XM = tigetflag("XM");
1686         int have_bce = back_color_erase;
1687         bool have_kmouse = FALSE;
1688         bool use_sgr_39_49 = FALSE;
1689         char *name = _nc_first_name(tp->term_names);
1690         bool is_screen = !strncmp(name, "screen", 6);
1691         bool screen_base = (is_screen
1692                             && strchr(name, '.') == 0);
1693
1694         if (!VALID_BOOLEAN(have_bce)) {
1695             have_bce = FALSE;
1696         }
1697         if (!VALID_BOOLEAN(have_XM)) {
1698             have_XM = FALSE;
1699         }
1700         if (!VALID_BOOLEAN(have_XT)) {
1701             have_XT = FALSE;
1702         }
1703         if (VALID_STRING(key_mouse)) {
1704             have_kmouse = !strcmp("\033[M", key_mouse);
1705         }
1706         if (VALID_STRING(orig_colors)) {
1707             use_sgr_39_49 = uses_SGR_39_49(orig_colors);
1708         } else if (VALID_STRING(orig_pair)) {
1709             use_sgr_39_49 = uses_SGR_39_49(orig_pair);
1710         }
1711
1712         if (have_XM && have_XT) {
1713             _nc_warning("screen's XT capability conflicts with XM");
1714         } else if (have_XT && screen_base) {
1715             _nc_warning("screen's \"screen\" entries should not have XT set");
1716         } else if (have_XT) {
1717             if (!have_kmouse && is_screen) {
1718                 if (VALID_STRING(key_mouse)) {
1719                     _nc_warning("value of kmous inconsistent with screen's usage");
1720                 } else {
1721                     _nc_warning("expected kmous capability with XT");
1722                 }
1723             }
1724             if (!have_bce && max_colors > 0)
1725                 _nc_warning("expected bce capability with XT");
1726             if (!use_sgr_39_49 && have_bce && max_colors > 0)
1727                 _nc_warning("expected orig_colors capability with XT to have 39/49 parameters");
1728             if (VALID_STRING(to_status_line))
1729                 _nc_warning("\"tsl\" capability is redundant, given XT");
1730         } else {
1731             if (have_kmouse
1732                 && !have_XM
1733                 && !screen_base && strchr(name, '+') == 0) {
1734                 _nc_warning("expected XT to be set, given kmous");
1735             }
1736         }
1737     }
1738 }
1739 #else
1740 #define check_screen(tp)        /* nothing */
1741 #endif
1742
1743 /*
1744  * Returns the expected number of parameters for the given capability.
1745  */
1746 static int
1747 expected_params(const char *name)
1748 {
1749 #define DATA(name,count) { { name }, count }
1750     /* *INDENT-OFF* */
1751     static const struct {
1752         const char name[9];
1753         int count;
1754     } table[] = {
1755         DATA( "S0",             1 ),    /* 'screen' extension */
1756         DATA( "birep",          2 ),
1757         DATA( "chr",            1 ),
1758         DATA( "colornm",        1 ),
1759         DATA( "cpi",            1 ),
1760         DATA( "csnm",           1 ),
1761         DATA( "csr",            2 ),
1762         DATA( "cub",            1 ),
1763         DATA( "cud",            1 ),
1764         DATA( "cuf",            1 ),
1765         DATA( "cup",            2 ),
1766         DATA( "cuu",            1 ),
1767         DATA( "cvr",            1 ),
1768         DATA( "cwin",           5 ),
1769         DATA( "dch",            1 ),
1770         DATA( "defc",           3 ),
1771         DATA( "dial",           1 ),
1772         DATA( "dispc",          1 ),
1773         DATA( "dl",             1 ),
1774         DATA( "ech",            1 ),
1775         DATA( "getm",           1 ),
1776         DATA( "hpa",            1 ),
1777         DATA( "ich",            1 ),
1778         DATA( "il",             1 ),
1779         DATA( "indn",           1 ),
1780         DATA( "initc",          4 ),
1781         DATA( "initp",          7 ),
1782         DATA( "lpi",            1 ),
1783         DATA( "mc5p",           1 ),
1784         DATA( "mrcup",          2 ),
1785         DATA( "mvpa",           1 ),
1786         DATA( "pfkey",          2 ),
1787         DATA( "pfloc",          2 ),
1788         DATA( "pfx",            2 ),
1789         DATA( "pfxl",           3 ),
1790         DATA( "pln",            2 ),
1791         DATA( "qdial",          1 ),
1792         DATA( "rcsd",           1 ),
1793         DATA( "rep",            2 ),
1794         DATA( "rin",            1 ),
1795         DATA( "sclk",           3 ),
1796         DATA( "scp",            1 ),
1797         DATA( "scs",            1 ),
1798         DATA( "scsd",           2 ),
1799         DATA( "setab",          1 ),
1800         DATA( "setaf",          1 ),
1801         DATA( "setb",           1 ),
1802         DATA( "setcolor",       1 ),
1803         DATA( "setf",           1 ),
1804         DATA( "sgr",            9 ),
1805         DATA( "sgr1",           6 ),
1806         DATA( "slength",        1 ),
1807         DATA( "slines",         1 ),
1808         DATA( "smgbp",          1 ),    /* 2 if smgtp is not given */
1809         DATA( "smglp",          1 ),
1810         DATA( "smglr",          2 ),
1811         DATA( "smgrp",          1 ),
1812         DATA( "smgtb",          2 ),
1813         DATA( "smgtp",          1 ),
1814         DATA( "tsl",            1 ),
1815         DATA( "u6",             -1 ),
1816         DATA( "vpa",            1 ),
1817         DATA( "wind",           4 ),
1818         DATA( "wingo",          1 ),
1819     };
1820     /* *INDENT-ON* */
1821
1822 #undef DATA
1823
1824     unsigned n;
1825     int result = 0;             /* function-keys, etc., use none */
1826
1827     for (n = 0; n < SIZEOF(table); n++) {
1828         if (!strcmp(name, table[n].name)) {
1829             result = table[n].count;
1830             break;
1831         }
1832     }
1833
1834     return result;
1835 }
1836
1837 /*
1838  * Check for user-capabilities that happen to be used in ncurses' terminal
1839  * database.
1840  */
1841 #if NCURSES_XNAMES
1842 static struct user_table_entry const *
1843 lookup_user_capability(const char *name)
1844 {
1845     struct user_table_entry const *result = 0;
1846     if (*name != 'k') {
1847         result = _nc_find_user_entry(name);
1848     }
1849     return result;
1850 }
1851 #endif
1852
1853 /*
1854  * If a given name is likely to be a user-capability, return the number of
1855  * parameters it would be used with.  If not, return -1.
1856  *
1857  * ncurses assumes that u6 could be used for getting the cursor-position, but
1858  * that is not implemented.  Make a special case for that, to quiet needless
1859  * warnings.
1860  *
1861  * The other string-capability extensions (see terminfo.src) which could have
1862  * parameters such as "Ss", "%u", are not used by ncurses.  But we check those
1863  * anyway, to validate the terminfo database.
1864  */
1865 static int
1866 is_user_capability(const char *name)
1867 {
1868     int result = -1;
1869     if (name[0] == 'u' &&
1870         (name[1] >= '0' && name[1] <= '9') &&
1871         name[2] == '\0') {
1872         result = (name[1] == '6') ? 2 : 0;
1873     }
1874 #if NCURSES_XNAMES
1875     else if (using_extensions) {
1876         struct user_table_entry const *p = lookup_user_capability(name);
1877         if (p != 0) {
1878             result = (int) p->ute_argc;
1879         }
1880     }
1881 #endif
1882     return result;
1883 }
1884
1885 /*
1886  * Make a quick sanity check for the parameters which are used in the given
1887  * strings.  If there are no "%p" tokens, then there should be no other "%"
1888  * markers.
1889  */
1890 static void
1891 check_params(TERMTYPE2 *tp, const char *name, char *value, int extended)
1892 {
1893     int expected = expected_params(name);
1894     int actual = 0;
1895     int n;
1896     bool params[NUM_PARM];
1897     char *s = value;
1898
1899 #ifdef set_top_margin_parm
1900     if (!strcmp(name, "smgbp")
1901         && set_top_margin_parm == 0)
1902         expected = 2;
1903 #endif
1904
1905     for (n = 0; n < NUM_PARM; n++)
1906         params[n] = FALSE;
1907
1908     while (*s != 0) {
1909         if (*s == '%') {
1910             if (*++s == '\0') {
1911                 _nc_warning("expected character after %% in %s", name);
1912                 break;
1913             } else if (*s == 'p') {
1914                 if (*++s == '\0' || !isdigit((int) *s)) {
1915                     _nc_warning("expected digit after %%p in %s", name);
1916                     return;
1917                 } else {
1918                     n = (*s - '0');
1919                     if (n > actual)
1920                         actual = n;
1921                     params[n] = TRUE;
1922                 }
1923             }
1924         }
1925         s++;
1926     }
1927
1928 #if NCURSES_XNAMES
1929     if (extended) {
1930         int check = is_user_capability(name);
1931         if (check != actual) {
1932             _nc_warning("extended %s capability has %d parameters, expected %d",
1933                         name, actual, check);
1934         } else if (debug_level > 1) {
1935             _nc_warning("extended %s capability has %d parameters, as expected",
1936                         name, actual);
1937         }
1938         expected = actual;
1939     }
1940 #else
1941     (void) extended;
1942 #endif
1943
1944     if (params[0]) {
1945         _nc_warning("%s refers to parameter 0 (%%p0), which is not allowed", name);
1946     }
1947     if (value == set_attributes || expected < 0) {
1948         ;
1949     } else if (expected != actual) {
1950         _nc_warning("%s uses %d parameters, expected %d", name,
1951                     actual, expected);
1952         for (n = 1; n < actual; n++) {
1953             if (!params[n])
1954                 _nc_warning("%s omits parameter %d", name, n);
1955         }
1956     }
1957
1958     /*
1959      * Counting "%p" markers does not account for termcap expressions which
1960      * may not have been fully translated.  Also, tparm does its own analysis.
1961      * Report differences here.
1962      */
1963     if (actual >= 0) {
1964         char *p_is_s[NUM_PARM];
1965         int popcount;
1966         int analyzed = _nc_tparm_analyze(value, p_is_s, &popcount);
1967         if (analyzed < popcount) {
1968             analyzed = popcount;
1969         }
1970         if (actual != analyzed && expected != analyzed) {
1971 #if NCURSES_XNAMES
1972             int user_cap = is_user_capability(name);
1973             if ((user_cap == analyzed) && using_extensions) {
1974                 ;               /* ignore */
1975             } else if (user_cap >= 0) {
1976                 _nc_warning("tparm will use %d parameters for %s, expected %d",
1977                             analyzed, name, user_cap);
1978             } else
1979 #endif
1980             {
1981                 _nc_warning("tparm analyzed %d parameters for %s, expected %d",
1982                             analyzed, name, actual);
1983             }
1984         }
1985     }
1986 }
1987
1988 static bool
1989 line_capability(const char *name)
1990 {
1991     bool result = FALSE;
1992     static const char *table[] =
1993     {
1994         "csr",                  /* change_scroll_region          */
1995         "clear",                /* clear_screen                  */
1996         "ed",                   /* clr_eos                       */
1997         "cwin",                 /* create_window                 */
1998         "cup",                  /* cursor_address                */
1999         "cud1",                 /* cursor_down                   */
2000         "home",                 /* cursor_home                   */
2001         "mrcup",                /* cursor_mem_address            */
2002         "ll",                   /* cursor_to_ll                  */
2003         "cuu1",                 /* cursor_up                     */
2004         "dl1",                  /* delete_line                   */
2005         "hd",                   /* down_half_line                */
2006         "flash",                /* flash_screen                  */
2007         "ff",                   /* form_feed                     */
2008         "il1",                  /* insert_line                   */
2009         "nel",                  /* newline                       */
2010         "dl",                   /* parm_delete_line              */
2011         "cud",                  /* parm_down_cursor              */
2012         "indn",                 /* parm_index                    */
2013         "il",                   /* parm_insert_line              */
2014         "rin",                  /* parm_rindex                   */
2015         "cuu",                  /* parm_up_cursor                */
2016         "mc0",                  /* print_screen                  */
2017         "vpa",                  /* row_address                   */
2018         "ind",                  /* scroll_forward                */
2019         "ri",                   /* scroll_reverse                */
2020         "hu",                   /* up_half_line                  */
2021     };
2022     size_t n;
2023     for (n = 0; n < SIZEOF(table); ++n) {
2024         if (!strcmp(name, table[n])) {
2025             result = TRUE;
2026             break;
2027         }
2028     }
2029     return result;
2030 }
2031
2032 /*
2033  * Check for DEC VT100 private mode for reverse video.
2034  */
2035 static const char *
2036 skip_DECSCNM(const char *value, int *flag)
2037 {
2038     *flag = -1;
2039     if (value != 0) {
2040         int skip = csi_length(value);
2041         if (skip > 0 &&
2042             value[skip++] == '?' &&
2043             value[skip++] == '5') {
2044             if (value[skip] == 'h') {
2045                 *flag = 1;
2046             } else if (value[skip] == 'l') {
2047                 *flag = 0;
2048             }
2049             value += skip + 1;
2050         }
2051     }
2052     return value;
2053 }
2054
2055 static void
2056 check_delays(TERMTYPE2 *tp, const char *name, const char *value)
2057 {
2058     const char *p, *q;
2059     const char *first = 0;
2060     const char *last = 0;
2061
2062     for (p = value; *p != '\0'; ++p) {
2063         if (p[0] == '$' && p[1] == '<') {
2064             const char *base = p + 2;
2065             const char *mark = 0;
2066             bool maybe = TRUE;
2067             bool mixed = FALSE;
2068             int proportional = 0;
2069             int mandatory = 0;
2070
2071             first = p;
2072
2073             for (q = base; *q != '\0'; ++q) {
2074                 if (*q == '>') {
2075                     if (mark == 0)
2076                         mark = q;
2077                     break;
2078                 } else if (*q == '*' || *q == '/') {
2079                     if (*q == '*')
2080                         ++proportional;
2081                     if (*q == '/')
2082                         ++mandatory;
2083                     if (mark == 0)
2084                         mark = q;
2085                 } else if (!(isalnum(UChar(*q)) || strchr("+-.", *q) != 0)) {
2086                     maybe = FALSE;
2087                     break;
2088                 } else if (proportional || mandatory) {
2089                     mixed = TRUE;
2090                 }
2091             }
2092             last = *q ? (q + 1) : q;
2093             if (*q == '\0') {
2094                 maybe = FALSE;  /* just an isolated "$<" */
2095             } else if (maybe) {
2096                 float check_f;
2097                 char check_c;
2098                 int rc = sscanf(base, "%f%c", &check_f, &check_c);
2099                 if ((rc != 2) || (check_c != *mark) || mixed) {
2100                     _nc_warning("syntax error in %s delay '%.*s'", name,
2101                                 (int) (q - base), base);
2102                 } else if (*name == 'k') {
2103                     _nc_warning("function-key %s has delay", name);
2104                 } else if (proportional && !line_capability(name)) {
2105                     _nc_warning("non-line capability using proportional delay: %s", name);
2106                 } else if (!xon_xoff &&
2107                            !mandatory &&
2108                            strchr(_nc_first_name(tp->term_names), '+') == 0) {
2109                     _nc_warning("%s in %s is used since no xon/xoff",
2110                                 (proportional
2111                                  ? "proportional delay"
2112                                  : "delay"),
2113                                 name);
2114                 }
2115             } else {
2116                 p = q - 1;      /* restart scan */
2117             }
2118         }
2119     }
2120
2121     if (!strcmp(name, "flash") ||
2122         !strcmp(name, "beep")) {
2123
2124         if (first != 0) {
2125             if (first == value || *last == 0) {
2126                 /*
2127                  * Delay is on one end or the other.
2128                  */
2129                 _nc_warning("expected delay embedded within %s", name);
2130             }
2131         } else {
2132             int flag;
2133
2134             /*
2135              * Check for missing delay when using VT100 reverse-video.
2136              * A real VT100 might not need this, but terminal emulators do.
2137              */
2138             if ((p = skip_DECSCNM(value, &flag)) != 0 &&
2139                 flag > 0 &&
2140                 (q = skip_DECSCNM(p, &flag)) != 0 &&
2141                 flag == 0) {
2142                 _nc_warning("expected a delay in %s", name);
2143             }
2144         }
2145     }
2146 }
2147
2148 static char *
2149 check_1_infotocap(const char *name, NCURSES_CONST char *value, int count)
2150 {
2151     int k;
2152     int ignored;
2153     long numbers[1 + NUM_PARM];
2154     char *strings[1 + NUM_PARM];
2155     char *p_is_s[NUM_PARM];
2156     char *result;
2157     char blob[NUM_PARM * 10];
2158     char *next = blob;
2159
2160     *next++ = '\0';
2161     for (k = 1; k <= NUM_PARM; k++) {
2162         numbers[k] = count;
2163         _nc_SPRINTF(next,
2164                     _nc_SLIMIT(sizeof(blob) - (size_t) (next - blob))
2165                     "XYZ%d", count);
2166         strings[k] = next;
2167         next += strlen(next) + 1;
2168     }
2169
2170     switch (tparm_type(name)) {
2171     case Num_Str:
2172         result = TPARM_2(value, numbers[1], strings[2]);
2173         break;
2174     case Num_Str_Str:
2175         result = TPARM_3(value, numbers[1], strings[2], strings[3]);
2176         break;
2177     case Numbers:
2178     default:
2179         (void) _nc_tparm_analyze(value, p_is_s, &ignored);
2180 #define myParam(n) (p_is_s[n - 1] != 0 ? ((TPARM_ARG) strings[n]) : numbers[n])
2181         result = TPARM_9(value,
2182                          myParam(1),
2183                          myParam(2),
2184                          myParam(3),
2185                          myParam(4),
2186                          myParam(5),
2187                          myParam(6),
2188                          myParam(7),
2189                          myParam(8),
2190                          myParam(9));
2191         break;
2192     }
2193     return strdup(result);
2194 }
2195
2196 #define IsDelay(ch) ((ch) == '.' || isdigit(UChar(ch)))
2197
2198 static const char *
2199 parse_delay_value(const char *src, double *delays, int *always)
2200 {
2201     int star = 0;
2202
2203     *delays = 0.0;
2204     if (always)
2205         *always = 0;
2206
2207     while (isdigit(UChar(*src))) {
2208         (*delays) = (*delays) * 10 + (*src++ - '0');
2209     }
2210     if (*src == '.') {
2211         int gotdot = 1;
2212
2213         ++src;
2214         while (isdigit(UChar(*src))) {
2215             gotdot *= 10;
2216             (*delays) += (*src++ - '0') / gotdot;
2217         }
2218     }
2219     while (*src == '*' || *src == '/') {
2220         if (always == 0 && *src == '/')
2221             break;
2222         if (*src++ == '*') {
2223             star = 1;
2224         } else {
2225             *always = 1;
2226         }
2227     }
2228     if (star)
2229         *delays = -(*delays);
2230     return src;
2231 }
2232
2233 static const char *
2234 parse_ti_delay(const char *ti, double *delays)
2235 {
2236     *delays = 0.0;
2237     while (*ti != '\0') {
2238         if (*ti == '\\') {
2239             ++ti;
2240         }
2241         if (ti[0] == '$'
2242             && ti[1] == '<'
2243             && IsDelay(UChar(ti[2]))) {
2244             int ignored;
2245             const char *last = parse_delay_value(ti + 2, delays, &ignored);
2246             if (*last == '>') {
2247                 ti = last;
2248             }
2249         } else {
2250             ++ti;
2251         }
2252     }
2253     return ti;
2254 }
2255
2256 static const char *
2257 parse_tc_delay(const char *tc, double *delays)
2258 {
2259     return parse_delay_value(tc, delays, (int *) 0);
2260 }
2261
2262 /*
2263  * Compare terminfo- and termcap-strings, factoring out delays.
2264  */
2265 static bool
2266 same_ti_tc(const char *ti, const char *tc, bool * embedded)
2267 {
2268     bool same = TRUE;
2269     double ti_delay = 0.0;
2270     double tc_delay = 0.0;
2271     const char *ti_last;
2272
2273     *embedded = FALSE;
2274     ti_last = parse_ti_delay(ti, &ti_delay);
2275     tc = parse_tc_delay(tc, &tc_delay);
2276
2277     while ((ti < ti_last) && *tc) {
2278         if (*ti == '\\' && ispunct(UChar(ti[1]))) {
2279             ++ti;
2280             if ((*ti == '^') && !strncmp(tc, "\\136", 4)) {
2281                 ti += 1;
2282                 tc += 4;
2283                 continue;
2284             }
2285         } else if (ti[0] == '$' && ti[1] == '<') {
2286             double no_delay;
2287             const char *ss = parse_ti_delay(ti, &no_delay);
2288             if (ss != ti) {
2289                 *embedded = TRUE;
2290                 ti = ss;
2291                 continue;
2292             }
2293         }
2294         if (*tc == '\\' && ispunct(UChar(tc[1]))) {
2295             ++tc;
2296         }
2297         if (*ti++ != *tc++) {
2298             same = FALSE;
2299             break;
2300         }
2301     }
2302
2303     if (*embedded) {
2304         if (same) {
2305             same = FALSE;
2306         } else {
2307             *embedded = FALSE;  /* report only one problem */
2308         }
2309     }
2310
2311     return same;
2312 }
2313
2314 /*
2315  * Check terminfo to termcap translation.
2316  */
2317 static void
2318 check_infotocap(TERMTYPE2 *tp, int i, const char *value)
2319 {
2320     const char *name = ExtStrname(tp, i, strnames);
2321     int params = ((i < (int) SIZEOF(parametrized))
2322                   ? parametrized[i]
2323                   : ((*value == 'k')
2324                      ? 0
2325                      : has_params(value)));
2326     int to_char = 0;
2327     char *ti_value;
2328     char *tc_value;
2329     bool embedded;
2330
2331     assert(SIZEOF(parametrized) == STRCOUNT);
2332     if ((ti_value = _nc_tic_expand(value, TRUE, to_char)) == ABSENT_STRING) {
2333         _nc_warning("tic-expansion of %s failed", name);
2334     } else if ((tc_value = _nc_infotocap(name, ti_value, params)) == ABSENT_STRING) {
2335         _nc_warning("tic-conversion of %s failed", name);
2336     } else if (params > 0) {
2337         int limit = 5;
2338         int count;
2339         bool first = TRUE;
2340
2341         if (!strcmp(name, "setf")
2342             || !strcmp(name, "setb")
2343             || !strcmp(name, "setaf")
2344             || !strcmp(name, "setab")) {
2345             if ((limit = max_colors) > 16)
2346                 limit = 16;
2347         }
2348         for (count = 0; count < limit; ++count) {
2349             char *ti_check = check_1_infotocap(name, ti_value, count);
2350             char *tc_check = check_1_infotocap(name, tc_value, count);
2351
2352             if (strcmp(ti_check, tc_check)) {
2353                 if (first) {
2354                     fprintf(stderr, "check_infotocap(%s)\n", name);
2355                     fprintf(stderr, "...ti '%s'\n", ti_value);
2356                     fprintf(stderr, "...tc '%s'\n", tc_value);
2357                     first = FALSE;
2358                 }
2359                 _nc_warning("tparm-conversion of %s(%d) differs between\n\tterminfo %s\n\ttermcap  %s",
2360                             name, count, ti_check, tc_check);
2361             }
2362             free(ti_check);
2363             free(tc_check);
2364         }
2365     } else if (params == 0 && !same_ti_tc(ti_value, tc_value, &embedded)) {
2366         if (embedded) {
2367             _nc_warning("termcap equivalent of %s cannot use embedded delay", name);
2368         } else {
2369             _nc_warning("tic-conversion of %s changed value\n\tfrom %s\n\tto   %s",
2370                         name, ti_value, tc_value);
2371         }
2372     }
2373 }
2374
2375 static char *
2376 skip_delay(char *s)
2377 {
2378     while (*s == '/' || isdigit(UChar(*s)))
2379         ++s;
2380     return s;
2381 }
2382
2383 /*
2384  * Skip a delay altogether, e.g., when comparing a simple string to sgr,
2385  * the latter may have a worst-case delay on the end.
2386  */
2387 static char *
2388 ignore_delays(char *s)
2389 {
2390     int delaying = 0;
2391
2392     do {
2393         switch (*s) {
2394         case '$':
2395             if (delaying == 0)
2396                 delaying = 1;
2397             break;
2398         case '<':
2399             if (delaying == 1)
2400                 delaying = 2;
2401             break;
2402         case '\0':
2403             delaying = 0;
2404             break;
2405         default:
2406             if (delaying) {
2407                 s = skip_delay(s);
2408                 if (*s == '>')
2409                     ++s;
2410                 delaying = 0;
2411             }
2412             break;
2413         }
2414         if (delaying)
2415             ++s;
2416     } while (delaying);
2417     return s;
2418 }
2419
2420 #define DATA(name) { #name }
2421 static const char sgr_names[][11] =
2422 {
2423     DATA(none),
2424     DATA(standout),
2425     DATA(underline),
2426     DATA(reverse),
2427     DATA(blink),
2428     DATA(dim),
2429     DATA(bold),
2430     DATA(invis),
2431     DATA(protect),
2432     DATA(altcharset),
2433     ""
2434 };
2435 #undef DATA
2436
2437 /*
2438  * An sgr string may contain several settings other than the one we're
2439  * interested in, essentially sgr0 + rmacs + whatever.  As long as the
2440  * "whatever" is contained in the sgr string, that is close enough for our
2441  * sanity check.
2442  */
2443 static bool
2444 similar_sgr(int num, char *a, char *b)
2445 {
2446     char *base_a = a;
2447     char *base_b = b;
2448     int delaying = 0;
2449
2450     while (*b != 0) {
2451         while (*a != *b) {
2452             if (*a == 0) {
2453                 if (num < 0) {
2454                     ;
2455                 } else if (b[0] == '$'
2456                            && b[1] == '<') {
2457                     _nc_warning("did not find delay %s", _nc_visbuf(b));
2458                 } else {
2459                     _nc_warning("checking sgr(%s) %s\n\tcompare to %s\n\tunmatched %s",
2460                                 sgr_names[num], _nc_visbuf2(1, base_a),
2461                                 _nc_visbuf2(2, base_b),
2462                                 _nc_visbuf2(3, b));
2463                 }
2464                 return FALSE;
2465             } else if (delaying) {
2466                 a = skip_delay(a);
2467                 b = skip_delay(b);
2468             } else if ((*b == '0' || (*b == ';')) && *a == 'm') {
2469                 b++;
2470             } else {
2471                 a++;
2472             }
2473         }
2474         switch (*a) {
2475         case '$':
2476             if (delaying == 0)
2477                 delaying = 1;
2478             break;
2479         case '<':
2480             if (delaying == 1)
2481                 delaying = 2;
2482             break;
2483         default:
2484             delaying = 0;
2485             break;
2486         }
2487         a++;
2488         b++;
2489     }
2490     /* ignore delays on the end of the string */
2491     a = ignore_delays(a);
2492     return ((num != 0) || (*a == 0));
2493 }
2494
2495 static char *
2496 check_sgr(TERMTYPE2 *tp, char *zero, int num, char *cap, const char *name)
2497 {
2498     char *test;
2499
2500     _nc_tparm_err = 0;
2501     test = TPARM_9(set_attributes,
2502                    num == 1,
2503                    num == 2,
2504                    num == 3,
2505                    num == 4,
2506                    num == 5,
2507                    num == 6,
2508                    num == 7,
2509                    num == 8,
2510                    num == 9);
2511     if (test != 0) {
2512         if (PRESENT(cap)) {
2513             if (!similar_sgr(num, test, cap)) {
2514                 _nc_warning("%s differs from sgr(%d)\n\t%s=%s\n\tsgr(%d)=%s",
2515                             name, num,
2516                             name, _nc_visbuf2(1, cap),
2517                             num, _nc_visbuf2(2, test));
2518             }
2519         } else if (_nc_capcmp(test, zero)) {
2520             _nc_warning("sgr(%d) present, but not %s", num, name);
2521         }
2522     } else if (PRESENT(cap)) {
2523         _nc_warning("sgr(%d) missing, but %s present", num, name);
2524     }
2525     if (_nc_tparm_err)
2526         _nc_warning("stack error in sgr(%d) string", num);
2527     return test;
2528 }
2529
2530 #define CHECK_SGR(num,name) check_sgr(tp, zero, num, name, #name)
2531
2532 #ifdef TRACE
2533 /*
2534  * If tic is compiled with TRACE, we'll be able to see the output from the
2535  * DEBUG() macro.  But since it doesn't use traceon(), it always goes to
2536  * the standard error.  Use this function to make it simpler to follow the
2537  * resulting debug traces.
2538  */
2539 static void
2540 show_where(unsigned level)
2541 {
2542     if (_nc_tracing >= DEBUG_LEVEL(level)) {
2543         char my_name[MAX_NAME_SIZE];
2544         _nc_get_type(my_name);
2545         _tracef("\"%s\", line %d, '%s'",
2546                 _nc_get_source(),
2547                 _nc_curr_line, my_name);
2548     }
2549 }
2550
2551 #else
2552 #define show_where(level)       /* nothing */
2553 #endif
2554
2555 typedef struct {
2556     int keycode;
2557     const char *name;
2558     const char *value;
2559 } NAME_VALUE;
2560
2561 static NAME_VALUE *
2562 get_fkey_list(TERMTYPE2 *tp)
2563 {
2564     NAME_VALUE *result = typeMalloc(NAME_VALUE, NUM_STRINGS(tp) + 1);
2565     const struct tinfo_fkeys *all_fkeys = _nc_tinfo_fkeys;
2566     int used = 0;
2567     unsigned j;
2568
2569     if (result == 0)
2570         failed("get_fkey_list");
2571
2572     for (j = 0; all_fkeys[j].code; j++) {
2573         char *a = tp->Strings[all_fkeys[j].offset];
2574         if (VALID_STRING(a)) {
2575             result[used].keycode = (int) all_fkeys[j].code;
2576             result[used].name = strnames[all_fkeys[j].offset];
2577             result[used].value = a;
2578             ++used;
2579         }
2580     }
2581 #if NCURSES_XNAMES
2582     for (j = STRCOUNT; j < NUM_STRINGS(tp); ++j) {
2583         const char *name = ExtStrname(tp, (int) j, strnames);
2584         if (*name == 'k') {
2585             result[used].keycode = -1;
2586             result[used].name = name;
2587             result[used].value = tp->Strings[j];
2588             ++used;
2589         }
2590     }
2591 #endif
2592     result[used].keycode = 0;
2593     return result;
2594 }
2595
2596 static void
2597 show_fkey_name(NAME_VALUE * data)
2598 {
2599     if (data->keycode > 0) {
2600         fprintf(stderr, " %s", keyname(data->keycode));
2601         fprintf(stderr, " (capability \"%s\")", data->name);
2602     } else {
2603         fprintf(stderr, " capability \"%s\"", data->name);
2604     }
2605 }
2606
2607 /*
2608  * A terminal entry may contain more than one keycode assigned to a given
2609  * string (e.g., KEY_END and KEY_LL).  But curses will only return one (the
2610  * last one assigned).
2611  */
2612 static void
2613 check_conflict(TERMTYPE2 *tp)
2614 {
2615     bool conflict = FALSE;
2616     unsigned j, k;
2617
2618     if (!(_nc_syntax == SYN_TERMCAP && capdump)) {
2619         char *check = calloc((size_t) (NUM_STRINGS(tp) + 1), sizeof(char));
2620         NAME_VALUE *given = get_fkey_list(tp);
2621
2622         if (check == 0)
2623             failed("check_conflict");
2624
2625         for (j = 0; given[j].keycode; ++j) {
2626             const char *a = given[j].value;
2627             bool first = TRUE;
2628
2629             if (!VALID_STRING(a))
2630                 continue;
2631
2632             for (k = j + 1; given[k].keycode; k++) {
2633                 const char *b = given[k].value;
2634
2635                 if (!VALID_STRING(b))
2636                     continue;
2637                 if (check[k])
2638                     continue;
2639
2640                 if (!_nc_capcmp(a, b)) {
2641                     check[j] = 1;
2642                     check[k] = 1;
2643                     if (first) {
2644                         if (!conflict) {
2645                             _nc_warning("conflicting key definitions (using the last)");
2646                             conflict = TRUE;
2647                         }
2648                         fprintf(stderr, "...");
2649                         show_fkey_name(given + j);
2650                         fprintf(stderr, " is the same as");
2651                         show_fkey_name(given + k);
2652                         first = FALSE;
2653                     } else {
2654                         fprintf(stderr, ", ");
2655                         show_fkey_name(given + k);
2656                     }
2657                 }
2658             }
2659             if (!first)
2660                 fprintf(stderr, "\n");
2661         }
2662 #if NCURSES_XNAMES
2663         if (using_extensions) {
2664             /* *INDENT-OFF* */
2665             static struct {
2666                 const char *xcurses;
2667                 const char *shifted;
2668             } table[] = {
2669                 { "kDC",  NULL },
2670                 { "kDN",  "kind" },
2671                 { "kEND", NULL },
2672                 { "kHOM", NULL },
2673                 { "kLFT", NULL },
2674                 { "kNXT", NULL },
2675                 { "kPRV", NULL },
2676                 { "kRIT", NULL },
2677                 { "kUP",  "kri" },
2678                 { NULL,   NULL },
2679             };
2680             /* *INDENT-ON* */
2681
2682             /*
2683              * SVr4 curses defines the "xcurses" names listed above except for
2684              * the special cases in the "shifted" column.  When using these
2685              * names for xterm's extensions, that was confusing, and resulted
2686              * in adding extended capabilities with "2" (shift) suffix.  This
2687              * check warns about unnecessary use of extensions for this quirk.
2688              */
2689             for (j = 0; given[j].keycode; ++j) {
2690                 const char *find = given[j].name;
2691                 int value;
2692                 char ch;
2693
2694                 if (!VALID_STRING(given[j].value))
2695                     continue;
2696
2697                 for (k = 0; table[k].xcurses; ++k) {
2698                     const char *test = table[k].xcurses;
2699                     size_t size = strlen(test);
2700
2701                     if (!strncmp(find, test, size) && strcmp(find, test)) {
2702                         switch (sscanf(find + size, "%d%c", &value, &ch)) {
2703                         case 1:
2704                             if (value == 2) {
2705                                 _nc_warning("expected '%s' rather than '%s'",
2706                                             (table[k].shifted
2707                                              ? table[k].shifted
2708                                              : test), find);
2709                             } else if (value < 2 || value > 15) {
2710                                 _nc_warning("expected numeric 2..15 '%s'", find);
2711                             }
2712                             break;
2713                         default:
2714                             _nc_warning("expected numeric suffix for '%s'", find);
2715                             break;
2716                         }
2717                         break;
2718                     }
2719                 }
2720             }
2721         }
2722 #endif
2723         free(given);
2724         free(check);
2725     }
2726 }
2727
2728 /*
2729  * Exiting a video mode should not duplicate sgr0
2730  */
2731 static void
2732 check_exit_attribute(const char *name, char *test, char *trimmed, char *untrimmed)
2733 {
2734     if (VALID_STRING(test) && (trimmed != 0)) {
2735         if (similar_sgr(-1, trimmed, test) ||
2736             similar_sgr(-1, untrimmed, test)) {
2737             _nc_warning("%s matches exit_attribute_mode", name);
2738         }
2739     }
2740 }
2741
2742 /*
2743  * Returns true if the string looks like a standard SGR string.
2744  */
2745 static bool
2746 is_sgr_string(char *value)
2747 {
2748     bool result = FALSE;
2749
2750     if (VALID_STRING(value)) {
2751         int skip = csi_length(value);
2752
2753         if (skip) {
2754             int ch;
2755
2756             result = TRUE;
2757             value += skip;
2758             while ((ch = UChar(*value++)) != '\0') {
2759                 if (isdigit(ch) || ch == ';') {
2760                     ;
2761                 } else if (ch == 'm' && *value == '\0') {
2762                     ;
2763                 } else {
2764                     result = FALSE;
2765                     break;
2766                 }
2767             }
2768         }
2769     }
2770     return result;
2771 }
2772
2773 /*
2774  * Check if the given capability contains a given SGR attribute.
2775  */
2776 static void
2777 check_sgr_param(TERMTYPE2 *tp, int code, const char *name, char *value)
2778 {
2779     if (VALID_STRING(value)) {
2780         int ncv = ((code != 0) ? (1 << (code - 1)) : 0);
2781         char *test = tgoto(value, 0, 0);
2782         if (is_sgr_string(test)) {
2783             int param = 0;
2784             int count = 0;
2785             int skips = 0;
2786             int color = (value == set_a_foreground ||
2787                          value == set_a_background ||
2788                          value == set_foreground ||
2789                          value == set_background);
2790             while (*test != 0) {
2791                 if (isdigit(UChar(*test))) {
2792                     param = 10 * param + (*test - '0');
2793                     ++count;
2794                 } else {
2795                     if (count) {
2796                         /*
2797                          * Avoid unnecessary warning for xterm 256color codes.
2798                          */
2799                         if (color && (param == 38 || param == 48))
2800                             skips = 3;
2801                         if ((skips-- <= 0) && (param == code))
2802                             break;
2803                     }
2804                     count = 0;
2805                     param = 0;
2806                 }
2807                 ++test;
2808             }
2809             if (count != 0 && param == code) {
2810                 if (code == 0 ||
2811                     no_color_video < 0 ||
2812                     !(no_color_video & ncv)) {
2813                     _nc_warning("\"%s\" SGR-attribute used in %s",
2814                                 sgr_names[code],
2815                                 name);
2816                 }
2817             }
2818         }
2819     }
2820 }
2821
2822 #if NCURSES_XNAMES
2823 static int
2824 standard_type(const char *name)
2825 {
2826     int result = -1;
2827     const struct name_table_entry *np;
2828
2829     if ((np = _nc_find_entry(name, _nc_get_hash_table(0))) != 0) {
2830         result = np->nte_type;
2831     }
2832     return result;
2833 }
2834
2835 static const char *
2836 name_of_type(int type)
2837 {
2838     const char *result = "unknown";
2839     switch (type) {
2840     case BOOLEAN:
2841         result = "boolean";
2842         break;
2843     case NUMBER:
2844         result = "number";
2845         break;
2846     case STRING:
2847         result = "string";
2848         break;
2849     }
2850     return result;
2851 }
2852
2853 static void
2854 check_user_capability_type(const char *name, int actual)
2855 {
2856     if (lookup_user_capability(name) == 0) {
2857         int expected = standard_type(name);
2858         if (expected >= 0) {
2859             _nc_warning("expected %s to be %s, but actually %s",
2860                         name,
2861                         name_of_type(actual),
2862                         name_of_type(expected)
2863                 );
2864         } else if (*name != 'k') {
2865             _nc_warning("undocumented %s capability %s",
2866                         name_of_type(actual),
2867                         name);
2868         }
2869     }
2870 }
2871 #endif
2872
2873 /* other sanity-checks (things that we don't want in the normal
2874  * logic that reads a terminfo entry)
2875  */
2876 static void
2877 check_termtype(TERMTYPE2 *tp, bool literal)
2878 {
2879     unsigned j;
2880
2881     check_conflict(tp);
2882
2883     for_each_string(j, tp) {
2884         char *a = tp->Strings[j];
2885         if (VALID_STRING(a)) {
2886             const char *name = ExtStrname(tp, (int) j, strnames);
2887             /*
2888              * If we expect parameters, or if there might be parameters,
2889              * check for consistent number of parameters.
2890              */
2891             if (j >= SIZEOF(parametrized) ||
2892                 is_user_capability(name) >= 0 ||
2893                 parametrized[j] > 0) {
2894                 check_params(tp, name, a, (j >= STRCOUNT));
2895             }
2896             check_delays(tp, ExtStrname(tp, (int) j, strnames), a);
2897             if (capdump) {
2898                 check_infotocap(tp, (int) j, a);
2899             }
2900         }
2901     }
2902 #if NCURSES_XNAMES
2903     /* in extended mode, verify that each extension is expected type */
2904     for_each_ext_boolean(j, tp) {
2905         check_user_capability_type(ExtBoolname(tp, (int) j, strnames), BOOLEAN);
2906     }
2907     for_each_ext_number(j, tp) {
2908         check_user_capability_type(ExtNumname(tp, (int) j, strnames), NUMBER);
2909     }
2910     for_each_ext_string(j, tp) {
2911         check_user_capability_type(ExtStrname(tp, (int) j, strnames), STRING);
2912     }
2913 #endif /* NCURSES_XNAMES */
2914
2915     check_acs(tp);
2916     check_colors(tp);
2917     check_cursor(tp);
2918     check_keypad(tp);
2919     check_printer(tp);
2920     check_screen(tp);
2921
2922     /*
2923      * These may be mismatched because the terminal description relies on
2924      * restoring the cursor visibility by resetting it.
2925      */
2926     ANDMISSING(cursor_invisible, cursor_normal);
2927     ANDMISSING(cursor_visible, cursor_normal);
2928
2929     if (PRESENT(cursor_visible) && PRESENT(cursor_normal)
2930         && !_nc_capcmp(cursor_visible, cursor_normal))
2931         _nc_warning("cursor_visible is same as cursor_normal");
2932
2933     /*
2934      * From XSI & O'Reilly, we gather that sc/rc are required if csr is
2935      * given, because the cursor position after the scrolling operation is
2936      * performed is undefined.
2937      */
2938     ANDMISSING(change_scroll_region, save_cursor);
2939     ANDMISSING(change_scroll_region, restore_cursor);
2940
2941     /*
2942      * If we can clear tabs, we should be able to initialize them.
2943      */
2944     ANDMISSING(clear_all_tabs, set_tab);
2945
2946     if (PRESENT(set_attributes)) {
2947         char *zero = 0;
2948
2949         _nc_tparm_err = 0;
2950         if (PRESENT(exit_attribute_mode)) {
2951             zero = strdup(CHECK_SGR(0, exit_attribute_mode));
2952         } else {
2953             zero = strdup(TPARM_9(set_attributes, 0, 0, 0, 0, 0, 0, 0, 0, 0));
2954         }
2955         if (_nc_tparm_err)
2956             _nc_warning("stack error in sgr(0) string");
2957
2958         if (zero != 0) {
2959             CHECK_SGR(1, enter_standout_mode);
2960             CHECK_SGR(2, enter_underline_mode);
2961             CHECK_SGR(3, enter_reverse_mode);
2962             CHECK_SGR(4, enter_blink_mode);
2963             CHECK_SGR(5, enter_dim_mode);
2964             CHECK_SGR(6, enter_bold_mode);
2965             CHECK_SGR(7, enter_secure_mode);
2966             CHECK_SGR(8, enter_protected_mode);
2967             CHECK_SGR(9, enter_alt_charset_mode);
2968             free(zero);
2969         } else {
2970             _nc_warning("sgr(0) did not return a value");
2971         }
2972     } else if (PRESENT(exit_attribute_mode) &&
2973                set_attributes != CANCELLED_STRING) {
2974         if (_nc_syntax == SYN_TERMINFO)
2975             _nc_warning("missing sgr string");
2976     }
2977 #define CHECK_SGR0(name) check_exit_attribute(#name, name, check_sgr0, exit_attribute_mode)
2978     if (PRESENT(exit_attribute_mode)) {
2979         char *check_sgr0 = _nc_trim_sgr0(tp);
2980
2981         if (check_sgr0 == 0 || *check_sgr0 == '\0') {
2982             _nc_warning("trimmed sgr0 is empty");
2983         } else {
2984             show_where(2);
2985             if (check_sgr0 != exit_attribute_mode) {
2986                 DEBUG(2,
2987                       ("will trim sgr0\n\toriginal sgr0=%s\n\ttrimmed  sgr0=%s",
2988                        _nc_visbuf2(1, exit_attribute_mode),
2989                        _nc_visbuf2(2, check_sgr0)));
2990             } else {
2991                 DEBUG(2,
2992                       ("will not trim sgr0\n\toriginal sgr0=%s",
2993                        _nc_visbuf(exit_attribute_mode)));
2994             }
2995         }
2996 #if defined(exit_italics_mode)
2997         CHECK_SGR0(exit_italics_mode);
2998 #endif
2999         CHECK_SGR0(exit_standout_mode);
3000         CHECK_SGR0(exit_underline_mode);
3001         if (check_sgr0 != exit_attribute_mode) {
3002             free(check_sgr0);
3003         }
3004     }
3005 #define CHECK_SGR_PARAM(code, name) check_sgr_param(tp, (int)code, #name, name)
3006     for (j = 0; *sgr_names[j] != '\0'; ++j) {
3007         CHECK_SGR_PARAM(j, set_a_foreground);
3008         CHECK_SGR_PARAM(j, set_a_background);
3009         CHECK_SGR_PARAM(j, set_foreground);
3010         CHECK_SGR_PARAM(j, set_background);
3011     }
3012 #ifdef TRACE
3013     show_where(2);
3014     if (!auto_right_margin) {
3015         DEBUG(2,
3016               ("can write to lower-right directly"));
3017     } else if (PRESENT(enter_am_mode) && PRESENT(exit_am_mode)) {
3018         DEBUG(2,
3019               ("can write to lower-right by suppressing automargin"));
3020     } else if ((PRESENT(enter_insert_mode) && PRESENT(exit_insert_mode))
3021                || PRESENT(insert_character) || PRESENT(parm_ich)) {
3022         DEBUG(2,
3023               ("can write to lower-right by using inserts"));
3024     } else {
3025         DEBUG(2,
3026               ("cannot write to lower-right"));
3027     }
3028 #endif
3029
3030     /*
3031      * Some standard applications (e.g., vi) and some non-curses
3032      * applications (e.g., jove) get confused if we have both ich1 and
3033      * smir/rmir.  Let's be nice and warn about that, too, even though
3034      * ncurses handles it.
3035      */
3036     if ((PRESENT(enter_insert_mode) || PRESENT(exit_insert_mode))
3037         && PRESENT(parm_ich)) {
3038         _nc_warning("non-curses applications may be confused by ich1 with smir/rmir");
3039     }
3040
3041     /*
3042      * Finally, do the non-verbose checks
3043      */
3044     if (save_check_termtype != 0)
3045         save_check_termtype(tp, literal);
3046 }