]> ncurses.scripts.mit.edu Git - ncurses.git/blob - progs/tic.c
ncurses 5.5
[ncurses.git] / progs / tic.c
1 /****************************************************************************
2  * Copyright (c) 1998-2004,2005 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  *
39  */
40
41 #include <progs.priv.h>
42 #include <sys/stat.h>
43
44 #include <dump_entry.h>
45 #include <transform.h>
46
47 MODULE_ID("$Id: tic.c,v 1.125 2005/09/25 00:39:43 tom Exp $")
48
49 const char *_nc_progname = "tic";
50
51 static FILE *log_fp;
52 static FILE *tmp_fp;
53 static bool capdump = FALSE;    /* running as infotocap? */
54 static bool infodump = FALSE;   /* running as captoinfo? */
55 static bool showsummary = FALSE;
56 static const char *to_remove;
57
58 static void (*save_check_termtype) (TERMTYPE *, bool);
59 static void check_termtype(TERMTYPE *tt, bool);
60
61 static const char usage_string[] = "\
62 [-e names] \
63 [-o dir] \
64 [-R name] \
65 [-v[n]] \
66 [-V] \
67 [-w[n]] \
68 [-\
69 1\
70 a\
71 C\
72 c\
73 f\
74 G\
75 g\
76 I\
77 L\
78 N\
79 r\
80 s\
81 T\
82 t\
83 U\
84 x\
85 ] \
86 source-file\n";
87
88 static void
89 cleanup(void)
90 {
91     if (tmp_fp != 0)
92         fclose(tmp_fp);
93     if (to_remove != 0) {
94 #if HAVE_REMOVE
95         remove(to_remove);
96 #else
97         unlink(to_remove);
98 #endif
99     }
100 }
101
102 static void
103 failed(const char *msg)
104 {
105     perror(msg);
106     cleanup();
107     ExitProgram(EXIT_FAILURE);
108 }
109
110 static void
111 usage(void)
112 {
113     static const char *const tbl[] =
114     {
115         "Options:",
116         "  -1         format translation output one capability per line",
117 #if NCURSES_XNAMES
118         "  -a         retain commented-out capabilities (sets -x also)",
119 #endif
120         "  -C         translate entries to termcap source form",
121         "  -c         check only, validate input without compiling or translating",
122         "  -e<names>  translate/compile only entries named by comma-separated list",
123         "  -f         format complex strings for readability",
124         "  -G         format %{number} to %'char'",
125         "  -g         format %'char' to %{number}",
126         "  -I         translate entries to terminfo source form",
127         "  -L         translate entries to full terminfo source form",
128         "  -N         disable smart defaults for source translation",
129         "  -o<dir>    set output directory for compiled entry writes",
130         "  -R<name>   restrict translation to given terminfo/termcap version",
131         "  -r         force resolution of all use entries in source translation",
132         "  -s         print summary statistics",
133         "  -T         remove size-restrictions on compiled description",
134 #if NCURSES_XNAMES
135         "  -t         suppress commented-out capabilities",
136 #endif
137         "  -U         suppress post-processing of entries",
138         "  -V         print version",
139         "  -v[n]      set verbosity level",
140         "  -w[n]      set format width for translation output",
141 #if NCURSES_XNAMES
142         "  -x         treat unknown capabilities as user-defined",
143 #endif
144         "",
145         "Parameters:",
146         "  <file>     file to translate or compile"
147     };
148     size_t j;
149
150     fprintf(stderr, "Usage: %s %s\n", _nc_progname, usage_string);
151     for (j = 0; j < SIZEOF(tbl); j++) {
152         fputs(tbl[j], stderr);
153         putc('\n', stderr);
154     }
155     ExitProgram(EXIT_FAILURE);
156 }
157
158 #define L_BRACE '{'
159 #define R_BRACE '}'
160 #define S_QUOTE '\'';
161
162 static void
163 write_it(ENTRY * ep)
164 {
165     unsigned n;
166     int ch;
167     char *s, *d, *t;
168     char result[MAX_ENTRY_SIZE];
169
170     /*
171      * Look for strings that contain %{number}, convert them to %'char',
172      * which is shorter and runs a little faster.
173      */
174     for (n = 0; n < STRCOUNT; n++) {
175         s = ep->tterm.Strings[n];
176         if (VALID_STRING(s)
177             && strchr(s, L_BRACE) != 0) {
178             d = result;
179             t = s;
180             while ((ch = *t++) != 0) {
181                 *d++ = ch;
182                 if (ch == '\\') {
183                     *d++ = *t++;
184                 } else if ((ch == '%')
185                            && (*t == L_BRACE)) {
186                     char *v = 0;
187                     long value = strtol(t + 1, &v, 0);
188                     if (v != 0
189                         && *v == R_BRACE
190                         && value > 0
191                         && value != '\\'        /* FIXME */
192                         && value < 127
193                         && isprint((int) value)) {
194                         *d++ = S_QUOTE;
195                         *d++ = (int) value;
196                         *d++ = S_QUOTE;
197                         t = (v + 1);
198                     }
199                 }
200             }
201             *d = 0;
202             if (strlen(result) < strlen(s))
203                 strcpy(s, result);
204         }
205     }
206
207     _nc_set_type(_nc_first_name(ep->tterm.term_names));
208     _nc_curr_line = ep->startline;
209     _nc_write_entry(&ep->tterm);
210 }
211
212 static bool
213 immedhook(ENTRY * ep GCC_UNUSED)
214 /* write out entries with no use capabilities immediately to save storage */
215 {
216 #if !HAVE_BIG_CORE
217     /*
218      * This is strictly a core-economy kluge.  The really clean way to handle
219      * compilation is to slurp the whole file into core and then do all the
220      * name-collision checks and entry writes in one swell foop.  But the
221      * terminfo master file is large enough that some core-poor systems swap
222      * like crazy when you compile it this way...there have been reports of
223      * this process taking *three hours*, rather than the twenty seconds or
224      * less typical on my development box.
225      *
226      * So.  This hook *immediately* writes out the referenced entry if it
227      * has no use capabilities.  The compiler main loop refrains from
228      * adding the entry to the in-core list when this hook fires.  If some
229      * other entry later needs to reference an entry that got written
230      * immediately, that's OK; the resolution code will fetch it off disk
231      * when it can't find it in core.
232      *
233      * Name collisions will still be detected, just not as cleanly.  The
234      * write_entry() code complains before overwriting an entry that
235      * postdates the time of tic's first call to write_entry().  Thus
236      * it will complain about overwriting entries newly made during the
237      * tic run, but not about overwriting ones that predate it.
238      *
239      * The reason this is a hook, and not in line with the rest of the
240      * compiler code, is that the support for termcap fallback cannot assume
241      * it has anywhere to spool out these entries!
242      *
243      * The _nc_set_type() call here requires a compensating one in
244      * _nc_parse_entry().
245      *
246      * If you define HAVE_BIG_CORE, you'll disable this kluge.  This will
247      * make tic a bit faster (because the resolution code won't have to do
248      * disk I/O nearly as often).
249      */
250     if (ep->nuses == 0) {
251         int oldline = _nc_curr_line;
252
253         write_it(ep);
254         _nc_curr_line = oldline;
255         free(ep->tterm.str_table);
256         return (TRUE);
257     }
258 #endif /* HAVE_BIG_CORE */
259     return (FALSE);
260 }
261
262 static void
263 put_translate(int c)
264 /* emit a comment char, translating terminfo names to termcap names */
265 {
266     static bool in_name = FALSE;
267     static size_t have, used;
268     static char *namebuf, *suffix;
269
270     if (in_name) {
271         if (used + 1 >= have) {
272             have += 132;
273             namebuf = typeRealloc(char, have, namebuf);
274             suffix = typeRealloc(char, have, suffix);
275         }
276         if (c == '\n' || c == '@') {
277             namebuf[used++] = '\0';
278             (void) putchar('<');
279             (void) fputs(namebuf, stdout);
280             putchar(c);
281             in_name = FALSE;
282         } else if (c != '>') {
283             namebuf[used++] = c;
284         } else {                /* ah! candidate name! */
285             char *up;
286             NCURSES_CONST char *tp;
287
288             namebuf[used++] = '\0';
289             in_name = FALSE;
290
291             suffix[0] = '\0';
292             if ((up = strchr(namebuf, '#')) != 0
293                 || (up = strchr(namebuf, '=')) != 0
294                 || ((up = strchr(namebuf, '@')) != 0 && up[1] == '>')) {
295                 (void) strcpy(suffix, up);
296                 *up = '\0';
297             }
298
299             if ((tp = nametrans(namebuf)) != 0) {
300                 (void) putchar(':');
301                 (void) fputs(tp, stdout);
302                 (void) fputs(suffix, stdout);
303                 (void) putchar(':');
304             } else {
305                 /* couldn't find a translation, just dump the name */
306                 (void) putchar('<');
307                 (void) fputs(namebuf, stdout);
308                 (void) fputs(suffix, stdout);
309                 (void) putchar('>');
310             }
311         }
312     } else {
313         used = 0;
314         if (c == '<') {
315             in_name = TRUE;
316         } else {
317             putchar(c);
318         }
319     }
320 }
321
322 /* Returns a string, stripped of leading/trailing whitespace */
323 static char *
324 stripped(char *src)
325 {
326     while (isspace(UChar(*src)))
327         src++;
328     if (*src != '\0') {
329         char *dst = strcpy((char *) malloc(strlen(src) + 1), src);
330         size_t len = strlen(dst);
331         while (--len != 0 && isspace(UChar(dst[len])))
332             dst[len] = '\0';
333         return dst;
334     }
335     return 0;
336 }
337
338 static FILE *
339 open_input(const char *filename)
340 {
341     FILE *fp = fopen(filename, "r");
342     struct stat sb;
343
344     if (fp == 0) {
345         fprintf(stderr, "%s: Can't open %s\n", _nc_progname, filename);
346         ExitProgram(EXIT_FAILURE);
347     }
348     if (fstat(fileno(fp), &sb) < 0
349         || (sb.st_mode & S_IFMT) != S_IFREG) {
350         fprintf(stderr, "%s: %s is not a file\n", _nc_progname, filename);
351         ExitProgram(EXIT_FAILURE);
352     }
353     return fp;
354 }
355
356 /* Parse the "-e" option-value into a list of names */
357 static const char **
358 make_namelist(char *src)
359 {
360     const char **dst = 0;
361
362     char *s, *base;
363     unsigned pass, n, nn;
364     char buffer[BUFSIZ];
365
366     if (src == 0) {
367         /* EMPTY */ ;
368     } else if (strchr(src, '/') != 0) {         /* a filename */
369         FILE *fp = open_input(src);
370
371         for (pass = 1; pass <= 2; pass++) {
372             nn = 0;
373             while (fgets(buffer, sizeof(buffer), fp) != 0) {
374                 if ((s = stripped(buffer)) != 0) {
375                     if (dst != 0)
376                         dst[nn] = s;
377                     nn++;
378                 }
379             }
380             if (pass == 1) {
381                 dst = typeCalloc(const char *, nn + 1);
382                 rewind(fp);
383             }
384         }
385         fclose(fp);
386     } else {                    /* literal list of names */
387         for (pass = 1; pass <= 2; pass++) {
388             for (n = nn = 0, base = src;; n++) {
389                 int mark = src[n];
390                 if (mark == ',' || mark == '\0') {
391                     if (pass == 1) {
392                         nn++;
393                     } else {
394                         src[n] = '\0';
395                         if ((s = stripped(base)) != 0)
396                             dst[nn++] = s;
397                         base = &src[n + 1];
398                     }
399                 }
400                 if (mark == '\0')
401                     break;
402             }
403             if (pass == 1)
404                 dst = typeCalloc(const char *, nn + 1);
405         }
406     }
407     if (showsummary) {
408         fprintf(log_fp, "Entries that will be compiled:\n");
409         for (n = 0; dst[n] != 0; n++)
410             fprintf(log_fp, "%u:%s\n", n + 1, dst[n]);
411     }
412     return dst;
413 }
414
415 static bool
416 matches(const char **needle, const char *haystack)
417 /* does entry in needle list match |-separated field in haystack? */
418 {
419     bool code = FALSE;
420     size_t n;
421
422     if (needle != 0) {
423         for (n = 0; needle[n] != 0; n++) {
424             if (_nc_name_match(haystack, needle[n], "|")) {
425                 code = TRUE;
426                 break;
427             }
428         }
429     } else
430         code = TRUE;
431     return (code);
432 }
433
434 static FILE *
435 open_tempfile(char *name)
436 {
437     FILE *result = 0;
438 #if HAVE_MKSTEMP
439     int fd = mkstemp(name);
440     if (fd >= 0)
441         result = fdopen(fd, "w");
442 #else
443     if (tmpnam(name) != 0)
444         result = fopen(name, "w");
445 #endif
446     return result;
447 }
448
449 int
450 main(int argc, char *argv[])
451 {
452     char my_tmpname[PATH_MAX];
453     int v_opt = -1, debug_level;
454     int smart_defaults = TRUE;
455     char *termcap;
456     ENTRY *qp;
457
458     int this_opt, last_opt = '?';
459
460     int outform = F_TERMINFO;   /* output format */
461     int sortmode = S_TERMINFO;  /* sort_mode */
462
463     int width = 60;
464     bool formatted = FALSE;     /* reformat complex strings? */
465     bool literal = FALSE;       /* suppress post-processing? */
466     int numbers = 0;            /* format "%'char'" to/from "%{number}" */
467     bool forceresolve = FALSE;  /* force resolution */
468     bool limited = TRUE;
469     char *tversion = (char *) NULL;
470     const char *source_file = "terminfo";
471     const char **namelst = 0;
472     char *outdir = (char *) NULL;
473     bool check_only = FALSE;
474     bool suppress_untranslatable = FALSE;
475
476     log_fp = stderr;
477
478     _nc_progname = _nc_rootname(argv[0]);
479
480     if ((infodump = (strcmp(_nc_progname, PROG_CAPTOINFO) == 0)) != FALSE) {
481         outform = F_TERMINFO;
482         sortmode = S_TERMINFO;
483     }
484     if ((capdump = (strcmp(_nc_progname, PROG_INFOTOCAP) == 0)) != FALSE) {
485         outform = F_TERMCAP;
486         sortmode = S_TERMCAP;
487     }
488 #if NCURSES_XNAMES
489     use_extended_names(FALSE);
490 #endif
491
492     /*
493      * Processing arguments is a little complicated, since someone made a
494      * design decision to allow the numeric values for -w, -v options to
495      * be optional.
496      */
497     while ((this_opt = getopt(argc, argv,
498                               "0123456789CILNR:TUVace:fGgo:rstvwx")) != EOF) {
499         if (isdigit(this_opt)) {
500             switch (last_opt) {
501             case 'v':
502                 v_opt = (v_opt * 10) + (this_opt - '0');
503                 break;
504             case 'w':
505                 width = (width * 10) + (this_opt - '0');
506                 break;
507             default:
508                 if (this_opt != '1')
509                     usage();
510                 last_opt = this_opt;
511                 width = 0;
512             }
513             continue;
514         }
515         switch (this_opt) {
516         case 'C':
517             capdump = TRUE;
518             outform = F_TERMCAP;
519             sortmode = S_TERMCAP;
520             break;
521         case 'I':
522             infodump = TRUE;
523             outform = F_TERMINFO;
524             sortmode = S_TERMINFO;
525             break;
526         case 'L':
527             infodump = TRUE;
528             outform = F_VARIABLE;
529             sortmode = S_VARIABLE;
530             break;
531         case 'N':
532             smart_defaults = FALSE;
533             literal = TRUE;
534             break;
535         case 'R':
536             tversion = optarg;
537             break;
538         case 'T':
539             limited = FALSE;
540             break;
541         case 'U':
542             literal = TRUE;
543             break;
544         case 'V':
545             puts(curses_version());
546             return EXIT_SUCCESS;
547         case 'c':
548             check_only = TRUE;
549             break;
550         case 'e':
551             namelst = make_namelist(optarg);
552             break;
553         case 'f':
554             formatted = TRUE;
555             break;
556         case 'G':
557             numbers = 1;
558             break;
559         case 'g':
560             numbers = -1;
561             break;
562         case 'o':
563             outdir = optarg;
564             break;
565         case 'r':
566             forceresolve = TRUE;
567             break;
568         case 's':
569             showsummary = TRUE;
570             break;
571         case 'v':
572             v_opt = 0;
573             break;
574         case 'w':
575             width = 0;
576             break;
577 #if NCURSES_XNAMES
578         case 't':
579             _nc_disable_period = FALSE;
580             suppress_untranslatable = TRUE;
581             break;
582         case 'a':
583             _nc_disable_period = TRUE;
584             /* FALLTHRU */
585         case 'x':
586             use_extended_names(TRUE);
587             break;
588 #endif
589         default:
590             usage();
591         }
592         last_opt = this_opt;
593     }
594
595     debug_level = (v_opt > 0) ? v_opt : (v_opt == 0);
596     set_trace_level(debug_level);
597
598     if (_nc_tracing) {
599         save_check_termtype = _nc_check_termtype2;
600         _nc_check_termtype2 = check_termtype;
601     }
602 #if !HAVE_BIG_CORE
603     /*
604      * Aaargh! immedhook seriously hoses us!
605      *
606      * One problem with immedhook is it means we can't do -e.  Problem
607      * is that we can't guarantee that for each terminal listed, all the
608      * terminals it depends on will have been kept in core for reference
609      * resolution -- in fact it's certain the primitive types at the end
610      * of reference chains *won't* be in core unless they were explicitly
611      * in the select list themselves.
612      */
613     if (namelst && (!infodump && !capdump)) {
614         (void) fprintf(stderr,
615                        "Sorry, -e can't be used without -I or -C\n");
616         cleanup();
617         ExitProgram(EXIT_FAILURE);
618     }
619 #endif /* HAVE_BIG_CORE */
620
621     if (optind < argc) {
622         source_file = argv[optind++];
623         if (optind < argc) {
624             fprintf(stderr,
625                     "%s: Too many file names.  Usage:\n\t%s %s",
626                     _nc_progname,
627                     _nc_progname,
628                     usage_string);
629             ExitProgram(EXIT_FAILURE);
630         }
631     } else {
632         if (infodump == TRUE) {
633             /* captoinfo's no-argument case */
634             source_file = "/etc/termcap";
635             if ((termcap = getenv("TERMCAP")) != 0
636                 && (namelst = make_namelist(getenv("TERM"))) != 0) {
637                 if (access(termcap, F_OK) == 0) {
638                     /* file exists */
639                     source_file = termcap;
640                 } else if ((tmp_fp = open_tempfile(strcpy(my_tmpname,
641                                                           "/tmp/XXXXXX")))
642                            != 0) {
643                     source_file = my_tmpname;
644                     fprintf(tmp_fp, "%s\n", termcap);
645                     fclose(tmp_fp);
646                     tmp_fp = open_input(source_file);
647                     to_remove = source_file;
648                 } else {
649                     failed("tmpnam");
650                 }
651             }
652         } else {
653             /* tic */
654             fprintf(stderr,
655                     "%s: File name needed.  Usage:\n\t%s %s",
656                     _nc_progname,
657                     _nc_progname,
658                     usage_string);
659             cleanup();
660             ExitProgram(EXIT_FAILURE);
661         }
662     }
663
664     if (tmp_fp == 0)
665         tmp_fp = open_input(source_file);
666
667     if (infodump)
668         dump_init(tversion,
669                   smart_defaults
670                   ? outform
671                   : F_LITERAL,
672                   sortmode, width, debug_level, formatted);
673     else if (capdump)
674         dump_init(tversion,
675                   outform,
676                   sortmode, width, debug_level, FALSE);
677
678     /* parse entries out of the source file */
679     _nc_set_source(source_file);
680 #if !HAVE_BIG_CORE
681     if (!(check_only || infodump || capdump))
682         _nc_set_writedir(outdir);
683 #endif /* HAVE_BIG_CORE */
684     _nc_read_entry_source(tmp_fp, (char *) NULL,
685                           !smart_defaults || literal, FALSE,
686                           ((check_only || infodump || capdump)
687                            ? NULLHOOK
688                            : immedhook));
689
690     /* do use resolution */
691     if (check_only || (!infodump && !capdump) || forceresolve) {
692         if (!_nc_resolve_uses2(TRUE, literal) && !check_only) {
693             cleanup();
694             ExitProgram(EXIT_FAILURE);
695         }
696     }
697
698     /* length check */
699     if (check_only && (capdump || infodump)) {
700         for_entry_list(qp) {
701             if (matches(namelst, qp->tterm.term_names)) {
702                 int len = fmt_entry(&qp->tterm, NULL, FALSE, TRUE, infodump, numbers);
703
704                 if (len > (infodump ? MAX_TERMINFO_LENGTH : MAX_TERMCAP_LENGTH))
705                     (void) fprintf(stderr,
706                                    "warning: resolved %s entry is %d bytes long\n",
707                                    _nc_first_name(qp->tterm.term_names),
708                                    len);
709             }
710         }
711     }
712
713     /* write or dump all entries */
714     if (!check_only) {
715         if (!infodump && !capdump) {
716             _nc_set_writedir(outdir);
717             for_entry_list(qp) {
718                 if (matches(namelst, qp->tterm.term_names))
719                     write_it(qp);
720             }
721         } else {
722             /* this is in case infotocap() generates warnings */
723             _nc_curr_col = _nc_curr_line = -1;
724
725             for_entry_list(qp) {
726                 if (matches(namelst, qp->tterm.term_names)) {
727                     int j = qp->cend - qp->cstart;
728                     int len = 0;
729
730                     /* this is in case infotocap() generates warnings */
731                     _nc_set_type(_nc_first_name(qp->tterm.term_names));
732
733                     (void) fseek(tmp_fp, qp->cstart, SEEK_SET);
734                     while (j--) {
735                         if (infodump)
736                             (void) putchar(fgetc(tmp_fp));
737                         else
738                             put_translate(fgetc(tmp_fp));
739                     }
740
741                     len = dump_entry(&qp->tterm, suppress_untranslatable,
742                                      limited, 0, numbers, NULL);
743                     for (j = 0; j < qp->nuses; j++)
744                         len += dump_uses(qp->uses[j].name, !capdump);
745                     (void) putchar('\n');
746                     if (debug_level != 0 && !limited)
747                         printf("# length=%d\n", len);
748                 }
749             }
750             if (!namelst && _nc_tail) {
751                 int c, oldc = '\0';
752                 bool in_comment = FALSE;
753                 bool trailing_comment = FALSE;
754
755                 (void) fseek(tmp_fp, _nc_tail->cend, SEEK_SET);
756                 while ((c = fgetc(tmp_fp)) != EOF) {
757                     if (oldc == '\n') {
758                         if (c == '#') {
759                             trailing_comment = TRUE;
760                             in_comment = TRUE;
761                         } else {
762                             in_comment = FALSE;
763                         }
764                     }
765                     if (trailing_comment
766                         && (in_comment || (oldc == '\n' && c == '\n')))
767                         putchar(c);
768                     oldc = c;
769                 }
770             }
771         }
772     }
773
774     /* Show the directory into which entries were written, and the total
775      * number of entries
776      */
777     if (showsummary
778         && (!(check_only || infodump || capdump))) {
779         int total = _nc_tic_written();
780         if (total != 0)
781             fprintf(log_fp, "%d entries written to %s\n",
782                     total,
783                     _nc_tic_dir((char *) 0));
784         else
785             fprintf(log_fp, "No entries written\n");
786     }
787     cleanup();
788     ExitProgram(EXIT_SUCCESS);
789 }
790
791 /*
792  * This bit of legerdemain turns all the terminfo variable names into
793  * references to locations in the arrays Booleans, Numbers, and Strings ---
794  * precisely what's needed (see comp_parse.c).
795  */
796
797 TERMINAL *cur_term;             /* tweak to avoid linking lib_cur_term.c */
798
799 #undef CUR
800 #define CUR tp->
801
802 /*
803  * Check if the alternate character-set capabilities are consistent.
804  */
805 static void
806 check_acs(TERMTYPE *tp)
807 {
808     if (VALID_STRING(acs_chars)) {
809         const char *boxes = "lmkjtuvwqxn";
810         char mapped[256];
811         char missing[256];
812         const char *p;
813         char *q;
814
815         memset(mapped, 0, sizeof(mapped));
816         for (p = acs_chars; *p != '\0'; p += 2) {
817             if (p[1] == '\0') {
818                 _nc_warning("acsc has odd number of characters");
819                 break;
820             }
821             mapped[UChar(p[0])] = p[1];
822         }
823         if (mapped[UChar('I')] && !mapped[UChar('i')]) {
824             _nc_warning("acsc refers to 'I', which is probably an error");
825         }
826         for (p = boxes, q = missing; *p != '\0'; ++p) {
827             if (!mapped[UChar(p[0])]) {
828                 *q++ = p[0];
829             }
830             *q = '\0';
831         }
832         if (*missing != '\0' && strcmp(missing, boxes)) {
833             _nc_warning("acsc is missing some line-drawing mapping: %s", missing);
834         }
835     }
836 }
837
838 /*
839  * Check if the color capabilities are consistent
840  */
841 static void
842 check_colors(TERMTYPE *tp)
843 {
844     if ((max_colors > 0) != (max_pairs > 0)
845         || ((max_colors > max_pairs) && (initialize_pair == 0)))
846         _nc_warning("inconsistent values for max_colors (%d) and max_pairs (%d)",
847                     max_colors, max_pairs);
848
849     PAIRED(set_foreground, set_background);
850     PAIRED(set_a_foreground, set_a_background);
851     PAIRED(set_color_pair, initialize_pair);
852
853     if (VALID_STRING(set_foreground)
854         && VALID_STRING(set_a_foreground)
855         && !_nc_capcmp(set_foreground, set_a_foreground))
856         _nc_warning("expected setf/setaf to be different");
857
858     if (VALID_STRING(set_background)
859         && VALID_STRING(set_a_background)
860         && !_nc_capcmp(set_background, set_a_background))
861         _nc_warning("expected setb/setab to be different");
862
863     /* see: has_colors() */
864     if (VALID_NUMERIC(max_colors) && VALID_NUMERIC(max_pairs)
865         && (((set_foreground != NULL)
866              && (set_background != NULL))
867             || ((set_a_foreground != NULL)
868                 && (set_a_background != NULL))
869             || set_color_pair)) {
870         if (!VALID_STRING(orig_pair) && !VALID_STRING(orig_colors))
871             _nc_warning("expected either op/oc string for resetting colors");
872     }
873 }
874
875 static int
876 keypad_final(const char *string)
877 {
878     int result = '\0';
879
880     if (VALID_STRING(string)
881         && *string++ == '\033'
882         && *string++ == 'O'
883         && strlen(string) == 1) {
884         result = *string;
885     }
886
887     return result;
888 }
889
890 static int
891 keypad_index(const char *string)
892 {
893     char *test;
894     const char *list = "PQRSwxymtuvlqrsPpn";    /* app-keypad except "Enter" */
895     int ch;
896     int result = -1;
897
898     if ((ch = keypad_final(string)) != '\0') {
899         test = strchr(list, ch);
900         if (test != 0)
901             result = (test - list);
902     }
903     return result;
904 }
905
906 /*
907  * Do a quick sanity-check for vt100-style keypads to see if the 5-key keypad
908  * is mapped inconsistently.
909  */
910 static void
911 check_keypad(TERMTYPE *tp)
912 {
913     char show[80];
914
915     if (VALID_STRING(key_a1) &&
916         VALID_STRING(key_a3) &&
917         VALID_STRING(key_b2) &&
918         VALID_STRING(key_c1) &&
919         VALID_STRING(key_c3)) {
920         char final[6];
921         int list[5];
922         int increase = 0;
923         int j, k, kk;
924         int last;
925         int test;
926
927         final[0] = keypad_final(key_a1);
928         final[1] = keypad_final(key_a3);
929         final[2] = keypad_final(key_b2);
930         final[3] = keypad_final(key_c1);
931         final[4] = keypad_final(key_c3);
932         final[5] = '\0';
933
934         /* special case: legacy coding using 1,2,3,0,. on the bottom */
935         if (!strcmp(final, "qsrpn"))
936             return;
937
938         list[0] = keypad_index(key_a1);
939         list[1] = keypad_index(key_a3);
940         list[2] = keypad_index(key_b2);
941         list[3] = keypad_index(key_c1);
942         list[4] = keypad_index(key_c3);
943
944         /* check that they're all vt100 keys */
945         for (j = 0; j < 5; ++j) {
946             if (list[j] < 0) {
947                 return;
948             }
949         }
950
951         /* check if they're all in increasing order */
952         for (j = 1; j < 5; ++j) {
953             if (list[j] > list[j - 1]) {
954                 ++increase;
955             }
956         }
957         if (increase != 4) {
958             show[0] = '\0';
959
960             for (j = 0, last = -1; j < 5; ++j) {
961                 for (k = 0, kk = -1, test = 100; k < 5; ++k) {
962                     if (list[k] > last &&
963                         list[k] < test) {
964                         test = list[k];
965                         kk = k;
966                     }
967                 }
968                 last = test;
969                 switch (kk) {
970                 case 0:
971                     strcat(show, " ka1");
972                     break;
973                 case 1:
974                     strcat(show, " ka3");
975                     break;
976                 case 2:
977                     strcat(show, " kb2");
978                     break;
979                 case 3:
980                     strcat(show, " kc1");
981                     break;
982                 case 4:
983                     strcat(show, " kc3");
984                     break;
985                 }
986             }
987
988             _nc_warning("vt100 keypad order inconsistent: %s", show);
989         }
990
991     } else if (VALID_STRING(key_a1) ||
992                VALID_STRING(key_a3) ||
993                VALID_STRING(key_b2) ||
994                VALID_STRING(key_c1) ||
995                VALID_STRING(key_c3)) {
996         show[0] = '\0';
997         if (keypad_index(key_a1) >= 0)
998             strcat(show, " ka1");
999         if (keypad_index(key_a3) >= 0)
1000             strcat(show, " ka3");
1001         if (keypad_index(key_b2) >= 0)
1002             strcat(show, " kb2");
1003         if (keypad_index(key_c1) >= 0)
1004             strcat(show, " kc1");
1005         if (keypad_index(key_c3) >= 0)
1006             strcat(show, " kc3");
1007         if (*show != '\0')
1008             _nc_warning("vt100 keypad map incomplete:%s", show);
1009     }
1010 }
1011
1012 /*
1013  * Returns the expected number of parameters for the given capability.
1014  */
1015 static int
1016 expected_params(const char *name)
1017 {
1018     /* *INDENT-OFF* */
1019     static const struct {
1020         const char *name;
1021         int count;
1022     } table[] = {
1023         { "S0",                 1 },    /* 'screen' extension */
1024         { "birep",              2 },
1025         { "chr",                1 },
1026         { "colornm",            1 },
1027         { "cpi",                1 },
1028         { "csnm",               1 },
1029         { "csr",                2 },
1030         { "cub",                1 },
1031         { "cud",                1 },
1032         { "cuf",                1 },
1033         { "cup",                2 },
1034         { "cuu",                1 },
1035         { "cvr",                1 },
1036         { "cwin",               5 },
1037         { "dch",                1 },
1038         { "defc",               3 },
1039         { "dial",               1 },
1040         { "dispc",              1 },
1041         { "dl",                 1 },
1042         { "ech",                1 },
1043         { "getm",               1 },
1044         { "hpa",                1 },
1045         { "ich",                1 },
1046         { "il",                 1 },
1047         { "indn",               1 },
1048         { "initc",              4 },
1049         { "initp",              7 },
1050         { "lpi",                1 },
1051         { "mc5p",               1 },
1052         { "mrcup",              2 },
1053         { "mvpa",               1 },
1054         { "pfkey",              2 },
1055         { "pfloc",              2 },
1056         { "pfx",                2 },
1057         { "pfxl",               3 },
1058         { "pln",                2 },
1059         { "qdial",              1 },
1060         { "rcsd",               1 },
1061         { "rep",                2 },
1062         { "rin",                1 },
1063         { "sclk",               3 },
1064         { "scp",                1 },
1065         { "scs",                1 },
1066         { "scsd",               2 },
1067         { "setab",              1 },
1068         { "setaf",              1 },
1069         { "setb",               1 },
1070         { "setcolor",           1 },
1071         { "setf",               1 },
1072         { "sgr",                9 },
1073         { "sgr1",               6 },
1074         { "slength",            1 },
1075         { "slines",             1 },
1076         { "smgbp",              1 },    /* 2 if smgtp is not given */
1077         { "smglp",              1 },
1078         { "smglr",              2 },
1079         { "smgrp",              1 },
1080         { "smgtb",              2 },
1081         { "smgtp",              1 },
1082         { "tsl",                1 },
1083         { "u6",                 -1 },
1084         { "vpa",                1 },
1085         { "wind",               4 },
1086         { "wingo",              1 },
1087     };
1088     /* *INDENT-ON* */
1089
1090     unsigned n;
1091     int result = 0;             /* function-keys, etc., use none */
1092
1093     for (n = 0; n < SIZEOF(table); n++) {
1094         if (!strcmp(name, table[n].name)) {
1095             result = table[n].count;
1096             break;
1097         }
1098     }
1099
1100     return result;
1101 }
1102
1103 /*
1104  * Make a quick sanity check for the parameters which are used in the given
1105  * strings.  If there are no "%p" tokens, then there should be no other "%"
1106  * markers.
1107  */
1108 static void
1109 check_params(TERMTYPE *tp, const char *name, char *value)
1110 {
1111     int expected = expected_params(name);
1112     int actual = 0;
1113     int n;
1114     bool params[10];
1115     char *s = value;
1116
1117 #ifdef set_top_margin_parm
1118     if (!strcmp(name, "smgbp")
1119         && set_top_margin_parm == 0)
1120         expected = 2;
1121 #endif
1122
1123     for (n = 0; n < 10; n++)
1124         params[n] = FALSE;
1125
1126     while (*s != 0) {
1127         if (*s == '%') {
1128             if (*++s == '\0') {
1129                 _nc_warning("expected character after %% in %s", name);
1130                 break;
1131             } else if (*s == 'p') {
1132                 if (*++s == '\0' || !isdigit((int) *s)) {
1133                     _nc_warning("expected digit after %%p in %s", name);
1134                     return;
1135                 } else {
1136                     n = (*s - '0');
1137                     if (n > actual)
1138                         actual = n;
1139                     params[n] = TRUE;
1140                 }
1141             }
1142         }
1143         s++;
1144     }
1145
1146     if (params[0]) {
1147         _nc_warning("%s refers to parameter 0 (%%p0), which is not allowed", name);
1148     }
1149     if (value == set_attributes || expected < 0) {
1150         ;
1151     } else if (expected != actual) {
1152         _nc_warning("%s uses %d parameters, expected %d", name,
1153                     actual, expected);
1154         for (n = 1; n < actual; n++) {
1155             if (!params[n])
1156                 _nc_warning("%s omits parameter %d", name, n);
1157         }
1158     }
1159 }
1160
1161 static char *
1162 skip_delay(char *s)
1163 {
1164     while (*s == '/' || isdigit(UChar(*s)))
1165         ++s;
1166     return s;
1167 }
1168
1169 /*
1170  * Skip a delay altogether, e.g., when comparing a simple string to sgr,
1171  * the latter may have a worst-case delay on the end.
1172  */
1173 static char *
1174 ignore_delays(char *s)
1175 {
1176     int delaying = 0;
1177
1178     do {
1179         switch (*s) {
1180         case '$':
1181             if (delaying == 0)
1182                 delaying = 1;
1183             break;
1184         case '<':
1185             if (delaying == 1)
1186                 delaying = 2;
1187             break;
1188         case '\0':
1189             delaying = 0;
1190             break;
1191         default:
1192             if (delaying) {
1193                 s = skip_delay(s);
1194                 if (*s == '>')
1195                     ++s;
1196                 delaying = 0;
1197             }
1198             break;
1199         }
1200         if (delaying)
1201             ++s;
1202     } while (delaying);
1203     return s;
1204 }
1205
1206 /*
1207  * An sgr string may contain several settings other than the one we're
1208  * interested in, essentially sgr0 + rmacs + whatever.  As long as the
1209  * "whatever" is contained in the sgr string, that is close enough for our
1210  * sanity check.
1211  */
1212 static bool
1213 similar_sgr(int num, char *a, char *b)
1214 {
1215     static const char *names[] =
1216     {
1217         "none"
1218         ,"standout"
1219         ,"underline"
1220         ,"reverse"
1221         ,"blink"
1222         ,"dim"
1223         ,"bold"
1224         ,"invis"
1225         ,"protect"
1226         ,"altcharset"
1227     };
1228     char *base_a = a;
1229     char *base_b = b;
1230     int delaying = 0;
1231
1232     while (*b != 0) {
1233         while (*a != *b) {
1234             if (*a == 0) {
1235                 if (b[0] == '$'
1236                     && b[1] == '<') {
1237                     _nc_warning("Did not find delay %s", _nc_visbuf(b));
1238                 } else {
1239                     _nc_warning("checking sgr(%s) %s\n\tcompare to %s\n\tunmatched %s",
1240                                 names[num], _nc_visbuf2(1, base_a),
1241                                 _nc_visbuf2(2, base_b),
1242                                 _nc_visbuf2(3, b));
1243                 }
1244                 return FALSE;
1245             } else if (delaying) {
1246                 a = skip_delay(a);
1247                 b = skip_delay(b);
1248             } else {
1249                 a++;
1250             }
1251         }
1252         switch (*a) {
1253         case '$':
1254             if (delaying == 0)
1255                 delaying = 1;
1256             break;
1257         case '<':
1258             if (delaying == 1)
1259                 delaying = 2;
1260             break;
1261         default:
1262             delaying = 0;
1263             break;
1264         }
1265         a++;
1266         b++;
1267     }
1268     /* ignore delays on the end of the string */
1269     a = ignore_delays(a);
1270     return ((num != 0) || (*a == 0));
1271 }
1272
1273 static char *
1274 check_sgr(TERMTYPE *tp, char *zero, int num, char *cap, const char *name)
1275 {
1276     char *test;
1277
1278     _nc_tparm_err = 0;
1279     test = tparm(set_attributes,
1280                  num == 1,
1281                  num == 2,
1282                  num == 3,
1283                  num == 4,
1284                  num == 5,
1285                  num == 6,
1286                  num == 7,
1287                  num == 8,
1288                  num == 9);
1289     if (test != 0) {
1290         if (PRESENT(cap)) {
1291             if (!similar_sgr(num, test, cap)) {
1292                 _nc_warning("%s differs from sgr(%d)\n\t%s=%s\n\tsgr(%d)=%s",
1293                             name, num,
1294                             name, _nc_visbuf2(1, cap),
1295                             num, _nc_visbuf2(2, test));
1296             }
1297         } else if (_nc_capcmp(test, zero)) {
1298             _nc_warning("sgr(%d) present, but not %s", num, name);
1299         }
1300     } else if (PRESENT(cap)) {
1301         _nc_warning("sgr(%d) missing, but %s present", num, name);
1302     }
1303     if (_nc_tparm_err)
1304         _nc_warning("stack error in sgr(%d) string", num);
1305     return test;
1306 }
1307
1308 #define CHECK_SGR(num,name) check_sgr(tp, zero, num, name, #name)
1309
1310 #ifdef TRACE
1311 /*
1312  * If tic is compiled with TRACE, we'll be able to see the output from the
1313  * DEBUG() macro.  But since it doesn't use traceon(), it always goes to
1314  * the standard error.  Use this function to make it simpler to follow the
1315  * resulting debug traces.
1316  */
1317 static void
1318 show_where(unsigned level)
1319 {
1320     if (_nc_tracing >= level) {
1321         char my_name[256];
1322         _nc_get_type(my_name);
1323         fprintf(stderr, "\"%s\", line %d, '%s' ",
1324                 _nc_get_source(),
1325                 _nc_curr_line, my_name);
1326     }
1327 }
1328
1329 #else
1330 #define show_where(level) /* nothing */
1331 #endif
1332
1333 /* other sanity-checks (things that we don't want in the normal
1334  * logic that reads a terminfo entry)
1335  */
1336 static void
1337 check_termtype(TERMTYPE *tp, bool literal)
1338 {
1339     bool conflict = FALSE;
1340     unsigned j, k;
1341     char fkeys[STRCOUNT];
1342
1343     /*
1344      * A terminal entry may contain more than one keycode assigned to
1345      * a given string (e.g., KEY_END and KEY_LL).  But curses will only
1346      * return one (the last one assigned).
1347      */
1348     if (!(_nc_syntax == SYN_TERMCAP && capdump)) {
1349         memset(fkeys, 0, sizeof(fkeys));
1350         for (j = 0; _nc_tinfo_fkeys[j].code; j++) {
1351             char *a = tp->Strings[_nc_tinfo_fkeys[j].offset];
1352             bool first = TRUE;
1353             if (!VALID_STRING(a))
1354                 continue;
1355             for (k = j + 1; _nc_tinfo_fkeys[k].code; k++) {
1356                 char *b = tp->Strings[_nc_tinfo_fkeys[k].offset];
1357                 if (!VALID_STRING(b)
1358                     || fkeys[k])
1359                     continue;
1360                 if (!_nc_capcmp(a, b)) {
1361                     fkeys[j] = 1;
1362                     fkeys[k] = 1;
1363                     if (first) {
1364                         if (!conflict) {
1365                             _nc_warning("Conflicting key definitions (using the last)");
1366                             conflict = TRUE;
1367                         }
1368                         fprintf(stderr, "... %s is the same as %s",
1369                                 keyname((int) _nc_tinfo_fkeys[j].code),
1370                                 keyname((int) _nc_tinfo_fkeys[k].code));
1371                         first = FALSE;
1372                     } else {
1373                         fprintf(stderr, ", %s",
1374                                 keyname((int) _nc_tinfo_fkeys[k].code));
1375                     }
1376                 }
1377             }
1378             if (!first)
1379                 fprintf(stderr, "\n");
1380         }
1381     }
1382
1383     for (j = 0; j < NUM_STRINGS(tp); j++) {
1384         char *a = tp->Strings[j];
1385         if (VALID_STRING(a))
1386             check_params(tp, ExtStrname(tp, j, strnames), a);
1387     }
1388
1389     check_acs(tp);
1390     check_colors(tp);
1391     check_keypad(tp);
1392
1393     /*
1394      * These may be mismatched because the terminal description relies on
1395      * restoring the cursor visibility by resetting it.
1396      */
1397     ANDMISSING(cursor_invisible, cursor_normal);
1398     ANDMISSING(cursor_visible, cursor_normal);
1399
1400     if (PRESENT(cursor_visible) && PRESENT(cursor_normal)
1401         && !_nc_capcmp(cursor_visible, cursor_normal))
1402         _nc_warning("cursor_visible is same as cursor_normal");
1403
1404     /*
1405      * From XSI & O'Reilly, we gather that sc/rc are required if csr is
1406      * given, because the cursor position after the scrolling operation is
1407      * performed is undefined.
1408      */
1409     ANDMISSING(change_scroll_region, save_cursor);
1410     ANDMISSING(change_scroll_region, restore_cursor);
1411
1412     if (PRESENT(set_attributes)) {
1413         char *zero = 0;
1414
1415         _nc_tparm_err = 0;
1416         if (PRESENT(exit_attribute_mode)) {
1417             zero = strdup(CHECK_SGR(0, exit_attribute_mode));
1418         } else {
1419             zero = strdup(tparm(set_attributes, 0, 0, 0, 0, 0, 0, 0, 0, 0));
1420         }
1421         if (_nc_tparm_err)
1422             _nc_warning("stack error in sgr(0) string");
1423
1424         if (zero != 0) {
1425             CHECK_SGR(1, enter_standout_mode);
1426             CHECK_SGR(2, enter_underline_mode);
1427             CHECK_SGR(3, enter_reverse_mode);
1428             CHECK_SGR(4, enter_blink_mode);
1429             CHECK_SGR(5, enter_dim_mode);
1430             CHECK_SGR(6, enter_bold_mode);
1431             CHECK_SGR(7, enter_secure_mode);
1432             CHECK_SGR(8, enter_protected_mode);
1433             CHECK_SGR(9, enter_alt_charset_mode);
1434             free(zero);
1435         } else {
1436             _nc_warning("sgr(0) did not return a value");
1437         }
1438     } else if (PRESENT(exit_attribute_mode) &&
1439                set_attributes != CANCELLED_STRING) {
1440         if (_nc_syntax == SYN_TERMINFO)
1441             _nc_warning("missing sgr string");
1442     }
1443
1444     if (PRESENT(exit_attribute_mode)) {
1445         char *check_sgr0 = _nc_trim_sgr0(tp);
1446
1447         if (check_sgr0 == 0 || *check_sgr0 == '\0') {
1448             _nc_warning("trimmed sgr0 is empty");
1449         } else {
1450             show_where(2);
1451             if (check_sgr0 != exit_attribute_mode) {
1452                 DEBUG(2,
1453                       ("will trim sgr0\n\toriginal sgr0=%s\n\ttrimmed  sgr0=%s",
1454                        _nc_visbuf2(1, exit_attribute_mode),
1455                        _nc_visbuf2(2, check_sgr0)));
1456                 free(check_sgr0);
1457             } else {
1458                 DEBUG(2,
1459                       ("will not trim sgr0\n\toriginal sgr0=%s",
1460                        _nc_visbuf(exit_attribute_mode)));
1461             }
1462         }
1463     }
1464 #ifdef TRACE
1465     show_where(2);
1466     if (!auto_right_margin) {
1467         DEBUG(2,
1468               ("can write to lower-right directly"));
1469     } else if (PRESENT(enter_am_mode) && PRESENT(exit_am_mode)) {
1470         DEBUG(2,
1471               ("can write to lower-right by suppressing automargin"));
1472     } else if ((PRESENT(enter_insert_mode) && PRESENT(exit_insert_mode))
1473                || PRESENT(insert_character) || PRESENT(parm_ich)) {
1474         DEBUG(2,
1475               ("can write to lower-right by using inserts"));
1476     } else {
1477         DEBUG(2,
1478               ("cannot write to lower-right"));
1479     }
1480 #endif
1481
1482     /*
1483      * Some standard applications (e.g., vi) and some non-curses
1484      * applications (e.g., jove) get confused if we have both ich1 and
1485      * smir/rmir.  Let's be nice and warn about that, too, even though
1486      * ncurses handles it.
1487      */
1488     if ((PRESENT(enter_insert_mode) || PRESENT(exit_insert_mode))
1489         && PRESENT(parm_ich)) {
1490         _nc_warning("non-curses applications may be confused by ich1 with smir/rmir");
1491     }
1492
1493     /*
1494      * Finally, do the non-verbose checks
1495      */
1496     if (save_check_termtype != 0)
1497         save_check_termtype(tp, literal);
1498 }