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