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