robin/laufey

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

robinmerge: 9a29622b3b00ddb601

master
89.6 KiB2728 linesraw
1// Terminal UI functions. Invoked by the UI process (ui_client.c), not the server.
2
3#include <assert.h>
4#include <inttypes.h>
5#include <signal.h>
6#include <stdbool.h>
7#include <stdio.h>
8#include <stdlib.h>
9#include <string.h>
10#include <uv.h>
11
12#include "auto/config.h"
13#include "klib/kvec.h"
14#include "nvim/api/private/defs.h"
15#include "nvim/api/private/helpers.h"
16#include "nvim/ascii_defs.h"
17#include "nvim/charset.h"
18#include "nvim/cursor_shape.h"
19#include "nvim/event/defs.h"
20#include "nvim/event/loop.h"
21#include "nvim/event/multiqueue.h"
22#include "nvim/event/signal.h"
23#include "nvim/event/stream.h"
24#include "nvim/globals.h"
25#include "nvim/grid.h"
26#include "nvim/highlight_defs.h"
27#include "nvim/log.h"
28#include "nvim/lua/executor.h"
29#include "nvim/macros_defs.h"
30#include "nvim/main.h"
31#include "nvim/map_defs.h"
32#include "nvim/mbyte.h"
33#include "nvim/memory.h"
34#include "nvim/msgpack_rpc/channel.h"
35#include "nvim/os/input.h"
36#include "nvim/os/os.h"
37#include "nvim/os/os_defs.h"
38#include "nvim/os/time.h"
39#include "nvim/strings.h"
40#include "nvim/tui/input.h"
41#include "nvim/tui/termdef_field_defs.h"
42#include "nvim/tui/terminfo.h"
43#include "nvim/tui/tui.h"
44#include "nvim/tui/ugrid.h"
45#include "nvim/types_defs.h"
46#include "nvim/ui_client.h"
47#include "nvim/ui_defs.h"
48#include "nvim/vim_defs.h"
49
50#ifdef MSWIN
51# include "nvim/os/os_win_console.h"
52#endif
53
54// Maximum amount of time (in ms) to wait to receive a Device Attributes
55// response before exiting.
56#define EXIT_TIMEOUT_MS 1000
57
58#define OUTBUF_SIZE 0xffff
59
60#define TOO_MANY_EVENTS 1000000
61#define STARTS_WITH(str, prefix) \
62  (strlen(str) >= (sizeof(prefix) - 1) \
63   && 0 == memcmp((str), (prefix), sizeof(prefix) - 1))
64#define TMUX_WRAP(is_tmux, seq) \
65  ((is_tmux) ? "\x1bPtmux;\x1b" seq "\x1b\\" : seq)
66#define LINUXSET0C "\x1b[?0c"
67#define LINUXSET1C "\x1b[?1c"
68
69typedef struct {
70  int top, bot, left, right;
71} Rect;
72
73struct TUIData {
74  Loop *loop;
75  char buf[OUTBUF_SIZE];
76  char *buf_to_flush;  ///< If non-null, flush this instead of buf[].
77  size_t bufpos;
78  TermInput input;
79  uv_loop_t write_loop;
80  TerminfoEntry ti;
81  char *term;  ///< value of $TERM
82  union {
83    uv_tty_t tty;
84    uv_pipe_t pipe;
85  } output_handle;
86  bool out_isatty;
87  SignalWatcher winch_handle;
88  uv_timer_t startup_delay_timer;
89  UGrid grid;
90  kvec_t(Rect) invalid_regions;
91  int row, col;
92  int out_fd;
93  int pending_resize_events;
94  bool terminfo_found_in_db;
95  bool can_change_scroll_region;
96  bool has_left_and_right_margin_mode;
97  bool has_sync_mode;
98  bool can_set_lr_margin;  // smglr
99  bool can_scroll;
100  bool can_erase_chars;
101  bool immediate_wrap_after_last_column;
102  bool bce;
103  bool mouse_enabled;
104  bool mouse_move_enabled;
105  bool mouse_enabled_save;
106  bool title_enabled;
107  bool sync_output;
108  bool sync_output_active;
109  bool busy, is_invisible, want_invisible;
110  bool set_cursor_color_as_str;
111  bool cursor_has_color;
112  bool is_starting;
113  bool resize_events_enabled;
114
115  // Terminal modes that Nvim enabled that it must disable on exit
116  struct {
117    bool grapheme_clusters : 1;
118    bool theme_updates : 1;
119    bool resize_events : 1;
120  } modes;
121
122  FILE *screenshot;
123  cursorentry_T cursor_shapes[SHAPE_IDX_COUNT];
124  HlAttrs clear_attrs;
125  kvec_t(HlAttrs) attrs;
126  int print_attr_id;
127  bool default_attr;
128  bool set_default_colors;
129  bool can_clear_attr;
130  ModeShape showing_mode;
131  Integer verbose;
132  struct {
133    char *enable_focus_reporting;
134    char *disable_focus_reporting;
135    char *reset_scroll_region;
136    char *enter_altfont_mode;
137  } terminfo_ext;
138  bool can_set_title;
139  bool can_set_underline_color;
140  bool can_resize_screen;
141  bool stopped;
142  int width;
143  int height;
144  bool rgb;
145  bool screen_or_tmux;
146  int url;  ///< Index of URL currently being printed, if any
147  StringBuilder urlbuf;  ///< Re-usable buffer for writing OSC 8 control sequences
148  Arena ti_arena;
149};
150
151typedef enum {
152  kFlushBufPartial,
153  kFlushBufFinal,
154} FlushBufFinish;
155
156static bool cursor_style_enabled = false;
157#include "tui/tui.c.generated.h"
158
159#define TERMINFO_SEQ_LIMIT 128
160
161#define terminfo_print_num1(tui, what, num) terminfo_print_num(tui, what, num, 0, 0)
162#define terminfo_print_num2(tui, what, num1, num2) terminfo_print_num(tui, what, num1, num2, 0)
163#define terminfo_print_num3 terminfo_print_num
164
165static Set(cstr_t) urls = SET_INIT;
166
167void tui_start(TUIData **tui_p, int *width, int *height, char **term, bool *rgb)
168  FUNC_ATTR_NONNULL_ALL
169{
170  TUIData *tui = xcalloc(1, sizeof(TUIData));
171  tui->is_starting = true;
172  tui->screenshot = NULL;
173  tui->stopped = false;
174  tui->loop = &main_loop;
175  tui->url = -1;
176
177  kv_init(tui->invalid_regions);
178  kv_init(tui->urlbuf);
179  signal_watcher_init(tui->loop, &tui->winch_handle, tui);
180  signal_watcher_start(&tui->winch_handle, sigwinch_cb, SIGWINCH);
181
182  // TODO(bfredl): zero hl is empty, send this explicitly?
183  kv_push(tui->attrs, HLATTRS_INIT);
184
185  tui->input.tk_ti_hook_fn = tui_tk_ti_getstr;
186  ugrid_init(&tui->grid);
187  tui_terminal_start(tui);
188
189  uv_timer_init(&tui->loop->uv, &tui->startup_delay_timer);
190  tui->startup_delay_timer.data = tui;
191  uv_timer_start(&tui->startup_delay_timer, after_startup_cb, 100, 0);
192
193  *tui_p = tui;
194  loop_poll_events(&main_loop, 1);
195  *width = tui->width;
196  *height = tui->height;
197  *term = tui->term;
198  *rgb = tui->rgb;
199}
200
201/// Request the terminal's mode (DECRQM).
202///
203/// @see handle_modereport
204static void tui_request_term_mode(TUIData *tui, TermMode mode)
205  FUNC_ATTR_NONNULL_ALL
206{
207  // 5 bytes for \x1b[?$p, 1 byte for null terminator, 6 bytes for mode digits (more than enough)
208  char buf[12];
209  int len = snprintf(buf, sizeof(buf), "\x1b[?%d$p", (int)mode);
210  assert((len > 0) && (len < (int)sizeof(buf)));
211  out(tui, buf, (size_t)len);
212}
213
214/// Set (DECSET) or reset (DECRST) a terminal mode.
215static void tui_set_term_mode(TUIData *tui, TermMode mode, bool set)
216  FUNC_ATTR_NONNULL_ALL
217{
218  char buf[12];
219  int len = snprintf(buf, sizeof(buf), "\x1b[?%d%c", (int)mode, set ? 'h' : 'l');
220  assert((len > 0) && (len < (int)sizeof(buf)));
221  out(tui, buf, (size_t)len);
222}
223
224/// Handle a mode report (DECRPM) from the terminal.
225void tui_handle_term_mode(TUIData *tui, TermMode mode, TermModeState state)
226  FUNC_ATTR_NONNULL_ALL
227{
228  bool is_set = false;
229  switch (state) {
230  case kTermModeNotRecognized:
231  case kTermModePermanentlyReset:
232    // TODO(bfredl): This is really ILOG but we want it in all builds.
233    // add to show_verbose_terminfo() without being too racy ????
234    if (!nvim_testing) {
235      // Very noisy in CI, don't log during tests. #33599
236      WLOG("TUI: terminal mode %d unavailable, state %d", mode, state);
237    }
238    // If the mode is not recognized, or if the terminal emulator does not allow it to be changed,
239    // then there is nothing to do
240    break;
241  case kTermModePermanentlySet:
242  case kTermModeSet:
243    is_set = true;
244    FALLTHROUGH;
245  case kTermModeReset:
246    // The terminal supports changing the given mode
247    if (!nvim_testing) {
248      // Very noisy in CI, don't log during tests. #33599
249      WLOG("TUI: terminal mode %d detected, state %d", mode, state);
250    }
251    switch (mode) {
252    case kTermModeSynchronizedOutput:
253      // Ref: https://gist.github.com/christianparpart/d8a62cc1ab659194337d73e399004036
254      tui->has_sync_mode = true;
255      break;
256    case kTermModeGraphemeClusters:
257      if (!is_set) {
258        tui_set_term_mode(tui, mode, true);
259        tui->modes.grapheme_clusters = true;
260      }
261      break;
262    case kTermModeThemeUpdates:
263      if (!is_set) {
264        tui_set_term_mode(tui, mode, true);
265        tui->modes.theme_updates = true;
266      }
267      break;
268    case kTermModeResizeEvents:
269      if (!is_set) {
270        tui_set_term_mode(tui, mode, true);
271        tui->modes.resize_events = true;
272      }
273
274      // We track both whether the mode is enabled AND if Nvim was the one to enable it
275      tui->resize_events_enabled = true;
276      break;
277    case kTermModeLeftAndRightMargins:
278      tui->has_left_and_right_margin_mode = true;
279      break;
280    default:
281      break;
282    }
283  }
284}
285
286/// Query the terminal emulator to see if it supports extended underline.
287static void tui_query_extended_underline(TUIData *tui)
288{
289  // Try to set an undercurl using an SGR sequence, followed by a DECRQSS SGR query.
290  // Reset attributes first, as other code may have set attributes.
291  out(tui, S_LEN("\x1b[0m\x1b[4:3m\x1bP$qm\x1b\\"));
292  tui->print_attr_id = -1;
293}
294
295void tui_enable_extended_underline(TUIData *tui)
296{
297  terminfo_set_if_empty(tui, kTerm_set_underline_style, "\x1b[4:%p1%dm");
298  tui->can_set_underline_color = true;
299}
300
301/// Query the terminal emulator to see if it supports Kitty's keyboard protocol.
302///
303/// Write CSI ? u followed by a primary device attributes request (CSI c). If
304/// a primary device attributes response is received without first receiving an
305/// answer to the progressive enhancement query (CSI u), then the terminal does
306/// not support the Kitty keyboard protocol.
307///
308/// See https://sw.kovidgoyal.net/kitty/keyboard-protocol/#detection-of-support-for-this-protocol
309static void tui_query_kitty_keyboard(TUIData *tui)
310  FUNC_ATTR_NONNULL_ALL
311{
312  // Set the key encoding whenever the Device Attributes (DA1) response is received.
313  tui->input.callbacks.primary_device_attr = tui_set_key_encoding;
314  out(tui, S_LEN("\x1b[?u\x1b[c"));
315}
316
317void tui_set_key_encoding(TUIData *tui)
318  FUNC_ATTR_NONNULL_ALL
319{
320  switch (tui->input.key_encoding) {
321  case kKeyEncodingKitty:
322    // Progressive enhancement flags:
323    //   0b01   (1) Disambiguate escape codes
324    //   0b10   (2) Report event types
325    out(tui, S_LEN("\x1b[>3u"));
326    break;
327  case kKeyEncodingXterm:
328    out(tui, S_LEN("\x1b[>4;2m"));
329    break;
330  case kKeyEncodingLegacy:
331    break;
332  }
333}
334
335static void tui_reset_key_encoding(TUIData *tui)
336  FUNC_ATTR_NONNULL_ALL
337{
338  switch (tui->input.key_encoding) {
339  case kKeyEncodingKitty:
340    out(tui, S_LEN("\x1b[<u"));
341    break;
342  case kKeyEncodingXterm:
343    out(tui, S_LEN("\x1b[>4;0m"));
344    break;
345  case kKeyEncodingLegacy:
346    break;
347  }
348}
349
350static void tui_query_bg_color_noflush(TUIData *tui)
351  FUNC_ATTR_NONNULL_ALL
352{
353  out(tui, S_LEN("\x1b]11;?\x07\x1b[5n"));
354}
355
356/// Write the OSC 11 + DSR sequence to the terminal emulator to query the current
357/// background color, and flush the terminal.
358///
359/// Response will be handled by the TermResponse handler in _core/defaults.lua.
360void tui_query_bg_color(TUIData *tui)
361  FUNC_ATTR_NONNULL_ALL
362{
363  tui_query_bg_color_noflush(tui);
364  flush_buf(tui, kFlushBufFinal);
365}
366
367/// Use $NVIM_TERMDEFS to apply user overrides to terminfo. This is our own homebaked "terminfo",
368/// analogous to Vim's t_xx options. #37274
369///
370/// This also positions us to drop Unibilium entirely.
371static void apply_termdefs(TUIData *tui)
372{
373  // We allow empty values just to provide the user with a warning
374  if (!os_env_exists("NVIM_TERMDEFS", false)) {
375    return;
376  }
377
378  Error lua_err = ERROR_INIT;
379  Object rv = NLUA_EXEC_STATIC("return require('vim.tty')._get_termdefs()",
380                               (Array)ARRAY_DICT_INIT, kRetObject, NULL, &lua_err);
381  if (rv.type != kObjectTypeDict) {
382    return;
383  }
384
385  init_termdef_fields();
386
387  Arena err_arena = ARENA_EMPTY;
388  Array chunks = ARRAY_DICT_INIT;
389  int err_count = 0;
390
391#define PUSH_ERR(fmt, ...) \
392  do { \
393    String str = arena_printf(&err_arena, fmt, __VA_ARGS__); \
394    Array err = arena_array(&err_arena, 2); \
395    ADD(err, STRING_OBJ(str)); \
396    ADD(err, STATIC_CSTR_AS_OBJ("ErrorMsg")); \
397    ADD(chunks, ARRAY_OBJ(err)); \
398    err_count++; \
399  } while (0)
400
401  for (size_t i = 0; i < rv.data.dict.size; i++) {
402    KeyValuePair kv = rv.data.dict.items[i];
403    TermdefField *td_field = pmap_get(cstr_t)(&termdef_fields, kv.key.data);
404    if (!td_field || kv.value.type != td_field->type) {
405      PUSH_ERR("skipping invalid field in $NVIM_TERMDEFS: '%s'\n", kv.key.data);
406      continue;
407    }
408    Object val = kv.value;
409    char *dst = (char *)&tui->ti + td_field->offset;
410
411    switch (val.type) {
412    case kObjectTypeBoolean:
413      *(bool *)dst = val.data.boolean;
414      break;
415    case kObjectTypeInteger:
416      *(int *)dst = (int)val.data.integer;
417      break;
418    case kObjectTypeString:
419      *(const char **)dst = arena_strdup(&tui->ti_arena,
420                                         val.data.string.data);
421      break;
422    case kObjectTypeArray:
423      if (val.data.array.size > 2) {
424        PUSH_ERR(
425                "skipping invalid field definition in $NVIM_TERMDEFS for %s: array should have at most two entries for unshifted and shifted key variants.\n",
426                kv.key.data);
427        continue;
428      }
429      *(const char **)dst = NULL;
430      *(const char **)(dst + sizeof(char *)) = NULL;
431
432      for (size_t key_map_idx = 0; key_map_idx < val.data.array.size;
433           key_map_idx++) {
434        Object key_mapping = val.data.array.items[key_map_idx];
435        if (key_mapping.type != kObjectTypeString) {
436          PUSH_ERR(
437                  "skipping invalid field definition in $NVIM_TERMDEFS for %s[%zu]: expected type 'string'\n",
438                  kv.key.data, key_map_idx);
439          continue;
440        }
441        size_t offset = key_map_idx * sizeof(char *);
442        *(const char **)(dst + offset) = arena_strdup(&tui->ti_arena, key_mapping.data.string.data);
443      }
444      break;
445    default:
446      break;
447    }
448  }
449
450  if (err_count > 0) {
451    MAXSIZE_TEMP_ARRAY(args, 3);
452    ADD_C(args, ARRAY_OBJ(chunks));
453    ADD_C(args, BOOLEAN_OBJ(true));  // history
454    MAXSIZE_TEMP_DICT(opts, 1);
455    PUT_C(opts, "err", BOOLEAN_OBJ(true));
456    ADD_C(args, DICT_OBJ(opts));
457    rpc_send_event(ui_client_channel_id, "nvim_echo", args);
458  }
459
460  arena_mem_free(arena_finish(&err_arena));
461  kv_destroy(chunks);
462  api_free_object(rv);
463  api_clear_error(&lua_err);
464
465#undef PUSH_ERR
466}
467
468/// Enable the alternate screen and emit other control sequences to start the TUI.
469///
470/// This is also called when the TUI is resumed after being suspended. We reinitialize all state
471/// from terminfo just in case the controlling terminal has changed (#27177).
472static void terminfo_start(TUIData *tui)
473{
474  tui->bufpos = 0;
475  tui->default_attr = false;
476  tui->can_clear_attr = false;
477  tui->is_invisible = true;
478  tui->want_invisible = false;
479  tui->busy = false;
480  tui->set_cursor_color_as_str = false;
481  tui->cursor_has_color = false;
482  tui->resize_events_enabled = false;
483  tui->modes.grapheme_clusters = false;
484  tui->modes.resize_events = false;
485  tui->modes.theme_updates = false;
486  tui->showing_mode = SHAPE_IDX_N;
487  tui->terminfo_ext.enable_focus_reporting = NULL;
488  tui->terminfo_ext.disable_focus_reporting = NULL;
489
490  tui->out_fd = STDOUT_FILENO;
491  tui->out_isatty = os_isatty(tui->out_fd);
492  tui->input.tui_data = tui;
493
494  tui->ti_arena = (Arena)ARENA_EMPTY;
495  assert(tui->term == NULL);
496
497  char *term = os_getenv("TERM");
498#ifdef MSWIN
499  const char *guessed_term = NULL;
500  os_tty_guess_term(&guessed_term, tui->out_fd);
501  if (term == NULL && guessed_term != NULL) {
502    // TODO(bfredl): should be arena_strdup, make os_getenv ready for the BIG STAGE?
503    term = xstrdup(guessed_term);
504    os_setenv("TERM", guessed_term, 1);
505  }
506#endif
507
508  // Set up terminfo.
509  tui->terminfo_found_in_db = false;
510  if (term && !os_env_exists("NVIM_TERMDEFS", false)) {
511    if (terminfo_from_database(&tui->ti, term, &tui->ti_arena)) {
512      tui->term = arena_strdup(&tui->ti_arena, term);
513      tui->terminfo_found_in_db = true;
514    }
515  }
516
517  if (!tui->terminfo_found_in_db) {
518    const TerminfoEntry *new = terminfo_from_builtin(term, &tui->term);
519    // we will patch it below, so make a copy
520    memcpy(&tui->ti, new, sizeof tui->ti);
521  }
522
523  // None of the following work over SSH; see :help TERM .
524  char *colorterm = os_getenv("COLORTERM");
525  char *termprg = os_getenv("TERM_PROGRAM");
526  char *vte_version_env = os_getenv("VTE_VERSION");
527  char *konsolev_env = os_getenv("KONSOLE_VERSION");
528  char *term_program_version_env = os_getenv("TERM_PROGRAM_VERSION");
529
530  char *vte_version_end = vte_version_env;
531  int vtev = vte_version_env ? getdigits_int(&vte_version_end, false, 0) : 0;
532  bool iterm_env = termprg && strstr(termprg, "iTerm.app");
533  bool nsterm = (termprg && strstr(termprg, "Apple_Terminal"))
534                || terminfo_is_term_family(term, "nsterm");
535  bool konsole = terminfo_is_term_family(term, "konsole")
536                 || os_env_exists("KONSOLE_PROFILE_NAME", true)
537                 || os_env_exists("KONSOLE_DBUS_SESSION", true);
538  char *konsolev_end = konsolev_env;
539  int konsolev = konsolev_env ? getdigits_int(&konsolev_end, false, 0)
540                              : (konsole ? 1 : 0);
541  bool wezterm = strequal(termprg, "WezTerm");
542  const char *weztermv = wezterm ? term_program_version_env : NULL;
543  bool screen = terminfo_is_term_family(term, "screen");
544  bool tmux = terminfo_is_term_family(term, "tmux") || os_env_exists("TMUX", true);
545  tui->screen_or_tmux = screen || tmux;
546
547  // truecolor support must be checked before patching/augmenting terminfo
548  tui->rgb = term_has_truecolor(tui, colorterm);
549
550  patch_terminfo_bugs(tui, term, colorterm, vtev, konsolev, iterm_env, nsterm);
551  augment_terminfo(tui, term, vtev, konsolev, weztermv, iterm_env, nsterm);
552  apply_termdefs(tui);
553
554#define TI_HAS(name) (tui->ti.defs[name] != NULL)
555  tui->can_change_scroll_region = TI_HAS(kTerm_change_scroll_region);
556  // note: also gated by tui->has_left_and_right_margin_mode
557  tui->can_set_lr_margin = TI_HAS(kTerm_set_lr_margin);
558  tui->can_scroll =
559    TI_HAS(kTerm_delete_line)
560    && TI_HAS(kTerm_parm_delete_line)
561    && TI_HAS(kTerm_insert_line)
562    && TI_HAS(kTerm_parm_insert_line);
563  tui->can_erase_chars = TI_HAS(kTerm_erase_chars);
564  tui->immediate_wrap_after_last_column =
565    terminfo_is_term_family(term, "conemu")
566    || terminfo_is_term_family(term, "cygwin")
567    || terminfo_is_term_family(term, "win32con")
568    || terminfo_is_term_family(term, "interix");
569  tui->bce = tui->ti.back_color_erase;
570  // Set 't_Co' from the result of terminfo & fix_terminfo.
571  t_colors = tui->ti.max_colors;
572  // Enter alternate screen, save title, and clear.
573  // NOTE: Do this *before* changing terminal settings. #6433
574  terminfo_out(tui, kTerm_enter_ca_mode);
575  terminfo_out(tui, kTerm_keypad_xmit);
576  terminfo_out(tui, kTerm_clear_screen);
577
578  /// Terminals usually ignore unrecognized private modes, and there is no
579  /// known ambiguity with these. So we just set them unconditionally.
580  // Enable bracketed paste
581  tui_set_term_mode(tui, kTermModeBracketedPaste, true);
582
583  tui->has_left_and_right_margin_mode = false;
584  tui->has_sync_mode = false;
585
586  // Query support for private DEC modes that Nvim can take advantage of.
587  // Some terminals (such as Terminal.app) do not support DECRQM, so skip the query.
588  if (!nsterm) {
589    tui_request_term_mode(tui, kTermModeLeftAndRightMargins);
590    tui_request_term_mode(tui, kTermModeSynchronizedOutput);
591    tui_request_term_mode(tui, kTermModeGraphemeClusters);
592    tui_request_term_mode(tui, kTermModeThemeUpdates);
593    tui_request_term_mode(tui, kTermModeResizeEvents);
594  }
595
596  // Don't use DECRQSS in screen or tmux, as they behave strangely when receiving it.
597  // Terminal.app also doesn't support DECRQSS.
598  if (!TI_HAS(kTerm_set_underline_style) && !(screen || tmux || nsterm)) {
599    // Query the terminal to see if it supports extended underline.
600    tui_query_extended_underline(tui);
601  }
602
603  // Query the terminal to see if it supports Kitty's keyboard protocol
604  tui_query_kitty_keyboard(tui);
605
606  // Query the terminal's background color. We normally get it via continuous reporting (set via
607  // `kTermModeThemeUpdates` above), but if we were backgrounded while the light/dark mode changed,
608  // we won't have received the report, so we also query it on resume.
609  tui_query_bg_color_noflush(tui);
610
611  int ret;
612  uv_loop_init(&tui->write_loop);
613  if (tui->out_isatty) {
614    ret = uv_tty_init(&tui->write_loop, &tui->output_handle.tty, tui->out_fd, 0);
615    if (ret) {
616      ELOG("uv_tty_init failed: %s", uv_strerror(ret));
617    }
618#ifndef MSWIN
619    int retry_count = 10;
620    // A signal may cause uv_tty_set_mode() to fail (e.g., SIGCONT). Retry a
621    // few times. #12322
622    while ((ret = uv_tty_set_mode(&tui->output_handle.tty, UV_TTY_MODE_IO)) == UV_EINTR
623           && retry_count > 0) {
624      retry_count--;
625    }
626    if (ret) {
627      ELOG("uv_tty_set_mode failed: %s", uv_strerror(ret));
628    }
629#endif
630  } else {
631    ret = uv_pipe_init(&tui->write_loop, &tui->output_handle.pipe, 0);
632    if (ret) {
633      ELOG("uv_pipe_init failed: %s", uv_strerror(ret));
634    }
635    ret = uv_pipe_open(&tui->output_handle.pipe, tui->out_fd);
636    if (ret) {
637      ELOG("uv_pipe_open failed: %s", uv_strerror(ret));
638    }
639  }
640  flush_buf(tui, kFlushBufFinal);
641
642  xfree(term);
643  xfree(colorterm);
644  xfree(termprg);
645  xfree(vte_version_env);
646  xfree(konsolev_env);
647  xfree(term_program_version_env);
648#undef TI_HAS
649}
650
651/// Disable various terminal modes and other features.
652static void terminfo_disable(TUIData *tui)
653{
654  // Disable theme update notifications. We do this first to avoid getting any
655  // more notifications after we reset the cursor and any color palette changes.
656  if (tui->modes.theme_updates) {
657    tui_set_term_mode(tui, kTermModeThemeUpdates, false);
658  }
659
660  // Destroy output stuff
661  tui_mode_change(tui, NULL_STRING, SHAPE_IDX_N);
662  tui_mouse_off(tui);
663  terminfo_out(tui, kTerm_exit_attribute_mode);
664  // Reset cursor to normal before exiting alternate screen.
665  terminfo_out(tui, kTerm_cursor_normal);
666  terminfo_out(tui, kTerm_reset_cursor_style);
667  terminfo_out(tui, kTerm_keypad_local);
668
669  // Reset the key encoding
670  tui_reset_key_encoding(tui);
671
672  // Disable terminal modes that we enabled
673  if (tui->modes.resize_events) {
674    tui_set_term_mode(tui, kTermModeResizeEvents, false);
675  }
676
677  if (tui->modes.grapheme_clusters) {
678    tui_set_term_mode(tui, kTermModeGraphemeClusters, false);
679  }
680
681  // May restore old title before exiting alternate screen.
682  tui_set_title(tui, NULL_STRING);
683  if (tui->cursor_has_color) {
684    terminfo_out(tui, kTerm_reset_cursor_color);
685  }
686  // Disable bracketed paste
687  tui_set_term_mode(tui, kTermModeBracketedPaste, false);
688  // Disable focus reporting
689  out_len(tui, tui->terminfo_ext.disable_focus_reporting);
690
691  // Send a DA1 request. When the terminal responds we know that it has
692  // processed all of our requests and won't be emitting anymore sequences.
693  out(tui, S_LEN("\x1b[c"));
694
695  // Immediately flush the buffer and wait for the DA1 response.
696  flush_buf(tui, kFlushBufFinal);
697}
698
699/// Disable the alternate screen and prepare for the TUI to close.
700static void terminfo_stop(TUIData *tui)
701{
702  if (ui_client_exit_status == 0 && ui_client_error_exit > 0) {
703    ui_client_exit_status = ui_client_error_exit;
704  }
705
706  // If Nvim exited with nonzero status, without indicating this was an
707  // intentional exit (like `:1cquit`), it likely was an internal failure.
708  // Don't clobber the stderr error message in this case. #21608
709  if (ui_client_exit_status == MAX(ui_client_error_exit, 0)) {
710    // Position the cursor on the last screen line, below all the text
711    cursor_goto(tui, tui->height - 1, 0);
712    // Exit alternate screen.
713    terminfo_out(tui, kTerm_exit_ca_mode);
714  }
715
716  flush_buf(tui, kFlushBufFinal);
717  uv_tty_reset_mode();
718  uv_close((uv_handle_t *)&tui->output_handle, NULL);
719  uv_run(&tui->write_loop, UV_RUN_DEFAULT);
720  if (uv_loop_close(&tui->write_loop)) {
721    abort();
722  }
723  arena_mem_free(arena_finish(&tui->ti_arena));
724  // Avoid using freed memory.
725  memset(&tui->ti, 0, sizeof(tui->ti));
726  tui->term = NULL;
727}
728
729static void tui_terminal_start(TUIData *tui)
730{
731  tui->print_attr_id = -1;
732  terminfo_start(tui);
733  if (tui->input.loop == NULL) {
734    tinput_init(&tui->input, &main_loop, &tui->ti);
735  }
736  tui_guess_size(tui);
737  tinput_start(&tui->input);
738}
739
740static void after_startup_cb(uv_timer_t *handle)
741{
742  TUIData *tui = handle->data;
743  tui_terminal_after_startup(tui);
744}
745
746static void tui_terminal_after_startup(TUIData *tui)
747  FUNC_ATTR_NONNULL_ALL
748{
749  // Emit this after Nvim startup, not during.  This works around a tmux
750  // 2.3 bug(?) which caused slow drawing during startup.  #7649
751  out_len(tui, tui->terminfo_ext.enable_focus_reporting);
752  flush_buf(tui, kFlushBufFinal);
753}
754
755void tui_stop(TUIData *tui)
756  FUNC_ATTR_NONNULL_ALL
757{
758  if (uv_is_closing((uv_handle_t *)&tui->output_handle)) {
759    // Race between SIGCONT (tui.c) and SIGHUP (os/signal.c)? #8075
760    ELOG("TUI already stopped (race?)");
761    tui->stopped = true;
762    return;
763  }
764
765  tui->input.callbacks.primary_device_attr = tui_stop_cb;
766  terminfo_disable(tui);
767
768  // Wait until DA1 response is received, or stdin is closed (#35744).
769  uint64_t wait_start = os_hrtime();
770  LOOP_PROCESS_EVENTS_UNTIL(tui->loop, tui->loop->events, EXIT_TIMEOUT_MS,
771                            tui->stopped || tui->input.read_stream.did_eof);
772  if (!tui->stopped && (os_hrtime() - wait_start) / 1000000 >= EXIT_TIMEOUT_MS) {
773    WLOG("TUI: timed out waiting for DA1 response");
774  }
775  tui->stopped = true;
776
777  tui_terminal_stop(tui);
778  stream_set_blocking(tui->input.in_fd, true);   // normalize stream (#2598)
779  tinput_destroy(&tui->input);
780  signal_watcher_stop(&tui->winch_handle);
781  signal_watcher_close(&tui->winch_handle, NULL);
782  uv_close((uv_handle_t *)&tui->startup_delay_timer, NULL);
783}
784
785/// Callback function called when the response to the Device Attributes (DA1)
786/// request is sent during shutdown.
787static void tui_stop_cb(TUIData *tui)
788  FUNC_ATTR_NONNULL_ALL
789{
790  tui->stopped = true;
791}
792
793/// Stop the terminal but allow it to restart later (like after suspend)
794///
795/// This is called after we receive the response to the DA1 request sent from
796/// terminfo_disable.
797static void tui_terminal_stop(TUIData *tui)
798  FUNC_ATTR_NONNULL_ALL
799{
800  tinput_stop(&tui->input);
801  terminfo_stop(tui);
802}
803
804/// Returns true if UI `ui` is stopped.
805bool tui_is_stopped(TUIData *tui)
806{
807  return tui->stopped;
808}
809
810#ifdef EXITFREE
811void tui_free_all_mem(TUIData *tui)
812{
813  ugrid_free(&tui->grid);
814  kv_destroy(tui->invalid_regions);
815
816  const char *url;
817  set_foreach(&urls, url, {
818    xfree((void *)url);
819  });
820  set_destroy(cstr_t, &urls);
821
822  kv_destroy(tui->attrs);
823  kv_destroy(tui->urlbuf);
824  xfree(tui);
825}
826#endif
827
828static void sigwinch_cb(SignalWatcher *watcher, int signum, void *cbdata)
829{
830  TUIData *tui = cbdata;
831  if (tui_is_stopped(tui) || tui->resize_events_enabled) {
832    return;
833  }
834
835  tui_guess_size(tui);
836}
837
838static bool attrs_differ(TUIData *tui, int id1, int id2, bool rgb)
839{
840  if (id1 == id2) {
841    return false;
842  } else if (id1 < 0 || id2 < 0) {
843    return true;
844  }
845  HlAttrs a1 = kv_A(tui->attrs, (size_t)id1);
846  HlAttrs a2 = kv_A(tui->attrs, (size_t)id2);
847
848  if (a1.url != a2.url) {
849    return true;
850  }
851
852  if (rgb) {
853    return a1.rgb_fg_color != a2.rgb_fg_color
854           || a1.rgb_bg_color != a2.rgb_bg_color
855           || a1.rgb_ae_attr != a2.rgb_ae_attr
856           || a1.rgb_sp_color != a2.rgb_sp_color;
857  } else {
858    return a1.cterm_fg_color != a2.cterm_fg_color
859           || a1.cterm_bg_color != a2.cterm_bg_color
860           || a1.cterm_ae_attr != a2.cterm_ae_attr
861           || (a1.cterm_ae_attr & HL_UNDERLINE_MASK
862               && a1.rgb_sp_color != a2.rgb_sp_color);
863  }
864}
865
866static void update_attrs(TUIData *tui, int attr_id)
867{
868  if (!attrs_differ(tui, attr_id, tui->print_attr_id, tui->rgb)) {
869    tui->print_attr_id = attr_id;
870    return;
871  }
872  tui->print_attr_id = attr_id;
873  HlAttrs attrs = kv_A(tui->attrs, (size_t)attr_id);
874  int attr = tui->rgb ? attrs.rgb_ae_attr : attrs.cterm_ae_attr;
875
876  bool bold = attr & HL_BOLD;
877  bool italic = attr & HL_ITALIC;
878  bool reverse = attr & HL_INVERSE;
879  bool standout = attr & HL_STANDOUT;
880  bool strikethrough = attr & HL_STRIKETHROUGH;
881  bool altfont = attr & HL_ALTFONT;
882  bool dim = attr & HL_DIM;
883  bool blink = attr & HL_BLINK;
884  bool conceal = attr & HL_CONCEALED;
885  bool overline = attr & HL_OVERLINE;
886
887  bool underline;
888  bool undercurl;
889  bool underdouble;
890  bool underdotted;
891  bool underdashed;
892  if (tui->ti.defs[kTerm_set_underline_style]) {
893    int ul = attr & HL_UNDERLINE_MASK;
894    underline = ul == HL_UNDERLINE;
895    undercurl = ul == HL_UNDERCURL;
896    underdouble = ul == HL_UNDERDOUBLE;
897    underdashed = ul == HL_UNDERDASHED;
898    underdotted = ul == HL_UNDERDOTTED;
899  } else {
900    underline = attr & HL_UNDERLINE_MASK;
901    undercurl = false;
902    underdouble = false;
903    underdotted = false;
904    underdashed = false;
905  }
906
907  bool has_any_underline = undercurl || underline
908                           || underdouble || underdotted || underdashed;
909
910  if (tui->ti.defs[kTerm_set_attributes] != NULL) {
911    if (bold || dim || blink || reverse || underline || standout) {
912      TPVAR params[9] = { 0 };
913      params[0].num = standout;
914      params[1].num = underline;
915      params[2].num = reverse;
916      params[3].num = blink;
917      params[4].num = dim;
918      params[5].num = bold;
919      params[6].num = 0;   // blank
920      params[7].num = 0;   // protect
921      params[8].num = 0;   // alternate character set
922      terminfo_print(tui, kTerm_set_attributes, params);
923    } else if (!tui->default_attr) {
924      terminfo_out(tui, kTerm_exit_attribute_mode);
925    }
926  } else {
927    if (!tui->default_attr) {
928      terminfo_out(tui, kTerm_exit_attribute_mode);
929    }
930    if (bold) {
931      terminfo_out(tui, kTerm_enter_bold_mode);
932    }
933    if (underline) {
934      terminfo_out(tui, kTerm_enter_underline_mode);
935    }
936    if (standout) {
937      terminfo_out(tui, kTerm_enter_standout_mode);
938    }
939    if (reverse) {
940      terminfo_out(tui, kTerm_enter_reverse_mode);
941    }
942    if (dim) {
943      terminfo_out(tui, kTerm_enter_dim_mode);
944    }
945    if (blink) {
946      terminfo_out(tui, kTerm_enter_blink_mode);
947    }
948  }
949  if (italic) {
950    terminfo_out(tui, kTerm_enter_italics_mode);
951  }
952  if (altfont) {
953    out_len(tui, tui->terminfo_ext.enter_altfont_mode);
954  }
955  if (strikethrough) {
956    terminfo_out(tui, kTerm_enter_strikethrough_mode);
957  }
958  if (conceal) {
959    terminfo_out(tui, kTerm_enter_secure_mode);
960  }
961  if (overline) {
962    out(tui, S_LEN("\x1b[53m"));
963  }
964  if (tui->ti.defs[kTerm_set_underline_style]) {
965    if (undercurl) {
966      terminfo_print_num1(tui, kTerm_set_underline_style, 3);
967    }
968    if (underdouble) {
969      terminfo_print_num1(tui, kTerm_set_underline_style, 2);
970    }
971    if (underdotted) {
972      terminfo_print_num1(tui, kTerm_set_underline_style, 4);
973    }
974    if (underdashed) {
975      terminfo_print_num1(tui, kTerm_set_underline_style, 5);
976    }
977  }
978
979  if (has_any_underline && tui->can_set_underline_color) {
980    int color = attrs.rgb_sp_color;
981    if (color != -1) {
982      // Only support colon syntax. #9270
983      out_printf(tui, 128, "\x1b[58:2::%d:%d:%dm",
984                 (color >> 16) & 0xff,  // red
985                 (color >> 8) & 0xff,   // green
986                 color & 0xff);         // blue
987    }
988  }
989
990  int fg, bg;
991  if (tui->rgb && !(attr & HL_FG_INDEXED)) {
992    fg = ((attrs.rgb_fg_color != -1)
993          ? attrs.rgb_fg_color : tui->clear_attrs.rgb_fg_color);
994    if (fg != -1) {
995      terminfo_print_num3(tui, kTerm_set_rgb_foreground,
996                          (fg >> 16) & 0xff,  // red
997                          (fg >> 8) & 0xff,   // green
998                          fg & 0xff);         // blue
999    }
1000  } else {
1001    fg = (attrs.cterm_fg_color
1002          ? attrs.cterm_fg_color - 1 : (tui->clear_attrs.cterm_fg_color - 1));
1003    if (fg != -1) {
1004      terminfo_print_num1(tui, kTerm_set_a_foreground, fg);
1005    }
1006  }
1007
1008  if (tui->rgb && !(attr & HL_BG_INDEXED)) {
1009    bg = ((attrs.rgb_bg_color != -1)
1010          ? attrs.rgb_bg_color : tui->clear_attrs.rgb_bg_color);
1011    if (bg != -1) {
1012      terminfo_print_num3(tui, kTerm_set_rgb_background,
1013                          (bg >> 16) & 0xff,  // red
1014                          (bg >> 8) & 0xff,   // green
1015                          bg & 0xff);         // blue
1016    }
1017  } else {
1018    bg = (attrs.cterm_bg_color
1019          ? attrs.cterm_bg_color - 1 : (tui->clear_attrs.cterm_bg_color - 1));
1020    if (bg != -1) {
1021      terminfo_print_num1(tui, kTerm_set_a_background, bg);
1022    }
1023  }
1024
1025  if (tui->url != attrs.url) {
1026    if (attrs.url >= 0) {
1027      const char *url = urls.keys[attrs.url];
1028      kv_size(tui->urlbuf) = 0;
1029
1030      // Add some fixed offset to the URL ID to deconflict with other
1031      // applications which may set their own IDs
1032      const uint64_t id = 0xE1EA0000U + (uint32_t)attrs.url;
1033
1034      kv_printf(tui->urlbuf, "\x1b]8;id=%" PRIu64 ";%s\x1b\\", id, url);
1035      out(tui, tui->urlbuf.items, kv_size(tui->urlbuf));
1036    } else {
1037      out(tui, S_LEN("\x1b]8;;\x1b\\"));
1038    }
1039
1040    tui->url = attrs.url;
1041  }
1042
1043  tui->default_attr = fg == -1 && bg == -1
1044                      && !bold && !dim && !blink && !conceal && !overline && !italic
1045                      && !has_any_underline && !reverse && !standout && !strikethrough;
1046
1047  // Non-BCE terminals can't clear with non-default background color. Some BCE
1048  // terminals don't support attributes either, so don't rely on it. But assume
1049  // italic and bold has no effect if there is no text.
1050  tui->can_clear_attr = !reverse && !standout && !dim && !blink && !conceal && !overline
1051                        && !has_any_underline && !strikethrough && (tui->bce || bg == -1);
1052}
1053
1054static void final_column_wrap(TUIData *tui)
1055{
1056  UGrid *grid = &tui->grid;
1057  if (grid->row != -1 && grid->col == tui->width) {
1058    grid->col = 0;
1059    if (grid->row < MIN(tui->height, grid->height - 1)) {
1060      grid->row++;
1061    }
1062  }
1063}
1064
1065/// It is undocumented, but in the majority of terminals and terminal emulators
1066/// printing at the right margin does not cause an automatic wrap until the
1067/// next character is printed, holding the cursor in place until then.
1068static void print_cell(TUIData *tui, char *buf, sattr_T attr)
1069{
1070  UGrid *grid = &tui->grid;
1071  if (!tui->immediate_wrap_after_last_column) {
1072    // Printing the next character finally advances the cursor.
1073    final_column_wrap(tui);
1074  }
1075  update_attrs(tui, attr);
1076  out(tui, buf, strlen(buf));
1077  grid->col++;
1078  if (tui->immediate_wrap_after_last_column) {
1079    // Printing at the right margin immediately advances the cursor.
1080    final_column_wrap(tui);
1081  }
1082}
1083
1084static bool cheap_to_print(TUIData *tui, int row, int col, int next)
1085{
1086  UGrid *grid = &tui->grid;
1087  UCell *cell = grid->cells[row] + col;
1088  while (next) {
1089    next--;
1090    if (attrs_differ(tui, cell->attr,
1091                     tui->print_attr_id, tui->rgb)) {
1092      if (tui->default_attr) {
1093        return false;
1094      }
1095    }
1096    if (schar_get_ascii(cell->data) == 0) {
1097      return false;  // not ascii
1098    }
1099    cell++;
1100  }
1101  return true;
1102}
1103
1104/// This optimizes several cases where it is cheaper to do something other
1105/// than send a full cursor positioning control sequence.  However, there are
1106/// some further optimizations that may seem obvious but that will not work.
1107///
1108/// We cannot use VT (ASCII 0/11) for moving the cursor up, because VT means
1109/// move the cursor down on a DEC terminal.  Similarly, on a DEC terminal FF
1110/// (ASCII 0/12) means the same thing and does not mean home.  VT, CVT, and
1111/// TAB also stop at software-defined tabulation stops, not at a fixed set
1112/// of row/column positions.
1113static void cursor_goto(TUIData *tui, int row, int col)
1114{
1115  UGrid *grid = &tui->grid;
1116  if (row == grid->row && col == grid->col) {
1117    return;
1118  }
1119
1120  // If an OSC 8 sequence is active terminate it before moving the cursor
1121  if (tui->url >= 0) {
1122    out(tui, S_LEN("\x1b]8;;\x1b\\"));
1123    tui->url = -1;
1124    tui->print_attr_id = -1;
1125  }
1126
1127  if (0 == row && 0 == col) {
1128    terminfo_out(tui, kTerm_cursor_home);
1129    ugrid_goto(grid, row, col);
1130    return;
1131  }
1132  if (grid->row == -1) {
1133    goto safe_move;
1134  }
1135  if (0 == col
1136      ? col != grid->col
1137      : (row != grid->row
1138         ? false
1139         : (1 == col
1140            ? (2 < grid->col && cheap_to_print(tui, grid->row, 0, col))
1141            : (2 == col
1142               ? (5 < grid->col && cheap_to_print(tui, grid->row, 0, col))
1143               : false)))) {
1144    // Motion to left margin from anywhere else, or CR + printing chars is
1145    // even less expensive than using BSes or CUB.
1146    terminfo_out(tui, kTerm_carriage_return);
1147    ugrid_goto(grid, grid->row, 0);
1148  }
1149  if (row == grid->row) {
1150    if (col < grid->col
1151        // Deferred right margin wrap terminals have inconsistent ideas about
1152        // where the cursor actually is during a deferred wrap.  Relative
1153        // motion calculations have OBOEs that cannot be compensated for,
1154        // because two terminals that claim to be the same will implement
1155        // different cursor positioning rules.
1156        && (tui->immediate_wrap_after_last_column || grid->col < tui->width)) {
1157      int n = grid->col - col;
1158      if (n <= 4) {  // This might be just BS, so it is considered really cheap.
1159        while (n--) {
1160          terminfo_out(tui, kTerm_cursor_left);
1161        }
1162      } else {
1163        terminfo_print_num1(tui, kTerm_parm_left_cursor, n);
1164      }
1165      ugrid_goto(grid, row, col);
1166      return;
1167    } else if (col > grid->col) {
1168      int n = col - grid->col;
1169      if (n <= 2) {
1170        while (n--) {
1171          terminfo_out(tui, kTerm_cursor_right);
1172        }
1173      } else {
1174        terminfo_print_num1(tui, kTerm_parm_right_cursor, n);
1175      }
1176      ugrid_goto(grid, row, col);
1177      return;
1178    }
1179  }
1180  if (col == grid->col) {
1181    if (row > grid->row) {
1182      int n = row - grid->row;
1183      if (n <= 4) {  // This might be just LF, so it is considered really cheap.
1184        while (n--) {
1185          terminfo_out(tui, kTerm_cursor_down);
1186        }
1187      } else {
1188        terminfo_print_num1(tui, kTerm_parm_down_cursor, n);
1189      }
1190      ugrid_goto(grid, row, col);
1191      return;
1192    } else if (row < grid->row) {
1193      int n = grid->row - row;
1194      if (n <= 2) {
1195        while (n--) {
1196          terminfo_out(tui, kTerm_cursor_up);
1197        }
1198      } else {
1199        terminfo_print_num1(tui, kTerm_parm_up_cursor, n);
1200      }
1201      ugrid_goto(grid, row, col);
1202      return;
1203    }
1204  }
1205
1206safe_move:
1207  terminfo_print_num2(tui, kTerm_cursor_address, row, col);
1208  ugrid_goto(grid, row, col);
1209}
1210
1211static void print_spaces(TUIData *tui, int width)
1212{
1213  UGrid *grid = &tui->grid;
1214  size_t left = (size_t)width;
1215
1216  // spaces are not a sequence, we can squeeze whatever's left of the buffer
1217  while (true) {
1218    size_t buf_fit = MIN(left, sizeof tui->buf - tui->bufpos);
1219    memset(tui->buf + tui->bufpos, ' ', buf_fit);
1220    tui->bufpos += buf_fit;
1221    left -= buf_fit;
1222
1223    if (left == 0) {
1224      break;  // likely: didn't need to flush for sm0l spaces
1225    }
1226    flush_buf(tui, kFlushBufPartial);
1227  }
1228
1229  grid->col += width;
1230  if (tui->immediate_wrap_after_last_column) {
1231    // Printing at the right margin immediately advances the cursor.
1232    final_column_wrap(tui);
1233  }
1234}
1235
1236/// Move cursor to the position given by `row` and `col` and print the char in `cell`.
1237/// Allows grid and host terminal to assume different widths of ambiguous-width chars.
1238///
1239/// @param is_doublewidth  whether the char is double-width on the grid.
1240///                        If true and the char is ambiguous-width, clear two cells.
1241static void print_cell_at_pos(TUIData *tui, int row, int col, UCell *cell, bool is_doublewidth)
1242{
1243  UGrid *grid = &tui->grid;
1244
1245  if (grid->row == -1 && cell->data == NUL) {
1246    // If cursor needs repositioning and there is nothing to print, don't move cursor.
1247    return;
1248  }
1249
1250  cursor_goto(tui, row, col);
1251
1252  char buf[MAX_SCHAR_SIZE];
1253  schar_get(buf, cell->data);
1254  int c = utf_ptr2char(buf);
1255  bool is_ambiwidth = utf_ambiguous_width(buf);
1256  if (is_doublewidth && (is_ambiwidth || utf_char2cells(c) == 1)) {
1257    // If the server used setcellwidths() to treat a single-width char as double-width,
1258    // it needs to be treated like an ambiguous-width char.
1259    is_ambiwidth = true;
1260    // Clear the two screen cells.
1261    // If the char is single-width in host terminal it won't change the second cell.
1262    update_attrs(tui, cell->attr);
1263    print_spaces(tui, 2);
1264    cursor_goto(tui, row, col);
1265  }
1266
1267  print_cell(tui, buf, cell->attr);
1268
1269  if (is_ambiwidth) {
1270    // Force repositioning cursor after printing an ambiguous-width char.
1271    grid->row = -1;
1272  }
1273}
1274
1275static void clear_region(TUIData *tui, int top, int bot, int left, int right, int attr_id)
1276{
1277  UGrid *grid = &tui->grid;
1278
1279  // Setting the default colors is delayed until after startup to avoid flickering
1280  // with the default colorscheme background. Consequently, any flush that happens
1281  // during startup would result in clearing invalidated regions with zeroed
1282  // clear_attrs, perceived as a black flicker. Reset attributes to clear with
1283  // current terminal background instead (#28667, #28668).
1284  if (tui->set_default_colors) {
1285    update_attrs(tui, attr_id);
1286  } else {
1287    terminfo_out(tui, kTerm_exit_attribute_mode);
1288  }
1289
1290  // Background is set to the default color and the right edge matches the
1291  // screen end, try to use terminal codes for clearing the requested area.
1292  if (tui->can_clear_attr
1293      && left == 0 && right == tui->width && bot == tui->height) {
1294    if (top == 0) {
1295      terminfo_out(tui, kTerm_clear_screen);
1296      ugrid_goto(grid, top, left);
1297    } else {
1298      cursor_goto(tui, top, 0);
1299      terminfo_out(tui, kTerm_clr_eos);
1300    }
1301  } else {
1302    int width = right - left;
1303
1304    // iterate through each line and clear
1305    for (int row = top; row < bot; row++) {
1306      cursor_goto(tui, row, left);
1307      if (tui->can_clear_attr && right == tui->width) {
1308        terminfo_out(tui, kTerm_clr_eol);
1309      } else if (tui->can_erase_chars && tui->can_clear_attr) {
1310        terminfo_print_num1(tui, kTerm_erase_chars, width);
1311      } else {
1312        print_spaces(tui, width);
1313      }
1314    }
1315  }
1316}
1317
1318static void set_scroll_region(TUIData *tui, int top, int bot, int left, int right)
1319{
1320  UGrid *grid = &tui->grid;
1321
1322  terminfo_print_num2(tui, kTerm_change_scroll_region, top, bot);
1323  if (left != 0 || right != tui->width - 1) {
1324    tui_set_term_mode(tui, kTermModeLeftAndRightMargins, true);
1325    terminfo_print_num2(tui, kTerm_set_lr_margin, left, right);
1326  }
1327  grid->row = -1;
1328}
1329
1330static void reset_scroll_region(TUIData *tui, bool fullwidth)
1331{
1332  UGrid *grid = &tui->grid;
1333
1334  if (tui->terminfo_ext.reset_scroll_region) {
1335    out_len(tui, tui->terminfo_ext.reset_scroll_region);
1336  } else {
1337    terminfo_print_num2(tui, kTerm_change_scroll_region, 0, tui->height - 1);
1338  }
1339  if (!fullwidth) {
1340    terminfo_print_num2(tui, kTerm_set_lr_margin, 0, tui->width - 1);
1341    tui_set_term_mode(tui, kTermModeLeftAndRightMargins, false);
1342  }
1343  grid->row = -1;
1344}
1345
1346void tui_grid_resize(TUIData *tui, Integer g, Integer width, Integer height)
1347{
1348  UGrid *grid = &tui->grid;
1349  ugrid_resize(grid, (int)width, (int)height);
1350
1351  // resize might not always be followed by a clear before flush
1352  // so clip the invalid region
1353  for (size_t i = 0; i < kv_size(tui->invalid_regions); i++) {
1354    Rect *r = &kv_A(tui->invalid_regions, i);
1355    r->bot = MIN(r->bot, grid->height);
1356    r->right = MIN(r->right, grid->width);
1357  }
1358
1359  if (tui->pending_resize_events == 0 && !tui->is_starting) {
1360    // Resize the _host_ terminal.
1361    out_printf(tui, 64, "\x1b[8;%d;%dt", (int)height, (int)width);
1362  } else {  // Already handled the resize; avoid double-resize.
1363    tui->pending_resize_events = tui->pending_resize_events >
1364                                 0 ? tui->pending_resize_events - 1 : 0;
1365    grid->row = -1;
1366  }
1367}
1368
1369void tui_grid_clear(TUIData *tui, Integer g)
1370{
1371  UGrid *grid = &tui->grid;
1372  ugrid_clear(grid);
1373  // safe to clear cache at this point
1374  schar_cache_clear_if_full();
1375  kv_size(tui->invalid_regions) = 0;
1376  clear_region(tui, 0, tui->height, 0, tui->width, 0);
1377}
1378
1379void tui_grid_cursor_goto(TUIData *tui, Integer grid, Integer row, Integer col)
1380{
1381  // cursor position is validated in tui_flush
1382  tui->row = (int)row;
1383  tui->col = (int)col;
1384}
1385
1386static CursorShape tui_cursor_decode_shape(const char *shape_str)
1387{
1388  CursorShape shape;
1389  if (strequal(shape_str, "block")) {
1390    shape = SHAPE_BLOCK;
1391  } else if (strequal(shape_str, "vertical")) {
1392    shape = SHAPE_VER;
1393  } else if (strequal(shape_str, "horizontal")) {
1394    shape = SHAPE_HOR;
1395  } else {
1396    WLOG("Unknown shape value '%s'", shape_str);
1397    shape = SHAPE_BLOCK;
1398  }
1399  return shape;
1400}
1401
1402/// Reset terminal cursor style. This may be different across terminals and
1403/// terminal configs. Also, it depends on what escape sequence Unibilium or
1404/// terminfo_builtin.h have set for kTerm_reset_cursor_style (which can also
1405/// depend on other runtime logic). It doesn't necessarily send out a
1406/// `\x1b[0 q` (terminal default) sequence.
1407/// See https://ghostty.org/docs/vt/csi/decscusr for more details.
1408static void tui_cursor_reset_style(TUIData *tui)
1409{
1410  terminfo_out(tui, kTerm_reset_cursor_style);
1411}
1412
1413static cursorentry_T decode_cursor_entry(Dict args)
1414{
1415  cursorentry_T r = shape_table[0];
1416
1417  for (size_t i = 0; i < args.size; i++) {
1418    char *key = args.items[i].key.data;
1419    Object value = args.items[i].value;
1420
1421    if (strequal(key, "cursor_shape")) {
1422      r.shape = tui_cursor_decode_shape(args.items[i].value.data.string.data);
1423    } else if (strequal(key, "blinkon")) {
1424      r.blinkon = (int)value.data.integer;
1425    } else if (strequal(key, "blinkoff")) {
1426      r.blinkoff = (int)value.data.integer;
1427    } else if (strequal(key, "attr_id")) {
1428      r.id = (int)value.data.integer;
1429    }
1430  }
1431  return r;
1432}
1433
1434void tui_mode_info_set(TUIData *tui, bool guicursor_enabled, Array args)
1435{
1436  cursor_style_enabled = guicursor_enabled;
1437  if (!guicursor_enabled) {
1438    tui_cursor_reset_style(tui);
1439    return;
1440  }
1441
1442  assert(args.size);
1443
1444  // cursor style entries as defined by `shape_table`.
1445  for (size_t i = 0; i < args.size; i++) {
1446    assert(args.items[i].type == kObjectTypeDict);
1447    cursorentry_T r = decode_cursor_entry(args.items[i].data.dict);
1448    tui->cursor_shapes[i] = r;
1449  }
1450
1451  tui_set_mode(tui, tui->showing_mode);
1452}
1453
1454void tui_update_menu(TUIData *tui)
1455{
1456  // Do nothing; menus are for GUI only
1457}
1458
1459void tui_busy_start(TUIData *tui)
1460{
1461  tui->busy = true;
1462}
1463
1464void tui_busy_stop(TUIData *tui)
1465{
1466  tui->busy = false;
1467}
1468
1469void tui_mouse_on(TUIData *tui)
1470{
1471  if (!tui->mouse_enabled) {
1472    tui_set_term_mode(tui, kTermModeMouseButtonEvent, true);
1473    tui_set_term_mode(tui, kTermModeMouseSGRExt, true);
1474    if (tui->mouse_move_enabled) {
1475      tui_set_term_mode(tui, kTermModeMouseAnyEvent, true);
1476    }
1477    tui->mouse_enabled = true;
1478  }
1479}
1480
1481void tui_mouse_off(TUIData *tui)
1482{
1483  if (tui->mouse_enabled) {
1484    if (tui->mouse_move_enabled) {
1485      tui_set_term_mode(tui, kTermModeMouseAnyEvent, false);
1486    }
1487    tui_set_term_mode(tui, kTermModeMouseButtonEvent, false);
1488    tui_set_term_mode(tui, kTermModeMouseSGRExt, false);
1489    tui->mouse_enabled = false;
1490  }
1491}
1492
1493static void tui_set_mode(TUIData *tui, ModeShape mode)
1494{
1495  if (!cursor_style_enabled) {
1496    tui_cursor_reset_style(tui);
1497    return;
1498  }
1499  cursorentry_T c = tui->cursor_shapes[mode];
1500
1501  if (c.id != 0 && c.id < (int)kv_size(tui->attrs) && tui->rgb) {
1502    HlAttrs aep = kv_A(tui->attrs, c.id);
1503
1504    tui->want_invisible = aep.hl_blend == 100;
1505    if (!tui->want_invisible && aep.rgb_ae_attr & HL_INVERSE) {
1506      // We interpret "inverse" as "default" (no termcode for "inverse"...).
1507      // Hopefully the user's default cursor color is inverse.
1508      terminfo_out(tui, kTerm_reset_cursor_color);
1509    } else if (!tui->want_invisible && aep.rgb_bg_color >= 0) {
1510      TPVAR params[9] = { 0 };
1511      char hexbuf[8];
1512      if (tui->set_cursor_color_as_str) {
1513        snprintf(hexbuf, 7 + 1, "#%06x", aep.rgb_bg_color);
1514        params[0].string = hexbuf;
1515      } else {
1516        params[0].num = aep.rgb_bg_color;
1517      }
1518      terminfo_print(tui, kTerm_set_cursor_color, params);
1519      tui->cursor_has_color = true;
1520    }
1521  } else if (c.id == 0 && (tui->want_invisible || tui->cursor_has_color)) {
1522    // No cursor color for this mode; reset to default.
1523    tui->want_invisible = false;
1524    tui->cursor_has_color = false;
1525    terminfo_out(tui, kTerm_reset_cursor_color);
1526  }
1527
1528  int shape;
1529  switch (c.shape) {
1530  case SHAPE_BLOCK:
1531    shape = 1; break;
1532  case SHAPE_HOR:
1533    shape = 3; break;
1534  case SHAPE_VER:
1535    shape = 5; break;
1536  }
1537  terminfo_print_num1(tui, kTerm_set_cursor_style,
1538                      shape + (int)(c.blinkon == 0 || c.blinkoff == 0));
1539}
1540
1541/// @param mode editor mode
1542void tui_mode_change(TUIData *tui, String mode, Integer mode_idx)
1543{
1544#ifdef UNIX
1545  // If stdin is not a TTY, the LHS of pipe may change the state of the TTY
1546  // after calling uv_tty_set_mode. So, set the mode of the TTY again here.
1547  // #13073
1548  if (tui->out_isatty && tui->is_starting && !stdin_isatty) {
1549    int ret = uv_tty_set_mode(&tui->output_handle.tty, UV_TTY_MODE_NORMAL);
1550    if (ret) {
1551      ELOG("uv_tty_set_mode failed: %s", uv_strerror(ret));
1552    }
1553    ret = uv_tty_set_mode(&tui->output_handle.tty, UV_TTY_MODE_IO);
1554    if (ret) {
1555      ELOG("uv_tty_set_mode failed: %s", uv_strerror(ret));
1556    }
1557  }
1558#endif
1559  tui_set_mode(tui, (ModeShape)mode_idx);
1560  if (tui->is_starting) {
1561    if (tui->verbose >= 3) {
1562      show_verbose_terminfo(tui);
1563    }
1564  }
1565  tui->is_starting = false;  // mode entered, no longer starting
1566  tui->showing_mode = (ModeShape)mode_idx;
1567}
1568
1569void tui_grid_scroll(TUIData *tui, Integer g, Integer startrow, Integer endrow, Integer startcol,
1570                     Integer endcol, Integer rows, Integer cols FUNC_ATTR_UNUSED)
1571{
1572  UGrid *grid = &tui->grid;
1573  int top = (int)startrow;
1574  int bot = (int)endrow - 1;
1575  int left = (int)startcol;
1576  int right = (int)endcol - 1;
1577
1578  bool fullwidth = left == 0 && right == tui->width - 1;
1579  bool full_screen_scroll = fullwidth && top == 0 && bot == tui->height - 1;
1580
1581  ugrid_scroll(grid, top, bot, left, right, (int)rows);
1582
1583  bool has_lr_margins = tui->has_left_and_right_margin_mode && tui->can_set_lr_margin;
1584
1585  bool can_scroll = tui->can_scroll
1586                    && (full_screen_scroll
1587                        || (tui->can_change_scroll_region
1588                            && ((left == 0 && right == tui->width - 1) || has_lr_margins)));
1589
1590  if (can_scroll) {
1591    // Change terminal scroll region and move cursor to the top
1592    if (!full_screen_scroll) {
1593      set_scroll_region(tui, top, bot, left, right);
1594    }
1595    cursor_goto(tui, top, left);
1596    update_attrs(tui, 0);
1597
1598    if (rows > 0) {
1599      if (rows == 1) {
1600        terminfo_out(tui, kTerm_delete_line);
1601      } else {
1602        terminfo_print_num1(tui, kTerm_parm_delete_line, (int)rows);
1603      }
1604    } else {
1605      if (rows == -1) {
1606        terminfo_out(tui, kTerm_insert_line);
1607      } else {
1608        terminfo_print_num1(tui, kTerm_parm_insert_line, -(int)rows);
1609      }
1610    }
1611
1612    // Restore terminal scroll region and cursor
1613    if (!full_screen_scroll) {
1614      reset_scroll_region(tui, fullwidth);
1615    }
1616  } else {
1617    // Mark the moved region as invalid for redrawing later
1618    if (rows > 0) {
1619      endrow = endrow - rows;
1620    } else {
1621      startrow = startrow - rows;
1622    }
1623    invalidate(tui, (int)startrow, (int)endrow, (int)startcol, (int)endcol);
1624  }
1625}
1626
1627/// Add a URL to be used in an OSC 8 hyperlink.
1628///
1629/// @param tui TUIData
1630/// @param url URL to add
1631/// @return Index of new URL, or -1 if URL is invalid
1632int32_t tui_add_url(TUIData *tui, const char *url)
1633  FUNC_ATTR_NONNULL_ARG(1)
1634{
1635  if (url == NULL) {
1636    return -1;
1637  }
1638
1639  MHPutStatus status;
1640  uint32_t k = set_put_idx(cstr_t, &urls, url, &status);
1641  if (status != kMHExisting) {
1642    urls.keys[k] = xstrdup(url);
1643  }
1644  return (int32_t)k;
1645}
1646
1647void tui_hl_attr_define(TUIData *tui, Integer id, HlAttrs attrs, HlAttrs cterm_attrs, Array info)
1648{
1649  attrs.cterm_ae_attr = cterm_attrs.cterm_ae_attr;
1650  attrs.cterm_fg_color = cterm_attrs.cterm_fg_color;
1651  attrs.cterm_bg_color = cterm_attrs.cterm_bg_color;
1652
1653  kv_a(tui->attrs, (size_t)id) = attrs;
1654}
1655
1656void tui_bell(TUIData *tui)
1657{
1658  out(tui, S_LEN("\a"));
1659}
1660
1661void tui_visual_bell(TUIData *tui)
1662{
1663  if (tui->screen_or_tmux) {
1664    out(tui, S_LEN("\x1bg"));
1665  } else {
1666    out(tui, S_LEN("\x1b[?5h"));
1667
1668    flush_buf(tui, kFlushBufFinal);
1669    uv_sleep(100);  // typically either 100 or 200 in terminfo. 100 seems enough
1670
1671    out(tui, S_LEN("\x1b[?5l"));
1672  }
1673  flush_buf(tui, kFlushBufFinal);
1674}
1675
1676void tui_default_colors_set(TUIData *tui, Integer rgb_fg, Integer rgb_bg, Integer rgb_sp,
1677                            Integer cterm_fg, Integer cterm_bg)
1678{
1679  tui->clear_attrs.rgb_fg_color = (RgbValue)rgb_fg;
1680  tui->clear_attrs.rgb_bg_color = (RgbValue)rgb_bg;
1681  tui->clear_attrs.rgb_sp_color = (RgbValue)rgb_sp;
1682  tui->clear_attrs.cterm_fg_color = (int16_t)cterm_fg;
1683  tui->clear_attrs.cterm_bg_color = (int16_t)cterm_bg;
1684
1685  tui->print_attr_id = -1;
1686  tui->set_default_colors = true;
1687  invalidate(tui, 0, tui->grid.height, 0, tui->grid.width);
1688}
1689
1690/// Writes to the TTY, or buffers (to avoid "tearing") if a frame is being assembled (or output is
1691/// already buffered).
1692void tui_ui_send(TUIData *tui, String content)
1693  FUNC_ATTR_NONNULL_ALL
1694{
1695  if (kv_size(tui->invalid_regions) || tui->bufpos > 0) {
1696    // Append to buffer instead of writing directly.
1697    out(tui, content.data, content.size);
1698    return;
1699  }
1700  uv_write_t req;
1701  uv_buf_t buf = { .base = content.data, .len = UV_BUF_LEN(content.size) };
1702  int ret = uv_write(&req, (uv_stream_t *)&tui->output_handle, &buf, 1, NULL);
1703  if (ret) {
1704    ELOG("uv_write failed: %s", uv_strerror(ret));
1705  }
1706  uv_run(&tui->write_loop, UV_RUN_DEFAULT);
1707}
1708
1709/// Flushes TUI grid state to a buffer (which is later flushed to the TTY by `flush_buf`).
1710///
1711/// @see flush_buf
1712void tui_flush(TUIData *tui)
1713{
1714  UGrid *grid = &tui->grid;
1715
1716  size_t nrevents = loop_size(tui->loop);
1717  if (nrevents > TOO_MANY_EVENTS) {
1718    WLOG("TUI event-queue flooded (thread_events=%zu); purging", nrevents);
1719    // Back-pressure: UI events may accumulate much faster than the terminal
1720    // device can serve them. Even if SIGINT/CTRL-C is received, user must still
1721    // wait for the TUI event-queue to drain, and if there are ~millions of
1722    // events in the queue, it could take hours. Clearing the queue allows the
1723    // UI to recover. #1234 #5396
1724    loop_purge(tui->loop);
1725    tui_busy_stop(tui);  // avoid hidden cursor
1726  }
1727
1728  while (kv_size(tui->invalid_regions)) {
1729    Rect r = kv_pop(tui->invalid_regions);
1730    assert(r.bot <= grid->height && r.right <= grid->width);
1731
1732    for (int row = r.top; row < r.bot; row++) {
1733      int clear_attr = grid->cells[row][r.right - 1].attr;
1734      int clear_col;
1735      for (clear_col = r.right; clear_col > 0; clear_col--) {
1736        UCell *cell = &grid->cells[row][clear_col - 1];
1737        if (!(cell->data == schar_from_ascii(' ')
1738              && cell->attr == clear_attr)) {
1739          break;
1740        }
1741      }
1742
1743      UGRID_FOREACH_CELL(grid, row, r.left, clear_col, {
1744        print_cell_at_pos(tui, row, curcol, cell,
1745                          curcol < clear_col - 1 && (cell + 1)->data == NUL);
1746      });
1747      if (clear_col < r.right) {
1748        clear_region(tui, row, row + 1, clear_col, r.right, clear_attr);
1749      }
1750    }
1751  }
1752
1753  cursor_goto(tui, tui->row, tui->col);
1754
1755  flush_buf(tui, kFlushBufFinal);
1756}
1757
1758/// Dumps termcap info to the messages area, if 'verbose' >= 3.
1759static void show_verbose_terminfo(TUIData *tui)
1760{
1761  MAXSIZE_TEMP_ARRAY(chunks, 3);
1762  MAXSIZE_TEMP_ARRAY(title, 2);
1763  ADD_C(title, CSTR_AS_OBJ("\n\n--- Terminal info --- {{{\n"));
1764  ADD_C(title, CSTR_AS_OBJ("Title"));
1765  ADD_C(chunks, ARRAY_OBJ(title));
1766  MAXSIZE_TEMP_ARRAY(info, 1);
1767  String str = terminfo_info_msg(&tui->ti, tui->term, tui->terminfo_found_in_db);
1768  ADD_C(info, STRING_OBJ(str));
1769  ADD_C(chunks, ARRAY_OBJ(info));
1770  MAXSIZE_TEMP_ARRAY(end_fold, 2);
1771  ADD_C(end_fold, CSTR_AS_OBJ("}}}\n"));
1772  ADD_C(end_fold, CSTR_AS_OBJ("Title"));
1773  ADD_C(chunks, ARRAY_OBJ(end_fold));
1774
1775  MAXSIZE_TEMP_ARRAY(args, 3);
1776  ADD_C(args, ARRAY_OBJ(chunks));
1777  ADD_C(args, BOOLEAN_OBJ(true));  // history
1778  MAXSIZE_TEMP_DICT(opts, 1);
1779  PUT_C(opts, "verbose", BOOLEAN_OBJ(true));
1780  ADD_C(args, DICT_OBJ(opts));
1781  rpc_send_event(ui_client_channel_id, "nvim_echo", args);
1782  xfree(str.data);
1783}
1784
1785void tui_suspend(TUIData *tui)
1786{
1787// on a non-UNIX system, this is a no-op
1788#ifdef UNIX
1789  ui_client_detach();
1790  tui->mouse_enabled_save = tui->mouse_enabled;
1791  tui->input.callbacks.primary_device_attr = tui_suspend_cb;
1792  terminfo_disable(tui);
1793#endif
1794}
1795
1796#ifdef UNIX
1797static void tui_suspend_cb(TUIData *tui)
1798  FUNC_ATTR_NONNULL_ALL
1799{
1800  tui_terminal_stop(tui);
1801  stream_set_blocking(tui->input.in_fd, true);   // normalize stream (#2598)
1802
1803  // Avoid os/signal.c SIGTSTP handler. ex_stop calls auto_writeall. #33258
1804  kill(0, SIGSTOP);
1805
1806  tui_terminal_start(tui);
1807  tui_terminal_after_startup(tui);
1808  if (tui->mouse_enabled_save) {
1809    tui_mouse_on(tui);
1810  }
1811  stream_set_blocking(tui->input.in_fd, false);  // libuv expects this
1812  ui_client_attach(tui->width, tui->height, tui->term, tui->rgb);
1813}
1814#endif
1815
1816void tui_set_title(TUIData *tui, String title)
1817{
1818  if (!tui->can_set_title) {
1819    return;
1820  }
1821
1822  bool too_long = (title.size > 4096);  // should be enough
1823  if (too_long) {
1824    ELOG("set_title: title string too long!");
1825  }
1826  if (title.size > 0 && !too_long) {
1827    if (!tui->title_enabled) {
1828      // Save title/icon to the "stack". #4063
1829      out(tui, S_LEN("\x1b[22;0t"));
1830      tui->title_enabled = true;
1831    }
1832
1833    if ((sizeof tui->buf - tui->bufpos) < title.size + 2 * TERMINFO_SEQ_LIMIT) {
1834      // The sequence to set title, is usually an OSC sequence that cannot be cut in half.
1835      // flush buffer prior to printing to avoid this
1836      flush_buf(tui, kFlushBufFinal);
1837    }
1838    terminfo_out(tui, kTerm_to_status_line);
1839    out(tui, title.data, title.size);
1840    terminfo_out(tui, kTerm_from_status_line);
1841  } else if (tui->title_enabled) {
1842    // Restore title/icon from the "stack". #4063
1843    out(tui, S_LEN("\x1b[23;0t"));
1844    tui->title_enabled = false;
1845  }
1846}
1847
1848void tui_set_icon(TUIData *tui, String icon)
1849{
1850}
1851
1852void tui_screenshot(TUIData *tui, String path)
1853{
1854  FILE *f = fopen(path.data, "w");
1855  if (f == NULL) {
1856    return;
1857  }
1858
1859  UGrid *grid = &tui->grid;
1860  flush_buf(tui, kFlushBufFinal);
1861  grid->row = 0;
1862  grid->col = 0;
1863
1864  tui->screenshot = f;
1865  fprintf(f, "%d,%d\n", grid->height, grid->width);
1866  terminfo_out(tui, kTerm_clear_screen);
1867  for (int i = 0; i < grid->height; i++) {
1868    cursor_goto(tui, i, 0);
1869    for (int j = 0; j < grid->width; j++) {
1870      UCell cell = grid->cells[i][j];
1871      char buf[MAX_SCHAR_SIZE];
1872      schar_get(buf, cell.data);
1873      print_cell(tui, buf, cell.attr);
1874    }
1875  }
1876  flush_buf(tui, kFlushBufFinal);
1877  tui->screenshot = NULL;
1878
1879  fclose(f);
1880}
1881
1882void tui_option_set(TUIData *tui, String name, Object value)
1883{
1884  if (strequal(name.data, "mousemoveevent")) {
1885    if (tui->mouse_move_enabled != value.data.boolean) {
1886      if (tui->mouse_enabled) {
1887        tui_mouse_off(tui);
1888        tui->mouse_move_enabled = value.data.boolean;
1889        tui_mouse_on(tui);
1890      } else {
1891        tui->mouse_move_enabled = value.data.boolean;
1892      }
1893    }
1894  } else if (strequal(name.data, "termguicolors")) {
1895    tui->rgb = value.data.boolean;
1896    tui->print_attr_id = -1;
1897    invalidate(tui, 0, tui->grid.height, 0, tui->grid.width);
1898
1899    if (ui_client_channel_id) {
1900      MAXSIZE_TEMP_ARRAY(args, 2);
1901      ADD_C(args, CSTR_AS_OBJ("rgb"));
1902      ADD_C(args, BOOLEAN_OBJ(value.data.boolean));
1903      rpc_send_event(ui_client_channel_id, "nvim_ui_set_option", args);
1904    }
1905  } else if (strequal(name.data, "ttimeout")) {
1906    tui->input.ttimeout = value.data.boolean;
1907  } else if (strequal(name.data, "ttimeoutlen")) {
1908    tui->input.ttimeoutlen = (OptInt)value.data.integer;
1909  } else if (strequal(name.data, "verbose")) {
1910    tui->verbose = value.data.integer;
1911  } else if (strequal(name.data, "termsync")) {
1912    tui->sync_output = value.data.boolean;
1913  }
1914}
1915
1916void tui_chdir(TUIData *tui, String path)
1917{
1918  int err = uv_chdir(path.data);
1919  if (err != 0) {
1920    ELOG("Failed to chdir to %s: %s", path.data, uv_strerror(err));
1921  }
1922}
1923
1924void tui_raw_line(TUIData *tui, Integer g, Integer linerow, Integer startcol, Integer endcol,
1925                  Integer clearcol, Integer clearattr, LineFlags flags, const schar_T *chunk,
1926                  const sattr_T *attrs)
1927{
1928  UGrid *grid = &tui->grid;
1929  for (Integer c = startcol; c < endcol; c++) {
1930    grid->cells[linerow][c].data = chunk[c - startcol];
1931    assert((size_t)attrs[c - startcol] < kv_size(tui->attrs));
1932    grid->cells[linerow][c].attr = attrs[c - startcol];
1933  }
1934  UGRID_FOREACH_CELL(grid, (int)linerow, (int)startcol, (int)endcol, {
1935    print_cell_at_pos(tui, (int)linerow, curcol, cell,
1936                      curcol < endcol - 1 && (cell + 1)->data == NUL);
1937  });
1938
1939  if (clearcol > endcol) {
1940    ugrid_clear_chunk(grid, (int)linerow, (int)endcol, (int)clearcol,
1941                      (sattr_T)clearattr);
1942    clear_region(tui, (int)linerow, (int)linerow + 1, (int)endcol, (int)clearcol,
1943                 (int)clearattr);
1944  }
1945
1946  if (flags & kLineFlagWrap && tui->width == grid->width
1947      && linerow + 1 < grid->height) {
1948    // Only do line wrapping if the grid width is equal to the terminal
1949    // width and the line continuation is within the grid.
1950
1951    if (endcol != grid->width) {
1952      // Print the last char of the row, if we haven't already done so.
1953      int size = grid->cells[linerow][grid->width - 1].data == NUL ? 2 : 1;
1954      print_cell_at_pos(tui, (int)linerow, grid->width - size,
1955                        &grid->cells[linerow][grid->width - size], size == 2);
1956    }
1957
1958    // Wrap the cursor over to the next line. The next line will be
1959    // printed immediately without an intervening newline.
1960    final_column_wrap(tui);
1961  }
1962}
1963
1964static void invalidate(TUIData *tui, int top, int bot, int left, int right)
1965{
1966  Rect *intersects = NULL;
1967
1968  for (size_t i = 0; i < kv_size(tui->invalid_regions); i++) {
1969    Rect *r = &kv_A(tui->invalid_regions, i);
1970    // adjacent regions are treated as overlapping
1971    if (!(top > r->bot || bot < r->top)
1972        && !(left > r->right || right < r->left)) {
1973      intersects = r;
1974      break;
1975    }
1976  }
1977
1978  if (intersects) {
1979    // If top/bot/left/right intersects with a invalid rect, we replace it
1980    // by the union
1981    intersects->top = MIN(top, intersects->top);
1982    intersects->bot = MAX(bot, intersects->bot);
1983    intersects->left = MIN(left, intersects->left);
1984    intersects->right = MAX(right, intersects->right);
1985  } else {
1986    // Else just add a new entry;
1987    kv_push(tui->invalid_regions, ((Rect) { top, bot, left, right }));
1988  }
1989}
1990
1991void tui_set_size(TUIData *tui, int width, int height)
1992  FUNC_ATTR_NONNULL_ALL
1993{
1994  tui->pending_resize_events++;
1995  tui->width = width;
1996  tui->height = height;
1997  ui_client_set_size(width, height);
1998}
1999
2000/// Tries to get the user's wanted dimensions (columns and rows) for the entire
2001/// application (i.e., the host terminal).
2002void tui_guess_size(TUIData *tui)
2003{
2004  int width = 0;
2005  int height = 0;
2006  char *lines = NULL;
2007  char *columns = NULL;
2008
2009  // 1 - try from a system call (ioctl/TIOCGWINSZ on unix)
2010  if (tui->out_isatty
2011      && !uv_tty_get_winsize(&tui->output_handle.tty, &width, &height)) {
2012    goto end;
2013  }
2014
2015  // 2 - use $LINES/$COLUMNS if available
2016  const char *val;
2017  int advance;
2018  if ((val = os_getenv_noalloc("LINES"))
2019      && sscanf(val, "%d%n", &height, &advance) != EOF && advance
2020      && (val = os_getenv_noalloc("COLUMNS"))
2021      && sscanf(val, "%d%n", &width, &advance) != EOF && advance) {
2022    goto end;
2023  }
2024
2025  // 3 - read from terminfo if available
2026  height = tui->ti.lines;
2027  width = tui->ti.columns;
2028
2029  end:
2030  if (width <= 0 || height <= 0) {
2031    // use the defaults
2032    width = DFLT_COLS;
2033    height = DFLT_ROWS;
2034  }
2035
2036  tui_set_size(tui, width, height);
2037
2038  xfree(lines);
2039  xfree(columns);
2040}
2041
2042static void out(TUIData *tui, const char *str, size_t len)
2043{
2044  size_t available = sizeof(tui->buf) - tui->bufpos;
2045
2046  if (len > available) {
2047    flush_buf(tui, kFlushBufPartial);
2048    if (len > sizeof(tui->buf)) {
2049      // Don't use tui->buf[] when the string to output is too long. #30794
2050      tui->buf_to_flush = (char *)str;
2051      tui->bufpos = len;
2052      flush_buf(tui, kFlushBufPartial);
2053      return;
2054    }
2055  }
2056
2057  memcpy(tui->buf + tui->bufpos, str, len);
2058  tui->bufpos += len;
2059}
2060
2061static void out_len(TUIData *tui, const char *str)
2062{
2063  if (str != NULL) {
2064    out(tui, str, strlen(str));
2065  }
2066}
2067
2068/// drops the entire message if it doesn't fit in "limit"
2069void out_printf(TUIData *tui, size_t limit, const char *fmt, ...)
2070  FUNC_ATTR_PRINTF(3, 4)
2071{
2072  assert(limit <= sizeof(tui->buf));
2073  size_t available = sizeof(tui->buf) - tui->bufpos;
2074  if (available < limit) {
2075    flush_buf(tui, kFlushBufPartial);
2076  }
2077
2078  va_list ap;
2079  va_start(ap, fmt);
2080  int printed = vsnprintf(tui->buf + tui->bufpos, limit, fmt, ap);
2081  va_end(ap);
2082
2083  if (printed > 0) {
2084    tui->bufpos += (size_t)printed;
2085  }
2086}
2087
2088static void terminfo_out(TUIData *tui, TerminfoDef what)
2089{
2090  TPVAR null_params[9] = { 0 };
2091  terminfo_print(tui, what, null_params);
2092}
2093
2094static void terminfo_print_num(TUIData *tui, TerminfoDef what, int num1, int num2, int num3)
2095{
2096  TPVAR params[9] = { 0 };
2097  params[0].num = num1;
2098  params[1].num = num2;
2099  params[2].num = num3;
2100  terminfo_print(tui, what, params);
2101}
2102
2103static void terminfo_print(TUIData *tui, TerminfoDef what, TPVAR *params)
2104{
2105  if (what >= kTermCount) {
2106    abort();
2107  }
2108
2109  const char *str = tui->ti.defs[what];
2110  if (str == NULL || *str == NUL) {
2111    return;
2112  }
2113
2114  if (sizeof(tui->buf) - tui->bufpos > TERMINFO_SEQ_LIMIT) {
2115    TPVAR copy_params[9];
2116    memcpy(copy_params, params, sizeof copy_params);
2117    size_t len = terminfo_fmt(tui->buf + tui->bufpos, tui->buf + sizeof(tui->buf), str,
2118                              copy_params);
2119    if (len > 0) {
2120      tui->bufpos += len;
2121      return;
2122    }
2123  }
2124
2125  // try again with fresh buffer
2126  flush_buf(tui, kFlushBufPartial);
2127  size_t len = terminfo_fmt(tui->buf + tui->bufpos, tui->buf + sizeof(tui->buf), str, params);
2128  if (len > 0) {
2129    tui->bufpos += len;
2130  }
2131}
2132static void terminfo_set_if_empty(TUIData *tui, TerminfoDef str, const char *val)
2133{
2134  if (!tui->ti.defs[str]) {
2135    tui->ti.defs[str] = val;
2136  }
2137}
2138
2139static void terminfo_set_str(TUIData *tui, TerminfoDef str, const char *val)
2140{
2141  tui->ti.defs[str] = val;
2142}
2143
2144/// Determine if the terminal supports truecolor or not.
2145///
2146/// note: We get another chance at detecting these in the nvim server process, see
2147/// the use of vim.tty in runtime/lua/vim/_core/defaults.lua
2148///
2149/// If terminfo contains Tc, RGB, or both setrgbf and setrgbb capabilities, return true.
2150static bool term_has_truecolor(TUIData *tui, const char *colorterm)
2151{
2152  // Check $COLORTERM
2153  if (strequal(colorterm, "truecolor") || strequal(colorterm, "24bit")) {
2154    return true;
2155  }
2156
2157  if (tui->ti.Tc || tui->ti.RGB) {
2158    // terminfo had one of "Tc" or "RGB" extended boolean capabilities
2159    return true;
2160  }
2161
2162  // Check for setrgbf and setrgbb
2163  bool setrgbf = tui->ti.defs[kTerm_set_rgb_foreground];
2164  bool setrgbb = tui->ti.defs[kTerm_set_rgb_background];
2165
2166  return setrgbf && setrgbb;
2167}
2168
2169/// Patches the terminfo records after loading from system or built-in db.
2170/// Several entries in terminfo are known to be deficient or outright wrong;
2171/// and several terminal emulators falsely announce incorrect terminal types.
2172static void patch_terminfo_bugs(TUIData *tui, const char *term, const char *colorterm,
2173                                int vte_version, int konsolev, bool iterm_env, bool nsterm)
2174{
2175  char *xterm_version = os_getenv("XTERM_VERSION");
2176  bool xterm = terminfo_is_term_family(term, "xterm")
2177               // Treat Terminal.app as generic xterm-like, for now.
2178               || nsterm;
2179  bool hterm = terminfo_is_term_family(term, "hterm");
2180  bool kitty = terminfo_is_term_family(term, "xterm-kitty");
2181  bool linuxvt = terminfo_is_term_family(term, "linux");
2182  bool bsdvt = terminfo_is_bsd_console(term);
2183  bool rxvt = terminfo_is_term_family(term, "rxvt");
2184  bool teraterm = terminfo_is_term_family(term, "teraterm");
2185  bool putty = terminfo_is_term_family(term, "putty");
2186  bool screen = terminfo_is_term_family(term, "screen");
2187  bool tmux = terminfo_is_term_family(term, "tmux") || os_env_exists("TMUX", true);
2188  bool st = terminfo_is_term_family(term, "st");
2189  bool gnome = terminfo_is_term_family(term, "gnome")
2190               || terminfo_is_term_family(term, "vte");
2191  bool iterm = terminfo_is_term_family(term, "iterm")
2192               || terminfo_is_term_family(term, "iterm2")
2193               || terminfo_is_term_family(term, "iTerm.app")
2194               || terminfo_is_term_family(term, "iTerm2.app");
2195  bool alacritty = terminfo_is_term_family(term, "alacritty");
2196  bool foot = terminfo_is_term_family(term, "foot");
2197  // None of the following work over SSH; see :help TERM .
2198  bool iterm_pretending_xterm = xterm && iterm_env;
2199  bool gnome_pretending_xterm = xterm && colorterm
2200                                && strstr(colorterm, "gnome-terminal");
2201  bool mate_pretending_xterm = xterm && colorterm
2202                               && strstr(colorterm, "mate-terminal");
2203  bool true_xterm = xterm && !!xterm_version && !bsdvt;
2204  bool cygwin = terminfo_is_term_family(term, "cygwin");
2205  bool ghostty = terminfo_is_term_family(term, "xterm-ghostty");
2206
2207  const char *fix_normal = tui->ti.defs[kTerm_cursor_normal];
2208  if (fix_normal) {
2209    if (STARTS_WITH(fix_normal, "\x1b[?12l")) {
2210      // terminfo typically includes DECRST 12 as part of setting up the
2211      // normal cursor, which interferes with the user's control via
2212      // set_cursor_style.  When DECRST 12 is present, skip over it, but honor
2213      // the rest of the cnorm setting.
2214      fix_normal += sizeof "\x1b[?12l" - 1;
2215      terminfo_set_str(tui, kTerm_cursor_normal, fix_normal);
2216    }
2217    if (linuxvt
2218        && strlen(fix_normal) >= (sizeof LINUXSET0C - 1)
2219        && !memcmp(strchr(fix_normal, 0) - (sizeof LINUXSET0C - 1),
2220                   LINUXSET0C, sizeof LINUXSET0C - 1)) {
2221      // The Linux terminfo entry similarly includes a Linux-idiosyncractic
2222      // cursor shape reset in cnorm, which similarly interferes with
2223      // set_cursor_style.
2224      char *new_normal = arena_memdupz(&tui->ti_arena, fix_normal,
2225                                       strlen(fix_normal) - (sizeof LINUXSET0C - 1));
2226      terminfo_set_str(tui, kTerm_cursor_normal, new_normal);
2227    }
2228  }
2229  const char *fix_invisible = tui->ti.defs[kTerm_cursor_invisible];
2230  if (fix_invisible) {
2231    if (linuxvt
2232        && strlen(fix_invisible) >= (sizeof LINUXSET1C - 1)
2233        && !memcmp(strchr(fix_invisible, 0) - (sizeof LINUXSET1C - 1),
2234                   LINUXSET1C, sizeof LINUXSET1C - 1)) {
2235      // The Linux terminfo entry similarly includes a Linux-idiosyncractic
2236      // cursor shape reset in cinvis, which similarly interferes with
2237      // set_cursor_style.
2238      char *new_invisible = arena_memdupz(&tui->ti_arena, fix_invisible,
2239                                          strlen(fix_invisible) - (sizeof LINUXSET1C - 1));
2240      terminfo_set_str(tui, kTerm_cursor_invisible, new_invisible);
2241    }
2242  }
2243
2244  if (tmux || screen || kitty) {
2245    // Disable BCE in some cases we know it is not working. #8806
2246    tui->ti.back_color_erase = false;
2247  }
2248
2249  if (xterm || hterm) {
2250    // Termit, LXTerminal, GTKTerm2, GNOME Terminal, MATE Terminal, roxterm,
2251    // and EvilVTE falsely claim to be xterm and do not support important xterm
2252    // control sequences that we use.  In an ideal world, these would have
2253    // their own terminal types and terminfo entries, like PuTTY does, and not
2254    // claim to be xterm.  Or they would mimic xterm properly enough to be
2255    // treatable as xterm.
2256
2257    // 2017-04 terminfo.src lacks these.  Xterm-likes have them.
2258    if (!hterm) {
2259      // hterm doesn't have a status line.
2260      terminfo_set_if_empty(tui, kTerm_to_status_line, "\x1b]0;");
2261      terminfo_set_if_empty(tui, kTerm_from_status_line, "\x07");
2262    }
2263    terminfo_set_if_empty(tui, kTerm_enter_italics_mode, "\x1b[3m");
2264
2265    // 2025: This are not supported by all xterm-alikes, but it is only
2266    // used when kTermModeLeftAndRightMargins is detected
2267    terminfo_set_if_empty(tui, kTerm_set_lr_margin, "\x1b[%i%p1%d;%p2%ds");
2268
2269#ifdef MSWIN
2270    // XXX: workaround libuv implicit LF => CRLF conversion. #10558
2271    terminfo_set_str(tui, kTerm_cursor_down, "\x1b[B");
2272#endif
2273  } else if (rxvt) {
2274    // 2017-04 terminfo.src lacks these.  Unicode rxvt has them.
2275    terminfo_set_if_empty(tui, kTerm_enter_italics_mode, "\x1b[3m");
2276    terminfo_set_if_empty(tui, kTerm_to_status_line, "\x1b]2");
2277    terminfo_set_if_empty(tui, kTerm_from_status_line, "\x07");
2278    // 2017-04 terminfo.src has older control sequences.
2279    terminfo_set_str(tui, kTerm_enter_ca_mode, "\x1b[?1049h");
2280    terminfo_set_str(tui, kTerm_exit_ca_mode, "\x1b[?1049l");
2281    // rxvt-unicode has a default steady block cursor, though there's an option
2282    // to initialize it with an underline https://cvs.schmorp.de/rxvt-unicode/src/init.C?revision=1.351&view=markup#l727
2283    // \x1b[0 q doesn't work because it makes it a blinking block https://cvs.schmorp.de/rxvt-unicode/src/command.C?revision=1.605&view=markup#l4122
2284    // We can't really account for that, so just set it to steady block and hope for the best.
2285    terminfo_set_str(tui, kTerm_reset_cursor_style, "\x1b[2 q");
2286    terminfo_set_str(tui, kTerm_set_cursor_style, "\x1b[%p1%d q");
2287  } else if (screen) {
2288    // per the screen manual; 2017-04 terminfo.src lacks these.
2289    terminfo_set_if_empty(tui, kTerm_to_status_line, "\x1b_");
2290    terminfo_set_if_empty(tui, kTerm_from_status_line, "\x1b\\");
2291  } else if (tmux) {
2292    terminfo_set_if_empty(tui, kTerm_to_status_line, "\x1b_");
2293    terminfo_set_if_empty(tui, kTerm_from_status_line, "\x1b\\");
2294    terminfo_set_if_empty(tui, kTerm_enter_italics_mode, "\x1b[3m");
2295  } else if (terminfo_is_term_family(term, "interix")) {
2296    // 2017-04 terminfo.src lacks this.
2297    terminfo_set_if_empty(tui, kTerm_carriage_return, "\x0d");
2298  } else if (linuxvt) {
2299    terminfo_set_if_empty(tui, kTerm_parm_up_cursor, "\x1b[%p1%dA");
2300    terminfo_set_if_empty(tui, kTerm_parm_down_cursor, "\x1b[%p1%dB");
2301    terminfo_set_if_empty(tui, kTerm_parm_right_cursor, "\x1b[%p1%dC");
2302    terminfo_set_if_empty(tui, kTerm_parm_left_cursor, "\x1b[%p1%dD");
2303  } else if (putty) {
2304    // No bugs in the vanilla terminfo for our purposes.
2305  } else if (iterm) {
2306    // 2017-04 terminfo.src has older control sequences.
2307    terminfo_set_str(tui, kTerm_enter_ca_mode, "\x1b[?1049h");
2308    terminfo_set_str(tui, kTerm_exit_ca_mode, "\x1b[?1049l");
2309    // 2017-04 terminfo.src lacks these.
2310    terminfo_set_if_empty(tui, kTerm_enter_italics_mode, "\x1b[3m");
2311  } else if (st) {
2312    // No bugs in the vanilla terminfo for our purposes.
2313  }
2314
2315// At this time (2017-07-12) it seems like all terminals that support 256
2316// color codes can use semicolons in the terminal code and be fine.
2317// However, this is not correct according to the spec. So to reward those
2318// terminals that also support colons, we output the code that way on these
2319// specific ones.
2320
2321// using colons like ISO 8613-6:1994/ITU T.416:1993 says.
2322#define XTERM_SETAF_256_COLON \
2323  "\x1b[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38:5:%p1%d%;m"
2324#define XTERM_SETAB_256_COLON \
2325  "\x1b[%?%p1%{8}%<%t4%p1%d%e%p1%{16}%<%t10%p1%{8}%-%d%e48:5:%p1%d%;m"
2326
2327#define XTERM_SETAF_256 \
2328  "\x1b[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;m"
2329#define XTERM_SETAB_256 \
2330  "\x1b[%?%p1%{8}%<%t4%p1%d%e%p1%{16}%<%t10%p1%{8}%-%d%e48;5;%p1%d%;m"
2331#define XTERM_SETAF_16 \
2332  "\x1b[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e39%;m"
2333#define XTERM_SETAB_16 \
2334  "\x1b[%?%p1%{8}%<%t4%p1%d%e%p1%{16}%<%t10%p1%{8}%-%d%e39%;m"
2335
2336  // Terminals with 256-colour SGR support despite what terminfo says.
2337  if (tui->ti.max_colors < 256) {
2338    // See http://fedoraproject.org/wiki/Features/256_Color_Terminals
2339    if (true_xterm || iterm || iterm_pretending_xterm) {
2340      tui->ti.max_colors = 256;
2341      terminfo_set_str(tui, kTerm_set_a_foreground, XTERM_SETAF_256_COLON);
2342      terminfo_set_str(tui, kTerm_set_a_background, XTERM_SETAB_256_COLON);
2343    } else if (konsolev || xterm || gnome || rxvt || st || putty
2344               || linuxvt  // Linux 4.8+ supports 256-colour SGR.
2345               || mate_pretending_xterm || gnome_pretending_xterm
2346               || tmux
2347               || (colorterm && strstr(colorterm, "256"))
2348               || (term && strstr(term, "256"))) {
2349      tui->ti.max_colors = 256;
2350      terminfo_set_str(tui, kTerm_set_a_foreground, XTERM_SETAF_256);
2351      terminfo_set_str(tui, kTerm_set_a_background, XTERM_SETAB_256);
2352    }
2353  }
2354  // Terminals with 16-colour SGR support despite what terminfo says.
2355  if (tui->ti.max_colors < 16) {
2356    if (colorterm) {
2357      tui->ti.max_colors = 16;
2358      terminfo_set_if_empty(tui, kTerm_set_a_foreground, XTERM_SETAF_16);
2359      terminfo_set_if_empty(tui, kTerm_set_a_background, XTERM_SETAB_16);
2360    }
2361  }
2362
2363  // Blacklist of terminals that cannot be trusted to report DECSCUSR support.
2364  if ((st || (vte_version != 0 && vte_version < 3900) || konsolev)) {
2365    tui->ti.defs[kTerm_reset_cursor_style] = NULL;
2366  }
2367
2368  // Dickey ncurses terminfo includes Ss/Se capabilities since 2011-07-14. So
2369  // adding them to terminal types, that have such control sequences but lack
2370  // the correct terminfo entries, is a fixup, not an augmentation.
2371  // DECSCUSR (cursor shape) is widely supported.
2372  // https://github.com/gnachman/iTerm2/pull/92
2373  if (!bsdvt
2374      && (putty         // per MinTTY 0.4.3-1 release notes from 2009
2375          // per https://chromium.googlesource.com/apps/libapps/+/a5fb83c190aa9d74f4a9bca233dac6be2664e9e9/hterm/doc/ControlSequences.md
2376          || hterm
2377          // per https://bugzilla.gnome.org/show_bug.cgi?id=720821
2378          || vte_version
2379          || konsolev   // #9364
2380          || tmux       // per tmux manual page
2381          // https://lists.gnu.org/archive/html/screen-devel/2013-03/msg00000.html
2382          || screen
2383          || st         // #7641
2384          // https://github.com/gnachman/iTerm2/pull/651
2385          || iterm || iterm_pretending_xterm
2386          || teraterm   // per TeraTerm "Supported Control Functions" doco
2387          || alacritty  // https://github.com/jwilm/alacritty/pull/608
2388          || cygwin
2389          || foot
2390          || kitty      // https://github.com/kovidgoyal/kitty/pull/9929
2391          || ghostty    // https://github.com/ghostty-org/ghostty/pull/12487
2392          // Some linux-type terminals implement the xterm extension.
2393          // Example: console-terminal-emulator from the nosh toolset.
2394          || (linuxvt
2395              && (xterm_version || colorterm)))) {
2396    terminfo_set_str(tui, kTerm_set_cursor_style, "\x1b[%p1%d q");
2397    terminfo_set_str(tui, kTerm_reset_cursor_style, "\x1b[0 q");
2398  } else if (linuxvt) {
2399    // Linux uses an idiosyncratic escape code to set the cursor shape and
2400    // does not support DECSCUSR.
2401    // See http://linuxgazette.net/137/anonymous.html for more info
2402    terminfo_set_str(tui, kTerm_set_cursor_style,
2403                     "\x1b[?"
2404                     "%?"
2405                     // The parameter passed to Ss is the DECSCUSR parameter, so the
2406                     // terminal capability has to translate into the Linux idiosyncratic
2407                     // parameter.
2408                     //
2409                     // linuxvt only supports block and underline. It is also only
2410                     // possible to have a steady block (no steady underline)
2411                     "%p1%{2}%<" "%t%{8}"       // blink block
2412                     "%e%p1%{2}%=" "%t%{112}"   // steady block
2413                     "%e%p1%{3}%=" "%t%{4}"     // blink underline (set to half block)
2414                     "%e%p1%{4}%=" "%t%{4}"     // steady underline
2415                     "%e%p1%{5}%=" "%t%{2}"     // blink bar (set to underline)
2416                     "%e%p1%{6}%=" "%t%{2}"     // steady bar
2417                     "%e%{0}"                   // anything else
2418                     "%;" "%dc");
2419    terminfo_set_str(tui, kTerm_reset_cursor_style, "\x1b[?c");
2420  } else if (!bsdvt && xterm) {
2421    terminfo_set_if_empty(tui, kTerm_set_cursor_style, "\x1b[%p1%d q");
2422    // xterm has a configurable cursor, but the default is 2, and 0 doesn't
2423    // reset to default. #41047
2424    terminfo_set_if_empty(tui, kTerm_reset_cursor_style, "\x1b[2 q");
2425  }
2426
2427  xfree(xterm_version);
2428}
2429
2430/// This adds stuff that is not in standard terminfo.
2431static void augment_terminfo(TUIData *tui, const char *term, int vte_version, int konsolev,
2432                             const char *weztermv, bool iterm_env, bool nsterm)
2433{
2434  char *xterm_version = os_getenv("XTERM_VERSION");
2435  bool xterm = terminfo_is_term_family(term, "xterm")
2436               // Treat Terminal.app as generic xterm-like, for now.
2437               || nsterm;
2438  bool hterm = terminfo_is_term_family(term, "hterm");
2439  bool bsdvt = terminfo_is_bsd_console(term);
2440  bool dtterm = terminfo_is_term_family(term, "dtterm");
2441  bool rxvt = terminfo_is_term_family(term, "rxvt");
2442  bool teraterm = terminfo_is_term_family(term, "teraterm");
2443  bool putty = terminfo_is_term_family(term, "putty");
2444  bool screen = terminfo_is_term_family(term, "screen");
2445  bool tmux = terminfo_is_term_family(term, "tmux") || os_env_exists("TMUX", true);
2446  bool st = terminfo_is_term_family(term, "st");
2447  bool iterm = terminfo_is_term_family(term, "iterm")
2448               || terminfo_is_term_family(term, "iterm2")
2449               || terminfo_is_term_family(term, "iTerm.app")
2450               || terminfo_is_term_family(term, "iTerm2.app");
2451  bool alacritty = terminfo_is_term_family(term, "alacritty");
2452  bool kitty = terminfo_is_term_family(term, "xterm-kitty");
2453  // None of the following work over SSH; see :help TERM .
2454  bool iterm_pretending_xterm = xterm && iterm_env;
2455
2456  bool true_xterm = xterm && !!xterm_version && !bsdvt;
2457
2458  // Only define this capability for terminal types that we know understand it.
2459  if (dtterm         // originated this extension
2460      || xterm       // per xterm ctlseqs doco
2461      || konsolev    // per commentary in VT102Emulation.cpp
2462      || teraterm    // per TeraTerm "Supported Control Functions" doco
2463      || rxvt) {     // per command.C
2464    tui->can_resize_screen = true;
2465  }
2466
2467  if (putty || xterm || hterm || rxvt) {
2468    tui->terminfo_ext.reset_scroll_region = "\x1b[r";
2469  }
2470
2471  // It should be pretty safe to always enable this, as terminals will ignore
2472  // unrecognised SGR numbers.
2473  tui->terminfo_ext.enter_altfont_mode = "\x1b[11m";
2474
2475  // Dickey ncurses terminfo does not include the setrgbf and setrgbb
2476  // capabilities, proposed by Rüdiger Sonderfeld on 2013-10-15.  Adding
2477  // them here when terminfo lacks them is an augmentation, not a fixup.
2478  // https://github.com/termstandard/colors
2479
2480  // At this time (2017-07-12) it seems like all terminals that support rgb
2481  // color codes can use semicolons in the terminal code and be fine.
2482  // However, this is not correct according to the spec. So to reward those
2483  // terminals that also support colons, we output the code that way on these
2484  // specific ones.
2485
2486  // can use colons like ISO 8613-6:1994/ITU T.416:1993 says.
2487  bool has_colon_rgb = !tmux && !screen
2488                       && !vte_version  // VTE colon-support has a big memory leak. #7573
2489                       && (iterm || iterm_pretending_xterm  // per VT100Terminal.m
2490                           // per http://invisible-island.net/xterm/xterm.log.html#xterm_282
2491                           || true_xterm);
2492
2493  if (tui->ti.defs[kTerm_set_rgb_foreground] == NULL) {
2494    if (has_colon_rgb) {
2495      tui->ti.defs[kTerm_set_rgb_foreground] = "\x1b[38:2:%p1%d:%p2%d:%p3%dm";
2496    } else {
2497      tui->ti.defs[kTerm_set_rgb_foreground] = "\x1b[38;2;%p1%d;%p2%d;%p3%dm";
2498    }
2499  }
2500  if (tui->ti.defs[kTerm_set_rgb_background] == NULL) {
2501    if (has_colon_rgb) {
2502      tui->ti.defs[kTerm_set_rgb_background] = "\x1b[48:2:%p1%d:%p2%d:%p3%dm";
2503    } else {
2504      tui->ti.defs[kTerm_set_rgb_background] = "\x1b[48;2;%p1%d;%p2%d;%p3%dm";
2505    }
2506  }
2507
2508  if (tui->ti.defs[kTerm_set_cursor_color] == NULL) {
2509    if (iterm || iterm_pretending_xterm) {
2510      // FIXME: Bypassing tmux like this affects the cursor colour globally, in
2511      // all panes, which is not particularly desirable.  A better approach
2512      // would use a tmux control sequence and an extra if(screen) test.
2513      tui->ti.defs[kTerm_set_cursor_color] = TMUX_WRAP(tmux, "\033]Pl%p1%06x\033\\");
2514    } else if ((xterm || hterm || rxvt || tmux || alacritty || st)
2515               && (vte_version == 0 || vte_version >= 3900)) {
2516      // Supported in urxvt, newer VTE.
2517      // Supported in st, but currently missing in ncurses definitions. #32217
2518      tui->ti.defs[kTerm_set_cursor_color] = "\033]12;%p1%s\007";
2519    }
2520  }
2521  if (tui->ti.defs[kTerm_set_cursor_color] != NULL) {
2522    // Some terminals supporting cursor color changing specify their Cs
2523    // capability to take a string parameter. Others take a numeric parameter.
2524    // If and only if the format string contains `%s` we assume a string
2525    // parameter. #20628
2526    tui->set_cursor_color_as_str = strstr(tui->ti.defs[kTerm_set_cursor_color], "%s") != NULL;
2527
2528    terminfo_set_if_empty(tui, kTerm_reset_cursor_color, "\x1b]112\x07");
2529  }
2530
2531  if (tui->ti.defs[kTerm_to_status_line] != NULL && tui->ti.defs[kTerm_from_status_line] != NULL) {
2532    tui->can_set_title = true;
2533  }
2534
2535  // For urxvt send BOTH xterm and old urxvt sequences. #8695
2536  tui->terminfo_ext.enable_focus_reporting =
2537    rxvt
2538    ? "\x1b[?1004h\x1b]777;focus;on\x7"
2539    : "\x1b[?1004h";
2540  tui->terminfo_ext.disable_focus_reporting =
2541    rxvt ? "\x1b[?1004l\x1b]777;focus;off\x7" : "\x1b[?1004l";
2542
2543  // Extended underline.
2544  // terminfo will have Smulx for this (but no support for colors yet).
2545  if (tui->ti.defs[kTerm_set_underline_style] == NULL) {
2546    if (vte_version >= 5102 || konsolev >= 221170
2547        || tui->ti.Su || (weztermv != NULL && strcmp(weztermv, "20210203-095643") > 0)) {
2548      tui_enable_extended_underline(tui);
2549    }
2550  } else {
2551    tui_enable_extended_underline(tui);
2552  }
2553
2554  if (kitty || (vte_version != 0 && vte_version < 5400)) {
2555    // Never use modifyOtherKeys in kitty if kitty keyboard protocol query fails.
2556    // Also don't emit the sequence to enable modifyOtherKeys in old VTE versions.
2557    tui->input.key_encoding = kKeyEncodingLegacy;
2558  } else {
2559    // Fallback to Xterm's modifyOtherKeys if terminal does not support the
2560    // Kitty keyboard protocol. We don't actually enable the key encoding here
2561    // though: it won't be enabled until the terminal responds to our query for
2562    // kitty keyboard support.
2563    tui->input.key_encoding = kKeyEncodingXterm;
2564  }
2565
2566  xfree(xterm_version);
2567}
2568
2569static bool should_invisible(TUIData *tui)
2570{
2571  return tui->busy || tui->want_invisible;
2572}
2573
2574/// Flushes the rendered buffer to the TTY.
2575///
2576/// @see tui_flush
2577static void flush_buf(TUIData *tui, FlushBufFinish finish)
2578  FUNC_ATTR_NONNULL_ALL
2579{
2580  bool should_be_invisible = should_invisible(tui);
2581
2582  // Nothing to flush unless a final flush must end an active synchronized update.
2583  if (tui->bufpos <= 0 && tui->is_invisible == should_be_invisible
2584      && !(finish == kFlushBufFinal && tui->sync_output_active)) {
2585    return;
2586  }
2587
2588  uv_write_t req;
2589  uv_buf_t bufs[3];
2590  char pre[32];
2591  char post[32];
2592  size_t pre_len = 0;
2593  size_t post_len = 0;
2594  TPVAR null_params[9] = { 0 };
2595
2596  // Begin flushing output. If 'termsync' is set and the terminal supports synchronized
2597  // output, begin synchronized update.
2598  if (!tui->sync_output_active && tui->sync_output && tui->has_sync_mode) {
2599    static const char sync_start[] = "\x1b[?2026h";
2600    memcpy(pre, sync_start, sizeof sync_start);
2601    pre_len += sizeof sync_start - 1;
2602    tui->sync_output_active = true;
2603  } else if (!tui->sync_output_active && !tui->is_invisible) {
2604    // Otherwise, hide the cursor to avoid cursor jumping.
2605    tui->is_invisible = true;
2606
2607    // TODO(bfredl): zero-param terminfo strings should be pre-filtered so we can just
2608    // return a cached string here
2609    const char *str = tui->ti.defs[kTerm_cursor_invisible];
2610    if (str != NULL) {
2611      pre_len += terminfo_fmt(pre + pre_len, pre + sizeof(pre), str, null_params);
2612    }
2613  }
2614
2615  // End synchronized update on the final flush.
2616  if (finish == kFlushBufFinal && tui->sync_output_active) {
2617    static const char sync_end[] = "\x1b[?2026l";
2618    memcpy(post, sync_end, sizeof sync_end);
2619    post_len += sizeof sync_end - 1;
2620    tui->sync_output_active = false;
2621  }
2622
2623  // Once synchronized output has ended, or when it was not active, make the cursor
2624  // visible or invisible according to the current TUI state.
2625  if (!tui->sync_output_active) {
2626    const char *str = NULL;
2627    if (tui->is_invisible && !should_be_invisible) {
2628      str = tui->ti.defs[kTerm_cursor_normal];
2629      tui->is_invisible = false;
2630    } else if (!tui->is_invisible && should_be_invisible) {
2631      str = tui->ti.defs[kTerm_cursor_invisible];
2632      tui->is_invisible = true;
2633    }
2634    if (str != NULL) {
2635      post_len += terminfo_fmt(post + post_len, post + sizeof(post), str, null_params);
2636    }
2637  }
2638
2639  bufs[0].base = pre;
2640  bufs[0].len = UV_BUF_LEN(pre_len);
2641
2642  bufs[1].base = tui->buf_to_flush != NULL ? tui->buf_to_flush : tui->buf;
2643  bufs[1].len = UV_BUF_LEN(tui->bufpos);
2644
2645  bufs[2].base = post;
2646  bufs[2].len = UV_BUF_LEN(post_len);
2647
2648  if (tui->screenshot) {
2649    for (size_t i = 0; i < ARRAY_SIZE(bufs); i++) {
2650      fwrite(bufs[i].base, bufs[i].len, 1, tui->screenshot);
2651    }
2652  } else {
2653    unsigned nbufs = ARRAY_SIZE(bufs);
2654    while (nbufs > 0 && bufs[nbufs - 1].len == 0) {
2655      nbufs--;  // Trim trailing zero-length buffers. https://github.com/libuv/libuv/issues/5182
2656    }
2657    if (nbufs > 0) {
2658      int ret = uv_write(&req, (uv_stream_t *)&tui->output_handle, bufs, nbufs, NULL);
2659      if (ret) {
2660        ELOG("uv_write failed: %s", uv_strerror(ret));
2661      }
2662      uv_run(&tui->write_loop, UV_RUN_DEFAULT);
2663    }
2664  }
2665  tui->buf_to_flush = NULL;
2666  tui->bufpos = 0;
2667}
2668
2669/// Try to get "kbs" code from stty because "the terminfo kbs entry is extremely
2670/// unreliable." (Vim, Bash, and tmux also do this.)
2671/// On Windows, use 0x7f as Backspace if VT input has been enabled by stream_init().
2672///
2673/// @see tmux/tty-keys.c fe4e9470bb504357d073320f5d305b22663ee3fd
2674/// @see https://bugzilla.redhat.com/show_bug.cgi?id=142659
2675/// @see https://github.com/microsoft/terminal/issues/4949
2676static const char *tui_get_stty_erase(TermInput *input)
2677{
2678  static char stty_erase[2] = { 0 };
2679#ifdef HAVE_TERMIOS_H
2680  struct termios t;
2681  if (tcgetattr(input->in_fd, &t) != -1) {
2682    stty_erase[0] = (char)t.c_cc[VERASE];
2683    stty_erase[1] = NUL;
2684    DLOG("stty/termios:erase=%s", stty_erase);
2685  }
2686#elif defined(MSWIN)
2687  DWORD dwMode;
2688  if (((uv_handle_t *)&input->read_stream.s.uv)->type == UV_TTY
2689      && GetConsoleMode(input->read_stream.s.uv.tty.handle, &dwMode)
2690      && (dwMode & ENABLE_VIRTUAL_TERMINAL_INPUT)) {
2691    stty_erase[0] = '\x7f';
2692    stty_erase[1] = NUL;
2693  }
2694#endif
2695  return stty_erase;
2696}
2697
2698/// libtermkey hook to override terminfo entries.
2699/// @see TermInput.tk_ti_hook_fn
2700static const char *tui_tk_ti_getstr(const char *name, const char *value, void *data)
2701{
2702  TermInput *input = data;
2703  static const char *stty_erase = NULL;
2704  if (stty_erase == NULL) {
2705    stty_erase = tui_get_stty_erase(input);
2706  }
2707
2708  if (strequal(name, "key_backspace")) {
2709    DLOG("libtermkey:kbs=%s", value);
2710    if (stty_erase[0] != 0) {
2711      return stty_erase;
2712    }
2713  } else if (strequal(name, "key_dc")) {
2714    DLOG("libtermkey:kdch1=%s", value);
2715    // Vim: "If <BS> and <DEL> are now the same, redefine <DEL>."
2716    if (value != NULL && value != (char *)-1 && strequal(stty_erase, value)) {
2717      return stty_erase[0] == DEL ? CTRL_H_STR : DEL_STR;
2718    }
2719  } else if (strequal(name, "key_mouse")) {
2720    DLOG("libtermkey:kmous=%s", value);
2721    // If key_mouse is found, libtermkey uses its terminfo driver (driver-ti.c)
2722    // for mouse input, which by accident only supports X10 protocol.
2723    // Force libtermkey to fallback to its CSI driver (driver-csi.c). #7948
2724    return NULL;
2725  }
2726
2727  return value;
2728}