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