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