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