robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
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 { 111VimState state ; 112Terminal * term ; 113int save_rd ;///< saved value of RedrawingDisabled 114bool close ; 115bool got_bsl ;///< if the last input was <C-\> 116bool got_bsl_o ;///< if left terminal mode with <c-\><c-o> 117bool 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. 121handle_T save_curwin_handle ; 122bool save_w_p_cul ; 123char * save_w_p_culopt ; 124uint8_t save_w_p_culopt_flags ; 125int save_w_p_cuc ; 126OptInt save_w_p_so ; 127OptInt 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 { 143size_t cols ; 144VTermScreenCell cells []; 145}ScrollbackLine ; 146 147struct terminal { 148TerminalOptions opts ;// options passed to terminal_alloc() 149VTerm * vt ; 150VTermScreen * vts ; 151// buffer used to: 152// - convert VTermScreen cell arrays into utf8 strings 153// - receive data from libvterm as a result of key presses. 154char textbuf [TEXTBUF_SIZE ]; 155 156ScrollbackLine ** sb_buffer ;///< Scrollback storage. 157size_t sb_current ;///< Lines stored in sb_buffer. 158size_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. 161int sb_pending ; 162size_t sb_deleted ;///< Lines deleted from sb_buffer. 163size_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. 165int old_height ; 166 167char * title ;// VTermStringFragment buffer 168size_t title_len ; 169size_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. 175handle_T buf_handle ; 176bool in_altscreen ; 177// program suspended 178bool suspended ; 179// program exited 180bool closed ; 181// when true, the terminal's destruction is already enqueued. 182bool destroy ; 183 184// some vterm properties 185bool forward_mouse ; 186int invalid_start ,invalid_end ;// invalid rows in libvterm screen 187struct { 188int row ,col ; 189int shape ; 190bool visible ;///< Terminal wants to show cursor. 191///< `TerminalState.cursor_visible` indicates whether it is actually shown. 192bool blink ; 193 }cursor ; 194 195struct { 196bool resize ;///< pending width/height 197bool cursor ;///< pending cursor shape or blink change 198StringBuilder * send ;///< When there is a pending TermRequest autocommand, block and store input. 199MultiQueue * events ;///< Events waiting for refresh. 200 }pending ; 201 202bool streamed_paste ;///< Streamed pasting 203bool theme_updates ;///< Send a theme update notification when 'bg' changes 204bool synchronized_output ;///< Mode 2026: suppress redraws until end of synchronized update 205bool sync_flush_pending ;///< Set when mode 2026 ends; triggers immediate buffer refresh 206 207bool color_set [16 ]; 208 209char * selection_buffer ;///< libvterm selection buffer 210StringBuilder selection ;///< Growable array containing full selection data 211 212StringBuilder termrequest_buffer ;///< Growable array containing unfinished request sequence 213VTermTerminator termrequest_terminator ;///< Terminator (BEL or ST) used in the termrequest 214 215size_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{ 240handle_T buf_handle = (handle_T )(intptr_t )argv [0 ]; 241char * sequence = argv [1 ]; 242size_t sequence_length = (size_t )argv [2 ]; 243StringBuilder * pending_send = argv [3 ]; 244int row = (int )(intptr_t )argv [4 ]; 245int col = (int )(intptr_t )argv [5 ]; 246size_t sb_deleted = (size_t )(intptr_t )argv [6 ]; 247VTermTerminator terminator = (VTermTerminator )(intptr_t )argv [7 ]; 248 249buf_T * buf = handle_get_buffer (buf_handle ); 250if (!buf || buf -> terminal == NULL ) {// Terminal already closed. 251xfree (sequence ); 252kv_destroy (* pending_send ); 253xfree (pending_send ); 254return ; 255 } 256Terminal * term = buf -> terminal ; 257 258if (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. 263multiqueue_put (term -> pending .events ,emit_termrequest ,argv [0 ],argv [1 ],argv [2 ], 264argv [3 ],argv [4 ],argv [5 ],argv [6 ],argv [7 ]); 265return ; 266 } 267 268set_vim_var_string (VV_TERMREQUEST ,sequence , (ptrdiff_t )sequence_length ); 269 270MAXSIZE_TEMP_ARRAY (cursor ,2 ); 271ADD_C (cursor ,INTEGER_OBJ (row - (int64_t )(term -> sb_deleted - sb_deleted ))); 272ADD_C (cursor ,INTEGER_OBJ (col )); 273 274MAXSIZE_TEMP_DICT (data ,3 ); 275String termrequest = { .data = sequence , .size = sequence_length }; 276PUT_C (data ,"sequence" ,STRING_OBJ (termrequest )); 277PUT_C (data ,"cursor" ,ARRAY_OBJ (cursor )); 278PUT_C (data ,"terminator" , 279terminator == 280VTERM_TERMINATOR_BEL ?STATIC_CSTR_AS_OBJ ("\x07" ) :STATIC_CSTR_AS_OBJ ("\x1b\\" )); 281 282term -> refcount ++ ; 283apply_autocmds_group (EVENT_TERMREQUEST ,NULL ,NULL , true,AUGROUP_ALL ,buf ,curwin ,NULL , 284& DICT_OBJ (data ), false); 285term -> refcount -- ; 286xfree (sequence ); 287 288StringBuilder * term_pending_send = term -> pending .send ; 289term -> pending .send = NULL ; 290if (kv_size (* pending_send )) { 291terminal_send (term ,pending_send -> items ,pending_send -> size ); 292kv_destroy (* pending_send ); 293 } 294if (term_pending_send != pending_send ) { 295term -> pending .send = term_pending_send ; 296 } 297xfree (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. 301if (term -> buf_handle == 0 && !term -> refcount ) { 302term -> destroy = true; 303term -> opts .close_cb (term -> opts .data ); 304 } 305} 306 307static void schedule_termrequest (Terminal * term ) 308{ 309term -> pending .send = xmalloc (sizeof (StringBuilder )); 310kv_init (* term -> pending .send ); 311 312int line = row_to_linenr (term ,term -> cursor .row ); 313multiqueue_put (main_loop .events ,emit_termrequest , (void * )(intptr_t )term -> buf_handle , 314xmemdup (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 ) 322FUNC_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) 326size_t i = 0 ; 327for (;str [i ]!= NUL ;i ++ ) { 328if (str [i ]== ';' ) { 329break ; 330 } 331 } 332 333if (str [i ]!= ';' ) { 334// Invalid OSC sequence 335return 0 ; 336 } 337 338// Move past the semicolon 339i ++ ; 340 341if (str [i ]== NUL ) { 342// Empty OSC 8, no URL 343* attr = 0 ; 344return 1 ; 345 } 346 347* attr = hl_add_url (0 ,str + i ); 348return 1 ; 349} 350 351static int on_osc (int command ,VTermStringFragment frag ,void * user ) 352FUNC_ATTR_NONNULL_ALL 353{ 354Terminal * term = user ; 355 356if (frag .str == NULL || frag .len == 0 ) { 357return 0 ; 358 } 359 360if (command != 8 && !has_event (EVENT_TERMREQUEST )) { 361return 1 ; 362 } 363 364if (frag .initial ) { 365kv_size (term -> termrequest_buffer )= 0 ; 366kv_printf (term -> termrequest_buffer ,"\x1b]%d;" ,command ); 367 } 368kv_concat_len (term -> termrequest_buffer ,frag .str ,frag .len ); 369if (frag .final ) { 370term -> termrequest_terminator = frag .terminator ; 371if (has_event (EVENT_TERMREQUEST )) { 372schedule_termrequest (term ); 373 } 374if (command == 8 ) { 375kv_push (term -> termrequest_buffer ,NUL ); 376const size_t off = STRLEN_LITERAL ("\x1b]8;" ); 377int attr = 0 ; 378if (parse_osc8 (term -> termrequest_buffer .items + off ,& attr )) { 379VTermState * state = vterm_obtain_state (term -> vt ); 380VTermValue value = { .number = attr }; 381vterm_state_set_penattr (state ,VTERM_ATTR_URI ,VTERM_VALUETYPE_INT ,& value ); 382 } 383 } 384 } 385return 1 ; 386} 387 388static int on_dcs (const char * command ,size_t commandlen ,VTermStringFragment frag ,void * user ) 389{ 390Terminal * term = user ; 391 392if (command == NULL || frag .str == NULL ) { 393return 0 ; 394 } 395if (!has_event (EVENT_TERMREQUEST )) { 396return 1 ; 397 } 398 399if (frag .initial ) { 400kv_size (term -> termrequest_buffer )= 0 ; 401kv_printf (term -> termrequest_buffer ,"\x1bP%.*s" , (int )commandlen ,command ); 402 } 403kv_concat_len (term -> termrequest_buffer ,frag .str ,frag .len ); 404if (frag .final ) { 405term -> termrequest_terminator = frag .terminator ; 406schedule_termrequest (term ); 407 } 408return 1 ; 409} 410 411static int on_apc (VTermStringFragment frag ,void * user ) 412{ 413Terminal * term = user ; 414if (frag .str == NULL || frag .len == 0 ) { 415return 0 ; 416 } 417 418if (!has_event (EVENT_TERMREQUEST )) { 419return 1 ; 420 } 421 422if (frag .initial ) { 423kv_size (term -> termrequest_buffer )= 0 ; 424kv_printf (term -> termrequest_buffer ,"\x1b_" ); 425 } 426kv_concat_len (term -> termrequest_buffer ,frag .str ,frag .len ); 427if (frag .final ) { 428term -> termrequest_terminator = frag .terminator ; 429schedule_termrequest (term ); 430 } 431return 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{ 446time_watcher_init (& main_loop ,& refresh_timer ,NULL ); 447// refresh_timer_cb will redraw the screen which can call vimscript 448refresh_timer .events = multiqueue_new_child (main_loop .events ); 449} 450 451void terminal_teardown (void ) 452{ 453time_watcher_stop (& refresh_timer ); 454multiqueue_free (refresh_timer .events ); 455time_watcher_close (& refresh_timer ,NULL ); 456set_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 459invalidated_terminals = (Set (ptr_t ))SET_INIT ; 460} 461 462static void term_output_callback (const char * s ,size_t len ,void * user_data ) 463{ 464terminal_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{ 476if (term -> sb_buffer != NULL ) { 477return true; 478 } 479if (buf == NULL ) { 480buf = handle_get_buffer (term -> buf_handle ); 481if (buf == NULL ) {// No need to allocate scrollback if buffer is deleted. 482return false; 483 } 484 } 485 486if (buf -> b_p_scbk < 1 ) { 487buf -> b_p_scbk = SB_MAX ; 488 } 489// Configure the scrollback buffer. 490term -> sb_size = (size_t )buf -> b_p_scbk ; 491term -> sb_buffer = xmalloc (sizeof (ScrollbackLine * )* term -> sb_size ); 492return 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 ) 507FUNC_ATTR_NONNULL_ALL 508{ 509// Create a new terminal instance and configure it 510Terminal * term = xcalloc (1 ,sizeof (Terminal )); 511term -> opts = opts ; 512 513// Associate the terminal instance with the new buffer 514term -> buf_handle = buf -> handle ; 515buf -> terminal = term ; 516// Create VTerm 517term -> vt = vterm_new (opts .height ,opts .width ); 518vterm_set_utf8 (term -> vt ,1 ); 519// Setup state 520VTermState * state = vterm_obtain_state (term -> vt ); 521// Set up screen 522term -> vts = vterm_obtain_screen (term -> vt ); 523vterm_screen_enable_altscreen (term -> vts , true); 524vterm_screen_enable_reflow (term -> vts , true); 525// delete empty lines at the end of the buffer 526vterm_screen_set_callbacks (term -> vts ,& vterm_screen_callbacks ,term ); 527vterm_screen_set_unrecognised_fallbacks (term -> vts ,& vterm_fallbacks ,term ); 528vterm_screen_set_damage_merge (term -> vts ,VTERM_DAMAGE_SCROLL ); 529vterm_screen_reset (term -> vts ,1 ); 530vterm_output_set_callback (term -> vt ,term_output_callback ,term ); 531 532term -> selection_buffer = xcalloc (SELECTIONBUF_SIZE ,1 ); 533vterm_state_set_selection_callbacks (state ,& vterm_selection_callbacks ,term , 534term -> selection_buffer ,SELECTIONBUF_SIZE ); 535 536VTermValue cursor_shape ; 537switch (shape_table [SHAPE_IDX_TERM ].shape ) { 538case SHAPE_BLOCK : 539cursor_shape .number = VTERM_PROP_CURSORSHAPE_BLOCK ; 540break ; 541case SHAPE_HOR : 542cursor_shape .number = VTERM_PROP_CURSORSHAPE_UNDERLINE ; 543break ; 544case SHAPE_VER : 545cursor_shape .number = VTERM_PROP_CURSORSHAPE_BAR_LEFT ; 546break ; 547 } 548vterm_state_set_termprop (state ,VTERM_PROP_CURSORSHAPE ,& cursor_shape ); 549 550VTermValue cursor_blink ; 551if (shape_table [SHAPE_IDX_TERM ].blinkon != 0 && shape_table [SHAPE_IDX_TERM ].blinkoff != 0 ) { 552cursor_blink .boolean = true; 553 }else { 554cursor_blink .boolean = false; 555 } 556vterm_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. 560term -> invalid_start = 0 ; 561term -> 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. 568term -> pending .events = multiqueue_new (NULL ,NULL ); 569 570if (!(buf -> b_ml .ml_flags & ML_EMPTY )) { 571linenr_T line_count = buf -> b_ml .ml_line_count ; 572while (!(buf -> b_ml .ml_flags & ML_EMPTY )) { 573ml_delete_buf (buf ,1 , false); 574 } 575deleted_lines_buf (buf ,1 ,line_count ); 576 } 577term -> old_height = 1 ; 578 579return 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 ) 587FUNC_ATTR_NONNULL_ALL 588{ 589Terminal * term = * termpp ; 590assert (term != NULL ); 591 592CtxSwitch aco = {0 }; 593ctx_switch (& aco ,NULL ,NULL ,buf ,0 ); 594 595if (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. 598refresh_scrollback (term ,buf ); 599 }else { 600assert (term -> invalid_start >=0 ); 601 } 602refresh_screen (term ,buf ); 603buf -> b_locked ++ ; 604set_option_value (kOptBuftype ,STATIC_CSTR_AS_OBJ ("terminal" ),OPT_LOCAL , true,NULL ); 605buf -> b_locked -- ; 606 607if (buf -> b_ffname != NULL ) { 608buf_set_term_title (buf ,buf -> b_ffname ,strlen (buf -> b_ffname )); 609 } 610RESET_BINDING (curwin ); 611// Reset cursor in current window. 612curwin -> 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. 618apply_autocmds (EVENT_TERMOPEN ,NULL ,NULL , false,buf ); 619 620ctx_restore (& aco ); 621 622if (* termpp == NULL || term -> buf_handle == 0 ) { 623return ;// Terminal has already been destroyed. 624 } 625 626// Local 'scrollback' _after_ autocmds. 627if (!term_may_alloc_scrollback (term ,buf )) { 628abort (); 629 } 630 631VTermState * 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 637for (int i = 0 ;i < 16 ;i ++ ) { 638char var [64 ]; 639snprintf (var ,sizeof (var ),"terminal_color_%d" ,i ); 640char * name = get_config_string (buf ,var ); 641if (name ) { 642int dummy ; 643RgbValue color_val = name_to_color (name ,& dummy ); 644 645if (color_val != -1 ) { 646VTermColor color ; 647vterm_color_rgb (& color , 648 (uint8_t )((color_val >>16 )& 0xFF ), 649 (uint8_t )((color_val >>8 )& 0xFF ), 650 (uint8_t )((color_val >>0 )& 0xFF )); 651vterm_state_set_palette_color (state ,i ,& color ); 652term -> 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 ) 662FUNC_ATTR_NONNULL_ALL 663{ 664Terminal * term = * termpp ; 665 666#ifdef EXITFREE 667if (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. 670terminal_destroy (termpp ); 671return ; 672 } 673#endif 674 675if (term -> destroy ) {// Destruction already scheduled on the main loop. 676return ; 677 } 678 679bool only_destroy = false; 680 681buf_T * buf = handle_get_buffer (term -> buf_handle ); 682 683if (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. 686only_destroy = true; 687 }else { 688// flush any pending changes to the buffer 689if (!exiting ) { 690block_autocmds (); 691refresh_terminal (term ); 692unblock_autocmds (); 693 } 694term -> closed = true; 695 } 696 697int pos = buf ?buf -> b_ml .ml_line_count - 1 :0 ; 698if (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. 704term -> buf_handle = 0 ; 705if (buf ) { 706buf -> terminal = NULL ; 707 } 708if (!term -> refcount ) { 709// Not inside Terminal mode event handling. 710// We should not wait for the user to press a key. 711term -> destroy = true; 712term -> 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. 718FOR_ALL_WINDOWS_IN_TAB (wp ,curtab ) { 719if (wp -> w_buffer == buf ) { 720wp -> w_redr_status = true; 721 } 722 } 723 724// Gets the line number to display "[Process exited]" virt text 725pos = MIN (row_to_linenr (term ,term -> cursor .row ),pos ); 726 } 727 728if (only_destroy ) { 729return ; 730 } 731 732if (status >=0 ) {// The job may have changed files on disk, like `do_shell` (":!cmd"). 733did_check_timestamps = false; 734need_check_timestamps = true; 735 } 736 737if (buf && !is_autocmd_blocked ()) { 738save_v_event_T save_v_event ; 739dict_T * dict = get_v_event (& save_v_event ); 740tv_dict_add_nr (dict ,S_LEN ("status" ),status ); 741tv_dict_set_keys_readonly (dict ); 742 743MAXSIZE_TEMP_DICT (data ,1 ); 744PUT_C (data ,"pos" ,INTEGER_OBJ (pos )); 745 746apply_autocmds_group (EVENT_TERMCLOSE ,NULL ,NULL ,status >=0 ,AUGROUP_ALL , 747buf ,curwin ,NULL ,& DICT_OBJ (data ), false); 748 749restore_v_event (dict ,& save_v_event ); 750 } 751} 752 753static void terminal_state_change_event (void ** argv ) 754{ 755handle_T buf_handle = (handle_T )(intptr_t )argv [0 ]; 756buf_T * buf = handle_get_buffer (buf_handle ); 757if (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. 762redraw_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 ) 768FUNC_ATTR_NONNULL_ALL 769{ 770if (term -> suspended != suspended ) { 771// Trigger a main loop iteration to redraw the buffer. 772multiqueue_put (refresh_timer .events ,terminal_state_change_event , 773 (void * )(intptr_t )term -> buf_handle ); 774 } 775term -> suspended = suspended ; 776} 777 778void terminal_check_size (Terminal * term ) 779FUNC_ATTR_NONNULL_ALL 780{ 781if (term -> closed ) { 782return ; 783 } 784 785int curwidth ,curheight ; 786vterm_get_size (term -> vt ,& curheight ,& curwidth ); 787uint16_t width = 0 ; 788uint16_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. 792FOR_ALL_TAB_WINDOWS (tp ,wp ) { 793if (is_ctx_win (wp )) { 794continue ; 795 } 796if (wp -> w_buffer && wp -> w_buffer -> terminal == term ) { 797const uint16_t win_width = 798 (uint16_t )(MAX (0 ,wp -> w_view_width - win_col_off (wp ))); 799width = MAX (width ,win_width ); 800height = (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. 806if ((curheight == height && curwidth == width )|| height == 0 || width == 0 ) { 807return ; 808 } 809 810vterm_set_size (term -> vt ,height ,width ); 811vterm_screen_flush_damage (term -> vts ); 812term -> pending .resize = true; 813invalidate_terminal (term ,-1 ,-1 ); 814} 815 816static void set_terminal_winopts (TerminalState * const s ) 817FUNC_ATTR_NONNULL_ALL 818{ 819assert (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 823s -> save_curwin_handle = curwin -> handle ; 824s -> save_w_p_cul = curwin -> w_p_cul ; 825s -> save_w_p_culopt = NULL ; 826s -> save_w_p_culopt_flags = curwin -> w_p_culopt_flags ; 827s -> save_w_p_cuc = curwin -> w_p_cuc ; 828s -> save_w_p_so = curwin -> w_p_so ; 829s -> save_w_p_siso = curwin -> w_p_siso ; 830 831if (curwin -> w_p_cul && curwin -> w_p_culopt_flags & kOptCuloptFlagNumber ) { 832if (!strequal (curwin -> w_p_culopt ,"number" )) { 833s -> save_w_p_culopt = curwin -> w_p_culopt ; 834curwin -> w_p_culopt = xstrdup ("number" ); 835 } 836curwin -> w_p_culopt_flags = kOptCuloptFlagNumber ; 837 }else { 838curwin -> w_p_cul = false; 839 } 840curwin -> w_p_cuc = false; 841curwin -> w_p_so = 0 ; 842curwin -> w_p_siso = 0 ; 843 844if (curwin -> w_p_cuc != s -> save_w_p_cuc ) { 845redraw_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 )) { 848redraw_later (curwin ,UPD_VALID ); 849 } 850} 851 852static void unset_terminal_winopts (TerminalState * const s ) 853FUNC_ATTR_NONNULL_ALL 854{ 855assert (s -> save_curwin_handle != 0 ); 856 857win_T * const wp = handle_get_window (s -> save_curwin_handle ); 858if (!wp ) { 859 gotoend ; 860 } 861 862winopt_T * winopts = NULL ; 863if (wp -> w_buffer -> handle != s -> term -> buf_handle ) {// Buffer no longer in "wp". 864buf_T * buf = handle_get_buffer (s -> term -> buf_handle ); 865if (buf == NULL ) { 866 gotoend ;// Nothing to restore as the buffer was deleted. 867 } 868for (size_t i = 0 ;i < kv_size (buf -> b_wininfo );i ++ ) { 869WinInfo * wip = kv_A (buf -> b_wininfo ,i ); 870if (wip -> wi_win == wp && wip -> wi_optset ) { 871winopts = & wip -> wi_opt ; 872break ; 873 } 874 } 875if (winopts == NULL ) { 876 gotoend ;// Nothing to restore as there is no matching WinInfo. 877 } 878 }else { 879winopts = & wp -> w_onebuf_opt ; 880if (win_valid (wp )) {// No need to redraw if window not in curtab. 881if (s -> save_w_p_cuc != wp -> w_p_cuc ) { 882redraw_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 )) { 885redraw_later (wp ,UPD_VALID ); 886 } 887 } 888wp -> w_p_culopt_flags = s -> save_w_p_culopt_flags ; 889 } 890 891if (s -> save_w_p_culopt ) { 892free_string_option (winopts -> wo_culopt ); 893winopts -> wo_culopt = s -> save_w_p_culopt ; 894s -> save_w_p_culopt = NULL ; 895 } 896winopts -> wo_cul = s -> save_w_p_cul ; 897winopts -> wo_cuc = s -> save_w_p_cuc ; 898winopts -> wo_so = s -> save_w_p_so ; 899winopts -> wo_siso = s -> save_w_p_siso ; 900 901end : 902free_string_option (s -> save_w_p_culopt ); 903s -> save_curwin_handle = 0 ; 904} 905 906/// Implements MODE_TERMINAL state. :help Terminal-mode 907bool terminal_enter (void ) 908{ 909buf_T * buf = curbuf ; 910assert (buf -> terminal );// Should only be called when curbuf has a terminal. 911TerminalState s [1 ]= {0 }; 912s -> term = buf -> terminal ; 913s -> cursor_visible = true;// Assume visible; may change via refresh_cursor later. 914Ins .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. 919terminal_check_size (s -> term ); 920 921atom_term_enter (); 922int save_state = State ; 923s -> save_rd = RedrawingDisabled ; 924State = MODE_TERMINAL ; 925mapped_ctrl_c |=MODE_TERMINAL ;// Always map CTRL-C to avoid interrupt. 926RedrawingDisabled = false; 927 928set_terminal_winopts (s ); 929 930s -> term -> pending .cursor = true;// Update the cursor shape table 931adjust_topline_cursor (s -> term ,buf ,0 );// scroll to end 932showmode (); 933ui_cursor_shape (); 934 935// Tell the terminal it has focus 936terminal_focus (s -> term , true); 937// Don't fire TextChangedT from changes in Normal mode. 938curbuf -> b_last_changedtick_i = buf_get_changedtick (curbuf ); 939 940// Don't let autocommands free the terminal now! 941s -> term -> refcount ++ ; 942apply_autocmds (EVENT_TERMENTER ,NULL ,NULL , false,curbuf ); 943may_trigger_modechanged (); 944s -> term -> refcount -- ; 945if (s -> term -> buf_handle == 0 ) { 946s -> close = true; 947 } 948 949s -> state .execute = terminal_execute ; 950s -> state .check = terminal_check ; 951state_enter (& s -> state ); 952 953if (!s -> got_bsl_o ) { 954restart_edit = 0 ; 955 } 956State = save_state ; 957RedrawingDisabled = s -> save_rd ; 958if (!s -> cursor_visible ) { 959// If cursor was hidden, show it again. Do so right after restoring State. 960ui_busy_stop (); 961 } 962 963// Restore the terminal cursor to what is set in 'guicursor' 964 (void )parse_shape_opt (SHAPE_CURSOR ); 965 966unset_terminal_winopts (s ); 967 968// Tell the terminal it lost focus 969terminal_focus (s -> term , false); 970// Don't fire TextChanged from changes in terminal mode. 971curbuf -> b_last_changedtick = buf_get_changedtick (curbuf ); 972 973if (curbuf -> terminal == s -> term && !s -> close ) { 974terminal_check_cursor (); 975 } 976if (restart_edit ) { 977showmode (); 978 }else { 979unshowmode (true); 980 } 981ui_cursor_shape (); 982 983// If we're to close the terminal, don't let TermLeave autocommands free it first! 984if (s -> close ) { 985s -> term -> refcount ++ ; 986 } 987apply_autocmds (EVENT_TERMLEAVE ,NULL ,NULL , false,curbuf ); 988if (s -> close ) { 989s -> term -> refcount -- ; 990const handle_T buf_handle = s -> term -> buf_handle ;// Callback may free s->term. 991s -> term -> destroy = true; 992s -> term -> opts .close_cb (s -> term -> opts .data ); 993if (buf_handle != 0 ) { 994do_buffer (DOBUF_WIPE ,DOBUF_FIRST ,FORWARD ,buf_handle , true); 995 } 996 } 997 998return s -> got_bsl_o ; 999} 1000 1001static void terminal_check_cursor (void ) 1002{ 1003Terminal * term = curbuf -> terminal ; 1004curwin -> w_cursor .lnum = MIN (curbuf -> b_ml .ml_line_count , 1005row_to_linenr (term ,term -> cursor .row )); 1006const 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. 1008if (topline != curwin -> w_topline ) { 1009set_topline (curwin ,topline ); 1010 } 1011if (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. 1014curwin -> w_cursor = (pos_T ){ .lnum = curbuf -> b_ml .ml_line_count }; 1015 }else { 1016// Nudge cursor when returning to normal-mode. 1017int off = (State & MODE_TERMINAL ) ?0 : (curwin -> w_p_rl ?1 :-1 ); 1018coladvance (curwin ,MAX (0 ,term -> cursor .col + off )); 1019 } 1020} 1021 1022static bool terminal_check_focus (TerminalState * const s ) 1023FUNC_ATTR_NONNULL_ALL 1024{ 1025if (curbuf -> terminal == NULL ) { 1026return false; 1027 } 1028 1029if (s -> save_curwin_handle != curwin -> handle ) { 1030// Terminal window changed, update window options. 1031unset_terminal_winopts (s ); 1032set_terminal_winopts (s ); 1033 } 1034if (s -> term != curbuf -> terminal ) { 1035// Active terminal changed, flush terminal's cursor state to the UI. 1036terminal_focus (s -> term , false); 1037if (s -> close ) { 1038s -> term -> destroy = true; 1039s -> term -> opts .close_cb (s -> term -> opts .data ); 1040s -> close = false; 1041 } 1042 1043s -> term = curbuf -> terminal ; 1044s -> term -> pending .cursor = true; 1045invalidate_terminal (s -> term ,-1 ,-1 ); 1046terminal_focus (s -> term , true); 1047 } 1048return 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{ 1058TerminalState * const s = (TerminalState * )state ; 1059 1060// Shouldn't reach here when pressing a key to close the terminal buffer. 1061assert (!s -> close || (s -> term -> buf_handle == 0 && s -> term != curbuf -> terminal )); 1062 1063if (Ins .stop_insert_mode || !terminal_check_focus (s )) { 1064return 0 ; 1065 } 1066 1067terminal_check_refresh (); 1068 1069// Validate topline and cursor position for autocommands. Especially important for WinScrolled. 1070terminal_check_cursor (); 1071validate_cursor (curwin ); 1072 1073// Don't let autocommands free the terminal from under our fingers. 1074s -> term -> refcount ++ ; 1075if (has_event (EVENT_TEXTCHANGEDT ) 1076&& curbuf -> b_last_changedtick_i != buf_get_changedtick (curbuf )) { 1077apply_autocmds (EVENT_TEXTCHANGEDT ,NULL ,NULL , false,curbuf ); 1078curbuf -> b_last_changedtick_i = buf_get_changedtick (curbuf ); 1079 } 1080may_trigger_win_scrolled_resized (); 1081s -> term -> refcount -- ; 1082if (s -> term -> buf_handle == 0 ) { 1083s -> close = true; 1084 } 1085 1086// Autocommands above may have changed focus, scrolled, or moved the cursor. 1087if (!terminal_check_focus (s )) { 1088return 0 ; 1089 } 1090terminal_check_cursor (); 1091validate_cursor (curwin ); 1092 1093show_cursor_info_later (false); 1094if (must_redraw ) { 1095update_screen (); 1096 }else { 1097redraw_statuslines (); 1098if (clear_cmdline || redraw_cmdline || redraw_mode ) { 1099showmode ();// clear cmdline and show mode 1100 } 1101 } 1102 1103setcursor (); 1104refresh_cursor (s -> term ,& s -> cursor_visible ); 1105ui_flush (); 1106return 1 ; 1107} 1108 1109/// Processes one char of terminal-mode input. 1110static int terminal_execute (VimState * state ,int key ) 1111{ 1112TerminalState * 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. 1116int tmp_mod_mask = mod_mask ; 1117int mod_key = merge_modifiers (key ,& tmp_mod_mask ); 1118 1119switch (mod_key ) { 1120case K_LEFTMOUSE : 1121case K_LEFTDRAG : 1122case K_LEFTRELEASE : 1123case K_MIDDLEMOUSE : 1124case K_MIDDLEDRAG : 1125case K_MIDDLERELEASE : 1126case K_RIGHTMOUSE : 1127case K_RIGHTDRAG : 1128case K_RIGHTRELEASE : 1129case K_X1MOUSE : 1130case K_X1DRAG : 1131case K_X1RELEASE : 1132case K_X2MOUSE : 1133case K_X2DRAG : 1134case K_X2RELEASE : 1135case K_MOUSEDOWN : 1136case K_MOUSEUP : 1137case K_MOUSELEFT : 1138case K_MOUSERIGHT : 1139case K_MOUSEMOVE : 1140if (send_mouse_event (s -> term ,key )) { 1141return 0 ; 1142 } 1143break ; 1144 1145case K_PASTE_START : 1146paste_repeat (1 ); 1147break ; 1148 1149case K_EVENT : 1150// We cannot let an event free the terminal yet. It is still needed. 1151s -> term -> refcount ++ ; 1152state_handle_k_event (); 1153s -> term -> refcount -- ; 1154if (s -> term -> buf_handle == 0 ) { 1155s -> close = true; 1156 } 1157break ; 1158 1159case K_COMMAND : 1160do_cmdline (NULL ,getcmdkeycmd ,NULL ,0 ); 1161break ; 1162 1163case K_LUA : 1164map_execute_lua (false, false); 1165break ; 1166 1167case K_IGNORE : 1168case K_NOP : 1169// Do not interrupt a Ctrl-\ sequence or close a finished terminal. 1170break ; 1171 1172case Ctrl_N : 1173if (s -> got_bsl ) { 1174return 0 ; 1175 } 1176FALLTHROUGH ; 1177 1178case Ctrl_O : 1179if (s -> got_bsl ) { 1180s -> got_bsl_o = true; 1181restart_edit = 'I' ; 1182return 0 ; 1183 } 1184FALLTHROUGH ; 1185 1186default : 1187if (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. 1191got_int = false; 1192 } 1193if (mod_key == Ctrl_BSL && !s -> got_bsl ) { 1194s -> got_bsl = true; 1195break ; 1196 } 1197if (s -> term -> suspended ) { 1198s -> 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. 1201terminal_set_state (s -> term , false); 1202break ; 1203 } 1204if (s -> term -> closed ) { 1205s -> close = true; 1206return 0 ; 1207 } 1208 1209s -> got_bsl = false; 1210terminal_send_key (s -> term ,key ); 1211 } 1212 1213return 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 ) 1219FUNC_ATTR_NONNULL_ALL 1220{ 1221Terminal * term = * termpp ; 1222buf_T * buf = handle_get_buffer (term -> buf_handle ); 1223if (buf ) { 1224term -> buf_handle = 0 ; 1225buf -> terminal = NULL ; 1226 } 1227 1228if (!term -> refcount ) { 1229if (set_has (ptr_t ,& invalidated_terminals ,term )) { 1230// flush any pending changes to the buffer 1231block_autocmds (); 1232refresh_terminal (term ); 1233unblock_autocmds (); 1234set_del (ptr_t ,& invalidated_terminals ,term ); 1235 } 1236for (size_t i = 0 ;i < term -> sb_current ;i ++ ) { 1237xfree (term -> sb_buffer [i ]); 1238 } 1239xfree (term -> sb_buffer ); 1240xfree (term -> title ); 1241xfree (term -> selection_buffer ); 1242kv_destroy (term -> selection ); 1243kv_destroy (term -> termrequest_buffer ); 1244vterm_free (term -> vt ); 1245multiqueue_free (term -> pending .events ); 1246xfree (term ); 1247* termpp = NULL ;// coverity[dead-store] 1248 } 1249} 1250 1251static void terminal_send (Terminal * term ,const char * data ,size_t size ) 1252{ 1253if (term -> closed ) { 1254return ; 1255 } 1256if (term -> pending .send ) { 1257kv_concat_len (* term -> pending .send ,data ,size ); 1258return ; 1259 } 1260term -> opts .write_cb (data ,size ,term -> opts .data ); 1261} 1262 1263static bool is_filter_char (int c ) 1264{ 1265unsigned flag = 0 ; 1266switch (c ) { 1267case 0x08 : 1268flag = kOptTpfFlagBS ; 1269break ; 1270case 0x09 : 1271flag = kOptTpfFlagHT ; 1272break ; 1273case 0x0A : 1274case 0x0D : 1275break ; 1276case 0x0C : 1277flag = kOptTpfFlagFF ; 1278break ; 1279case 0x1b : 1280flag = kOptTpfFlagESC ; 1281break ; 1282case 0x7F : 1283flag = kOptTpfFlagDEL ; 1284break ; 1285default : 1286if (c < ' ' ) { 1287flag = kOptTpfFlagC0 ; 1288 }else if (c >=0x80 && c <=0x9F ) { 1289flag = kOptTpfFlagC1 ; 1290 } 1291 } 1292return !!(tpf_flags & flag ); 1293} 1294 1295void terminal_set_streamed_paste (Terminal * term ,bool streamed ) 1296FUNC_ATTR_NONNULL_ALL 1297{ 1298if (term -> streamed_paste != streamed ) { 1299if (streamed ) { 1300vterm_keyboard_start_paste (curbuf -> terminal -> vt ); 1301 }else { 1302vterm_keyboard_end_paste (curbuf -> terminal -> vt ); 1303 } 1304 } 1305term -> streamed_paste = streamed ; 1306} 1307 1308void terminal_paste (int count ,String * y_array ,size_t y_size ) 1309{ 1310if (y_size == 0 ) { 1311return ; 1312 } 1313if (!curbuf -> terminal -> streamed_paste ) { 1314vterm_keyboard_start_paste (curbuf -> terminal -> vt ); 1315 } 1316size_t buff_len = y_array [0 ].size ; 1317char * buff = xmalloc (buff_len ); 1318for (int i = 0 ;i < count ;i ++ ) { 1319// feed the lines to the terminal 1320for (size_t j = 0 ;j < y_size ;j ++ ) { 1321if (j ) { 1322// terminate the previous line 1323#ifdef MSWIN 1324terminal_send (curbuf -> terminal ,"\r\n" ,2 ); 1325#else 1326terminal_send (curbuf -> terminal ,"\n" ,1 ); 1327#endif 1328 } 1329size_t len = y_array [j ].size ; 1330if (len > buff_len ) { 1331buff = xrealloc (buff ,len ); 1332buff_len = len ; 1333 } 1334char * dst = buff ; 1335char * src = y_array [j ].data ; 1336while (* src != NUL ) { 1337len = (size_t )utf_ptr2len (src ); 1338int c = utf_ptr2char (src ); 1339if (!is_filter_char (c )) { 1340memcpy (dst ,src ,len ); 1341dst += len ; 1342 } 1343src += len ; 1344 } 1345terminal_send (curbuf -> terminal ,buff , (size_t )(dst - buff )); 1346 } 1347 } 1348xfree (buff ); 1349if (!curbuf -> terminal -> streamed_paste ) { 1350vterm_keyboard_end_paste (curbuf -> terminal -> vt ); 1351 } 1352} 1353 1354static void terminal_send_key (Terminal * term ,int c ) 1355{ 1356VTermModifier mod = VTERM_MOD_NONE ; 1357 1358// Convert K_ZERO back to ASCII 1359if (c == K_ZERO ) { 1360c = Ctrl_AT ; 1361 } 1362 1363VTermKey key = convert_key (& c ,mod_mask ,& mod ); 1364 1365if (key != VTERM_KEY_NONE ) { 1366vterm_keyboard_key (term -> vt ,key ,mod ); 1367 }else if (!IS_SPECIAL (c )) { 1368vterm_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{ 1376if (exiting ) { 1377return ; 1378 } 1379handle_T buf_handle = (handle_T )(intptr_t )argv [0 ]; 1380buf_T * buf = handle_get_buffer (buf_handle ); 1381if (!buf || !buf -> terminal ) { 1382return ; 1383 } 1384block_autocmds (); 1385refresh_terminal (buf -> terminal ); 1386unblock_autocmds (); 1387} 1388 1389void terminal_receive (Terminal * term ,const char * data ,size_t len ) 1390{ 1391if (!data ) { 1392return ; 1393 } 1394 1395if (term -> opts .force_crlf ) { 1396StringBuilder crlf_data = KV_INITIAL_VALUE ; 1397 1398for (size_t i = 0 ;i < len ;i ++ ) { 1399if (data [i ]== '\n' && (i == 0 || (i > 0 && data [i - 1 ]!= '\r' ))) { 1400kv_push (crlf_data ,'\r' ); 1401 } 1402kv_push (crlf_data ,data [i ]); 1403 } 1404 1405vterm_input_write (term -> vt ,crlf_data .items ,kv_size (crlf_data )); 1406kv_destroy (crlf_data ); 1407 }else { 1408vterm_input_write (term -> vt ,data ,len ); 1409 } 1410vterm_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. 1415if (term -> sync_flush_pending ) { 1416term -> 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. 1420int height ; 1421vterm_get_size (term -> vt ,& height ,NULL ); 1422term -> invalid_start = 0 ; 1423term -> invalid_end = height ; 1424multiqueue_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{ 1431vterm_state_convert_color_to_rgb (state ,& color ); 1432return RGB_ (color .rgb .red ,color .rgb .green ,color .rgb .blue ); 1433} 1434 1435static int get_underline_hl_flag (VTermScreenCellAttrs attrs ) 1436{ 1437switch (attrs .underline ) { 1438case VTERM_UNDERLINE_OFF : 1439return 0 ; 1440case VTERM_UNDERLINE_SINGLE : 1441return HL_UNDERLINE ; 1442case VTERM_UNDERLINE_DOUBLE : 1443return HL_UNDERDOUBLE ; 1444case VTERM_UNDERLINE_CURLY : 1445return HL_UNDERCURL ; 1446default : 1447return HL_UNDERLINE ; 1448 } 1449} 1450 1451void terminal_get_line_attributes (Terminal * term ,win_T * wp ,int linenr ,int * term_attrs ) 1452{ 1453int height ,width ; 1454vterm_get_size (term -> vt ,& height ,& width ); 1455VTermState * state = vterm_obtain_state (term -> vt ); 1456assert (linenr ); 1457int row = linenr_to_row (term ,linenr ); 1458if (row >=height ) { 1459// Terminal height was decreased but the change wasn't reflected into the 1460// buffer yet 1461return ; 1462 } 1463 1464width = MIN (TERM_ATTRS_MAX ,width ); 1465for (int col = 0 ;col < width ;col ++ ) { 1466VTermScreenCell cell ; 1467bool color_valid = fetch_cell (term ,row ,col ,& cell ); 1468bool fg_default = !color_valid || VTERM_COLOR_IS_DEFAULT_FG (& cell .fg ); 1469bool bg_default = !color_valid || VTERM_COLOR_IS_DEFAULT_BG (& cell .bg ); 1470 1471// Get the rgb value set by libvterm. 1472int vt_fg = fg_default ?-1 :get_rgb (state ,cell .fg ); 1473int vt_bg = bg_default ?-1 :get_rgb (state ,cell .bg ); 1474 1475bool fg_indexed = VTERM_COLOR_IS_INDEXED (& cell .fg ); 1476bool bg_indexed = VTERM_COLOR_IS_INDEXED (& cell .bg ); 1477 1478int16_t vt_fg_idx = ((!fg_default && fg_indexed ) ?cell .fg .indexed .idx + 1 :0 ); 1479int16_t vt_bg_idx = ((!bg_default && bg_indexed ) ?cell .bg .indexed .idx + 1 :0 ); 1480 1481bool fg_set = vt_fg_idx && vt_fg_idx <=16 && term -> color_set [vt_fg_idx - 1 ]; 1482bool bg_set = vt_bg_idx && vt_bg_idx <=16 && term -> color_set [vt_bg_idx - 1 ]; 1483 1484int 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 1496int attr_id = 0 ; 1497 1498if (hl_attrs || !fg_default || !bg_default ) { 1499attr_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 1512if (cell .uri > 0 ) { 1513attr_id = hl_combine_attr (attr_id ,cell .uri ); 1514 } 1515 1516term_attrs [col ]= attr_id ; 1517 } 1518} 1519 1520Buffer terminal_buf (const Terminal * term ) 1521FUNC_ATTR_NONNULL_ALL 1522{ 1523return term -> buf_handle ; 1524} 1525 1526bool terminal_running (const Terminal * term ) 1527FUNC_ATTR_NONNULL_ALL 1528{ 1529return !term -> closed ; 1530} 1531 1532bool terminal_suspended (const Terminal * term ) 1533FUNC_ATTR_NONNULL_ALL 1534{ 1535return term -> suspended ; 1536} 1537 1538void terminal_notify_theme (Terminal * term ,bool dark ) 1539FUNC_ATTR_NONNULL_ALL 1540{ 1541if (!term -> theme_updates ) { 1542return ; 1543 } 1544 1545char buf [10 ]; 1546ssize_t ret = snprintf (buf ,sizeof (buf ),"\x1b[997;%cn" ,dark ?'1' :'2' ); 1547assert (ret > 0 ); 1548assert ((size_t )ret <=sizeof (buf )); 1549terminal_send (term ,buf , (size_t )ret ); 1550} 1551 1552static void terminal_focus (const Terminal * term ,bool focus ) 1553FUNC_ATTR_NONNULL_ALL 1554{ 1555VTermState * state = vterm_obtain_state (term -> vt ); 1556if (focus ) { 1557vterm_state_focus_in (state ); 1558 }else { 1559vterm_state_focus_out (state ); 1560 } 1561} 1562 1563// }}} 1564// libvterm callbacks {{{ 1565 1566static int term_damage (VTermRect rect ,void * data ) 1567{ 1568invalidate_terminal (data ,rect .start_row ,rect .end_row ); 1569return 1 ; 1570} 1571 1572static int term_moverect (VTermRect dest ,VTermRect src ,void * data ) 1573{ 1574invalidate_terminal (data ,MIN (dest .start_row ,src .start_row ), 1575MAX (dest .end_row ,src .end_row )); 1576return 1 ; 1577} 1578 1579static int term_movecursor (VTermPos new_pos ,VTermPos old_pos ,int visible ,void * data ) 1580{ 1581Terminal * term = data ; 1582term -> cursor .row = new_pos .row ; 1583term -> cursor .col = new_pos .col ; 1584invalidate_terminal (term ,-1 ,-1 ); 1585return 1 ; 1586} 1587 1588static void buf_set_term_title (buf_T * buf ,const char * title ,size_t len ) 1589{ 1590if (!buf ) { 1591return ;// In case of receiving OSC 2 between buffer close and job exit. 1592 } 1593 1594Error err = ERROR_INIT ; 1595buf -> b_locked ++ ; 1596dict_set_var (buf -> b_vars , 1597STATIC_CSTR_AS_STRING ("term_title" ), 1598STRING_OBJ (((String ){ .data = (char * )title , .size = len })), 1599 false, 1600 false, 1601NULL , 1602& err ); 1603buf -> b_locked -- ; 1604api_clear_error (& err ); 1605status_redraw_buf (buf ); 1606} 1607 1608static int term_settermprop (VTermProp prop ,VTermValue * val ,void * data ) 1609{ 1610Terminal * term = data ; 1611 1612switch (prop ) { 1613case VTERM_PROP_ALTSCREEN : 1614term -> in_altscreen = val -> boolean ; 1615break ; 1616 1617case VTERM_PROP_CURSORVISIBLE : 1618term -> cursor .visible = val -> boolean ; 1619invalidate_terminal (term ,-1 ,-1 ); 1620break ; 1621 1622case VTERM_PROP_TITLE : { 1623buf_T * buf = handle_get_buffer (term -> buf_handle );// May be NULL 1624VTermStringFragment frag = val -> string ; 1625 1626if (frag .initial && frag .final ) { 1627buf_set_term_title (buf ,frag .str ,frag .len ); 1628break ; 1629 } 1630 1631if (frag .initial ) { 1632term -> title_len = 0 ; 1633term -> title_size = MAX (frag .len ,1024 ); 1634term -> title = xmalloc (sizeof (char * )* term -> title_size ); 1635 }else if (term -> title_len + frag .len > term -> title_size ) { 1636term -> title_size *=2 ; 1637term -> title = xrealloc (term -> title ,sizeof (char * )* term -> title_size ); 1638 } 1639 1640memcpy (term -> title + term -> title_len ,frag .str ,frag .len ); 1641term -> title_len += frag .len ; 1642 1643if (frag .final ) { 1644buf_set_term_title (buf ,term -> title ,term -> title_len ); 1645xfree (term -> title ); 1646term -> title = NULL ; 1647 } 1648break ; 1649 } 1650 1651case VTERM_PROP_MOUSE : 1652term -> forward_mouse = (bool )val -> number ; 1653break ; 1654 1655case VTERM_PROP_CURSORBLINK : 1656term -> cursor .blink = val -> boolean ; 1657term -> pending .cursor = true; 1658invalidate_terminal (term ,-1 ,-1 ); 1659break ; 1660 1661case VTERM_PROP_CURSORSHAPE : 1662term -> cursor .shape = val -> number ; 1663term -> pending .cursor = true; 1664invalidate_terminal (term ,-1 ,-1 ); 1665break ; 1666 1667case VTERM_PROP_THEMEUPDATES : 1668term -> theme_updates = val -> boolean ; 1669break ; 1670 1671case VTERM_PROP_SYNCOUTPUT : 1672term -> synchronized_output = val -> boolean ; 1673if (!val -> boolean ) { 1674// Mark that sync just ended; terminal_receive() will flush 1675// the buffer immediately rather than waiting for the 10ms timer. 1676term -> sync_flush_pending = true; 1677 } 1678break ; 1679 1680default : 1681return 0 ; 1682 } 1683 1684return 1 ; 1685} 1686 1687/// Called when the terminal wants to ring the system bell. 1688static int term_bell (void * data ) 1689{ 1690vim_beep (kOptBoFlagTerm ); 1691return 1 ; 1692} 1693 1694/// Called when the terminal wants to query the system theme. 1695static int term_theme (bool * dark ,void * data ) 1696FUNC_ATTR_NONNULL_ALL 1697{ 1698* dark = (* p_bg == 'd' ); 1699return 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{ 1708Terminal * term = data ; 1709 1710if (!term_may_alloc_scrollback (term ,NULL )) { 1711return 0 ; 1712 } 1713assert (term -> sb_size > 0 ); 1714 1715// copy vterm cells into sb_buffer 1716size_t c = (size_t )cols ; 1717ScrollbackLine * sbrow = NULL ; 1718if (term -> sb_current == term -> sb_size ) { 1719if (term -> sb_buffer [term -> sb_current - 1 ]-> cols == c ) { 1720// Recycle old row if it's the right size 1721sbrow = term -> sb_buffer [term -> sb_current - 1 ]; 1722 }else { 1723xfree (term -> sb_buffer [term -> sb_current - 1 ]); 1724 } 1725term -> sb_deleted ++ ; 1726 1727// Make room at the start by shifting to the right. 1728memmove (term -> sb_buffer + 1 ,term -> sb_buffer , 1729sizeof (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. 1732memmove (term -> sb_buffer + 1 ,term -> sb_buffer , 1733sizeof (term -> sb_buffer [0 ])* term -> sb_current ); 1734 } 1735 1736if (!sbrow ) { 1737sbrow = xmalloc (sizeof (ScrollbackLine )+ c * sizeof (sbrow -> cells [0 ])); 1738sbrow -> cols = c ; 1739 } 1740 1741// New row is added at the start of the storage buffer. 1742term -> sb_buffer [0 ]= sbrow ; 1743if (term -> sb_current < term -> sb_size ) { 1744term -> sb_current ++ ; 1745 } 1746 1747if (term -> sb_pending < (int )term -> sb_size ) { 1748term -> sb_pending ++ ; 1749 } 1750 1751memcpy (sbrow -> cells ,cells ,sizeof (cells [0 ])* c ); 1752if (!term -> synchronized_output ) { 1753set_put (ptr_t ,& invalidated_terminals ,term ); 1754 } 1755 1756return 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{ 1766Terminal * term = data ; 1767 1768if (!term -> sb_current ) { 1769return 0 ; 1770 } 1771 1772if (term -> sb_pending > 0 ) { 1773term -> sb_pending -- ; 1774 }else { 1775term -> old_height ++ ; 1776 } 1777 1778ScrollbackLine * sbrow = term -> sb_buffer [0 ]; 1779term -> sb_current -- ; 1780// Forget the "popped" row by shifting the rest onto it. 1781memmove (term -> sb_buffer ,term -> sb_buffer + 1 , 1782sizeof (term -> sb_buffer [0 ])* (term -> sb_current )); 1783 1784size_t cols_to_copy = MIN ((size_t )cols ,sbrow -> cols ); 1785 1786// copy to vterm state 1787memcpy (cells ,sbrow -> cells ,sizeof (cells [0 ])* cols_to_copy ); 1788for (size_t col = cols_to_copy ;col < (size_t )cols ;col ++ ) { 1789cells [col ].schar = 0 ; 1790cells [col ].width = 1 ; 1791 } 1792 1793xfree (sbrow ); 1794if (!term -> synchronized_output ) { 1795set_put (ptr_t ,& invalidated_terminals ,term ); 1796 } 1797 1798return 1 ; 1799} 1800 1801static int term_sb_clear (void * data ) 1802{ 1803Terminal * term = data ; 1804 1805if (term -> in_altscreen || !term -> sb_size || !term -> sb_current ) { 1806return 1 ; 1807 } 1808 1809for (size_t i = 0 ;i < term -> sb_current ;i ++ ) { 1810xfree (term -> sb_buffer [i ]); 1811 } 1812 1813term -> sb_deleted += term -> sb_current ; 1814term -> sb_current = 0 ; 1815term -> sb_pending = 0 ; 1816invalidate_terminal (term ,-1 ,-1 ); 1817 1818return 1 ; 1819} 1820 1821static void term_clipboard_set (void ** argv ) 1822{ 1823VTermSelectionMask mask = (VTermSelectionMask )(long )argv [0 ]; 1824char * data = argv [1 ]; 1825 1826char regname ; 1827switch (mask ) { 1828case VTERM_SELECTION_CLIPBOARD : 1829regname = '+' ; 1830break ; 1831case VTERM_SELECTION_PRIMARY : 1832regname = '*' ; 1833break ; 1834default : 1835regname = '+' ; 1836break ; 1837 } 1838 1839// Split the payload into readfile()-style list (:h chansend()). 1840// TODO(justinmk): drop this, support Blob in clipboard provider: #41097 1841list_T * lines = tv_list_alloc (kListLenMayKnow ); 1842char * start = data ; 1843char * end ; 1844while ((end = strchr (start ,'\n' ))!= NULL ) { 1845tv_list_append_string (lines ,start ,end - start ); 1846start = end + 1 ; 1847 } 1848tv_list_append_string (lines ,start ,-1 ); 1849xfree (data ); 1850 1851list_T * args = tv_list_alloc (3 ); 1852tv_list_append_list (args ,lines ); 1853 1854const char regtype = 'v' ; 1855tv_list_append_string (args ,& regtype ,1 ); 1856 1857tv_list_append_string (args ,& regname ,1 ); 1858eval_call_provider ("clipboard" ,"set" ,args , true); 1859} 1860 1861static int term_selection_set (VTermSelectionMask mask ,VTermStringFragment frag ,void * user ) 1862{ 1863Terminal * term = user ; 1864if (frag .initial ) { 1865kv_size (term -> selection )= 0 ; 1866 } 1867 1868kv_concat_len (term -> selection ,frag .str ,frag .len ); 1869 1870if (frag .final ) { 1871char * data = xmemdupz (term -> selection .items ,kv_size (term -> selection )); 1872multiqueue_put (main_loop .events ,term_clipboard_set , (void * )mask ,data ); 1873 } 1874 1875return 1 ; 1876} 1877 1878// }}} 1879// input handling {{{ 1880 1881static void convert_modifiers (int * key ,int modifiers ,VTermModifier * statep ) 1882{ 1883if (modifiers & MOD_MASK_SHIFT ) { 1884* statep |=VTERM_MOD_SHIFT ; 1885 } 1886if (modifiers & MOD_MASK_CTRL ) { 1887* statep |=VTERM_MOD_CTRL ; 1888if (!(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 } 1893if (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 ); 1901convert_modifiers (key ,modifiers ,statep ); 1902 1903switch (* key ) { 1904case K_BS : 1905return VTERM_KEY_BACKSPACE ; 1906case K_TAB : 1907case TAB : 1908return VTERM_KEY_TAB ; 1909case Ctrl_M : 1910return VTERM_KEY_ENTER ; 1911case ESC : 1912return VTERM_KEY_ESCAPE ; 1913 1914case K_UP : 1915return VTERM_KEY_UP ; 1916case K_DOWN : 1917return VTERM_KEY_DOWN ; 1918case K_LEFT : 1919return VTERM_KEY_LEFT ; 1920case K_RIGHT : 1921return VTERM_KEY_RIGHT ; 1922 1923case K_INS : 1924return VTERM_KEY_INS ; 1925case K_DEL : 1926return VTERM_KEY_DEL ; 1927case K_HOME : 1928return VTERM_KEY_HOME ; 1929case K_END : 1930return VTERM_KEY_END ; 1931case K_PAGEUP : 1932return VTERM_KEY_PAGEUP ; 1933case K_PAGEDOWN : 1934return VTERM_KEY_PAGEDOWN ; 1935 1936case K_K0 : 1937case K_KINS : 1938return VTERM_KEY_KP_0 ; 1939case K_K1 : 1940case K_KEND : 1941return VTERM_KEY_KP_1 ; 1942case K_K2 : 1943case K_KDOWN : 1944return VTERM_KEY_KP_2 ; 1945case K_K3 : 1946case K_KPAGEDOWN : 1947return VTERM_KEY_KP_3 ; 1948case K_K4 : 1949case K_KLEFT : 1950return VTERM_KEY_KP_4 ; 1951case K_K5 : 1952case K_KORIGIN : 1953return VTERM_KEY_KP_5 ; 1954case K_K6 : 1955case K_KRIGHT : 1956return VTERM_KEY_KP_6 ; 1957case K_K7 : 1958case K_KHOME : 1959return VTERM_KEY_KP_7 ; 1960case K_K8 : 1961case K_KUP : 1962return VTERM_KEY_KP_8 ; 1963case K_K9 : 1964case K_KPAGEUP : 1965return VTERM_KEY_KP_9 ; 1966case K_KDEL : 1967case K_KPOINT : 1968return VTERM_KEY_KP_PERIOD ; 1969case K_KENTER : 1970return VTERM_KEY_KP_ENTER ; 1971case K_KPLUS : 1972return VTERM_KEY_KP_PLUS ; 1973case K_KMINUS : 1974return VTERM_KEY_KP_MINUS ; 1975case K_KMULTIPLY : 1976return VTERM_KEY_KP_MULT ; 1977case K_KDIVIDE : 1978return VTERM_KEY_KP_DIVIDE ; 1979 1980case K_F1 : 1981return VTERM_KEY_FUNCTION (1 ); 1982case K_F2 : 1983return VTERM_KEY_FUNCTION (2 ); 1984case K_F3 : 1985return VTERM_KEY_FUNCTION (3 ); 1986case K_F4 : 1987return VTERM_KEY_FUNCTION (4 ); 1988case K_F5 : 1989return VTERM_KEY_FUNCTION (5 ); 1990case K_F6 : 1991return VTERM_KEY_FUNCTION (6 ); 1992case K_F7 : 1993return VTERM_KEY_FUNCTION (7 ); 1994case K_F8 : 1995return VTERM_KEY_FUNCTION (8 ); 1996case K_F9 : 1997return VTERM_KEY_FUNCTION (9 ); 1998case K_F10 : 1999return VTERM_KEY_FUNCTION (10 ); 2000case K_F11 : 2001return VTERM_KEY_FUNCTION (11 ); 2002case K_F12 : 2003return VTERM_KEY_FUNCTION (12 ); 2004 2005case K_F13 : 2006return VTERM_KEY_FUNCTION (13 ); 2007case K_F14 : 2008return VTERM_KEY_FUNCTION (14 ); 2009case K_F15 : 2010return VTERM_KEY_FUNCTION (15 ); 2011case K_F16 : 2012return VTERM_KEY_FUNCTION (16 ); 2013case K_F17 : 2014return VTERM_KEY_FUNCTION (17 ); 2015case K_F18 : 2016return VTERM_KEY_FUNCTION (18 ); 2017case K_F19 : 2018return VTERM_KEY_FUNCTION (19 ); 2019case K_F20 : 2020return VTERM_KEY_FUNCTION (20 ); 2021case K_F21 : 2022return VTERM_KEY_FUNCTION (21 ); 2023case K_F22 : 2024return VTERM_KEY_FUNCTION (22 ); 2025case K_F23 : 2026return VTERM_KEY_FUNCTION (23 ); 2027case K_F24 : 2028return VTERM_KEY_FUNCTION (24 ); 2029case K_F25 : 2030return VTERM_KEY_FUNCTION (25 ); 2031case K_F26 : 2032return VTERM_KEY_FUNCTION (26 ); 2033case K_F27 : 2034return VTERM_KEY_FUNCTION (27 ); 2035case K_F28 : 2036return VTERM_KEY_FUNCTION (28 ); 2037case K_F29 : 2038return VTERM_KEY_FUNCTION (29 ); 2039case K_F30 : 2040return VTERM_KEY_FUNCTION (30 ); 2041case K_F31 : 2042return VTERM_KEY_FUNCTION (31 ); 2043case K_F32 : 2044return VTERM_KEY_FUNCTION (32 ); 2045case K_F33 : 2046return VTERM_KEY_FUNCTION (33 ); 2047case K_F34 : 2048return VTERM_KEY_FUNCTION (34 ); 2049case K_F35 : 2050return VTERM_KEY_FUNCTION (35 ); 2051case K_F36 : 2052return VTERM_KEY_FUNCTION (36 ); 2053case K_F37 : 2054return VTERM_KEY_FUNCTION (37 ); 2055case K_F38 : 2056return VTERM_KEY_FUNCTION (38 ); 2057case K_F39 : 2058return VTERM_KEY_FUNCTION (39 ); 2059case K_F40 : 2060return VTERM_KEY_FUNCTION (40 ); 2061case K_F41 : 2062return VTERM_KEY_FUNCTION (41 ); 2063case K_F42 : 2064return VTERM_KEY_FUNCTION (42 ); 2065case K_F43 : 2066return VTERM_KEY_FUNCTION (43 ); 2067case K_F44 : 2068return VTERM_KEY_FUNCTION (44 ); 2069case K_F45 : 2070return VTERM_KEY_FUNCTION (45 ); 2071case K_F46 : 2072return VTERM_KEY_FUNCTION (46 ); 2073case K_F47 : 2074return VTERM_KEY_FUNCTION (47 ); 2075case K_F48 : 2076return VTERM_KEY_FUNCTION (48 ); 2077case K_F49 : 2078return VTERM_KEY_FUNCTION (49 ); 2079case K_F50 : 2080return VTERM_KEY_FUNCTION (50 ); 2081case K_F51 : 2082return VTERM_KEY_FUNCTION (51 ); 2083case K_F52 : 2084return VTERM_KEY_FUNCTION (52 ); 2085case K_F53 : 2086return VTERM_KEY_FUNCTION (53 ); 2087case K_F54 : 2088return VTERM_KEY_FUNCTION (54 ); 2089case K_F55 : 2090return VTERM_KEY_FUNCTION (55 ); 2091case K_F56 : 2092return VTERM_KEY_FUNCTION (56 ); 2093case K_F57 : 2094return VTERM_KEY_FUNCTION (57 ); 2095case K_F58 : 2096return VTERM_KEY_FUNCTION (58 ); 2097case K_F59 : 2098return VTERM_KEY_FUNCTION (59 ); 2099case K_F60 : 2100return VTERM_KEY_FUNCTION (60 ); 2101case K_F61 : 2102return VTERM_KEY_FUNCTION (61 ); 2103case K_F62 : 2104return VTERM_KEY_FUNCTION (62 ); 2105case K_F63 : 2106return VTERM_KEY_FUNCTION (63 ); 2107 2108default : 2109return VTERM_KEY_NONE ; 2110 } 2111} 2112 2113static void mouse_action (Terminal * term ,int button ,int row ,int col ,bool pressed , 2114VTermModifier mod ) 2115{ 2116vterm_mouse_move (term -> vt ,row ,col ,mod ); 2117if (button ) { 2118vterm_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{ 2126int row = mouse_row ; 2127int col = mouse_col ; 2128int grid = mouse_grid ; 2129win_T * mouse_win = mouse_find_win_inner (& grid ,& row ,& col ); 2130if (mouse_win == NULL ) { 2131 gotoend ; 2132 } 2133 2134int offset ; 2135if (!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 2142int button ; 2143bool pressed = false; 2144 2145switch (c ) { 2146case K_LEFTDRAG : 2147case K_LEFTMOUSE : 2148pressed = true;FALLTHROUGH ; 2149case K_LEFTRELEASE : 2150button = 1 ;break ; 2151case K_MIDDLEDRAG : 2152case K_MIDDLEMOUSE : 2153pressed = true;FALLTHROUGH ; 2154case K_MIDDLERELEASE : 2155button = 2 ;break ; 2156case K_RIGHTDRAG : 2157case K_RIGHTMOUSE : 2158pressed = true;FALLTHROUGH ; 2159case K_RIGHTRELEASE : 2160button = 3 ;break ; 2161case K_X1DRAG : 2162case K_X1MOUSE : 2163pressed = true;FALLTHROUGH ; 2164case K_X1RELEASE : 2165button = 8 ;break ; 2166case K_X2DRAG : 2167case K_X2MOUSE : 2168pressed = true;FALLTHROUGH ; 2169case K_X2RELEASE : 2170button = 9 ;break ; 2171case K_MOUSEDOWN : 2172pressed = true;button = 4 ;break ; 2173case K_MOUSEUP : 2174pressed = true;button = 5 ;break ; 2175case K_MOUSELEFT : 2176pressed = true;button = 7 ;break ; 2177case K_MOUSERIGHT : 2178pressed = true;button = 6 ;break ; 2179case K_MOUSEMOVE : 2180button = 0 ;break ; 2181default : 2182return false; 2183 } 2184 2185VTermModifier mod = VTERM_MOD_NONE ; 2186convert_modifiers (& c ,mod_mask ,& mod ); 2187mouse_action (term ,button ,row ,col - offset ,pressed ,mod ); 2188return false; 2189 } 2190 2191if (c == K_MOUSEUP || c == K_MOUSEDOWN || c == K_MOUSELEFT || c == K_MOUSERIGHT ) { 2192win_T * save_curwin = curwin ; 2193// switch window/buffer to perform the scroll 2194curwin = mouse_win ; 2195curbuf = curwin -> w_buffer ; 2196 2197cmdarg_T cap ; 2198oparg_T oa ; 2199CLEAR_FIELD (cap ); 2200clear_oparg (& oa ); 2201cap .oap = & oa ; 2202 2203switch (cap .cmdchar = c ) { 2204case K_MOUSEUP : 2205cap .arg = MSCR_UP ; 2206break ; 2207case K_MOUSEDOWN : 2208cap .arg = MSCR_DOWN ; 2209break ; 2210case K_MOUSELEFT : 2211cap .arg = MSCR_LEFT ; 2212break ; 2213case K_MOUSERIGHT : 2214cap .arg = MSCR_RIGHT ; 2215break ; 2216default : 2217abort (); 2218 } 2219 2220// Call the common mouse scroll function shared with other modes. 2221do_mousescroll (& cap ); 2222 2223curwin -> w_redr_status = true; 2224curwin = save_curwin ; 2225curbuf = curwin -> w_buffer ; 2226redraw_later (mouse_win ,UPD_NOT_VALID ); 2227invalidate_terminal (term ,-1 ,-1 ); 2228// Only need to exit focus if the scrolled window is the terminal window 2229return 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. 2235if ((c == K_LEFTRELEASE && mouse_win != NULL && mouse_win -> w_buffer -> terminal == term ) 2236|| c == K_MOUSEMOVE ) { 2237return false; 2238 } 2239 2240requeue_key (vgetc_char ,vgetc_mod_mask ,0 , true); 2241return true; 2242} 2243 2244// }}} 2245// terminal buffer refresh & misc {{{ 2246 2247static void fetch_row (Terminal * term ,int row ,int end_col ) 2248{ 2249int col = 0 ; 2250size_t line_len = 0 ; 2251char * ptr = term -> textbuf ; 2252 2253while (col < end_col ) { 2254VTermScreenCell cell ; 2255fetch_cell (term ,row ,col ,& cell ); 2256if (cell .schar ) { 2257schar_get_adv (& ptr ,cell .schar ); 2258line_len = (size_t )(ptr - term -> textbuf ); 2259 }else { 2260* ptr ++ = ' ' ; 2261 } 2262col += cell .width ; 2263 } 2264 2265// end of line 2266term -> textbuf [line_len ]= NUL ; 2267} 2268 2269static bool fetch_cell (Terminal * term ,int row ,int col ,VTermScreenCell * cell ) 2270{ 2271if (row < 0 ) { 2272ScrollbackLine * sbrow = term -> sb_buffer [- row - 1 ]; 2273if ((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 }; 2281return false; 2282 } 2283 }else { 2284vterm_screen_get_cell (term -> vts , (VTermPos ){ .row = row , .col = col }, 2285cell ); 2286 } 2287return true; 2288} 2289 2290// queue a terminal instance for refresh 2291static void invalidate_terminal (Terminal * term ,int start_row ,int end_row ) 2292{ 2293if (start_row != -1 && end_row != -1 ) { 2294term -> invalid_start = MIN (term -> invalid_start ,start_row ); 2295term -> 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. 2300if (term -> synchronized_output ) { 2301return ; 2302 } 2303 2304set_put (ptr_t ,& invalidated_terminals ,term ); 2305if (!refresh_pending ) { 2306time_watcher_start (& refresh_timer ,refresh_timer_cb ,REFRESH_DELAY ,0 ); 2307refresh_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{ 2316multiqueue_process_events (refresh_timer .events ); 2317} 2318 2319static void refresh_terminal (Terminal * term ) 2320{ 2321buf_T * buf = handle_get_buffer (term -> buf_handle ); 2322if (!buf ) { 2323// Destroyed by `buf_freeall()`. Do not do anything else. 2324return ; 2325 } 2326linenr_T ml_before = buf -> b_ml .ml_line_count ; 2327 2328bool resized = refresh_size (term ,buf ); 2329refresh_scrollback (term ,buf ); 2330refresh_screen (term ,buf ); 2331 2332int ml_added = buf -> b_ml .ml_line_count - ml_before ; 2333adjust_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. 2337if (resized ) { 2338FOR_ALL_TAB_WINDOWS (tp ,wp ) { 2339if (wp -> w_buffer == buf && wp -> w_leftcol != 0 ) { 2340wp -> w_leftcol = 0 ; 2341curs_columns (wp , true); 2342 } 2343 } 2344 } 2345 2346// Copy pending events back to the main event queue 2347multiqueue_move_events (main_loop .events ,term -> pending .events ); 2348} 2349 2350static void refresh_cursor (Terminal * term ,bool * cursor_visible ) 2351FUNC_ATTR_NONNULL_ALL 2352{ 2353if (!is_focused (term )) { 2354return ; 2355 } 2356if (term -> cursor .visible != * cursor_visible ) { 2357* cursor_visible = term -> cursor .visible ; 2358if (* cursor_visible ) { 2359ui_busy_stop (); 2360 }else { 2361ui_busy_start (); 2362 } 2363 } 2364 2365if (!term -> pending .cursor ) { 2366return ; 2367 } 2368term -> pending .cursor = false; 2369 2370if (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. 2374shape_table [SHAPE_IDX_TERM ].blinkon = 500 ; 2375shape_table [SHAPE_IDX_TERM ].blinkoff = 500 ; 2376 }else { 2377shape_table [SHAPE_IDX_TERM ].blinkon = 0 ; 2378shape_table [SHAPE_IDX_TERM ].blinkoff = 0 ; 2379 } 2380 2381switch (term -> cursor .shape ) { 2382case VTERM_PROP_CURSORSHAPE_BLOCK : 2383shape_table [SHAPE_IDX_TERM ].shape = SHAPE_BLOCK ; 2384break ; 2385case VTERM_PROP_CURSORSHAPE_UNDERLINE : 2386shape_table [SHAPE_IDX_TERM ].shape = SHAPE_HOR ; 2387shape_table [SHAPE_IDX_TERM ].percentage = 20 ; 2388break ; 2389case VTERM_PROP_CURSORSHAPE_BAR_LEFT : 2390shape_table [SHAPE_IDX_TERM ].shape = SHAPE_VER ; 2391shape_table [SHAPE_IDX_TERM ].percentage = 25 ; 2392break ; 2393 } 2394 2395ui_mode_info_set (); 2396} 2397 2398/// Calls refresh_terminal() on all invalidated_terminals. 2399static void refresh_timer_cb (TimeWatcher * watcher ,void * data ) 2400{ 2401refresh_pending = false; 2402if (exiting ) {// Cannot redraw (requires event loop) during teardown/exit. 2403return ; 2404 } 2405 2406// Don't process autocommands while updating terminal buffers. 2407block_autocmds (); 2408// Refreshing one terminal may poll for output to another, which should not 2409// interfere with the set_foreach() below. 2410Set (ptr_t )to_refresh = invalidated_terminals ; 2411invalidated_terminals = (Set (ptr_t ))SET_INIT ; 2412 2413Terminal * term ; 2414set_foreach (& to_refresh ,term , { 2415// Skip terminals in synchronized output — they will be refreshed 2416// when the synchronized update ends (mode 2026 reset). 2417if (!term -> synchronized_output ) { 2418refresh_terminal (term ); 2419 } 2420 }); 2421 2422set_destroy (ptr_t ,& to_refresh ); 2423unblock_autocmds (); 2424} 2425 2426static bool refresh_size (Terminal * term ,buf_T * buf ) 2427{ 2428if (!term -> pending .resize || term -> closed ) { 2429return false; 2430 } 2431 2432term -> pending .resize = false; 2433int width ,height ; 2434vterm_get_size (term -> vt ,& height ,& width ); 2435term -> invalid_start = 0 ; 2436term -> invalid_end = height ; 2437term -> opts .resize_cb ((uint16_t )width , (uint16_t )height ,term -> opts .data ); 2438return 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. 2444if (term -> sb_buffer != NULL ) { 2445refresh_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{ 2452if (buf -> b_p_scbk < 1 ) {// Local 'scrollback' was set to -1. 2453buf -> b_p_scbk = SB_MAX ; 2454 } 2455const size_t scbk = (size_t )buf -> b_p_scbk ; 2456assert (term -> sb_current < SIZE_MAX ); 2457if (term -> sb_pending > 0 ) {// Pending rows must be processed first. 2458abort (); 2459 } 2460 2461// Delete lines exceeding the new 'scrollback' limit. 2462if (scbk < term -> sb_current ) { 2463size_t diff = term -> sb_current - scbk ; 2464for (size_t i = 0 ;i < diff ;i ++ ) { 2465ml_delete_buf (buf ,1 , false); 2466term -> sb_current -- ; 2467xfree (term -> sb_buffer [term -> sb_current ]); 2468 } 2469mark_adjust_buf (buf ,1 , (linenr_T )diff ,MAXLNUM ,- (linenr_T )diff , true, 2470kMarkAdjustTerm ,kExtmarkUndo ); 2471deleted_lines_buf (buf ,1 , (linenr_T )diff ); 2472 } 2473 2474// Resize the scrollback storage. 2475size_t sb_region = sizeof (ScrollbackLine * )* scbk ; 2476if (scbk != term -> sb_size ) { 2477term -> sb_buffer = xrealloc (term -> sb_buffer ,sb_region ); 2478 } 2479 2480term -> 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. 2488term -> opts .read_pause_cb (true,term -> opts .data ); 2489 2490linenr_T deleted = (linenr_T )(term -> sb_deleted - term -> old_sb_deleted ); 2491deleted = MIN (deleted ,buf -> b_ml .ml_line_count ); 2492mark_adjust_buf (buf ,1 ,deleted ,MAXLNUM ,- deleted , true,kMarkAdjustTerm ,kExtmarkUndo ); 2493term -> old_sb_deleted = term -> sb_deleted ; 2494 2495int old_height = term -> old_height ; 2496int width ,height ; 2497vterm_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(). 2501while (deleted > 0 && buf -> b_ml .ml_line_count > old_height ) { 2502ml_delete_buf (buf ,1 , false); 2503deleted_lines_buf (buf ,1 ,1 ); 2504deleted -- ; 2505 } 2506 2507// Clamp old_height in case buffer lines have been deleted by the user. 2508old_height = MIN (old_height ,buf -> b_ml .ml_line_count ); 2509while (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. 2514fetch_row (term ,- term -> sb_pending ,width ); 2515int buf_index = buf -> b_ml .ml_line_count - old_height ; 2516ml_append_buf (buf ,buf_index ,term -> textbuf ,0 , false); 2517appended_lines_buf (buf ,buf_index ,1 ); 2518term -> sb_pending -- ; 2519 } 2520 2521int max_line_count = (int )term -> sb_current + height ; 2522// Remove extra lines at the bottom. 2523while (buf -> b_ml .ml_line_count > max_line_count ) { 2524ml_delete_buf (buf ,buf -> b_ml .ml_line_count , false); 2525deleted_lines_buf (buf ,buf -> b_ml .ml_line_count ,1 ); 2526 } 2527 2528adjust_scrollback (term ,buf ); 2529 2530term -> 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{ 2537int changed = 0 ; 2538int added = 0 ; 2539int height ; 2540int width ; 2541vterm_get_size (term -> vt ,& height ,& width ); 2542// Terminal height may have decreased before `invalid_end` reflects it. 2543term -> invalid_end = MIN (term -> invalid_end ,height ); 2544 2545// There are no invalid rows. 2546if (term -> invalid_start >=term -> invalid_end ) { 2547term -> invalid_start = INT_MAX ; 2548term -> invalid_end = -1 ; 2549return ; 2550 } 2551 2552for (int r = term -> invalid_start ,linenr = row_to_linenr (term ,r ); 2553r < term -> invalid_end ;r ++ ,linenr ++ ) { 2554fetch_row (term ,r ,width ); 2555 2556if (linenr <=buf -> b_ml .ml_line_count ) { 2557ml_replace_buf (buf ,linenr ,term -> textbuf , true, false); 2558changed ++ ; 2559 }else { 2560ml_append_buf (buf ,linenr - 1 ,term -> textbuf ,0 , false); 2561added ++ ; 2562 } 2563 } 2564term -> old_height = height ; 2565 2566int change_start = row_to_linenr (term ,term -> invalid_start ); 2567int change_end = change_start + changed ; 2568term -> invalid_start = INT_MAX ; 2569term -> 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. 2572changed_lines (buf ,change_start ,0 ,change_end ,added , true); 2573} 2574 2575static void adjust_topline_cursor (Terminal * term ,buf_T * buf ,int added ) 2576{ 2577linenr_T ml_end = buf -> b_ml .ml_line_count ; 2578 2579FOR_ALL_TAB_WINDOWS (tp ,wp ) { 2580if (wp -> w_buffer == buf ) { 2581if (wp == curwin && is_focused (term )) { 2582// Move window cursor to terminal cursor's position and "follow" output. 2583terminal_check_cursor (); 2584continue ; 2585 } 2586 2587bool following = ml_end == wp -> w_cursor .lnum + added ;// cursor at end? 2588if (following ) { 2589// "Follow" the terminal output 2590wp -> w_cursor .lnum = ml_end ; 2591set_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. 2594wp -> w_cursor .lnum = MIN (wp -> w_cursor .lnum ,ml_end ); 2595 } 2596mb_check_adjust_col (wp ); 2597 } 2598 } 2599 2600if (ml_end == buf -> b_last_cursor .mark .lnum + added ) { 2601buf -> b_last_cursor .mark .lnum = ml_end ; 2602 } 2603 2604for (size_t i = 0 ;i < kv_size (buf -> b_wininfo );i ++ ) { 2605WinInfo * wip = kv_A (buf -> b_wininfo ,i ); 2606if (ml_end == wip -> wi_mark .mark .lnum + added ) { 2607wip -> wi_mark .mark .lnum = ml_end ; 2608 } 2609 } 2610} 2611 2612static int row_to_linenr (Terminal * term ,int row ) 2613{ 2614return row != INT_MAX ?row + (int )term -> sb_current + 1 :INT_MAX ; 2615} 2616 2617static int linenr_to_row (Terminal * term ,int linenr ) 2618{ 2619return linenr - (int )term -> sb_current - 1 ; 2620} 2621 2622static bool is_focused (Terminal * term ) 2623{ 2624return State & MODE_TERMINAL && curbuf -> terminal == term ; 2625} 2626 2627static char * get_config_string (buf_T * buf ,char * key ) 2628{ 2629Error err = ERROR_INIT ; 2630Object obj = dict_get_value (buf -> b_vars ,cstr_as_string (key ),NULL ,& err ); 2631api_clear_error (& err ); 2632if (obj .type == kObjectTypeNil ) { 2633obj = dict_get_value (get_globvar_dict (),cstr_as_string (key ),NULL ,& err ); 2634api_clear_error (& err ); 2635 } 2636if (obj .type == kObjectTypeString ) { 2637return obj .data .string .data ; 2638 } 2639api_free_object (obj ); 2640return NULL ; 2641} 2642 2643// }}} 2644 2645// vim: foldmethod=marker