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