]> ncurses.scripts.mit.edu Git - ncurses.git/blob - progs/tic.c
ncurses 5.9 - patch 20120324
[ncurses.git] / progs / tic.c
1 /****************************************************************************
2  * Copyright (c) 1998-2011,2012 Free Software Foundation, Inc.              *
3  *                                                                          *
4  * Permission is hereby granted, free of charge, to any person obtaining a  *
5  * copy of this software and associated documentation files (the            *
6  * "Software"), to deal in the Software without restriction, including      *
7  * without limitation the rights to use, copy, modify, merge, publish,      *
8  * distribute, distribute with modifications, sublicense, and/or sell       *
9  * copies of the Software, and to permit persons to whom the Software is    *
10  * furnished to do so, subject to the following conditions:                 *
11  *                                                                          *
12  * The above copyright notice and this permission notice shall be included  *
13  * in all copies or substantial portions of the Software.                   *
14  *                                                                          *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS  *
16  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF               *
17  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.   *
18  * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,   *
19  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR    *
20  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR    *
21  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.                               *
22  *                                                                          *
23  * Except as contained in this notice, the name(s) of the above copyright   *
24  * holders shall not be used in advertising or otherwise to promote the     *
25  * sale, use or other dealings in this Software without prior written       *
26  * authorization.                                                           *
27  ****************************************************************************/
28
29 /****************************************************************************
30  *  Author: Zeyd M. Ben-Halim <zmbenhal@netcom.com> 1992,1995               *
31  *     and: Eric S. Raymond <esr@snark.thyrsus.com>                         *
32  *     and: Thomas E. Dickey                        1996 on                 *
33  ****************************************************************************/
34
35 /*
36  *      tic.c --- Main program for terminfo compiler
37  *                      by Eric S. Raymond
38  *                      and Thomas E Dickey
39  *
40  */
41
42 #include <progs.priv.h>
43 #include <sys/stat.h>
44
45 #include <dump_entry.h>
46 #include <hashed_db.h>
47 #include <transform.h>
48
49 MODULE_ID("$Id: tic.c,v 1.165 2012/03/24 22:07:10 tom Exp $")
50
51 #define STDIN_NAME "<stdin>"
52
53 const char *_nc_progname = "tic";
54
55 static FILE *log_fp;
56 static FILE *tmp_fp;
57 static bool capdump = FALSE;    /* running as infotocap? */
58 static bool infodump = FALSE;   /* running as captoinfo? */
59 static bool showsummary = FALSE;
60 static const char *to_remove;
61
62 static void (*save_check_termtype) (TERMTYPE *, bool);
63 static void check_termtype(TERMTYPE *tt, bool);
64
65 static const char usage_string[] = "\
66 [-e names] \
67 [-o dir] \
68 [-R name] \
69 [-v[n]] \
70 [-V] \
71 [-w[n]] \
72 [-\
73 1\
74 a\
75 C\
76 D\
77 c\
78 f\
79 G\
80 g\
81 I\
82 K\
83 L\
84 N\
85 r\
86 s\
87 T\
88 t\
89 U\
90 x\
91 ] \
92 source-file\n";
93
94 #if NO_LEAKS
95 static void
96 free_namelist(char **src)
97 {
98     if (src != 0) {
99         int n;
100         for (n = 0; src[n] != 0; ++n)
101             free(src[n]);
102         free(src);
103     }
104 }
105 #endif
106
107 static void
108 cleanup(char **namelst GCC_UNUSED)
109 {
110 #if NO_LEAKS
111     free_namelist(namelst);
112 #endif
113     if (tmp_fp != 0)
114         fclose(tmp_fp);
115     if (to_remove != 0) {
116 #if HAVE_REMOVE
117         remove(to_remove);
118 #else
119         unlink(to_remove);
120 #endif
121     }
122 }
123
124 static void
125 failed(const char *msg)
126 {
127     perror(msg);
128     cleanup((char **) 0);
129     ExitProgram(EXIT_FAILURE);
130 }
131
132 static void
133 usage(void)
134 {
135     static const char *const tbl[] =
136     {
137         "Options:",
138         "  -1         format translation output one capability per line",
139 #if NCURSES_XNAMES
140         "  -a         retain commented-out capabilities (sets -x also)",
141 #endif
142         "  -K         translate entries to termcap source form with BSD syntax",
143         "  -C         translate entries to termcap source form",
144         "  -D         print list of tic's database locations (first must be writable)",
145         "  -c         check only, validate input without compiling or translating",
146         "  -e<names>  translate/compile only entries named by comma-separated list",
147         "  -f         format complex strings for readability",
148         "  -G         format %{number} to %'char'",
149         "  -g         format %'char' to %{number}",
150         "  -I         translate entries to terminfo source form",
151         "  -L         translate entries to full terminfo source form",
152         "  -N         disable smart defaults for source translation",
153         "  -o<dir>    set output directory for compiled entry writes",
154         "  -R<name>   restrict translation to given terminfo/termcap version",
155         "  -r         force resolution of all use entries in source translation",
156         "  -s         print summary statistics",
157         "  -T         remove size-restrictions on compiled description",
158 #if NCURSES_XNAMES
159         "  -t         suppress commented-out capabilities",
160 #endif
161         "  -U         suppress post-processing of entries",
162         "  -V         print version",
163         "  -v[n]      set verbosity level",
164         "  -w[n]      set format width for translation output",
165 #if NCURSES_XNAMES
166         "  -x         treat unknown capabilities as user-defined",
167 #endif
168         "",
169         "Parameters:",
170         "  <file>     file to translate or compile"
171     };
172     size_t j;
173
174     fprintf(stderr, "Usage: %s %s\n", _nc_progname, usage_string);
175     for (j = 0; j < SIZEOF(tbl); j++) {
176         fputs(tbl[j], stderr);
177         putc('\n', stderr);
178     }
179     ExitProgram(EXIT_FAILURE);
180 }
181
182 #define L_BRACE '{'
183 #define R_BRACE '}'
184 #define S_QUOTE '\''
185
186 static void
187 write_it(ENTRY * ep)
188 {
189     unsigned n;
190     int ch;
191     char *s, *d, *t;
192     char result[MAX_ENTRY_SIZE];
193
194     /*
195      * Look for strings that contain %{number}, convert them to %'char',
196      * which is shorter and runs a little faster.
197      */
198     for (n = 0; n < STRCOUNT; n++) {
199         s = ep->tterm.Strings[n];
200         if (VALID_STRING(s)
201             && strchr(s, L_BRACE) != 0) {
202             d = result;
203             t = s;
204             while ((ch = *t++) != 0) {
205                 *d++ = (char) ch;
206                 if (ch == '\\') {
207                     *d++ = *t++;
208                 } else if ((ch == '%')
209                            && (*t == L_BRACE)) {
210                     char *v = 0;
211                     long value = strtol(t + 1, &v, 0);
212                     if (v != 0
213                         && *v == R_BRACE
214                         && value > 0
215                         && value != '\\'        /* FIXME */
216                         && value < 127
217                         && isprint((int) value)) {
218                         *d++ = S_QUOTE;
219                         *d++ = (char) value;
220                         *d++ = S_QUOTE;
221                         t = (v + 1);
222                     }
223                 }
224             }
225             *d = 0;
226             if (strlen(result) < strlen(s))
227                 _nc_STRCPY(s, result, strlen(s) + 1);
228         }
229     }
230
231     _nc_set_type(_nc_first_name(ep->tterm.term_names));
232     _nc_curr_line = (int) ep->startline;
233     _nc_write_entry(&ep->tterm);
234 }
235
236 static bool
237 immedhook(ENTRY * ep GCC_UNUSED)
238 /* write out entries with no use capabilities immediately to save storage */
239 {
240 #if !HAVE_BIG_CORE
241     /*
242      * This is strictly a core-economy kluge.  The really clean way to handle
243      * compilation is to slurp the whole file into core and then do all the
244      * name-collision checks and entry writes in one swell foop.  But the
245      * terminfo master file is large enough that some core-poor systems swap
246      * like crazy when you compile it this way...there have been reports of
247      * this process taking *three hours*, rather than the twenty seconds or
248      * less typical on my development box.
249      *
250      * So.  This hook *immediately* writes out the referenced entry if it
251      * has no use capabilities.  The compiler main loop refrains from
252      * adding the entry to the in-core list when this hook fires.  If some
253      * other entry later needs to reference an entry that got written
254      * immediately, that's OK; the resolution code will fetch it off disk
255      * when it can't find it in core.
256      *
257      * Name collisions will still be detected, just not as cleanly.  The
258      * write_entry() code complains before overwriting an entry that
259      * postdates the time of tic's first call to write_entry().  Thus
260      * it will complain about overwriting entries newly made during the
261      * tic run, but not about overwriting ones that predate it.
262      *
263      * The reason this is a hook, and not in line with the rest of the
264      * compiler code, is that the support for termcap fallback cannot assume
265      * it has anywhere to spool out these entries!
266      *
267      * The _nc_set_type() call here requires a compensating one in
268      * _nc_parse_entry().
269      *
270      * If you define HAVE_BIG_CORE, you'll disable this kluge.  This will
271      * make tic a bit faster (because the resolution code won't have to do
272      * disk I/O nearly as often).
273      */
274     if (ep->nuses == 0) {
275         int oldline = _nc_curr_line;
276
277         write_it(ep);
278         _nc_curr_line = oldline;
279         free(ep->tterm.str_table);
280         return (TRUE);
281     }
282 #endif /* HAVE_BIG_CORE */
283     return (FALSE);
284 }
285
286 static void
287 put_translate(int c)
288 /* emit a comment char, translating terminfo names to termcap names */
289 {
290     static bool in_name = FALSE;
291     static size_t have, used;
292     static char *namebuf, *suffix;
293
294     if (in_name) {
295         if (used + 1 >= have) {
296             have += 132;
297             namebuf = typeRealloc(char, have, namebuf);
298             suffix = typeRealloc(char, have, suffix);
299         }
300         if (c == '\n' || c == '@') {
301             namebuf[used++] = '\0';
302             (void) putchar('<');
303             (void) fputs(namebuf, stdout);
304             putchar(c);
305             in_name = FALSE;
306         } else if (c != '>') {
307             namebuf[used++] = (char) c;
308         } else {                /* ah! candidate name! */
309             char *up;
310             NCURSES_CONST char *tp;
311
312             namebuf[used++] = '\0';
313             in_name = FALSE;
314
315             suffix[0] = '\0';
316             if ((up = strchr(namebuf, '#')) != 0
317                 || (up = strchr(namebuf, '=')) != 0
318                 || ((up = strchr(namebuf, '@')) != 0 && up[1] == '>')) {
319                 _nc_STRCPY(suffix, up, have);
320                 *up = '\0';
321             }
322
323             if ((tp = nametrans(namebuf)) != 0) {
324                 (void) putchar(':');
325                 (void) fputs(tp, stdout);
326                 (void) fputs(suffix, stdout);
327                 (void) putchar(':');
328             } else {
329                 /* couldn't find a translation, just dump the name */
330                 (void) putchar('<');
331                 (void) fputs(namebuf, stdout);
332                 (void) fputs(suffix, stdout);
333                 (void) putchar('>');
334             }
335         }
336     } else {
337         used = 0;
338         if (c == '<') {
339             in_name = TRUE;
340         } else {
341             putchar(c);
342         }
343     }
344 }
345
346 /* Returns a string, stripped of leading/trailing whitespace */
347 static char *
348 stripped(char *src)
349 {
350     char *dst = 0;
351
352     while (isspace(UChar(*src)))
353         src++;
354
355     if (*src != '\0') {
356         size_t len;
357
358         if ((dst = strdup(src)) == NULL) {
359             failed("strdup");
360         } else {
361             len = strlen(dst);
362             while (--len != 0 && isspace(UChar(dst[len])))
363                 dst[len] = '\0';
364         }
365     }
366     return dst;
367 }
368
369 static FILE *
370 open_tempfile(char *filename)
371 {
372     FILE *result = 0;
373
374     _nc_STRCPY(filename, "/tmp/XXXXXX", PATH_MAX);
375 #if HAVE_MKSTEMP
376     {
377         int fd = mkstemp(filename);
378         if (fd >= 0)
379             result = fdopen(fd, "w");
380     }
381 #else
382     if (tmpnam(filename) != 0)
383         result = fopen(filename, "w");
384 #endif
385     return result;
386 }
387
388 static FILE *
389 copy_input(FILE *source, const char *filename, char *alt_file)
390 {
391     FILE *result = 0;
392     FILE *target = open_tempfile(alt_file);
393     int ch;
394
395     if (source == 0) {
396         failed("copy_input (source)");
397     } else if (target == 0) {
398         failed("copy_input (target)");
399     } else {
400         clearerr(source);
401         for (;;) {
402             ch = fgetc(source);
403             if (feof(source)) {
404                 break;
405             } else if (ferror(source)) {
406                 failed(filename);
407             } else if (ch == 0) {
408                 /* don't loop in case someone wants to convert /dev/zero */
409                 fprintf(stderr, "%s: %s is not a text-file\n", _nc_progname, filename);
410                 ExitProgram(EXIT_FAILURE);
411             }
412             fputc(ch, target);
413         }
414         fclose(source);
415         /*
416          * rewind() does not force the target file's data to disk (not does
417          * fflush()...).  So open a second stream on the data and then close
418          * the one that we were writing on before starting to read from the
419          * second stream.
420          */
421         result = fopen(alt_file, "r+");
422         fclose(target);
423         to_remove = alt_file;
424     }
425     return result;
426 }
427
428 static FILE *
429 open_input(const char *filename, char *alt_file)
430 {
431     FILE *fp;
432     struct stat sb;
433     int mode;
434
435     if (!strcmp(filename, "-")) {
436         fp = copy_input(stdin, STDIN_NAME, alt_file);
437     } else if (stat(filename, &sb) < 0) {
438         fprintf(stderr, "%s: %s %s\n", _nc_progname, filename, strerror(errno));
439         ExitProgram(EXIT_FAILURE);
440     } else if ((mode = (sb.st_mode & S_IFMT)) == S_IFDIR
441                || (mode != S_IFREG && mode != S_IFCHR)) {
442         fprintf(stderr, "%s: %s is not a file\n", _nc_progname, filename);
443         ExitProgram(EXIT_FAILURE);
444     } else {
445         fp = fopen(filename, "r");
446
447         if (fp == 0) {
448             fprintf(stderr, "%s: Can't open %s\n", _nc_progname, filename);
449             ExitProgram(EXIT_FAILURE);
450         }
451         if (mode != S_IFREG) {
452             if (alt_file != 0) {
453                 FILE *fp2 = copy_input(fp, filename, alt_file);
454                 fp = fp2;
455             } else {
456                 fprintf(stderr, "%s: %s is not a file\n", _nc_progname, filename);
457                 ExitProgram(EXIT_FAILURE);
458             }
459         }
460     }
461     return fp;
462 }
463
464 /* Parse the "-e" option-value into a list of names */
465 static char **
466 make_namelist(char *src)
467 {
468     char **dst = 0;
469
470     char *s, *base;
471     unsigned pass, n, nn;
472     char buffer[BUFSIZ];
473
474     if (src == 0) {
475         /* EMPTY */ ;
476     } else if (strchr(src, '/') != 0) {         /* a filename */
477         FILE *fp = open_input(src, (char *) 0);
478
479         for (pass = 1; pass <= 2; pass++) {
480             nn = 0;
481             while (fgets(buffer, sizeof(buffer), fp) != 0) {
482                 if ((s = stripped(buffer)) != 0) {
483                     if (dst != 0)
484                         dst[nn] = s;
485                     else
486                         free(s);
487                     nn++;
488                 }
489             }
490             if (pass == 1) {
491                 dst = typeCalloc(char *, nn + 1);
492                 rewind(fp);
493             }
494         }
495         fclose(fp);
496     } else {                    /* literal list of names */
497         for (pass = 1; pass <= 2; pass++) {
498             for (n = nn = 0, base = src;; n++) {
499                 int mark = src[n];
500                 if (mark == ',' || mark == '\0') {
501                     if (pass == 1) {
502                         nn++;
503                     } else {
504                         src[n] = '\0';
505                         if ((s = stripped(base)) != 0)
506                             dst[nn++] = s;
507                         base = &src[n + 1];
508                     }
509                 }
510                 if (mark == '\0')
511                     break;
512             }
513             if (pass == 1)
514                 dst = typeCalloc(char *, nn + 1);
515         }
516     }
517     if (showsummary && (dst != 0)) {
518         fprintf(log_fp, "Entries that will be compiled:\n");
519         for (n = 0; dst[n] != 0; n++)
520             fprintf(log_fp, "%u:%s\n", n + 1, dst[n]);
521     }
522     return dst;
523 }
524
525 static bool
526 matches(char **needle, const char *haystack)
527 /* does entry in needle list match |-separated field in haystack? */
528 {
529     bool code = FALSE;
530     size_t n;
531
532     if (needle != 0) {
533         for (n = 0; needle[n] != 0; n++) {
534             if (_nc_name_match(haystack, needle[n], "|")) {
535                 code = TRUE;
536                 break;
537             }
538         }
539     } else
540         code = TRUE;
541     return (code);
542 }
543
544 static const char *
545 valid_db_path(const char *nominal)
546 {
547     struct stat sb;
548 #if USE_HASHED_DB
549     char suffix[] = DBM_SUFFIX;
550     size_t need = strlen(nominal) + sizeof(suffix);
551     char *result = malloc(need);
552
553     _nc_STRCPY(result, nominal, need);
554     if (strcmp(result + need - sizeof(suffix), suffix)) {
555         _nc_STRCAT(result, suffix, need);
556     }
557 #else
558     char *result = strdup(nominal);
559 #endif
560
561     DEBUG(1, ("** stat(%s)", result));
562     if (stat(result, &sb) >= 0) {
563 #if USE_HASHED_DB
564         if (!S_ISREG(sb.st_mode)
565             || access(result, R_OK | W_OK) != 0) {
566             DEBUG(1, ("...not a writable file"));
567             free(result);
568             result = 0;
569         }
570 #else
571         if (!S_ISDIR(sb.st_mode)
572             || access(result, R_OK | W_OK | X_OK) != 0) {
573             DEBUG(1, ("...not a writable directory"));
574             free(result);
575             result = 0;
576         }
577 #endif
578     } else {
579         /* check if parent is directory and is writable */
580         unsigned leaf = _nc_pathlast(result);
581
582         DEBUG(1, ("...not found"));
583         if (leaf) {
584             char save = result[leaf];
585             result[leaf] = 0;
586             if (stat(result, &sb) >= 0
587                 && S_ISDIR(sb.st_mode)
588                 && access(result, R_OK | W_OK | X_OK) == 0) {
589                 result[leaf] = save;
590             } else {
591                 DEBUG(1, ("...parent directory %s is not writable", result));
592                 free(result);
593                 result = 0;
594             }
595         } else {
596             DEBUG(1, ("... no parent directory"));
597             free(result);
598             result = 0;
599         }
600     }
601     return result;
602 }
603
604 /*
605  * Show the databases to which tic could write.  The location to which it
606  * writes is always the first one.  If none are writable, print an error
607  * message.
608  */
609 static void
610 show_databases(const char *outdir)
611 {
612     bool specific = (outdir != 0) || getenv("TERMINFO") != 0;
613     const char *result;
614     const char *tried = 0;
615
616     if (outdir == 0) {
617         outdir = _nc_tic_dir(0);
618     }
619     if ((result = valid_db_path(outdir)) != 0) {
620         printf("%s\n", result);
621     } else {
622         tried = outdir;
623     }
624
625     if ((outdir = _nc_home_terminfo())) {
626         if ((result = valid_db_path(outdir)) != 0) {
627             printf("%s\n", result);
628         } else if (!specific) {
629             tried = outdir;
630         }
631     }
632
633     /*
634      * If we can write in neither location, give an error message.
635      */
636     if (tried) {
637         fflush(stdout);
638         fprintf(stderr, "%s: %s (no permission)\n", _nc_progname, tried);
639         ExitProgram(EXIT_FAILURE);
640     }
641 }
642
643 #define VtoTrace(opt) (unsigned) ((opt > 0) ? opt : (opt == 0))
644
645 int
646 main(int argc, char *argv[])
647 {
648     char my_tmpname[PATH_MAX];
649     char my_altfile[PATH_MAX];
650     int v_opt = -1;
651     unsigned debug_level;
652     int smart_defaults = TRUE;
653     char *termcap;
654     ENTRY *qp;
655
656     int this_opt, last_opt = '?';
657
658     int outform = F_TERMINFO;   /* output format */
659     int sortmode = S_TERMINFO;  /* sort_mode */
660
661     int width = 60;
662     int height = 65535;
663     bool formatted = FALSE;     /* reformat complex strings? */
664     bool literal = FALSE;       /* suppress post-processing? */
665     int numbers = 0;            /* format "%'char'" to/from "%{number}" */
666     bool forceresolve = FALSE;  /* force resolution */
667     bool limited = TRUE;
668     char *tversion = (char *) NULL;
669     const char *source_file = "terminfo";
670     char **namelst = 0;
671     char *outdir = (char *) NULL;
672     bool check_only = FALSE;
673     bool suppress_untranslatable = FALSE;
674
675     log_fp = stderr;
676
677     _nc_progname = _nc_rootname(argv[0]);
678
679     if ((infodump = same_program(_nc_progname, PROG_CAPTOINFO)) != FALSE) {
680         outform = F_TERMINFO;
681         sortmode = S_TERMINFO;
682     }
683     if ((capdump = same_program(_nc_progname, PROG_INFOTOCAP)) != FALSE) {
684         outform = F_TERMCAP;
685         sortmode = S_TERMCAP;
686     }
687 #if NCURSES_XNAMES
688     use_extended_names(FALSE);
689 #endif
690     _nc_strict_bsd = 0;
691
692     /*
693      * Processing arguments is a little complicated, since someone made a
694      * design decision to allow the numeric values for -w, -v options to
695      * be optional.
696      */
697     while ((this_opt = getopt(argc, argv,
698                               "0123456789CDIKLNR:TUVace:fGgo:rstvwx")) != -1) {
699         if (isdigit(this_opt)) {
700             switch (last_opt) {
701             case 'v':
702                 v_opt = (v_opt * 10) + (this_opt - '0');
703                 break;
704             case 'w':
705                 width = (width * 10) + (this_opt - '0');
706                 break;
707             default:
708                 switch (this_opt) {
709                 case '0':
710                     last_opt = this_opt;
711                     width = 65535;
712                     height = 1;
713                     break;
714                 case '1':
715                     last_opt = this_opt;
716                     width = 0;
717                     break;
718                 default:
719                     usage();
720                 }
721             }
722             continue;
723         }
724         switch (this_opt) {
725         case 'K':
726             _nc_strict_bsd = 1;
727             /* the initial version of -K in 20110730 fell-thru here, but the
728              * same flag is useful when reading sources -TD
729              */
730             break;
731         case 'C':
732             capdump = TRUE;
733             outform = F_TERMCAP;
734             sortmode = S_TERMCAP;
735             break;
736         case 'D':
737             debug_level = VtoTrace(v_opt);
738             set_trace_level(debug_level);
739             show_databases(outdir);
740             ExitProgram(EXIT_SUCCESS);
741             break;
742         case 'I':
743             infodump = TRUE;
744             outform = F_TERMINFO;
745             sortmode = S_TERMINFO;
746             break;
747         case 'L':
748             infodump = TRUE;
749             outform = F_VARIABLE;
750             sortmode = S_VARIABLE;
751             break;
752         case 'N':
753             smart_defaults = FALSE;
754             literal = TRUE;
755             break;
756         case 'R':
757             tversion = optarg;
758             break;
759         case 'T':
760             limited = FALSE;
761             break;
762         case 'U':
763             literal = TRUE;
764             break;
765         case 'V':
766             puts(curses_version());
767             cleanup(namelst);
768             ExitProgram(EXIT_SUCCESS);
769         case 'c':
770             check_only = TRUE;
771             break;
772         case 'e':
773             namelst = make_namelist(optarg);
774             break;
775         case 'f':
776             formatted = TRUE;
777             break;
778         case 'G':
779             numbers = 1;
780             break;
781         case 'g':
782             numbers = -1;
783             break;
784         case 'o':
785             outdir = optarg;
786             break;
787         case 'r':
788             forceresolve = TRUE;
789             break;
790         case 's':
791             showsummary = TRUE;
792             break;
793         case 'v':
794             v_opt = 0;
795             break;
796         case 'w':
797             width = 0;
798             break;
799 #if NCURSES_XNAMES
800         case 't':
801             _nc_disable_period = FALSE;
802             suppress_untranslatable = TRUE;
803             break;
804         case 'a':
805             _nc_disable_period = TRUE;
806             /* FALLTHRU */
807         case 'x':
808             use_extended_names(TRUE);
809             break;
810 #endif
811         default:
812             usage();
813         }
814         last_opt = this_opt;
815     }
816
817     debug_level = VtoTrace(v_opt);
818     set_trace_level(debug_level);
819
820     if (_nc_tracing) {
821         save_check_termtype = _nc_check_termtype2;
822         _nc_check_termtype2 = check_termtype;
823     }
824 #if !HAVE_BIG_CORE
825     /*
826      * Aaargh! immedhook seriously hoses us!
827      *
828      * One problem with immedhook is it means we can't do -e.  Problem
829      * is that we can't guarantee that for each terminal listed, all the
830      * terminals it depends on will have been kept in core for reference
831      * resolution -- in fact it's certain the primitive types at the end
832      * of reference chains *won't* be in core unless they were explicitly
833      * in the select list themselves.
834      */
835     if (namelst && (!infodump && !capdump)) {
836         (void) fprintf(stderr,
837                        "%s: Sorry, -e can't be used without -I or -C\n",
838                        _nc_progname);
839         cleanup(namelst);
840         ExitProgram(EXIT_FAILURE);
841     }
842 #endif /* HAVE_BIG_CORE */
843
844     if (optind < argc) {
845         source_file = argv[optind++];
846         if (optind < argc) {
847             fprintf(stderr,
848                     "%s: Too many file names.  Usage:\n\t%s %s",
849                     _nc_progname,
850                     _nc_progname,
851                     usage_string);
852             ExitProgram(EXIT_FAILURE);
853         }
854     } else {
855         if (infodump == TRUE) {
856             /* captoinfo's no-argument case */
857             source_file = "/etc/termcap";
858             if ((termcap = getenv("TERMCAP")) != 0
859                 && (namelst = make_namelist(getenv("TERM"))) != 0) {
860                 if (access(termcap, F_OK) == 0) {
861                     /* file exists */
862                     source_file = termcap;
863                 } else {
864                     if ((tmp_fp = open_tempfile(my_tmpname)) != 0) {
865                         source_file = my_tmpname;
866                         fprintf(tmp_fp, "%s\n", termcap);
867                         fclose(tmp_fp);
868                         tmp_fp = open_input(source_file, (char *) 0);
869                         to_remove = source_file;
870                     } else {
871                         failed("tmpnam");
872                     }
873                 }
874             }
875         } else {
876             /* tic */
877             fprintf(stderr,
878                     "%s: File name needed.  Usage:\n\t%s %s",
879                     _nc_progname,
880                     _nc_progname,
881                     usage_string);
882             cleanup(namelst);
883             ExitProgram(EXIT_FAILURE);
884         }
885     }
886
887     if (tmp_fp == 0) {
888         tmp_fp = open_input(source_file, my_altfile);
889         if (!strcmp(source_file, "-")) {
890             source_file = STDIN_NAME;
891         }
892     }
893
894     if (infodump) {
895         dump_init(tversion,
896                   smart_defaults
897                   ? outform
898                   : F_LITERAL,
899                   sortmode, width, height, debug_level, formatted);
900     } else if (capdump) {
901         dump_init(tversion,
902                   outform,
903                   sortmode, width, height, debug_level, FALSE);
904     }
905
906     /* parse entries out of the source file */
907     _nc_set_source(source_file);
908 #if !HAVE_BIG_CORE
909     if (!(check_only || infodump || capdump))
910         _nc_set_writedir(outdir);
911 #endif /* HAVE_BIG_CORE */
912     _nc_read_entry_source(tmp_fp, (char *) NULL,
913                           !smart_defaults || literal, FALSE,
914                           ((check_only || infodump || capdump)
915                            ? NULLHOOK
916                            : immedhook));
917
918     /* do use resolution */
919     if (check_only || (!infodump && !capdump) || forceresolve) {
920         if (!_nc_resolve_uses2(TRUE, literal) && !check_only) {
921             cleanup(namelst);
922             ExitProgram(EXIT_FAILURE);
923         }
924     }
925
926     /* length check */
927     if (check_only && (capdump || infodump)) {
928         for_entry_list(qp) {
929             if (matches(namelst, qp->tterm.term_names)) {
930                 int len = fmt_entry(&qp->tterm, NULL, FALSE, TRUE, infodump, numbers);
931
932                 if (len > (infodump ? MAX_TERMINFO_LENGTH : MAX_TERMCAP_LENGTH))
933                     (void) fprintf(stderr,
934                                    "warning: resolved %s entry is %d bytes long\n",
935                                    _nc_first_name(qp->tterm.term_names),
936                                    len);
937             }
938         }
939     }
940
941     /* write or dump all entries */
942     if (!check_only) {
943         if (!infodump && !capdump) {
944             _nc_set_writedir(outdir);
945             for_entry_list(qp) {
946                 if (matches(namelst, qp->tterm.term_names))
947                     write_it(qp);
948             }
949         } else {
950             /* this is in case infotocap() generates warnings */
951             _nc_curr_col = _nc_curr_line = -1;
952
953             for_entry_list(qp) {
954                 if (matches(namelst, qp->tterm.term_names)) {
955                     long j = qp->cend - qp->cstart;
956                     int len = 0;
957
958                     /* this is in case infotocap() generates warnings */
959                     _nc_set_type(_nc_first_name(qp->tterm.term_names));
960
961                     (void) fseek(tmp_fp, qp->cstart, SEEK_SET);
962                     while (j-- > 0) {
963                         if (infodump)
964                             (void) putchar(fgetc(tmp_fp));
965                         else
966                             put_translate(fgetc(tmp_fp));
967                     }
968
969                     repair_acsc(&qp->tterm);
970                     dump_entry(&qp->tterm, suppress_untranslatable,
971                                limited, numbers, NULL);
972                     for (j = 0; j < (long) qp->nuses; j++)
973                         dump_uses(qp->uses[j].name, !capdump);
974                     len = show_entry();
975                     if (debug_level != 0 && !limited)
976                         printf("# length=%d\n", len);
977                 }
978             }
979             if (!namelst && _nc_tail) {
980                 int c, oldc = '\0';
981                 bool in_comment = FALSE;
982                 bool trailing_comment = FALSE;
983
984                 (void) fseek(tmp_fp, _nc_tail->cend, SEEK_SET);
985                 while ((c = fgetc(tmp_fp)) != EOF) {
986                     if (oldc == '\n') {
987                         if (c == '#') {
988                             trailing_comment = TRUE;
989                             in_comment = TRUE;
990                         } else {
991                             in_comment = FALSE;
992                         }
993                     }
994                     if (trailing_comment
995                         && (in_comment || (oldc == '\n' && c == '\n')))
996                         putchar(c);
997                     oldc = c;
998                 }
999             }
1000         }
1001     }
1002
1003     /* Show the directory into which entries were written, and the total
1004      * number of entries
1005      */
1006     if (showsummary
1007         && (!(check_only || infodump || capdump))) {
1008         int total = _nc_tic_written();
1009         if (total != 0)
1010             fprintf(log_fp, "%d entries written to %s\n",
1011                     total,
1012                     _nc_tic_dir((char *) 0));
1013         else
1014             fprintf(log_fp, "No entries written\n");
1015     }
1016     cleanup(namelst);
1017     ExitProgram(EXIT_SUCCESS);
1018 }
1019
1020 /*
1021  * This bit of legerdemain turns all the terminfo variable names into
1022  * references to locations in the arrays Booleans, Numbers, and Strings ---
1023  * precisely what's needed (see comp_parse.c).
1024  */
1025 #undef CUR
1026 #define CUR tp->
1027
1028 /*
1029  * Check if the alternate character-set capabilities are consistent.
1030  */
1031 static void
1032 check_acs(TERMTYPE *tp)
1033 {
1034     if (VALID_STRING(acs_chars)) {
1035         const char *boxes = "lmkjtuvwqxn";
1036         char mapped[256];
1037         char missing[256];
1038         const char *p;
1039         char *q;
1040
1041         memset(mapped, 0, sizeof(mapped));
1042         for (p = acs_chars; *p != '\0'; p += 2) {
1043             if (p[1] == '\0') {
1044                 _nc_warning("acsc has odd number of characters");
1045                 break;
1046             }
1047             mapped[UChar(p[0])] = p[1];
1048         }
1049
1050         if (mapped[UChar('I')] && !mapped[UChar('i')]) {
1051             _nc_warning("acsc refers to 'I', which is probably an error");
1052         }
1053
1054         for (p = boxes, q = missing; *p != '\0'; ++p) {
1055             if (!mapped[UChar(p[0])]) {
1056                 *q++ = p[0];
1057             }
1058         }
1059         *q = '\0';
1060
1061         assert(strlen(missing) <= strlen(boxes));
1062         if (*missing != '\0' && strcmp(missing, boxes)) {
1063             _nc_warning("acsc is missing some line-drawing mapping: %s", missing);
1064         }
1065     }
1066 }
1067
1068 /*
1069  * Check if the color capabilities are consistent
1070  */
1071 static void
1072 check_colors(TERMTYPE *tp)
1073 {
1074     if ((max_colors > 0) != (max_pairs > 0)
1075         || ((max_colors > max_pairs) && (initialize_pair == 0)))
1076         _nc_warning("inconsistent values for max_colors (%d) and max_pairs (%d)",
1077                     max_colors, max_pairs);
1078
1079     PAIRED(set_foreground, set_background);
1080     PAIRED(set_a_foreground, set_a_background);
1081     PAIRED(set_color_pair, initialize_pair);
1082
1083     if (VALID_STRING(set_foreground)
1084         && VALID_STRING(set_a_foreground)
1085         && !_nc_capcmp(set_foreground, set_a_foreground))
1086         _nc_warning("expected setf/setaf to be different");
1087
1088     if (VALID_STRING(set_background)
1089         && VALID_STRING(set_a_background)
1090         && !_nc_capcmp(set_background, set_a_background))
1091         _nc_warning("expected setb/setab to be different");
1092
1093     /* see: has_colors() */
1094     if (VALID_NUMERIC(max_colors) && VALID_NUMERIC(max_pairs)
1095         && (((set_foreground != NULL)
1096              && (set_background != NULL))
1097             || ((set_a_foreground != NULL)
1098                 && (set_a_background != NULL))
1099             || set_color_pair)) {
1100         if (!VALID_STRING(orig_pair) && !VALID_STRING(orig_colors))
1101             _nc_warning("expected either op/oc string for resetting colors");
1102     }
1103 }
1104
1105 static char
1106 keypad_final(const char *string)
1107 {
1108     char result = '\0';
1109
1110     if (VALID_STRING(string)
1111         && *string++ == '\033'
1112         && *string++ == 'O'
1113         && strlen(string) == 1) {
1114         result = *string;
1115     }
1116
1117     return result;
1118 }
1119
1120 static long
1121 keypad_index(const char *string)
1122 {
1123     char *test;
1124     const char *list = "PQRSwxymtuvlqrsPpn";    /* app-keypad except "Enter" */
1125     int ch;
1126     long result = -1;
1127
1128     if ((ch = keypad_final(string)) != '\0') {
1129         test = strchr(list, ch);
1130         if (test != 0)
1131             result = (long) (test - list);
1132     }
1133     return result;
1134 }
1135
1136 /*
1137  * list[] is down, up, left, right
1138  * "left" may be ^H rather than \E[D
1139  * "down" may be ^J rather than \E[B
1140  * But up/right are generally consistently escape sequences for ANSI terminals.
1141  */
1142 static void
1143 check_ansi_cursor(char *list[4])
1144 {
1145     int j, k;
1146     int want;
1147     size_t prefix = 0;
1148     size_t suffix;
1149     bool skip[4];
1150     bool repeated = FALSE;
1151
1152     for (j = 0; j < 4; ++j) {
1153         skip[j] = FALSE;
1154         for (k = 0; k < j; ++k) {
1155             if (j != k
1156                 && !strcmp(list[j], list[k])) {
1157                 char *value = _nc_tic_expand(list[k], TRUE, 0);
1158                 _nc_warning("repeated cursor control %s\n", value);
1159                 repeated = TRUE;
1160             }
1161         }
1162     }
1163     if (!repeated) {
1164         char *up = list[1];
1165
1166         if (UChar(up[0]) == '\033') {
1167             if (up[1] == '[') {
1168                 prefix = 2;
1169             } else {
1170                 prefix = 1;
1171             }
1172         } else if (UChar(up[0]) == UChar('\233')) {
1173             prefix = 1;
1174         }
1175         if (prefix) {
1176             suffix = prefix;
1177             while (up[suffix] && isdigit(UChar(up[suffix])))
1178                 ++suffix;
1179         }
1180         if (prefix && up[suffix] == 'A') {
1181             skip[1] = TRUE;
1182             if (!strcmp(list[0], "\n"))
1183                 skip[0] = TRUE;
1184             if (!strcmp(list[2], "\b"))
1185                 skip[2] = TRUE;
1186
1187             for (j = 0; j < 4; ++j) {
1188                 if (skip[j] || strlen(list[j]) == 1)
1189                     continue;
1190                 if (memcmp(list[j], up, prefix)) {
1191                     char *value = _nc_tic_expand(list[j], TRUE, 0);
1192                     _nc_warning("inconsistent prefix for %s\n", value);
1193                     continue;
1194                 }
1195                 if (strlen(list[j]) < suffix) {
1196                     char *value = _nc_tic_expand(list[j], TRUE, 0);
1197                     _nc_warning("inconsistent length for %s, expected %d\n",
1198                                 value, (int) suffix + 1);
1199                     continue;
1200                 }
1201                 want = "BADC"[j];
1202                 if (list[j][suffix] != want) {
1203                     char *value = _nc_tic_expand(list[j], TRUE, 0);
1204                     _nc_warning("inconsistent suffix for %s, expected %c, have %c\n",
1205                                 value, want, list[j][suffix]);
1206                 }
1207             }
1208         }
1209     }
1210 }
1211
1212 #define EXPECTED(name) if (!PRESENT(name)) _nc_warning("expected " #name)
1213
1214 static void
1215 check_cursor(TERMTYPE *tp)
1216 {
1217     int count;
1218     char *list[4];
1219
1220     /* if we have a parameterized form, then the non-parameterized is easy */
1221     ANDMISSING(parm_down_cursor, cursor_down);
1222     ANDMISSING(parm_up_cursor, cursor_up);
1223     ANDMISSING(parm_left_cursor, cursor_left);
1224     ANDMISSING(parm_right_cursor, cursor_right);
1225
1226     /* Given any of a set of cursor movement, the whole set should be present. 
1227      * Technically this is not true (we could use cursor_address to fill in
1228      * unsupported controls), but it is likely.
1229      */
1230     count = 0;
1231     if (PRESENT(parm_down_cursor)) {
1232         list[count++] = parm_down_cursor;
1233     }
1234     if (PRESENT(parm_up_cursor)) {
1235         list[count++] = parm_up_cursor;
1236     }
1237     if (PRESENT(parm_left_cursor)) {
1238         list[count++] = parm_left_cursor;
1239     }
1240     if (PRESENT(parm_right_cursor)) {
1241         list[count++] = parm_right_cursor;
1242     }
1243     if (count == 4) {
1244         check_ansi_cursor(list);
1245     } else if (count != 0) {
1246         EXPECTED(parm_down_cursor);
1247         EXPECTED(parm_up_cursor);
1248         EXPECTED(parm_left_cursor);
1249         EXPECTED(parm_right_cursor);
1250     }
1251
1252     count = 0;
1253     if (PRESENT(cursor_down)) {
1254         list[count++] = cursor_down;
1255     }
1256     if (PRESENT(cursor_up)) {
1257         list[count++] = cursor_up;
1258     }
1259     if (PRESENT(cursor_left)) {
1260         list[count++] = cursor_left;
1261     }
1262     if (PRESENT(cursor_right)) {
1263         list[count++] = cursor_right;
1264     }
1265     if (count == 4) {
1266         check_ansi_cursor(list);
1267     } else if (count != 0) {
1268         count = 0;
1269         if (PRESENT(cursor_down) && strcmp(cursor_down, "\n"))
1270             ++count;
1271         if (PRESENT(cursor_left) && strcmp(cursor_left, "\b"))
1272             ++count;
1273         if (PRESENT(cursor_up) && strlen(cursor_up) > 1)
1274             ++count;
1275         if (PRESENT(cursor_right) && strlen(cursor_right) > 1)
1276             ++count;
1277         if (count) {
1278             EXPECTED(cursor_down);
1279             EXPECTED(cursor_up);
1280             EXPECTED(cursor_left);
1281             EXPECTED(cursor_right);
1282         }
1283     }
1284 }
1285
1286 #define MAX_KP 5
1287 /*
1288  * Do a quick sanity-check for vt100-style keypads to see if the 5-key keypad
1289  * is mapped inconsistently.
1290  */
1291 static void
1292 check_keypad(TERMTYPE *tp)
1293 {
1294     char show[80];
1295
1296     if (VALID_STRING(key_a1) &&
1297         VALID_STRING(key_a3) &&
1298         VALID_STRING(key_b2) &&
1299         VALID_STRING(key_c1) &&
1300         VALID_STRING(key_c3)) {
1301         char final[MAX_KP + 1];
1302         long list[MAX_KP];
1303         int increase = 0;
1304         int j, k, kk;
1305         long last;
1306         long test;
1307
1308         final[0] = keypad_final(key_a1);
1309         final[1] = keypad_final(key_a3);
1310         final[2] = keypad_final(key_b2);
1311         final[3] = keypad_final(key_c1);
1312         final[4] = keypad_final(key_c3);
1313         final[5] = '\0';
1314
1315         /* special case: legacy coding using 1,2,3,0,. on the bottom */
1316         assert(strlen(final) <= MAX_KP);
1317         if (!strcmp(final, "qsrpn"))
1318             return;
1319
1320         list[0] = keypad_index(key_a1);
1321         list[1] = keypad_index(key_a3);
1322         list[2] = keypad_index(key_b2);
1323         list[3] = keypad_index(key_c1);
1324         list[4] = keypad_index(key_c3);
1325
1326         /* check that they're all vt100 keys */
1327         for (j = 0; j < MAX_KP; ++j) {
1328             if (list[j] < 0) {
1329                 return;
1330             }
1331         }
1332
1333         /* check if they're all in increasing order */
1334         for (j = 1; j < MAX_KP; ++j) {
1335             if (list[j] > list[j - 1]) {
1336                 ++increase;
1337             }
1338         }
1339         if (increase != (MAX_KP - 1)) {
1340             show[0] = '\0';
1341
1342             for (j = 0, last = -1; j < MAX_KP; ++j) {
1343                 for (k = 0, kk = -1, test = 100; k < 5; ++k) {
1344                     if (list[k] > last &&
1345                         list[k] < test) {
1346                         test = list[k];
1347                         kk = k;
1348                     }
1349                 }
1350                 last = test;
1351                 assert(strlen(show) < (MAX_KP * 4));
1352                 switch (kk) {
1353                 case 0:
1354                     _nc_STRCAT(show, " ka1", sizeof(show));
1355                     break;
1356                 case 1:
1357                     _nc_STRCAT(show, " ka3", sizeof(show));
1358                     break;
1359                 case 2:
1360                     _nc_STRCAT(show, " kb2", sizeof(show));
1361                     break;
1362                 case 3:
1363                     _nc_STRCAT(show, " kc1", sizeof(show));
1364                     break;
1365                 case 4:
1366                     _nc_STRCAT(show, " kc3", sizeof(show));
1367                     break;
1368                 }
1369             }
1370
1371             _nc_warning("vt100 keypad order inconsistent: %s", show);
1372         }
1373
1374     } else if (VALID_STRING(key_a1) ||
1375                VALID_STRING(key_a3) ||
1376                VALID_STRING(key_b2) ||
1377                VALID_STRING(key_c1) ||
1378                VALID_STRING(key_c3)) {
1379         show[0] = '\0';
1380         if (keypad_index(key_a1) >= 0)
1381             _nc_STRCAT(show, " ka1", sizeof(show));
1382         if (keypad_index(key_a3) >= 0)
1383             _nc_STRCAT(show, " ka3", sizeof(show));
1384         if (keypad_index(key_b2) >= 0)
1385             _nc_STRCAT(show, " kb2", sizeof(show));
1386         if (keypad_index(key_c1) >= 0)
1387             _nc_STRCAT(show, " kc1", sizeof(show));
1388         if (keypad_index(key_c3) >= 0)
1389             _nc_STRCAT(show, " kc3", sizeof(show));
1390         if (*show != '\0')
1391             _nc_warning("vt100 keypad map incomplete:%s", show);
1392     }
1393 }
1394
1395 static void
1396 check_printer(TERMTYPE *tp)
1397 {
1398     PAIRED(enter_doublewide_mode, exit_doublewide_mode);
1399     PAIRED(enter_italics_mode, exit_italics_mode);
1400     PAIRED(enter_leftward_mode, exit_leftward_mode);
1401     PAIRED(enter_micro_mode, exit_micro_mode);
1402     PAIRED(enter_shadow_mode, exit_shadow_mode);
1403     PAIRED(enter_subscript_mode, exit_subscript_mode);
1404     PAIRED(enter_superscript_mode, exit_superscript_mode);
1405     PAIRED(enter_upward_mode, exit_upward_mode);
1406
1407     ANDMISSING(start_char_set_def, stop_char_set_def);
1408
1409     /* if we have a parameterized form, then the non-parameterized is easy */
1410     ANDMISSING(set_bottom_margin_parm, set_bottom_margin);
1411     ANDMISSING(set_left_margin_parm, set_left_margin);
1412     ANDMISSING(set_right_margin_parm, set_right_margin);
1413     ANDMISSING(set_top_margin_parm, set_top_margin);
1414
1415     ANDMISSING(parm_down_micro, micro_down);
1416     ANDMISSING(parm_left_micro, micro_left);
1417     ANDMISSING(parm_right_micro, micro_right);
1418     ANDMISSING(parm_up_micro, micro_up);
1419 }
1420
1421 /*
1422  * Returns the expected number of parameters for the given capability.
1423  */
1424 static int
1425 expected_params(const char *name)
1426 {
1427     /* *INDENT-OFF* */
1428     static const struct {
1429         const char *name;
1430         int count;
1431     } table[] = {
1432         { "S0",                 1 },    /* 'screen' extension */
1433         { "birep",              2 },
1434         { "chr",                1 },
1435         { "colornm",            1 },
1436         { "cpi",                1 },
1437         { "csnm",               1 },
1438         { "csr",                2 },
1439         { "cub",                1 },
1440         { "cud",                1 },
1441         { "cuf",                1 },
1442         { "cup",                2 },
1443         { "cuu",                1 },
1444         { "cvr",                1 },
1445         { "cwin",               5 },
1446         { "dch",                1 },
1447         { "defc",               3 },
1448         { "dial",               1 },
1449         { "dispc",              1 },
1450         { "dl",                 1 },
1451         { "ech",                1 },
1452         { "getm",               1 },
1453         { "hpa",                1 },
1454         { "ich",                1 },
1455         { "il",                 1 },
1456         { "indn",               1 },
1457         { "initc",              4 },
1458         { "initp",              7 },
1459         { "lpi",                1 },
1460         { "mc5p",               1 },
1461         { "mrcup",              2 },
1462         { "mvpa",               1 },
1463         { "pfkey",              2 },
1464         { "pfloc",              2 },
1465         { "pfx",                2 },
1466         { "pfxl",               3 },
1467         { "pln",                2 },
1468         { "qdial",              1 },
1469         { "rcsd",               1 },
1470         { "rep",                2 },
1471         { "rin",                1 },
1472         { "sclk",               3 },
1473         { "scp",                1 },
1474         { "scs",                1 },
1475         { "scsd",               2 },
1476         { "setab",              1 },
1477         { "setaf",              1 },
1478         { "setb",               1 },
1479         { "setcolor",           1 },
1480         { "setf",               1 },
1481         { "sgr",                9 },
1482         { "sgr1",               6 },
1483         { "slength",            1 },
1484         { "slines",             1 },
1485         { "smgbp",              1 },    /* 2 if smgtp is not given */
1486         { "smglp",              1 },
1487         { "smglr",              2 },
1488         { "smgrp",              1 },
1489         { "smgtb",              2 },
1490         { "smgtp",              1 },
1491         { "tsl",                1 },
1492         { "u6",                 -1 },
1493         { "vpa",                1 },
1494         { "wind",               4 },
1495         { "wingo",              1 },
1496     };
1497     /* *INDENT-ON* */
1498
1499     unsigned n;
1500     int result = 0;             /* function-keys, etc., use none */
1501
1502     for (n = 0; n < SIZEOF(table); n++) {
1503         if (!strcmp(name, table[n].name)) {
1504             result = table[n].count;
1505             break;
1506         }
1507     }
1508
1509     return result;
1510 }
1511
1512 /*
1513  * Make a quick sanity check for the parameters which are used in the given
1514  * strings.  If there are no "%p" tokens, then there should be no other "%"
1515  * markers.
1516  */
1517 static void
1518 check_params(TERMTYPE *tp, const char *name, char *value)
1519 {
1520     int expected = expected_params(name);
1521     int actual = 0;
1522     int n;
1523     bool params[10];
1524     char *s = value;
1525
1526 #ifdef set_top_margin_parm
1527     if (!strcmp(name, "smgbp")
1528         && set_top_margin_parm == 0)
1529         expected = 2;
1530 #endif
1531
1532     for (n = 0; n < 10; n++)
1533         params[n] = FALSE;
1534
1535     while (*s != 0) {
1536         if (*s == '%') {
1537             if (*++s == '\0') {
1538                 _nc_warning("expected character after %% in %s", name);
1539                 break;
1540             } else if (*s == 'p') {
1541                 if (*++s == '\0' || !isdigit((int) *s)) {
1542                     _nc_warning("expected digit after %%p in %s", name);
1543                     return;
1544                 } else {
1545                     n = (*s - '0');
1546                     if (n > actual)
1547                         actual = n;
1548                     params[n] = TRUE;
1549                 }
1550             }
1551         }
1552         s++;
1553     }
1554
1555     if (params[0]) {
1556         _nc_warning("%s refers to parameter 0 (%%p0), which is not allowed", name);
1557     }
1558     if (value == set_attributes || expected < 0) {
1559         ;
1560     } else if (expected != actual) {
1561         _nc_warning("%s uses %d parameters, expected %d", name,
1562                     actual, expected);
1563         for (n = 1; n < actual; n++) {
1564             if (!params[n])
1565                 _nc_warning("%s omits parameter %d", name, n);
1566         }
1567     }
1568 }
1569
1570 static char *
1571 skip_delay(char *s)
1572 {
1573     while (*s == '/' || isdigit(UChar(*s)))
1574         ++s;
1575     return s;
1576 }
1577
1578 /*
1579  * Skip a delay altogether, e.g., when comparing a simple string to sgr,
1580  * the latter may have a worst-case delay on the end.
1581  */
1582 static char *
1583 ignore_delays(char *s)
1584 {
1585     int delaying = 0;
1586
1587     do {
1588         switch (*s) {
1589         case '$':
1590             if (delaying == 0)
1591                 delaying = 1;
1592             break;
1593         case '<':
1594             if (delaying == 1)
1595                 delaying = 2;
1596             break;
1597         case '\0':
1598             delaying = 0;
1599             break;
1600         default:
1601             if (delaying) {
1602                 s = skip_delay(s);
1603                 if (*s == '>')
1604                     ++s;
1605                 delaying = 0;
1606             }
1607             break;
1608         }
1609         if (delaying)
1610             ++s;
1611     } while (delaying);
1612     return s;
1613 }
1614
1615 /*
1616  * An sgr string may contain several settings other than the one we're
1617  * interested in, essentially sgr0 + rmacs + whatever.  As long as the
1618  * "whatever" is contained in the sgr string, that is close enough for our
1619  * sanity check.
1620  */
1621 static bool
1622 similar_sgr(int num, char *a, char *b)
1623 {
1624     static const char *names[] =
1625     {
1626         "none"
1627         ,"standout"
1628         ,"underline"
1629         ,"reverse"
1630         ,"blink"
1631         ,"dim"
1632         ,"bold"
1633         ,"invis"
1634         ,"protect"
1635         ,"altcharset"
1636     };
1637     char *base_a = a;
1638     char *base_b = b;
1639     int delaying = 0;
1640
1641     while (*b != 0) {
1642         while (*a != *b) {
1643             if (*a == 0) {
1644                 if (b[0] == '$'
1645                     && b[1] == '<') {
1646                     _nc_warning("Did not find delay %s", _nc_visbuf(b));
1647                 } else {
1648                     _nc_warning("checking sgr(%s) %s\n\tcompare to %s\n\tunmatched %s",
1649                                 names[num], _nc_visbuf2(1, base_a),
1650                                 _nc_visbuf2(2, base_b),
1651                                 _nc_visbuf2(3, b));
1652                 }
1653                 return FALSE;
1654             } else if (delaying) {
1655                 a = skip_delay(a);
1656                 b = skip_delay(b);
1657             } else if ((*b == '0' || (*b == ';')) && *a == 'm') {
1658                 b++;
1659             } else {
1660                 a++;
1661             }
1662         }
1663         switch (*a) {
1664         case '$':
1665             if (delaying == 0)
1666                 delaying = 1;
1667             break;
1668         case '<':
1669             if (delaying == 1)
1670                 delaying = 2;
1671             break;
1672         default:
1673             delaying = 0;
1674             break;
1675         }
1676         a++;
1677         b++;
1678     }
1679     /* ignore delays on the end of the string */
1680     a = ignore_delays(a);
1681     return ((num != 0) || (*a == 0));
1682 }
1683
1684 static char *
1685 check_sgr(TERMTYPE *tp, char *zero, int num, char *cap, const char *name)
1686 {
1687     char *test;
1688
1689     _nc_tparm_err = 0;
1690     test = TPARM_9(set_attributes,
1691                    num == 1,
1692                    num == 2,
1693                    num == 3,
1694                    num == 4,
1695                    num == 5,
1696                    num == 6,
1697                    num == 7,
1698                    num == 8,
1699                    num == 9);
1700     if (test != 0) {
1701         if (PRESENT(cap)) {
1702             if (!similar_sgr(num, test, cap)) {
1703                 _nc_warning("%s differs from sgr(%d)\n\t%s=%s\n\tsgr(%d)=%s",
1704                             name, num,
1705                             name, _nc_visbuf2(1, cap),
1706                             num, _nc_visbuf2(2, test));
1707             }
1708         } else if (_nc_capcmp(test, zero)) {
1709             _nc_warning("sgr(%d) present, but not %s", num, name);
1710         }
1711     } else if (PRESENT(cap)) {
1712         _nc_warning("sgr(%d) missing, but %s present", num, name);
1713     }
1714     if (_nc_tparm_err)
1715         _nc_warning("stack error in sgr(%d) string", num);
1716     return test;
1717 }
1718
1719 #define CHECK_SGR(num,name) check_sgr(tp, zero, num, name, #name)
1720
1721 #ifdef TRACE
1722 /*
1723  * If tic is compiled with TRACE, we'll be able to see the output from the
1724  * DEBUG() macro.  But since it doesn't use traceon(), it always goes to
1725  * the standard error.  Use this function to make it simpler to follow the
1726  * resulting debug traces.
1727  */
1728 static void
1729 show_where(unsigned level)
1730 {
1731     if (_nc_tracing >= DEBUG_LEVEL(level)) {
1732         char my_name[256];
1733         _nc_get_type(my_name);
1734         _tracef("\"%s\", line %d, '%s'",
1735                 _nc_get_source(),
1736                 _nc_curr_line, my_name);
1737     }
1738 }
1739
1740 #else
1741 #define show_where(level)       /* nothing */
1742 #endif
1743
1744 /* other sanity-checks (things that we don't want in the normal
1745  * logic that reads a terminfo entry)
1746  */
1747 static void
1748 check_termtype(TERMTYPE *tp, bool literal)
1749 {
1750     bool conflict = FALSE;
1751     unsigned j, k;
1752     char fkeys[STRCOUNT];
1753
1754     /*
1755      * A terminal entry may contain more than one keycode assigned to
1756      * a given string (e.g., KEY_END and KEY_LL).  But curses will only
1757      * return one (the last one assigned).
1758      */
1759     if (!(_nc_syntax == SYN_TERMCAP && capdump)) {
1760         memset(fkeys, 0, sizeof(fkeys));
1761         for (j = 0; _nc_tinfo_fkeys[j].code; j++) {
1762             char *a = tp->Strings[_nc_tinfo_fkeys[j].offset];
1763             bool first = TRUE;
1764             if (!VALID_STRING(a))
1765                 continue;
1766             for (k = j + 1; _nc_tinfo_fkeys[k].code; k++) {
1767                 char *b = tp->Strings[_nc_tinfo_fkeys[k].offset];
1768                 if (!VALID_STRING(b)
1769                     || fkeys[k])
1770                     continue;
1771                 if (!_nc_capcmp(a, b)) {
1772                     fkeys[j] = 1;
1773                     fkeys[k] = 1;
1774                     if (first) {
1775                         if (!conflict) {
1776                             _nc_warning("Conflicting key definitions (using the last)");
1777                             conflict = TRUE;
1778                         }
1779                         fprintf(stderr, "... %s is the same as %s",
1780                                 keyname((int) _nc_tinfo_fkeys[j].code),
1781                                 keyname((int) _nc_tinfo_fkeys[k].code));
1782                         first = FALSE;
1783                     } else {
1784                         fprintf(stderr, ", %s",
1785                                 keyname((int) _nc_tinfo_fkeys[k].code));
1786                     }
1787                 }
1788             }
1789             if (!first)
1790                 fprintf(stderr, "\n");
1791         }
1792     }
1793
1794     for (j = 0; j < NUM_STRINGS(tp); j++) {
1795         char *a = tp->Strings[j];
1796         if (VALID_STRING(a))
1797             check_params(tp, ExtStrname(tp, (int) j, strnames), a);
1798     }
1799
1800     check_acs(tp);
1801     check_colors(tp);
1802     check_cursor(tp);
1803     check_keypad(tp);
1804     check_printer(tp);
1805
1806     /*
1807      * These may be mismatched because the terminal description relies on
1808      * restoring the cursor visibility by resetting it.
1809      */
1810     ANDMISSING(cursor_invisible, cursor_normal);
1811     ANDMISSING(cursor_visible, cursor_normal);
1812
1813     if (PRESENT(cursor_visible) && PRESENT(cursor_normal)
1814         && !_nc_capcmp(cursor_visible, cursor_normal))
1815         _nc_warning("cursor_visible is same as cursor_normal");
1816
1817     /*
1818      * From XSI & O'Reilly, we gather that sc/rc are required if csr is
1819      * given, because the cursor position after the scrolling operation is
1820      * performed is undefined.
1821      */
1822     ANDMISSING(change_scroll_region, save_cursor);
1823     ANDMISSING(change_scroll_region, restore_cursor);
1824
1825     /*
1826      * If we can clear tabs, we should be able to initialize them.
1827      */
1828     ANDMISSING(clear_all_tabs, set_tab);
1829
1830     if (PRESENT(set_attributes)) {
1831         char *zero = 0;
1832
1833         _nc_tparm_err = 0;
1834         if (PRESENT(exit_attribute_mode)) {
1835             zero = strdup(CHECK_SGR(0, exit_attribute_mode));
1836         } else {
1837             zero = strdup(TPARM_9(set_attributes, 0, 0, 0, 0, 0, 0, 0, 0, 0));
1838         }
1839         if (_nc_tparm_err)
1840             _nc_warning("stack error in sgr(0) string");
1841
1842         if (zero != 0) {
1843             CHECK_SGR(1, enter_standout_mode);
1844             CHECK_SGR(2, enter_underline_mode);
1845             CHECK_SGR(3, enter_reverse_mode);
1846             CHECK_SGR(4, enter_blink_mode);
1847             CHECK_SGR(5, enter_dim_mode);
1848             CHECK_SGR(6, enter_bold_mode);
1849             CHECK_SGR(7, enter_secure_mode);
1850             CHECK_SGR(8, enter_protected_mode);
1851             CHECK_SGR(9, enter_alt_charset_mode);
1852             free(zero);
1853         } else {
1854             _nc_warning("sgr(0) did not return a value");
1855         }
1856     } else if (PRESENT(exit_attribute_mode) &&
1857                set_attributes != CANCELLED_STRING) {
1858         if (_nc_syntax == SYN_TERMINFO)
1859             _nc_warning("missing sgr string");
1860     }
1861
1862     if (PRESENT(exit_attribute_mode)) {
1863         char *check_sgr0 = _nc_trim_sgr0(tp);
1864
1865         if (check_sgr0 == 0 || *check_sgr0 == '\0') {
1866             _nc_warning("trimmed sgr0 is empty");
1867         } else {
1868             show_where(2);
1869             if (check_sgr0 != exit_attribute_mode) {
1870                 DEBUG(2,
1871                       ("will trim sgr0\n\toriginal sgr0=%s\n\ttrimmed  sgr0=%s",
1872                        _nc_visbuf2(1, exit_attribute_mode),
1873                        _nc_visbuf2(2, check_sgr0)));
1874                 free(check_sgr0);
1875             } else {
1876                 DEBUG(2,
1877                       ("will not trim sgr0\n\toriginal sgr0=%s",
1878                        _nc_visbuf(exit_attribute_mode)));
1879             }
1880         }
1881     }
1882 #ifdef TRACE
1883     show_where(2);
1884     if (!auto_right_margin) {
1885         DEBUG(2,
1886               ("can write to lower-right directly"));
1887     } else if (PRESENT(enter_am_mode) && PRESENT(exit_am_mode)) {
1888         DEBUG(2,
1889               ("can write to lower-right by suppressing automargin"));
1890     } else if ((PRESENT(enter_insert_mode) && PRESENT(exit_insert_mode))
1891                || PRESENT(insert_character) || PRESENT(parm_ich)) {
1892         DEBUG(2,
1893               ("can write to lower-right by using inserts"));
1894     } else {
1895         DEBUG(2,
1896               ("cannot write to lower-right"));
1897     }
1898 #endif
1899
1900     /*
1901      * Some standard applications (e.g., vi) and some non-curses
1902      * applications (e.g., jove) get confused if we have both ich1 and
1903      * smir/rmir.  Let's be nice and warn about that, too, even though
1904      * ncurses handles it.
1905      */
1906     if ((PRESENT(enter_insert_mode) || PRESENT(exit_insert_mode))
1907         && PRESENT(parm_ich)) {
1908         _nc_warning("non-curses applications may be confused by ich1 with smir/rmir");
1909     }
1910
1911     /*
1912      * Finally, do the non-verbose checks
1913      */
1914     if (save_check_termtype != 0)
1915         save_check_termtype(tp, literal);
1916 }