]> ncurses.scripts.mit.edu Git - ncurses.git/blob - progs/infocmp.c
ncurses 5.9 - patch 20120107
[ncurses.git] / progs / infocmp.c
1 /****************************************************************************
2  * Copyright (c) 1998-2010,2011 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  *              and Thomas E Dickey
39  */
40
41 #include <progs.priv.h>
42
43 #include <dump_entry.h>
44
45 MODULE_ID("$Id: infocmp.c,v 1.110 2011/12/17 23:59:50 tom Exp $")
46
47 #define L_CURL "{"
48 #define R_CURL "}"
49
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 ENTRY *entries;          /* terminfo entries */
64 static int termcount;           /* count of terminal entries */
65
66 static bool limited = TRUE;     /* "-r" option is not set */
67 static bool quiet = FALSE;
68 static bool literal = FALSE;
69 static const char *bool_sep = ":";
70 static const char *s_absent = "NULL";
71 static const char *s_cancel = "NULL";
72 static const char *tversion;    /* terminfo version selected */
73 static unsigned itrace;         /* trace flag for debugging */
74 static int mwidth = 60;
75 static int mheight = 65535;
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     free(entries);
100     _nc_free_tic(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     unsigned 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     unsigned 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, size_t 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     char *result = 0;
573     const char *ep = strtok(src, ";");
574
575     if (ep != 0) {
576         const assoc *ap;
577
578         do {
579             bool found = FALSE;
580
581             for (ap = table; ap->from; ap++) {
582                 size_t tlen = strlen(ap->from);
583
584                 if (same_param(ap->from, ep, tlen)) {
585                     (void) strcat(dst, ap->to);
586                     found = TRUE;
587                     break;
588                 }
589             }
590
591             if (!found)
592                 (void) strcat(dst, ep);
593             (void) strcat(dst, ";");
594         } while
595             ((ep = strtok((char *) 0, ";")));
596
597         dst[strlen(dst) - 1] = '\0';
598
599         result = dst;
600     }
601     return result;
602 }
603
604 static void
605 analyze_string(const char *name, const char *cap, TERMTYPE *tp)
606 {
607     char buf2[MAX_TERMINFO_LENGTH];
608     const char *sp;
609     const assoc *ap;
610     int tp_lines = tp->Numbers[2];
611
612     if (cap == ABSENT_STRING || cap == CANCELLED_STRING)
613         return;
614     (void) printf("%s: ", name);
615
616     for (sp = cap; *sp; sp++) {
617         int i;
618         int csi;
619         size_t len = 0;
620         size_t next;
621         const char *expansion = 0;
622         char buf3[MAX_TERMINFO_LENGTH];
623
624         /* first, check other capabilities in this entry */
625         for (i = 0; i < STRCOUNT; i++) {
626             char *cp = tp->Strings[i];
627
628             /* don't use soft-key capabilities */
629             if (strnames[i][0] == 'k' && strnames[i][0] == 'f')
630                 continue;
631
632             if (cp != ABSENT_STRING && cp != CANCELLED_STRING && cp[0] && cp
633                 != cap) {
634                 len = strlen(cp);
635                 (void) strncpy(buf2, sp, len);
636                 buf2[len] = '\0';
637
638                 if (_nc_capcmp(cp, buf2))
639                     continue;
640
641 #define ISRS(s) (!strncmp((s), "is", 2) || !strncmp((s), "rs", 2))
642                 /*
643                  * Theoretically we just passed the test for translation
644                  * (equality once the padding is stripped).  However, there
645                  * are a few more hoops that need to be jumped so that
646                  * identical pairs of initialization and reset strings
647                  * don't just refer to each other.
648                  */
649                 if (ISRS(name) || ISRS(strnames[i]))
650                     if (cap < cp)
651                         continue;
652 #undef ISRS
653
654                 expansion = strnames[i];
655                 break;
656             }
657         }
658
659         /* now check the standard capabilities */
660         if (!expansion) {
661             csi = skip_csi(sp);
662             for (ap = std_caps; ap->from; ap++) {
663                 size_t adj = (size_t) (csi ? 2 : 0);
664
665                 len = strlen(ap->from);
666                 if (csi && skip_csi(ap->from) != csi)
667                     continue;
668                 if (len > adj
669                     && strncmp(ap->from + adj, sp + csi, len - adj) == 0) {
670                     expansion = ap->to;
671                     len -= adj;
672                     len += (size_t) csi;
673                     break;
674                 }
675             }
676         }
677
678         /* now check for standard-mode sequences */
679         if (!expansion
680             && (csi = skip_csi(sp)) != 0
681             && (len = strspn(sp + csi, "0123456789;"))
682             && (len < sizeof(buf3))
683             && (next = (size_t) csi + len)
684             && ((sp[next] == 'h') || (sp[next] == 'l'))) {
685
686             (void) strcpy(buf2, (sp[next] == 'h') ? "ECMA+" : "ECMA-");
687             (void) strncpy(buf3, sp + csi, len);
688             buf3[len] = '\0';
689             len += (size_t) csi + 1;
690
691             expansion = lookup_params(std_modes, buf2, buf3);
692         }
693
694         /* now check for private-mode sequences */
695         if (!expansion
696             && (csi = skip_csi(sp)) != 0
697             && sp[csi] == '?'
698             && (len = strspn(sp + csi + 1, "0123456789;"))
699             && (len < sizeof(buf3))
700             && (next = (size_t) csi + 1 + len)
701             && ((sp[next] == 'h') || (sp[next] == 'l'))) {
702
703             (void) strcpy(buf2, (sp[next] == 'h') ? "DEC+" : "DEC-");
704             (void) strncpy(buf3, sp + csi + 1, len);
705             buf3[len] = '\0';
706             len += (size_t) csi + 2;
707
708             expansion = lookup_params(private_modes, buf2, buf3);
709         }
710
711         /* now check for ECMA highlight sequences */
712         if (!expansion
713             && (csi = skip_csi(sp)) != 0
714             && (len = strspn(sp + csi, "0123456789;")) != 0
715             && (len < sizeof(buf3))
716             && (next = (size_t) csi + len)
717             && sp[next] == 'm') {
718
719             (void) strcpy(buf2, "SGR:");
720             (void) strncpy(buf3, sp + csi, len);
721             buf3[len] = '\0';
722             len += (size_t) csi + 1;
723
724             expansion = lookup_params(ecma_highlights, buf2, buf3);
725         }
726
727         if (!expansion
728             && (csi = skip_csi(sp)) != 0
729             && sp[csi] == 'm') {
730             len = (size_t) csi + 1;
731             (void) strcpy(buf2, "SGR:");
732             strcat(buf2, ecma_highlights[0].to);
733             expansion = buf2;
734         }
735
736         /* now check for scroll region reset */
737         if (!expansion
738             && (csi = skip_csi(sp)) != 0) {
739             if (sp[csi] == 'r') {
740                 expansion = "RSR";
741                 len = 1;
742             } else {
743                 (void) sprintf(buf2, "1;%dr", tp_lines);
744                 len = strlen(buf2);
745                 if (strncmp(buf2, sp + csi, len) == 0)
746                     expansion = "RSR";
747             }
748             len += (size_t) csi;
749         }
750
751         /* now check for home-down */
752         if (!expansion
753             && (csi = skip_csi(sp)) != 0) {
754             (void) sprintf(buf2, "%d;1H", tp_lines);
755             len = strlen(buf2);
756             if (strncmp(buf2, sp + csi, len) == 0) {
757                 expansion = "LL";
758             } else {
759                 (void) sprintf(buf2, "%dH", tp_lines);
760                 len = strlen(buf2);
761                 if (strncmp(buf2, sp + csi, len) == 0) {
762                     expansion = "LL";
763                 }
764             }
765             len += (size_t) csi;
766         }
767
768         /* now look at the expansion we got, if any */
769         if (expansion) {
770             printf("{%s}", expansion);
771             sp += len - 1;
772         } else {
773             /* couldn't match anything */
774             buf2[0] = *sp;
775             buf2[1] = '\0';
776             fputs(TIC_EXPAND(buf2), stdout);
777         }
778     }
779     putchar('\n');
780 }
781
782 /***************************************************************************
783  *
784  * File comparison
785  *
786  ***************************************************************************/
787
788 static void
789 file_comparison(int argc, char *argv[])
790 {
791 #define MAXCOMPARE      2
792     /* someday we may allow comparisons on more files */
793     int filecount = 0;
794     ENTRY *heads[MAXCOMPARE];
795     ENTRY *qp, *rp;
796     int i, n;
797
798     memset(heads, 0, sizeof(heads));
799     dump_init((char *) 0, F_LITERAL, S_TERMINFO, 0, 65535, itrace, FALSE);
800
801     for (n = 0; n < argc && n < MAXCOMPARE; n++) {
802         if (freopen(argv[n], "r", stdin) == 0)
803             _nc_err_abort("Can't open %s", argv[n]);
804
805         _nc_head = _nc_tail = 0;
806
807         /* parse entries out of the source file */
808         _nc_set_source(argv[n]);
809         _nc_read_entry_source(stdin, NULL, TRUE, literal, NULLHOOK);
810
811         if (itrace)
812             (void) fprintf(stderr, "Resolving file %d...\n", n - 0);
813
814         /* maybe do use resolution */
815         if (!_nc_resolve_uses2(!limited, literal)) {
816             (void) fprintf(stderr,
817                            "There are unresolved use entries in %s:\n",
818                            argv[n]);
819             for_entry_list(qp) {
820                 if (qp->nuses) {
821                     (void) fputs(qp->tterm.term_names, stderr);
822                     (void) fputc('\n', stderr);
823                 }
824             }
825             ExitProgram(EXIT_FAILURE);
826         }
827
828         heads[filecount] = _nc_head;
829         filecount++;
830     }
831
832     /* OK, all entries are in core.  Ready to do the comparison */
833     if (itrace)
834         (void) fprintf(stderr, "Entries are now in core...\n");
835
836     /* The entry-matching loop. Sigh, this is intrinsically quadratic. */
837     for (qp = heads[0]; qp; qp = qp->next) {
838         for (rp = heads[1]; rp; rp = rp->next)
839             if (_nc_entry_match(qp->tterm.term_names, rp->tterm.term_names)) {
840                 if (qp->ncrosslinks < MAX_CROSSLINKS)
841                     qp->crosslinks[qp->ncrosslinks] = rp;
842                 qp->ncrosslinks++;
843
844                 if (rp->ncrosslinks < MAX_CROSSLINKS)
845                     rp->crosslinks[rp->ncrosslinks] = qp;
846                 rp->ncrosslinks++;
847             }
848     }
849
850     /* now we have two circular lists with crosslinks */
851     if (itrace)
852         (void) fprintf(stderr, "Name matches are done...\n");
853
854     for (qp = heads[0]; qp; qp = qp->next) {
855         if (qp->ncrosslinks > 1) {
856             (void) fprintf(stderr,
857                            "%s in file 1 (%s) has %d matches in file 2 (%s):\n",
858                            _nc_first_name(qp->tterm.term_names),
859                            argv[0],
860                            qp->ncrosslinks,
861                            argv[1]);
862             for (i = 0; i < qp->ncrosslinks; i++)
863                 (void) fprintf(stderr,
864                                "\t%s\n",
865                                _nc_first_name((qp->crosslinks[i])->tterm.term_names));
866         }
867     }
868
869     for (rp = heads[1]; rp; rp = rp->next) {
870         if (rp->ncrosslinks > 1) {
871             (void) fprintf(stderr,
872                            "%s in file 2 (%s) has %d matches in file 1 (%s):\n",
873                            _nc_first_name(rp->tterm.term_names),
874                            argv[1],
875                            rp->ncrosslinks,
876                            argv[0]);
877             for (i = 0; i < rp->ncrosslinks; i++)
878                 (void) fprintf(stderr,
879                                "\t%s\n",
880                                _nc_first_name((rp->crosslinks[i])->tterm.term_names));
881         }
882     }
883
884     (void) printf("In file 1 (%s) only:\n", argv[0]);
885     for (qp = heads[0]; qp; qp = qp->next)
886         if (qp->ncrosslinks == 0)
887             (void) printf("\t%s\n",
888                           _nc_first_name(qp->tterm.term_names));
889
890     (void) printf("In file 2 (%s) only:\n", argv[1]);
891     for (rp = heads[1]; rp; rp = rp->next)
892         if (rp->ncrosslinks == 0)
893             (void) printf("\t%s\n",
894                           _nc_first_name(rp->tterm.term_names));
895
896     (void) printf("The following entries are equivalent:\n");
897     for (qp = heads[0]; qp; qp = qp->next) {
898         if (qp->ncrosslinks == 1) {
899             rp = qp->crosslinks[0];
900
901             repair_acsc(&qp->tterm);
902             repair_acsc(&rp->tterm);
903 #if NCURSES_XNAMES
904             _nc_align_termtype(&qp->tterm, &rp->tterm);
905 #endif
906             if (entryeq(&qp->tterm, &rp->tterm) && useeq(qp, rp)) {
907                 char name1[NAMESIZE], name2[NAMESIZE];
908
909                 (void) canonical_name(qp->tterm.term_names, name1);
910                 (void) canonical_name(rp->tterm.term_names, name2);
911
912                 (void) printf("%s = %s\n", name1, name2);
913             }
914         }
915     }
916
917     (void) printf("Differing entries:\n");
918     termcount = 2;
919     for (qp = heads[0]; qp; qp = qp->next) {
920
921         if (qp->ncrosslinks == 1) {
922             rp = qp->crosslinks[0];
923 #if NCURSES_XNAMES
924             /* sorry - we have to do this on each pass */
925             _nc_align_termtype(&qp->tterm, &rp->tterm);
926 #endif
927             if (!(entryeq(&qp->tterm, &rp->tterm) && useeq(qp, rp))) {
928                 char name1[NAMESIZE], name2[NAMESIZE];
929
930                 entries[0] = *qp;
931                 entries[1] = *rp;
932
933                 (void) canonical_name(qp->tterm.term_names, name1);
934                 (void) canonical_name(rp->tterm.term_names, name2);
935
936                 switch (compare) {
937                 case C_DIFFERENCE:
938                     if (itrace)
939                         (void) fprintf(stderr,
940                                        "%s: dumping differences\n",
941                                        _nc_progname);
942                     (void) printf("comparing %s to %s.\n", name1, name2);
943                     compare_entry(compare_predicate, &entries->tterm, quiet);
944                     break;
945
946                 case C_COMMON:
947                     if (itrace)
948                         (void) fprintf(stderr,
949                                        "%s: dumping common capabilities\n",
950                                        _nc_progname);
951                     (void) printf("comparing %s to %s.\n", name1, name2);
952                     compare_entry(compare_predicate, &entries->tterm, quiet);
953                     break;
954
955                 case C_NAND:
956                     if (itrace)
957                         (void) fprintf(stderr,
958                                        "%s: dumping differences\n",
959                                        _nc_progname);
960                     (void) printf("comparing %s to %s.\n", name1, name2);
961                     compare_entry(compare_predicate, &entries->tterm, quiet);
962                     break;
963
964                 }
965             }
966         }
967     }
968 }
969
970 static void
971 usage(void)
972 {
973     static const char *tbl[] =
974     {
975         "Usage: infocmp [options] [-A directory] [-B directory] [termname...]"
976         ,""
977         ,"Options:"
978         ,"  -0    print single-row"
979         ,"  -1    print single-column"
980         ,"  -K    use termcap-names and BSD syntax"
981         ,"  -C    use termcap-names"
982         ,"  -F    compare terminfo-files"
983         ,"  -I    use terminfo-names"
984         ,"  -L    use long names"
985         ,"  -R subset (see manpage)"
986         ,"  -T    eliminate size limits (test)"
987         ,"  -U    eliminate post-processing of entries"
988         ,"  -V    print version"
989 #if NCURSES_XNAMES
990         ,"  -a    with -F, list commented-out caps"
991 #endif
992         ,"  -c    list common capabilities"
993         ,"  -d    list different capabilities"
994         ,"  -e    format output for C initializer"
995         ,"  -E    format output as C tables"
996         ,"  -f    with -1, format complex strings"
997         ,"  -G    format %{number} to %'char'"
998         ,"  -g    format %'char' to %{number}"
999         ,"  -i    analyze initialization/reset"
1000         ,"  -l    output terminfo names"
1001         ,"  -n    list capabilities in neither"
1002         ,"  -p    ignore padding specifiers"
1003         ,"  -q    brief listing, removes headers"
1004         ,"  -r    with -C, output in termcap form"
1005         ,"  -r    with -F, resolve use-references"
1006         ,"  -s [d|i|l|c] sort fields"
1007 #if NCURSES_XNAMES
1008         ,"  -t    suppress commented-out capabilities"
1009 #endif
1010         ,"  -u    produce source with 'use='"
1011         ,"  -v number  (verbose)"
1012         ,"  -w number  (width)"
1013 #if NCURSES_XNAMES
1014         ,"  -x    treat unknown capabilities as user-defined"
1015 #endif
1016     };
1017     const size_t first = 3;
1018     const size_t last = SIZEOF(tbl);
1019     const size_t left = (last - first + 1) / 2 + first;
1020     size_t n;
1021
1022     for (n = 0; n < left; n++) {
1023         size_t m = (n < first) ? last : n + left - first;
1024         if (m < last)
1025             fprintf(stderr, "%-40.40s%s\n", tbl[n], tbl[m]);
1026         else
1027             fprintf(stderr, "%s\n", tbl[n]);
1028     }
1029     ExitProgram(EXIT_FAILURE);
1030 }
1031
1032 static char *
1033 any_initializer(const char *fmt, const char *type)
1034 {
1035     static char *initializer;
1036     char *s;
1037
1038     if (initializer == 0)
1039         initializer = (char *) malloc(strlen(entries->tterm.term_names) +
1040                                       strlen(type) + strlen(fmt));
1041
1042     (void) strcpy(initializer, entries->tterm.term_names);
1043     for (s = initializer; *s != 0 && *s != '|'; s++) {
1044         if (!isalnum(UChar(*s)))
1045             *s = '_';
1046     }
1047     *s = 0;
1048     (void) sprintf(s, fmt, type);
1049     return initializer;
1050 }
1051
1052 static char *
1053 name_initializer(const char *type)
1054 {
1055     return any_initializer("_%s_data", type);
1056 }
1057
1058 static char *
1059 string_variable(const char *type)
1060 {
1061     return any_initializer("_s_%s", type);
1062 }
1063
1064 /* dump C initializers for the terminal type */
1065 static void
1066 dump_initializers(TERMTYPE *term)
1067 {
1068     unsigned n;
1069     const char *str = 0;
1070
1071     printf("\nstatic char %s[] = \"%s\";\n\n",
1072            name_initializer("alias"), entries->tterm.term_names);
1073
1074     for_each_string(n, term) {
1075         char buf[MAX_STRING], *sp, *tp;
1076
1077         if (VALID_STRING(term->Strings[n])) {
1078             tp = buf;
1079             *tp++ = '"';
1080             for (sp = term->Strings[n];
1081                  *sp != 0 && (tp - buf) < MAX_STRING - 6;
1082                  sp++) {
1083                 if (isascii(UChar(*sp))
1084                     && isprint(UChar(*sp))
1085                     && *sp != '\\'
1086                     && *sp != '"')
1087                     *tp++ = *sp;
1088                 else {
1089                     (void) sprintf(tp, "\\%03o", UChar(*sp));
1090                     tp += 4;
1091                 }
1092             }
1093             *tp++ = '"';
1094             *tp = '\0';
1095             (void) printf("static char %-20s[] = %s;\n",
1096                           string_variable(ExtStrname(term, (int) n, strnames)),
1097                           buf);
1098         }
1099     }
1100     printf("\n");
1101
1102     (void) printf("static char %s[] = %s\n", name_initializer("bool"), L_CURL);
1103
1104     for_each_boolean(n, term) {
1105         switch ((int) (term->Booleans[n])) {
1106         case TRUE:
1107             str = "TRUE";
1108             break;
1109
1110         case FALSE:
1111             str = "FALSE";
1112             break;
1113
1114         case ABSENT_BOOLEAN:
1115             str = "ABSENT_BOOLEAN";
1116             break;
1117
1118         case CANCELLED_BOOLEAN:
1119             str = "CANCELLED_BOOLEAN";
1120             break;
1121         }
1122         (void) printf("\t/* %3u: %-8s */\t%s,\n",
1123                       n, ExtBoolname(term, (int) n, boolnames), str);
1124     }
1125     (void) printf("%s;\n", R_CURL);
1126
1127     (void) printf("static short %s[] = %s\n", name_initializer("number"), L_CURL);
1128
1129     for_each_number(n, term) {
1130         char buf[BUFSIZ];
1131         switch (term->Numbers[n]) {
1132         case ABSENT_NUMERIC:
1133             str = "ABSENT_NUMERIC";
1134             break;
1135         case CANCELLED_NUMERIC:
1136             str = "CANCELLED_NUMERIC";
1137             break;
1138         default:
1139             sprintf(buf, "%d", term->Numbers[n]);
1140             str = buf;
1141             break;
1142         }
1143         (void) printf("\t/* %3u: %-8s */\t%s,\n", n,
1144                       ExtNumname(term, (int) n, numnames), str);
1145     }
1146     (void) printf("%s;\n", R_CURL);
1147
1148     (void) printf("static char * %s[] = %s\n", name_initializer("string"), L_CURL);
1149
1150     for_each_string(n, term) {
1151
1152         if (term->Strings[n] == ABSENT_STRING)
1153             str = "ABSENT_STRING";
1154         else if (term->Strings[n] == CANCELLED_STRING)
1155             str = "CANCELLED_STRING";
1156         else {
1157             str = string_variable(ExtStrname(term, (int) n, strnames));
1158         }
1159         (void) printf("\t/* %3u: %-8s */\t%s,\n", n,
1160                       ExtStrname(term, (int) n, strnames), str);
1161     }
1162     (void) printf("%s;\n", R_CURL);
1163
1164 #if NCURSES_XNAMES
1165     if ((NUM_BOOLEANS(term) != BOOLCOUNT)
1166         || (NUM_NUMBERS(term) != NUMCOUNT)
1167         || (NUM_STRINGS(term) != STRCOUNT)) {
1168         (void) printf("static char * %s[] = %s\n",
1169                       name_initializer("string_ext"), L_CURL);
1170         for (n = BOOLCOUNT; n < NUM_BOOLEANS(term); ++n) {
1171             (void) printf("\t/* %3u: bool */\t\"%s\",\n",
1172                           n, ExtBoolname(term, (int) n, boolnames));
1173         }
1174         for (n = NUMCOUNT; n < NUM_NUMBERS(term); ++n) {
1175             (void) printf("\t/* %3u: num */\t\"%s\",\n",
1176                           n, ExtNumname(term, (int) n, numnames));
1177         }
1178         for (n = STRCOUNT; n < NUM_STRINGS(term); ++n) {
1179             (void) printf("\t/* %3u: str */\t\"%s\",\n",
1180                           n, ExtStrname(term, (int) n, strnames));
1181         }
1182         (void) printf("%s;\n", R_CURL);
1183     }
1184 #endif
1185 }
1186
1187 /* dump C initializers for the terminal type */
1188 static void
1189 dump_termtype(TERMTYPE *term)
1190 {
1191     (void) printf("\t%s\n\t\t%s,\n", L_CURL, name_initializer("alias"));
1192     (void) printf("\t\t(char *)0,\t/* pointer to string table */\n");
1193
1194     (void) printf("\t\t%s,\n", name_initializer("bool"));
1195     (void) printf("\t\t%s,\n", name_initializer("number"));
1196
1197     (void) printf("\t\t%s,\n", name_initializer("string"));
1198
1199 #if NCURSES_XNAMES
1200     (void) printf("#if NCURSES_XNAMES\n");
1201     (void) printf("\t\t(char *)0,\t/* pointer to extended string table */\n");
1202     (void) printf("\t\t%s,\t/* ...corresponding names */\n",
1203                   ((NUM_BOOLEANS(term) != BOOLCOUNT)
1204                    || (NUM_NUMBERS(term) != NUMCOUNT)
1205                    || (NUM_STRINGS(term) != STRCOUNT))
1206                   ? name_initializer("string_ext")
1207                   : "(char **)0");
1208
1209     (void) printf("\t\t%d,\t\t/* count total Booleans */\n", NUM_BOOLEANS(term));
1210     (void) printf("\t\t%d,\t\t/* count total Numbers */\n", NUM_NUMBERS(term));
1211     (void) printf("\t\t%d,\t\t/* count total Strings */\n", NUM_STRINGS(term));
1212
1213     (void) printf("\t\t%d,\t\t/* count extensions to Booleans */\n",
1214                   NUM_BOOLEANS(term) - BOOLCOUNT);
1215     (void) printf("\t\t%d,\t\t/* count extensions to Numbers */\n",
1216                   NUM_NUMBERS(term) - NUMCOUNT);
1217     (void) printf("\t\t%d,\t\t/* count extensions to Strings */\n",
1218                   NUM_STRINGS(term) - STRCOUNT);
1219
1220     (void) printf("#endif /* NCURSES_XNAMES */\n");
1221 #else
1222     (void) term;
1223 #endif /* NCURSES_XNAMES */
1224     (void) printf("\t%s\n", R_CURL);
1225 }
1226
1227 static int
1228 optarg_to_number(void)
1229 {
1230     char *temp = 0;
1231     long value = strtol(optarg, &temp, 0);
1232
1233     if (temp == 0 || temp == optarg || *temp != 0) {
1234         fprintf(stderr, "Expected a number, not \"%s\"\n", optarg);
1235         ExitProgram(EXIT_FAILURE);
1236     }
1237     return (int) value;
1238 }
1239
1240 static char *
1241 terminal_env(void)
1242 {
1243     char *terminal;
1244
1245     if ((terminal = getenv("TERM")) == 0) {
1246         (void) fprintf(stderr,
1247                        "%s: environment variable TERM not set\n",
1248                        _nc_progname);
1249         exit(EXIT_FAILURE);
1250     }
1251     return terminal;
1252 }
1253
1254 /*
1255  * Show the databases that infocmp knows about.  The location to which it writes is
1256  */
1257 static void
1258 show_databases(void)
1259 {
1260     DBDIRS state;
1261     int offset;
1262     const char *path2;
1263
1264     _nc_first_db(&state, &offset);
1265     while ((path2 = _nc_next_db(&state, &offset)) != 0) {
1266         printf("%s\n", path2);
1267     }
1268     _nc_last_db();
1269 }
1270
1271 /***************************************************************************
1272  *
1273  * Main sequence
1274  *
1275  ***************************************************************************/
1276
1277 #if NO_LEAKS
1278 #define MAIN_LEAKS() \
1279     free(myargv); \
1280     free(tfile); \
1281     free(tname)
1282 #else
1283 #define MAIN_LEAKS()            /* nothing */
1284 #endif
1285
1286 int
1287 main(int argc, char *argv[])
1288 {
1289     /* Avoid "local data >32k" error with mwcc */
1290     /* Also avoid overflowing smaller stacks on systems like AmigaOS */
1291     path *tfile = 0;
1292     char **tname = 0;
1293     size_t maxterms;
1294
1295     char **myargv;
1296
1297     char *firstdir, *restdir;
1298     int c, i, len;
1299     bool formatted = FALSE;
1300     bool filecompare = FALSE;
1301     int initdump = 0;
1302     bool init_analyze = FALSE;
1303     bool suppress_untranslatable = FALSE;
1304
1305     /* where is the terminfo database location going to default to? */
1306     restdir = firstdir = 0;
1307
1308 #if NCURSES_XNAMES
1309     use_extended_names(FALSE);
1310 #endif
1311     _nc_strict_bsd = 0;
1312
1313     _nc_progname = _nc_rootname(argv[0]);
1314
1315     /* make sure we have enough space to add two terminal entries */
1316     myargv = typeCalloc(char *, (size_t) (argc + 3));
1317     memcpy(myargv, argv, (sizeof(char *) * (size_t) argc));
1318     argv = myargv;
1319
1320     while ((c = getopt(argc,
1321                        argv,
1322                        "01A:aB:CcDdEeFfGgIiKLlnpqR:rs:TtUuVv:w:x")) != -1) {
1323         switch (c) {
1324         case '0':
1325             mwidth = 65535;
1326             mheight = 1;
1327             break;
1328
1329         case '1':
1330             mwidth = 0;
1331             break;
1332
1333         case 'A':
1334             firstdir = optarg;
1335             break;
1336
1337 #if NCURSES_XNAMES
1338         case 'a':
1339             _nc_disable_period = TRUE;
1340             use_extended_names(TRUE);
1341             break;
1342 #endif
1343         case 'B':
1344             restdir = optarg;
1345             break;
1346
1347         case 'K':
1348             _nc_strict_bsd = 1;
1349             /* FALLTHRU */
1350         case 'C':
1351             outform = F_TERMCAP;
1352             tversion = "BSD";
1353             if (sortmode == S_DEFAULT)
1354                 sortmode = S_TERMCAP;
1355             break;
1356
1357         case 'D':
1358             show_databases();
1359             ExitProgram(EXIT_SUCCESS);
1360             break;
1361
1362         case 'c':
1363             compare = C_COMMON;
1364             break;
1365
1366         case 'd':
1367             compare = C_DIFFERENCE;
1368             break;
1369
1370         case 'E':
1371             initdump |= 2;
1372             break;
1373
1374         case 'e':
1375             initdump |= 1;
1376             break;
1377
1378         case 'F':
1379             filecompare = TRUE;
1380             break;
1381
1382         case 'f':
1383             formatted = TRUE;
1384             break;
1385
1386         case 'G':
1387             numbers = 1;
1388             break;
1389
1390         case 'g':
1391             numbers = -1;
1392             break;
1393
1394         case 'I':
1395             outform = F_TERMINFO;
1396             if (sortmode == S_DEFAULT)
1397                 sortmode = S_VARIABLE;
1398             tversion = 0;
1399             break;
1400
1401         case 'i':
1402             init_analyze = TRUE;
1403             break;
1404
1405         case 'L':
1406             outform = F_VARIABLE;
1407             if (sortmode == S_DEFAULT)
1408                 sortmode = S_VARIABLE;
1409             break;
1410
1411         case 'l':
1412             outform = F_TERMINFO;
1413             break;
1414
1415         case 'n':
1416             compare = C_NAND;
1417             break;
1418
1419         case 'p':
1420             ignorepads = TRUE;
1421             break;
1422
1423         case 'q':
1424             quiet = TRUE;
1425             s_absent = "-";
1426             s_cancel = "@";
1427             bool_sep = ", ";
1428             break;
1429
1430         case 'R':
1431             tversion = optarg;
1432             break;
1433
1434         case 'r':
1435             tversion = 0;
1436             break;
1437
1438         case 's':
1439             if (*optarg == 'd')
1440                 sortmode = S_NOSORT;
1441             else if (*optarg == 'i')
1442                 sortmode = S_TERMINFO;
1443             else if (*optarg == 'l')
1444                 sortmode = S_VARIABLE;
1445             else if (*optarg == 'c')
1446                 sortmode = S_TERMCAP;
1447             else {
1448                 (void) fprintf(stderr,
1449                                "%s: unknown sort mode\n",
1450                                _nc_progname);
1451                 ExitProgram(EXIT_FAILURE);
1452             }
1453             break;
1454
1455         case 'T':
1456             limited = FALSE;
1457             break;
1458
1459 #if NCURSES_XNAMES
1460         case 't':
1461             _nc_disable_period = FALSE;
1462             suppress_untranslatable = TRUE;
1463             break;
1464 #endif
1465
1466         case 'U':
1467             literal = TRUE;
1468             break;
1469
1470         case 'u':
1471             compare = C_USEALL;
1472             break;
1473
1474         case 'V':
1475             puts(curses_version());
1476             ExitProgram(EXIT_SUCCESS);
1477
1478         case 'v':
1479             itrace = (unsigned) optarg_to_number();
1480             set_trace_level(itrace);
1481             break;
1482
1483         case 'w':
1484             mwidth = optarg_to_number();
1485             break;
1486
1487 #if NCURSES_XNAMES
1488         case 'x':
1489             use_extended_names(TRUE);
1490             break;
1491 #endif
1492
1493         default:
1494             usage();
1495         }
1496     }
1497
1498     maxterms = (size_t) (argc + 2 - optind);
1499     tfile = typeMalloc(path, maxterms);
1500     tname = typeCalloc(char *, maxterms);
1501     entries = typeCalloc(ENTRY, maxterms);
1502
1503     if (tfile == 0
1504         || tname == 0
1505         || entries == 0) {
1506         fprintf(stderr, "%s: not enough memory\n", _nc_progname);
1507         ExitProgram(EXIT_FAILURE);
1508     }
1509
1510     /* by default, sort by terminfo name */
1511     if (sortmode == S_DEFAULT)
1512         sortmode = S_TERMINFO;
1513
1514     /* set up for display */
1515     dump_init(tversion, outform, sortmode, mwidth, mheight, itrace, formatted);
1516
1517     /* make sure we have at least one terminal name to work with */
1518     if (optind >= argc)
1519         argv[argc++] = terminal_env();
1520
1521     /* if user is after a comparison, make sure we have two entries */
1522     if (compare != C_DEFAULT && optind >= argc - 1)
1523         argv[argc++] = terminal_env();
1524
1525     /* exactly two terminal names with no options means do -d */
1526     if (argc - optind == 2 && compare == C_DEFAULT)
1527         compare = C_DIFFERENCE;
1528
1529     if (!filecompare) {
1530         /* grab the entries */
1531         termcount = 0;
1532         for (; optind < argc; optind++) {
1533             const char *directory = termcount ? restdir : firstdir;
1534             int status;
1535
1536             tname[termcount] = argv[optind];
1537
1538             if (directory) {
1539 #if USE_DATABASE
1540 #if MIXEDCASE_FILENAMES
1541 #define LEAF_FMT "%c"
1542 #else
1543 #define LEAF_FMT "%02x"
1544 #endif
1545                 (void) sprintf(tfile[termcount], "%s/" LEAF_FMT "/%s",
1546                                directory,
1547                                UChar(*argv[optind]), argv[optind]);
1548                 if (itrace)
1549                     (void) fprintf(stderr,
1550                                    "%s: reading entry %s from file %s\n",
1551                                    _nc_progname,
1552                                    argv[optind], tfile[termcount]);
1553
1554                 status = _nc_read_file_entry(tfile[termcount],
1555                                              &entries[termcount].tterm);
1556 #else
1557                 (void) fprintf(stderr, "%s: terminfo files not supported\n",
1558                                _nc_progname);
1559                 MAIN_LEAKS();
1560                 ExitProgram(EXIT_FAILURE);
1561 #endif
1562             } else {
1563                 if (itrace)
1564                     (void) fprintf(stderr,
1565                                    "%s: reading entry %s from database\n",
1566                                    _nc_progname,
1567                                    tname[termcount]);
1568
1569                 status = _nc_read_entry(tname[termcount],
1570                                         tfile[termcount],
1571                                         &entries[termcount].tterm);
1572             }
1573
1574             if (status <= 0) {
1575                 (void) fprintf(stderr,
1576                                "%s: couldn't open terminfo file %s.\n",
1577                                _nc_progname,
1578                                tfile[termcount]);
1579                 MAIN_LEAKS();
1580                 ExitProgram(EXIT_FAILURE);
1581             }
1582             repair_acsc(&entries[termcount].tterm);
1583             termcount++;
1584         }
1585
1586 #if NCURSES_XNAMES
1587         if (termcount > 1)
1588             _nc_align_termtype(&entries[0].tterm, &entries[1].tterm);
1589 #endif
1590
1591         /* dump as C initializer for the terminal type */
1592         if (initdump) {
1593             if (initdump & 1)
1594                 dump_termtype(&entries[0].tterm);
1595             if (initdump & 2)
1596                 dump_initializers(&entries[0].tterm);
1597         }
1598
1599         /* analyze the init strings */
1600         else if (init_analyze) {
1601 #undef CUR
1602 #define CUR     entries[0].tterm.
1603             analyze_string("is1", init_1string, &entries[0].tterm);
1604             analyze_string("is2", init_2string, &entries[0].tterm);
1605             analyze_string("is3", init_3string, &entries[0].tterm);
1606             analyze_string("rs1", reset_1string, &entries[0].tterm);
1607             analyze_string("rs2", reset_2string, &entries[0].tterm);
1608             analyze_string("rs3", reset_3string, &entries[0].tterm);
1609             analyze_string("smcup", enter_ca_mode, &entries[0].tterm);
1610             analyze_string("rmcup", exit_ca_mode, &entries[0].tterm);
1611 #undef CUR
1612         } else {
1613
1614             /*
1615              * Here's where the real work gets done
1616              */
1617             switch (compare) {
1618             case C_DEFAULT:
1619                 if (itrace)
1620                     (void) fprintf(stderr,
1621                                    "%s: about to dump %s\n",
1622                                    _nc_progname,
1623                                    tname[0]);
1624                 (void) printf("#\tReconstructed via infocmp from file: %s\n",
1625                               tfile[0]);
1626                 dump_entry(&entries[0].tterm,
1627                            suppress_untranslatable,
1628                            limited,
1629                            numbers,
1630                            NULL);
1631                 len = show_entry();
1632                 if (itrace)
1633                     (void) fprintf(stderr, "%s: length %d\n", _nc_progname, len);
1634                 break;
1635
1636             case C_DIFFERENCE:
1637                 if (itrace)
1638                     (void) fprintf(stderr, "%s: dumping differences\n", _nc_progname);
1639                 (void) printf("comparing %s to %s.\n", tname[0], tname[1]);
1640                 compare_entry(compare_predicate, &entries->tterm, quiet);
1641                 break;
1642
1643             case C_COMMON:
1644                 if (itrace)
1645                     (void) fprintf(stderr,
1646                                    "%s: dumping common capabilities\n",
1647                                    _nc_progname);
1648                 (void) printf("comparing %s to %s.\n", tname[0], tname[1]);
1649                 compare_entry(compare_predicate, &entries->tterm, quiet);
1650                 break;
1651
1652             case C_NAND:
1653                 if (itrace)
1654                     (void) fprintf(stderr,
1655                                    "%s: dumping differences\n",
1656                                    _nc_progname);
1657                 (void) printf("comparing %s to %s.\n", tname[0], tname[1]);
1658                 compare_entry(compare_predicate, &entries->tterm, quiet);
1659                 break;
1660
1661             case C_USEALL:
1662                 if (itrace)
1663                     (void) fprintf(stderr, "%s: dumping use entry\n", _nc_progname);
1664                 dump_entry(&entries[0].tterm,
1665                            suppress_untranslatable,
1666                            limited,
1667                            numbers,
1668                            use_predicate);
1669                 for (i = 1; i < termcount; i++)
1670                     dump_uses(tname[i], !(outform == F_TERMCAP
1671                                           || outform == F_TCONVERR));
1672                 len = show_entry();
1673                 if (itrace)
1674                     (void) fprintf(stderr, "%s: length %d\n", _nc_progname, len);
1675                 break;
1676             }
1677         }
1678     } else if (compare == C_USEALL)
1679         (void) fprintf(stderr, "Sorry, -u doesn't work with -F\n");
1680     else if (compare == C_DEFAULT)
1681         (void) fprintf(stderr, "Use `tic -[CI] <file>' for this.\n");
1682     else if (argc - optind != 2)
1683         (void) fprintf(stderr,
1684                        "File comparison needs exactly two file arguments.\n");
1685     else
1686         file_comparison(argc - optind, argv + optind);
1687
1688     MAIN_LEAKS();
1689     ExitProgram(EXIT_SUCCESS);
1690 }
1691
1692 /* infocmp.c ends here */