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