]> ncurses.scripts.mit.edu Git - ncurses.git/blob - ncurses/tinfo/parse_entry.c
ncurses 6.1 - patch 20180512
[ncurses.git] / ncurses / tinfo / parse_entry.c
1 /****************************************************************************
2  * Copyright (c) 1998-2017,2018 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  *      parse_entry.c -- compile one terminfo or termcap entry
37  *
38  *      Get an exact in-core representation of an entry.  Don't
39  *      try to resolve use or tc capabilities, that is someone
40  *      else's job.  Depends on the lexical analyzer to get tokens
41  *      from the input stream.
42  */
43
44 #define __INTERNAL_CAPS_VISIBLE
45 #include <curses.priv.h>
46
47 #include <ctype.h>
48 #include <tic.h>
49
50 MODULE_ID("$Id: parse_entry.c,v 1.93 2018/04/14 17:41:12 tom Exp $")
51
52 #ifdef LINT
53 static short const parametrized[] =
54 {0};
55 #else
56 #include <parametrized.h>
57 #endif
58
59 static void postprocess_termcap(TERMTYPE2 *, bool);
60 static void postprocess_terminfo(TERMTYPE2 *);
61 static struct name_table_entry const *lookup_fullname(const char *name);
62
63 #if NCURSES_XNAMES
64
65 static struct name_table_entry const *
66 _nc_extend_names(ENTRY * entryp, char *name, int token_type)
67 {
68     static struct name_table_entry temp;
69     TERMTYPE2 *tp = &(entryp->tterm);
70     unsigned offset = 0;
71     unsigned actual;
72     unsigned tindex;
73     unsigned first, last, n;
74     bool found;
75
76     switch (token_type) {
77     case BOOLEAN:
78         first = 0;
79         last = tp->ext_Booleans;
80         offset = tp->ext_Booleans;
81         tindex = tp->num_Booleans;
82         break;
83     case NUMBER:
84         first = tp->ext_Booleans;
85         last = tp->ext_Numbers + first;
86         offset = (unsigned) (tp->ext_Booleans + tp->ext_Numbers);
87         tindex = tp->num_Numbers;
88         break;
89     case STRING:
90         first = (unsigned) (tp->ext_Booleans + tp->ext_Numbers);
91         last = tp->ext_Strings + first;
92         offset = (unsigned) (tp->ext_Booleans + tp->ext_Numbers + tp->ext_Strings);
93         tindex = tp->num_Strings;
94         break;
95     case CANCEL:
96         actual = NUM_EXT_NAMES(tp);
97         for (n = 0; n < actual; n++) {
98             if (!strcmp(name, tp->ext_Names[n])) {
99                 if (n > (unsigned) (tp->ext_Booleans + tp->ext_Numbers)) {
100                     token_type = STRING;
101                 } else if (n > tp->ext_Booleans) {
102                     token_type = NUMBER;
103                 } else {
104                     token_type = BOOLEAN;
105                 }
106                 return _nc_extend_names(entryp, name, token_type);
107             }
108         }
109         /* Well, we are given a cancel for a name that we don't recognize */
110         return _nc_extend_names(entryp, name, STRING);
111     default:
112         return 0;
113     }
114
115     /* Adjust the 'offset' (insertion-point) to keep the lists of extended
116      * names sorted.
117      */
118     for (n = first, found = FALSE; n < last; n++) {
119         int cmp = strcmp(tp->ext_Names[n], name);
120         if (cmp == 0)
121             found = TRUE;
122         if (cmp >= 0) {
123             offset = n;
124             tindex = n - first;
125             switch (token_type) {
126             case BOOLEAN:
127                 tindex += BOOLCOUNT;
128                 break;
129             case NUMBER:
130                 tindex += NUMCOUNT;
131                 break;
132             case STRING:
133                 tindex += STRCOUNT;
134                 break;
135             }
136             break;
137         }
138     }
139
140 #define for_each_value(max) \
141         for (last = (unsigned) (max - 1); last > tindex; last--)
142
143     if (!found) {
144         switch (token_type) {
145         case BOOLEAN:
146             tp->ext_Booleans++;
147             tp->num_Booleans++;
148             TYPE_REALLOC(NCURSES_SBOOL, tp->num_Booleans, tp->Booleans);
149             for_each_value(tp->num_Booleans)
150                 tp->Booleans[last] = tp->Booleans[last - 1];
151             break;
152         case NUMBER:
153             tp->ext_Numbers++;
154             tp->num_Numbers++;
155             TYPE_REALLOC(NCURSES_INT2, tp->num_Numbers, tp->Numbers);
156             for_each_value(tp->num_Numbers)
157                 tp->Numbers[last] = tp->Numbers[last - 1];
158             break;
159         case STRING:
160             tp->ext_Strings++;
161             tp->num_Strings++;
162             TYPE_REALLOC(char *, tp->num_Strings, tp->Strings);
163             for_each_value(tp->num_Strings)
164                 tp->Strings[last] = tp->Strings[last - 1];
165             break;
166         }
167         actual = NUM_EXT_NAMES(tp);
168         TYPE_REALLOC(char *, actual, tp->ext_Names);
169         while (--actual > offset)
170             tp->ext_Names[actual] = tp->ext_Names[actual - 1];
171         tp->ext_Names[offset] = _nc_save_str(name);
172     }
173
174     temp.nte_name = tp->ext_Names[offset];
175     temp.nte_type = token_type;
176     temp.nte_index = (short) tindex;
177     temp.nte_link = -1;
178
179     return &temp;
180 }
181 #endif /* NCURSES_XNAMES */
182
183 static bool
184 valid_entryname(const char *name)
185 {
186     bool result = TRUE;
187     int ch;
188     while ((ch = UChar(*name++)) != '\0') {
189         if (ch <= ' ' || ch > '~' || ch == '/') {
190             result = FALSE;
191             break;
192         }
193     }
194     return result;
195 }
196
197 /*
198  *      int
199  *      _nc_parse_entry(entry, literal, silent)
200  *
201  *      Compile one entry.  Doesn't try to resolve use or tc capabilities.
202  *
203  *      found-forward-use = FALSE
204  *      re-initialise internal arrays
205  *      get_token();
206  *      if the token was not a name in column 1, complain and die
207  *      save names in entry's string table
208  *      while (get_token() is not EOF and not NAMES)
209  *              check for existence and type-correctness
210  *              enter cap into structure
211  *              if STRING
212  *                  save string in entry's string table
213  *      push back token
214  */
215
216 #define BAD_TC_USAGE if (!bad_tc_usage) \
217         { bad_tc_usage = TRUE; \
218          _nc_warning("Legacy termcap allows only a trailing tc= clause"); }
219
220 #define MAX_NUMBER MAX_OF_TYPE(NCURSES_INT2)
221
222 NCURSES_EXPORT(int)
223 _nc_parse_entry(ENTRY * entryp, int literal, bool silent)
224 {
225     int token_type;
226     struct name_table_entry const *entry_ptr;
227     char *ptr, *base;
228     const char *name;
229     bool bad_tc_usage = FALSE;
230
231     token_type = _nc_get_token(silent);
232
233     if (token_type == EOF)
234         return (EOF);
235     if (token_type != NAMES)
236         _nc_err_abort("Entry does not start with terminal names in column one");
237
238     _nc_init_entry(entryp);
239
240     entryp->cstart = _nc_comment_start;
241     entryp->cend = _nc_comment_end;
242     entryp->startline = _nc_start_line;
243     DEBUG(2, ("Comment range is %ld to %ld", entryp->cstart, entryp->cend));
244
245     /*
246      * Strip off the 2-character termcap name, if present.  Originally termcap
247      * used that as an indexing aid.  We can retain 2-character terminfo names,
248      * but note that they would be lost if we translate to/from termcap.  This
249      * feature is supposedly obsolete since "newer" BSD implementations do not
250      * use it; however our reference for this feature is SunOS 4.x, which
251      * implemented it.  Note that the resulting terminal type was never the
252      * 2-character name, but was instead the first alias after that.
253      */
254 #define ok_TC2(s) (isgraph(UChar(s)) && (s) != '|')
255     ptr = _nc_curr_token.tk_name;
256     if (_nc_syntax == SYN_TERMCAP
257 #if NCURSES_XNAMES
258         && !_nc_user_definable
259 #endif
260         ) {
261         if (ok_TC2(ptr[0]) && ok_TC2(ptr[1]) && (ptr[2] == '|')) {
262             ptr += 3;
263             _nc_curr_token.tk_name[2] = '\0';
264         }
265     }
266
267     entryp->tterm.str_table = entryp->tterm.term_names = _nc_save_str(ptr);
268
269     if (entryp->tterm.str_table == 0)
270         return (ERR);
271
272     DEBUG(1, ("Starting '%s'", ptr));
273
274     /*
275      * We do this because the one-token lookahead in the parse loop
276      * results in the terminal type getting prematurely set to correspond
277      * to that of the next entry.
278      */
279     name = _nc_first_name(entryp->tterm.term_names);
280     if (!valid_entryname(name)) {
281         _nc_warning("invalid entry name \"%s\"", name);
282         name = "invalid";
283     }
284     _nc_set_type(name);
285
286     /* check for overly-long names and aliases */
287     for (base = entryp->tterm.term_names; (ptr = strchr(base, '|')) != 0;
288          base = ptr + 1) {
289         if (ptr - base > MAX_ALIAS) {
290             _nc_warning("%s `%.*s' may be too long",
291                         (base == entryp->tterm.term_names)
292                         ? "primary name"
293                         : "alias",
294                         (int) (ptr - base), base);
295         }
296     }
297
298     entryp->nuses = 0;
299
300     for (token_type = _nc_get_token(silent);
301          token_type != EOF && token_type != NAMES;
302          token_type = _nc_get_token(silent)) {
303         bool is_use = (strcmp(_nc_curr_token.tk_name, "use") == 0);
304         bool is_tc = !is_use && (strcmp(_nc_curr_token.tk_name, "tc") == 0);
305         if (is_use || is_tc) {
306             if (!VALID_STRING(_nc_curr_token.tk_valstring)
307                 || _nc_curr_token.tk_valstring[0] == '\0') {
308                 _nc_warning("missing name for use-clause");
309                 continue;
310             } else if (!valid_entryname(_nc_curr_token.tk_valstring)) {
311                 _nc_warning("invalid name for use-clause \"%s\"",
312                             _nc_curr_token.tk_valstring);
313                 continue;
314             } else if (entryp->nuses >= MAX_USES) {
315                 _nc_warning("too many use-clauses, ignored \"%s\"",
316                             _nc_curr_token.tk_valstring);
317                 continue;
318             }
319             entryp->uses[entryp->nuses].name = _nc_save_str(_nc_curr_token.tk_valstring);
320             entryp->uses[entryp->nuses].line = _nc_curr_line;
321             entryp->nuses++;
322             if (entryp->nuses > 1 && is_tc) {
323                 BAD_TC_USAGE
324             }
325         } else {
326             /* normal token lookup */
327             entry_ptr = _nc_find_entry(_nc_curr_token.tk_name,
328                                        _nc_get_hash_table(_nc_syntax));
329
330             /*
331              * Our kluge to handle aliasing.  The reason it's done
332              * this ugly way, with a linear search, is so the hashing
333              * machinery doesn't have to be made really complicated
334              * (also we get better warnings this way).  No point in
335              * making this case fast, aliased caps aren't common now
336              * and will get rarer.
337              */
338             if (entry_ptr == NOTFOUND) {
339                 const struct alias *ap;
340
341                 if (_nc_syntax == SYN_TERMCAP) {
342                     if (entryp->nuses != 0) {
343                         BAD_TC_USAGE
344                     }
345                     for (ap = _nc_get_alias_table(TRUE); ap->from; ap++)
346                         if (strcmp(ap->from, _nc_curr_token.tk_name) == 0) {
347                             if (ap->to == (char *) 0) {
348                                 _nc_warning("%s (%s termcap extension) ignored",
349                                             ap->from, ap->source);
350                                 goto nexttok;
351                             }
352
353                             entry_ptr = _nc_find_entry(ap->to,
354                                                        _nc_get_hash_table(TRUE));
355                             if (entry_ptr && !silent)
356                                 _nc_warning("%s (%s termcap extension) aliased to %s",
357                                             ap->from, ap->source, ap->to);
358                             break;
359                         }
360                 } else {        /* if (_nc_syntax == SYN_TERMINFO) */
361                     for (ap = _nc_get_alias_table(FALSE); ap->from; ap++)
362                         if (strcmp(ap->from, _nc_curr_token.tk_name) == 0) {
363                             if (ap->to == (char *) 0) {
364                                 _nc_warning("%s (%s terminfo extension) ignored",
365                                             ap->from, ap->source);
366                                 goto nexttok;
367                             }
368
369                             entry_ptr = _nc_find_entry(ap->to,
370                                                        _nc_get_hash_table(FALSE));
371                             if (entry_ptr && !silent)
372                                 _nc_warning("%s (%s terminfo extension) aliased to %s",
373                                             ap->from, ap->source, ap->to);
374                             break;
375                         }
376
377                     if (entry_ptr == NOTFOUND) {
378                         entry_ptr = lookup_fullname(_nc_curr_token.tk_name);
379                     }
380                 }
381             }
382 #if NCURSES_XNAMES
383             /*
384              * If we have extended-names active, we will automatically
385              * define a name based on its context.
386              */
387             if (entry_ptr == NOTFOUND
388                 && _nc_user_definable
389                 && (entry_ptr = _nc_extend_names(entryp,
390                                                  _nc_curr_token.tk_name,
391                                                  token_type)) != 0) {
392                 if (_nc_tracing >= DEBUG_LEVEL(1))
393                     _nc_warning("extended capability '%s'", _nc_curr_token.tk_name);
394             }
395 #endif /* NCURSES_XNAMES */
396
397             /* can't find this cap name, not even as an alias */
398             if (entry_ptr == NOTFOUND) {
399                 if (!silent)
400                     _nc_warning("unknown capability '%s'",
401                                 _nc_curr_token.tk_name);
402                 continue;
403             }
404
405             /* deal with bad type/value combinations. */
406             if (token_type == CANCEL) {
407                 /*
408                  * Prefer terminfo in this (long-obsolete) ambiguity:
409                  */
410                 if (!strcmp("ma", _nc_curr_token.tk_name)) {
411                     entry_ptr = _nc_find_type_entry("ma", NUMBER,
412                                                     _nc_syntax != 0);
413                     assert(entry_ptr != 0);
414                 }
415             } else if (entry_ptr->nte_type != token_type) {
416                 /*
417                  * Nasty special cases here handle situations in which type
418                  * information can resolve name clashes.  Normal lookup
419                  * finds the last instance in the capability table of a
420                  * given name, regardless of type.  find_type_entry looks
421                  * for a first matching instance with given type.  So as
422                  * long as all ambiguous names occur in pairs of distinct
423                  * type, this will do the job.
424                  */
425
426                 if (token_type == NUMBER
427                     && !strcmp("ma", _nc_curr_token.tk_name)) {
428                     /* tell max_attributes from arrow_key_map */
429                     entry_ptr = _nc_find_type_entry("ma", NUMBER,
430                                                     _nc_syntax != 0);
431                     assert(entry_ptr != 0);
432
433                 } else if (token_type == STRING
434                            && !strcmp("MT", _nc_curr_token.tk_name)) {
435                     /* map terminfo's string MT to MT */
436                     entry_ptr = _nc_find_type_entry("MT", STRING,
437                                                     _nc_syntax != 0);
438                     assert(entry_ptr != 0);
439
440                 } else if (token_type == BOOLEAN
441                            && entry_ptr->nte_type == STRING) {
442                     /* treat strings without following "=" as empty strings */
443                     token_type = STRING;
444                 } else {
445                     /* we couldn't recover; skip this token */
446                     if (!silent) {
447                         const char *type_name;
448                         switch (entry_ptr->nte_type) {
449                         case BOOLEAN:
450                             type_name = "boolean";
451                             break;
452                         case STRING:
453                             type_name = "string";
454                             break;
455                         case NUMBER:
456                             type_name = "numeric";
457                             break;
458                         default:
459                             type_name = "unknown";
460                             break;
461                         }
462                         _nc_warning("wrong type used for %s capability '%s'",
463                                     type_name, _nc_curr_token.tk_name);
464                     }
465                     continue;
466                 }
467             }
468
469             /* now we know that the type/value combination is OK */
470             switch (token_type) {
471             case CANCEL:
472                 switch (entry_ptr->nte_type) {
473                 case BOOLEAN:
474                     entryp->tterm.Booleans[entry_ptr->nte_index] = CANCELLED_BOOLEAN;
475                     break;
476
477                 case NUMBER:
478                     entryp->tterm.Numbers[entry_ptr->nte_index] = CANCELLED_NUMERIC;
479                     break;
480
481                 case STRING:
482                     entryp->tterm.Strings[entry_ptr->nte_index] = CANCELLED_STRING;
483                     break;
484                 }
485                 break;
486
487             case BOOLEAN:
488                 entryp->tterm.Booleans[entry_ptr->nte_index] = TRUE;
489                 break;
490
491             case NUMBER:
492                 if (_nc_curr_token.tk_valnumber > MAX_NUMBER) {
493                     entryp->tterm.Numbers[entry_ptr->nte_index] = MAX_NUMBER;
494                 } else {
495                     entryp->tterm.Numbers[entry_ptr->nte_index] =
496                         (NCURSES_INT2) _nc_curr_token.tk_valnumber;
497                 }
498                 break;
499
500             case STRING:
501                 ptr = _nc_curr_token.tk_valstring;
502                 if (_nc_syntax == SYN_TERMCAP)
503                     ptr = _nc_captoinfo(_nc_curr_token.tk_name,
504                                         ptr,
505                                         parametrized[entry_ptr->nte_index]);
506                 entryp->tterm.Strings[entry_ptr->nte_index] = _nc_save_str(ptr);
507                 break;
508
509             default:
510                 if (!silent)
511                     _nc_warning("unknown token type");
512                 _nc_panic_mode((char) ((_nc_syntax == SYN_TERMCAP) ? ':' : ','));
513                 continue;
514             }
515         }                       /* end else cur_token.name != "use" */
516       nexttok:
517         continue;               /* cannot have a label w/o statement */
518     }                           /* endwhile (not EOF and not NAMES) */
519
520     _nc_push_token(token_type);
521     _nc_set_type(_nc_first_name(entryp->tterm.term_names));
522
523     /*
524      * Try to deduce as much as possible from extension capabilities
525      * (this includes obsolete BSD capabilities).  Sigh...it would be more
526      * space-efficient to call this after use resolution, but it has
527      * to be done before entry allocation is wrapped up.
528      */
529     if (!literal) {
530         if (_nc_syntax == SYN_TERMCAP) {
531             bool has_base_entry = FALSE;
532
533             /*
534              * Don't insert defaults if this is a `+' entry meant only
535              * for inclusion in other entries (not sure termcap ever
536              * had these, actually).
537              */
538             if (strchr(entryp->tterm.term_names, '+')) {
539                 has_base_entry = TRUE;
540             } else {
541                 unsigned i;
542                 /*
543                  * Otherwise, look for a base entry that will already
544                  * have picked up defaults via translation.
545                  */
546                 for (i = 0; i < entryp->nuses; i++) {
547                     if (entryp->uses[i].name != 0
548                         && !strchr(entryp->uses[i].name, '+'))
549                         has_base_entry = TRUE;
550                 }
551             }
552
553             postprocess_termcap(&entryp->tterm, has_base_entry);
554         } else
555             postprocess_terminfo(&entryp->tterm);
556     }
557     _nc_wrap_entry(entryp, FALSE);
558
559     return (OK);
560 }
561
562 NCURSES_EXPORT(int)
563 _nc_capcmp(const char *s, const char *t)
564 /* compare two string capabilities, stripping out padding */
565 {
566     bool ok_s = VALID_STRING(s);
567     bool ok_t = VALID_STRING(t);
568
569     if (ok_s && ok_t) {
570         for (;;) {
571             if (s[0] == '$' && s[1] == '<') {
572                 for (s += 2;; s++) {
573                     if (!(isdigit(UChar(*s))
574                           || *s == '.'
575                           || *s == '*'
576                           || *s == '/'
577                           || *s == '>')) {
578                         break;
579                     }
580                 }
581             }
582
583             if (t[0] == '$' && t[1] == '<') {
584                 for (t += 2;; t++) {
585                     if (!(isdigit(UChar(*t))
586                           || *t == '.'
587                           || *t == '*'
588                           || *t == '/'
589                           || *t == '>')) {
590                         break;
591                     }
592                 }
593             }
594
595             /* we've now pushed s and t past any padding they pointed at */
596
597             if (*s == '\0' && *t == '\0')
598                 return (0);
599
600             if (*s != *t)
601                 return (*t - *s);
602
603             /* else *s == *t but one is not NUL, so continue */
604             s++, t++;
605         }
606     } else if (ok_s || ok_t) {
607         return 1;
608     }
609     return 0;
610 }
611
612 static void
613 append_acs0(string_desc * dst, int code, int src)
614 {
615     if (src != 0) {
616         char temp[3];
617         temp[0] = (char) code;
618         temp[1] = (char) src;
619         temp[2] = 0;
620         _nc_safe_strcat(dst, temp);
621     }
622 }
623
624 static void
625 append_acs(string_desc * dst, int code, char *src)
626 {
627     if (VALID_STRING(src) && strlen(src) == 1) {
628         append_acs0(dst, code, *src);
629     }
630 }
631
632 /*
633  * The ko capability, if present, consists of a comma-separated capability
634  * list.  For each capability, we may assume there is a keycap that sends the
635  * string which is the value of that capability.
636  */
637 #define DATA(from, to) { { from }, { to } }
638 typedef struct {
639     const char from[3];
640     const char to[6];
641 } assoc;
642 static assoc const ko_xlate[] =
643 {
644     DATA("al", "kil1"),         /* insert line key  -> KEY_IL    */
645     DATA("bt", "kcbt"),         /* back tab         -> KEY_BTAB  */
646     DATA("cd", "ked"),          /* clear-to-eos key -> KEY_EOL   */
647     DATA("ce", "kel"),          /* clear-to-eol key -> KEY_EOS   */
648     DATA("cl", "kclr"),         /* clear key        -> KEY_CLEAR */
649     DATA("ct", "tbc"),          /* clear all tabs   -> KEY_CATAB */
650     DATA("dc", "kdch1"),        /* delete char      -> KEY_DC    */
651     DATA("dl", "kdl1"),         /* delete line      -> KEY_DL    */
652     DATA("do", "kcud1"),        /* down key         -> KEY_DOWN  */
653     DATA("ei", "krmir"),        /* exit insert key  -> KEY_EIC   */
654     DATA("ho", "khome"),        /* home key         -> KEY_HOME  */
655     DATA("ic", "kich1"),        /* insert char key  -> KEY_IC    */
656     DATA("im", "kIC"),          /* insert-mode key  -> KEY_SIC   */
657     DATA("le", "kcub1"),        /* le key           -> KEY_LEFT  */
658     DATA("nd", "kcuf1"),        /* nd key           -> KEY_RIGHT */
659     DATA("nl", "kent"),         /* new line key     -> KEY_ENTER */
660     DATA("st", "khts"),         /* set-tab key      -> KEY_STAB  */
661     DATA("ta", ""),
662     DATA("up", "kcuu1"),        /* up-arrow key     -> KEY_UP    */
663 };
664
665 /*
666  * This routine fills in string caps that either had defaults under
667  * termcap or can be manufactured from obsolete termcap capabilities.
668  * It was lifted from Ross Ridge's mytinfo package.
669  */
670
671 static const char C_CR[] = "\r";
672 static const char C_LF[] = "\n";
673 static const char C_BS[] = "\b";
674 static const char C_HT[] = "\t";
675
676 /*
677  * This bit of legerdemain turns all the terminfo variable names into
678  * references to locations in the arrays Booleans, Numbers, and Strings ---
679  * precisely what's needed.
680  */
681
682 #undef CUR
683 #define CUR tp->
684
685 static void
686 postprocess_termcap(TERMTYPE2 *tp, bool has_base)
687 {
688     char buf[MAX_LINE * 2 + 2];
689     string_desc result;
690
691     /*
692      * TERMCAP DEFAULTS AND OBSOLETE-CAPABILITY TRANSLATIONS
693      *
694      * This first part of the code is the functional inverse of the
695      * fragment in capdefaults.c.
696      * ----------------------------------------------------------------------
697      */
698
699     /* if there was a tc entry, assume we picked up defaults via that */
700     if (!has_base) {
701         if (WANTED(init_3string) && PRESENT(termcap_init2))
702             init_3string = _nc_save_str(termcap_init2);
703
704         if (WANTED(reset_2string) && PRESENT(termcap_reset))
705             reset_2string = _nc_save_str(termcap_reset);
706
707         if (WANTED(carriage_return)) {
708             if (carriage_return_delay > 0) {
709                 _nc_SPRINTF(buf, _nc_SLIMIT(sizeof(buf))
710                             "%s$<%d>", C_CR, carriage_return_delay);
711                 carriage_return = _nc_save_str(buf);
712             } else
713                 carriage_return = _nc_save_str(C_CR);
714         }
715         if (WANTED(cursor_left)) {
716             if (backspace_delay > 0) {
717                 _nc_SPRINTF(buf, _nc_SLIMIT(sizeof(buf))
718                             "%s$<%d>", C_BS, backspace_delay);
719                 cursor_left = _nc_save_str(buf);
720             } else if (backspaces_with_bs == 1)
721                 cursor_left = _nc_save_str(C_BS);
722             else if (PRESENT(backspace_if_not_bs))
723                 cursor_left = backspace_if_not_bs;
724         }
725         /* vi doesn't use "do", but it does seem to use nl (or '\n') instead */
726         if (WANTED(cursor_down)) {
727             if (PRESENT(linefeed_if_not_lf))
728                 cursor_down = linefeed_if_not_lf;
729             else if (linefeed_is_newline != 1) {
730                 if (new_line_delay > 0) {
731                     _nc_SPRINTF(buf, _nc_SLIMIT(sizeof(buf))
732                                 "%s$<%d>", C_LF, new_line_delay);
733                     cursor_down = _nc_save_str(buf);
734                 } else
735                     cursor_down = _nc_save_str(C_LF);
736             }
737         }
738         if (WANTED(scroll_forward) && crt_no_scrolling != 1) {
739             if (PRESENT(linefeed_if_not_lf))
740                 cursor_down = linefeed_if_not_lf;
741             else if (linefeed_is_newline != 1) {
742                 if (new_line_delay > 0) {
743                     _nc_SPRINTF(buf, _nc_SLIMIT(sizeof(buf))
744                                 "%s$<%d>", C_LF, new_line_delay);
745                     scroll_forward = _nc_save_str(buf);
746                 } else
747                     scroll_forward = _nc_save_str(C_LF);
748             }
749         }
750         if (WANTED(newline)) {
751             if (linefeed_is_newline == 1) {
752                 if (new_line_delay > 0) {
753                     _nc_SPRINTF(buf, _nc_SLIMIT(sizeof(buf))
754                                 "%s$<%d>", C_LF, new_line_delay);
755                     newline = _nc_save_str(buf);
756                 } else
757                     newline = _nc_save_str(C_LF);
758             } else if (PRESENT(carriage_return) && PRESENT(scroll_forward)) {
759                 _nc_str_init(&result, buf, sizeof(buf));
760                 if (_nc_safe_strcat(&result, carriage_return)
761                     && _nc_safe_strcat(&result, scroll_forward))
762                     newline = _nc_save_str(buf);
763             } else if (PRESENT(carriage_return) && PRESENT(cursor_down)) {
764                 _nc_str_init(&result, buf, sizeof(buf));
765                 if (_nc_safe_strcat(&result, carriage_return)
766                     && _nc_safe_strcat(&result, cursor_down))
767                     newline = _nc_save_str(buf);
768             }
769         }
770     }
771
772     /*
773      * Inverse of capdefaults.c code ends here.
774      * ----------------------------------------------------------------------
775      *
776      * TERMCAP-TO TERMINFO MAPPINGS FOR SOURCE TRANSLATION
777      *
778      * These translations will *not* be inverted by tgetent().
779      */
780
781     if (!has_base) {
782         /*
783          * We wait until now to decide if we've got a working cr because even
784          * one that doesn't work can be used for newline. Unfortunately the
785          * space allocated for it is wasted.
786          */
787         if (return_does_clr_eol == 1 || no_correctly_working_cr == 1)
788             carriage_return = ABSENT_STRING;
789
790         /*
791          * Supposedly most termcap entries have ta now and '\t' is no longer a
792          * default, but it doesn't seem to be true...
793          */
794         if (WANTED(tab)) {
795             if (horizontal_tab_delay > 0) {
796                 _nc_SPRINTF(buf, _nc_SLIMIT(sizeof(buf))
797                             "%s$<%d>", C_HT, horizontal_tab_delay);
798                 tab = _nc_save_str(buf);
799             } else
800                 tab = _nc_save_str(C_HT);
801         }
802         if (init_tabs == ABSENT_NUMERIC && has_hardware_tabs == TRUE)
803             init_tabs = 8;
804
805         /*
806          * Assume we can beep with ^G unless we're given bl@.
807          */
808         if (WANTED(bell))
809             bell = _nc_save_str("\007");
810     }
811
812     /*
813      * Translate the old termcap :pt: capability to it#8 + ht=\t
814      */
815     if (has_hardware_tabs == TRUE) {
816         if (init_tabs != 8 && init_tabs != ABSENT_NUMERIC)
817             _nc_warning("hardware tabs with a width other than 8: %d", init_tabs);
818         else {
819             if (PRESENT(tab) && _nc_capcmp(tab, C_HT))
820                 _nc_warning("hardware tabs with a non-^I tab string %s",
821                             _nc_visbuf(tab));
822             else {
823                 if (WANTED(tab))
824                     tab = _nc_save_str(C_HT);
825                 init_tabs = 8;
826             }
827         }
828     }
829     /*
830      * Now translate the ko capability, if there is one.  This
831      * isn't from mytinfo...
832      */
833     if (PRESENT(other_non_function_keys)) {
834         char *base;
835         char *bp, *cp, *dp;
836         struct name_table_entry const *from_ptr;
837         struct name_table_entry const *to_ptr;
838         char buf2[MAX_TERMINFO_LENGTH];
839         bool foundim;
840
841         /* we're going to use this for a special case later */
842         dp = strchr(other_non_function_keys, 'i');
843         foundim = (dp != 0) && (dp[1] == 'm');
844
845         /* look at each comma-separated capability in the ko string... */
846         for (base = other_non_function_keys;
847              (cp = strchr(base, ',')) != 0;
848              base = cp + 1) {
849             size_t len = (unsigned) (cp - base);
850             size_t n;
851             assoc const *ap = 0;
852
853             for (n = 0; n < SIZEOF(ko_xlate); ++n) {
854                 if (len == strlen(ko_xlate[n].from)
855                     && strncmp(ko_xlate[n].from, base, len) == 0) {
856                     ap = ko_xlate + n;
857                     break;
858                 }
859             }
860             if (ap == 0) {
861                 _nc_warning("unknown capability `%.*s' in ko string",
862                             (int) len, base);
863                 continue;
864             } else if (ap->to[0] == '\0')       /* ignore it */
865                 continue;
866
867             /* now we know we found a match in ko_table, so... */
868
869             from_ptr = _nc_find_entry(ap->from, _nc_get_hash_table(TRUE));
870             to_ptr = _nc_find_entry(ap->to, _nc_get_hash_table(FALSE));
871
872             if (!from_ptr || !to_ptr)   /* should never happen! */
873                 _nc_err_abort("ko translation table is invalid, I give up");
874
875             if (WANTED(tp->Strings[from_ptr->nte_index])) {
876                 _nc_warning("no value for ko capability %s", ap->from);
877                 continue;
878             }
879
880             if (tp->Strings[to_ptr->nte_index]) {
881                 const char *s = tp->Strings[from_ptr->nte_index];
882                 const char *t = tp->Strings[to_ptr->nte_index];
883                 /* There's no point in warning about it if it's the same
884                  * string; that's just an inefficiency.
885                  */
886                 if (VALID_STRING(s) && VALID_STRING(t) && strcmp(s, t) != 0)
887                     _nc_warning("%s (%s) already has an explicit value %s, ignoring ko",
888                                 ap->to, ap->from, t);
889                 continue;
890             }
891
892             /*
893              * The magic moment -- copy the mapped key string over,
894              * stripping out padding.
895              */
896             bp = tp->Strings[from_ptr->nte_index];
897             if (VALID_STRING(bp)) {
898                 for (dp = buf2; *bp; bp++) {
899                     if (bp[0] == '$' && bp[1] == '<') {
900                         while (*bp && *bp != '>') {
901                             ++bp;
902                         }
903                     } else
904                         *dp++ = *bp;
905                 }
906                 *dp = '\0';
907
908                 tp->Strings[to_ptr->nte_index] = _nc_save_str(buf2);
909             } else {
910                 tp->Strings[to_ptr->nte_index] = bp;
911             }
912         }
913
914         /*
915          * Note: ko=im and ko=ic both want to grab the `Insert'
916          * keycap.  There's a kich1 but no ksmir, so the ic capability
917          * got mapped to kich1 and im to kIC to avoid a collision.
918          * If the description has im but not ic, hack kIC back to kich1.
919          */
920         if (foundim && WANTED(key_ic) && PRESENT(key_sic)) {
921             key_ic = key_sic;
922             key_sic = ABSENT_STRING;
923         }
924     }
925
926     if (!has_base) {
927         if (!hard_copy) {
928             if (WANTED(key_backspace))
929                 key_backspace = _nc_save_str(C_BS);
930             if (WANTED(key_left))
931                 key_left = _nc_save_str(C_BS);
932             if (WANTED(key_down))
933                 key_down = _nc_save_str(C_LF);
934         }
935     }
936
937     /*
938      * Translate XENIX forms characters.
939      */
940     if (PRESENT(acs_ulcorner) ||
941         PRESENT(acs_llcorner) ||
942         PRESENT(acs_urcorner) ||
943         PRESENT(acs_lrcorner) ||
944         PRESENT(acs_ltee) ||
945         PRESENT(acs_rtee) ||
946         PRESENT(acs_btee) ||
947         PRESENT(acs_ttee) ||
948         PRESENT(acs_hline) ||
949         PRESENT(acs_vline) ||
950         PRESENT(acs_plus)) {
951         char buf2[MAX_TERMCAP_LENGTH];
952
953         _nc_str_init(&result, buf2, sizeof(buf2));
954         _nc_safe_strcat(&result, acs_chars);
955
956         append_acs(&result, 'j', acs_lrcorner);
957         append_acs(&result, 'k', acs_urcorner);
958         append_acs(&result, 'l', acs_ulcorner);
959         append_acs(&result, 'm', acs_llcorner);
960         append_acs(&result, 'n', acs_plus);
961         append_acs(&result, 'q', acs_hline);
962         append_acs(&result, 't', acs_ltee);
963         append_acs(&result, 'u', acs_rtee);
964         append_acs(&result, 'v', acs_btee);
965         append_acs(&result, 'w', acs_ttee);
966         append_acs(&result, 'x', acs_vline);
967
968         if (buf2[0]) {
969             acs_chars = _nc_save_str(buf2);
970             _nc_warning("acsc string synthesized from XENIX capabilities");
971         }
972     } else if (acs_chars == ABSENT_STRING
973                && PRESENT(enter_alt_charset_mode)
974                && PRESENT(exit_alt_charset_mode)) {
975         acs_chars = _nc_save_str(VT_ACSC);
976     }
977 }
978
979 static void
980 postprocess_terminfo(TERMTYPE2 *tp)
981 {
982     /*
983      * TERMINFO-TO-TERMINFO MAPPINGS FOR SOURCE TRANSLATION
984      * ----------------------------------------------------------------------
985      */
986
987     /*
988      * Translate AIX forms characters.
989      */
990     if (PRESENT(box_chars_1)) {
991         char buf2[MAX_TERMCAP_LENGTH];
992         string_desc result;
993
994         _nc_str_init(&result, buf2, sizeof(buf2));
995         _nc_safe_strcat(&result, acs_chars);
996
997         append_acs0(&result, 'l', box_chars_1[0]);      /* ACS_ULCORNER */
998         append_acs0(&result, 'q', box_chars_1[1]);      /* ACS_HLINE */
999         append_acs0(&result, 'k', box_chars_1[2]);      /* ACS_URCORNER */
1000         append_acs0(&result, 'x', box_chars_1[3]);      /* ACS_VLINE */
1001         append_acs0(&result, 'j', box_chars_1[4]);      /* ACS_LRCORNER */
1002         append_acs0(&result, 'm', box_chars_1[5]);      /* ACS_LLCORNER */
1003         append_acs0(&result, 'w', box_chars_1[6]);      /* ACS_TTEE */
1004         append_acs0(&result, 'u', box_chars_1[7]);      /* ACS_RTEE */
1005         append_acs0(&result, 'v', box_chars_1[8]);      /* ACS_BTEE */
1006         append_acs0(&result, 't', box_chars_1[9]);      /* ACS_LTEE */
1007         append_acs0(&result, 'n', box_chars_1[10]);     /* ACS_PLUS */
1008
1009         if (buf2[0]) {
1010             acs_chars = _nc_save_str(buf2);
1011             _nc_warning("acsc string synthesized from AIX capabilities");
1012             box_chars_1 = ABSENT_STRING;
1013         }
1014     }
1015     /*
1016      * ----------------------------------------------------------------------
1017      */
1018 }
1019
1020 /*
1021  * Do a linear search through the terminfo tables to find a given full-name.
1022  * We don't expect to do this often, so there's no hashing function.
1023  *
1024  * In effect, this scans through the 3 lists of full-names, and looks them
1025  * up in _nc_info_table, which is organized so that the nte_index fields are
1026  * sorted, but the nte_type fields are not necessarily grouped together.
1027  */
1028 static struct name_table_entry const *
1029 lookup_fullname(const char *find)
1030 {
1031     int state = -1;
1032
1033     for (;;) {
1034         int count = 0;
1035         NCURSES_CONST char *const *names;
1036
1037         switch (++state) {
1038         case BOOLEAN:
1039             names = boolfnames;
1040             break;
1041         case STRING:
1042             names = strfnames;
1043             break;
1044         case NUMBER:
1045             names = numfnames;
1046             break;
1047         default:
1048             return NOTFOUND;
1049         }
1050
1051         for (count = 0; names[count] != 0; count++) {
1052             if (!strcmp(names[count], find)) {
1053                 struct name_table_entry const *entry_ptr = _nc_get_table(FALSE);
1054                 while (entry_ptr->nte_type != state
1055                        || entry_ptr->nte_index != count)
1056                     entry_ptr++;
1057                 return entry_ptr;
1058             }
1059         }
1060     }
1061 }
1062
1063 /* parse_entry.c ends here */