]> ncurses.scripts.mit.edu Git - ncurses.git/blob - progs/infocmp.c
ncurses 5.9 - patch 20130209
[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.123 2012/11/17 23:15:10 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
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         ,"  -V    print version"
1169 #if NCURSES_XNAMES
1170         ,"  -a    with -F, list commented-out caps"
1171 #endif
1172         ,"  -c    list common capabilities"
1173         ,"  -d    list different capabilities"
1174         ,"  -e    format output for C initializer"
1175         ,"  -E    format output as C tables"
1176         ,"  -f    with -1, format complex strings"
1177         ,"  -G    format %{number} to %'char'"
1178         ,"  -g    format %'char' to %{number}"
1179         ,"  -i    analyze initialization/reset"
1180         ,"  -l    output terminfo names"
1181         ,"  -n    list capabilities in neither"
1182         ,"  -p    ignore padding specifiers"
1183         ,"  -q    brief listing, removes headers"
1184         ,"  -r    with -C, output in termcap form"
1185         ,"  -r    with -F, resolve use-references"
1186         ,"  -s [d|i|l|c] sort fields"
1187 #if NCURSES_XNAMES
1188         ,"  -t    suppress commented-out capabilities"
1189 #endif
1190         ,"  -u    produce source with 'use='"
1191         ,"  -v number  (verbose)"
1192         ,"  -w number  (width)"
1193 #if NCURSES_XNAMES
1194         ,"  -x    treat unknown capabilities as user-defined"
1195 #endif
1196     };
1197     const size_t first = 3;
1198     const size_t last = SIZEOF(tbl);
1199     const size_t left = (last - first + 1) / 2 + first;
1200     size_t n;
1201
1202     for (n = 0; n < left; n++) {
1203         size_t m = (n < first) ? last : n + left - first;
1204         if (m < last)
1205             fprintf(stderr, "%-40.40s%s\n", tbl[n], tbl[m]);
1206         else
1207             fprintf(stderr, "%s\n", tbl[n]);
1208     }
1209     ExitProgram(EXIT_FAILURE);
1210 }
1211
1212 static char *
1213 any_initializer(const char *fmt, const char *type)
1214 {
1215     static char *initializer;
1216     static size_t need;
1217     char *s;
1218
1219     if (initializer == 0) {
1220         need = (strlen(entries->tterm.term_names)
1221                 + strlen(type)
1222                 + strlen(fmt));
1223         initializer = (char *) malloc(need + 1);
1224         if (initializer == 0)
1225             failed("any_initializer");
1226     }
1227
1228     _nc_STRCPY(initializer, entries->tterm.term_names, need);
1229     for (s = initializer; *s != 0 && *s != '|'; s++) {
1230         if (!isalnum(UChar(*s)))
1231             *s = '_';
1232     }
1233     *s = 0;
1234     _nc_SPRINTF(s, _nc_SLIMIT(need) fmt, type);
1235     return initializer;
1236 }
1237
1238 static char *
1239 name_initializer(const char *type)
1240 {
1241     return any_initializer("_%s_data", type);
1242 }
1243
1244 static char *
1245 string_variable(const char *type)
1246 {
1247     return any_initializer("_s_%s", type);
1248 }
1249
1250 /* dump C initializers for the terminal type */
1251 static void
1252 dump_initializers(TERMTYPE *term)
1253 {
1254     unsigned n;
1255     const char *str = 0;
1256
1257     printf("\nstatic char %s[] = \"%s\";\n\n",
1258            name_initializer("alias"), entries->tterm.term_names);
1259
1260     for_each_string(n, term) {
1261         char buf[MAX_STRING], *sp, *tp;
1262
1263         if (VALID_STRING(term->Strings[n])) {
1264             tp = buf;
1265 #define TP_LIMIT        ((MAX_STRING - 5) - (size_t)(tp - buf))
1266             *tp++ = '"';
1267             for (sp = term->Strings[n];
1268                  *sp != 0 && TP_LIMIT > 2;
1269                  sp++) {
1270                 if (isascii(UChar(*sp))
1271                     && isprint(UChar(*sp))
1272                     && *sp != '\\'
1273                     && *sp != '"')
1274                     *tp++ = *sp;
1275                 else {
1276                     _nc_SPRINTF(tp, _nc_SLIMIT(TP_LIMIT) "\\%03o", UChar(*sp));
1277                     tp += 4;
1278                 }
1279             }
1280             *tp++ = '"';
1281             *tp = '\0';
1282             (void) printf("static char %-20s[] = %s;\n",
1283                           string_variable(ExtStrname(term, (int) n, strnames)),
1284                           buf);
1285         }
1286     }
1287     printf("\n");
1288
1289     (void) printf("static char %s[] = %s\n", name_initializer("bool"), L_CURL);
1290
1291     for_each_boolean(n, term) {
1292         switch ((int) (term->Booleans[n])) {
1293         case TRUE:
1294             str = "TRUE";
1295             break;
1296
1297         case FALSE:
1298             str = "FALSE";
1299             break;
1300
1301         case ABSENT_BOOLEAN:
1302             str = "ABSENT_BOOLEAN";
1303             break;
1304
1305         case CANCELLED_BOOLEAN:
1306             str = "CANCELLED_BOOLEAN";
1307             break;
1308         }
1309         (void) printf("\t/* %3u: %-8s */\t%s,\n",
1310                       n, ExtBoolname(term, (int) n, boolnames), str);
1311     }
1312     (void) printf("%s;\n", R_CURL);
1313
1314     (void) printf("static short %s[] = %s\n", name_initializer("number"), L_CURL);
1315
1316     for_each_number(n, term) {
1317         char buf[BUFSIZ];
1318         switch (term->Numbers[n]) {
1319         case ABSENT_NUMERIC:
1320             str = "ABSENT_NUMERIC";
1321             break;
1322         case CANCELLED_NUMERIC:
1323             str = "CANCELLED_NUMERIC";
1324             break;
1325         default:
1326             _nc_SPRINTF(buf, _nc_SLIMIT(sizeof(buf)) "%d", term->Numbers[n]);
1327             str = buf;
1328             break;
1329         }
1330         (void) printf("\t/* %3u: %-8s */\t%s,\n", n,
1331                       ExtNumname(term, (int) n, numnames), str);
1332     }
1333     (void) printf("%s;\n", R_CURL);
1334
1335     (void) printf("static char * %s[] = %s\n", name_initializer("string"), L_CURL);
1336
1337     for_each_string(n, term) {
1338
1339         if (term->Strings[n] == ABSENT_STRING)
1340             str = "ABSENT_STRING";
1341         else if (term->Strings[n] == CANCELLED_STRING)
1342             str = "CANCELLED_STRING";
1343         else {
1344             str = string_variable(ExtStrname(term, (int) n, strnames));
1345         }
1346         (void) printf("\t/* %3u: %-8s */\t%s,\n", n,
1347                       ExtStrname(term, (int) n, strnames), str);
1348     }
1349     (void) printf("%s;\n", R_CURL);
1350
1351 #if NCURSES_XNAMES
1352     if ((NUM_BOOLEANS(term) != BOOLCOUNT)
1353         || (NUM_NUMBERS(term) != NUMCOUNT)
1354         || (NUM_STRINGS(term) != STRCOUNT)) {
1355         (void) printf("static char * %s[] = %s\n",
1356                       name_initializer("string_ext"), L_CURL);
1357         for (n = BOOLCOUNT; n < NUM_BOOLEANS(term); ++n) {
1358             (void) printf("\t/* %3u: bool */\t\"%s\",\n",
1359                           n, ExtBoolname(term, (int) n, boolnames));
1360         }
1361         for (n = NUMCOUNT; n < NUM_NUMBERS(term); ++n) {
1362             (void) printf("\t/* %3u: num */\t\"%s\",\n",
1363                           n, ExtNumname(term, (int) n, numnames));
1364         }
1365         for (n = STRCOUNT; n < NUM_STRINGS(term); ++n) {
1366             (void) printf("\t/* %3u: str */\t\"%s\",\n",
1367                           n, ExtStrname(term, (int) n, strnames));
1368         }
1369         (void) printf("%s;\n", R_CURL);
1370     }
1371 #endif
1372 }
1373
1374 /* dump C initializers for the terminal type */
1375 static void
1376 dump_termtype(TERMTYPE *term)
1377 {
1378     (void) printf("\t%s\n\t\t%s,\n", L_CURL, name_initializer("alias"));
1379     (void) printf("\t\t(char *)0,\t/* pointer to string table */\n");
1380
1381     (void) printf("\t\t%s,\n", name_initializer("bool"));
1382     (void) printf("\t\t%s,\n", name_initializer("number"));
1383
1384     (void) printf("\t\t%s,\n", name_initializer("string"));
1385
1386 #if NCURSES_XNAMES
1387     (void) printf("#if NCURSES_XNAMES\n");
1388     (void) printf("\t\t(char *)0,\t/* pointer to extended string table */\n");
1389     (void) printf("\t\t%s,\t/* ...corresponding names */\n",
1390                   ((NUM_BOOLEANS(term) != BOOLCOUNT)
1391                    || (NUM_NUMBERS(term) != NUMCOUNT)
1392                    || (NUM_STRINGS(term) != STRCOUNT))
1393                   ? name_initializer("string_ext")
1394                   : "(char **)0");
1395
1396     (void) printf("\t\t%d,\t\t/* count total Booleans */\n", NUM_BOOLEANS(term));
1397     (void) printf("\t\t%d,\t\t/* count total Numbers */\n", NUM_NUMBERS(term));
1398     (void) printf("\t\t%d,\t\t/* count total Strings */\n", NUM_STRINGS(term));
1399
1400     (void) printf("\t\t%d,\t\t/* count extensions to Booleans */\n",
1401                   NUM_BOOLEANS(term) - BOOLCOUNT);
1402     (void) printf("\t\t%d,\t\t/* count extensions to Numbers */\n",
1403                   NUM_NUMBERS(term) - NUMCOUNT);
1404     (void) printf("\t\t%d,\t\t/* count extensions to Strings */\n",
1405                   NUM_STRINGS(term) - STRCOUNT);
1406
1407     (void) printf("#endif /* NCURSES_XNAMES */\n");
1408 #else
1409     (void) term;
1410 #endif /* NCURSES_XNAMES */
1411     (void) printf("\t%s\n", R_CURL);
1412 }
1413
1414 static int
1415 optarg_to_number(void)
1416 {
1417     char *temp = 0;
1418     long value = strtol(optarg, &temp, 0);
1419
1420     if (temp == 0 || temp == optarg || *temp != 0) {
1421         fprintf(stderr, "Expected a number, not \"%s\"\n", optarg);
1422         ExitProgram(EXIT_FAILURE);
1423     }
1424     return (int) value;
1425 }
1426
1427 static char *
1428 terminal_env(void)
1429 {
1430     char *terminal;
1431
1432     if ((terminal = getenv("TERM")) == 0) {
1433         (void) fprintf(stderr,
1434                        "%s: environment variable TERM not set\n",
1435                        _nc_progname);
1436         exit(EXIT_FAILURE);
1437     }
1438     return terminal;
1439 }
1440
1441 /*
1442  * Show the databases that infocmp knows about.  The location to which it writes is
1443  */
1444 static void
1445 show_databases(void)
1446 {
1447     DBDIRS state;
1448     int offset;
1449     const char *path2;
1450
1451     _nc_first_db(&state, &offset);
1452     while ((path2 = _nc_next_db(&state, &offset)) != 0) {
1453         printf("%s\n", path2);
1454     }
1455     _nc_last_db();
1456 }
1457
1458 /***************************************************************************
1459  *
1460  * Main sequence
1461  *
1462  ***************************************************************************/
1463
1464 #if NO_LEAKS
1465 #define MAIN_LEAKS() \
1466     free(myargv); \
1467     free(tfile); \
1468     free(tname)
1469 #else
1470 #define MAIN_LEAKS()            /* nothing */
1471 #endif
1472
1473 int
1474 main(int argc, char *argv[])
1475 {
1476     /* Avoid "local data >32k" error with mwcc */
1477     /* Also avoid overflowing smaller stacks on systems like AmigaOS */
1478     path *tfile = 0;
1479     char **tname = 0;
1480     size_t maxterms;
1481
1482     char **myargv;
1483
1484     char *firstdir, *restdir;
1485     int c, i, len;
1486     bool formatted = FALSE;
1487     bool filecompare = FALSE;
1488     int initdump = 0;
1489     bool init_analyze = FALSE;
1490     bool suppress_untranslatable = FALSE;
1491
1492     /* where is the terminfo database location going to default to? */
1493     restdir = firstdir = 0;
1494
1495 #if NCURSES_XNAMES
1496     use_extended_names(FALSE);
1497 #endif
1498     _nc_strict_bsd = 0;
1499
1500     _nc_progname = _nc_rootname(argv[0]);
1501
1502     /* make sure we have enough space to add two terminal entries */
1503     myargv = typeCalloc(char *, (size_t) (argc + 3));
1504     if (myargv == 0)
1505         failed("myargv");
1506
1507     memcpy(myargv, argv, (sizeof(char *) * (size_t) argc));
1508     argv = myargv;
1509
1510     while ((c = getopt(argc,
1511                        argv,
1512                        "01A:aB:CcDdEeFfGgIiKLlnpqR:rs:TtUuVv:w:x")) != -1) {
1513         switch (c) {
1514         case '0':
1515             mwidth = 65535;
1516             mheight = 1;
1517             break;
1518
1519         case '1':
1520             mwidth = 0;
1521             break;
1522
1523         case 'A':
1524             firstdir = optarg;
1525             break;
1526
1527 #if NCURSES_XNAMES
1528         case 'a':
1529             _nc_disable_period = TRUE;
1530             use_extended_names(TRUE);
1531             break;
1532 #endif
1533         case 'B':
1534             restdir = optarg;
1535             break;
1536
1537         case 'K':
1538             _nc_strict_bsd = 1;
1539             /* FALLTHRU */
1540         case 'C':
1541             outform = F_TERMCAP;
1542             tversion = "BSD";
1543             if (sortmode == S_DEFAULT)
1544                 sortmode = S_TERMCAP;
1545             break;
1546
1547         case 'D':
1548             show_databases();
1549             ExitProgram(EXIT_SUCCESS);
1550             break;
1551
1552         case 'c':
1553             compare = C_COMMON;
1554             break;
1555
1556         case 'd':
1557             compare = C_DIFFERENCE;
1558             break;
1559
1560         case 'E':
1561             initdump |= 2;
1562             break;
1563
1564         case 'e':
1565             initdump |= 1;
1566             break;
1567
1568         case 'F':
1569             filecompare = TRUE;
1570             break;
1571
1572         case 'f':
1573             formatted = TRUE;
1574             break;
1575
1576         case 'G':
1577             numbers = 1;
1578             break;
1579
1580         case 'g':
1581             numbers = -1;
1582             break;
1583
1584         case 'I':
1585             outform = F_TERMINFO;
1586             if (sortmode == S_DEFAULT)
1587                 sortmode = S_VARIABLE;
1588             tversion = 0;
1589             break;
1590
1591         case 'i':
1592             init_analyze = TRUE;
1593             break;
1594
1595         case 'L':
1596             outform = F_VARIABLE;
1597             if (sortmode == S_DEFAULT)
1598                 sortmode = S_VARIABLE;
1599             break;
1600
1601         case 'l':
1602             outform = F_TERMINFO;
1603             break;
1604
1605         case 'n':
1606             compare = C_NAND;
1607             break;
1608
1609         case 'p':
1610             ignorepads = TRUE;
1611             break;
1612
1613         case 'q':
1614             quiet = TRUE;
1615             s_absent = "-";
1616             s_cancel = "@";
1617             bool_sep = ", ";
1618             break;
1619
1620         case 'R':
1621             tversion = optarg;
1622             break;
1623
1624         case 'r':
1625             tversion = 0;
1626             break;
1627
1628         case 's':
1629             if (*optarg == 'd')
1630                 sortmode = S_NOSORT;
1631             else if (*optarg == 'i')
1632                 sortmode = S_TERMINFO;
1633             else if (*optarg == 'l')
1634                 sortmode = S_VARIABLE;
1635             else if (*optarg == 'c')
1636                 sortmode = S_TERMCAP;
1637             else {
1638                 (void) fprintf(stderr,
1639                                "%s: unknown sort mode\n",
1640                                _nc_progname);
1641                 ExitProgram(EXIT_FAILURE);
1642             }
1643             break;
1644
1645         case 'T':
1646             limited = FALSE;
1647             break;
1648
1649 #if NCURSES_XNAMES
1650         case 't':
1651             _nc_disable_period = FALSE;
1652             suppress_untranslatable = TRUE;
1653             break;
1654 #endif
1655
1656         case 'U':
1657             literal = TRUE;
1658             break;
1659
1660         case 'u':
1661             compare = C_USEALL;
1662             break;
1663
1664         case 'V':
1665             puts(curses_version());
1666             ExitProgram(EXIT_SUCCESS);
1667
1668         case 'v':
1669             itrace = (unsigned) optarg_to_number();
1670             set_trace_level(itrace);
1671             break;
1672
1673         case 'w':
1674             mwidth = optarg_to_number();
1675             break;
1676
1677 #if NCURSES_XNAMES
1678         case 'x':
1679             use_extended_names(TRUE);
1680             break;
1681 #endif
1682
1683         default:
1684             usage();
1685         }
1686     }
1687
1688     maxterms = (size_t) (argc + 2 - optind);
1689     if ((tfile = typeMalloc(path, maxterms)) == 0)
1690         failed("tfile");
1691     if ((tname = typeCalloc(char *, maxterms)) == 0)
1692           failed("tname");
1693     if ((entries = typeCalloc(ENTRY, maxterms)) == 0)
1694         failed("entries");
1695 #if NO_LEAKS
1696     if ((entered = typeCalloc(ENTERED, maxterms)) == 0)
1697         failed("entered");
1698 #endif
1699
1700     if (tfile == 0
1701         || tname == 0
1702         || entries == 0) {
1703         fprintf(stderr, "%s: not enough memory\n", _nc_progname);
1704         ExitProgram(EXIT_FAILURE);
1705     }
1706
1707     /* by default, sort by terminfo name */
1708     if (sortmode == S_DEFAULT)
1709         sortmode = S_TERMINFO;
1710
1711     /* make sure we have at least one terminal name to work with */
1712     if (optind >= argc)
1713         argv[argc++] = terminal_env();
1714
1715     /* if user is after a comparison, make sure we have two entries */
1716     if (compare != C_DEFAULT && optind >= argc - 1)
1717         argv[argc++] = terminal_env();
1718
1719     /* exactly one terminal name with no options means display it */
1720     /* exactly two terminal names with no options means do -d */
1721     if (compare == C_DEFAULT) {
1722         switch (argc - optind) {
1723         default:
1724             fprintf(stderr, "%s: too many names to compare\n", _nc_progname);
1725             ExitProgram(EXIT_FAILURE);
1726         case 1:
1727             break;
1728         case 2:
1729             compare = C_DIFFERENCE;
1730             break;
1731         }
1732     }
1733
1734     /* set up for display */
1735     dump_init(tversion, outform, sortmode, mwidth, mheight, itrace, formatted);
1736
1737     if (!filecompare) {
1738         /* grab the entries */
1739         termcount = 0;
1740         for (; optind < argc; optind++) {
1741             const char *directory = termcount ? restdir : firstdir;
1742             int status;
1743
1744             tname[termcount] = argv[optind];
1745
1746             if (directory) {
1747 #if USE_DATABASE
1748 #if MIXEDCASE_FILENAMES
1749 #define LEAF_FMT "%c"
1750 #else
1751 #define LEAF_FMT "%02x"
1752 #endif
1753                 _nc_SPRINTF(tfile[termcount],
1754                             _nc_SLIMIT(sizeof(path))
1755                             "%s/" LEAF_FMT "/%s",
1756                             directory,
1757                             UChar(*argv[optind]), argv[optind]);
1758                 if (itrace)
1759                     (void) fprintf(stderr,
1760                                    "%s: reading entry %s from file %s\n",
1761                                    _nc_progname,
1762                                    argv[optind], tfile[termcount]);
1763
1764                 status = _nc_read_file_entry(tfile[termcount],
1765                                              &entries[termcount].tterm);
1766 #else
1767                 (void) fprintf(stderr, "%s: terminfo files not supported\n",
1768                                _nc_progname);
1769                 MAIN_LEAKS();
1770                 ExitProgram(EXIT_FAILURE);
1771 #endif
1772             } else {
1773                 if (itrace)
1774                     (void) fprintf(stderr,
1775                                    "%s: reading entry %s from database\n",
1776                                    _nc_progname,
1777                                    tname[termcount]);
1778
1779                 status = _nc_read_entry(tname[termcount],
1780                                         tfile[termcount],
1781                                         &entries[termcount].tterm);
1782             }
1783
1784             if (status <= 0) {
1785                 (void) fprintf(stderr,
1786                                "%s: couldn't open terminfo file %s.\n",
1787                                _nc_progname,
1788                                tfile[termcount]);
1789                 MAIN_LEAKS();
1790                 ExitProgram(EXIT_FAILURE);
1791             }
1792             repair_acsc(&entries[termcount].tterm);
1793             termcount++;
1794         }
1795
1796 #if NCURSES_XNAMES
1797         if (termcount > 1)
1798             _nc_align_termtype(&entries[0].tterm, &entries[1].tterm);
1799 #endif
1800
1801         /* dump as C initializer for the terminal type */
1802         if (initdump) {
1803             if (initdump & 1)
1804                 dump_termtype(&entries[0].tterm);
1805             if (initdump & 2)
1806                 dump_initializers(&entries[0].tterm);
1807         }
1808
1809         /* analyze the init strings */
1810         else if (init_analyze) {
1811 #undef CUR
1812 #define CUR     entries[0].tterm.
1813             analyze_string("is1", init_1string, &entries[0].tterm);
1814             analyze_string("is2", init_2string, &entries[0].tterm);
1815             analyze_string("is3", init_3string, &entries[0].tterm);
1816             analyze_string("rs1", reset_1string, &entries[0].tterm);
1817             analyze_string("rs2", reset_2string, &entries[0].tterm);
1818             analyze_string("rs3", reset_3string, &entries[0].tterm);
1819             analyze_string("smcup", enter_ca_mode, &entries[0].tterm);
1820             analyze_string("rmcup", exit_ca_mode, &entries[0].tterm);
1821 #undef CUR
1822         } else {
1823
1824             /*
1825              * Here's where the real work gets done
1826              */
1827             switch (compare) {
1828             case C_DEFAULT:
1829                 if (itrace)
1830                     (void) fprintf(stderr,
1831                                    "%s: about to dump %s\n",
1832                                    _nc_progname,
1833                                    tname[0]);
1834                 (void) printf("#\tReconstructed via infocmp from file: %s\n",
1835                               tfile[0]);
1836                 dump_entry(&entries[0].tterm,
1837                            suppress_untranslatable,
1838                            limited,
1839                            numbers,
1840                            NULL);
1841                 len = show_entry();
1842                 if (itrace)
1843                     (void) fprintf(stderr, "%s: length %d\n", _nc_progname, len);
1844                 break;
1845
1846             case C_DIFFERENCE:
1847                 show_comparing(tname);
1848                 compare_entry(compare_predicate, &entries->tterm, quiet);
1849                 break;
1850
1851             case C_COMMON:
1852                 show_comparing(tname);
1853                 compare_entry(compare_predicate, &entries->tterm, quiet);
1854                 break;
1855
1856             case C_NAND:
1857                 show_comparing(tname);
1858                 compare_entry(compare_predicate, &entries->tterm, quiet);
1859                 break;
1860
1861             case C_USEALL:
1862                 if (itrace)
1863                     (void) fprintf(stderr, "%s: dumping use entry\n", _nc_progname);
1864                 dump_entry(&entries[0].tterm,
1865                            suppress_untranslatable,
1866                            limited,
1867                            numbers,
1868                            use_predicate);
1869                 for (i = 1; i < termcount; i++)
1870                     dump_uses(tname[i], !(outform == F_TERMCAP
1871                                           || outform == F_TCONVERR));
1872                 len = show_entry();
1873                 if (itrace)
1874                     (void) fprintf(stderr, "%s: length %d\n", _nc_progname, len);
1875                 break;
1876             }
1877         }
1878     } else if (compare == C_USEALL) {
1879         (void) fprintf(stderr, "Sorry, -u doesn't work with -F\n");
1880     } else if (compare == C_DEFAULT) {
1881         (void) fprintf(stderr, "Use `tic -[CI] <file>' for this.\n");
1882     } else if (argc - optind != 2) {
1883         (void) fprintf(stderr,
1884                        "File comparison needs exactly two file arguments.\n");
1885     } else {
1886         file_comparison(argc - optind, argv + optind);
1887     }
1888
1889     MAIN_LEAKS();
1890     ExitProgram(EXIT_SUCCESS);
1891 }
1892
1893 /* infocmp.c ends here */