robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
74.2 KiB2645 linesraw
1// VT220/xterm-like terminal emulator.
2// Powered by libvterm http://www.leonerd.org.uk/code/libvterm
3//
4// libvterm is a pure C99 terminal emulation library with abstract input and
5// display. This means that the library needs to read data from the master fd
6// and feed VTerm instances, which will invoke user callbacks with screen
7// update instructions that must be mirrored to the real display.
8//
9// Keys are sent to VTerm instances by calling
10// vterm_keyboard_key/vterm_keyboard_unichar, which generates byte streams that
11// must be fed back to the master fd.
12//
13// Nvim buffers are used as the display mechanism for both the visible screen
14// and the scrollback buffer.
15//
16// When a line becomes invisible due to a decrease in screen height or because
17// a line was pushed up during normal terminal output, we store the line
18// information in the scrollback buffer, which is mirrored in the nvim buffer
19// by appending lines just above the visible part of the buffer.
20//
21// When the screen height increases, libvterm will ask for a row in the
22// scrollback buffer, which is mirrored in the nvim buffer displaying lines
23// that were previously invisible.
24//
25// The vterm->nvim synchronization is performed in intervals of 10 milliseconds,
26// to minimize screen updates when receiving large bursts of data.
27//
28// This module is decoupled from the processes that normally feed it data, so
29// it's possible to use it as a general purpose console buffer (possibly as a
30// log/display mechanism for nvim in the future)
31//
32// Inspired by: vimshell http://www.wana.at/vimshell
33//              Conque https://code.google.com/p/conque
34// Some code from pangoterm http://www.leonerd.org.uk/code/pangoterm
35
36#include <assert.h>
37#include <limits.h>
38#include <stdbool.h>
39#include <stdint.h>
40#include <stdio.h>
41#include <stdlib.h>
42#include <string.h>
43
44#include "klib/kvec.h"
45#include "nvim/api/private/helpers.h"
46#include "nvim/ascii_defs.h"
47#include "nvim/autocmd.h"
48#include "nvim/autocmd_defs.h"
49#include "nvim/buffer.h"
50#include "nvim/buffer_defs.h"
51#include "nvim/change.h"
52#include "nvim/channel.h"
53#include "nvim/channel_defs.h"
54#include "nvim/context.h"
55#include "nvim/cursor.h"
56#include "nvim/cursor_shape.h"
57#include "nvim/drawline.h"
58#include "nvim/drawscreen.h"
59#include "nvim/eval.h"
60#include "nvim/eval/typval.h"
61#include "nvim/eval/typval_defs.h"
62#include "nvim/eval/vars.h"
63#include "nvim/event/defs.h"
64#include "nvim/event/loop.h"
65#include "nvim/event/multiqueue.h"
66#include "nvim/event/time.h"
67#include "nvim/ex_docmd.h"
68#include "nvim/globals.h"
69#include "nvim/grid.h"
70#include "nvim/highlight.h"
71#include "nvim/highlight_defs.h"
72#include "nvim/highlight_group.h"
73#include "nvim/input.h"
74#include "nvim/input_cmdatom.h"
75#include "nvim/keycodes.h"
76#include "nvim/macros_defs.h"
77#include "nvim/main.h"
78#include "nvim/map_defs.h"
79#include "nvim/mark.h"
80#include "nvim/mbyte.h"
81#include "nvim/memline.h"
82#include "nvim/memory.h"
83#include "nvim/mouse.h"
84#include "nvim/move.h"
85#include "nvim/msgpack_rpc/channel_defs.h"
86#include "nvim/normal_defs.h"
87#include "nvim/ops.h"
88#include "nvim/option.h"
89#include "nvim/option_defs.h"
90#include "nvim/option_vars.h"
91#include "nvim/optionstr.h"
92#include "nvim/pos_defs.h"
93#include "nvim/state.h"
94#include "nvim/state_defs.h"
95#include "nvim/strings.h"
96#include "nvim/terminal.h"
97#include "nvim/types_defs.h"
98#include "nvim/ui.h"
99#include "nvim/vim_defs.h"
100#include "nvim/vterm/keyboard.h"
101#include "nvim/vterm/mouse.h"
102#include "nvim/vterm/parser.h"
103#include "nvim/vterm/pen.h"
104#include "nvim/vterm/screen.h"
105#include "nvim/vterm/state.h"
106#include "nvim/vterm/vterm.h"
107#include "nvim/vterm/vterm_keycodes_defs.h"
108#include "nvim/window.h"
109
110typedef struct {
111  VimState state;
112  Terminal *term;
113  int save_rd;          ///< saved value of RedrawingDisabled
114  bool close;
115  bool got_bsl;         ///< if the last input was <C-\>
116  bool got_bsl_o;       ///< if left terminal mode with <c-\><c-o>
117  bool cursor_visible;  ///< cursor's current visibility; ensures matched busy_start/stop UI events
118
119  // These fields remember the prior values of window options before entering terminal mode.
120  // Valid only when save_curwin_handle != 0.
121  handle_T save_curwin_handle;
122  bool save_w_p_cul;
123  char *save_w_p_culopt;
124  uint8_t save_w_p_culopt_flags;
125  int save_w_p_cuc;
126  OptInt save_w_p_so;
127  OptInt save_w_p_siso;
128} TerminalState;
129
130#include "terminal.c.generated.h"
131
132// Delay for refreshing the terminal buffer after receiving updates from
133// libvterm. Improves performance when receiving large bursts of data.
134#define REFRESH_DELAY 10
135
136#define TEXTBUF_SIZE      0x1fff
137#define SELECTIONBUF_SIZE 0x0400
138
139static TimeWatcher refresh_timer;
140static bool refresh_pending = false;
141
142typedef struct {
143  size_t cols;
144  VTermScreenCell cells[];
145} ScrollbackLine;
146
147struct terminal {
148  TerminalOptions opts;  // options passed to terminal_alloc()
149  VTerm *vt;
150  VTermScreen *vts;
151  // buffer used to:
152  //  - convert VTermScreen cell arrays into utf8 strings
153  //  - receive data from libvterm as a result of key presses.
154  char textbuf[TEXTBUF_SIZE];
155
156  ScrollbackLine **sb_buffer;  ///< Scrollback storage.
157  size_t sb_current;           ///< Lines stored in sb_buffer.
158  size_t sb_size;              ///< Capacity of sb_buffer.
159  /// "virtual index" that points to the first sb_buffer row that we need to
160  /// push to the terminal buffer when refreshing the scrollback.
161  int sb_pending;
162  size_t sb_deleted;      ///< Lines deleted from sb_buffer.
163  size_t old_sb_deleted;  ///< Value of sb_deleted on last refresh_scrollback().
164  /// Lines in the terminal buffer belonging to the screen instead of the scrollback.
165  int old_height;
166
167  char *title;     // VTermStringFragment buffer
168  size_t title_len;
169  size_t title_size;
170
171  // buf_T instance that acts as a "drawing surface" for libvterm
172  // we can't store a direct reference to the buffer because the
173  // refresh_timer_cb may be called after the buffer was freed, and there's
174  // no way to know if the memory was reused.
175  handle_T buf_handle;
176  bool in_altscreen;
177  // program suspended
178  bool suspended;
179  // program exited
180  bool closed;
181  // when true, the terminal's destruction is already enqueued.
182  bool destroy;
183
184  // some vterm properties
185  bool forward_mouse;
186  int invalid_start, invalid_end;   // invalid rows in libvterm screen
187  struct {
188    int row, col;
189    int shape;
190    bool visible;  ///< Terminal wants to show cursor.
191                   ///< `TerminalState.cursor_visible` indicates whether it is actually shown.
192    bool blink;
193  } cursor;
194
195  struct {
196    bool resize;          ///< pending width/height
197    bool cursor;          ///< pending cursor shape or blink change
198    StringBuilder *send;  ///< When there is a pending TermRequest autocommand, block and store input.
199    MultiQueue *events;   ///< Events waiting for refresh.
200  } pending;
201
202  bool streamed_paste;  ///< Streamed pasting
203  bool theme_updates;  ///< Send a theme update notification when 'bg' changes
204  bool synchronized_output;  ///< Mode 2026: suppress redraws until end of synchronized update
205  bool sync_flush_pending;   ///< Set when mode 2026 ends; triggers immediate buffer refresh
206
207  bool color_set[16];
208
209  char *selection_buffer;  ///< libvterm selection buffer
210  StringBuilder selection;  ///< Growable array containing full selection data
211
212  StringBuilder termrequest_buffer;  ///< Growable array containing unfinished request sequence
213  VTermTerminator termrequest_terminator;  ///< Terminator (BEL or ST) used in the termrequest
214
215  size_t refcount;                  // reference count
216};
217
218static VTermScreenCallbacks vterm_screen_callbacks = {
219  .damage = term_damage,
220  .moverect = term_moverect,
221  .movecursor = term_movecursor,
222  .settermprop = term_settermprop,
223  .bell = term_bell,
224  .theme = term_theme,
225  .sb_pushline = term_sb_push,  // Called before a line goes offscreen.
226  .sb_popline = term_sb_pop,
227  .sb_clear = term_sb_clear,
228};
229
230static VTermSelectionCallbacks vterm_selection_callbacks = {
231  .set = term_selection_set,
232  // For security reasons we don't support querying the system clipboard from the embedded terminal
233  .query = NULL,
234};
235
236static Set(ptr_t) invalidated_terminals = SET_INIT;
237
238static void emit_termrequest(void **argv)
239{
240  handle_T buf_handle = (handle_T)(intptr_t)argv[0];
241  char *sequence = argv[1];
242  size_t sequence_length = (size_t)argv[2];
243  StringBuilder *pending_send = argv[3];
244  int row = (int)(intptr_t)argv[4];
245  int col = (int)(intptr_t)argv[5];
246  size_t sb_deleted = (size_t)(intptr_t)argv[6];
247  VTermTerminator terminator = (VTermTerminator)(intptr_t)argv[7];
248
249  buf_T *buf = handle_get_buffer(buf_handle);
250  if (!buf || buf->terminal == NULL) {  // Terminal already closed.
251    xfree(sequence);
252    kv_destroy(*pending_send);
253    xfree(pending_send);
254    return;
255  }
256  Terminal *term = buf->terminal;
257
258  if (term->sb_pending > 0) {
259    // Don't emit the event while there is pending scrollback because we need
260    // the buffer contents to be fully updated. If this is the case, schedule
261    // the event onto the pending queue where it will be executed after the
262    // terminal is refreshed and the pending scrollback is cleared.
263    multiqueue_put(term->pending.events, emit_termrequest, argv[0], argv[1], argv[2],
264                   argv[3], argv[4], argv[5], argv[6], argv[7]);
265    return;
266  }
267
268  set_vim_var_string(VV_TERMREQUEST, sequence, (ptrdiff_t)sequence_length);
269
270  MAXSIZE_TEMP_ARRAY(cursor, 2);
271  ADD_C(cursor, INTEGER_OBJ(row - (int64_t)(term->sb_deleted - sb_deleted)));
272  ADD_C(cursor, INTEGER_OBJ(col));
273
274  MAXSIZE_TEMP_DICT(data, 3);
275  String termrequest = { .data = sequence, .size = sequence_length };
276  PUT_C(data, "sequence", STRING_OBJ(termrequest));
277  PUT_C(data, "cursor", ARRAY_OBJ(cursor));
278  PUT_C(data, "terminator",
279        terminator ==
280        VTERM_TERMINATOR_BEL ? STATIC_CSTR_AS_OBJ("\x07") : STATIC_CSTR_AS_OBJ("\x1b\\"));
281
282  term->refcount++;
283  apply_autocmds_group(EVENT_TERMREQUEST, NULL, NULL, true, AUGROUP_ALL, buf, curwin, NULL,
284                       &DICT_OBJ(data), false);
285  term->refcount--;
286  xfree(sequence);
287
288  StringBuilder *term_pending_send = term->pending.send;
289  term->pending.send = NULL;
290  if (kv_size(*pending_send)) {
291    terminal_send(term, pending_send->items, pending_send->size);
292    kv_destroy(*pending_send);
293  }
294  if (term_pending_send != pending_send) {
295    term->pending.send = term_pending_send;
296  }
297  xfree(pending_send);
298
299  // Terminal buffer closed during TermRequest in Normal mode: destroy the terminal.
300  // In Terminal mode term->refcount should still be non-zero here.
301  if (term->buf_handle == 0 && !term->refcount) {
302    term->destroy = true;
303    term->opts.close_cb(term->opts.data);
304  }
305}
306
307static void schedule_termrequest(Terminal *term)
308{
309  term->pending.send = xmalloc(sizeof(StringBuilder));
310  kv_init(*term->pending.send);
311
312  int line = row_to_linenr(term, term->cursor.row);
313  multiqueue_put(main_loop.events, emit_termrequest, (void *)(intptr_t)term->buf_handle,
314                 xmemdup(term->termrequest_buffer.items, term->termrequest_buffer.size),
315                 (void *)(intptr_t)term->termrequest_buffer.size, term->pending.send,
316                 (void *)(intptr_t)line, (void *)(intptr_t)term->cursor.col,
317                 (void *)(intptr_t)term->sb_deleted,
318                 (void *)(intptr_t)term->termrequest_terminator);
319}
320
321static int parse_osc8(const char *str, int *attr)
322  FUNC_ATTR_NONNULL_ALL
323{
324  // Parse the URI from the OSC 8 sequence and add the URL to our URL set.
325  // Skip the ID, we don't use it (for now)
326  size_t i = 0;
327  for (; str[i] != NUL; i++) {
328    if (str[i] == ';') {
329      break;
330    }
331  }
332
333  if (str[i] != ';') {
334    // Invalid OSC sequence
335    return 0;
336  }
337
338  // Move past the semicolon
339  i++;
340
341  if (str[i] == NUL) {
342    // Empty OSC 8, no URL
343    *attr = 0;
344    return 1;
345  }
346
347  *attr = hl_add_url(0, str + i);
348  return 1;
349}
350
351static int on_osc(int command, VTermStringFragment frag, void *user)
352  FUNC_ATTR_NONNULL_ALL
353{
354  Terminal *term = user;
355
356  if (frag.str == NULL || frag.len == 0) {
357    return 0;
358  }
359
360  if (command != 8 && !has_event(EVENT_TERMREQUEST)) {
361    return 1;
362  }
363
364  if (frag.initial) {
365    kv_size(term->termrequest_buffer) = 0;
366    kv_printf(term->termrequest_buffer, "\x1b]%d;", command);
367  }
368  kv_concat_len(term->termrequest_buffer, frag.str, frag.len);
369  if (frag.final) {
370    term->termrequest_terminator = frag.terminator;
371    if (has_event(EVENT_TERMREQUEST)) {
372      schedule_termrequest(term);
373    }
374    if (command == 8) {
375      kv_push(term->termrequest_buffer, NUL);
376      const size_t off = STRLEN_LITERAL("\x1b]8;");
377      int attr = 0;
378      if (parse_osc8(term->termrequest_buffer.items + off, &attr)) {
379        VTermState *state = vterm_obtain_state(term->vt);
380        VTermValue value = { .number = attr };
381        vterm_state_set_penattr(state, VTERM_ATTR_URI, VTERM_VALUETYPE_INT, &value);
382      }
383    }
384  }
385  return 1;
386}
387
388static int on_dcs(const char *command, size_t commandlen, VTermStringFragment frag, void *user)
389{
390  Terminal *term = user;
391
392  if (command == NULL || frag.str == NULL) {
393    return 0;
394  }
395  if (!has_event(EVENT_TERMREQUEST)) {
396    return 1;
397  }
398
399  if (frag.initial) {
400    kv_size(term->termrequest_buffer) = 0;
401    kv_printf(term->termrequest_buffer, "\x1bP%.*s", (int)commandlen, command);
402  }
403  kv_concat_len(term->termrequest_buffer, frag.str, frag.len);
404  if (frag.final) {
405    term->termrequest_terminator = frag.terminator;
406    schedule_termrequest(term);
407  }
408  return 1;
409}
410
411static int on_apc(VTermStringFragment frag, void *user)
412{
413  Terminal *term = user;
414  if (frag.str == NULL || frag.len == 0) {
415    return 0;
416  }
417
418  if (!has_event(EVENT_TERMREQUEST)) {
419    return 1;
420  }
421
422  if (frag.initial) {
423    kv_size(term->termrequest_buffer) = 0;
424    kv_printf(term->termrequest_buffer, "\x1b_");
425  }
426  kv_concat_len(term->termrequest_buffer, frag.str, frag.len);
427  if (frag.final) {
428    term->termrequest_terminator = frag.terminator;
429    schedule_termrequest(term);
430  }
431  return 1;
432}
433
434static VTermStateFallbacks vterm_fallbacks = {
435  .control = NULL,
436  .csi = NULL,
437  .osc = on_osc,
438  .dcs = on_dcs,
439  .apc = on_apc,
440  .pm = NULL,
441  .sos = NULL,
442};
443
444void terminal_init(void)
445{
446  time_watcher_init(&main_loop, &refresh_timer, NULL);
447  // refresh_timer_cb will redraw the screen which can call vimscript
448  refresh_timer.events = multiqueue_new_child(main_loop.events);
449}
450
451void terminal_teardown(void)
452{
453  time_watcher_stop(&refresh_timer);
454  multiqueue_free(refresh_timer.events);
455  time_watcher_close(&refresh_timer, NULL);
456  set_destroy(ptr_t, &invalidated_terminals);
457  // terminal_destroy might be called after terminal_teardown is invoked
458  // make sure it is in an empty, valid state
459  invalidated_terminals = (Set(ptr_t)) SET_INIT;
460}
461
462static void term_output_callback(const char *s, size_t len, void *user_data)
463{
464  terminal_send((Terminal *)user_data, s, len);
465}
466
467/// Allocates a terminal's scrollback buffer if it hasn't been allocated yet.
468/// Does nothing if it's already allocated, unlike adjust_scrollback().
469///
470/// @param term Terminal instance.
471/// @param buf  The terminal's buffer, or NULL to get it from buf_handle.
472///
473/// @return whether the terminal now has a scrollback buffer.
474static bool term_may_alloc_scrollback(Terminal *term, buf_T *buf)
475{
476  if (term->sb_buffer != NULL) {
477    return true;
478  }
479  if (buf == NULL) {
480    buf = handle_get_buffer(term->buf_handle);
481    if (buf == NULL) {  // No need to allocate scrollback if buffer is deleted.
482      return false;
483    }
484  }
485
486  if (buf->b_p_scbk < 1) {
487    buf->b_p_scbk = SB_MAX;
488  }
489  // Configure the scrollback buffer.
490  term->sb_size = (size_t)buf->b_p_scbk;
491  term->sb_buffer = xmalloc(sizeof(ScrollbackLine *) * term->sb_size);
492  return true;
493}
494
495// public API {{{
496
497/// Allocates a terminal instance and initializes terminal properties.
498///
499/// The PTY process (TerminalOptions.data) was already started by jobstart(),
500/// via ex_terminal() or the term:// BufReadCmd.
501///
502/// @param buf Buffer used for presentation of the terminal.
503/// @param opts PTY process channel, various terminal properties and callbacks.
504///
505/// @return the terminal instance.
506Terminal *terminal_alloc(buf_T *buf, TerminalOptions opts)
507  FUNC_ATTR_NONNULL_ALL
508{
509  // Create a new terminal instance and configure it
510  Terminal *term = xcalloc(1, sizeof(Terminal));
511  term->opts = opts;
512
513  // Associate the terminal instance with the new buffer
514  term->buf_handle = buf->handle;
515  buf->terminal = term;
516  // Create VTerm
517  term->vt = vterm_new(opts.height, opts.width);
518  vterm_set_utf8(term->vt, 1);
519  // Setup state
520  VTermState *state = vterm_obtain_state(term->vt);
521  // Set up screen
522  term->vts = vterm_obtain_screen(term->vt);
523  vterm_screen_enable_altscreen(term->vts, true);
524  vterm_screen_enable_reflow(term->vts, true);
525  // delete empty lines at the end of the buffer
526  vterm_screen_set_callbacks(term->vts, &vterm_screen_callbacks, term);
527  vterm_screen_set_unrecognised_fallbacks(term->vts, &vterm_fallbacks, term);
528  vterm_screen_set_damage_merge(term->vts, VTERM_DAMAGE_SCROLL);
529  vterm_screen_reset(term->vts, 1);
530  vterm_output_set_callback(term->vt, term_output_callback, term);
531
532  term->selection_buffer = xcalloc(SELECTIONBUF_SIZE, 1);
533  vterm_state_set_selection_callbacks(state, &vterm_selection_callbacks, term,
534                                      term->selection_buffer, SELECTIONBUF_SIZE);
535
536  VTermValue cursor_shape;
537  switch (shape_table[SHAPE_IDX_TERM].shape) {
538  case SHAPE_BLOCK:
539    cursor_shape.number = VTERM_PROP_CURSORSHAPE_BLOCK;
540    break;
541  case SHAPE_HOR:
542    cursor_shape.number = VTERM_PROP_CURSORSHAPE_UNDERLINE;
543    break;
544  case SHAPE_VER:
545    cursor_shape.number = VTERM_PROP_CURSORSHAPE_BAR_LEFT;
546    break;
547  }
548  vterm_state_set_termprop(state, VTERM_PROP_CURSORSHAPE, &cursor_shape);
549
550  VTermValue cursor_blink;
551  if (shape_table[SHAPE_IDX_TERM].blinkon != 0 && shape_table[SHAPE_IDX_TERM].blinkoff != 0) {
552    cursor_blink.boolean = true;
553  } else {
554    cursor_blink.boolean = false;
555  }
556  vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &cursor_blink);
557
558  // Force a initial refresh of the screen to ensure the buffer will always
559  // have as many lines as screen rows when refresh_scrollback() is called.
560  term->invalid_start = 0;
561  term->invalid_end = opts.height;
562
563  // Create a separate queue for events which need to wait for a terminal
564  // refresh. We cannot reschedule events back onto the main queue because this
565  // can create an infinite loop (#32753).
566  // This queue is never processed directly: when the terminal is refreshed, all
567  // events from this queue are copied back onto the main event queue.
568  term->pending.events = multiqueue_new(NULL, NULL);
569
570  if (!(buf->b_ml.ml_flags & ML_EMPTY)) {
571    linenr_T line_count = buf->b_ml.ml_line_count;
572    while (!(buf->b_ml.ml_flags & ML_EMPTY)) {
573      ml_delete_buf(buf, 1, false);
574    }
575    deleted_lines_buf(buf, 1, line_count);
576  }
577  term->old_height = 1;
578
579  return term;
580}
581
582/// Triggers TermOpen and allocates terminal scrollback buffer.
583///
584/// @param termpp  Pointer to the terminal channel's `term` field.
585/// @param buf     Buffer used for presentation of the terminal.
586void terminal_open(Terminal **termpp, buf_T *buf)
587  FUNC_ATTR_NONNULL_ALL
588{
589  Terminal *term = *termpp;
590  assert(term != NULL);
591
592  CtxSwitch aco = { 0 };
593  ctx_switch(&aco, NULL, NULL, buf, 0);
594
595  if (term->sb_buffer != NULL) {
596    // If scrollback has been allocated by autocommands between terminal_alloc()
597    // and terminal_open(), it also needs to be refreshed.
598    refresh_scrollback(term, buf);
599  } else {
600    assert(term->invalid_start >= 0);
601  }
602  refresh_screen(term, buf);
603  buf->b_locked++;
604  set_option_value(kOptBuftype, STATIC_CSTR_AS_OBJ("terminal"), OPT_LOCAL, true, NULL);
605  buf->b_locked--;
606
607  if (buf->b_ffname != NULL) {
608    buf_set_term_title(buf, buf->b_ffname, strlen(buf->b_ffname));
609  }
610  RESET_BINDING(curwin);
611  // Reset cursor in current window.
612  curwin->w_cursor = (pos_T){ .lnum = 1, .col = 0, .coladd = 0 };
613
614  // Apply TermOpen autocmds _before_ configuring the scrollback buffer, to avoid
615  // over-allocating in case TermOpen reduces 'scrollback'.
616  // In the rare case where TermOpen polls for events, the scrollback buffer will be
617  // allocated anyway if needed.
618  apply_autocmds(EVENT_TERMOPEN, NULL, NULL, false, buf);
619
620  ctx_restore(&aco);
621
622  if (*termpp == NULL || term->buf_handle == 0) {
623    return;  // Terminal has already been destroyed.
624  }
625
626  // Local 'scrollback' _after_ autocmds.
627  if (!term_may_alloc_scrollback(term, buf)) {
628    abort();
629  }
630
631  VTermState *state = vterm_obtain_state(term->vt);
632  // Configure the color palette. Try to get the color from:
633  //
634  // - b:terminal_color_{NUM}
635  // - g:terminal_color_{NUM}
636  // - the VTerm instance
637  for (int i = 0; i < 16; i++) {
638    char var[64];
639    snprintf(var, sizeof(var), "terminal_color_%d", i);
640    char *name = get_config_string(buf, var);
641    if (name) {
642      int dummy;
643      RgbValue color_val = name_to_color(name, &dummy);
644
645      if (color_val != -1) {
646        VTermColor color;
647        vterm_color_rgb(&color,
648                        (uint8_t)((color_val >> 16) & 0xFF),
649                        (uint8_t)((color_val >> 8) & 0xFF),
650                        (uint8_t)((color_val >> 0) & 0xFF));
651        vterm_state_set_palette_color(state, i, &color);
652        term->color_set[i] = true;
653      }
654    }
655  }
656}
657
658/// Closes the Terminal buffer.
659///
660/// May call terminal_destroy, which sets caller storage to NULL.
661void terminal_close(Terminal **termpp, int status)
662  FUNC_ATTR_NONNULL_ALL
663{
664  Terminal *term = *termpp;
665
666#ifdef EXITFREE
667  if (entered_free_all_mem) {
668    // If called from buf_close_terminal() inside free_all_mem(), the main loop has
669    // already been freed, so it is not safe to call the close callback here.
670    terminal_destroy(termpp);
671    return;
672  }
673#endif
674
675  if (term->destroy) {  // Destruction already scheduled on the main loop.
676    return;
677  }
678
679  bool only_destroy = false;
680
681  buf_T *buf = handle_get_buffer(term->buf_handle);
682
683  if (term->closed) {
684    // If called from buf_close_terminal() after the process has already exited, we
685    // only need to call the close callback to clean up the terminal object.
686    only_destroy = true;
687  } else {
688    // flush any pending changes to the buffer
689    if (!exiting) {
690      block_autocmds();
691      refresh_terminal(term);
692      unblock_autocmds();
693    }
694    term->closed = true;
695  }
696
697  int pos = buf ? buf->b_ml.ml_line_count - 1 : 0;
698  if (status == -1 || exiting) {
699    // If this was called by buf_close_terminal() (status is -1), or if exiting, we
700    // must inform the buffer the terminal no longer exists so that buf_freeall()
701    // won't call buf_close_terminal() again.
702    // If inside Terminal mode event handling, setting buf_handle to 0 also
703    // informs terminal_enter() to call the close callback before returning.
704    term->buf_handle = 0;
705    if (buf) {
706      buf->terminal = NULL;
707    }
708    if (!term->refcount) {
709      // Not inside Terminal mode event handling.
710      // We should not wait for the user to press a key.
711      term->destroy = true;
712      term->opts.close_cb(term->opts.data);
713    }
714  } else if (!only_destroy) {
715    // Associated channel has been closed and the editor is not exiting.
716    // Do not call the close callback now. Wait for the user to press a key.
717    // Redraw statusline to show the exit code.
718    FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
719      if (wp->w_buffer == buf) {
720        wp->w_redr_status = true;
721      }
722    }
723
724    // Gets the line number to display "[Process exited]" virt text
725    pos = MIN(row_to_linenr(term, term->cursor.row), pos);
726  }
727
728  if (only_destroy) {
729    return;
730  }
731
732  if (status >= 0) {  // The job may have changed files on disk, like `do_shell` (":!cmd").
733    did_check_timestamps = false;
734    need_check_timestamps = true;
735  }
736
737  if (buf && !is_autocmd_blocked()) {
738    save_v_event_T save_v_event;
739    dict_T *dict = get_v_event(&save_v_event);
740    tv_dict_add_nr(dict, S_LEN("status"), status);
741    tv_dict_set_keys_readonly(dict);
742
743    MAXSIZE_TEMP_DICT(data, 1);
744    PUT_C(data, "pos", INTEGER_OBJ(pos));
745
746    apply_autocmds_group(EVENT_TERMCLOSE, NULL, NULL, status >= 0, AUGROUP_ALL,
747                         buf, curwin, NULL, &DICT_OBJ(data), false);
748
749    restore_v_event(dict, &save_v_event);
750  }
751}
752
753static void terminal_state_change_event(void **argv)
754{
755  handle_T buf_handle = (handle_T)(intptr_t)argv[0];
756  buf_T *buf = handle_get_buffer(buf_handle);
757  if (buf && buf->terminal) {
758    // Don't change the actual terminal content to indicate the suspended state here,
759    // as unlike the process exit case the change needs to be reversed on resume.
760    // Instead, the code in win_update() will add a "[Process suspended]" virtual text
761    // at the botton-left of the buffer.
762    redraw_buf_line_later(buf, buf->b_ml.ml_line_count, false);
763  }
764}
765
766/// Updates the suspended state of the terminal program.
767void terminal_set_state(Terminal *term, bool suspended)
768  FUNC_ATTR_NONNULL_ALL
769{
770  if (term->suspended != suspended) {
771    // Trigger a main loop iteration to redraw the buffer.
772    multiqueue_put(refresh_timer.events, terminal_state_change_event,
773                   (void *)(intptr_t)term->buf_handle);
774  }
775  term->suspended = suspended;
776}
777
778void terminal_check_size(Terminal *term)
779  FUNC_ATTR_NONNULL_ALL
780{
781  if (term->closed) {
782    return;
783  }
784
785  int curwidth, curheight;
786  vterm_get_size(term->vt, &curheight, &curwidth);
787  uint16_t width = 0;
788  uint16_t height = 0;
789
790  // Check if there is a window that displays the terminal and find the maximum width and height.
791  // Skip the autocommand window which isn't actually displayed.
792  FOR_ALL_TAB_WINDOWS(tp, wp) {
793    if (is_ctx_win(wp)) {
794      continue;
795    }
796    if (wp->w_buffer && wp->w_buffer->terminal == term) {
797      const uint16_t win_width =
798        (uint16_t)(MAX(0, wp->w_view_width - win_col_off(wp)));
799      width = MAX(width, win_width);
800      height = (uint16_t)MAX(height, wp->w_view_height);
801    }
802  }
803
804  // if no window displays the terminal, or such all windows are zero-height,
805  // don't resize the terminal.
806  if ((curheight == height && curwidth == width) || height == 0 || width == 0) {
807    return;
808  }
809
810  vterm_set_size(term->vt, height, width);
811  vterm_screen_flush_damage(term->vts);
812  term->pending.resize = true;
813  invalidate_terminal(term, -1, -1);
814}
815
816static void set_terminal_winopts(TerminalState *const s)
817  FUNC_ATTR_NONNULL_ALL
818{
819  assert(s->save_curwin_handle == 0);
820
821  // Disable these options in terminal-mode. They are nonsense because cursor is
822  // placed at end of buffer to "follow" output. #11072
823  s->save_curwin_handle = curwin->handle;
824  s->save_w_p_cul = curwin->w_p_cul;
825  s->save_w_p_culopt = NULL;
826  s->save_w_p_culopt_flags = curwin->w_p_culopt_flags;
827  s->save_w_p_cuc = curwin->w_p_cuc;
828  s->save_w_p_so = curwin->w_p_so;
829  s->save_w_p_siso = curwin->w_p_siso;
830
831  if (curwin->w_p_cul && curwin->w_p_culopt_flags & kOptCuloptFlagNumber) {
832    if (!strequal(curwin->w_p_culopt, "number")) {
833      s->save_w_p_culopt = curwin->w_p_culopt;
834      curwin->w_p_culopt = xstrdup("number");
835    }
836    curwin->w_p_culopt_flags = kOptCuloptFlagNumber;
837  } else {
838    curwin->w_p_cul = false;
839  }
840  curwin->w_p_cuc = false;
841  curwin->w_p_so = 0;
842  curwin->w_p_siso = 0;
843
844  if (curwin->w_p_cuc != s->save_w_p_cuc) {
845    redraw_later(curwin, UPD_SOME_VALID);
846  } else if (curwin->w_p_cul != s->save_w_p_cul
847             || (curwin->w_p_cul && curwin->w_p_culopt_flags != s->save_w_p_culopt_flags)) {
848    redraw_later(curwin, UPD_VALID);
849  }
850}
851
852static void unset_terminal_winopts(TerminalState *const s)
853  FUNC_ATTR_NONNULL_ALL
854{
855  assert(s->save_curwin_handle != 0);
856
857  win_T *const wp = handle_get_window(s->save_curwin_handle);
858  if (!wp) {
859    goto end;
860  }
861
862  winopt_T *winopts = NULL;
863  if (wp->w_buffer->handle != s->term->buf_handle) {  // Buffer no longer in "wp".
864    buf_T *buf = handle_get_buffer(s->term->buf_handle);
865    if (buf == NULL) {
866      goto end;  // Nothing to restore as the buffer was deleted.
867    }
868    for (size_t i = 0; i < kv_size(buf->b_wininfo); i++) {
869      WinInfo *wip = kv_A(buf->b_wininfo, i);
870      if (wip->wi_win == wp && wip->wi_optset) {
871        winopts = &wip->wi_opt;
872        break;
873      }
874    }
875    if (winopts == NULL) {
876      goto end;  // Nothing to restore as there is no matching WinInfo.
877    }
878  } else {
879    winopts = &wp->w_onebuf_opt;
880    if (win_valid(wp)) {  // No need to redraw if window not in curtab.
881      if (s->save_w_p_cuc != wp->w_p_cuc) {
882        redraw_later(wp, UPD_SOME_VALID);
883      } else if (s->save_w_p_cul != wp->w_p_cul
884                 || (s->save_w_p_cul && s->save_w_p_culopt_flags != wp->w_p_culopt_flags)) {
885        redraw_later(wp, UPD_VALID);
886      }
887    }
888    wp->w_p_culopt_flags = s->save_w_p_culopt_flags;
889  }
890
891  if (s->save_w_p_culopt) {
892    free_string_option(winopts->wo_culopt);
893    winopts->wo_culopt = s->save_w_p_culopt;
894    s->save_w_p_culopt = NULL;
895  }
896  winopts->wo_cul = s->save_w_p_cul;
897  winopts->wo_cuc = s->save_w_p_cuc;
898  winopts->wo_so = s->save_w_p_so;
899  winopts->wo_siso = s->save_w_p_siso;
900
901end:
902  free_string_option(s->save_w_p_culopt);
903  s->save_curwin_handle = 0;
904}
905
906/// Implements MODE_TERMINAL state. :help Terminal-mode
907bool terminal_enter(void)
908{
909  buf_T *buf = curbuf;
910  assert(buf->terminal);  // Should only be called when curbuf has a terminal.
911  TerminalState s[1] = { 0 };
912  s->term = buf->terminal;
913  s->cursor_visible = true;  // Assume visible; may change via refresh_cursor later.
914  Ins.stop_insert_mode = false;
915
916  // Ensure the terminal is properly sized. Ideally window size management
917  // code should always have resized the terminal already, but check here to
918  // be sure.
919  terminal_check_size(s->term);
920
921  atom_term_enter();
922  int save_state = State;
923  s->save_rd = RedrawingDisabled;
924  State = MODE_TERMINAL;
925  mapped_ctrl_c |= MODE_TERMINAL;  // Always map CTRL-C to avoid interrupt.
926  RedrawingDisabled = false;
927
928  set_terminal_winopts(s);
929
930  s->term->pending.cursor = true;  // Update the cursor shape table
931  adjust_topline_cursor(s->term, buf, 0);  // scroll to end
932  showmode();
933  ui_cursor_shape();
934
935  // Tell the terminal it has focus
936  terminal_focus(s->term, true);
937  // Don't fire TextChangedT from changes in Normal mode.
938  curbuf->b_last_changedtick_i = buf_get_changedtick(curbuf);
939
940  // Don't let autocommands free the terminal now!
941  s->term->refcount++;
942  apply_autocmds(EVENT_TERMENTER, NULL, NULL, false, curbuf);
943  may_trigger_modechanged();
944  s->term->refcount--;
945  if (s->term->buf_handle == 0) {
946    s->close = true;
947  }
948
949  s->state.execute = terminal_execute;
950  s->state.check = terminal_check;
951  state_enter(&s->state);
952
953  if (!s->got_bsl_o) {
954    restart_edit = 0;
955  }
956  State = save_state;
957  RedrawingDisabled = s->save_rd;
958  if (!s->cursor_visible) {
959    // If cursor was hidden, show it again. Do so right after restoring State.
960    ui_busy_stop();
961  }
962
963  // Restore the terminal cursor to what is set in 'guicursor'
964  (void)parse_shape_opt(SHAPE_CURSOR);
965
966  unset_terminal_winopts(s);
967
968  // Tell the terminal it lost focus
969  terminal_focus(s->term, false);
970  // Don't fire TextChanged from changes in terminal mode.
971  curbuf->b_last_changedtick = buf_get_changedtick(curbuf);
972
973  if (curbuf->terminal == s->term && !s->close) {
974    terminal_check_cursor();
975  }
976  if (restart_edit) {
977    showmode();
978  } else {
979    unshowmode(true);
980  }
981  ui_cursor_shape();
982
983  // If we're to close the terminal, don't let TermLeave autocommands free it first!
984  if (s->close) {
985    s->term->refcount++;
986  }
987  apply_autocmds(EVENT_TERMLEAVE, NULL, NULL, false, curbuf);
988  if (s->close) {
989    s->term->refcount--;
990    const handle_T buf_handle = s->term->buf_handle;  // Callback may free s->term.
991    s->term->destroy = true;
992    s->term->opts.close_cb(s->term->opts.data);
993    if (buf_handle != 0) {
994      do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf_handle, true);
995    }
996  }
997
998  return s->got_bsl_o;
999}
1000
1001static void terminal_check_cursor(void)
1002{
1003  Terminal *term = curbuf->terminal;
1004  curwin->w_cursor.lnum = MIN(curbuf->b_ml.ml_line_count,
1005                              row_to_linenr(term, term->cursor.row));
1006  const linenr_T topline = MAX(curbuf->b_ml.ml_line_count - curwin->w_view_height + 1, 1);
1007  // Don't update topline if unchanged to avoid unnecessary redraws.
1008  if (topline != curwin->w_topline) {
1009    set_topline(curwin, topline);
1010  }
1011  if (term->suspended && (State & MODE_TERMINAL)) {
1012    // Put cursor at the "[Process suspended]" text to hint that pressing a key will
1013    // change the suspended state.
1014    curwin->w_cursor = (pos_T){ .lnum = curbuf->b_ml.ml_line_count };
1015  } else {
1016    // Nudge cursor when returning to normal-mode.
1017    int off = (State & MODE_TERMINAL) ? 0 : (curwin->w_p_rl ? 1 : -1);
1018    coladvance(curwin, MAX(0, term->cursor.col + off));
1019  }
1020}
1021
1022static bool terminal_check_focus(TerminalState *const s)
1023  FUNC_ATTR_NONNULL_ALL
1024{
1025  if (curbuf->terminal == NULL) {
1026    return false;
1027  }
1028
1029  if (s->save_curwin_handle != curwin->handle) {
1030    // Terminal window changed, update window options.
1031    unset_terminal_winopts(s);
1032    set_terminal_winopts(s);
1033  }
1034  if (s->term != curbuf->terminal) {
1035    // Active terminal changed, flush terminal's cursor state to the UI.
1036    terminal_focus(s->term, false);
1037    if (s->close) {
1038      s->term->destroy = true;
1039      s->term->opts.close_cb(s->term->opts.data);
1040      s->close = false;
1041    }
1042
1043    s->term = curbuf->terminal;
1044    s->term->pending.cursor = true;
1045    invalidate_terminal(s->term, -1, -1);
1046    terminal_focus(s->term, true);
1047  }
1048  return true;
1049}
1050
1051/// Function executed before each iteration of terminal mode.
1052///
1053/// @return:
1054///           1 if the iteration should continue normally
1055///           0 if the main loop must exit
1056static int terminal_check(VimState *state)
1057{
1058  TerminalState *const s = (TerminalState *)state;
1059
1060  // Shouldn't reach here when pressing a key to close the terminal buffer.
1061  assert(!s->close || (s->term->buf_handle == 0 && s->term != curbuf->terminal));
1062
1063  if (Ins.stop_insert_mode || !terminal_check_focus(s)) {
1064    return 0;
1065  }
1066
1067  terminal_check_refresh();
1068
1069  // Validate topline and cursor position for autocommands. Especially important for WinScrolled.
1070  terminal_check_cursor();
1071  validate_cursor(curwin);
1072
1073  // Don't let autocommands free the terminal from under our fingers.
1074  s->term->refcount++;
1075  if (has_event(EVENT_TEXTCHANGEDT)
1076      && curbuf->b_last_changedtick_i != buf_get_changedtick(curbuf)) {
1077    apply_autocmds(EVENT_TEXTCHANGEDT, NULL, NULL, false, curbuf);
1078    curbuf->b_last_changedtick_i = buf_get_changedtick(curbuf);
1079  }
1080  may_trigger_win_scrolled_resized();
1081  s->term->refcount--;
1082  if (s->term->buf_handle == 0) {
1083    s->close = true;
1084  }
1085
1086  // Autocommands above may have changed focus, scrolled, or moved the cursor.
1087  if (!terminal_check_focus(s)) {
1088    return 0;
1089  }
1090  terminal_check_cursor();
1091  validate_cursor(curwin);
1092
1093  show_cursor_info_later(false);
1094  if (must_redraw) {
1095    update_screen();
1096  } else {
1097    redraw_statuslines();
1098    if (clear_cmdline || redraw_cmdline || redraw_mode) {
1099      showmode();  // clear cmdline and show mode
1100    }
1101  }
1102
1103  setcursor();
1104  refresh_cursor(s->term, &s->cursor_visible);
1105  ui_flush();
1106  return 1;
1107}
1108
1109/// Processes one char of terminal-mode input.
1110static int terminal_execute(VimState *state, int key)
1111{
1112  TerminalState *s = (TerminalState *)state;
1113
1114  // Check for certain control keys like Ctrl-C and Ctrl-\. We still send the
1115  // unmerged key and modifiers to the terminal.
1116  int tmp_mod_mask = mod_mask;
1117  int mod_key = merge_modifiers(key, &tmp_mod_mask);
1118
1119  switch (mod_key) {
1120  case K_LEFTMOUSE:
1121  case K_LEFTDRAG:
1122  case K_LEFTRELEASE:
1123  case K_MIDDLEMOUSE:
1124  case K_MIDDLEDRAG:
1125  case K_MIDDLERELEASE:
1126  case K_RIGHTMOUSE:
1127  case K_RIGHTDRAG:
1128  case K_RIGHTRELEASE:
1129  case K_X1MOUSE:
1130  case K_X1DRAG:
1131  case K_X1RELEASE:
1132  case K_X2MOUSE:
1133  case K_X2DRAG:
1134  case K_X2RELEASE:
1135  case K_MOUSEDOWN:
1136  case K_MOUSEUP:
1137  case K_MOUSELEFT:
1138  case K_MOUSERIGHT:
1139  case K_MOUSEMOVE:
1140    if (send_mouse_event(s->term, key)) {
1141      return 0;
1142    }
1143    break;
1144
1145  case K_PASTE_START:
1146    paste_repeat(1);
1147    break;
1148
1149  case K_EVENT:
1150    // We cannot let an event free the terminal yet. It is still needed.
1151    s->term->refcount++;
1152    state_handle_k_event();
1153    s->term->refcount--;
1154    if (s->term->buf_handle == 0) {
1155      s->close = true;
1156    }
1157    break;
1158
1159  case K_COMMAND:
1160    do_cmdline(NULL, getcmdkeycmd, NULL, 0);
1161    break;
1162
1163  case K_LUA:
1164    map_execute_lua(false, false);
1165    break;
1166
1167  case K_IGNORE:
1168  case K_NOP:
1169    // Do not interrupt a Ctrl-\ sequence or close a finished terminal.
1170    break;
1171
1172  case Ctrl_N:
1173    if (s->got_bsl) {
1174      return 0;
1175    }
1176    FALLTHROUGH;
1177
1178  case Ctrl_O:
1179    if (s->got_bsl) {
1180      s->got_bsl_o = true;
1181      restart_edit = 'I';
1182      return 0;
1183    }
1184    FALLTHROUGH;
1185
1186  default:
1187    if (mod_key == Ctrl_C) {
1188      // terminal_enter() always sets `mapped_ctrl_c` to avoid `got_int`. 8eeda7169aa4
1189      // But `got_int` may be set elsewhere, e.g. by interrupt() or an autocommand,
1190      // so ensure that it is cleared.
1191      got_int = false;
1192    }
1193    if (mod_key == Ctrl_BSL && !s->got_bsl) {
1194      s->got_bsl = true;
1195      break;
1196    }
1197    if (s->term->suspended) {
1198      s->term->opts.resume_cb(s->term->opts.data);
1199      // XXX: detecting continued process via waitpid() on SIGCHLD doesn't always work
1200      // (e.g. on macOS), so also consider it continued after sending SIGCONT.
1201      terminal_set_state(s->term, false);
1202      break;
1203    }
1204    if (s->term->closed) {
1205      s->close = true;
1206      return 0;
1207    }
1208
1209    s->got_bsl = false;
1210    terminal_send_key(s->term, key);
1211  }
1212
1213  return 1;
1214}
1215
1216/// Frees the given Terminal structure and sets the caller storage to NULL (in the spirit of
1217/// XFREE_CLEAR).
1218void terminal_destroy(Terminal **termpp)
1219  FUNC_ATTR_NONNULL_ALL
1220{
1221  Terminal *term = *termpp;
1222  buf_T *buf = handle_get_buffer(term->buf_handle);
1223  if (buf) {
1224    term->buf_handle = 0;
1225    buf->terminal = NULL;
1226  }
1227
1228  if (!term->refcount) {
1229    if (set_has(ptr_t, &invalidated_terminals, term)) {
1230      // flush any pending changes to the buffer
1231      block_autocmds();
1232      refresh_terminal(term);
1233      unblock_autocmds();
1234      set_del(ptr_t, &invalidated_terminals, term);
1235    }
1236    for (size_t i = 0; i < term->sb_current; i++) {
1237      xfree(term->sb_buffer[i]);
1238    }
1239    xfree(term->sb_buffer);
1240    xfree(term->title);
1241    xfree(term->selection_buffer);
1242    kv_destroy(term->selection);
1243    kv_destroy(term->termrequest_buffer);
1244    vterm_free(term->vt);
1245    multiqueue_free(term->pending.events);
1246    xfree(term);
1247    *termpp = NULL;  // coverity[dead-store]
1248  }
1249}
1250
1251static void terminal_send(Terminal *term, const char *data, size_t size)
1252{
1253  if (term->closed) {
1254    return;
1255  }
1256  if (term->pending.send) {
1257    kv_concat_len(*term->pending.send, data, size);
1258    return;
1259  }
1260  term->opts.write_cb(data, size, term->opts.data);
1261}
1262
1263static bool is_filter_char(int c)
1264{
1265  unsigned flag = 0;
1266  switch (c) {
1267  case 0x08:
1268    flag = kOptTpfFlagBS;
1269    break;
1270  case 0x09:
1271    flag = kOptTpfFlagHT;
1272    break;
1273  case 0x0A:
1274  case 0x0D:
1275    break;
1276  case 0x0C:
1277    flag = kOptTpfFlagFF;
1278    break;
1279  case 0x1b:
1280    flag = kOptTpfFlagESC;
1281    break;
1282  case 0x7F:
1283    flag = kOptTpfFlagDEL;
1284    break;
1285  default:
1286    if (c < ' ') {
1287      flag = kOptTpfFlagC0;
1288    } else if (c >= 0x80 && c <= 0x9F) {
1289      flag = kOptTpfFlagC1;
1290    }
1291  }
1292  return !!(tpf_flags & flag);
1293}
1294
1295void terminal_set_streamed_paste(Terminal *term, bool streamed)
1296  FUNC_ATTR_NONNULL_ALL
1297{
1298  if (term->streamed_paste != streamed) {
1299    if (streamed) {
1300      vterm_keyboard_start_paste(curbuf->terminal->vt);
1301    } else {
1302      vterm_keyboard_end_paste(curbuf->terminal->vt);
1303    }
1304  }
1305  term->streamed_paste = streamed;
1306}
1307
1308void terminal_paste(int count, String *y_array, size_t y_size)
1309{
1310  if (y_size == 0) {
1311    return;
1312  }
1313  if (!curbuf->terminal->streamed_paste) {
1314    vterm_keyboard_start_paste(curbuf->terminal->vt);
1315  }
1316  size_t buff_len = y_array[0].size;
1317  char *buff = xmalloc(buff_len);
1318  for (int i = 0; i < count; i++) {
1319    // feed the lines to the terminal
1320    for (size_t j = 0; j < y_size; j++) {
1321      if (j) {
1322        // terminate the previous line
1323#ifdef MSWIN
1324        terminal_send(curbuf->terminal, "\r\n", 2);
1325#else
1326        terminal_send(curbuf->terminal, "\n", 1);
1327#endif
1328      }
1329      size_t len = y_array[j].size;
1330      if (len > buff_len) {
1331        buff = xrealloc(buff, len);
1332        buff_len = len;
1333      }
1334      char *dst = buff;
1335      char *src = y_array[j].data;
1336      while (*src != NUL) {
1337        len = (size_t)utf_ptr2len(src);
1338        int c = utf_ptr2char(src);
1339        if (!is_filter_char(c)) {
1340          memcpy(dst, src, len);
1341          dst += len;
1342        }
1343        src += len;
1344      }
1345      terminal_send(curbuf->terminal, buff, (size_t)(dst - buff));
1346    }
1347  }
1348  xfree(buff);
1349  if (!curbuf->terminal->streamed_paste) {
1350    vterm_keyboard_end_paste(curbuf->terminal->vt);
1351  }
1352}
1353
1354static void terminal_send_key(Terminal *term, int c)
1355{
1356  VTermModifier mod = VTERM_MOD_NONE;
1357
1358  // Convert K_ZERO back to ASCII
1359  if (c == K_ZERO) {
1360    c = Ctrl_AT;
1361  }
1362
1363  VTermKey key = convert_key(&c, mod_mask, &mod);
1364
1365  if (key != VTERM_KEY_NONE) {
1366    vterm_keyboard_key(term->vt, key, mod);
1367  } else if (!IS_SPECIAL(c)) {
1368    vterm_keyboard_unichar(term->vt, (uint32_t)c, mod);
1369  }
1370}
1371
1372/// Callback scheduled on the main loop when a synchronized update ends.
1373/// Refreshes a single terminal with full-screen damage.
1374static void on_sync_flush(void **argv)
1375{
1376  if (exiting) {
1377    return;
1378  }
1379  handle_T buf_handle = (handle_T)(intptr_t)argv[0];
1380  buf_T *buf = handle_get_buffer(buf_handle);
1381  if (!buf || !buf->terminal) {
1382    return;
1383  }
1384  block_autocmds();
1385  refresh_terminal(buf->terminal);
1386  unblock_autocmds();
1387}
1388
1389void terminal_receive(Terminal *term, const char *data, size_t len)
1390{
1391  if (!data) {
1392    return;
1393  }
1394
1395  if (term->opts.force_crlf) {
1396    StringBuilder crlf_data = KV_INITIAL_VALUE;
1397
1398    for (size_t i = 0; i < len; i++) {
1399      if (data[i] == '\n' && (i == 0 || (i > 0 && data[i - 1] != '\r'))) {
1400        kv_push(crlf_data, '\r');
1401      }
1402      kv_push(crlf_data, data[i]);
1403    }
1404
1405    vterm_input_write(term->vt, crlf_data.items, kv_size(crlf_data));
1406    kv_destroy(crlf_data);
1407  } else {
1408    vterm_input_write(term->vt, data, len);
1409  }
1410  vterm_screen_flush_damage(term->vts);
1411
1412  // When a synchronized update just ended, refresh the buffer immediately
1413  // instead of waiting for the 10ms timer.  This eliminates the window where
1414  // neovim's UI could repaint showing stale buffer content.
1415  if (term->sync_flush_pending) {
1416    term->sync_flush_pending = false;
1417    // Schedule a full-screen refresh for this terminal on the main loop.
1418    // Force full-screen damage so every row is updated, not just
1419    // the rows with accumulated damage from individual callbacks.
1420    int height;
1421    vterm_get_size(term->vt, &height, NULL);
1422    term->invalid_start = 0;
1423    term->invalid_end = height;
1424    multiqueue_put(main_loop.events, on_sync_flush,
1425                   (void *)(intptr_t)term->buf_handle);
1426  }
1427}
1428
1429static int get_rgb(VTermState *state, VTermColor color)
1430{
1431  vterm_state_convert_color_to_rgb(state, &color);
1432  return RGB_(color.rgb.red, color.rgb.green, color.rgb.blue);
1433}
1434
1435static int get_underline_hl_flag(VTermScreenCellAttrs attrs)
1436{
1437  switch (attrs.underline) {
1438  case VTERM_UNDERLINE_OFF:
1439    return 0;
1440  case VTERM_UNDERLINE_SINGLE:
1441    return HL_UNDERLINE;
1442  case VTERM_UNDERLINE_DOUBLE:
1443    return HL_UNDERDOUBLE;
1444  case VTERM_UNDERLINE_CURLY:
1445    return HL_UNDERCURL;
1446  default:
1447    return HL_UNDERLINE;
1448  }
1449}
1450
1451void terminal_get_line_attributes(Terminal *term, win_T *wp, int linenr, int *term_attrs)
1452{
1453  int height, width;
1454  vterm_get_size(term->vt, &height, &width);
1455  VTermState *state = vterm_obtain_state(term->vt);
1456  assert(linenr);
1457  int row = linenr_to_row(term, linenr);
1458  if (row >= height) {
1459    // Terminal height was decreased but the change wasn't reflected into the
1460    // buffer yet
1461    return;
1462  }
1463
1464  width = MIN(TERM_ATTRS_MAX, width);
1465  for (int col = 0; col < width; col++) {
1466    VTermScreenCell cell;
1467    bool color_valid = fetch_cell(term, row, col, &cell);
1468    bool fg_default = !color_valid || VTERM_COLOR_IS_DEFAULT_FG(&cell.fg);
1469    bool bg_default = !color_valid || VTERM_COLOR_IS_DEFAULT_BG(&cell.bg);
1470
1471    // Get the rgb value set by libvterm.
1472    int vt_fg = fg_default ? -1 : get_rgb(state, cell.fg);
1473    int vt_bg = bg_default ? -1 : get_rgb(state, cell.bg);
1474
1475    bool fg_indexed = VTERM_COLOR_IS_INDEXED(&cell.fg);
1476    bool bg_indexed = VTERM_COLOR_IS_INDEXED(&cell.bg);
1477
1478    int16_t vt_fg_idx = ((!fg_default && fg_indexed) ? cell.fg.indexed.idx + 1 : 0);
1479    int16_t vt_bg_idx = ((!bg_default && bg_indexed) ? cell.bg.indexed.idx + 1 : 0);
1480
1481    bool fg_set = vt_fg_idx && vt_fg_idx <= 16 && term->color_set[vt_fg_idx - 1];
1482    bool bg_set = vt_bg_idx && vt_bg_idx <= 16 && term->color_set[vt_bg_idx - 1];
1483
1484    int hl_attrs = (cell.attrs.bold ? HL_BOLD : 0)
1485                   | (cell.attrs.dim ? HL_DIM : 0)
1486                   | (cell.attrs.blink ? HL_BLINK : 0)
1487                   | (cell.attrs.conceal ? HL_CONCEALED : 0)
1488                   | (cell.attrs.overline ? HL_OVERLINE : 0)
1489                   | (cell.attrs.italic ? HL_ITALIC : 0)
1490                   | (cell.attrs.reverse ? HL_INVERSE : 0)
1491                   | get_underline_hl_flag(cell.attrs)
1492                   | (cell.attrs.strike ? HL_STRIKETHROUGH : 0)
1493                   | ((fg_indexed && !fg_set) ? HL_FG_INDEXED : 0)
1494                   | ((bg_indexed && !bg_set) ? HL_BG_INDEXED : 0);
1495
1496    int attr_id = 0;
1497
1498    if (hl_attrs || !fg_default || !bg_default) {
1499      attr_id = hl_get_term_attr(&(HlAttrs) {
1500        .cterm_ae_attr = (int32_t)hl_attrs,
1501        .cterm_fg_color = vt_fg_idx,
1502        .cterm_bg_color = vt_bg_idx,
1503        .rgb_ae_attr = (int32_t)hl_attrs,
1504        .rgb_fg_color = vt_fg,
1505        .rgb_bg_color = vt_bg,
1506        .rgb_sp_color = -1,
1507        .hl_blend = -1,
1508        .url = -1,
1509      });
1510    }
1511
1512    if (cell.uri > 0) {
1513      attr_id = hl_combine_attr(attr_id, cell.uri);
1514    }
1515
1516    term_attrs[col] = attr_id;
1517  }
1518}
1519
1520Buffer terminal_buf(const Terminal *term)
1521  FUNC_ATTR_NONNULL_ALL
1522{
1523  return term->buf_handle;
1524}
1525
1526bool terminal_running(const Terminal *term)
1527  FUNC_ATTR_NONNULL_ALL
1528{
1529  return !term->closed;
1530}
1531
1532bool terminal_suspended(const Terminal *term)
1533  FUNC_ATTR_NONNULL_ALL
1534{
1535  return term->suspended;
1536}
1537
1538void terminal_notify_theme(Terminal *term, bool dark)
1539  FUNC_ATTR_NONNULL_ALL
1540{
1541  if (!term->theme_updates) {
1542    return;
1543  }
1544
1545  char buf[10];
1546  ssize_t ret = snprintf(buf, sizeof(buf), "\x1b[997;%cn", dark ? '1' : '2');
1547  assert(ret > 0);
1548  assert((size_t)ret <= sizeof(buf));
1549  terminal_send(term, buf, (size_t)ret);
1550}
1551
1552static void terminal_focus(const Terminal *term, bool focus)
1553  FUNC_ATTR_NONNULL_ALL
1554{
1555  VTermState *state = vterm_obtain_state(term->vt);
1556  if (focus) {
1557    vterm_state_focus_in(state);
1558  } else {
1559    vterm_state_focus_out(state);
1560  }
1561}
1562
1563// }}}
1564// libvterm callbacks {{{
1565
1566static int term_damage(VTermRect rect, void *data)
1567{
1568  invalidate_terminal(data, rect.start_row, rect.end_row);
1569  return 1;
1570}
1571
1572static int term_moverect(VTermRect dest, VTermRect src, void *data)
1573{
1574  invalidate_terminal(data, MIN(dest.start_row, src.start_row),
1575                      MAX(dest.end_row, src.end_row));
1576  return 1;
1577}
1578
1579static int term_movecursor(VTermPos new_pos, VTermPos old_pos, int visible, void *data)
1580{
1581  Terminal *term = data;
1582  term->cursor.row = new_pos.row;
1583  term->cursor.col = new_pos.col;
1584  invalidate_terminal(term, -1, -1);
1585  return 1;
1586}
1587
1588static void buf_set_term_title(buf_T *buf, const char *title, size_t len)
1589{
1590  if (!buf) {
1591    return;  // In case of receiving OSC 2 between buffer close and job exit.
1592  }
1593
1594  Error err = ERROR_INIT;
1595  buf->b_locked++;
1596  dict_set_var(buf->b_vars,
1597               STATIC_CSTR_AS_STRING("term_title"),
1598               STRING_OBJ(((String){ .data = (char *)title, .size = len })),
1599               false,
1600               false,
1601               NULL,
1602               &err);
1603  buf->b_locked--;
1604  api_clear_error(&err);
1605  status_redraw_buf(buf);
1606}
1607
1608static int term_settermprop(VTermProp prop, VTermValue *val, void *data)
1609{
1610  Terminal *term = data;
1611
1612  switch (prop) {
1613  case VTERM_PROP_ALTSCREEN:
1614    term->in_altscreen = val->boolean;
1615    break;
1616
1617  case VTERM_PROP_CURSORVISIBLE:
1618    term->cursor.visible = val->boolean;
1619    invalidate_terminal(term, -1, -1);
1620    break;
1621
1622  case VTERM_PROP_TITLE: {
1623    buf_T *buf = handle_get_buffer(term->buf_handle);  // May be NULL
1624    VTermStringFragment frag = val->string;
1625
1626    if (frag.initial && frag.final) {
1627      buf_set_term_title(buf, frag.str, frag.len);
1628      break;
1629    }
1630
1631    if (frag.initial) {
1632      term->title_len = 0;
1633      term->title_size = MAX(frag.len, 1024);
1634      term->title = xmalloc(sizeof(char *) * term->title_size);
1635    } else if (term->title_len + frag.len > term->title_size) {
1636      term->title_size *= 2;
1637      term->title = xrealloc(term->title, sizeof(char *) * term->title_size);
1638    }
1639
1640    memcpy(term->title + term->title_len, frag.str, frag.len);
1641    term->title_len += frag.len;
1642
1643    if (frag.final) {
1644      buf_set_term_title(buf, term->title, term->title_len);
1645      xfree(term->title);
1646      term->title = NULL;
1647    }
1648    break;
1649  }
1650
1651  case VTERM_PROP_MOUSE:
1652    term->forward_mouse = (bool)val->number;
1653    break;
1654
1655  case VTERM_PROP_CURSORBLINK:
1656    term->cursor.blink = val->boolean;
1657    term->pending.cursor = true;
1658    invalidate_terminal(term, -1, -1);
1659    break;
1660
1661  case VTERM_PROP_CURSORSHAPE:
1662    term->cursor.shape = val->number;
1663    term->pending.cursor = true;
1664    invalidate_terminal(term, -1, -1);
1665    break;
1666
1667  case VTERM_PROP_THEMEUPDATES:
1668    term->theme_updates = val->boolean;
1669    break;
1670
1671  case VTERM_PROP_SYNCOUTPUT:
1672    term->synchronized_output = val->boolean;
1673    if (!val->boolean) {
1674      // Mark that sync just ended; terminal_receive() will flush
1675      // the buffer immediately rather than waiting for the 10ms timer.
1676      term->sync_flush_pending = true;
1677    }
1678    break;
1679
1680  default:
1681    return 0;
1682  }
1683
1684  return 1;
1685}
1686
1687/// Called when the terminal wants to ring the system bell.
1688static int term_bell(void *data)
1689{
1690  vim_beep(kOptBoFlagTerm);
1691  return 1;
1692}
1693
1694/// Called when the terminal wants to query the system theme.
1695static int term_theme(bool *dark, void *data)
1696  FUNC_ATTR_NONNULL_ALL
1697{
1698  *dark = (*p_bg == 'd');
1699  return 1;
1700}
1701
1702/// Scrollback push handler: called just before a line goes offscreen (and libvterm will forget it),
1703/// giving us a chance to store it.
1704///
1705/// Code adapted from pangoterm.
1706static int term_sb_push(int cols, const VTermScreenCell *cells, void *data)
1707{
1708  Terminal *term = data;
1709
1710  if (!term_may_alloc_scrollback(term, NULL)) {
1711    return 0;
1712  }
1713  assert(term->sb_size > 0);
1714
1715  // copy vterm cells into sb_buffer
1716  size_t c = (size_t)cols;
1717  ScrollbackLine *sbrow = NULL;
1718  if (term->sb_current == term->sb_size) {
1719    if (term->sb_buffer[term->sb_current - 1]->cols == c) {
1720      // Recycle old row if it's the right size
1721      sbrow = term->sb_buffer[term->sb_current - 1];
1722    } else {
1723      xfree(term->sb_buffer[term->sb_current - 1]);
1724    }
1725    term->sb_deleted++;
1726
1727    // Make room at the start by shifting to the right.
1728    memmove(term->sb_buffer + 1, term->sb_buffer,
1729            sizeof(term->sb_buffer[0]) * (term->sb_current - 1));
1730  } else if (term->sb_current > 0) {
1731    // Make room at the start by shifting to the right.
1732    memmove(term->sb_buffer + 1, term->sb_buffer,
1733            sizeof(term->sb_buffer[0]) * term->sb_current);
1734  }
1735
1736  if (!sbrow) {
1737    sbrow = xmalloc(sizeof(ScrollbackLine) + c * sizeof(sbrow->cells[0]));
1738    sbrow->cols = c;
1739  }
1740
1741  // New row is added at the start of the storage buffer.
1742  term->sb_buffer[0] = sbrow;
1743  if (term->sb_current < term->sb_size) {
1744    term->sb_current++;
1745  }
1746
1747  if (term->sb_pending < (int)term->sb_size) {
1748    term->sb_pending++;
1749  }
1750
1751  memcpy(sbrow->cells, cells, sizeof(cells[0]) * c);
1752  if (!term->synchronized_output) {
1753    set_put(ptr_t, &invalidated_terminals, term);
1754  }
1755
1756  return 1;
1757}
1758
1759/// Scrollback pop handler (from pangoterm).
1760///
1761/// @param cols
1762/// @param cells  VTerm state to update.
1763/// @param data   Terminal
1764static int term_sb_pop(int cols, VTermScreenCell *cells, void *data)
1765{
1766  Terminal *term = data;
1767
1768  if (!term->sb_current) {
1769    return 0;
1770  }
1771
1772  if (term->sb_pending > 0) {
1773    term->sb_pending--;
1774  } else {
1775    term->old_height++;
1776  }
1777
1778  ScrollbackLine *sbrow = term->sb_buffer[0];
1779  term->sb_current--;
1780  // Forget the "popped" row by shifting the rest onto it.
1781  memmove(term->sb_buffer, term->sb_buffer + 1,
1782          sizeof(term->sb_buffer[0]) * (term->sb_current));
1783
1784  size_t cols_to_copy = MIN((size_t)cols, sbrow->cols);
1785
1786  // copy to vterm state
1787  memcpy(cells, sbrow->cells, sizeof(cells[0]) * cols_to_copy);
1788  for (size_t col = cols_to_copy; col < (size_t)cols; col++) {
1789    cells[col].schar = 0;
1790    cells[col].width = 1;
1791  }
1792
1793  xfree(sbrow);
1794  if (!term->synchronized_output) {
1795    set_put(ptr_t, &invalidated_terminals, term);
1796  }
1797
1798  return 1;
1799}
1800
1801static int term_sb_clear(void *data)
1802{
1803  Terminal *term = data;
1804
1805  if (term->in_altscreen || !term->sb_size || !term->sb_current) {
1806    return 1;
1807  }
1808
1809  for (size_t i = 0; i < term->sb_current; i++) {
1810    xfree(term->sb_buffer[i]);
1811  }
1812
1813  term->sb_deleted += term->sb_current;
1814  term->sb_current = 0;
1815  term->sb_pending = 0;
1816  invalidate_terminal(term, -1, -1);
1817
1818  return 1;
1819}
1820
1821static void term_clipboard_set(void **argv)
1822{
1823  VTermSelectionMask mask = (VTermSelectionMask)(long)argv[0];
1824  char *data = argv[1];
1825
1826  char regname;
1827  switch (mask) {
1828  case VTERM_SELECTION_CLIPBOARD:
1829    regname = '+';
1830    break;
1831  case VTERM_SELECTION_PRIMARY:
1832    regname = '*';
1833    break;
1834  default:
1835    regname = '+';
1836    break;
1837  }
1838
1839  // Split the payload into readfile()-style list (:h chansend()).
1840  // TODO(justinmk): drop this, support Blob in clipboard provider: #41097
1841  list_T *lines = tv_list_alloc(kListLenMayKnow);
1842  char *start = data;
1843  char *end;
1844  while ((end = strchr(start, '\n')) != NULL) {
1845    tv_list_append_string(lines, start, end - start);
1846    start = end + 1;
1847  }
1848  tv_list_append_string(lines, start, -1);
1849  xfree(data);
1850
1851  list_T *args = tv_list_alloc(3);
1852  tv_list_append_list(args, lines);
1853
1854  const char regtype = 'v';
1855  tv_list_append_string(args, &regtype, 1);
1856
1857  tv_list_append_string(args, &regname, 1);
1858  eval_call_provider("clipboard", "set", args, true);
1859}
1860
1861static int term_selection_set(VTermSelectionMask mask, VTermStringFragment frag, void *user)
1862{
1863  Terminal *term = user;
1864  if (frag.initial) {
1865    kv_size(term->selection) = 0;
1866  }
1867
1868  kv_concat_len(term->selection, frag.str, frag.len);
1869
1870  if (frag.final) {
1871    char *data = xmemdupz(term->selection.items, kv_size(term->selection));
1872    multiqueue_put(main_loop.events, term_clipboard_set, (void *)mask, data);
1873  }
1874
1875  return 1;
1876}
1877
1878// }}}
1879// input handling {{{
1880
1881static void convert_modifiers(int *key, int modifiers, VTermModifier *statep)
1882{
1883  if (modifiers & MOD_MASK_SHIFT) {
1884    *statep |= VTERM_MOD_SHIFT;
1885  }
1886  if (modifiers & MOD_MASK_CTRL) {
1887    *statep |= VTERM_MOD_CTRL;
1888    if (!(modifiers & MOD_MASK_SHIFT) && *key >= 'A' && *key <= 'Z') {
1889      // vterm interprets CTRL+A as SHIFT+CTRL, change to CTRL+a
1890      *key += ('a' - 'A');
1891    }
1892  }
1893  if (modifiers & MOD_MASK_ALT) {
1894    *statep |= VTERM_MOD_ALT;
1895  }
1896}
1897
1898static VTermKey convert_key(int *key, int modifiers, VTermModifier *statep)
1899{
1900  *key = unsimplify_key(*key, &modifiers);
1901  convert_modifiers(key, modifiers, statep);
1902
1903  switch (*key) {
1904  case K_BS:
1905    return VTERM_KEY_BACKSPACE;
1906  case K_TAB:
1907  case TAB:
1908    return VTERM_KEY_TAB;
1909  case Ctrl_M:
1910    return VTERM_KEY_ENTER;
1911  case ESC:
1912    return VTERM_KEY_ESCAPE;
1913
1914  case K_UP:
1915    return VTERM_KEY_UP;
1916  case K_DOWN:
1917    return VTERM_KEY_DOWN;
1918  case K_LEFT:
1919    return VTERM_KEY_LEFT;
1920  case K_RIGHT:
1921    return VTERM_KEY_RIGHT;
1922
1923  case K_INS:
1924    return VTERM_KEY_INS;
1925  case K_DEL:
1926    return VTERM_KEY_DEL;
1927  case K_HOME:
1928    return VTERM_KEY_HOME;
1929  case K_END:
1930    return VTERM_KEY_END;
1931  case K_PAGEUP:
1932    return VTERM_KEY_PAGEUP;
1933  case K_PAGEDOWN:
1934    return VTERM_KEY_PAGEDOWN;
1935
1936  case K_K0:
1937  case K_KINS:
1938    return VTERM_KEY_KP_0;
1939  case K_K1:
1940  case K_KEND:
1941    return VTERM_KEY_KP_1;
1942  case K_K2:
1943  case K_KDOWN:
1944    return VTERM_KEY_KP_2;
1945  case K_K3:
1946  case K_KPAGEDOWN:
1947    return VTERM_KEY_KP_3;
1948  case K_K4:
1949  case K_KLEFT:
1950    return VTERM_KEY_KP_4;
1951  case K_K5:
1952  case K_KORIGIN:
1953    return VTERM_KEY_KP_5;
1954  case K_K6:
1955  case K_KRIGHT:
1956    return VTERM_KEY_KP_6;
1957  case K_K7:
1958  case K_KHOME:
1959    return VTERM_KEY_KP_7;
1960  case K_K8:
1961  case K_KUP:
1962    return VTERM_KEY_KP_8;
1963  case K_K9:
1964  case K_KPAGEUP:
1965    return VTERM_KEY_KP_9;
1966  case K_KDEL:
1967  case K_KPOINT:
1968    return VTERM_KEY_KP_PERIOD;
1969  case K_KENTER:
1970    return VTERM_KEY_KP_ENTER;
1971  case K_KPLUS:
1972    return VTERM_KEY_KP_PLUS;
1973  case K_KMINUS:
1974    return VTERM_KEY_KP_MINUS;
1975  case K_KMULTIPLY:
1976    return VTERM_KEY_KP_MULT;
1977  case K_KDIVIDE:
1978    return VTERM_KEY_KP_DIVIDE;
1979
1980  case K_F1:
1981    return VTERM_KEY_FUNCTION(1);
1982  case K_F2:
1983    return VTERM_KEY_FUNCTION(2);
1984  case K_F3:
1985    return VTERM_KEY_FUNCTION(3);
1986  case K_F4:
1987    return VTERM_KEY_FUNCTION(4);
1988  case K_F5:
1989    return VTERM_KEY_FUNCTION(5);
1990  case K_F6:
1991    return VTERM_KEY_FUNCTION(6);
1992  case K_F7:
1993    return VTERM_KEY_FUNCTION(7);
1994  case K_F8:
1995    return VTERM_KEY_FUNCTION(8);
1996  case K_F9:
1997    return VTERM_KEY_FUNCTION(9);
1998  case K_F10:
1999    return VTERM_KEY_FUNCTION(10);
2000  case K_F11:
2001    return VTERM_KEY_FUNCTION(11);
2002  case K_F12:
2003    return VTERM_KEY_FUNCTION(12);
2004
2005  case K_F13:
2006    return VTERM_KEY_FUNCTION(13);
2007  case K_F14:
2008    return VTERM_KEY_FUNCTION(14);
2009  case K_F15:
2010    return VTERM_KEY_FUNCTION(15);
2011  case K_F16:
2012    return VTERM_KEY_FUNCTION(16);
2013  case K_F17:
2014    return VTERM_KEY_FUNCTION(17);
2015  case K_F18:
2016    return VTERM_KEY_FUNCTION(18);
2017  case K_F19:
2018    return VTERM_KEY_FUNCTION(19);
2019  case K_F20:
2020    return VTERM_KEY_FUNCTION(20);
2021  case K_F21:
2022    return VTERM_KEY_FUNCTION(21);
2023  case K_F22:
2024    return VTERM_KEY_FUNCTION(22);
2025  case K_F23:
2026    return VTERM_KEY_FUNCTION(23);
2027  case K_F24:
2028    return VTERM_KEY_FUNCTION(24);
2029  case K_F25:
2030    return VTERM_KEY_FUNCTION(25);
2031  case K_F26:
2032    return VTERM_KEY_FUNCTION(26);
2033  case K_F27:
2034    return VTERM_KEY_FUNCTION(27);
2035  case K_F28:
2036    return VTERM_KEY_FUNCTION(28);
2037  case K_F29:
2038    return VTERM_KEY_FUNCTION(29);
2039  case K_F30:
2040    return VTERM_KEY_FUNCTION(30);
2041  case K_F31:
2042    return VTERM_KEY_FUNCTION(31);
2043  case K_F32:
2044    return VTERM_KEY_FUNCTION(32);
2045  case K_F33:
2046    return VTERM_KEY_FUNCTION(33);
2047  case K_F34:
2048    return VTERM_KEY_FUNCTION(34);
2049  case K_F35:
2050    return VTERM_KEY_FUNCTION(35);
2051  case K_F36:
2052    return VTERM_KEY_FUNCTION(36);
2053  case K_F37:
2054    return VTERM_KEY_FUNCTION(37);
2055  case K_F38:
2056    return VTERM_KEY_FUNCTION(38);
2057  case K_F39:
2058    return VTERM_KEY_FUNCTION(39);
2059  case K_F40:
2060    return VTERM_KEY_FUNCTION(40);
2061  case K_F41:
2062    return VTERM_KEY_FUNCTION(41);
2063  case K_F42:
2064    return VTERM_KEY_FUNCTION(42);
2065  case K_F43:
2066    return VTERM_KEY_FUNCTION(43);
2067  case K_F44:
2068    return VTERM_KEY_FUNCTION(44);
2069  case K_F45:
2070    return VTERM_KEY_FUNCTION(45);
2071  case K_F46:
2072    return VTERM_KEY_FUNCTION(46);
2073  case K_F47:
2074    return VTERM_KEY_FUNCTION(47);
2075  case K_F48:
2076    return VTERM_KEY_FUNCTION(48);
2077  case K_F49:
2078    return VTERM_KEY_FUNCTION(49);
2079  case K_F50:
2080    return VTERM_KEY_FUNCTION(50);
2081  case K_F51:
2082    return VTERM_KEY_FUNCTION(51);
2083  case K_F52:
2084    return VTERM_KEY_FUNCTION(52);
2085  case K_F53:
2086    return VTERM_KEY_FUNCTION(53);
2087  case K_F54:
2088    return VTERM_KEY_FUNCTION(54);
2089  case K_F55:
2090    return VTERM_KEY_FUNCTION(55);
2091  case K_F56:
2092    return VTERM_KEY_FUNCTION(56);
2093  case K_F57:
2094    return VTERM_KEY_FUNCTION(57);
2095  case K_F58:
2096    return VTERM_KEY_FUNCTION(58);
2097  case K_F59:
2098    return VTERM_KEY_FUNCTION(59);
2099  case K_F60:
2100    return VTERM_KEY_FUNCTION(60);
2101  case K_F61:
2102    return VTERM_KEY_FUNCTION(61);
2103  case K_F62:
2104    return VTERM_KEY_FUNCTION(62);
2105  case K_F63:
2106    return VTERM_KEY_FUNCTION(63);
2107
2108  default:
2109    return VTERM_KEY_NONE;
2110  }
2111}
2112
2113static void mouse_action(Terminal *term, int button, int row, int col, bool pressed,
2114                         VTermModifier mod)
2115{
2116  vterm_mouse_move(term->vt, row, col, mod);
2117  if (button) {
2118    vterm_mouse_button(term->vt, button, pressed, mod);
2119  }
2120}
2121
2122// process a mouse event while the terminal is focused. return true if the
2123// terminal should lose focus
2124static bool send_mouse_event(Terminal *term, int c)
2125{
2126  int row = mouse_row;
2127  int col = mouse_col;
2128  int grid = mouse_grid;
2129  win_T *mouse_win = mouse_find_win_inner(&grid, &row, &col);
2130  if (mouse_win == NULL) {
2131    goto end;
2132  }
2133
2134  int offset;
2135  if (!term->suspended && !term->closed
2136      && term->forward_mouse && mouse_win->w_buffer->terminal == term && row >= 0
2137      && (grid > 1 || row + mouse_win->w_winbar_height < mouse_win->w_height)
2138      && col >= (offset = win_col_off(mouse_win))
2139      && (grid > 1 || col < mouse_win->w_width)) {
2140    // event in the terminal window and mouse events was enabled by the
2141    // program. translate and forward the event
2142    int button;
2143    bool pressed = false;
2144
2145    switch (c) {
2146    case K_LEFTDRAG:
2147    case K_LEFTMOUSE:
2148      pressed = true; FALLTHROUGH;
2149    case K_LEFTRELEASE:
2150      button = 1; break;
2151    case K_MIDDLEDRAG:
2152    case K_MIDDLEMOUSE:
2153      pressed = true; FALLTHROUGH;
2154    case K_MIDDLERELEASE:
2155      button = 2; break;
2156    case K_RIGHTDRAG:
2157    case K_RIGHTMOUSE:
2158      pressed = true; FALLTHROUGH;
2159    case K_RIGHTRELEASE:
2160      button = 3; break;
2161    case K_X1DRAG:
2162    case K_X1MOUSE:
2163      pressed = true; FALLTHROUGH;
2164    case K_X1RELEASE:
2165      button = 8; break;
2166    case K_X2DRAG:
2167    case K_X2MOUSE:
2168      pressed = true; FALLTHROUGH;
2169    case K_X2RELEASE:
2170      button = 9; break;
2171    case K_MOUSEDOWN:
2172      pressed = true; button = 4; break;
2173    case K_MOUSEUP:
2174      pressed = true; button = 5; break;
2175    case K_MOUSELEFT:
2176      pressed = true; button = 7; break;
2177    case K_MOUSERIGHT:
2178      pressed = true; button = 6; break;
2179    case K_MOUSEMOVE:
2180      button = 0; break;
2181    default:
2182      return false;
2183    }
2184
2185    VTermModifier mod = VTERM_MOD_NONE;
2186    convert_modifiers(&c, mod_mask, &mod);
2187    mouse_action(term, button, row, col - offset, pressed, mod);
2188    return false;
2189  }
2190
2191  if (c == K_MOUSEUP || c == K_MOUSEDOWN || c == K_MOUSELEFT || c == K_MOUSERIGHT) {
2192    win_T *save_curwin = curwin;
2193    // switch window/buffer to perform the scroll
2194    curwin = mouse_win;
2195    curbuf = curwin->w_buffer;
2196
2197    cmdarg_T cap;
2198    oparg_T oa;
2199    CLEAR_FIELD(cap);
2200    clear_oparg(&oa);
2201    cap.oap = &oa;
2202
2203    switch (cap.cmdchar = c) {
2204    case K_MOUSEUP:
2205      cap.arg = MSCR_UP;
2206      break;
2207    case K_MOUSEDOWN:
2208      cap.arg = MSCR_DOWN;
2209      break;
2210    case K_MOUSELEFT:
2211      cap.arg = MSCR_LEFT;
2212      break;
2213    case K_MOUSERIGHT:
2214      cap.arg = MSCR_RIGHT;
2215      break;
2216    default:
2217      abort();
2218    }
2219
2220    // Call the common mouse scroll function shared with other modes.
2221    do_mousescroll(&cap);
2222
2223    curwin->w_redr_status = true;
2224    curwin = save_curwin;
2225    curbuf = curwin->w_buffer;
2226    redraw_later(mouse_win, UPD_NOT_VALID);
2227    invalidate_terminal(term, -1, -1);
2228    // Only need to exit focus if the scrolled window is the terminal window
2229    return mouse_win == curwin;
2230  }
2231
2232end:
2233  // Ignore left release action if it was not forwarded to prevent
2234  // leaving Terminal mode after entering to it using a mouse.
2235  if ((c == K_LEFTRELEASE && mouse_win != NULL && mouse_win->w_buffer->terminal == term)
2236      || c == K_MOUSEMOVE) {
2237    return false;
2238  }
2239
2240  requeue_key(vgetc_char, vgetc_mod_mask, 0, true);
2241  return true;
2242}
2243
2244// }}}
2245// terminal buffer refresh & misc {{{
2246
2247static void fetch_row(Terminal *term, int row, int end_col)
2248{
2249  int col = 0;
2250  size_t line_len = 0;
2251  char *ptr = term->textbuf;
2252
2253  while (col < end_col) {
2254    VTermScreenCell cell;
2255    fetch_cell(term, row, col, &cell);
2256    if (cell.schar) {
2257      schar_get_adv(&ptr, cell.schar);
2258      line_len = (size_t)(ptr - term->textbuf);
2259    } else {
2260      *ptr++ = ' ';
2261    }
2262    col += cell.width;
2263  }
2264
2265  // end of line
2266  term->textbuf[line_len] = NUL;
2267}
2268
2269static bool fetch_cell(Terminal *term, int row, int col, VTermScreenCell *cell)
2270{
2271  if (row < 0) {
2272    ScrollbackLine *sbrow = term->sb_buffer[-row - 1];
2273    if ((size_t)col < sbrow->cols) {
2274      *cell = sbrow->cells[col];
2275    } else {
2276      // fill the pointer with an empty cell
2277      *cell = (VTermScreenCell) {
2278        .schar = 0,
2279        .width = 1,
2280      };
2281      return false;
2282    }
2283  } else {
2284    vterm_screen_get_cell(term->vts, (VTermPos){ .row = row, .col = col },
2285                          cell);
2286  }
2287  return true;
2288}
2289
2290// queue a terminal instance for refresh
2291static void invalidate_terminal(Terminal *term, int start_row, int end_row)
2292{
2293  if (start_row != -1 && end_row != -1) {
2294    term->invalid_start = MIN(term->invalid_start, start_row);
2295    term->invalid_end = MAX(term->invalid_end, end_row);
2296  }
2297
2298  // During synchronized output (mode 2026), accumulate damage but defer
2299  // the actual refresh until the synchronized update ends.
2300  if (term->synchronized_output) {
2301    return;
2302  }
2303
2304  set_put(ptr_t, &invalidated_terminals, term);
2305  if (!refresh_pending) {
2306    time_watcher_start(&refresh_timer, refresh_timer_cb, REFRESH_DELAY, 0);
2307    refresh_pending = true;
2308  }
2309}
2310
2311/// Normally refresh_timer_cb() is called when processing main_loop.events, but with
2312/// partial mappings main_loop.events isn't processed, while terminal buffers still
2313/// need refreshing after processing a key, so call this function before redrawing.
2314void terminal_check_refresh(void)
2315{
2316  multiqueue_process_events(refresh_timer.events);
2317}
2318
2319static void refresh_terminal(Terminal *term)
2320{
2321  buf_T *buf = handle_get_buffer(term->buf_handle);
2322  if (!buf) {
2323    // Destroyed by `buf_freeall()`. Do not do anything else.
2324    return;
2325  }
2326  linenr_T ml_before = buf->b_ml.ml_line_count;
2327
2328  bool resized = refresh_size(term, buf);
2329  refresh_scrollback(term, buf);
2330  refresh_screen(term, buf);
2331
2332  int ml_added = buf->b_ml.ml_line_count - ml_before;
2333  adjust_topline_cursor(term, buf, ml_added);
2334
2335  // Resized window may have scrolled horizontally to keep its cursor in-view using the old terminal
2336  // size. Reset the scroll, and let curs_columns correct it if that sends the cursor out-of-view.
2337  if (resized) {
2338    FOR_ALL_TAB_WINDOWS(tp, wp) {
2339      if (wp->w_buffer == buf && wp->w_leftcol != 0) {
2340        wp->w_leftcol = 0;
2341        curs_columns(wp, true);
2342      }
2343    }
2344  }
2345
2346  // Copy pending events back to the main event queue
2347  multiqueue_move_events(main_loop.events, term->pending.events);
2348}
2349
2350static void refresh_cursor(Terminal *term, bool *cursor_visible)
2351  FUNC_ATTR_NONNULL_ALL
2352{
2353  if (!is_focused(term)) {
2354    return;
2355  }
2356  if (term->cursor.visible != *cursor_visible) {
2357    *cursor_visible = term->cursor.visible;
2358    if (*cursor_visible) {
2359      ui_busy_stop();
2360    } else {
2361      ui_busy_start();
2362    }
2363  }
2364
2365  if (!term->pending.cursor) {
2366    return;
2367  }
2368  term->pending.cursor = false;
2369
2370  if (term->cursor.blink) {
2371    // For the TUI, this value doesn't actually matter, as long as it's non-zero. The terminal
2372    // emulator dictates the blink frequency, not the application.
2373    // For GUIs we just pick an arbitrary value, for now.
2374    shape_table[SHAPE_IDX_TERM].blinkon = 500;
2375    shape_table[SHAPE_IDX_TERM].blinkoff = 500;
2376  } else {
2377    shape_table[SHAPE_IDX_TERM].blinkon = 0;
2378    shape_table[SHAPE_IDX_TERM].blinkoff = 0;
2379  }
2380
2381  switch (term->cursor.shape) {
2382  case VTERM_PROP_CURSORSHAPE_BLOCK:
2383    shape_table[SHAPE_IDX_TERM].shape = SHAPE_BLOCK;
2384    break;
2385  case VTERM_PROP_CURSORSHAPE_UNDERLINE:
2386    shape_table[SHAPE_IDX_TERM].shape = SHAPE_HOR;
2387    shape_table[SHAPE_IDX_TERM].percentage = 20;
2388    break;
2389  case VTERM_PROP_CURSORSHAPE_BAR_LEFT:
2390    shape_table[SHAPE_IDX_TERM].shape = SHAPE_VER;
2391    shape_table[SHAPE_IDX_TERM].percentage = 25;
2392    break;
2393  }
2394
2395  ui_mode_info_set();
2396}
2397
2398/// Calls refresh_terminal() on all invalidated_terminals.
2399static void refresh_timer_cb(TimeWatcher *watcher, void *data)
2400{
2401  refresh_pending = false;
2402  if (exiting) {  // Cannot redraw (requires event loop) during teardown/exit.
2403    return;
2404  }
2405
2406  // Don't process autocommands while updating terminal buffers.
2407  block_autocmds();
2408  // Refreshing one terminal may poll for output to another, which should not
2409  // interfere with the set_foreach() below.
2410  Set(ptr_t) to_refresh = invalidated_terminals;
2411  invalidated_terminals = (Set(ptr_t)) SET_INIT;
2412
2413  Terminal *term;
2414  set_foreach(&to_refresh, term, {
2415    // Skip terminals in synchronized output — they will be refreshed
2416    // when the synchronized update ends (mode 2026 reset).
2417    if (!term->synchronized_output) {
2418      refresh_terminal(term);
2419    }
2420  });
2421
2422  set_destroy(ptr_t, &to_refresh);
2423  unblock_autocmds();
2424}
2425
2426static bool refresh_size(Terminal *term, buf_T *buf)
2427{
2428  if (!term->pending.resize || term->closed) {
2429    return false;
2430  }
2431
2432  term->pending.resize = false;
2433  int width, height;
2434  vterm_get_size(term->vt, &height, &width);
2435  term->invalid_start = 0;
2436  term->invalid_end = height;
2437  term->opts.resize_cb((uint16_t)width, (uint16_t)height, term->opts.data);
2438  return true;
2439}
2440
2441void on_scrollback_option_changed(Terminal *term)
2442{
2443  // Scrollback buffer may not exist yet, e.g. if 'scrollback' is set in a TermOpen autocmd.
2444  if (term->sb_buffer != NULL) {
2445    refresh_terminal(term);
2446  }
2447}
2448
2449/// Adjusts scrollback storage and the terminal buffer scrollback lines
2450static void adjust_scrollback(Terminal *term, buf_T *buf)
2451{
2452  if (buf->b_p_scbk < 1) {  // Local 'scrollback' was set to -1.
2453    buf->b_p_scbk = SB_MAX;
2454  }
2455  const size_t scbk = (size_t)buf->b_p_scbk;
2456  assert(term->sb_current < SIZE_MAX);
2457  if (term->sb_pending > 0) {  // Pending rows must be processed first.
2458    abort();
2459  }
2460
2461  // Delete lines exceeding the new 'scrollback' limit.
2462  if (scbk < term->sb_current) {
2463    size_t diff = term->sb_current - scbk;
2464    for (size_t i = 0; i < diff; i++) {
2465      ml_delete_buf(buf, 1, false);
2466      term->sb_current--;
2467      xfree(term->sb_buffer[term->sb_current]);
2468    }
2469    mark_adjust_buf(buf, 1, (linenr_T)diff, MAXLNUM, -(linenr_T)diff, true,
2470                    kMarkAdjustTerm, kExtmarkUndo);
2471    deleted_lines_buf(buf, 1, (linenr_T)diff);
2472  }
2473
2474  // Resize the scrollback storage.
2475  size_t sb_region = sizeof(ScrollbackLine *) * scbk;
2476  if (scbk != term->sb_size) {
2477    term->sb_buffer = xrealloc(term->sb_buffer, sb_region);
2478  }
2479
2480  term->sb_size = scbk;
2481}
2482
2483// Refresh the scrollback of an invalidated terminal.
2484static void refresh_scrollback(Terminal *term, buf_T *buf)
2485{
2486  // Buffer update callbacks may poll for uv events.
2487  // Avoid polling for output to the same terminal as the one being refreshed.
2488  term->opts.read_pause_cb(true, term->opts.data);
2489
2490  linenr_T deleted = (linenr_T)(term->sb_deleted - term->old_sb_deleted);
2491  deleted = MIN(deleted, buf->b_ml.ml_line_count);
2492  mark_adjust_buf(buf, 1, deleted, MAXLNUM, -deleted, true, kMarkAdjustTerm, kExtmarkUndo);
2493  term->old_sb_deleted = term->sb_deleted;
2494
2495  int old_height = term->old_height;
2496  int width, height;
2497  vterm_get_size(term->vt, &height, &width);
2498
2499  // Remove deleted scrollback lines at the top, but don't unnecessarily remove
2500  // lines that will be overwritten by refresh_screen().
2501  while (deleted > 0 && buf->b_ml.ml_line_count > old_height) {
2502    ml_delete_buf(buf, 1, false);
2503    deleted_lines_buf(buf, 1, 1);
2504    deleted--;
2505  }
2506
2507  // Clamp old_height in case buffer lines have been deleted by the user.
2508  old_height = MIN(old_height, buf->b_ml.ml_line_count);
2509  while (term->sb_pending > 0) {
2510    // This means that either the window height has decreased or the screen
2511    // became full and libvterm had to push all rows up. Convert the first
2512    // pending scrollback row into a string and append it just above the visible
2513    // section of the buffer.
2514    fetch_row(term, -term->sb_pending, width);
2515    int buf_index = buf->b_ml.ml_line_count - old_height;
2516    ml_append_buf(buf, buf_index, term->textbuf, 0, false);
2517    appended_lines_buf(buf, buf_index, 1);
2518    term->sb_pending--;
2519  }
2520
2521  int max_line_count = (int)term->sb_current + height;
2522  // Remove extra lines at the bottom.
2523  while (buf->b_ml.ml_line_count > max_line_count) {
2524    ml_delete_buf(buf, buf->b_ml.ml_line_count, false);
2525    deleted_lines_buf(buf, buf->b_ml.ml_line_count, 1);
2526  }
2527
2528  adjust_scrollback(term, buf);
2529
2530  term->opts.read_pause_cb(false, term->opts.data);
2531}
2532
2533// Refresh the screen (visible part of the buffer when the terminal is
2534// focused) of a invalidated terminal
2535static void refresh_screen(Terminal *term, buf_T *buf)
2536{
2537  int changed = 0;
2538  int added = 0;
2539  int height;
2540  int width;
2541  vterm_get_size(term->vt, &height, &width);
2542  // Terminal height may have decreased before `invalid_end` reflects it.
2543  term->invalid_end = MIN(term->invalid_end, height);
2544
2545  // There are no invalid rows.
2546  if (term->invalid_start >= term->invalid_end) {
2547    term->invalid_start = INT_MAX;
2548    term->invalid_end = -1;
2549    return;
2550  }
2551
2552  for (int r = term->invalid_start, linenr = row_to_linenr(term, r);
2553       r < term->invalid_end; r++, linenr++) {
2554    fetch_row(term, r, width);
2555
2556    if (linenr <= buf->b_ml.ml_line_count) {
2557      ml_replace_buf(buf, linenr, term->textbuf, true, false);
2558      changed++;
2559    } else {
2560      ml_append_buf(buf, linenr - 1, term->textbuf, 0, false);
2561      added++;
2562    }
2563  }
2564  term->old_height = height;
2565
2566  int change_start = row_to_linenr(term, term->invalid_start);
2567  int change_end = change_start + changed;
2568  term->invalid_start = INT_MAX;
2569  term->invalid_end = -1;
2570  // Call this after resetting the invalid region, as buffer update callbacks may
2571  // poll for terminal output and lead to new invalidations.
2572  changed_lines(buf, change_start, 0, change_end, added, true);
2573}
2574
2575static void adjust_topline_cursor(Terminal *term, buf_T *buf, int added)
2576{
2577  linenr_T ml_end = buf->b_ml.ml_line_count;
2578
2579  FOR_ALL_TAB_WINDOWS(tp, wp) {
2580    if (wp->w_buffer == buf) {
2581      if (wp == curwin && is_focused(term)) {
2582        // Move window cursor to terminal cursor's position and "follow" output.
2583        terminal_check_cursor();
2584        continue;
2585      }
2586
2587      bool following = ml_end == wp->w_cursor.lnum + added;  // cursor at end?
2588      if (following) {
2589        // "Follow" the terminal output
2590        wp->w_cursor.lnum = ml_end;
2591        set_topline(wp, MAX(wp->w_cursor.lnum - wp->w_view_height + 1, 1));
2592      } else {
2593        // Ensure valid cursor for each window displaying this terminal.
2594        wp->w_cursor.lnum = MIN(wp->w_cursor.lnum, ml_end);
2595      }
2596      mb_check_adjust_col(wp);
2597    }
2598  }
2599
2600  if (ml_end == buf->b_last_cursor.mark.lnum + added) {
2601    buf->b_last_cursor.mark.lnum = ml_end;
2602  }
2603
2604  for (size_t i = 0; i < kv_size(buf->b_wininfo); i++) {
2605    WinInfo *wip = kv_A(buf->b_wininfo, i);
2606    if (ml_end == wip->wi_mark.mark.lnum + added) {
2607      wip->wi_mark.mark.lnum = ml_end;
2608    }
2609  }
2610}
2611
2612static int row_to_linenr(Terminal *term, int row)
2613{
2614  return row != INT_MAX ? row + (int)term->sb_current + 1 : INT_MAX;
2615}
2616
2617static int linenr_to_row(Terminal *term, int linenr)
2618{
2619  return linenr - (int)term->sb_current - 1;
2620}
2621
2622static bool is_focused(Terminal *term)
2623{
2624  return State & MODE_TERMINAL && curbuf->terminal == term;
2625}
2626
2627static char *get_config_string(buf_T *buf, char *key)
2628{
2629  Error err = ERROR_INIT;
2630  Object obj = dict_get_value(buf->b_vars, cstr_as_string(key), NULL, &err);
2631  api_clear_error(&err);
2632  if (obj.type == kObjectTypeNil) {
2633    obj = dict_get_value(get_globvar_dict(), cstr_as_string(key), NULL, &err);
2634    api_clear_error(&err);
2635  }
2636  if (obj.type == kObjectTypeString) {
2637    return obj.data.string.data;
2638  }
2639  api_free_object(obj);
2640  return NULL;
2641}
2642
2643// }}}
2644
2645// vim: foldmethod=marker