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