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