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