]> ncurses.scripts.mit.edu Git - ncurses.git/blob - progs/infocmp.c
ncurses 6.4 - patch 20231111
[ncurses.git] / progs / infocmp.c
1 /****************************************************************************
2  * Copyright 2020-2022,2023 Thomas E. Dickey                                *
3  * Copyright 1998-2016,2017 Free Software Foundation, Inc.                  *
4  *                                                                          *
5  * Permission is hereby granted, free of charge, to any person obtaining a  *
6  * copy of this software and associated documentation files (the            *
7  * "Software"), to deal in the Software without restriction, including      *
8  * without limitation the rights to use, copy, modify, merge, publish,      *
9  * distribute, distribute with modifications, sublicense, and/or sell       *
10  * copies of the Software, and to permit persons to whom the Software is    *
11  * furnished to do so, subject to the following conditions:                 *
12  *                                                                          *
13  * The above copyright notice and this permission notice shall be included  *
14  * in all copies or substantial portions of the Software.                   *
15  *                                                                          *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS  *
17  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF               *
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.   *
19  * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,   *
20  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR    *
21  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR    *
22  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.                               *
23  *                                                                          *
24  * Except as contained in this notice, the name(s) of the above copyright   *
25  * holders shall not be used in advertising or otherwise to promote the     *
26  * sale, use or other dealings in this Software without prior written       *
27  * authorization.                                                           *
28  ****************************************************************************/
29
30 /****************************************************************************
31  *  Author: Zeyd M. Ben-Halim <zmbenhal@netcom.com> 1992,1995               *
32  *     and: Eric S. Raymond <esr@snark.thyrsus.com>                         *
33  *     and: Thomas E. Dickey                        1996-on                 *
34  ****************************************************************************/
35
36 /*
37  *      infocmp.c -- decompile an entry, or compare two entries
38  *              written by Eric S. Raymond
39  *              and Thomas E Dickey
40  */
41
42 #include <progs.priv.h>
43
44 #include <dump_entry.h>
45
46 MODULE_ID("$Id: infocmp.c,v 1.158 2023/11/11 18:25:52 tom Exp $")
47
48 #define MAX_STRING      1024    /* maximum formatted string */
49
50 const char *_nc_progname = "infocmp";
51
52 typedef char path[PATH_MAX];
53
54 /***************************************************************************
55  *
56  * The following control variables, together with the contents of the
57  * terminfo entries, completely determine the actions of the program.
58  *
59  ***************************************************************************/
60
61 static ENTRY *entries;          /* terminfo entries */
62 static int termcount;           /* count of terminal entries */
63
64 static bool limited = TRUE;     /* "-r" option is not set */
65 static bool quiet = FALSE;
66 static bool literal = FALSE;
67 static const char *bool_sep = ":";
68 static const char *s_absent = "NULL";
69 static const char *s_cancel = "NULL";
70 static const char *tversion;    /* terminfo version selected */
71 static unsigned itrace;         /* trace flag for debugging */
72 static int mwidth = 60;
73 static int mheight = 65535;
74 static int numbers = 0;         /* format "%'char'" to/from "%{number}" */
75 static int outform = F_TERMINFO;        /* output format */
76 static int sortmode;            /* sort_mode */
77
78 /* main comparison mode */
79 static int compare;
80 #define C_DEFAULT       0       /* don't force comparison mode */
81 #define C_DIFFERENCE    1       /* list differences between two terminals */
82 #define C_COMMON        2       /* list common capabilities */
83 #define C_NAND          3       /* list capabilities in neither terminal */
84 #define C_USEALL        4       /* generate relative use-form entry */
85 static bool ignorepads;         /* ignore pad prefixes when diffing */
86
87 #if NO_LEAKS
88
89 typedef struct {
90     ENTRY *head;
91     ENTRY *tail;
92 } ENTERED;
93
94 static ENTERED *entered;
95
96 #undef ExitProgram
97 static GCC_NORETURN void ExitProgram(int code);
98 /* prototype is to get gcc to accept the noreturn attribute */
99 static void
100 ExitProgram(int code)
101 {
102     int n;
103
104     for (n = 0; n < termcount; ++n) {
105         ENTRY *new_head = _nc_head;
106         ENTRY *new_tail = _nc_tail;
107         _nc_head = entered[n].head;
108         _nc_tail = entered[n].tail;
109         _nc_free_entries(entered[n].head);
110         _nc_head = new_head;
111         _nc_tail = new_tail;
112     }
113     _nc_leaks_dump_entry();
114     free(entries);
115     free(entered);
116     _nc_free_tic(code);
117 }
118 #endif
119
120 static void
121 failed(const char *s)
122 {
123     perror(s);
124     ExitProgram(EXIT_FAILURE);
125 }
126
127 static void
128 canonical_name(char *source, char *target)
129 /* extract the terminal type's primary name */
130 {
131     int limit = NAMESIZE;
132
133     while (--limit > 0) {
134         char ch = *source++;
135         if (ch == '|')
136             break;
137         *target++ = ch;
138     }
139     *target = '\0';
140 }
141
142 static bool
143 no_boolean(int value)
144 {
145     bool result = (value == ABSENT_BOOLEAN);
146     if (!strcmp(s_absent, s_cancel))
147         result = !VALID_BOOLEAN(value);
148     return result;
149 }
150
151 static bool
152 no_numeric(int value)
153 {
154     bool result = (value == ABSENT_NUMERIC);
155     if (!strcmp(s_absent, s_cancel))
156         result = !VALID_NUMERIC(value);
157     return result;
158 }
159
160 static bool
161 no_string(const char *const value)
162 {
163     bool result = (value == ABSENT_STRING);
164     if (!strcmp(s_absent, s_cancel))
165         result = !VALID_STRING(value);
166     return result;
167 }
168
169 /***************************************************************************
170  *
171  * Predicates for dump function
172  *
173  ***************************************************************************/
174
175 static int
176 capcmp(PredIdx idx, const char *s, const char *t)
177 /* capability comparison function */
178 {
179     if (!VALID_STRING(s) && !VALID_STRING(t))
180         return (s != t);
181     else if (!VALID_STRING(s) || !VALID_STRING(t))
182         return (1);
183
184     if ((idx == acs_chars_index) || !ignorepads)
185         return (strcmp(s, t));
186     else
187         return (_nc_capcmp(s, t));
188 }
189
190 static int
191 use_predicate(unsigned type, PredIdx idx)
192 /* predicate function to use for use decompilation */
193 {
194     ENTRY *ep;
195
196     switch (type) {
197     case BOOLEAN:
198         {
199             int is_set = FALSE;
200
201             /*
202              * This assumes that multiple use entries are supposed
203              * to contribute the logical or of their boolean capabilities.
204              * This is true if we take the semantics of multiple uses to
205              * be 'each capability gets the first non-default value found
206              * in the sequence of use entries'.
207              *
208              * Note that cancelled or absent booleans are stored as FALSE,
209              * unlike numbers and strings, whose cancelled/absent state is
210              * recorded in the terminfo database.
211              */
212             if (idx < NUM_BOOLEANS(&(entries[0].tterm))) {
213                 for (ep = &entries[1]; ep < entries + termcount; ep++) {
214                     if (idx < NUM_BOOLEANS(&(ep->tterm))
215                         && ep->tterm.Booleans[idx] == TRUE) {
216                         is_set = entries[0].tterm.Booleans[idx];
217                         break;
218                     }
219                 }
220                 if (is_set != entries[0].tterm.Booleans[idx])
221                     return (!is_set);
222             }
223             return (FAIL);
224         }
225
226     case NUMBER:
227         {
228             int value = ABSENT_NUMERIC;
229
230             /*
231              * We take the semantics of multiple uses to be 'each
232              * capability gets the first non-default value found
233              * in the sequence of use entries'.
234              */
235             if (idx < NUM_NUMBERS(&(entries[0].tterm))) {
236                 for (ep = &entries[1]; ep < entries + termcount; ep++)
237                     if (idx < NUM_NUMBERS(&(ep->tterm))
238                         && VALID_NUMERIC(ep->tterm.Numbers[idx])) {
239                         value = ep->tterm.Numbers[idx];
240                         break;
241                     }
242
243                 if (value != entries[0].tterm.Numbers[idx])
244                     return (value != ABSENT_NUMERIC);
245             }
246             return (FAIL);
247         }
248
249     case STRING:
250         {
251             char *termstr, *usestr = ABSENT_STRING;
252
253             termstr = entries[0].tterm.Strings[idx];
254
255             /*
256              * We take the semantics of multiple uses to be 'each
257              * capability gets the first non-default value found
258              * in the sequence of use entries'.
259              */
260             if (idx < NUM_STRINGS(&(entries[0].tterm))) {
261                 for (ep = &entries[1]; ep < entries + termcount; ep++)
262                     if (idx < NUM_STRINGS(&(ep->tterm))
263                         && ep->tterm.Strings[idx]) {
264                         usestr = ep->tterm.Strings[idx];
265                         break;
266                     }
267
268                 if (usestr == ABSENT_STRING && termstr == ABSENT_STRING)
269                     return (FAIL);
270                 else if (!usestr || !termstr || capcmp(idx, usestr, termstr))
271                     return (TRUE);
272             }
273             return (FAIL);
274         }
275     }
276
277     return (FALSE);             /* pacify compiler */
278 }
279
280 static bool
281 useeq(ENTRY * e1, ENTRY * e2)
282 /* are the use references in two entries equivalent? */
283 {
284     unsigned i, j;
285
286     if (e1->nuses != e2->nuses)
287         return (FALSE);
288
289     /* Ugh...this is quadratic again */
290     for (i = 0; i < e1->nuses; i++) {
291         bool foundmatch = FALSE;
292
293         /* search second entry for given use reference */
294         for (j = 0; j < e2->nuses; j++)
295             if (!strcmp(e1->uses[i].name, e2->uses[j].name)) {
296                 foundmatch = TRUE;
297                 break;
298             }
299
300         if (!foundmatch)
301             return (FALSE);
302     }
303
304     return (TRUE);
305 }
306
307 static bool
308 entryeq(TERMTYPE2 *t1, TERMTYPE2 *t2)
309 /* are two entries equivalent? */
310 {
311     unsigned i;
312
313     for (i = 0; i < NUM_BOOLEANS(t1); i++)
314         if (t1->Booleans[i] != t2->Booleans[i])
315             return (FALSE);
316
317     for (i = 0; i < NUM_NUMBERS(t1); i++)
318         if (t1->Numbers[i] != t2->Numbers[i])
319             return (FALSE);
320
321     for (i = 0; i < NUM_STRINGS(t1); i++)
322         if (capcmp((PredIdx) i, t1->Strings[i], t2->Strings[i]))
323             return (FALSE);
324
325     return (TRUE);
326 }
327
328 #define TIC_EXPAND(result) _nc_tic_expand(result, outform==F_TERMINFO, numbers)
329
330 static void
331 print_uses(ENTRY * ep, FILE *fp)
332 /* print an entry's use references */
333 {
334     if (!ep->nuses) {
335         fputs("NULL", fp);
336     } else {
337         unsigned i;
338
339         for (i = 0; i < ep->nuses; i++) {
340             fputs(ep->uses[i].name, fp);
341             if (i < ep->nuses - 1)
342                 fputs(" ", fp);
343         }
344     }
345 }
346
347 static const char *
348 dump_boolean(int val)
349 /* display the value of a boolean capability */
350 {
351     switch (val) {
352     case ABSENT_BOOLEAN:
353         return (s_absent);
354     case CANCELLED_BOOLEAN:
355         return (s_cancel);
356     case FALSE:
357         return ("F");
358     case TRUE:
359         return ("T");
360     default:
361         return ("?");
362     }
363 }
364
365 static void
366 dump_numeric(int val, char *buf)
367 /* display the value of a numeric capability */
368 {
369     switch (val) {
370     case ABSENT_NUMERIC:
371         _nc_STRCPY(buf, s_absent, MAX_STRING);
372         break;
373     case CANCELLED_NUMERIC:
374         _nc_STRCPY(buf, s_cancel, MAX_STRING);
375         break;
376     default:
377         _nc_SPRINTF(buf, _nc_SLIMIT(MAX_STRING) "%d", val);
378         break;
379     }
380 }
381
382 static void
383 dump_string(char *val, char *buf)
384 /* display the value of a string capability */
385 {
386     if (val == ABSENT_STRING)
387         _nc_STRCPY(buf, s_absent, MAX_STRING);
388     else if (val == CANCELLED_STRING)
389         _nc_STRCPY(buf, s_cancel, MAX_STRING);
390     else {
391         _nc_SPRINTF(buf, _nc_SLIMIT(MAX_STRING)
392                     "'%.*s'", MAX_STRING - 3, TIC_EXPAND(val));
393     }
394 }
395
396 /*
397  * Show "comparing..." message for the given terminal names.
398  */
399 static void
400 show_comparing(char **names)
401 {
402     if (itrace) {
403         switch (compare) {
404         case C_DIFFERENCE:
405             (void) fprintf(stderr, "%s: dumping differences\n", _nc_progname);
406             break;
407
408         case C_COMMON:
409             (void) fprintf(stderr, "%s: dumping common capabilities\n", _nc_progname);
410             break;
411
412         case C_NAND:
413             (void) fprintf(stderr, "%s: dumping differences\n", _nc_progname);
414             break;
415         }
416     }
417     if (*names) {
418         printf("comparing %s", *names++);
419         if (*names) {
420             printf(" to %s", *names++);
421             while (*names) {
422                 printf(", %s", *names++);
423             }
424         }
425         printf(".\n");
426     }
427 }
428
429 /*
430  * ncurses stores two types of non-standard capabilities:
431  * a) capabilities listed past the "STOP-HERE" comment in the Caps file.
432  *    These are used in the terminfo source file to provide data for termcaps,
433  *    e.g., when there is no equivalent capability in terminfo, as well as for
434  *    widely-used non-standard capabilities.
435  * b) user-definable capabilities, via "tic -x".
436  *
437  * However, if "-x" is omitted from the tic command, both types of
438  * non-standard capability are not loaded into the terminfo database.  This
439  * macro is used for limit-checks against the symbols that tic uses to omit
440  * the two types of non-standard entry.
441  */
442 #if NCURSES_XNAMES
443 #define check_user_definable(n,limit) if (!_nc_user_definable && (n) > (limit)) break
444 #else
445 #define check_user_definable(n,limit) if ((n) > (limit)) break
446 #endif
447
448 /*
449  * Use these macros to simplify loops on C_COMMON and C_NAND:
450  */
451 #define for_each_entry() while (entries[extra].tterm.term_names)
452 #define next_entry           (&(entries[extra++].tterm))
453
454 static void
455 compare_predicate(PredType type, PredIdx idx, const char *name)
456 /* predicate function to use for entry difference reports */
457 {
458     ENTRY *e1 = &entries[0];
459     ENTRY *e2 = &entries[1];
460     char buf1[MAX_STRING];
461     char buf2[MAX_STRING];
462     int b1, b2;
463     int n1, n2;
464     char *s1, *s2;
465     bool found;
466     int extra = 1;
467
468     switch (type) {
469     case CMP_BOOLEAN:
470         check_user_definable(idx, BOOLWRITE);
471         b1 = e1->tterm.Booleans[idx];
472         switch (compare) {
473         case C_DIFFERENCE:
474             b2 = next_entry->Booleans[idx];
475             if (!(no_boolean(b1) && no_boolean(b2)) && (b1 != b2))
476                 (void) printf("\t%s: %s%s%s.\n",
477                               name,
478                               dump_boolean(b1),
479                               bool_sep,
480                               dump_boolean(b2));
481             break;
482
483         case C_COMMON:
484             if (b1 != ABSENT_BOOLEAN) {
485                 found = TRUE;
486                 for_each_entry() {
487                     b2 = next_entry->Booleans[idx];
488                     if (b1 != b2) {
489                         found = FALSE;
490                         break;
491                     }
492                 }
493                 if (found) {
494                     (void) printf("\t%s= %s.\n", name, dump_boolean(b1));
495                 }
496             }
497             break;
498
499         case C_NAND:
500             if (b1 == ABSENT_BOOLEAN) {
501                 found = TRUE;
502                 for_each_entry() {
503                     b2 = next_entry->Booleans[idx];
504                     if (b1 != b2) {
505                         found = FALSE;
506                         break;
507                     }
508                 }
509                 if (found) {
510                     (void) printf("\t!%s.\n", name);
511                 }
512             }
513             break;
514         }
515         break;
516
517     case CMP_NUMBER:
518         check_user_definable(idx, NUMWRITE);
519         n1 = e1->tterm.Numbers[idx];
520         switch (compare) {
521         case C_DIFFERENCE:
522             n2 = next_entry->Numbers[idx];
523             if (!(no_numeric(n1) && no_numeric(n2)) && n1 != n2) {
524                 dump_numeric(n1, buf1);
525                 dump_numeric(n2, buf2);
526                 (void) printf("\t%s: %s, %s.\n", name, buf1, buf2);
527             }
528             break;
529
530         case C_COMMON:
531             if (n1 != ABSENT_NUMERIC) {
532                 found = TRUE;
533                 for_each_entry() {
534                     n2 = next_entry->Numbers[idx];
535                     if (n1 != n2) {
536                         found = FALSE;
537                         break;
538                     }
539                 }
540                 if (found) {
541                     dump_numeric(n1, buf1);
542                     (void) printf("\t%s= %s.\n", name, buf1);
543                 }
544             }
545             break;
546
547         case C_NAND:
548             if (n1 == ABSENT_NUMERIC) {
549                 found = TRUE;
550                 for_each_entry() {
551                     n2 = next_entry->Numbers[idx];
552                     if (n1 != n2) {
553                         found = FALSE;
554                         break;
555                     }
556                 }
557                 if (found) {
558                     (void) printf("\t!%s.\n", name);
559                 }
560             }
561             break;
562         }
563         break;
564
565     case CMP_STRING:
566         check_user_definable(idx, STRWRITE);
567         s1 = e1->tterm.Strings[idx];
568         switch (compare) {
569         case C_DIFFERENCE:
570             s2 = next_entry->Strings[idx];
571             if (!(no_string(s1) && no_string(s2)) && capcmp(idx, s1, s2)) {
572                 dump_string(s1, buf1);
573                 dump_string(s2, buf2);
574                 if (strcmp(buf1, buf2))
575                     (void) printf("\t%s: %s, %s.\n", name, buf1, buf2);
576             }
577             break;
578
579         case C_COMMON:
580             if (s1 != ABSENT_STRING) {
581                 found = TRUE;
582                 for_each_entry() {
583                     s2 = next_entry->Strings[idx];
584                     if (capcmp(idx, s1, s2) != 0) {
585                         found = FALSE;
586                         break;
587                     }
588                 }
589                 if (found) {
590                     (void) printf("\t%s= '%s'.\n", name, TIC_EXPAND(s1));
591                 }
592             }
593             break;
594
595         case C_NAND:
596             if (s1 == ABSENT_STRING) {
597                 found = TRUE;
598                 for_each_entry() {
599                     s2 = next_entry->Strings[idx];
600                     if (s2 != s1) {
601                         found = FALSE;
602                         break;
603                     }
604                 }
605                 if (found) {
606                     (void) printf("\t!%s.\n", name);
607                 }
608             }
609             break;
610         }
611         break;
612
613     case CMP_USE:
614         /* unlike the other modes, this compares *all* use entries */
615         switch (compare) {
616         case C_DIFFERENCE:
617             if (!useeq(e1, e2)) {
618                 (void) fputs("\tuse: ", stdout);
619                 print_uses(e1, stdout);
620                 fputs(", ", stdout);
621                 print_uses(e2, stdout);
622                 fputs(".\n", stdout);
623             }
624             break;
625
626         case C_COMMON:
627             if (e1->nuses) {
628                 found = TRUE;
629                 for_each_entry() {
630                     e2 = &entries[extra++];
631                     if (e2->nuses != e1->nuses || !useeq(e1, e2)) {
632                         found = FALSE;
633                         break;
634                     }
635                 }
636                 if (found) {
637                     (void) fputs("\tuse: ", stdout);
638                     print_uses(e1, stdout);
639                     fputs(".\n", stdout);
640                 }
641             }
642             break;
643
644         case C_NAND:
645             if (!e1->nuses) {
646                 found = TRUE;
647                 for_each_entry() {
648                     e2 = &entries[extra++];
649                     if (e2->nuses != e1->nuses) {
650                         found = FALSE;
651                         break;
652                     }
653                 }
654                 if (found) {
655                     (void) printf("\t!use.\n");
656                 }
657             }
658             break;
659         }
660     }
661 }
662
663 /***************************************************************************
664  *
665  * Init string analysis
666  *
667  ***************************************************************************/
668
669 #define DATA(from, to) { { from }, { to } }
670 #define DATAX()        DATA("", "")
671
672 typedef struct {
673     const char from[4];
674     const char to[12];
675 } assoc;
676
677 static const assoc std_caps[] =
678 {
679     /* these are specified by X.364 and iBCS2 */
680     DATA("\033c", "RIS"),       /* full reset */
681     DATA("\0337", "SC"),        /* save cursor */
682     DATA("\0338", "RC"),        /* restore cursor */
683     DATA("\033[r", "RSR"),      /* not an X.364 mnemonic */
684     DATA("\033[m", "SGR0"),     /* not an X.364 mnemonic */
685     DATA("\033[2J", "ED2"),     /* clear page */
686
687     /* this group is specified by ISO 2022 */
688     DATA("\033(0", "ISO DEC G0"),       /* enable DEC graphics for G0 */
689     DATA("\033(A", "ISO UK G0"),        /* enable UK chars for G0 */
690     DATA("\033(B", "ISO US G0"),        /* enable US chars for G0 */
691     DATA("\033)0", "ISO DEC G1"),       /* enable DEC graphics for G1 */
692     DATA("\033)A", "ISO UK G1"),        /* enable UK chars for G1 */
693     DATA("\033)B", "ISO US G1"),        /* enable US chars for G1 */
694
695     /* these are DEC private controls widely supported by emulators */
696     DATA("\033=", "DECPAM"),    /* application keypad mode */
697     DATA("\033>", "DECPNM"),    /* normal keypad mode */
698     DATA("\033<", "DECANSI"),   /* enter ANSI mode */
699     DATA("\033[!p", "DECSTR"),  /* soft reset */
700     DATA("\033 F", "S7C1T"),    /* 7-bit controls */
701
702     DATAX()
703 };
704
705 static const assoc std_modes[] =
706 /* ECMA \E[ ... [hl] modes recognized by many emulators */
707 {
708     DATA("2", "AM"),            /* keyboard action mode */
709     DATA("4", "IRM"),           /* insert/replace mode */
710     DATA("12", "SRM"),          /* send/receive mode */
711     DATA("20", "LNM"),          /* linefeed mode */
712     DATAX()
713 };
714
715 static const assoc private_modes[] =
716 /* DEC \E[ ... [hl] modes recognized by many emulators */
717 {
718     DATA("1", "CKM"),           /* application cursor keys */
719     DATA("2", "ANM"),           /* set VT52 mode */
720     DATA("3", "COLM"),          /* 132-column mode */
721     DATA("4", "SCLM"),          /* smooth scroll */
722     DATA("5", "SCNM"),          /* reverse video mode */
723     DATA("6", "OM"),            /* origin mode */
724     DATA("7", "AWM"),           /* wraparound mode */
725     DATA("8", "ARM"),           /* auto-repeat mode */
726     DATAX()
727 };
728
729 static const assoc ecma_highlights[] =
730 /* recognize ECMA attribute sequences */
731 {
732     DATA("0", "NORMAL"),        /* normal */
733     DATA("1", "+BOLD"),         /* bold on */
734     DATA("2", "+DIM"),          /* dim on */
735     DATA("3", "+ITALIC"),       /* italic on */
736     DATA("4", "+UNDERLINE"),    /* underline on */
737     DATA("5", "+BLINK"),        /* blink on */
738     DATA("6", "+FASTBLINK"),    /* fastblink on */
739     DATA("7", "+REVERSE"),      /* reverse on */
740     DATA("8", "+INVISIBLE"),    /* invisible on */
741     DATA("9", "+DELETED"),      /* deleted on */
742     DATA("10", "MAIN-FONT"),    /* select primary font */
743     DATA("11", "ALT-FONT-1"),   /* select alternate font 1 */
744     DATA("12", "ALT-FONT-2"),   /* select alternate font 2 */
745     DATA("13", "ALT-FONT-3"),   /* select alternate font 3 */
746     DATA("14", "ALT-FONT-4"),   /* select alternate font 4 */
747     DATA("15", "ALT-FONT-5"),   /* select alternate font 5 */
748     DATA("16", "ALT-FONT-6"),   /* select alternate font 6 */
749     DATA("17", "ALT-FONT-7"),   /* select alternate font 7 */
750     DATA("18", "ALT-FONT-1"),   /* select alternate font 1 */
751     DATA("19", "ALT-FONT-1"),   /* select alternate font 1 */
752     DATA("20", "FRAKTUR"),      /* Fraktur font */
753     DATA("21", "DOUBLEUNDER"),  /* double underline */
754     DATA("22", "-DIM"),         /* dim off */
755     DATA("23", "-ITALIC"),      /* italic off */
756     DATA("24", "-UNDERLINE"),   /* underline off */
757     DATA("25", "-BLINK"),       /* blink off */
758     DATA("26", "-FASTBLINK"),   /* fastblink off */
759     DATA("27", "-REVERSE"),     /* reverse off */
760     DATA("28", "-INVISIBLE"),   /* invisible off */
761     DATA("29", "-DELETED"),     /* deleted off */
762     DATAX()
763 };
764
765 #undef DATA
766
767 static int
768 skip_csi(const char *cap)
769 {
770     int result = 0;
771     if (cap[0] == '\033' && cap[1] == '[')
772         result = 2;
773     else if (UChar(cap[0]) == 0233)
774         result = 1;
775     return result;
776 }
777
778 static bool
779 same_param(const char *table, const char *param, size_t length)
780 {
781     bool result = FALSE;
782     if (strncmp(table, param, length) == 0) {
783         result = !isdigit(UChar(param[length]));
784     }
785     return result;
786 }
787
788 static char *
789 lookup_params(const assoc * table, char *dst, char *src)
790 {
791     char *result = 0;
792     const char *ep = strtok(src, ";");
793
794     if (ep != 0) {
795         const assoc *ap;
796
797         do {
798             bool found = FALSE;
799
800             for (ap = table; ap->from[0]; ap++) {
801                 size_t tlen = strlen(ap->from);
802
803                 if (same_param(ap->from, ep, tlen)) {
804                     _nc_STRCAT(dst, ap->to, MAX_TERMINFO_LENGTH);
805                     found = TRUE;
806                     break;
807                 }
808             }
809
810             if (!found)
811                 _nc_STRCAT(dst, ep, MAX_TERMINFO_LENGTH);
812             _nc_STRCAT(dst, ";", MAX_TERMINFO_LENGTH);
813         } while
814             ((ep = strtok((char *) 0, ";")));
815
816         dst[strlen(dst) - 1] = '\0';
817
818         result = dst;
819     }
820     return result;
821 }
822
823 static void
824 analyze_string(const char *name, const char *cap, TERMTYPE2 *tp)
825 {
826     char buf2[MAX_TERMINFO_LENGTH];
827     const char *sp;
828     const assoc *ap;
829     int tp_lines = tp->Numbers[2];
830
831     if (!VALID_STRING(cap))
832         return;
833     (void) printf("%s: ", name);
834
835     for (sp = cap; *sp; sp++) {
836         int i;
837         int csi;
838         size_t len = 0;
839         size_t next;
840         const char *expansion = 0;
841         char buf3[MAX_TERMINFO_LENGTH];
842
843         /* first, check other capabilities in this entry */
844         for (i = 0; i < STRCOUNT; i++) {
845             char *cp = tp->Strings[i];
846
847             /* don't use function-key capabilities */
848             if (strnames[i] == NULL)
849                 continue;
850             if (strnames[i][0] == 'k' && strnames[i][1] == 'f')
851                 continue;
852
853             if (VALID_STRING(cp) &&
854                 cp[0] != '\0' &&
855                 cp != cap) {
856                 len = strlen(cp);
857                 _nc_STRNCPY(buf2, sp, len);
858                 buf2[len] = '\0';
859
860                 if (_nc_capcmp(cp, buf2))
861                     continue;
862
863 #define ISRS(s) (!strncmp((s), "is", (size_t) 2) || !strncmp((s), "rs", (size_t) 2))
864                 /*
865                  * Theoretically we just passed the test for translation
866                  * (equality once the padding is stripped).  However, there
867                  * are a few more hoops that need to be jumped so that
868                  * identical pairs of initialization and reset strings
869                  * don't just refer to each other.
870                  */
871                 if (ISRS(name) || ISRS(strnames[i]))
872                     if (cap < cp)
873                         continue;
874 #undef ISRS
875
876                 expansion = strnames[i];
877                 break;
878             }
879         }
880
881         /* now check the standard capabilities */
882         if (!expansion) {
883             csi = skip_csi(sp);
884             for (ap = std_caps; ap->from[0]; ap++) {
885                 size_t adj = (size_t) (csi ? 2 : 0);
886
887                 len = strlen(ap->from);
888                 if (csi && skip_csi(ap->from) != csi)
889                     continue;
890                 if (len > adj
891                     && strncmp(ap->from + adj, sp + csi, len - adj) == 0) {
892                     expansion = ap->to;
893                     len -= adj;
894                     len += (size_t) csi;
895                     break;
896                 }
897             }
898         }
899
900         /* now check for standard-mode sequences */
901         if (!expansion
902             && (csi = skip_csi(sp)) != 0
903             && (len = (strspn) (sp + csi, "0123456789;"))
904             && (len < sizeof(buf3))
905             && (next = (size_t) csi + len)
906             && ((sp[next] == 'h') || (sp[next] == 'l'))) {
907
908             _nc_STRCPY(buf2,
909                        ((sp[next] == 'h')
910                         ? "ECMA+"
911                         : "ECMA-"),
912                        sizeof(buf2));
913             _nc_STRNCPY(buf3, sp + csi, len);
914             buf3[len] = '\0';
915
916             expansion = lookup_params(std_modes, buf2, buf3);
917         }
918
919         /* now check for private-mode sequences */
920         if (!expansion
921             && (csi = skip_csi(sp)) != 0
922             && sp[csi] == '?'
923             && (len = (strspn) (sp + csi + 1, "0123456789;"))
924             && (len < sizeof(buf3))
925             && (next = (size_t) csi + 1 + len)
926             && ((sp[next] == 'h') || (sp[next] == 'l'))) {
927
928             _nc_STRCPY(buf2,
929                        ((sp[next] == 'h')
930                         ? "DEC+"
931                         : "DEC-"),
932                        sizeof(buf2));
933             _nc_STRNCPY(buf3, sp + csi + 1, len);
934             buf3[len] = '\0';
935
936             expansion = lookup_params(private_modes, buf2, buf3);
937         }
938
939         /* now check for ECMA highlight sequences */
940         if (!expansion
941             && (csi = skip_csi(sp)) != 0
942             && (len = (strspn) (sp + csi, "0123456789;")) != 0
943             && (len < sizeof(buf3))
944             && (next = (size_t) csi + len)
945             && sp[next] == 'm') {
946
947             _nc_STRCPY(buf2, "SGR:", sizeof(buf2));
948             _nc_STRNCPY(buf3, sp + csi, len);
949             buf3[len] = '\0';
950             len += (size_t) csi + 1;
951
952             expansion = lookup_params(ecma_highlights, buf2, buf3);
953         }
954
955         if (!expansion
956             && (csi = skip_csi(sp)) != 0
957             && sp[csi] == 'm') {
958             len = (size_t) csi + 1;
959             _nc_STRCPY(buf2, "SGR:", sizeof(buf2));
960             _nc_STRCAT(buf2, ecma_highlights[0].to, sizeof(buf2));
961             expansion = buf2;
962         }
963
964         /* now check for scroll region reset */
965         if (!expansion
966             && (csi = skip_csi(sp)) != 0) {
967             if (sp[csi] == 'r') {
968                 expansion = "RSR";
969                 len = 1;
970             } else {
971                 _nc_SPRINTF(buf2, _nc_SLIMIT(sizeof(buf2)) "1;%dr", tp_lines);
972                 len = strlen(buf2);
973                 if (strncmp(buf2, sp + csi, len) == 0)
974                     expansion = "RSR";
975             }
976             len += (size_t) csi;
977         }
978
979         /* now check for home-down */
980         if (!expansion
981             && (csi = skip_csi(sp)) != 0) {
982             _nc_SPRINTF(buf2, _nc_SLIMIT(sizeof(buf2)) "%d;1H", tp_lines);
983             len = strlen(buf2);
984             if (strncmp(buf2, sp + csi, len) == 0) {
985                 expansion = "LL";
986             } else {
987                 _nc_SPRINTF(buf2, _nc_SLIMIT(sizeof(buf2)) "%dH", tp_lines);
988                 len = strlen(buf2);
989                 if (strncmp(buf2, sp + csi, len) == 0) {
990                     expansion = "LL";
991                 }
992             }
993             len += (size_t) csi;
994         }
995
996         /* now look at the expansion we got, if any */
997         if (expansion) {
998             printf("{%s}", expansion);
999             sp += len - 1;
1000         } else {
1001             /* couldn't match anything */
1002             buf2[0] = *sp;
1003             buf2[1] = '\0';
1004             fputs(TIC_EXPAND(buf2), stdout);
1005         }
1006     }
1007     putchar('\n');
1008 }
1009
1010 /***************************************************************************
1011  *
1012  * File comparison
1013  *
1014  ***************************************************************************/
1015
1016 static void
1017 file_comparison(int argc, char *argv[])
1018 {
1019 #define MAXCOMPARE      2
1020     /* someday we may allow comparisons on more files */
1021     int filecount = 0;
1022     ENTRY *heads[MAXCOMPARE];
1023     ENTRY *qp, *rp;
1024     int i, n;
1025
1026     memset(heads, 0, sizeof(heads));
1027     dump_init((char *) 0, F_LITERAL, S_TERMINFO,
1028               FALSE, 0, 65535, itrace, FALSE, FALSE, FALSE);
1029
1030     for (n = 0; n < argc && n < MAXCOMPARE; n++) {
1031         if (freopen(argv[n], "r", stdin) == 0)
1032             _nc_err_abort("Can't open %s", argv[n]);
1033
1034 #if NO_LEAKS
1035         entered[n].head = _nc_head;
1036         entered[n].tail = _nc_tail;
1037 #endif
1038         _nc_head = _nc_tail = 0;
1039
1040         /* parse entries out of the source file */
1041         _nc_set_source(argv[n]);
1042         _nc_read_entry_source(stdin, NULL, TRUE, literal, NULLHOOK);
1043
1044         if (itrace)
1045             (void) fprintf(stderr, "Resolving file %d...\n", n - 0);
1046
1047         /* maybe do use resolution */
1048         if (!_nc_resolve_uses2(!limited, literal)) {
1049             (void) fprintf(stderr,
1050                            "There are unresolved use entries in %s:\n",
1051                            argv[n]);
1052             for_entry_list(qp) {
1053                 if (qp->nuses) {
1054                     (void) fputs(qp->tterm.term_names, stderr);
1055                     (void) fputc('\n', stderr);
1056                 }
1057             }
1058             ExitProgram(EXIT_FAILURE);
1059         }
1060
1061         heads[filecount] = _nc_head;
1062         filecount++;
1063     }
1064
1065     /* OK, all entries are in core.  Ready to do the comparison */
1066     if (itrace)
1067         (void) fprintf(stderr, "Entries are now in core...\n");
1068
1069     /* The entry-matching loop. Sigh, this is intrinsically quadratic. */
1070     for (qp = heads[0]; qp; qp = qp->next) {
1071         for (rp = heads[1]; rp; rp = rp->next)
1072             if (_nc_entry_match(qp->tterm.term_names, rp->tterm.term_names)) {
1073                 if (qp->ncrosslinks < MAX_CROSSLINKS)
1074                     qp->crosslinks[qp->ncrosslinks] = rp;
1075                 qp->ncrosslinks++;
1076
1077                 if (rp->ncrosslinks < MAX_CROSSLINKS)
1078                     rp->crosslinks[rp->ncrosslinks] = qp;
1079                 rp->ncrosslinks++;
1080             }
1081     }
1082
1083     /* now we have two circular lists with crosslinks */
1084     if (itrace)
1085         (void) fprintf(stderr, "Name matches are done...\n");
1086
1087     for (qp = heads[0]; qp; qp = qp->next) {
1088         if (qp->ncrosslinks > 1) {
1089             (void) fprintf(stderr,
1090                            "%s in file 1 (%s) has %d matches in file 2 (%s):\n",
1091                            _nc_first_name(qp->tterm.term_names),
1092                            argv[0],
1093                            qp->ncrosslinks,
1094                            argv[1]);
1095             for (i = 0; i < qp->ncrosslinks; i++)
1096                 (void) fprintf(stderr,
1097                                "\t%s\n",
1098                                _nc_first_name((qp->crosslinks[i])->tterm.term_names));
1099         }
1100     }
1101
1102     for (rp = heads[1]; rp; rp = rp->next) {
1103         if (rp->ncrosslinks > 1) {
1104             (void) fprintf(stderr,
1105                            "%s in file 2 (%s) has %d matches in file 1 (%s):\n",
1106                            _nc_first_name(rp->tterm.term_names),
1107                            argv[1],
1108                            rp->ncrosslinks,
1109                            argv[0]);
1110             for (i = 0; i < rp->ncrosslinks; i++)
1111                 (void) fprintf(stderr,
1112                                "\t%s\n",
1113                                _nc_first_name((rp->crosslinks[i])->tterm.term_names));
1114         }
1115     }
1116
1117     (void) printf("In file 1 (%s) only:\n", argv[0]);
1118     for (qp = heads[0]; qp; qp = qp->next)
1119         if (qp->ncrosslinks == 0)
1120             (void) printf("\t%s\n",
1121                           _nc_first_name(qp->tterm.term_names));
1122
1123     (void) printf("In file 2 (%s) only:\n", argv[1]);
1124     for (rp = heads[1]; rp; rp = rp->next)
1125         if (rp->ncrosslinks == 0)
1126             (void) printf("\t%s\n",
1127                           _nc_first_name(rp->tterm.term_names));
1128
1129     (void) printf("The following entries are equivalent:\n");
1130     for (qp = heads[0]; qp; qp = qp->next) {
1131         if (qp->ncrosslinks == 1) {
1132             rp = qp->crosslinks[0];
1133
1134             repair_acsc(&qp->tterm);
1135             repair_acsc(&rp->tterm);
1136 #if NCURSES_XNAMES
1137             _nc_align_termtype(&qp->tterm, &rp->tterm);
1138 #endif
1139             if (entryeq(&qp->tterm, &rp->tterm) && useeq(qp, rp)) {
1140                 char name1[NAMESIZE], name2[NAMESIZE];
1141
1142                 canonical_name(qp->tterm.term_names, name1);
1143                 canonical_name(rp->tterm.term_names, name2);
1144
1145                 (void) printf("%s = %s\n", name1, name2);
1146             }
1147         }
1148     }
1149
1150     (void) printf("Differing entries:\n");
1151     termcount = 2;
1152     for (qp = heads[0]; qp; qp = qp->next) {
1153
1154         if (qp->ncrosslinks == 1) {
1155             rp = qp->crosslinks[0];
1156 #if NCURSES_XNAMES
1157             /* sorry - we have to do this on each pass */
1158             _nc_align_termtype(&qp->tterm, &rp->tterm);
1159 #endif
1160             if (!(entryeq(&qp->tterm, &rp->tterm) && useeq(qp, rp))) {
1161                 char name1[NAMESIZE], name2[NAMESIZE];
1162                 char *names[3];
1163
1164                 names[0] = name1;
1165                 names[1] = name2;
1166                 names[2] = 0;
1167
1168                 entries[0] = *qp;
1169                 entries[1] = *rp;
1170
1171                 canonical_name(qp->tterm.term_names, name1);
1172                 canonical_name(rp->tterm.term_names, name2);
1173
1174                 switch (compare) {
1175                 case C_DIFFERENCE:
1176                     show_comparing(names);
1177                     compare_entry(compare_predicate, &entries->tterm, quiet);
1178                     break;
1179
1180                 case C_COMMON:
1181                     show_comparing(names);
1182                     compare_entry(compare_predicate, &entries->tterm, quiet);
1183                     break;
1184
1185                 case C_NAND:
1186                     show_comparing(names);
1187                     compare_entry(compare_predicate, &entries->tterm, quiet);
1188                     break;
1189
1190                 }
1191             }
1192         }
1193     }
1194 }
1195
1196 static void
1197 usage(void)
1198 {
1199 #define DATA(s) s "\n"
1200     static const char head[] =
1201     {
1202         DATA("Usage: infocmp [options] [-A directory] [-B directory] [termname...]")
1203         DATA("")
1204         DATA("Options:")
1205     };
1206 #undef DATA
1207     /* length is given here so the compiler can make everything readonly */
1208 #define DATA(s) s
1209     static const char options[][46] =
1210     {
1211         "  -0    print single-row"
1212         ,"  -1    print single-column"
1213         ,"  -C    use termcap-names"
1214         ,"  -D    print database locations"
1215         ,"  -E    format output as C tables"
1216         ,"  -F    compare terminfo-files"
1217         ,"  -G    format %{number} to %'char'"
1218         ,"  -I    use terminfo-names"
1219         ,"  -K    use termcap-names and BSD syntax"
1220         ,"  -L    use long names"
1221         ,"  -R subset (see manpage)"
1222         ,"  -T    eliminate size limits (test)"
1223         ,"  -U    do not post-process entries"
1224         ,"  -V    print version"
1225         ,"  -W    wrap long strings per -w[n]"
1226 #if NCURSES_XNAMES
1227         ,"  -a    with -F, list commented-out caps"
1228 #endif
1229         ,"  -c    list common capabilities"
1230         ,"  -d    list different capabilities"
1231         ,"  -e    format output for C initializer"
1232         ,"  -f    with -1, format complex strings"
1233         ,"  -g    format %'char' to %{number}"
1234         ,"  -i    analyze initialization/reset"
1235         ,"  -l    output terminfo names"
1236         ,"  -n    list capabilities in neither"
1237         ,"  -p    ignore padding specifiers"
1238         ,"  -Q number  dump compiled description"
1239         ,"  -q    brief listing, removes headers"
1240         ,"  -r    with -C, output in termcap form"
1241         ,"  -r    with -F, resolve use-references"
1242         ,"  -s [d|i|l|c] sort fields"
1243 #if NCURSES_XNAMES
1244         ,"  -t    suppress commented-out capabilities"
1245 #endif
1246         ,"  -u    produce source with 'use='"
1247         ,"  -v number  (verbose)"
1248         ,"  -w number  (width)"
1249 #if NCURSES_XNAMES
1250         ,"  -x    unknown capabilities are user-defined"
1251 #endif
1252     };
1253 #undef DATA
1254     const size_t last = SIZEOF(options);
1255     const size_t left = (last + 1) / 2;
1256     size_t n;
1257
1258     fputs(head, stderr);
1259     for (n = 0; n < left; n++) {
1260         size_t m = n + left;
1261         if (m < last)
1262             fprintf(stderr, "%-40.40s%s\n", options[n], options[m]);
1263         else
1264             fprintf(stderr, "%s\n", options[n]);
1265     }
1266     ExitProgram(EXIT_FAILURE);
1267 }
1268
1269 static char *
1270 any_initializer(const char *fmt, const char *type)
1271 {
1272     static char *initializer;
1273     static size_t need;
1274     char *s;
1275
1276     if (initializer == 0) {
1277         need = (strlen(entries->tterm.term_names)
1278                 + strlen(type)
1279                 + strlen(fmt));
1280         initializer = (char *) malloc(need + 1);
1281         if (initializer == 0)
1282             failed("any_initializer");
1283     }
1284
1285     _nc_STRCPY(initializer, entries->tterm.term_names, need);
1286     for (s = initializer; *s != 0 && *s != '|'; s++) {
1287         if (!isalnum(UChar(*s)))
1288             *s = '_';
1289     }
1290     *s = 0;
1291     _nc_SPRINTF(s, _nc_SLIMIT(need) fmt, type);
1292     return initializer;
1293 }
1294
1295 static char *
1296 name_initializer(const char *type)
1297 {
1298     return any_initializer("_%s_data", type);
1299 }
1300
1301 static char *
1302 string_variable(const char *type)
1303 {
1304     return any_initializer("_s_%s", type);
1305 }
1306
1307 /* dump C initializers for the terminal type */
1308 static void
1309 dump_initializers(TERMTYPE2 *term)
1310 {
1311     unsigned n;
1312     const char *str = 0;
1313
1314     printf("\nstatic char %s[] = \"%s\";\n\n",
1315            name_initializer("alias"), entries->tterm.term_names);
1316
1317     for_each_string(n, term) {
1318         if (VALID_STRING(term->Strings[n])) {
1319             char buf[MAX_STRING], *sp, *tp;
1320
1321             tp = buf;
1322 #define TP_LIMIT        ((MAX_STRING - 5) - (size_t)(tp - buf))
1323             *tp++ = '"';
1324             for (sp = term->Strings[n];
1325                  *sp != 0 && TP_LIMIT > 2;
1326                  sp++) {
1327                 if (isascii(UChar(*sp))
1328                     && isprint(UChar(*sp))
1329                     && *sp != '\\'
1330                     && *sp != '"')
1331                     *tp++ = *sp;
1332                 else {
1333                     _nc_SPRINTF(tp, _nc_SLIMIT(TP_LIMIT) "\\%03o", UChar(*sp));
1334                     tp += 4;
1335                 }
1336             }
1337             *tp++ = '"';
1338             *tp = '\0';
1339             (void) printf("static char %-20s[] = %s;\n",
1340                           string_variable(ExtStrname(term, (int) n, strnames)),
1341                           buf);
1342         }
1343     }
1344     printf("\n");
1345
1346     (void) printf("static char %s[] = %s\n", name_initializer("bool"), L_CURL);
1347
1348     for_each_boolean(n, term) {
1349         switch ((int) (term->Booleans[n])) {
1350         case TRUE:
1351             str = "TRUE";
1352             break;
1353
1354         case FALSE:
1355             str = "FALSE";
1356             break;
1357
1358         case ABSENT_BOOLEAN:
1359             str = "ABSENT_BOOLEAN";
1360             break;
1361
1362         case CANCELLED_BOOLEAN:
1363             str = "CANCELLED_BOOLEAN";
1364             break;
1365         }
1366         (void) printf("\t/* %3u: %-8s */\t%s,\n",
1367                       n, ExtBoolname(term, (int) n, boolnames), str);
1368     }
1369     (void) printf("%s;\n", R_CURL);
1370
1371     (void) printf("static short %s[] = %s\n", name_initializer("number"), L_CURL);
1372
1373     for_each_number(n, term) {
1374         char buf[BUFSIZ];
1375         switch (term->Numbers[n]) {
1376         case ABSENT_NUMERIC:
1377             str = "ABSENT_NUMERIC";
1378             break;
1379         case CANCELLED_NUMERIC:
1380             str = "CANCELLED_NUMERIC";
1381             break;
1382         default:
1383             _nc_SPRINTF(buf, _nc_SLIMIT(sizeof(buf)) "%d", term->Numbers[n]);
1384             str = buf;
1385             break;
1386         }
1387         (void) printf("\t/* %3u: %-8s */\t%s,\n", n,
1388                       ExtNumname(term, (int) n, numnames), str);
1389     }
1390     (void) printf("%s;\n", R_CURL);
1391
1392     (void) printf("static char * %s[] = %s\n", name_initializer("string"), L_CURL);
1393
1394     for_each_string(n, term) {
1395
1396         if (term->Strings[n] == ABSENT_STRING)
1397             str = "ABSENT_STRING";
1398         else if (term->Strings[n] == CANCELLED_STRING)
1399             str = "CANCELLED_STRING";
1400         else {
1401             str = string_variable(ExtStrname(term, (int) n, strnames));
1402         }
1403         (void) printf("\t/* %3u: %-8s */\t%s,\n", n,
1404                       ExtStrname(term, (int) n, strnames), str);
1405     }
1406     (void) printf("%s;\n", R_CURL);
1407
1408 #if NCURSES_XNAMES
1409     if ((NUM_BOOLEANS(term) != BOOLCOUNT)
1410         || (NUM_NUMBERS(term) != NUMCOUNT)
1411         || (NUM_STRINGS(term) != STRCOUNT)) {
1412         (void) printf("static char * %s[] = %s\n",
1413                       name_initializer("string_ext"), L_CURL);
1414         for (n = BOOLCOUNT; n < NUM_BOOLEANS(term); ++n) {
1415             (void) printf("\t/* %3u: bool */\t\"%s\",\n",
1416                           n, ExtBoolname(term, (int) n, boolnames));
1417         }
1418         for (n = NUMCOUNT; n < NUM_NUMBERS(term); ++n) {
1419             (void) printf("\t/* %3u: num */\t\"%s\",\n",
1420                           n, ExtNumname(term, (int) n, numnames));
1421         }
1422         for (n = STRCOUNT; n < NUM_STRINGS(term); ++n) {
1423             (void) printf("\t/* %3u: str */\t\"%s\",\n",
1424                           n, ExtStrname(term, (int) n, strnames));
1425         }
1426         (void) printf("%s;\n", R_CURL);
1427     }
1428 #endif
1429 }
1430
1431 /* dump C initializers for the terminal type */
1432 static void
1433 dump_termtype(TERMTYPE2 *term)
1434 {
1435     (void) printf("\t%s\n\t\t%s,\n", L_CURL, name_initializer("alias"));
1436     (void) printf("\t\t(char *)0,\t/* pointer to string table */\n");
1437
1438     (void) printf("\t\t%s,\n", name_initializer("bool"));
1439     (void) printf("\t\t%s,\n", name_initializer("number"));
1440
1441     (void) printf("\t\t%s,\n", name_initializer("string"));
1442
1443 #if NCURSES_XNAMES
1444     (void) printf("#if NCURSES_XNAMES\n");
1445     (void) printf("\t\t(char *)0,\t/* pointer to extended string table */\n");
1446     (void) printf("\t\t%s,\t/* ...corresponding names */\n",
1447                   ((NUM_BOOLEANS(term) != BOOLCOUNT)
1448                    || (NUM_NUMBERS(term) != NUMCOUNT)
1449                    || (NUM_STRINGS(term) != STRCOUNT))
1450                   ? name_initializer("string_ext")
1451                   : "(char **)0");
1452
1453     (void) printf("\t\t%d,\t\t/* count total Booleans */\n", NUM_BOOLEANS(term));
1454     (void) printf("\t\t%d,\t\t/* count total Numbers */\n", NUM_NUMBERS(term));
1455     (void) printf("\t\t%d,\t\t/* count total Strings */\n", NUM_STRINGS(term));
1456
1457     (void) printf("\t\t%d,\t\t/* count extensions to Booleans */\n",
1458                   NUM_BOOLEANS(term) - BOOLCOUNT);
1459     (void) printf("\t\t%d,\t\t/* count extensions to Numbers */\n",
1460                   NUM_NUMBERS(term) - NUMCOUNT);
1461     (void) printf("\t\t%d,\t\t/* count extensions to Strings */\n",
1462                   NUM_STRINGS(term) - STRCOUNT);
1463
1464     (void) printf("#endif /* NCURSES_XNAMES */\n");
1465 #else
1466     (void) term;
1467 #endif /* NCURSES_XNAMES */
1468     (void) printf("\t%s\n", R_CURL);
1469 }
1470
1471 static int
1472 optarg_to_number(void)
1473 {
1474     char *temp = 0;
1475     long value = strtol(optarg, &temp, 0);
1476
1477     if (temp == 0 || temp == optarg || *temp != 0) {
1478         fprintf(stderr, "Expected a number, not \"%s\"\n", optarg);
1479         ExitProgram(EXIT_FAILURE);
1480     }
1481     return (int) value;
1482 }
1483
1484 static char *
1485 terminal_env(void)
1486 {
1487     char *terminal;
1488
1489     if ((terminal = getenv("TERM")) == 0) {
1490         (void) fprintf(stderr,
1491                        "%s: environment variable TERM not set\n",
1492                        _nc_progname);
1493         exit(EXIT_FAILURE);
1494     }
1495     return terminal;
1496 }
1497
1498 /*
1499  * Show the databases that infocmp knows about.  The location to which it writes is
1500  */
1501 static void
1502 show_databases(void)
1503 {
1504     DBDIRS state;
1505     int offset;
1506     const char *path2;
1507
1508     _nc_first_db(&state, &offset);
1509     while ((path2 = _nc_next_db(&state, &offset)) != 0) {
1510         printf("%s\n", path2);
1511     }
1512     _nc_last_db();
1513 }
1514
1515 /***************************************************************************
1516  *
1517  * Main sequence
1518  *
1519  ***************************************************************************/
1520
1521 #if NO_LEAKS
1522 #define MAIN_LEAKS() \
1523     _nc_free_termtype2(&entries[0].tterm); \
1524     _nc_free_termtype2(&entries[1].tterm); \
1525     free(myargv); \
1526     free(tfile); \
1527     free(tname)
1528 #else
1529 #define MAIN_LEAKS()            /* nothing */
1530 #endif
1531
1532 int
1533 main(int argc, char *argv[])
1534 {
1535     /* Avoid "local data >32k" error with mwcc */
1536     /* Also avoid overflowing smaller stacks on systems like AmigaOS */
1537     path *tfile = 0;
1538     char **tname = 0;
1539     size_t maxterms;
1540
1541     char **myargv;
1542
1543     char *firstdir, *restdir;
1544     int c;
1545     bool formatted = FALSE;
1546     bool filecompare = FALSE;
1547     int initdump = 0;
1548     bool init_analyze = FALSE;
1549     bool suppress_untranslatable = FALSE;
1550     int quickdump = 0;
1551     bool wrap_strings = FALSE;
1552
1553     /* where is the terminfo database location going to default to? */
1554     restdir = firstdir = 0;
1555
1556 #if NCURSES_XNAMES
1557     use_extended_names(FALSE);
1558 #endif
1559     _nc_strict_bsd = 0;
1560
1561     _nc_progname = _nc_rootname(argv[0]);
1562
1563     /* make sure we have enough space to add two terminal entries */
1564     myargv = typeCalloc(char *, (size_t) (argc + 3));
1565     if (myargv == 0)
1566         failed("myargv");
1567
1568     memcpy(myargv, argv, (sizeof(char *) * (size_t) argc));
1569     argv = myargv;
1570
1571     while ((c = getopt(argc,
1572                        argv,
1573                        "01A:aB:CcDdEeFfGgIiKLlnpQ:qR:rs:TtUuVv:Ww:x")) != -1) {
1574         switch (c) {
1575         case '0':
1576             mwidth = 65535;
1577             mheight = 1;
1578             break;
1579
1580         case '1':
1581             mwidth = 0;
1582             break;
1583
1584         case 'A':
1585             firstdir = optarg;
1586             break;
1587
1588 #if NCURSES_XNAMES
1589         case 'a':
1590             _nc_disable_period = TRUE;
1591             use_extended_names(TRUE);
1592             break;
1593 #endif
1594         case 'B':
1595             restdir = optarg;
1596             break;
1597
1598         case 'K':
1599             _nc_strict_bsd = 1;
1600             /* FALLTHRU */
1601         case 'C':
1602             outform = F_TERMCAP;
1603             tversion = "BSD";
1604             if (sortmode == S_DEFAULT)
1605                 sortmode = S_TERMCAP;
1606             break;
1607
1608         case 'D':
1609             show_databases();
1610             ExitProgram(EXIT_SUCCESS);
1611             break;
1612
1613         case 'c':
1614             compare = C_COMMON;
1615             break;
1616
1617         case 'd':
1618             compare = C_DIFFERENCE;
1619             break;
1620
1621         case 'E':
1622             initdump |= 2;
1623             break;
1624
1625         case 'e':
1626             initdump |= 1;
1627             break;
1628
1629         case 'F':
1630             filecompare = TRUE;
1631             break;
1632
1633         case 'f':
1634             formatted = TRUE;
1635             break;
1636
1637         case 'G':
1638             numbers = 1;
1639             break;
1640
1641         case 'g':
1642             numbers = -1;
1643             break;
1644
1645         case 'I':
1646             outform = F_TERMINFO;
1647             if (sortmode == S_DEFAULT)
1648                 sortmode = S_VARIABLE;
1649             tversion = 0;
1650             break;
1651
1652         case 'i':
1653             init_analyze = TRUE;
1654             break;
1655
1656         case 'L':
1657             outform = F_VARIABLE;
1658             if (sortmode == S_DEFAULT)
1659                 sortmode = S_VARIABLE;
1660             break;
1661
1662         case 'l':
1663             outform = F_TERMINFO;
1664             break;
1665
1666         case 'n':
1667             compare = C_NAND;
1668             break;
1669
1670         case 'p':
1671             ignorepads = TRUE;
1672             break;
1673
1674         case 'Q':
1675             quickdump = optarg_to_number();
1676             break;
1677
1678         case 'q':
1679             quiet = TRUE;
1680             s_absent = "-";
1681             s_cancel = "@";
1682             bool_sep = ", ";
1683             break;
1684
1685         case 'R':
1686             tversion = optarg;
1687             break;
1688
1689         case 'r':
1690             tversion = 0;
1691             break;
1692
1693         case 's':
1694             if (*optarg == 'd')
1695                 sortmode = S_NOSORT;
1696             else if (*optarg == 'i')
1697                 sortmode = S_TERMINFO;
1698             else if (*optarg == 'l')
1699                 sortmode = S_VARIABLE;
1700             else if (*optarg == 'c')
1701                 sortmode = S_TERMCAP;
1702             else {
1703                 (void) fprintf(stderr,
1704                                "%s: unknown sort mode\n",
1705                                _nc_progname);
1706                 ExitProgram(EXIT_FAILURE);
1707             }
1708             break;
1709
1710         case 'T':
1711             limited = FALSE;
1712             break;
1713
1714 #if NCURSES_XNAMES
1715         case 't':
1716             _nc_disable_period = FALSE;
1717             suppress_untranslatable = TRUE;
1718             break;
1719 #endif
1720
1721         case 'U':
1722             literal = TRUE;
1723             break;
1724
1725         case 'u':
1726             compare = C_USEALL;
1727             break;
1728
1729         case 'V':
1730             puts(curses_version());
1731             ExitProgram(EXIT_SUCCESS);
1732
1733         case 'v':
1734             itrace = (unsigned) optarg_to_number();
1735             use_verbosity(itrace);
1736             break;
1737
1738         case 'W':
1739             wrap_strings = TRUE;
1740             break;
1741
1742         case 'w':
1743             mwidth = optarg_to_number();
1744             break;
1745
1746 #if NCURSES_XNAMES
1747         case 'x':
1748             use_extended_names(TRUE);
1749             break;
1750 #endif
1751
1752         default:
1753             usage();
1754         }
1755     }
1756
1757     maxterms = (size_t) (argc + 2 - optind);
1758     if ((tfile = typeMalloc(path, maxterms)) == 0)
1759         failed("tfile");
1760     if ((tname = typeCalloc(char *, maxterms)) == 0)
1761           failed("tname");
1762     if ((entries = typeCalloc(ENTRY, maxterms)) == 0)
1763         failed("entries");
1764 #if NO_LEAKS
1765     if ((entered = typeCalloc(ENTERED, maxterms)) == 0)
1766         failed("entered");
1767 #endif
1768
1769     if (tfile == 0
1770         || tname == 0
1771         || entries == 0) {
1772         fprintf(stderr, "%s: not enough memory\n", _nc_progname);
1773         ExitProgram(EXIT_FAILURE);
1774     }
1775
1776     /* by default, sort by terminfo name */
1777     if (sortmode == S_DEFAULT)
1778         sortmode = S_TERMINFO;
1779
1780     /* make sure we have at least one terminal name to work with */
1781     if (optind >= argc)
1782         argv[argc++] = terminal_env();
1783
1784     /* if user is after a comparison, make sure we have two entries */
1785     if (compare != C_DEFAULT && optind >= argc - 1)
1786         argv[argc++] = terminal_env();
1787
1788     /* exactly one terminal name with no options means display it */
1789     /* exactly two terminal names with no options means do -d */
1790     if (compare == C_DEFAULT) {
1791         switch (argc - optind) {
1792         default:
1793             fprintf(stderr, "%s: too many names to compare\n", _nc_progname);
1794             ExitProgram(EXIT_FAILURE);
1795         case 1:
1796             break;
1797         case 2:
1798             compare = C_DIFFERENCE;
1799             break;
1800         }
1801     }
1802
1803     /* set up for display */
1804     dump_init(tversion, outform, sortmode,
1805               wrap_strings, mwidth, mheight, itrace,
1806               formatted, FALSE, quickdump);
1807
1808     if (!filecompare) {
1809         /* grab the entries */
1810         termcount = 0;
1811         for (; optind < argc; optind++) {
1812             const char *directory = termcount ? restdir : firstdir;
1813             int status;
1814
1815             tname[termcount] = argv[optind];
1816
1817             if (directory) {
1818 #if NCURSES_USE_DATABASE
1819 #if MIXEDCASE_FILENAMES
1820 #define LEAF_FMT "%c"
1821 #else
1822 #define LEAF_FMT "%02x"
1823 #endif
1824                 _nc_SPRINTF(tfile[termcount],
1825                             _nc_SLIMIT(sizeof(path))
1826                             "%s/" LEAF_FMT "/%s",
1827                             directory,
1828                             UChar(*argv[optind]), argv[optind]);
1829                 if (itrace)
1830                     (void) fprintf(stderr,
1831                                    "%s: reading entry %s from file %s\n",
1832                                    _nc_progname,
1833                                    argv[optind], tfile[termcount]);
1834
1835                 status = _nc_read_file_entry(tfile[termcount],
1836                                              &entries[termcount].tterm);
1837 #else
1838                 (void) fprintf(stderr, "%s: terminfo files not supported\n",
1839                                _nc_progname);
1840                 MAIN_LEAKS();
1841                 ExitProgram(EXIT_FAILURE);
1842 #endif
1843             } else {
1844                 if (itrace)
1845                     (void) fprintf(stderr,
1846                                    "%s: reading entry %s from database\n",
1847                                    _nc_progname,
1848                                    tname[termcount]);
1849
1850                 status = _nc_read_entry2(tname[termcount],
1851                                          tfile[termcount],
1852                                          &entries[termcount].tterm);
1853             }
1854
1855             if (status <= 0) {
1856                 (void) fprintf(stderr,
1857                                "%s: couldn't open terminfo file %s.\n",
1858                                _nc_progname,
1859                                tfile[termcount]);
1860                 MAIN_LEAKS();
1861                 ExitProgram(EXIT_FAILURE);
1862             }
1863             repair_acsc(&entries[termcount].tterm);
1864             termcount++;
1865         }
1866
1867 #if NCURSES_XNAMES
1868         if (termcount > 1)
1869             _nc_align_termtype(&entries[0].tterm, &entries[1].tterm);
1870 #endif
1871
1872         /* dump as C initializer for the terminal type */
1873         if (initdump) {
1874             if (initdump & 1)
1875                 dump_termtype(&entries[0].tterm);
1876             if (initdump & 2)
1877                 dump_initializers(&entries[0].tterm);
1878         }
1879
1880         /* analyze the init strings */
1881         else if (init_analyze) {
1882 #undef CUR
1883 #define CUR     entries[0].tterm.
1884             analyze_string("is1", init_1string, &entries[0].tterm);
1885             analyze_string("is2", init_2string, &entries[0].tterm);
1886             analyze_string("is3", init_3string, &entries[0].tterm);
1887             analyze_string("rs1", reset_1string, &entries[0].tterm);
1888             analyze_string("rs2", reset_2string, &entries[0].tterm);
1889             analyze_string("rs3", reset_3string, &entries[0].tterm);
1890             analyze_string("smcup", enter_ca_mode, &entries[0].tterm);
1891             analyze_string("rmcup", exit_ca_mode, &entries[0].tterm);
1892             analyze_string("smkx", keypad_xmit, &entries[0].tterm);
1893             analyze_string("rmkx", keypad_local, &entries[0].tterm);
1894 #undef CUR
1895         } else {
1896             int i;
1897             int len;
1898
1899             /*
1900              * Here's where the real work gets done
1901              */
1902             switch (compare) {
1903             case C_DEFAULT:
1904                 if (itrace)
1905                     (void) fprintf(stderr,
1906                                    "%s: about to dump %s\n",
1907                                    _nc_progname,
1908                                    tname[0]);
1909                 if (!quiet)
1910                     (void)
1911                         printf("#\tReconstructed via infocmp from file: %s\n",
1912                                tfile[0]);
1913                 dump_entry(&entries[0].tterm,
1914                            suppress_untranslatable,
1915                            limited,
1916                            numbers,
1917                            NULL);
1918                 len = show_entry();
1919                 if (itrace)
1920                     (void) fprintf(stderr, "%s: length %d\n", _nc_progname, len);
1921                 break;
1922
1923             case C_DIFFERENCE:
1924                 show_comparing(tname);
1925                 compare_entry(compare_predicate, &entries->tterm, quiet);
1926                 break;
1927
1928             case C_COMMON:
1929                 show_comparing(tname);
1930                 compare_entry(compare_predicate, &entries->tterm, quiet);
1931                 break;
1932
1933             case C_NAND:
1934                 show_comparing(tname);
1935                 compare_entry(compare_predicate, &entries->tterm, quiet);
1936                 break;
1937
1938             case C_USEALL:
1939                 if (itrace)
1940                     (void) fprintf(stderr, "%s: dumping use entry\n", _nc_progname);
1941                 dump_entry(&entries[0].tterm,
1942                            suppress_untranslatable,
1943                            limited,
1944                            numbers,
1945                            use_predicate);
1946                 for (i = 1; i < termcount; i++)
1947                     dump_uses(tname[i], !(outform == F_TERMCAP
1948                                           || outform == F_TCONVERR));
1949                 len = show_entry();
1950                 if (itrace)
1951                     (void) fprintf(stderr, "%s: length %d\n", _nc_progname, len);
1952                 break;
1953             }
1954         }
1955     } else if (compare == C_USEALL) {
1956         (void) fprintf(stderr, "Sorry, -u doesn't work with -F\n");
1957     } else if (compare == C_DEFAULT) {
1958         (void) fprintf(stderr, "Use `tic -[CI] <file>' for this.\n");
1959     } else if (argc - optind != 2) {
1960         (void) fprintf(stderr,
1961                        "File comparison needs exactly two file arguments.\n");
1962     } else {
1963         file_comparison(argc - optind, argv + optind);
1964     }
1965
1966     MAIN_LEAKS();
1967     ExitProgram(EXIT_SUCCESS);
1968 }
1969
1970 /* infocmp.c ends here */