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