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