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