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