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