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