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