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