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