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