robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

Kylefeat(tui): $NVIM_TERMDEFS can override builtin terminfo #3955584d5c5f4bf

master
18.6 KiB746 linesraw
1// Built-in fallback terminfo entries.
2
3#include <stdbool.h>
4#include <string.h>
5
6#ifdef HAVE_UNIBILIUM
7# include <unibilium.h>
8#endif
9
10#include "klib/kvec.h"
11#include "nvim/api/private/defs.h"
12#include "nvim/api/private/helpers.h"
13#include "nvim/ascii_defs.h"
14#include "nvim/charset.h"
15#include "nvim/memory.h"
16#include "nvim/tui/terminfo.h"
17#include "nvim/tui/terminfo_builtin.h"
18
19#ifdef __FreeBSD__
20# include "nvim/os/os.h"
21#endif
22
23typedef struct {
24  long nums[20];
25  char *strings[20];
26  size_t offset;
27} TPSTACK;
28
29#include "tui/terminfo.c.generated.h"
30
31bool terminfo_is_term_family(const char *term, const char *family)
32{
33  if (!term) {
34    return false;
35  }
36  size_t tlen = strlen(term);
37  size_t flen = strlen(family);
38  return tlen >= flen
39         && 0 == memcmp(term, family, flen)
40         // Per commentary in terminfo, minus is the only valid suffix separator.
41         // The screen terminfo may have a terminal name like screen.xterm. By making
42         // the dot(.) a valid separator, such terminal names will also be the
43         // terminal family of the screen.
44         && (NUL == term[flen] || '-' == term[flen] || '.' == term[flen]);
45}
46
47bool terminfo_is_bsd_console(const char *term)
48{
49#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) \
50  || defined(__DragonFly__)
51  if (strequal(term, "vt220")         // OpenBSD
52      || strequal(term, "vt100")) {   // NetBSD
53    return true;
54  }
55# if defined(__FreeBSD__)
56  // FreeBSD console sets TERM=xterm, but it does not support xterm features
57  // like cursor-shaping. Assume that TERM=xterm is degraded. #8644
58  return strequal(term, "xterm") && os_env_exists("XTERM_VERSION", true);
59# endif
60#endif
61  return false;
62}
63
64/// Loads a built-in terminfo db when we (unibilium) failed to load a terminfo
65/// record from the environment (termcap systems, unrecognized $TERM, …).
66/// We do not attempt to detect xterm pretenders here.
67///
68/// @param term $TERM value
69/// @param[out,static] termname decided builtin 'term' name
70/// @return [allocated] terminfo structure
71const TerminfoEntry *terminfo_from_builtin(const char *term, char **termname)
72{
73  if (strequal(term, "ghostty") || strequal(term, "xterm-ghostty")) {
74    *termname = "ghostty";
75    return &ghostty_terminfo;
76  } else if (terminfo_is_term_family(term, "xterm")) {
77    *termname = "xterm";
78    return &xterm_256colour_terminfo;
79  } else if (terminfo_is_term_family(term, "screen")) {
80    *termname = "screen";
81    return &screen_256colour_terminfo;
82  } else if (terminfo_is_term_family(term, "tmux")) {
83    *termname = "tmux";
84    return &tmux_256colour_terminfo;
85  } else if (terminfo_is_term_family(term, "rxvt")) {
86    *termname = "rxvt";
87    return &rxvt_256colour_terminfo;
88  } else if (terminfo_is_term_family(term, "putty")) {
89    *termname = "putty";
90    return &putty_256colour_terminfo;
91  } else if (terminfo_is_term_family(term, "linux")) {
92    *termname = "linux";
93    return &linux_16colour_terminfo;
94  } else if (terminfo_is_term_family(term, "interix")) {
95    *termname = "interix";
96    return &interix_8colour_terminfo;
97  } else if (terminfo_is_term_family(term, "iterm")
98             || terminfo_is_term_family(term, "iterm2")
99             || terminfo_is_term_family(term, "iTerm.app")
100             || terminfo_is_term_family(term, "iTerm2.app")) {
101    *termname = "iterm";
102    return &iterm_256colour_terminfo;
103  } else if (terminfo_is_term_family(term, "st")) {
104    *termname = "st";
105    return &st_256colour_terminfo;
106  } else if (terminfo_is_term_family(term, "gnome")
107             || terminfo_is_term_family(term, "vte")) {
108    *termname = "vte";
109    return &vte_256colour_terminfo;
110  } else if (terminfo_is_term_family(term, "cygwin")) {
111    *termname = "cygwin";
112    return &cygwin_terminfo;
113  } else if (terminfo_is_term_family(term, "win32con")) {
114    *termname = "win32con";
115    return &win32con_terminfo;
116  } else if (terminfo_is_term_family(term, "conemu")) {
117    *termname = "conemu";
118    return &conemu_terminfo;
119  } else if (terminfo_is_term_family(term, "vtpcon")) {
120    *termname = "vtpcon";
121    return &vtpcon_terminfo;
122  } else {
123    *termname = "ansi";
124    return &ansi_terminfo;
125  }
126}
127
128bool terminfo_from_database(TerminfoEntry *ti, char *termname, Arena *arena)
129{
130#ifdef HAVE_UNIBILIUM
131  unibi_term *ut = unibi_from_term(termname);
132  if (!ut) {
133    return false;
134  }
135
136  ti->back_color_erase = unibi_get_bool(ut, unibi_back_color_erase);
137  ti->max_colors = unibi_get_num(ut, unibi_max_colors);
138  ti->lines = unibi_get_num(ut, unibi_lines);
139  ti->columns = unibi_get_num(ut, unibi_columns);
140
141  // Check for Tc or RGB
142  ti->Tc = false;
143  ti->RGB = false;
144  ti->Su = false;
145  for (size_t i = 0; i < unibi_count_ext_bool(ut); i++) {
146    const char *n = unibi_get_ext_bool_name(ut, i);
147    if (n && !strcmp(n, "Tc")) {
148      ti->Tc = true;
149    } else if (n && !strcmp(n, "RGB")) {
150      ti->RGB = true;
151    } else if (n && !strcmp(n, "Su")) {
152      ti->Su = true;
153    }
154  }
155
156  static const enum unibi_string uni_ids[] = {
157# define X(name) unibi_##name,
158    XLIST_TERMINFO_BUILTIN
159# undef X
160  };
161
162  for (size_t i = 0; i < ARRAY_SIZE(uni_ids); i++) {
163    const char *val = unibi_get_str(ut, uni_ids[i]);
164    ti->defs[i] = val ? arena_strdup(arena, val) : NULL;
165  }
166
167  static const char *uni_ext[] = {
168# define X(informal_name, terminfo_name) #terminfo_name,
169    XLIST_TERMINFO_EXT
170# undef X
171  };
172
173  size_t max = unibi_count_ext_str(ut);
174  for (size_t i = 0; i < ARRAY_SIZE(uni_ext); i++) {
175    const char *name = uni_ext[i];
176    for (size_t val = 0; val < max; val++) {
177      const char *n = unibi_get_ext_str_name(ut, val);
178      if (n && strequal(n, name)) {
179        const char *data = unibi_get_ext_str(ut, val);
180        ti->defs[kTermExtOffset + i] = data ? arena_strdup(arena, data) : NULL;
181        break;
182      }
183    }
184  }
185
186# define X(name) { unibi_key_##name, unibi_string_begin_ },
187# define Y(name) { unibi_key_##name, unibi_key_s##name },
188  static const enum unibi_string uni_keys[][2] = {
189    XYLIST_TERMINFO_KEYS
190  };
191# undef X
192# undef Y
193
194  for (size_t i = 0; i < ARRAY_SIZE(uni_keys); i++) {
195    const char *val = unibi_get_str(ut, uni_keys[i][0]);
196    if (val) {
197      ti->keys[i][0] = arena_strdup(arena, val);
198      if (uni_keys[i][1] != unibi_string_begin_) {
199        const char *sval = unibi_get_str(ut, uni_keys[i][1]);
200        ti->keys[i][1] = sval ? arena_strdup(arena, sval) : NULL;
201      }
202    }
203  }
204
205  static const enum unibi_string uni_fkeys[] = {
206# define X(name, idx) unibi_key_##name,
207    XLIST_TERMINFO_FKEYS
208# undef X
209  };
210
211  for (size_t i = 0; i < ARRAY_SIZE(uni_fkeys); i++) {
212    const char *val = unibi_get_str(ut, uni_fkeys[i]);
213    ti->f_keys[i] = val ? arena_strdup(arena, val) : NULL;
214  }
215
216  unibi_destroy(ut);
217  return true;
218#else
219  return false;
220#endif
221}
222
223static const char *fmt(bool val)
224{
225  return val ? "true" : "false";
226}
227
228/// Dumps termcap info to the messages area.
229/// Serves a similar purpose as Vim `:set termcap` (removed in Nvim).
230///
231/// @return allocated string
232String terminfo_info_msg(const TerminfoEntry *ti, const char *termname, bool from_db)
233{
234  StringBuilder data = KV_INITIAL_VALUE;
235
236  kv_printf(data, "&term: %s\n", termname);
237  if (from_db) {
238    kv_printf(data, "using terminfo database\n");
239  } else {
240    kv_printf(data, "using builtin terminfo\n");
241  }
242  kv_printf(data, "\n");
243
244  kv_printf(data, "Boolean capabilities:\n");
245  kv_printf(data, "  back_color_erase: %s\n", fmt(ti->back_color_erase));
246  kv_printf(data, "  truecolor ('Tc'): %s\n", fmt(ti->Tc));
247  kv_printf(data, "  RGB: %s\n", fmt(ti->RGB));
248  kv_printf(data, "  extended underline ('Su'): %s\n", fmt(ti->Su));
249  kv_printf(data, "\n");
250
251  kv_printf(data, "Numeric capabilities: (-1 for unknown)\n");
252  kv_printf(data, "  lines: %d\n", ti->lines);
253  kv_printf(data, "  columns: %d\n", ti->columns);
254  kv_printf(data, "  max_colors: %d\n", ti->max_colors);
255  kv_printf(data, "\n");
256
257  kv_printf(data, "String capabilities:\n");
258
259  static const char *string_names[] = {
260#define X(name) #name,
261    XLIST_TERMINFO_BUILTIN
262#undef X
263#define X(internal_name, terminfo_name) (#internal_name " (" #terminfo_name ")"),
264    XLIST_TERMINFO_EXT
265#undef X
266  };
267
268  for (size_t i = 0; i < ARRAY_SIZE(string_names); i++) {
269    const char *s = ti->defs[i];
270    if (s) {
271      kv_printf(data, "  %-31s = ", string_names[i]);
272      // Most of these strings will contain escape sequences.
273      kv_transstr(&data, s, false);
274      kv_push(data, '\n');
275    }
276  }
277
278  static const char *key_names[] = {
279#define X(name) #name,
280#define Y(name) #name,
281    XYLIST_TERMINFO_KEYS
282#undef X
283#undef Y
284  };
285
286  for (size_t i = 0; i < ARRAY_SIZE(key_names); i++) {
287    const char *s = ti->keys[i][0];
288    if (s) {
289      kv_printf(data, "  key_%-27s = ", key_names[i]);
290      kv_transstr(&data, s, false);
291      const char *ss = ti->keys[i][1];
292      if (ss) {
293        kv_printf(data, ", key_s%s = ", key_names[i]);
294        kv_transstr(&data, ss, false);
295      }
296      kv_push(data, '\n');
297    }
298  }
299
300  static const char *fkey_names[] = {
301#define X(name, idx) #name,
302    XLIST_TERMINFO_FKEYS
303#undef X
304  };
305
306  for (size_t i = 0; i < ARRAY_SIZE(fkey_names); i++) {
307    const char *s = ti->f_keys[i];
308    if (s) {
309      kv_printf(data, "  key_%-27s = ", fkey_names[i]);
310      kv_transstr(&data, s, false);
311      kv_push(data, '\n');
312    }
313  }
314
315  kv_push(data, NUL);
316  return cbuf_as_string(data.items, data.size - 1);
317}
318
319// The implementation of terminfo_fmt() is based on NetBSD libterminfo,
320// with full license reproduced below
321
322// Copyright (c) 2009, 2011, 2013 The NetBSD Foundation, Inc.
323//
324// This code is derived from software contributed to The NetBSD Foundation
325// by Roy Marples.
326//
327// Redistribution and use in source and binary forms, with or without
328// modification, are permitted provided that the following conditions
329// are met:
330// 1. Redistributions of source code must retain the above copyright
331//    notice, this list of conditions and the following disclaimer.
332// 2. Redistributions in binary form must reproduce the above copyright
333//    notice, this list of conditions and the following disclaimer in the
334//    documentation and/or other materials provided with the distribution.
335//
336// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
337// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
338// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
339// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
340// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
341// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
342// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
343// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
344// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
345// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
346
347// nvim modifications:
348// - use typesafe param args instead of va_args and piss
349// - caller provides the output buffer
350// - static variables are not preserved
351
352static int push(long num, char *string, TPSTACK *stack)
353{
354  if (stack->offset >= ARRAY_SIZE(stack->nums)) {
355    return -1;
356  }
357  stack->nums[stack->offset] = num;
358  stack->strings[stack->offset] = string;
359  stack->offset++;
360  return 0;
361}
362
363static int pop(long *num, char **string, TPSTACK *stack)
364{
365  if (stack->offset == 0) {
366    if (num) {
367      *num = 0;
368    }
369    if (string) {
370      *string = NULL;
371    }
372    return -1;
373  }
374  stack->offset--;
375  if (num) {
376    *num = stack->nums[stack->offset];
377  }
378  if (string) {
379    *string = stack->strings[stack->offset];
380  }
381  return 0;
382}
383
384static bool ochar(char **buf, const char *buf_end, int c)
385{
386  if (c == 0) {
387    c = 0200;
388  }
389  // Check we have space and a terminator
390  if (buf_end - *buf < 2) {
391    return 0;
392  }
393  *(*buf)++ = (char)c;
394  return 1;
395}
396
397static bool onum(char **buf, const char *buf_end, const char *fmt, int num, size_t len)
398{
399  const size_t LONG_STR_MAX = 21;
400  len = MAX(len, LONG_STR_MAX);
401
402  if (buf_end - *buf < (ssize_t)(len + 2)) {
403    return 0;
404  }
405  int l = snprintf(*buf, len + 2, fmt, num);
406  if (l == -1) {
407    return 0;
408  }
409  *buf += l;
410  return true;
411}
412
413/// @return number of chars printed or 0 for any error
414size_t terminfo_fmt(char *buf_start, char *buf_end, const char *str, TPVAR params[9])
415{
416  char c, fmt[64], *fp, *ostr;
417  long val, val2;
418  long dnums[26];  // dynamic variables a-z, not preserved
419  long snums[26];  // static variables a-z, not preserved EITHER HAHA
420  memset(dnums, 0, sizeof snums);
421  memset(snums, 0, sizeof snums);
422
423  char *buf = buf_start;
424
425  size_t l, width, precision, olen;
426  TPSTACK stack;
427  unsigned done, dot, minus;
428
429  memset(&stack, 0, sizeof(stack));
430  while ((c = *str++) != '\0') {
431    if (c != '%' || (c = *str++) == '%') {
432      if (c == '\0') {
433        break;
434      }
435      if (!ochar(&buf, buf_end, c)) {
436        return false;
437      }
438      continue;
439    }
440
441    // Handle formatting.
442    fp = fmt;
443    *fp++ = '%';
444    done = dot = minus = 0;
445    width = precision = 0;
446    val = 0;
447    while (done == 0 && (size_t)(fp - fmt) < sizeof(fmt)) {
448      switch (c) {
449      case 'c':
450      case 's':
451        *fp++ = c;
452        done = 1;
453        break;
454      case 'd':
455      case 'o':
456      case 'x':
457      case 'X':
458        *fp++ = 'l';
459        *fp++ = c;
460        done = 1;
461        break;
462      case '#':
463      case ' ':
464        *fp++ = c;
465        break;
466      case '.':
467        *fp++ = c;
468        if (dot == 0) {
469          dot = 1;
470          width = (size_t)val;
471        } else {
472          done = 2;
473        }
474        val = 0;
475        break;
476      case ':':
477        minus = 1;
478        break;
479      case '-':
480        if (minus) {
481          *fp++ = c;
482        } else {
483          done = 1;
484        }
485        break;
486      default:
487        if (isdigit((unsigned char)c)) {
488          val = (val * 10) + (c - '0');
489          if (val > 10000) {
490            done = 2;
491          } else {
492            *fp++ = c;
493          }
494        } else {
495          done = 1;
496        }
497      }
498      if (done == 0) {
499        c = *str++;
500      }
501    }
502    if (done == 2) {
503      // Found an error in the format
504      fp = fmt + 1;
505      *fp = *str;
506      olen = 0;
507    } else {
508      if (dot == 0) {
509        width = (size_t)val;
510      } else {
511        precision = (size_t)val;
512      }
513      olen = MAX(width, precision);
514    }
515    *fp++ = '\0';
516
517    // Handle commands
518    switch (c) {
519    case 'c':
520      pop(&val, NULL, &stack);
521      if (!ochar(&buf, buf_end, (unsigned char)val)) {
522        return false;
523      }
524      break;
525    case 's':
526      pop(NULL, &ostr, &stack);
527      if (ostr != NULL) {
528        int r;
529
530        l = strlen(ostr);
531        if (l < olen) {
532          l = olen;
533        }
534        if ((size_t)(buf_end - buf) < (l + 1)) {
535          return false;
536        }
537        r = snprintf(buf, l + 1,
538                     fmt, ostr);
539        if (r != -1) {
540          buf += (size_t)r;
541        }
542      }
543      break;
544    case 'l':
545      pop(NULL, &ostr, &stack);
546      if (ostr == NULL) {
547        l = 0;
548      } else {
549        l = strlen(ostr);
550      }
551      push((long)l, NULL, &stack);
552      break;
553    case 'd':
554    case 'o':
555    case 'x':
556    case 'X':
557      pop(&val, NULL, &stack);
558      if (onum(&buf, buf_end, fmt, (int)val, olen) == 0) {
559        return 0;
560      }
561      break;
562    case 'p':
563      if (*str < '1' || *str > '9') {
564        break;
565      }
566      l = (size_t)(*str++ - '1');
567      if (push(params[l].num, params[l].string, &stack)) {
568        return 0;
569      }
570      break;
571    case 'P':
572      pop(&val, NULL, &stack);
573      if (*str >= 'a' && *str <= 'z') {
574        dnums[*str - 'a'] = val;
575      } else if (*str >= 'A' && *str <= 'Z') {
576        snums[*str - 'A'] = val;
577      }
578      break;
579    case 'g':
580      if (*str >= 'a' && *str <= 'z') {
581        if (push(dnums[*str - 'a'], NULL, &stack)) {
582          return 0;
583        }
584      } else if (*str >= 'A' && *str <= 'Z') {
585        if (push(snums[*str - 'A'], NULL, &stack)) {
586          return 0;
587        }
588      }
589      break;
590    case 'i':
591      params[0].num++;
592      params[1].num++;
593      break;
594    case '\'':
595      if (push((long)(unsigned char)(*str++), NULL, &stack)) {
596        return 0;
597      }
598      while (*str != '\0' && *str != '\'') {
599        str++;
600      }
601      if (*str == '\'') {
602        str++;
603      }
604      break;
605    case '{':
606      val = 0;
607      for (; isdigit((unsigned char)(*str)); str++) {
608        val = (val * 10) + (*str - '0');
609      }
610      if (push(val, NULL, &stack)) {
611        return 0;
612      }
613      while (*str != '\0' && *str != '}') {
614        str++;
615      }
616      if (*str == '}') {
617        str++;
618      }
619      break;
620    case '+':
621    case '-':
622    case '*':
623    case '/':
624    case 'm':
625    case 'A':
626    case 'O':
627    case '&':
628    case '|':
629    case '^':
630    case '=':
631    case '<':
632    case '>':
633      pop(&val, NULL, &stack);
634      pop(&val2, NULL, &stack);
635      switch (c) {
636      case '+':
637        val = val + val2;
638        break;
639      case '-':
640        val = val2 - val;
641        break;
642      case '*':
643        val = val * val2;
644        break;
645      case '/':
646        val = val ? val2 / val : 0;
647        break;
648      case 'm':
649        val = val ? val2 % val : 0;
650        break;
651      case 'A':
652        val = val && val2;
653        break;
654      case 'O':
655        val = val || val2;
656        break;
657      case '&':
658        val = val & val2;
659        break;
660      case '|':
661        val = val | val2;
662        break;
663      case '^':
664        val = val ^ val2;
665        break;
666      case '=':
667        val = val == val2;
668        break;
669      case '<':
670        val = val2 < val;
671        break;
672      case '>':
673        val = val2 > val;
674        break;
675      }
676      if (push(val, NULL, &stack)) {
677        return 0;
678      }
679      break;
680    case '!':
681    case '~':
682      pop(&val, NULL, &stack);
683      switch (c) {
684      case '!':
685        val = !val;
686        break;
687      case '~':
688        val = ~val;
689        break;
690      }
691      if (push(val, NULL, &stack)) {
692        return 0;
693      }
694      break;
695    case '?':  // if
696      break;
697    case 't':  // then
698      pop(&val, NULL, &stack);
699      if (val == 0) {
700        l = 0;
701        for (; *str != '\0'; str++) {
702          if (*str != '%') {
703            continue;
704          }
705          str++;
706          if (*str == '?') {
707            l++;
708          } else if (*str == ';') {
709            if (l > 0) {
710              l--;
711            } else {
712              str++;
713              break;
714            }
715          } else if (*str == 'e' && l == 0) {
716            str++;
717            break;
718          }
719        }
720      }
721      break;
722    case 'e':  // else
723      l = 0;
724      for (; *str != '\0'; str++) {
725        if (*str != '%') {
726          continue;
727        }
728        str++;
729        if (*str == '?') {
730          l++;
731        } else if (*str == ';') {
732          if (l > 0) {
733            l--;
734          } else {
735            str++;
736            break;
737          }
738        }
739      }
740      break;
741    case ';':  // fi
742      break;
743    }
744  }
745  return (size_t)(buf - buf_start);
746}