robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1#include <assert.h> 2#include <inttypes.h> 3#include <lauxlib.h> 4#include <limits.h> 5#include <stdbool.h> 6#include <stddef.h> 7#include <stdio.h> 8#include <stdlib.h> 9#include <string.h> 10 11#include "klib/kvec.h" 12#include "nvim/api/buffer.h" 13#include "nvim/api/deprecated.h" 14#include "nvim/api/keysets_defs.h" 15#include "nvim/api/private/converter.h" 16#include "nvim/api/private/defs.h" 17#include "nvim/api/private/dispatch.h" 18#include "nvim/api/private/helpers.h" 19#include "nvim/api/private/validate.h" 20#include "nvim/api/vim.h" 21#include "nvim/ascii_defs.h" 22#include "nvim/autocmd.h" 23#include "nvim/autocmd_defs.h" 24#include "nvim/buffer.h" 25#include "nvim/buffer_defs.h" 26#include "nvim/channel.h" 27#include "nvim/channel_defs.h" 28#include "nvim/context.h" 29#include "nvim/cursor.h" 30#include "nvim/decoration.h" 31#include "nvim/drawline.h" 32#include "nvim/drawscreen.h" 33#include "nvim/errors.h" 34#include "nvim/eval.h" 35#include "nvim/eval/typval.h" 36#include "nvim/eval/typval_defs.h" 37#include "nvim/eval/vars.h" 38#include "nvim/ex_docmd.h" 39#include "nvim/ex_eval.h" 40#include "nvim/fold.h" 41#include "nvim/globals.h" 42#include "nvim/grid.h" 43#include "nvim/grid_defs.h" 44#include "nvim/highlight.h" 45#include "nvim/highlight_defs.h" 46#include "nvim/highlight_group.h" 47#include "nvim/input.h" 48#include "nvim/input_defs.h" 49#include "nvim/insert.h" 50#include "nvim/insexpand.h" 51#include "nvim/keycodes.h" 52#include "nvim/log.h" 53#include "nvim/lua/executor.h" 54#include "nvim/lua/treesitter.h" 55#include "nvim/macros_defs.h" 56#include "nvim/mapping.h" 57#include "nvim/mark.h" 58#include "nvim/mark_defs.h" 59#include "nvim/math.h" 60#include "nvim/mbyte.h" 61#include "nvim/mcursor.h" 62#include "nvim/memline.h" 63#include "nvim/memory.h" 64#include "nvim/memory_defs.h" 65#include "nvim/message.h" 66#include "nvim/message_defs.h" 67#include "nvim/move.h" 68#include "nvim/msgpack_rpc/channel.h" 69#include "nvim/msgpack_rpc/channel_defs.h" 70#include "nvim/msgpack_rpc/unpacker.h" 71#include "nvim/normal.h" 72#include "nvim/option.h" 73#include "nvim/option_defs.h" 74#include "nvim/option_vars.h" 75#include "nvim/optionstr.h" 76#include "nvim/os/input.h" 77#include "nvim/os/os_defs.h" 78#include "nvim/os/proc.h" 79#include "nvim/popupmenu.h" 80#include "nvim/pos_defs.h" 81#include "nvim/register.h" 82#include "nvim/runtime.h" 83#include "nvim/sign_defs.h" 84#include "nvim/state.h" 85#include "nvim/statusline.h" 86#include "nvim/statusline_defs.h" 87#include "nvim/terminal.h" 88#include "nvim/types_defs.h" 89#include "nvim/ui.h" 90#include "nvim/vim_defs.h" 91#include "nvim/window.h" 92 93#include "api/vim.c.generated.h" 94 95/// Gets a highlight group by name 96/// 97/// similar to |hlID()|, but allocates a new ID if not present. 98/// @param[out] err Error details, if any 99Integer nvim_get_hl_id_by_name (String name ,Error * err ) 100FUNC_API_SINCE (7 ) 101{ 102int ret ; 103TRY_WRAP (err , { 104ret = syn_check_group (name .data ,name .size ); 105 }); 106return ret ; 107} 108 109/// Gets all or specific highlight groups in a namespace. 110/// 111/// @note When the `link` attribute is defined in the highlight definition 112/// map, other attributes will not be taking effect (see |:hi-link|). 113/// 114/// @param ns_id Get highlight groups for namespace ns_id |nvim_get_namespaces()|. 115/// Use 0 to get global highlight groups |:highlight|. 116/// @param opts Options dict: 117/// - create: (boolean, default true) When highlight group doesn't exist create it. 118/// - id: (integer) Get a highlight definition by id. 119/// - link: (boolean, default true) Show linked group name instead of effective definition |:hi-link|. 120/// - name: (string) Get a highlight definition by name. 121/// 122/// @param[out] err Error details, if any. 123/// @return Highlight groups as a map from group name to a highlight definition map as in |nvim_set_hl()|, 124/// or only a single highlight definition map if requested by name or id. 125DictAs (get_hl_info )nvim_get_hl (Integer ns_id ,Dict (get_highlight )* opts ,Arena * arena ,Error * err ) 126FUNC_API_SINCE (11 ) 127{ 128return ns_get_hl_defs ((NS )ns_id ,opts ,arena ,err ); 129} 130 131/// Sets a highlight group. By default, replaces the entire definition (e.g. `nvim_set_hl(0, 'Visual', {})` 132/// will clear the "Visual" group), unless `update` is specified. 133/// 134/// @note The fg and bg keys also accept the string values `"fg"` or `"bg"` 135/// which act as aliases to the corresponding foreground and background 136/// values of the Normal group. If the Normal group has not been defined, 137/// using these values results in an error. 138/// 139/// @note If `link` is used in combination with other attributes; only the 140/// `link` will take effect (see |:hi-link|). 141/// 142/// @param ns_id Namespace id for this highlight |nvim_create_namespace()|. 143/// Use 0 to set a highlight group globally |:highlight|. 144/// Highlights from non-global namespaces are not active by default, use 145/// |nvim_set_hl_ns()| or |nvim_win_set_hl_ns()| to activate them. 146/// @param name Highlight group name, e.g. "ErrorMsg" 147/// @param val Highlight definition map, accepts the following keys: 148/// - altfont: boolean 149/// - bg: color name or "#RRGGBB", see note. 150/// - bg_indexed: boolean. If true, `bg` is an RGB approximation of `ctermbg` 151/// (a palette index). UIs rendering cterm natively may prefer `ctermbg`. 152/// - blend: integer between 0 and 100 153/// - blink: boolean 154/// - bold: boolean 155/// - conceal: boolean Concealment at the UI level (terminal SGR), unrelated to |:syn-conceal|. 156/// - cterm: cterm attribute map, like |highlight-args|. If not set, cterm attributes 157/// will match those from the attribute map documented above. 158/// - ctermbg: Sets background of cterm color |ctermbg| 159/// - ctermfg: Sets foreground of cterm color |ctermfg| 160/// - default: boolean Don't override existing definition |:hi-default| 161/// - dim: boolean 162/// - fg: Color name or "#RRGGBB", see note. 163/// - fg_indexed: boolean. Same as `bg_indexed`, for `fg` and `ctermfg`. 164/// - font: GUI font name (string). Sets |highlight-font|. Use "NONE" to clear. 165/// - force: (boolean, default: false) Update the highlight group even if it already exists. 166/// - italic: boolean 167/// - link: Name of highlight group to link to. |:hi-link| 168/// - link_global: Like "link", but always resolved in the global namespace (ns=0). 169/// - nocombine: boolean 170/// - overline: boolean 171/// - reverse: boolean 172/// - sp: Color name or "#RRGGBB" 173/// - standout: boolean 174/// - strikethrough: boolean 175/// - undercurl: boolean 176/// - underdashed: boolean 177/// - underdotted: boolean 178/// - underdouble: boolean 179/// - underline: boolean 180/// - update: (boolean, default: false) Update specified attributes only, leave others unchanged. 181/// @param[out] err Error details, if any 182void nvim_set_hl (uint64_t channel_id ,Integer ns_id ,String name ,Dict (highlight )* val ,Error * err ) 183FUNC_API_SINCE (7 ) 184{ 185int hl_id ; 186TRY_WRAP (err , { 187hl_id = syn_check_group (name .data ,name .size ); 188 }); 189if (ERROR_SET (err )|| hl_id == 0 ) { 190return ; 191 } 192int link_id = -1 ; 193 194// Setting URLs directly through highlight attributes is not supported 195if (HAS_KEY (val ,highlight ,url )) { 196api_set_error (err ,kErrorTypeValidation ,"Invalid key: 'url'" ); 197return ; 198 } 199 200bool update = HAS_KEY (val ,highlight ,update )&& val -> update ; 201HlAttrs * base = NULL ; 202HlAttrs base_attrs ; 203if (update && hl_ns_get_attrs ((int )ns_id ,hl_id ,NULL ,& base_attrs )) { 204base = & base_attrs ; 205 } 206 207HlAttrs attrs = dict2hlattrs (val , true,& link_id ,base ,err ); 208if (!ERROR_SET (err )) { 209WITH_SCRIPT_CONTEXT (channel_id , { 210ns_hl_def ((NS )ns_id ,hl_id ,attrs ,link_id ,val ); 211 }); 212 } 213} 214 215/// Gets the active highlight namespace. 216/// 217/// @param opts Optional parameters 218/// - winid: (number) |window-ID| for retrieving a window's highlight 219/// namespace. A value of -1 is returned when |nvim_win_set_hl_ns()| 220/// has not been called for the window (or was called with a namespace 221/// of -1). 222/// @param[out] err Error details, if any 223/// @return Namespace id, or -1 224Integer nvim_get_hl_ns (Dict (get_ns )* opts ,Error * err ) 225FUNC_API_SINCE (12 ) 226{ 227if (HAS_KEY (opts ,get_ns ,winid )) { 228win_T * win = find_window_by_handle (opts -> winid ,err ); 229if (!win ) { 230return 0 ; 231 } 232return win -> w_ns_hl ; 233 }else { 234return ns_hl_global ; 235 } 236} 237 238/// Set active namespace for highlights defined with |nvim_set_hl()|. This can be set for 239/// a single window, see |nvim_win_set_hl_ns()|. 240/// 241/// @param ns_id the namespace to use 242/// @param[out] err Error details, if any 243void nvim_set_hl_ns (Integer ns_id ,Error * err ) 244FUNC_API_SINCE (10 ) 245{ 246VALIDATE_INT ((ns_id >=0 ),"namespace" ,ns_id , { 247return ; 248 }); 249 250ns_hl_global = (NS )ns_id ; 251hl_check_ns (); 252redraw_all_later (UPD_NOT_VALID ); 253} 254 255/// Set active namespace for highlights defined with |nvim_set_hl()| while redrawing. 256/// 257/// This function is meant to be called while redrawing, primarily from 258/// |nvim_set_decoration_provider()| on_win and on_line callbacks, which 259/// are allowed to change the namespace during a redraw cycle. 260/// 261/// @param ns_id the namespace to activate 262/// @param[out] err Error details, if any 263void nvim_set_hl_ns_fast (Integer ns_id ,Error * err ) 264FUNC_API_SINCE (10 ) 265FUNC_API_FAST 266{ 267ns_hl_fast = (NS )ns_id ; 268hl_check_ns (); 269} 270 271/// Sends input-keys to Nvim, subject to various quirks controlled by `mode` flags. This is 272/// a blocking call, unlike |nvim_input()|. 273/// 274/// On execution error: does not fail, but updates v:errmsg. 275/// 276/// To input keycodes like [<C-o>], pass the result of |nvim_replace_termcodes()|: 277/// 278/// ```vim 279/// :let key = nvim_replace_termcodes('<C-o>', v:true, v:false, v:true) 280/// :call nvim_feedkeys(key, 'n', v:false) 281/// ``` 282/// 283/// @param keys Keys to send as input. 284/// @param mode Behavior flags, see |feedkeys()|. 285/// @param escape_ks If true, escape K_SPECIAL bytes in `keys`. Should be false if you used 286/// |nvim_replace_termcodes()|, else true. 287/// @see feedkeys() 288/// @see vim_strsave_escape_ks 289void nvim_feedkeys (String keys ,String mode ,Boolean escape_ks ) 290FUNC_API_SINCE (1 ) 291{ 292bool remap = true; 293bool insert = false; 294bool typed = false; 295bool execute = false; 296bool dangerous = false; 297bool lowlevel = false; 298 299for (size_t i = 0 ;i < mode .size ;i ++ ) { 300switch (mode .data [i ]) { 301case 'n' : 302remap = false;break ; 303case 'm' : 304remap = true;break ; 305case 't' : 306typed = true;break ; 307case 'i' : 308insert = true;break ; 309case 'x' : 310execute = true;break ; 311case '!' : 312dangerous = true;break ; 313case 'L' : 314lowlevel = true;break ; 315 } 316 } 317 318if (keys .size == 0 && !execute ) { 319return ; 320 } 321 322char * keys_esc ; 323if (escape_ks ) { 324// Need to escape K_SPECIAL before putting the string in the 325// typeahead buffer. 326keys_esc = vim_strsave_escape_ks (keys .data ); 327 }else { 328keys_esc = keys .data ; 329 } 330if (lowlevel ) { 331input_enqueue_raw (keys_esc ,strlen (keys_esc )); 332 }else { 333ins_typebuf (keys_esc , (remap ?REMAP_YES :REMAP_NONE ), 334insert ?0 :typebuf .tb_len , !typed , false); 335if (vgetc_busy ) { 336typebuf_was_filled = true; 337 } 338 } 339 340if (escape_ks ) { 341xfree (keys_esc ); 342 } 343 344if (execute ) { 345int save_msg_scroll = msg_scroll ; 346 347// Avoid a 1 second delay when the keys start Insert mode. 348msg_scroll = false; 349if (!dangerous ) { 350ex_normal_busy ++ ; 351 } 352exec_normal (true,lowlevel ); 353if (!dangerous ) { 354ex_normal_busy -- ; 355 } 356msg_scroll |=save_msg_scroll ; 357 } 358} 359 360/// Queues raw user-input. Unlike |nvim_feedkeys()|, this uses a low-level input buffer and the call 361/// is non-blocking (input is processed asynchronously by the eventloop). 362/// 363/// To input blocks of text, |nvim_paste()| is much faster and should be preferred. 364/// 365/// On execution error: does not fail, but updates v:errmsg. 366/// 367/// @note |keycodes| like [<CR>] are translated, so "<" is special. 368/// To input a literal "<", send [<LT>]. 369/// 370/// @note For mouse events use |nvim_input_mouse()|. The pseudokey form 371/// `<LeftMouse><col,row>` is deprecated since |api-level| 6. 372/// 373/// @param keys to be typed 374/// @return Number of bytes actually written (can be fewer than 375/// requested if the buffer becomes full). 376Integer nvim_input (uint64_t channel_id ,String keys ) 377FUNC_API_SINCE (1 )FUNC_API_FAST 378{ 379may_trigger_vim_suspend_resume (false); 380return (Integer )input_enqueue (channel_id ,keys ); 381} 382 383/// Send mouse event from GUI. 384/// 385/// Non-blocking: does not wait on any result, but queues the event to be 386/// processed soon by the event loop. 387/// 388/// @note Currently this doesn't support "scripting" multiple mouse events 389/// by calling it multiple times in a loop: the intermediate mouse 390/// positions will be ignored. It should be used to implement real-time 391/// mouse input in a GUI. The deprecated pseudokey form 392/// (`<LeftMouse><col,row>`) of |nvim_input()| has the same limitation. 393/// 394/// @param button Mouse button: one of "left", "right", "middle", "wheel", "move", 395/// "x1", "x2". 396/// @param action For ordinary buttons, one of "press", "drag", "release". 397/// For the wheel, one of "up", "down", "left", "right". Ignored for "move". 398/// @param modifier String of modifiers each represented by a single char. 399/// The same specifiers are used as for a key press, except 400/// that the "-" separator is optional, so "C-A-", "c-a" 401/// and "CA" can all be used to specify Ctrl+Alt+click. 402/// @param grid Grid number (used by |ui-multigrid| client), or 0 to let Nvim decide positioning of 403/// windows. For more information, see [dev-ui-multigrid] 404/// @param row Mouse row-position (zero-based, like redraw events) 405/// @param col Mouse column-position (zero-based, like redraw events) 406/// @param[out] err Error details, if any 407void nvim_input_mouse (String button ,String action ,String modifier ,Integer grid ,Integer row , 408Integer col ,Error * err ) 409FUNC_API_SINCE (6 )FUNC_API_FAST 410{ 411may_trigger_vim_suspend_resume (false); 412 413if (button .data == NULL || action .data == NULL ) { 414 gotoerror ; 415 } 416 417int code = 0 ; 418 419if (strequal (button .data ,"left" )) { 420code = KE_LEFTMOUSE ; 421 }else if (strequal (button .data ,"middle" )) { 422code = KE_MIDDLEMOUSE ; 423 }else if (strequal (button .data ,"right" )) { 424code = KE_RIGHTMOUSE ; 425 }else if (strequal (button .data ,"wheel" )) { 426code = KE_MOUSEDOWN ; 427 }else if (strequal (button .data ,"x1" )) { 428code = KE_X1MOUSE ; 429 }else if (strequal (button .data ,"x2" )) { 430code = KE_X2MOUSE ; 431 }else if (strequal (button .data ,"move" )) { 432code = KE_MOUSEMOVE ; 433 }else { 434 gotoerror ; 435 } 436 437if (code == KE_MOUSEDOWN ) { 438if (strequal (action .data ,"down" )) { 439code = KE_MOUSEUP ; 440 }else if (strequal (action .data ,"up" )) { 441// code = KE_MOUSEDOWN 442 }else if (strequal (action .data ,"left" )) { 443code = KE_MOUSERIGHT ; 444 }else if (strequal (action .data ,"right" )) { 445code = KE_MOUSELEFT ; 446 }else { 447 gotoerror ; 448 } 449 }else if (code != KE_MOUSEMOVE ) { 450if (strequal (action .data ,"press" )) { 451// pass 452 }else if (strequal (action .data ,"drag" )) { 453code += KE_LEFTDRAG - KE_LEFTMOUSE ; 454 }else if (strequal (action .data ,"release" )) { 455code += KE_LEFTRELEASE - KE_LEFTMOUSE ; 456 }else { 457 gotoerror ; 458 } 459 } 460 461int modmask = 0 ; 462for (size_t i = 0 ;i < modifier .size ;i ++ ) { 463char byte = modifier .data [i ]; 464if (byte == '-' ) { 465continue ; 466 } 467int mod = name_to_mod_mask (byte ); 468VALIDATE ((mod != 0 ),"Invalid modifier: %c" ,byte , { 469return ; 470 }); 471modmask |=mod ; 472 } 473 474input_enqueue_mouse (code , (uint8_t )modmask , (int )grid , (int )row , (int )col ); 475return ; 476 477error : 478api_set_error (err ,kErrorTypeValidation , 479"invalid button or action" ); 480} 481 482/// Converts terminal codes and |keycodes| ([<CR>], [<Esc>], …) in a key sequence, to the internal 483/// representation. See also Lua |vim.keycode()|. 484/// 485/// @see replace_termcodes 486/// @see cpoptions 487/// 488/// @param str String to be converted. 489/// @param from_part Legacy Vim parameter. Usually true. 490/// @param do_lt Also translate [<lt>]. Ignored if `special` is false. 491/// @param special Replace |keycodes|, e.g. [<CR>] becomes a "\r" char. 492String nvim_replace_termcodes (String str ,Boolean from_part ,Boolean do_lt ,Boolean special ) 493FUNC_API_SINCE (1 )FUNC_API_FAST FUNC_API_RET_ALLOC 494{ 495if (str .size == 0 ) { 496// Empty string 497return (String ) { .data = NULL , .size = 0 }; 498 } 499 500int flags = 0 ; 501if (from_part ) { 502flags |=REPTERM_FROM_PART ; 503 } 504if (do_lt ) { 505flags |=REPTERM_DO_LT ; 506 } 507if (!special ) { 508flags |=REPTERM_NO_SPECIAL ; 509 } 510 511char * ptr = NULL ; 512replace_termcodes (str .data ,str .size ,& ptr ,0 ,flags ,NULL ,p_cpo ); 513return cstr_as_string (ptr ); 514} 515 516/// Executes Lua code. Arguments are available as `...` inside the chunk. The chunk can return 517/// a value. 518/// 519/// Only statements are executed. To evaluate an expression, prefix it with "return": `return 520/// my_function(...)` 521/// 522/// Example: 523/// ```lua 524/// local peer = vim.fn.jobstart({ vim.v.progpath, '--clean', '--embed' }, { rpc=true }) 525/// vim.print(vim.rpcrequest(peer, 'nvim_exec_lua', [[ 526/// local a, b = ... 527/// return ('result: %s'):format(a + b) 528/// ]], 529/// { 1, 3 } 530/// ) 531/// ) 532/// ``` 533/// 534/// @param code Lua code to execute. 535/// @param args Arguments to the Lua code. 536/// @param[out] err Lua error raised while parsing or executing the Lua code. 537/// 538/// @return Value returned by the Lua code (if any), or NIL. 539Object nvim_exec_lua (String code ,Array args ,Arena * arena ,Error * err ) 540FUNC_API_SINCE (7 ) 541FUNC_API_REMOTE_ONLY 542{ 543// TODO(bfredl): convert directly from msgpack to lua and then back again 544return nlua_exec (code ,NULL ,args ,kRetObject ,arena ,err ); 545} 546 547/// Like |nvim_exec_lua()|, but can be called during |api-fast| contexts. 548/// 549/// Execute Lua code. Parameters (if any) are available as `...` inside the 550/// chunk. The chunk can return a value. 551/// 552/// Only statements are executed. To evaluate an expression, prefix it 553/// with `return`: return my_function(...) 554/// 555/// @param code Lua code to execute 556/// @param args Arguments to the code 557/// @param[out] err Details of an error encountered while parsing 558/// or executing the Lua code. 559/// 560/// @return Return value of Lua code if present or NIL. 561Object nvim__exec_lua_fast (String code ,Array args ,Arena * arena ,Error * err ) 562FUNC_API_SINCE (14 ) 563FUNC_API_REMOTE_ONLY 564FUNC_API_FAST 565{ 566return nvim_exec_lua (code ,args ,arena ,err ); 567} 568 569/// Calculates the number of display cells occupied by `text`. 570/// Control characters including [<Tab>] count as one cell. 571/// 572/// @param text Some text 573/// @param[out] err Error details, if any 574/// @return Number of cells 575Integer nvim_strwidth (String text ,Error * err ) 576FUNC_API_SINCE (1 ) 577{ 578VALIDATE_S ((text .size <=INT_MAX ),"text length" ,"(too long)" , { 579return 0 ; 580 }); 581 582return (Integer )mb_string2cells (text .data ); 583} 584 585/// Gets the paths contained in |runtime-search-path|. 586/// 587/// @return List of paths 588ArrayOf (String )nvim_list_runtime_paths (Arena * arena ,Error * err ) 589FUNC_API_SINCE (1 ) 590{ 591return nvim_get_runtime_file (NULL_STRING , true,arena ,err ); 592} 593 594/// @nodoc 595Array nvim__runtime_inspect (Arena * arena ) 596{ 597return runtime_inspect (arena ); 598} 599 600typedef struct { 601ArrayBuilder rv ; 602Arena * arena ; 603}RuntimeCookie ; 604 605/// Finds files in runtime directories, in 'runtimepath' order. 606/// 607/// "name" can contain wildcards. For example 608/// `nvim_get_runtime_file("colors/*.{vim,lua}", true)` will return all color 609/// scheme files. Always use forward slashes (/) in the search pattern for 610/// subdirectories regardless of platform. 611/// 612/// It is not an error to not find any files. An empty array is returned then. 613/// 614/// @param name pattern of files to search for 615/// @param all whether to return all matches or only the first 616/// @return list of absolute paths to the found files 617ArrayOf (String )nvim_get_runtime_file (String name ,Boolean all ,Arena * arena ,Error * err ) 618FUNC_API_SINCE (7 ) 619FUNC_API_FAST 620{ 621RuntimeCookie cookie = { .rv = ARRAY_DICT_INIT , .arena = arena , }; 622kvi_init (cookie .rv ); 623 624int flags = DIP_DIRFILE | (all ?DIP_ALL :0 ); 625 626TRY_WRAP (err , { 627do_in_runtimepath ((name .size ?name .data :"" ),flags ,find_runtime_cb ,& cookie ); 628 }); 629 630return arena_take_arraybuilder (arena ,& cookie .rv ); 631} 632 633static bool find_runtime_cb (int num_fnames ,char ** fnames ,bool all ,void * c ) 634{ 635RuntimeCookie * cookie = (RuntimeCookie * )c ; 636for (int i = 0 ;i < num_fnames ;i ++ ) { 637// TODO(bfredl): consider memory management of gen_expand_wildcards() itself 638kvi_push (cookie -> rv ,CSTR_TO_ARENA_OBJ (cookie -> arena ,fnames [i ])); 639if (!all ) { 640return true; 641 } 642 } 643 644return num_fnames > 0 ; 645} 646 647/// @nodoc 648String nvim__get_lib_dir (void ) 649FUNC_API_RET_ALLOC 650{ 651return cstr_as_string (get_lib_dir ()); 652} 653 654/// Find files in runtime directories 655/// 656/// @param pat pattern of files to search for 657/// @param all whether to return all matches or only the first 658/// @param opts is_lua: only search Lua subdirs 659/// @return list of absolute paths to the found files 660ArrayOf (String )nvim__get_runtime (ArrayOf (String )pat ,Boolean all ,Dict (runtime )* opts , 661Arena * arena , 662Error * err ) 663FUNC_API_SINCE (8 ) 664FUNC_API_FAST 665{ 666VALIDATE (!opts -> do_source || nlua_is_deferred_safe (),"%s" ,"'do_source' used in fast callback" , 667 {}); 668if (ERROR_SET (err )) { 669return (Array )ARRAY_DICT_INIT ; 670 } 671 672ArrayOf (String )res = runtime_get_named (opts -> is_lua ,pat ,all ,arena ); 673 674if (opts -> do_source ) { 675for (size_t i = 0 ;i < res .size ;i ++ ) { 676String name = res .items [i ].data .string ; 677do_source (name .data , false,DOSO_NONE ,NULL ); 678 } 679 } 680 681return res ; 682} 683 684/// Changes the global working directory. 685/// 686/// @param dir Directory path 687/// @param[out] err Error details, if any 688void nvim_set_current_dir (String dir ,Error * err ) 689FUNC_API_SINCE (1 ) 690{ 691VALIDATE_S ((dir .size < MAXPATHL ),"directory name" ,"(too long)" , { 692return ; 693 }); 694 695TRY_WRAP (err , { 696do_chdir (dir .data ,kCdScopeGlobal ); 697 }); 698} 699 700/// Gets the current line. 701/// 702/// @param[out] err Error details, if any 703/// @return Current line string 704String nvim_get_current_line (Arena * arena ,Error * err ) 705FUNC_API_SINCE (1 ) 706{ 707return buffer_get_line (curbuf -> handle ,curwin -> w_cursor .lnum - 1 ,arena ,err ); 708} 709 710/// Sets the text on the current line. 711/// 712/// @param line Line contents 713/// @param[out] err Error details, if any 714void nvim_set_current_line (String line ,Arena * arena ,Error * err ) 715FUNC_API_SINCE (1 ) 716FUNC_API_TEXTLOCK 717{ 718buffer_set_line (curbuf -> handle ,curwin -> w_cursor .lnum - 1 ,line ,arena ,err ); 719} 720 721/// Deletes the current line. 722/// 723/// @param[out] err Error details, if any 724void nvim_del_current_line (Arena * arena ,Error * err ) 725FUNC_API_SINCE (1 ) 726FUNC_API_TEXTLOCK 727{ 728buffer_del_line (curbuf -> handle ,curwin -> w_cursor .lnum - 1 ,arena ,err ); 729} 730 731/// Gets a global (g:) variable. 732/// 733/// @param name Variable name 734/// @param[out] err Error details, if any 735/// @return Variable value 736Object nvim_get_var (String name ,Arena * arena ,Error * err ) 737FUNC_API_SINCE (1 ) 738{ 739dictitem_T * di = tv_dict_find (get_globvar_dict (),name .data , (ptrdiff_t )name .size ); 740if (di == NULL ) {// try to autoload script 741bool found = script_autoload (name .data ,name .size , false)&& !aborting (); 742VALIDATE (found ,"Key not found: %s" ,name .data , { 743return (Object )OBJECT_INIT ; 744 }); 745di = tv_dict_find (get_globvar_dict (),name .data , (ptrdiff_t )name .size ); 746 } 747VALIDATE ((di != NULL ),"Key not found: %s" ,name .data , { 748return (Object )OBJECT_INIT ; 749 }); 750return vim_to_object (& di -> di_tv ,arena , true); 751} 752 753/// Sets a global (g:) variable. 754/// 755/// @param name Variable name 756/// @param value Variable value 757/// @param[out] err Error details, if any 758void nvim_set_var (String name ,Object value ,Error * err ) 759FUNC_API_SINCE (1 ) 760{ 761dict_set_var (get_globvar_dict (),name ,value , false, false,NULL ,err ); 762} 763 764/// Removes a global (g:) variable. 765/// 766/// @param name Variable name 767/// @param[out] err Error details, if any 768void nvim_del_var (String name ,Error * err ) 769FUNC_API_SINCE (1 ) 770{ 771dict_set_var (get_globvar_dict (),name ,NIL , true, false,NULL ,err ); 772} 773 774/// Gets a v: variable. 775/// 776/// @param name Variable name 777/// @param[out] err Error details, if any 778/// @return Variable value 779Object nvim_get_vvar (String name ,Arena * arena ,Error * err ) 780FUNC_API_SINCE (1 ) 781{ 782return dict_get_value (get_vimvar_dict (),name ,arena ,err ); 783} 784 785/// Sets a v: variable, if it is not readonly. 786/// 787/// @param name Variable name 788/// @param value Variable value 789/// @param[out] err Error details, if any 790void nvim_set_vvar (String name ,Object value ,Error * err ) 791FUNC_API_SINCE (6 ) 792{ 793dict_set_var (get_vimvar_dict (),name ,value , false, false,NULL ,err ); 794} 795 796/// Prints a message given by a list of `[text, hl_group]` "chunks". Emits a |Progress| event if 797/// `kind='progress'`. 798/// 799/// Returns a message-id, which can be given in later calls to update an existing message. The 800/// message-id is an autogenerated integer, or a user-defined string. The id "address space" is 801/// global, so plugins specifying a string id should use qualified names such as "my.msg.id" to 802/// avoid unintentional conflicts. 803/// 804/// Example: 805/// ```lua 806/// vim.api.nvim_echo({ { 'chunk1-line1\nchunk1-line2\n' }, { 'chunk2-line1' } }, true) 807/// ``` 808/// 809/// @param chunks List of `[text, hl_group]` pairs, where each is a `text` string highlighted by 810/// the (optional) name or ID `hl_group`. 811/// @param history if true, add to |message-history|. 812/// @param opts Optional parameters. 813/// - data (`table?`) Dict of arbitrary data, available in |Progress| |event-data|. 814/// - err (`boolean?`) Treat the message like `:echoerr`. Sets `hl_group` to |hl-ErrorMsg| by default. 815/// - id (`integer|string?`) Message-id returned by a previous `nvim_echo` call, or 816/// a user-defined id (string). If existing message has this id, it will be updated 817/// instead of creating a new message. 818/// - kind (`string?`) Decides the |ui-messages| kind in the emitted message. Set "progress" 819/// to emit a |progress-message|. 820/// - percent (`integer?`) |progress-message| percentage, or nil to signal "unknown progress". 821/// - source (`string?`) |progress-message| source. 822/// - status (`string?`) |progress-message| status: 823/// - "success": Process completed successfully. 824/// - "running": Process is ongoing. 825/// - "failed": Process failed. 826/// - "cancel": Process should be cancelled. Progress owner must handle the |Progress| 827/// event to perform the cancellation. 828/// - title (`string?`) Message title. Only for |progress-message| currently. 829/// - verbose (`boolean?`) Message is controlled by the 'verbose' option. `nvim -V3log` will write the 830/// message to the "log" file instead of standard output. 831/// @return Message-id, or -1 if message wasn't shown. 832Union (Integer ,String )nvim_echo (ArrayOf (Tuple (String ,* HLGroupID ))chunks ,Boolean history , 833Dict (echo_opts )* opts ,Error * err ) 834FUNC_API_SINCE (7 ) 835{ 836MsgID id = INTEGER_OBJ (-1 ); 837HlMessage hl_msg = parse_hl_msg (chunks ,opts -> err ,err ); 838if (ERROR_SET (err )) { 839 gotoerror ; 840 } 841 842char * kind = opts -> kind .data ; 843if (opts -> verbose ) { 844verbose_enter (); 845 }else if (kind == NULL ) { 846kind = opts -> err ?"echoerr" :history ?"echomsg" :"echo" ; 847 } 848 849bool is_progress = strequal (kind ,"progress" ); 850bool needs_clear = !history ; 851 852VALIDATE (is_progress 853|| (opts -> status .size == 0 && opts -> title .size == 0 && !HAS_KEY (opts ,echo_opts ,percent ) 854&& opts -> data .size == 0 && opts -> source .size == 0 ), 855"Conflict: title/source/status/percent/data not allowed with kind='%s'" ,kind , 856 { 857 gotoerror ; 858 }); 859 860VALIDATE_EXP (!is_progress || strequal (opts -> status .data ,"success" ) 861|| strequal (opts -> status .data ,"failed" ) 862|| strequal (opts -> status .data ,"running" ) 863|| strequal (opts -> status .data ,"cancel" ), 864"status" ,"success|failed|running|cancel" ,opts -> status .data , { 865 gotoerror ; 866 }); 867 868VALIDATE_RANGE (!is_progress || !HAS_KEY (opts ,echo_opts ,percent ) 869|| (opts -> percent >=0 && opts -> percent <=100 ), 870"percent" , { 871 gotoerror ; 872 }); 873 874VALIDATE_R (!is_progress || opts -> source .size != 0 ,"opts.source" , { 875 gotoerror ; 876 }); 877VALIDATE_S (!is_progress || !strequal (opts -> source .data ,"nvim" ),"source" ,opts -> source .data , { 878 gotoerror ; 879 }); 880 881// Message-id may be user-defined only if String, not Integer. 882VALIDATE_INT (opts -> id .type != kObjectTypeInteger || msg_id_exists (opts -> id .data .integer ), 883"id" ,opts -> id .data .integer , { 884 gotoerror ; 885 }); 886 887MessageData msg_data = { .title = opts -> title , .status = opts -> status , 888 .percent = HAS_KEY (opts ,echo_opts ,percent ) ?opts -> percent :-1 , 889 .data = opts -> data , .source = opts -> source }; 890 891const bool save_nwr = need_wait_return ; 892const int save_lines_left = lines_left ; 893const bool save_msg_didany = msg_didany ; 894// Similar truncation method to showmode(). 895// TODO(justinmk): drop _truncate feature after ui2 graduates? 896if (opts -> _truncate ) { 897no_wait_return ++ ; 898lines_left = 0 ; 899msg_didany = true; 900msg_no_more = true; 901 } 902msg_ext_no_fast (); 903id = msg_multihl (opts -> id ,hl_msg ,kind ,history ,opts -> err ,& msg_data ,& needs_clear ); 904if (opts -> _truncate ) { 905msg_no_more = false; 906msg_didany = save_msg_didany ; 907lines_left = save_lines_left ; 908no_wait_return -- ; 909need_wait_return = save_nwr ; 910 } 911 912if (opts -> verbose ) { 913verbose_leave (); 914verbose_stop ();// flush now 915 } 916 917if (!needs_clear ) { 918// history takes ownership of `hl_msg` 919return id ; 920 } 921 922error : 923hl_msg_free (hl_msg ); 924return id ; 925} 926 927/// Gets the current list of buffers. 928/// 929/// Includes unlisted (unloaded/deleted) buffers, like `:ls!`. 930/// Use |nvim_buf_is_loaded()| to check if a buffer is loaded. 931/// 932/// @return List of buffer ids 933ArrayOf (Buffer )nvim_list_bufs (Arena * arena ) 934FUNC_API_SINCE (1 ) 935{ 936size_t n = 0 ; 937 938FOR_ALL_BUFFERS (b ) { 939n ++ ; 940 } 941 942Array rv = arena_array (arena ,n ); 943 944FOR_ALL_BUFFERS (b ) { 945ADD_C (rv ,BUFFER_OBJ (b -> handle )); 946 } 947 948return rv ; 949} 950 951/// Gets the current buffer. 952/// 953/// @return Buffer id 954Buffer nvim_get_current_buf (void ) 955FUNC_API_SINCE (1 ) 956{ 957return curbuf -> handle ; 958} 959 960/// Sets the current window's buffer to `buf`. 961/// 962/// @param buf Buffer id 963/// @param[out] err Error details, if any 964void nvim_set_current_buf (Buffer buf ,Error * err ) 965FUNC_API_SINCE (1 ) 966FUNC_API_TEXTLOCK 967{ 968buf_T * b = find_buffer_by_handle (buf ,err ); 969 970if (!b ) { 971return ; 972 } 973 974TRY_WRAP (err , { 975do_buffer (DOBUF_GOTO ,DOBUF_FIRST ,FORWARD ,b -> b_fnum ,0 ); 976 }); 977} 978 979/// Gets the current list of all |window-ID|s in all tabpages. 980/// 981/// @return List of |window-ID|s 982ArrayOf (Window )nvim_list_wins (Arena * arena ) 983FUNC_API_SINCE (1 ) 984{ 985size_t n = 0 ; 986 987FOR_ALL_TAB_WINDOWS (tp ,wp ) { 988n ++ ; 989 } 990 991Array rv = arena_array (arena ,n ); 992 993FOR_ALL_TAB_WINDOWS (tp ,wp ) { 994ADD_C (rv ,WINDOW_OBJ (wp -> handle )); 995 } 996 997return rv ; 998} 999 1000/// Gets the current window. 1001/// 1002/// @return |window-ID| 1003Window nvim_get_current_win (void ) 1004FUNC_API_SINCE (1 ) 1005{ 1006return curwin -> handle ; 1007} 1008 1009/// Navigates to the given window (and tabpage, implicitly). 1010/// 1011/// @param win |window-ID| to focus 1012/// @param[out] err Error details, if any 1013void nvim_set_current_win (Window win ,Error * err ) 1014FUNC_API_SINCE (1 ) 1015FUNC_API_TEXTLOCK 1016{ 1017win_T * w = find_window_by_handle (win ,err ); 1018 1019if (!w ) { 1020return ; 1021 } 1022 1023TRY_WRAP (err , { 1024if (w -> w_buffer != curbuf ) { 1025reset_VIsual_and_resel (); 1026 } 1027goto_tabpage_win (win_find_tabpage (w ),w ); 1028 }); 1029} 1030 1031/// Creates a new, empty, unnamed buffer. 1032/// 1033/// @param listed Sets 'buflisted' 1034/// @param scratch Creates a "throwaway" |scratch-buffer| for temporary work 1035/// (always 'nomodified'). Also sets 'nomodeline' on the buffer. 1036/// @param[out] err Error details, if any 1037/// @return Buffer id, or 0 on error 1038Buffer nvim_create_buf (Boolean listed ,Boolean scratch ,Error * err ) 1039FUNC_API_SINCE (6 ) 1040{ 1041Buffer ret = 0 ; 1042 1043TRY_WRAP (err , { 1044// Block autocommands for now so they don't mess with the buffer before we 1045// finish configuring it. 1046block_autocmds (); 1047 1048buf_T * buf = buflist_new (NULL ,NULL ,0 , 1049BLN_NOOPT |BLN_NEW | (listed ?BLN_LISTED :0 )); 1050if (buf == NULL ) { 1051unblock_autocmds (); 1052 gotofail ; 1053 } 1054 1055// Open the memline for the buffer. This will avoid spurious autocmds when 1056// a later nvim_buf_set_lines call would have needed to "open" the buffer. 1057if (ml_open (buf )== FAIL ) { 1058unblock_autocmds (); 1059 gotofail ; 1060 } 1061 1062// Set last_changedtick to avoid triggering a TextChanged autocommand right 1063// after it was added. 1064buf -> b_last_changedtick = buf_get_changedtick (buf ); 1065buf -> b_last_changedtick_i = buf_get_changedtick (buf ); 1066buf -> b_last_changedtick_pum = buf_get_changedtick (buf ); 1067 1068// Only strictly needed for scratch, but could just as well be consistent 1069// and do this now. Buffer is created NOW, not when it later first happens 1070// to reach a window or ctx_switch() .. 1071buf_copy_options (buf ,BCO_ENTER |BCO_NOHELP ); 1072 1073if (scratch ) { 1074set_option_direct_for (kOptBufhidden ,STATIC_CSTR_AS_OBJ ("hide" ),OPT_LOCAL ,0 , 1075kOptScopeBuf ,buf ); 1076set_option_direct_for (kOptBuftype ,STATIC_CSTR_AS_OBJ ("nofile" ),OPT_LOCAL ,0 , 1077kOptScopeBuf ,buf ); 1078assert (buf -> b_ml .ml_mfp -> mf_fd < 0 );// ml_open() should not have opened swapfile already 1079buf -> b_p_swf = false; 1080buf -> b_p_ml = false; 1081 } 1082 1083unblock_autocmds (); 1084 1085bufref_T bufref ; 1086set_bufref (& bufref ,buf ); 1087if (apply_autocmds (EVENT_BUFNEW ,NULL ,NULL , false,buf ) 1088&& !bufref_valid (& bufref )) { 1089 gotofail ; 1090 } 1091if (listed 1092&& apply_autocmds (EVENT_BUFADD ,NULL ,NULL , false,buf ) 1093&& !bufref_valid (& bufref )) { 1094 gotofail ; 1095 } 1096 1097ret = buf -> b_fnum ; 1098fail :; 1099 }); 1100 1101if (ret == 0 && !ERROR_SET (err )) { 1102api_set_error (err ,kErrorTypeException ,"Failed to create buffer" ); 1103 } 1104return ret ; 1105} 1106 1107/// Open a terminal instance in a buffer 1108/// 1109/// By default (and currently the only option) the terminal will not be 1110/// connected to an external process. Instead, input sent on the channel 1111/// will be echoed directly by the terminal. This is useful to display 1112/// ANSI terminal sequences returned as part of an RPC message, or similar. 1113/// 1114/// Note: |:ls| reports the buffer as "R" (running) until the channel is closed. |chanclose()| 1115/// 1116/// Note: To initialize the terminal size, display the buffer in a window first. E.g. for a floating display, 1117/// 1. Create an empty buffer using |nvim_create_buf()|. 1118/// 2. Display it with |nvim_open_win()|. 1119/// 3. Call nvim_open_term(). 1120/// 4. Then calling |nvim_chan_send()| will process sequences in a virtual terminal with the 1121/// intended size (defined by the window width/height). 1122/// 1123/// Example: this `TermHl` command can be used to display and highlight raw ANSI termcodes, so you 1124/// can use Nvim as a "scrollback pager" (for terminals like kitty): [ansi-colorize]() 1125/// [terminal-scrollback-pager]() 1126/// 1127/// ```lua 1128/// vim.api.nvim_create_user_command('TermHl', function() 1129/// vim.api.nvim_open_term(0) 1130/// end, { desc = 'Highlights ANSI termcodes in curbuf' }) 1131/// ``` 1132/// 1133/// @param buf Buffer which displays the PTY output. The initial buffer contents (if any) will be 1134/// written to the PTY. 1135/// @param opts Optional parameters. 1136/// - force_crlf: (boolean, default: true) Convert "\n" to "\r\n". 1137/// - on_input: (`fun("input", chan: integer, buf: integer, data: string)`) Function invoked 1138/// when the terminal emits bytes, see above. |textlock| applies. May call 1139/// |nvim_chan_send()| directly. 1140/// @param[out] err Error details, if any 1141/// @return Channel id, or 0 on error 1142Integer nvim_open_term (Buffer buf ,Dict (open_term )* opts ,Error * err ) 1143FUNC_API_SINCE (7 ) 1144FUNC_API_TEXTLOCK 1145{ 1146buf_T * b = api_buf_ensure_loaded (buf ,err ); 1147if (!b ) { 1148return 0 ; 1149 } 1150 1151bool may_read_buffer = true; 1152if (b -> terminal ) { 1153if (terminal_running (b -> terminal )) { 1154api_set_error (err ,kErrorTypeException , 1155"Terminal already connected to buffer %d" ,b -> handle ); 1156return 0 ; 1157 } 1158buf_close_terminal (b ); 1159may_read_buffer = false; 1160 } 1161 1162LuaRef cb = LUA_NOREF ; 1163if (HAS_KEY (opts ,open_term ,on_input )) { 1164cb = opts -> on_input ; 1165opts -> on_input = LUA_NOREF ; 1166 } 1167 1168Channel * chan = channel_alloc (kChannelStreamInternal ); 1169chan -> stream .internal .cb = cb ; 1170chan -> stream .internal .closed = false; 1171TerminalOptions topts = { 1172 .data = chan , 1173// NB: overridden in terminal_check_size if a window is already 1174// displaying the buffer 1175 .width = (uint16_t )MAX (curwin -> w_view_width - win_col_off (curwin ),0 ), 1176 .height = (uint16_t )curwin -> w_view_height , 1177 .read_pause_cb = term_read_pause , 1178 .write_cb = term_write , 1179 .resize_cb = term_resize , 1180 .resume_cb = term_resume , 1181 .close_cb = term_close , 1182 .force_crlf = GET_BOOL_OR_TRUE (opts ,open_term ,force_crlf ), 1183 }; 1184 1185// Read existing buffer contents (if any) 1186StringBuilder contents = KV_INITIAL_VALUE ; 1187if (may_read_buffer ) { 1188read_buffer_into (b ,1 ,b -> b_ml .ml_line_count ,& contents ); 1189 } 1190 1191channel_incref (chan ); 1192chan -> term = terminal_alloc (b ,topts ); 1193terminal_open (& chan -> term ,b ); 1194if (chan -> term != NULL ) { 1195terminal_check_size (chan -> term ); 1196 } 1197channel_decref (chan ); 1198 1199// Write buffer contents to channel. channel_send takes ownership of the 1200// buffer so we do not need to free it. 1201if (contents .size > 0 ) { 1202const char * error = NULL ; 1203channel_send (chan -> id ,contents .items ,contents .size , true,& error ); 1204VALIDATE (!error ,"%s" ,error , {}); 1205 } 1206 1207return (Integer )chan -> id ; 1208} 1209 1210static void term_read_pause (bool pause ,void * data ) 1211{ 1212// Not currently needed as sending to channel isn't allowed during buffer updates. 1213} 1214 1215static void term_write (const char * buf ,size_t size ,void * data ) 1216{ 1217Channel * chan = data ; 1218LuaRef cb = chan -> stream .internal .cb ; 1219if (cb == LUA_NOREF ) { 1220return ; 1221 } 1222MAXSIZE_TEMP_ARRAY (args ,3 ); 1223ADD_C (args ,INTEGER_OBJ ((Integer )chan -> id )); 1224ADD_C (args ,BUFFER_OBJ (terminal_buf (chan -> term ))); 1225ADD_C (args ,STRING_OBJ (((String ){ .data = (char * )buf , .size = size }))); 1226textlock ++ ; 1227nlua_call_ref (cb ,"input" ,args ,kRetNilBool ,NULL ,NULL ); 1228textlock -- ; 1229} 1230 1231static void term_resize (uint16_t width ,uint16_t height ,void * data ) 1232{ 1233// TODO(bfredl): Lua callback 1234} 1235 1236static void term_resume (void * data ) 1237{ 1238} 1239 1240static void term_close (void * data ) 1241{ 1242Channel * chan = data ; 1243terminal_destroy (& chan -> term ); 1244api_free_luaref (chan -> stream .internal .cb ); 1245chan -> stream .internal .cb = LUA_NOREF ; 1246channel_decref (chan ); 1247} 1248 1249/// Sends raw data to channel `chan`. |channel-bytes| 1250/// - For a job, it writes it to the stdin of the process. 1251/// - For the stdio channel |channel-stdio|, it writes to Nvim's stdout. 1252/// - For an internal terminal instance (|nvim_open_term()|) it writes directly to terminal output. 1253/// 1254/// This function writes raw data, not RPC messages. Use |vim.rpcrequest()| and |vim.rpcnotify()| if 1255/// the channel expects RPC messages (i.e. it was created with `rpc=true`). 1256/// 1257/// To write data to the |TUI| host terminal, see |nvim_ui_send()|. 1258/// 1259/// @param chan Channel id 1260/// @param data Data to write. 8-bit clean: may contain NUL bytes. 1261/// @param[out] err Error details, if any 1262void nvim_chan_send (Integer chan ,String data ,Error * err ) 1263FUNC_API_SINCE (7 )FUNC_API_REMOTE_ONLY FUNC_API_LUA_ONLY 1264{ 1265const char * error = NULL ; 1266if (!data .size ) { 1267return ; 1268 } 1269 1270channel_send ((uint64_t )chan ,data .data ,data .size , 1271 false,& error ); 1272VALIDATE (!error ,"%s" ,error , {}); 1273} 1274 1275/// Gets the current list of |tab-ID|s. 1276/// 1277/// @return List of |tab-ID|s 1278ArrayOf (Tabpage )nvim_list_tabpages (Arena * arena ) 1279FUNC_API_SINCE (1 ) 1280{ 1281size_t n = 0 ; 1282 1283FOR_ALL_TABS (tp ) { 1284n ++ ; 1285 } 1286 1287Array rv = arena_array (arena ,n ); 1288 1289FOR_ALL_TABS (tp ) { 1290ADD_C (rv ,TABPAGE_OBJ (tp -> handle )); 1291 } 1292 1293return rv ; 1294} 1295 1296/// Gets the current tabpage. 1297/// 1298/// @return |tab-ID| 1299Tabpage nvim_get_current_tabpage (void ) 1300FUNC_API_SINCE (1 ) 1301{ 1302return curtab -> handle ; 1303} 1304 1305/// Sets the current tabpage. 1306/// 1307/// @param tabpage |tab-ID| to focus 1308/// @param[out] err Error details, if any 1309void nvim_set_current_tabpage (Tabpage tabpage ,Error * err ) 1310FUNC_API_SINCE (1 ) 1311FUNC_API_TEXTLOCK 1312{ 1313tabpage_T * tp = find_tab_by_handle (tabpage ,err ); 1314 1315if (!tp ) { 1316return ; 1317 } 1318 1319TRY_WRAP (err , { 1320goto_tabpage_tp (tp , true, true); 1321 }); 1322} 1323 1324/// Pastes at cursor (in any mode), and sets "redo" so dot (|.|) will repeat the input. UIs call 1325/// this to implement "paste", but it's also intended for use by scripts to input large, 1326/// dot-repeatable blocks of text (as opposed to |nvim_input()| which is subject to mappings/events 1327/// and is thus much slower). 1328/// 1329/// Invokes the |vim.paste()| handler, which handles each mode appropriately. 1330/// 1331/// Errors ('nomodifiable', `vim.paste()` failure, …) are reflected in `err` but do not affect the 1332/// return value (which is strictly decided by `vim.paste()`). On error or cancel, subsequent calls 1333/// are ignored ("drained") until the next paste is initiated (phase 1 or -1). 1334/// 1335/// Useful in mappings and scripts to insert multiline text. Example: 1336/// 1337/// ```lua 1338/// vim.keymap.set('n', 'x', function() 1339/// vim.api.nvim_paste([[ 1340/// line1 1341/// line2 1342/// line3 1343/// ]], false, -1) 1344/// end, { buf = 0 }) 1345/// ``` 1346/// 1347/// @param data Multiline input. Lines break at LF ("\n"). May be binary (containing NUL bytes). 1348/// @param crlf Also break lines at CR and CRLF. 1349/// @param phase -1: paste in a single call (i.e. without streaming). 1350/// To "stream" a paste, call `nvim_paste` sequentially with 1351/// these `phase` values: 1352/// - 1: starts the paste (exactly once) 1353/// - 2: continues the paste (zero or more times) 1354/// - 3: ends the paste (exactly once) 1355/// @param[out] err Error details, if any 1356/// @return 1357/// - true: Client may continue pasting. 1358/// - false: Client should cancel the paste. 1359Boolean nvim_paste (uint64_t channel_id ,String data ,Boolean crlf ,Integer phase ,Arena * arena , 1360Error * err ) 1361FUNC_API_SINCE (6 ) 1362FUNC_API_TEXTLOCK 1363{ 1364static bool cancelled = false; 1365 1366VALIDATE_INT ((phase >=-1 && phase <=3 ),"phase" ,phase , { 1367return false; 1368 }); 1369if (phase == -1 || phase == 1 ) {// Start of paste-stream. 1370cancelled = false; 1371if (curbuf -> terminal ) { 1372terminal_set_streamed_paste (curbuf -> terminal , true); 1373 } 1374 }else if (cancelled ) { 1375// Skip remaining chunks. Report error only once per "stream". 1376 gototheend ; 1377 } 1378Array lines = string_to_array (data ,crlf ,arena ); 1379MAXSIZE_TEMP_ARRAY (args ,2 ); 1380ADD_C (args ,ARRAY_OBJ (lines )); 1381ADD_C (args ,INTEGER_OBJ (phase )); 1382Object rv = NLUA_EXEC_STATIC ("return vim.paste(...)" ,args ,kRetNilBool ,arena ,err ); 1383// vim.paste() decides if client should cancel. 1384if (ERROR_SET (err )|| (rv .type == kObjectTypeBoolean && !rv .data .boolean )) { 1385cancelled = true; 1386 } 1387if ((phase == -1 || phase == 3 || cancelled )&& curbuf -> terminal ) { 1388terminal_set_streamed_paste (curbuf -> terminal , false); 1389 } 1390if (!cancelled && (phase == -1 || phase == 1 )) { 1391paste_store (channel_id ,kFalse ,NULL_STRING ,crlf ); 1392 } 1393if (!cancelled ) { 1394paste_store (channel_id ,kNone ,data ,crlf ); 1395 } 1396if (phase == 3 || phase == (cancelled ?2 :-1 )) { 1397paste_store (channel_id ,kTrue ,NULL_STRING ,crlf ); 1398 } 1399theend : 1400 ; 1401bool retval = !cancelled ; 1402if (phase == -1 || phase == 3 ) {// End of paste-stream. 1403cancelled = false; 1404 } 1405return retval ; 1406} 1407 1408/// Puts text at cursor, in any mode. For dot-repeatable input, use |nvim_paste()|. 1409/// 1410/// Compare |:put| and |p| which are always linewise. 1411/// 1412/// @param lines |readfile()|-style list of lines. |channel-lines| 1413/// @param type Edit behavior: any |getregtype()| result, or: 1414/// - "b" |blockwise-visual| mode (may include width, e.g. "b3") 1415/// - "c" |charwise| mode 1416/// - "l" |linewise| mode 1417/// - "" guess by contents, see |setreg()| 1418/// @param after If true insert after cursor (like |p|), or before (like |P|). 1419/// @param follow If true place cursor at end of inserted text. 1420/// @param[out] err Error details, if any 1421void nvim_put (ArrayOf (String )lines ,String type ,Boolean after ,Boolean follow ,Arena * arena , 1422Error * err ) 1423FUNC_API_SINCE (6 ) 1424FUNC_API_TEXTLOCK 1425{ 1426yankreg_T reg [1 ]= {0 }; 1427VALIDATE_S ((prepare_yankreg_from_object (reg ,type ,lines .size )),"type" ,type .data , { 1428return ; 1429 }); 1430if (lines .size == 0 ) { 1431return ;// Nothing to do. 1432 } 1433 1434reg -> y_array = arena_alloc (arena ,lines .size * sizeof (String ), true); 1435reg -> y_size = lines .size ; 1436for (size_t i = 0 ;i < lines .size ;i ++ ) { 1437VALIDATE_T ("line" ,kObjectTypeString ,lines .items [i ].type , { 1438return ; 1439 }); 1440String line = lines .items [i ].data .string ; 1441reg -> y_array [i ]= copy_string (line ,arena ); 1442memchrsub (reg -> y_array [i ].data ,NUL ,NL ,line .size ); 1443 } 1444 1445finish_yankreg_from_object (reg , false); 1446 1447TRY_WRAP (err , { 1448bool VIsual_was_active = Visual .active ; 1449msg_silent ++ ;// Avoid "N more lines" message. 1450do_put ('_' ,reg ,after ?FORWARD :BACKWARD ,1 ,follow ?PUT_CURSEND :0 ); 1451msg_silent -- ; 1452Visual .active = VIsual_was_active ; 1453 }); 1454} 1455 1456/// Returns the 24-bit RGB value of a |nvim_get_color_map()| color name or 1457/// "#rrggbb" hexadecimal string. 1458/// 1459/// Example: 1460/// 1461/// ```vim 1462/// :echo nvim_get_color_by_name("Pink") 1463/// :echo nvim_get_color_by_name("#cbcbcb") 1464/// ``` 1465/// 1466/// @param name Color name or "#rrggbb" string 1467/// @return 24-bit RGB value, or -1 for invalid argument. 1468Integer nvim_get_color_by_name (String name ) 1469FUNC_API_SINCE (1 ) 1470{ 1471int dummy ; 1472return name_to_color (name .data ,& dummy ); 1473} 1474 1475/// Returns a map of color names and RGB values. 1476/// 1477/// Keys are color names (e.g. "Aqua") and values are 24-bit RGB color values 1478/// (e.g. 65535). 1479/// 1480/// @return Map of color names and RGB values. 1481DictOf (Integer )nvim_get_color_map (Arena * arena ) 1482FUNC_API_SINCE (1 ) 1483{ 1484DictOf (Integer )colors = arena_dict (arena ,ARRAY_SIZE (color_name_table )); 1485 1486for (int i = 0 ;color_name_table [i ].name != NULL ;i ++ ) { 1487PUT_C (colors ,color_name_table [i ].name ,INTEGER_OBJ (color_name_table [i ].color )); 1488 } 1489return colors ; 1490} 1491 1492/// Gets a map (msgpack encoding) of the current editor state: 1493/// 1494/// - "bufs" [buffer-list] 1495/// - "funcs" Vimscript global and [script-local] functions 1496/// - "gvars" [global-variable]s 1497/// - "jumps" [jumplist] 1498/// - "regs" [registers] 1499/// - "sfuncs" Vimscript [script-local] functions 1500/// 1501/// @param opts Optional parameters. 1502/// - types: List of context types (see above) to gather, or empty for "all". 1503/// @param[out] err Error details, if any 1504/// 1505/// @return Editor state as a msgpack-encoded map. 1506Dict nvim_get_context (Dict (context )* opts ,Arena * arena ,Error * err ) 1507FUNC_API_SINCE (6 ) 1508{ 1509Array types = ARRAY_DICT_INIT ; 1510if (HAS_KEY (opts ,context ,types )) { 1511types = opts -> types ; 1512 } 1513 1514CtxStateFlags int_types = types .size > 0 ?0 :kCtxAll ; 1515if (types .size > 0 ) { 1516for (size_t i = 0 ;i < types .size ;i ++ ) { 1517if (types .items [i ].type == kObjectTypeString ) { 1518const char * const s = types .items [i ].data .string .data ; 1519if (strequal (s ,"regs" )) { 1520int_types |=kCtxRegs ; 1521 }else if (strequal (s ,"jumps" )) { 1522int_types |=kCtxJumps ; 1523 }else if (strequal (s ,"bufs" )) { 1524int_types |=kCtxBufs ; 1525 }else if (strequal (s ,"gvars" )) { 1526int_types |=kCtxGVars ; 1527 }else if (strequal (s ,"sfuncs" )) { 1528int_types |=kCtxSFuncs ; 1529 }else if (strequal (s ,"funcs" )) { 1530int_types |=kCtxFuncs ; 1531 }else { 1532VALIDATE_S (false,"type" ,s , { 1533return (Dict )ARRAY_DICT_INIT ; 1534 }); 1535 } 1536 } 1537 } 1538 } 1539 1540Context ctx = CONTEXT_INIT ; 1541ctx_save (& ctx ,int_types ); 1542Dict dict = ctx_to_dict (& ctx ,arena ); 1543ctx_free (& ctx ); 1544return dict ; 1545} 1546 1547/// Sets the current editor state from the given map. 1548/// 1549/// @param dict Msgpack-encoded editor state, in the form returned by [nvim_get_context()]. 1550Object nvim_load_context (Dict dict ,Error * err ) 1551FUNC_API_SINCE (6 ) 1552{ 1553Context ctx = CONTEXT_INIT ; 1554 1555int save_did_emsg = did_emsg ; 1556did_emsg = false; 1557 1558ctx_from_dict (dict ,& ctx ,err ); 1559if (!ERROR_SET (err )) { 1560ctx_load (& ctx ,kCtxAll ,0 ); 1561 } 1562 1563ctx_free (& ctx ); 1564 1565did_emsg = save_did_emsg ; 1566return (Object )OBJECT_INIT ; 1567} 1568 1569/// Gets the current mode. |mode()| 1570/// "blocking" is true if Nvim is waiting for input. 1571/// 1572/// @returns Dict { "mode": String, "blocking": Boolean } 1573DictAs (get_mode )nvim_get_mode (Arena * arena ) 1574FUNC_API_SINCE (2 )FUNC_API_FAST 1575{ 1576Dict rv = arena_dict (arena ,2 ); 1577char * modestr = arena_alloc (arena ,MODE_MAX_LENGTH , false); 1578get_mode (modestr ); 1579bool blocked = input_blocking (); 1580 1581PUT_C (rv ,"mode" ,CSTR_AS_OBJ (modestr )); 1582PUT_C (rv ,"blocking" ,BOOLEAN_OBJ (blocked )); 1583 1584return rv ; 1585} 1586 1587/// Gets a list of global (non-buffer-local) |mapping| definitions. 1588/// 1589/// @param mode Mode short-name ("n", "i", "v", ...) 1590/// @returns Array of |maparg()|-like dictionaries describing mappings. 1591/// The "buf" key is always zero. 1592ArrayOf (DictAs (get_keymap ))nvim_get_keymap (String mode ,Arena * arena ) 1593FUNC_API_SINCE (3 ) 1594{ 1595return keymap_array (mode ,NULL ,arena ); 1596} 1597 1598/// Sets a global |mapping| for the given mode. 1599/// 1600/// To set a buffer-local mapping, use |nvim_buf_set_keymap()|. 1601/// 1602/// Unlike |:map|, leading/trailing whitespace is accepted as part of the {lhs} or {rhs}. 1603/// Empty {rhs} is [<Nop>]. |keycodes| are replaced as usual. 1604/// 1605/// Example: 1606/// 1607/// ```vim 1608/// call nvim_set_keymap('n', ' <NL>', '', {'nowait': v:true}) 1609/// ``` 1610/// 1611/// is equivalent to: 1612/// 1613/// ```vim 1614/// nmap <nowait> <Space><NL> <Nop> 1615/// ``` 1616/// 1617/// @param channel_id Channel id (implicit dispatcher arg) 1618/// @param mode Mode short-name (map command prefix: "n", "i", "v", "x", …) 1619/// or "!" for |:map!|, or empty string for |:map|. 1620/// "ia", "ca" or "!a" for abbreviation in Insert mode, Cmdline mode, or both, respectively 1621/// @param lhs Left-hand-side |{lhs}| of the mapping. 1622/// @param rhs Right-hand-side |{rhs}| of the mapping. 1623/// @param opts Optional parameters map: Accepts all |:map-arguments| as keys except [<buffer>], 1624/// values are booleans (default false). Also: 1625/// - "callback" Lua function called in place of {rhs}. 1626/// - "desc" human-readable description. 1627/// - "noremap" disables |recursive_mapping|, like |:noremap| 1628/// - "replace_keycodes" (boolean) When "expr" is true, replace keycodes in the 1629/// resulting string (see |nvim_replace_termcodes()|). Returning nil from the Lua 1630/// "callback" is equivalent to returning an empty string. 1631/// @param[out] err Error details, if any. 1632void nvim_set_keymap (uint64_t channel_id ,String mode ,String lhs ,String rhs ,Dict (keymap )* opts , 1633Error * err ) 1634FUNC_API_SINCE (6 ) 1635{ 1636modify_keymap (channel_id ,-1 ,MAPTYPE_MAP ,mode ,lhs ,rhs ,opts ,err ); 1637} 1638 1639/// Unmaps a global |mapping| for the given mode. 1640/// 1641/// To unmap a buffer-local mapping, use |nvim_buf_del_keymap()|. 1642/// 1643/// @param mode Mode short-name ("n", "i", "v", ...) 1644/// @param lhs Left-hand-side |{lhs}| of the mapping. 1645/// @param opts Optional parameters. 1646/// - lhs: When true, only match {lhs}, not {rhs}. 1647/// 1648/// @see |nvim_set_keymap()| 1649void nvim_del_keymap (uint64_t channel_id ,String mode ,String lhs ,Dict (keymap_del )* opts , 1650Error * err ) 1651FUNC_API_SINCE (6 ) 1652{ 1653nvim_buf_del_keymap (channel_id ,-1 ,mode ,lhs ,opts ,err ); 1654} 1655 1656/// Returns a 2-tuple (Array), where item 0 is the current channel id and item 1657/// 1 is the |api-metadata| map (Dict). 1658/// 1659/// @returns 2-tuple `[{channel-id}, {api-metadata}]` 1660ArrayOf (Object ,2 )nvim_get_api_info (uint64_t channel_id ,Arena * arena ) 1661FUNC_API_SINCE (1 )FUNC_API_FAST FUNC_API_REMOTE_ONLY 1662{ 1663Array rv = arena_array (arena ,2 ); 1664 1665assert (channel_id <=INT64_MAX ); 1666ADD_C (rv ,INTEGER_OBJ ((int64_t )channel_id )); 1667ADD_C (rv ,api_metadata ()); 1668 1669return rv ; 1670} 1671 1672/// Self-identifies the client, and sets optional flags on the channel. Defines the `client` object 1673/// returned by |nvim_get_chan_info()|. 1674/// 1675/// Clients should call this just after connecting, to provide hints for debugging and 1676/// orchestration. (Note: Something is better than nothing! Fields are optional, but at least set 1677/// `name`.) 1678/// 1679/// Can be called more than once; caller should merge old info if appropriate. Example: a library 1680/// first identifies the channel, then a plugin using that library later identifies itself. 1681/// 1682/// @param channel_id Channel id (implicit dispatcher arg) 1683/// @param name Client short-name. Sets the `client.name` field of |nvim_get_chan_info()|. 1684/// @param version Dict describing the version, with these 1685/// (optional) keys: 1686/// - "commit" hash or similar identifier of commit 1687/// - "major" major version (defaults to 0 if not set, for no release yet) 1688/// - "minor" minor version 1689/// - "patch" patch number 1690/// - "prerelease" string describing a prerelease, like "dev" or "beta1" 1691/// @param type Must be one of the following values. Client libraries should 1692/// default to "remote" unless overridden by the user. 1693/// - "embedder" application using Nvim as a component (for example, 1694/// IDE/editor implementing a vim mode). 1695/// - "host" plugin host, typically started by nvim 1696/// - "msgpack-rpc" remote client connected to Nvim via fully MessagePack-RPC 1697/// compliant protocol. 1698/// - "plugin" single plugin, started by nvim 1699/// - "remote" remote client connected "Nvim flavored" MessagePack-RPC (responses 1700/// must be in reverse order of requests). |msgpack-rpc| 1701/// - "ui" gui frontend 1702/// @param methods Builtin methods in the client. For a host, this does not 1703/// include plugin methods which will be discovered later. 1704/// The key should be the method name, the values are dicts with 1705/// these (optional) keys (more keys may be added in future 1706/// versions of Nvim, thus unknown keys are ignored. Clients 1707/// must only use keys defined in this or later versions of 1708/// Nvim): 1709/// - "async" if true, send as a notification. If false or unspecified, 1710/// use a blocking request 1711/// - "nargs" Number of arguments. Could be a single integer or an array 1712/// of two integers, minimum and maximum inclusive. 1713/// 1714/// @param attributes Arbitrary string:string map of informal client properties. 1715/// Suggested keys: 1716/// - "license": License description ("Apache 2", "GPLv3", "MIT", …) 1717/// - "logo": URI or path to image, preferably small logo or icon. 1718/// .png or .svg format is preferred. 1719/// - "pid": Process id. 1720/// - "website": Client homepage URL (e.g. GitHub repository) 1721/// 1722/// @param[out] err Error details, if any 1723void nvim_set_client_info (uint64_t channel_id ,String name ,Dict version ,String type ,Dict methods , 1724Dict attributes ,Arena * arena ,Error * err ) 1725FUNC_API_SINCE (4 )FUNC_API_REMOTE_ONLY 1726{ 1727MAXSIZE_TEMP_DICT (info ,5 ); 1728PUT_C (info ,"name" ,STRING_OBJ (name )); 1729 1730bool has_major = false; 1731for (size_t i = 0 ;i < version .size ;i ++ ) { 1732if (strequal (version .items [i ].key .data ,"major" )) { 1733has_major = true; 1734break ; 1735 } 1736 } 1737if (!has_major ) { 1738Dict v = arena_dict (arena ,version .size + 1 ); 1739if (version .size ) { 1740memcpy (v .items ,version .items ,version .size * sizeof (v .items [0 ])); 1741v .size = version .size ; 1742 } 1743PUT_C (v ,"major" ,INTEGER_OBJ (0 )); 1744version = v ; 1745 } 1746PUT_C (info ,"version" ,DICT_OBJ (version )); 1747 1748PUT_C (info ,"type" ,STRING_OBJ (type )); 1749PUT_C (info ,"methods" ,DICT_OBJ (methods )); 1750PUT_C (info ,"attributes" ,DICT_OBJ (attributes )); 1751 1752rpc_set_client_info (channel_id ,copy_dict (info ,NULL )); 1753} 1754 1755/// Sets the detach flag for the channel. 1756/// 1757/// Detached channels do not trigger self-exit when they are closed. 1758/// 1759/// @param channel_id 1760/// @param detach New detach value for the channel. 1761/// @param[out] err Error details, if any. 1762void nvim__chan_set_detach (uint64_t channel_id ,Boolean detach ,Error * err ) 1763FUNC_API_SINCE (14 )FUNC_API_REMOTE_ONLY 1764{ 1765Channel * chan = find_channel (channel_id ); 1766VALIDATE (chan != NULL ,"%s" ,e_invchan , { 1767return ; 1768 }); 1769 1770chan -> detach = (bool )detach ; 1771} 1772 1773/// Records the cmdwin scratchbuf and type, or clears both when type="" / buf=0. Internal use only. 1774/// 1775/// @param type ':', '/', '?' (first char only); empty to clear. 1776/// @param buf cmdwin buffer id, or 0 to clear. 1777/// @param[out] err Error details, if any. 1778void nvim__cmdwin_set (String type ,Buffer buf ,Error * err ) 1779FUNC_API_SINCE (14 ) 1780{ 1781if (type .size == 0 || buf == 0 ) { 1782cmdwin_type = 0 ; 1783cmdwin_buf = NULL ; 1784return ; 1785 } 1786buf_T * b = find_buffer_by_handle (buf ,err ); 1787if (ERROR_SET (err )) { 1788return ; 1789 } 1790cmdwin_type = (uint8_t )type .data [0 ]; 1791cmdwin_buf = b ; 1792} 1793 1794/// Gets information about a channel. 1795/// 1796/// See |nvim_list_uis()| for an example of how to get channel info. 1797/// 1798/// @param chan channel_id, or 0 for current channel 1799/// @returns Channel info dict with these keys: 1800/// - "id" Channel id. 1801/// - "argv" (optional) Job arguments list. 1802/// - "stream" Stream underlying the channel. 1803/// - "stdio" stdin and stdout of this Nvim instance 1804/// - "stderr" stderr of this Nvim instance 1805/// - "socket" TCP/IP socket or named pipe 1806/// - "job" Job with communication over its stdio. 1807/// - "mode" How data received on the channel is interpreted. 1808/// - "bytes" Send and receive raw bytes. 1809/// - "terminal" |terminal| instance interprets ASCII sequences. 1810/// - "rpc" |RPC| communication on the channel is active. 1811/// - "pty" (optional) Name of pseudoterminal. On a POSIX system this is a device path like 1812/// "/dev/pts/1". If unknown, the key will still be present if a pty is used (e.g. 1813/// for conpty on Windows). 1814/// - "buf" (optional) Buffer connected to |terminal| instance. 1815/// - "buffer" (optional) Deprecated alias for `buf`. 1816/// - "client" (optional) Info about the peer (client on the other end of the channel), as set 1817/// by |nvim_set_client_info()|. 1818/// - "exitcode" (optional) Exit code of the |terminal| process. 1819/// 1820Dict nvim_get_chan_info (uint64_t channel_id ,Integer chan ,Arena * arena ,Error * err ) 1821FUNC_API_SINCE (4 ) 1822{ 1823if (chan < 0 ) { 1824return (Dict )ARRAY_DICT_INIT ; 1825 } 1826 1827if (chan == 0 && !is_internal_call (channel_id )) { 1828assert (channel_id <=INT64_MAX ); 1829chan = (Integer )channel_id ; 1830 } 1831return channel_info ((uint64_t )chan ,arena ); 1832} 1833 1834/// Get information about all open channels. 1835/// 1836/// @returns Array of Dictionaries, each describing a channel with 1837/// the format specified at |nvim_get_chan_info()|. 1838ArrayOf (Dict )nvim_list_chans (Arena * arena ) 1839FUNC_API_SINCE (4 ) 1840{ 1841return channel_all_info (arena ); 1842} 1843 1844// Functions used for testing purposes 1845 1846/// Returns object given as argument. 1847/// 1848/// This API function is used for testing. One should not rely on its presence 1849/// in plugins. 1850/// 1851/// @param[in] obj Object to return. 1852/// 1853/// @return its argument. 1854Object nvim__id (Object obj ,Arena * arena ) 1855{ 1856return copy_object (obj ,arena ); 1857} 1858 1859/// Returns array given as argument. 1860/// 1861/// This API function is used for testing. One should not rely on its presence 1862/// in plugins. 1863/// 1864/// @param[in] arr Array to return. 1865/// 1866/// @return its argument. 1867Array nvim__id_array (Array arr ,Arena * arena ) 1868{ 1869return copy_array (arr ,arena ); 1870} 1871 1872/// Returns dict given as argument. 1873/// 1874/// This API function is used for testing. One should not rely on its presence 1875/// in plugins. 1876/// 1877/// @param[in] dct Dict to return. 1878/// 1879/// @return its argument. 1880Dict nvim__id_dict (Dict dct ,Arena * arena ) 1881{ 1882return copy_dict (dct ,arena ); 1883} 1884 1885/// Returns floating-point value given as argument. 1886/// 1887/// This API function is used for testing. One should not rely on its presence 1888/// in plugins. 1889/// 1890/// @param[in] flt Value to return. 1891/// 1892/// @return its argument. 1893Float nvim__id_float (Float flt ) 1894{ 1895return flt ; 1896} 1897 1898/// Gets internal stats. 1899/// 1900/// @return Map of various internal stats. 1901Dict nvim__stats (Arena * arena ) 1902{ 1903Dict rv = arena_dict (arena ,6 ); 1904PUT_C (rv ,"fsync" ,INTEGER_OBJ (g_stats .fsync )); 1905PUT_C (rv ,"log_skip" ,INTEGER_OBJ (g_stats .log_skip )); 1906PUT_C (rv ,"lua_refcount" ,INTEGER_OBJ (nlua_get_global_ref_count ())); 1907PUT_C (rv ,"redraw" ,INTEGER_OBJ (g_stats .redraw )); 1908PUT_C (rv ,"arena_alloc_count" ,INTEGER_OBJ ((Integer )arena_alloc_count )); 1909PUT_C (rv ,"ts_query_parse_count" ,INTEGER_OBJ ((Integer )tslua_query_parse_count )); 1910return rv ; 1911} 1912 1913/// Gets a list of dictionaries representing attached UIs. 1914/// 1915/// Example: The Nvim builtin |TUI| sets its channel info as described in |startup-tui|. In 1916/// particular, it sets `client.name` to "nvim-tui". So you can check if the TUI is running by 1917/// inspecting the client name of each UI: 1918/// 1919/// ```lua 1920/// vim.print(vim.api.nvim_get_chan_info(vim.api.nvim_list_uis()[1].chan).client.name) 1921/// ``` 1922/// 1923/// @return Array of UI dictionaries, each with these keys: 1924/// - "height" Requested height of the UI 1925/// - "width" Requested width of the UI 1926/// - "rgb" true if the UI uses RGB colors (false implies |cterm-colors|) 1927/// - "ext_..." Requested UI extensions, see |ui-option| 1928/// - "chan" |channel-id| of remote UI 1929ArrayOf (Dict )nvim_list_uis (Arena * arena ) 1930FUNC_API_SINCE (4 ) 1931{ 1932return ui_array (arena ); 1933} 1934 1935/// Gets the immediate children of process `pid`. 1936/// 1937/// @return Array of child process ids, empty if process not found. 1938Array nvim_get_proc_children (Integer pid ,Arena * arena ,Error * err ) 1939FUNC_API_SINCE (4 ) 1940{ 1941Array rvobj = ARRAY_DICT_INIT ; 1942int * proc_list = NULL ; 1943 1944VALIDATE_INT ((pid > 0 && pid <=INT_MAX ),"pid" ,pid , { 1945 gotoend ; 1946 }); 1947 1948size_t proc_count ; 1949int rv = os_proc_children ((int )pid ,& proc_list ,& proc_count ); 1950if (rv == 2 ) { 1951// syscall failed (possibly because of kernel options), try shelling out. 1952DLOG ("fallback to vim._os_proc_children()" ); 1953MAXSIZE_TEMP_ARRAY (a ,1 ); 1954ADD_C (a ,INTEGER_OBJ (pid )); 1955Object o = NLUA_EXEC_STATIC ("return vim._os_proc_children(...)" ,a ,kRetObject ,arena ,err ); 1956if (o .type == kObjectTypeArray ) { 1957rvobj = o .data .array ; 1958 }else if (!ERROR_SET (err )) { 1959api_set_error (err ,kErrorTypeException , 1960"Failed to get process children. pid=%" PRId64 " error=%d" , 1961pid ,rv ); 1962 } 1963 }else { 1964rvobj = arena_array (arena ,proc_count ); 1965for (size_t i = 0 ;i < proc_count ;i ++ ) { 1966ADD_C (rvobj ,INTEGER_OBJ (proc_list [i ])); 1967 } 1968 } 1969 1970end : 1971xfree (proc_list ); 1972return rvobj ; 1973} 1974 1975/// Gets info describing process `pid`. 1976/// 1977/// @return Map of process properties, or NIL if process not found. 1978Object nvim_get_proc (Integer pid ,Arena * arena ,Error * err ) 1979FUNC_API_SINCE (4 ) 1980{ 1981Object rvobj = NIL ; 1982 1983VALIDATE_INT ((pid > 0 && pid <=INT_MAX ),"pid" ,pid , { 1984return NIL ; 1985 }); 1986 1987#ifdef MSWIN 1988rvobj = DICT_OBJ (os_proc_info ((int )pid ,arena )); 1989if (rvobj .data .dict .size == 0 ) {// Process not found. 1990return NIL ; 1991 } 1992#else 1993// Cross-platform process info APIs are miserable, so use `ps` instead. 1994MAXSIZE_TEMP_ARRAY (a ,1 ); 1995ADD (a ,INTEGER_OBJ (pid )); 1996Object o = NLUA_EXEC_STATIC ("return vim._os_proc_info(...)" ,a ,kRetObject ,arena ,err ); 1997if (o .type == kObjectTypeArray && o .data .array .size == 0 ) { 1998return NIL ;// Process not found. 1999 }else if (o .type == kObjectTypeDict ) { 2000rvobj = o ; 2001 }else if (!ERROR_SET (err )) { 2002api_set_error (err ,kErrorTypeException , 2003"Failed to get process info. pid=%" PRId64 ,pid ); 2004 } 2005#endif 2006return rvobj ; 2007} 2008 2009/// Selects an item in the completion popup menu. 2010/// 2011/// If neither |ins-completion| nor |cmdline-completion| popup menu is active 2012/// this API call is silently ignored. 2013/// Useful for an external UI using |ui-popupmenu| to control the popup menu with the mouse. 2014/// Can also be used in a mapping; use [<Cmd>] |:map-cmd| or a Lua mapping to ensure the mapping 2015/// doesn't end completion mode. 2016/// 2017/// @param item Index (zero-based) of the item to select. Value of -1 selects nothing 2018/// and restores the original text. 2019/// @param insert For |ins-completion|, whether the selection should be inserted in the buffer. 2020/// Ignored for |cmdline-completion|. 2021/// @param finish Finish the completion and dismiss the popup menu. Implies {insert}. 2022/// @param opts Optional parameters. Reserved for future use. 2023/// @param[out] err Error details, if any 2024void nvim_select_popupmenu_item (Integer item ,Boolean insert ,Boolean finish ,Dict (empty )* opts , 2025Error * err ) 2026FUNC_API_SINCE (6 ) 2027{ 2028if (finish ) { 2029insert = true; 2030 } 2031 2032pum_ext_select_item ((int )item ,insert ,finish ); 2033} 2034 2035/// NB: if your UI doesn't use hlstate, this will not return hlstate first time. 2036Array nvim__inspect_cell (Integer grid ,Integer row ,Integer col ,Arena * arena ,Error * err ) 2037{ 2038Array ret = ARRAY_DICT_INIT ; 2039 2040// TODO(bfredl): if grid == 0 we should read from the compositor's buffer. 2041// The only problem is that it does not yet exist. 2042ScreenGrid * g = & default_grid ; 2043if (grid == pum_grid .handle ) { 2044g = & pum_grid ; 2045 }else if (grid > 1 ) { 2046win_T * wp = get_win_by_grid_handle ((handle_T )grid ); 2047VALIDATE_INT ((wp != NULL && wp -> w_grid_alloc .chars != NULL ),"grid handle" ,grid , { 2048return ret ; 2049 }); 2050g = & wp -> w_grid_alloc ; 2051 } 2052 2053if (row < 0 || row >=g -> rows 2054|| col < 0 || col >=g -> cols ) { 2055return ret ; 2056 } 2057ret = arena_array (arena ,3 ); 2058size_t off = g -> line_offset [(size_t )row ]+ (size_t )col ; 2059char * sc_buf = arena_alloc (arena ,MAX_SCHAR_SIZE , false); 2060schar_get (sc_buf ,g -> chars [off ]); 2061ADD_C (ret ,CSTR_AS_OBJ (sc_buf )); 2062int attr = g -> attrs [off ]; 2063ADD_C (ret ,DICT_OBJ (hl_get_attr_by_id (attr , true,arena ,err ))); 2064// will not work first time 2065if (!highlight_use_hlstate ()) { 2066ADD_C (ret ,ARRAY_OBJ (hl_inspect (attr ,arena ))); 2067 } 2068return ret ; 2069} 2070 2071/// @nodoc 2072void nvim__screenshot (String path ) 2073FUNC_API_FAST 2074{ 2075ui_call_screenshot (path ); 2076} 2077 2078/// For testing. The condition in schar_cache_clear_if_full is hard to 2079/// reach, so this function can be used to force a cache clear in a test. 2080void nvim__invalidate_glyph_cache (void ) 2081{ 2082schar_cache_clear (); 2083must_redraw = UPD_CLEAR ; 2084} 2085 2086/// @nodoc 2087/// Returns true if a multicursor cascade is in-progress. 2088Boolean nvim__mcursor_cascading (void ) 2089FUNC_API_SINCE (15 )FUNC_API_FAST 2090{ 2091return mc_replaying (); 2092} 2093 2094/// @nodoc 2095Object nvim__unpack (String str ,Arena * arena ,Error * err ) 2096FUNC_API_FAST 2097{ 2098return unpack (str .data ,str .size ,arena ,err ); 2099} 2100 2101/// Deletes an uppercase/file named mark. See |mark-motions|. 2102/// 2103/// @note Lowercase name (or other buffer-local mark) is an error. 2104/// @param name Mark name 2105/// @return true if the mark was deleted, else false. 2106/// @see |nvim_buf_del_mark()| 2107/// @see |nvim_get_mark()| 2108Boolean nvim_del_mark (String name ,Error * err ) 2109FUNC_API_SINCE (8 ) 2110{ 2111bool res = false; 2112VALIDATE_S ((name .size == 1 ),"mark name (must be a single char)" ,name .data , { 2113return res ; 2114 }); 2115// Only allow file/uppercase marks 2116// TODO(muniter): Refactor this ASCII_ISUPPER macro to a proper function 2117VALIDATE_S ((ASCII_ISUPPER (* name .data )|| ascii_isdigit (* name .data )), 2118"mark name (must be file/uppercase)" ,name .data , { 2119return res ; 2120 }); 2121res = set_mark (NULL ,name ,0 ,0 ,err ); 2122return res ; 2123} 2124 2125/// Returns a `(row, col, buffer, buffername)` tuple representing the position 2126/// of the uppercase/file named mark. "End of line" column position is returned 2127/// as |v:maxcol| (big number). See |mark-motions|. 2128/// 2129/// Marks are (1,0)-indexed. |api-indexing| 2130/// 2131/// @note Lowercase name (or other buffer-local mark) is an error. 2132/// @param name Mark name 2133/// @param opts Optional parameters. Reserved for future use. 2134/// @return 4-tuple (row, col, buffer, buffername), (0, 0, 0, '') if the mark is 2135/// not set. 2136/// @see |nvim_buf_set_mark()| 2137/// @see |nvim_del_mark()| 2138Tuple (Integer ,Integer ,Buffer ,String )nvim_get_mark (String name ,Dict (empty )* opts ,Arena * arena , 2139Error * err ) 2140FUNC_API_SINCE (8 ) 2141{ 2142Array rv = ARRAY_DICT_INIT ; 2143 2144VALIDATE_S ((name .size == 1 ),"mark name (must be a single char)" ,name .data , { 2145return rv ; 2146 }); 2147VALIDATE_S ((ASCII_ISUPPER (* name .data )|| ascii_isdigit (* name .data )), 2148"mark name (must be file/uppercase)" ,name .data , { 2149return rv ; 2150 }); 2151 2152xfmark_T * mark = mark_get_global (false,* name .data );// false avoids loading the mark buffer 2153pos_T pos = mark -> fmark .mark ; 2154bool allocated = false; 2155int bufnr ; 2156char * filename ; 2157 2158// Marks are from an open buffer it fnum is non zero 2159if (mark -> fmark .fnum != 0 ) { 2160bufnr = mark -> fmark .fnum ; 2161filename = buflist_nr2name (bufnr , true, true); 2162allocated = true; 2163// Marks comes from shada 2164 }else { 2165filename = mark -> fname ; 2166bufnr = 0 ; 2167 } 2168 2169bool exists = filename != NULL ; 2170Integer row ; 2171Integer col ; 2172 2173if (!exists || pos .lnum <=0 ) { 2174if (allocated ) { 2175xfree (filename ); 2176allocated = false; 2177 } 2178filename = "" ; 2179bufnr = 0 ; 2180row = 0 ; 2181col = 0 ; 2182 }else { 2183row = pos .lnum ; 2184col = pos .col ; 2185 } 2186 2187rv = arena_array (arena ,4 ); 2188ADD_C (rv ,INTEGER_OBJ (row )); 2189ADD_C (rv ,INTEGER_OBJ (col )); 2190ADD_C (rv ,INTEGER_OBJ (bufnr )); 2191ADD_C (rv ,CSTR_TO_ARENA_OBJ (arena ,filename )); 2192 2193if (allocated ) { 2194xfree (filename ); 2195 } 2196 2197return rv ; 2198} 2199 2200/// Evaluates statusline string. 2201/// 2202/// @param str Statusline string (see 'statusline'). 2203/// @param opts Optional parameters. 2204/// - fillchar: (string) Character to fill blank spaces in the statusline (see 2205/// 'fillchars'). Treated as single-width even if it isn't. 2206/// - highlights: (boolean) Return highlight information. 2207/// - maxwidth: (number) Maximum width of statusline. 2208/// - use_statuscol_lnum: (number) Evaluate statuscolumn for this line number instead of statusline. 2209/// - use_tabline: (boolean) Evaluate tabline instead of statusline. When true, {winid} 2210/// is ignored. Mutually exclusive with {use_winbar}. 2211/// - use_winbar: (boolean) Evaluate winbar instead of statusline. 2212/// - winid: (number) |window-ID| of the window to use as context for statusline. 2213/// 2214/// @param[out] err Error details, if any. 2215/// @return Dict containing statusline information, with these keys: 2216/// - str: (string) Characters that will be displayed on the statusline. 2217/// - width: (number) Display width of the statusline. 2218/// - highlights: Array containing highlight information of the statusline. Only included when 2219/// the "highlights" key in {opts} is true. Each element of the array is a 2220/// |Dict| with these keys: 2221/// - start: (number) Byte index (0-based) of first character that uses the highlight. 2222/// - group: (string) Deprecated. Use `groups` instead. 2223/// - groups: (array) Names of stacked highlight groups (highest priority last). 2224DictAs (eval_statusline_ret )nvim_eval_statusline (String str ,Dict (eval_statusline )* opts , 2225Arena * arena ,Error * err ) 2226FUNC_API_SINCE (8 )FUNC_API_FAST 2227{ 2228Dict result = ARRAY_DICT_INIT ; 2229 2230int maxwidth ; 2231schar_T fillchar = 0 ; 2232int statuscol_lnum = 0 ; 2233 2234if (str .size < 2 || memcmp (str .data ,"%!" ,2 )!= 0 ) { 2235const CharBuf errbuf = { (char [ERR_BUFLEN ]){0 },ERR_BUFLEN }; 2236const char * const errmsg = check_stl_option (str .data ,& errbuf ); 2237VALIDATE (!errmsg ,"%s" ,errmsg , { 2238return result ; 2239 }); 2240 } 2241 2242Window window = opts -> winid ; 2243 2244if (HAS_KEY (opts ,eval_statusline ,fillchar )) { 2245VALIDATE_EXP ((* opts -> fillchar .data != 0 2246&& ((size_t )utfc_ptr2len (opts -> fillchar .data )== opts -> fillchar .size )), 2247"fillchar" ,"single character" ,NULL , { 2248return result ; 2249 }); 2250int c ; 2251fillchar = utfc_ptr2schar (opts -> fillchar .data ,& c ); 2252// TODO(bfredl): actually check c is single width 2253 } 2254 2255int use_bools = (int )opts -> use_winbar + (int )opts -> use_tabline ; 2256 2257win_T * wp = opts -> use_tabline ?curwin :find_window_by_handle (window ,err ); 2258if (wp == NULL ) { 2259return result ; 2260 } 2261 2262if (HAS_KEY (opts ,eval_statusline ,use_statuscol_lnum )) { 2263statuscol_lnum = (int )opts -> use_statuscol_lnum ; 2264VALIDATE_RANGE (statuscol_lnum > 0 && statuscol_lnum <=wp -> w_buffer -> b_ml .ml_line_count , 2265"use_statuscol_lnum" , { 2266return result ; 2267 }); 2268use_bools ++ ; 2269 } 2270VALIDATE (use_bools <=1 ,"%s" , 2271"Can only use one of 'use_winbar', 'use_tabline' and 'use_statuscol_lnum'" , { 2272return result ; 2273 }); 2274 2275int stc_hl_id = 0 ; 2276int scl_hl_id = 0 ; 2277statuscol_T statuscol = {0 }; 2278SignTextAttrs sattrs [SIGN_SHOW_MAX ]= {0 }; 2279 2280if (statuscol_lnum ) { 2281int line_id = 0 ; 2282int cul_id = 0 ; 2283int num_id = 0 ; 2284linenr_T lnum = statuscol_lnum ; 2285foldinfo_T cursorline_fi = {0 }; 2286decor_redraw_signs (wp ,wp -> w_buffer ,lnum - 1 ,sattrs ,& line_id ,& cul_id ,& num_id ); 2287 2288statuscol .sattrs = sattrs ; 2289statuscol .foldinfo = fold_info (wp ,lnum ); 2290win_update_cursorline (wp ,& cursorline_fi ); 2291statuscol .sign_cul_id = use_cursor_line_highlight (wp ,lnum ) ?cul_id :0 ; 2292scl_hl_id = use_cursor_line_highlight (wp ,lnum ) ?HLF_CLS :HLF_SC ; 2293 2294if (num_id ) { 2295stc_hl_id = num_id ; 2296 }else if (use_cursor_line_highlight (wp ,lnum )) { 2297stc_hl_id = HLF_CLN ; 2298 }else if (wp -> w_p_rnu ) { 2299stc_hl_id = (lnum < wp -> w_cursor .lnum ?HLF_LNA :HLF_LNB ); 2300 }else { 2301stc_hl_id = HLF_N ; 2302 } 2303 2304set_vim_var_nr (VV_LNUM ,lnum ); 2305set_vim_var_nr (VV_RELNUM ,labs (get_cursor_rel_lnum (wp ,lnum ))); 2306set_vim_var_nr (VV_VIRTNUM ,0 ); 2307 }else if (fillchar == 0 && !opts -> use_tabline ) { 2308if (opts -> use_winbar ) { 2309fillchar = wp -> w_p_fcs_chars .wbr ; 2310 }else { 2311hlf_T group ; 2312fillchar = fillchar_status (& group ,wp ); 2313 } 2314 } 2315 2316if (HAS_KEY (opts ,eval_statusline ,maxwidth )) { 2317maxwidth = (int )opts -> maxwidth ; 2318 }else { 2319maxwidth = statuscol_lnum ?win_col_off (wp ) 2320 : (opts -> use_tabline 2321|| (!opts -> use_winbar 2322&& global_stl_height ()> 0 )) ?Columns :wp -> w_width ; 2323 } 2324 2325result = arena_dict (arena ,3 ); 2326const CharBuf buf = {arena_alloc (arena ,MAXPATHL , false),MAXPATHL }; 2327stl_hlrec_t * hltab ; 2328size_t hltab_len = 0 ; 2329 2330// Temporarily reset 'cursorbind' to prevent side effects from moving the cursor away and back. 2331int p_crb_save = wp -> w_p_crb ; 2332wp -> w_p_crb = false; 2333 2334int width = build_stl_str_hl (wp ,buf ,str .data ,-1 ,0 ,fillchar ,maxwidth , 2335opts -> highlights ?& hltab :NULL ,& hltab_len ,NULL , 2336statuscol_lnum ?& statuscol :NULL ); 2337 2338PUT_C (result ,"width" ,INTEGER_OBJ (width )); 2339 2340// Restore original value of 'cursorbind' 2341wp -> w_p_crb = p_crb_save ; 2342 2343if (opts -> highlights ) { 2344Array hl_values = arena_array (arena ,hltab_len + 1 ); 2345char user_group [15 ];// strlen("User") + strlen("2147483647") + NUL 2346 2347// If first character doesn't have a defined highlight, 2348// add the default highlight at the beginning of the highlight list 2349const char * dfltname = get_default_stl_hl (opts -> use_tabline ?NULL :wp , 2350opts -> use_winbar ,stc_hl_id ); 2351if (hltab -> start == NULL || (hltab -> start - buf .data )!= 0 ) { 2352Dict hl_info = arena_dict (arena ,3 ); 2353PUT_C (hl_info ,"start" ,INTEGER_OBJ (0 )); 2354PUT_C (hl_info ,"group" ,CSTR_AS_OBJ (dfltname )); 2355Array groups = arena_array (arena ,1 ); 2356ADD_C (groups ,CSTR_AS_OBJ (dfltname )); 2357PUT_C (hl_info ,"groups" ,ARRAY_OBJ (groups )); 2358ADD_C (hl_values ,DICT_OBJ (hl_info )); 2359 } 2360 2361for (stl_hlrec_t * sp = hltab ;sp -> start != NULL ;sp ++ ) { 2362const char * grpname ; 2363if (sp -> userhl == 0 ) { 2364grpname = get_default_stl_hl (opts -> use_tabline ?NULL :wp ,opts -> use_winbar ,stc_hl_id ); 2365 }else if (sp -> userhl < 0 ) { 2366grpname = syn_id2name (- sp -> userhl ); 2367 }else { 2368snprintf (user_group ,sizeof (user_group ),"User%d" ,sp -> userhl ); 2369grpname = arena_strdup (arena ,user_group ); 2370 } 2371 2372const char * combine = sp -> item == STL_SIGNCOL ?syn_id2name (scl_hl_id ) 2373 :sp -> item == STL_FOLDCOL ?grpname :dfltname ; 2374Dict hl_info = arena_dict (arena ,3 ); 2375PUT_C (hl_info ,"start" ,INTEGER_OBJ (sp -> start - buf .data )); 2376PUT_C (hl_info ,"group" ,CSTR_AS_OBJ (grpname )); 2377Array groups = arena_array (arena ,1 + (combine != grpname )); 2378if (combine != grpname ) { 2379ADD_C (groups ,CSTR_AS_OBJ (combine )); 2380 } 2381ADD_C (groups ,CSTR_AS_OBJ (grpname )); 2382PUT_C (hl_info ,"groups" ,ARRAY_OBJ (groups )); 2383ADD_C (hl_values ,DICT_OBJ (hl_info )); 2384 } 2385PUT_C (result ,"highlights" ,ARRAY_OBJ (hl_values )); 2386 } 2387PUT_C (result ,"str" ,CSTR_AS_OBJ (buf .data )); 2388 2389return result ; 2390} 2391 2392/// Sets info for the completion item at the given index. If the info text was shown in a window, 2393/// returns the window and buffer ids, or empty dict if not shown. 2394/// 2395/// @param index Completion candidate index 2396/// @param opts Optional parameters. 2397/// - info: (string) info text. 2398/// @return Dict containing these keys: 2399/// - winid: (integer) floating window id 2400/// - bufnr: (integer) buffer id in floating window 2401DictOf (Integer )nvim__complete_set (Integer index ,Dict (complete_set )* opts ,Arena * arena , 2402Error * err ) 2403{ 2404Dict rv = arena_dict (arena ,2 ); 2405if ((get_cot_flags ()& kOptCotFlagPopup )== 0 ) { 2406api_set_error (err ,kErrorTypeException ,"completeopt option does not include popup" ); 2407return rv ; 2408 } 2409if (HAS_KEY (opts ,complete_set ,info )) { 2410win_T * wp = pum_set_info ((int )index ,opts -> info .data ); 2411if (wp ) { 2412PUT_C (rv ,"winid" ,WINDOW_OBJ (wp -> handle )); 2413PUT_C (rv ,"bufnr" ,BUFFER_OBJ (wp -> w_buffer -> handle )); 2414 } 2415 } 2416return rv ; 2417} 2418 2419static void redraw_status (win_T * wp ,Dict (redraw )* opts ,bool * flush ) 2420{ 2421if (opts -> statuscolumn && * wp -> w_p_stc != NUL ) { 2422wp -> w_nrwidth_line_count = 0 ; 2423changed_window_setting (wp ); 2424 } 2425 2426int old_row_offset = wp -> w_grid .row_offset ; 2427win_grid_alloc (wp ); 2428 2429// Flush later in case winbar was just hidden or shown for the first time, or 2430// statuscolumn is being drawn. 2431if (wp -> w_lines_valid == 0 || wp -> w_grid .row_offset != old_row_offset ) { 2432* flush = true; 2433 } 2434 2435// Mark for redraw in case flush will happen, otherwise redraw now. 2436if (* flush && (opts -> statusline || opts -> winbar )) { 2437wp -> w_redr_status = true; 2438 }else if (opts -> statusline || opts -> winbar ) { 2439win_check_ns_hl (wp ); 2440if (opts -> winbar ) { 2441win_redr_winbar (wp ); 2442 } 2443if (opts -> statusline ) { 2444win_redr_status (wp ); 2445 } 2446win_check_ns_hl (NULL ); 2447 } 2448} 2449 2450/// Instruct Nvim to redraw various components. 2451/// 2452/// @see |:redraw| 2453/// 2454/// @param opts Optional parameters. 2455/// - buf: Target a specific buffer number as described below. 2456/// - cursor: Immediately update cursor position on the screen in 2457/// `win` or the current window. 2458/// - flush: Update the screen with pending updates. 2459/// - range: Redraw a range in `buf`, the buffer in `win` or the 2460/// current buffer (useful for decoration providers). Expects a 2461/// tuple `[first, last]` with the first and last line number 2462/// of the range, 0-based end-exclusive |api-indexing|. 2463/// - statuscolumn: Redraw the 'statuscolumn' in `buf`, `win` or 2464/// all windows. 2465/// - statusline: Redraw the 'statusline' in `buf`, `win` or all 2466/// windows. 2467/// - tabline: Redraw the 'tabline'. 2468/// - valid: When present mark `win`, `buf`, or all windows for 2469/// redraw. When `true`, only redraw changed lines (useful for 2470/// decoration providers). When `false`, forcefully redraw. 2471/// - win: Target a specific |window-ID| as described below. 2472/// - winbar: Redraw the 'winbar' in `buf`, `win` or all windows. 2473void nvim__redraw (Dict (redraw )* opts ,Error * err ) 2474FUNC_API_SINCE (12 ) 2475{ 2476win_T * win = NULL ; 2477buf_T * buf = NULL ; 2478 2479if (HAS_KEY (opts ,redraw ,win )) { 2480win = find_window_by_handle (opts -> win ,err ); 2481if (ERROR_SET (err )) { 2482return ; 2483 } 2484 } 2485 2486if (HAS_KEY (opts ,redraw ,buf )) { 2487VALIDATE (win == NULL ,"%s" ,"cannot use both 'buf' and 'win'" , { 2488return ; 2489 }); 2490buf = find_buffer_by_handle (opts -> buf ,err ); 2491if (ERROR_SET (err )) { 2492return ; 2493 } 2494 } 2495 2496unsigned count = (win != NULL )+ (buf != NULL ); 2497VALIDATE (xpopcount (opts -> is_set__redraw_ )> count ,"%s" ,"at least one action required" , { 2498return ; 2499 }); 2500 2501if (HAS_KEY (opts ,redraw ,valid )) { 2502// UPD_VALID redraw type does not actually do anything on it's own. Setting 2503// it here without scrolling or changing buffer text seems pointless but 2504// the expectation is that this may be called by decoration providers whose 2505// "on_win" callback may set "w_redr_top/bot". 2506int type = opts -> valid ?UPD_VALID :UPD_NOT_VALID ; 2507if (win != NULL ) { 2508redraw_later (win ,type ); 2509 }else if (buf != NULL ) { 2510redraw_buf_later (buf ,type ); 2511 }else { 2512redraw_all_later (type ); 2513 } 2514 } 2515 2516if (HAS_KEY (opts ,redraw ,range )) { 2517VALIDATE (kv_size (opts -> range )== 2 2518&& kv_A (opts -> range ,0 ).type == kObjectTypeInteger 2519&& kv_A (opts -> range ,1 ).type == kObjectTypeInteger 2520&& kv_A (opts -> range ,0 ).data .integer >=0 2521&& kv_A (opts -> range ,1 ).data .integer >=-1 , 2522"%s" ,"Invalid 'range': Expected 2-tuple of Integers" , { 2523return ; 2524 }); 2525int64_t begin_raw = kv_A (opts -> range ,0 ).data .integer ; 2526int64_t end_raw = kv_A (opts -> range ,1 ).data .integer ; 2527 2528buf_T * rbuf = win ?win -> w_buffer : (buf ?buf :curbuf ); 2529linenr_T line_count = rbuf -> b_ml .ml_line_count ; 2530 2531int begin = (int )MIN (begin_raw ,line_count ); 2532int end ; 2533if (end_raw == -1 ) { 2534end = line_count ; 2535 }else { 2536end = (int )MIN (MAX (begin ,end_raw ),line_count ); 2537 } 2538 2539if (begin < end ) { 2540redraw_buf_range_later (rbuf ,1 + begin ,end ); 2541 } 2542 } 2543 2544// Redraw later types require update_screen() so call implicitly unless set to false. 2545if (HAS_KEY (opts ,redraw ,valid )|| HAS_KEY (opts ,redraw ,range )) { 2546opts -> flush = HAS_KEY (opts ,redraw ,flush ) ?opts -> flush : true; 2547 } 2548 2549// When explicitly set to false and only "redraw later" types are present, 2550// don't call ui_flush() either. 2551bool flush_ui = opts -> flush ; 2552if (opts -> tabline ) { 2553// Flush later in case tabline was just hidden or shown for the first time. 2554if (redraw_tabline && firstwin -> w_lines_valid == 0 ) { 2555opts -> flush = true; 2556 }else { 2557draw_tabline (); 2558 } 2559flush_ui = true; 2560 } 2561 2562bool save_lz = p_lz ; 2563int save_rd = RedrawingDisabled ; 2564RedrawingDisabled = 0 ; 2565p_lz = false; 2566if (opts -> statuscolumn || opts -> statusline || opts -> winbar ) { 2567if (win == NULL ) { 2568FOR_ALL_WINDOWS_IN_TAB (wp ,curtab ) { 2569if (buf == NULL || wp -> w_buffer == buf ) { 2570redraw_status (wp ,opts ,& opts -> flush ); 2571 } 2572 } 2573 }else { 2574redraw_status (win ,opts ,& opts -> flush ); 2575 } 2576flush_ui = true; 2577 } 2578 2579win_T * cwin = win ?win :curwin ; 2580// Allow moving cursor to recently opened window and make sure it is drawn #28868. 2581if (opts -> cursor && (!cwin -> w_grid .target || !cwin -> w_grid .target -> valid )) { 2582opts -> flush = true; 2583 } 2584 2585// Redraw pending screen updates when explicitly requested or when determined 2586// that it is necessary to properly draw other requested components. 2587if (opts -> flush && !cmdpreview ) { 2588validate_cursor (curwin ); 2589update_topline (curwin ); 2590update_screen (); 2591 } 2592 2593if (opts -> cursor ) { 2594setcursor_mayforce (cwin , true); 2595flush_ui = true; 2596 } 2597 2598if (flush_ui ) { 2599ui_flush (); 2600 } 2601 2602RedrawingDisabled = save_rd ; 2603p_lz = save_lz ; 2604} 2605 2606void nvim__set_restart_on_crash (String progpath ,Array argv ) 2607{ 2608ui_call__set_restart_on_crash_exit (progpath ,argv ); 2609}