robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
83.8 KiB2609 linesraw
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)
100  FUNC_API_SINCE(7)
101{
102  int ret;
103  TRY_WRAP(err, {
104    ret = syn_check_group(name.data, name.size);
105  });
106  return 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)
126  FUNC_API_SINCE(11)
127{
128  return 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)
183  FUNC_API_SINCE(7)
184{
185  int hl_id;
186  TRY_WRAP(err, {
187    hl_id = syn_check_group(name.data, name.size);
188  });
189  if (ERROR_SET(err) || hl_id == 0) {
190    return;
191  }
192  int link_id = -1;
193
194  // Setting URLs directly through highlight attributes is not supported
195  if (HAS_KEY(val, highlight, url)) {
196    api_set_error(err, kErrorTypeValidation, "Invalid key: 'url'");
197    return;
198  }
199
200  bool update = HAS_KEY(val, highlight, update) && val->update;
201  HlAttrs *base = NULL;
202  HlAttrs base_attrs;
203  if (update && hl_ns_get_attrs((int)ns_id, hl_id, NULL, &base_attrs)) {
204    base = &base_attrs;
205  }
206
207  HlAttrs attrs = dict2hlattrs(val, true, &link_id, base, err);
208  if (!ERROR_SET(err)) {
209    WITH_SCRIPT_CONTEXT(channel_id, {
210      ns_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)
225  FUNC_API_SINCE(12)
226{
227  if (HAS_KEY(opts, get_ns, winid)) {
228    win_T *win = find_window_by_handle(opts->winid, err);
229    if (!win) {
230      return 0;
231    }
232    return win->w_ns_hl;
233  } else {
234    return 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)
244  FUNC_API_SINCE(10)
245{
246  VALIDATE_INT((ns_id >= 0), "namespace", ns_id, {
247    return;
248  });
249
250  ns_hl_global = (NS)ns_id;
251  hl_check_ns();
252  redraw_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)
264  FUNC_API_SINCE(10)
265  FUNC_API_FAST
266{
267  ns_hl_fast = (NS)ns_id;
268  hl_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)
290  FUNC_API_SINCE(1)
291{
292  bool remap = true;
293  bool insert = false;
294  bool typed = false;
295  bool execute = false;
296  bool dangerous = false;
297  bool lowlevel = false;
298
299  for (size_t i = 0; i < mode.size; i++) {
300    switch (mode.data[i]) {
301    case 'n':
302      remap = false; break;
303    case 'm':
304      remap = true; break;
305    case 't':
306      typed = true; break;
307    case 'i':
308      insert = true; break;
309    case 'x':
310      execute = true; break;
311    case '!':
312      dangerous = true; break;
313    case 'L':
314      lowlevel = true; break;
315    }
316  }
317
318  if (keys.size == 0 && !execute) {
319    return;
320  }
321
322  char *keys_esc;
323  if (escape_ks) {
324    // Need to escape K_SPECIAL before putting the string in the
325    // typeahead buffer.
326    keys_esc = vim_strsave_escape_ks(keys.data);
327  } else {
328    keys_esc = keys.data;
329  }
330  if (lowlevel) {
331    input_enqueue_raw(keys_esc, strlen(keys_esc));
332  } else {
333    ins_typebuf(keys_esc, (remap ? REMAP_YES : REMAP_NONE),
334                insert ? 0 : typebuf.tb_len, !typed, false);
335    if (vgetc_busy) {
336      typebuf_was_filled = true;
337    }
338  }
339
340  if (escape_ks) {
341    xfree(keys_esc);
342  }
343
344  if (execute) {
345    int save_msg_scroll = msg_scroll;
346
347    // Avoid a 1 second delay when the keys start Insert mode.
348    msg_scroll = false;
349    if (!dangerous) {
350      ex_normal_busy++;
351    }
352    exec_normal(true, lowlevel);
353    if (!dangerous) {
354      ex_normal_busy--;
355    }
356    msg_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)
377  FUNC_API_SINCE(1) FUNC_API_FAST
378{
379  may_trigger_vim_suspend_resume(false);
380  return (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,
408                      Integer col, Error *err)
409  FUNC_API_SINCE(6) FUNC_API_FAST
410{
411  may_trigger_vim_suspend_resume(false);
412
413  if (button.data == NULL || action.data == NULL) {
414    goto error;
415  }
416
417  int code = 0;
418
419  if (strequal(button.data, "left")) {
420    code = KE_LEFTMOUSE;
421  } else if (strequal(button.data, "middle")) {
422    code = KE_MIDDLEMOUSE;
423  } else if (strequal(button.data, "right")) {
424    code = KE_RIGHTMOUSE;
425  } else if (strequal(button.data, "wheel")) {
426    code = KE_MOUSEDOWN;
427  } else if (strequal(button.data, "x1")) {
428    code = KE_X1MOUSE;
429  } else if (strequal(button.data, "x2")) {
430    code = KE_X2MOUSE;
431  } else if (strequal(button.data, "move")) {
432    code = KE_MOUSEMOVE;
433  } else {
434    goto error;
435  }
436
437  if (code == KE_MOUSEDOWN) {
438    if (strequal(action.data, "down")) {
439      code = KE_MOUSEUP;
440    } else if (strequal(action.data, "up")) {
441      // code = KE_MOUSEDOWN
442    } else if (strequal(action.data, "left")) {
443      code = KE_MOUSERIGHT;
444    } else if (strequal(action.data, "right")) {
445      code = KE_MOUSELEFT;
446    } else {
447      goto error;
448    }
449  } else if (code != KE_MOUSEMOVE) {
450    if (strequal(action.data, "press")) {
451      // pass
452    } else if (strequal(action.data, "drag")) {
453      code += KE_LEFTDRAG - KE_LEFTMOUSE;
454    } else if (strequal(action.data, "release")) {
455      code += KE_LEFTRELEASE - KE_LEFTMOUSE;
456    } else {
457      goto error;
458    }
459  }
460
461  int modmask = 0;
462  for (size_t i = 0; i < modifier.size; i++) {
463    char byte = modifier.data[i];
464    if (byte == '-') {
465      continue;
466    }
467    int mod = name_to_mod_mask(byte);
468    VALIDATE((mod != 0), "Invalid modifier: %c", byte, {
469      return;
470    });
471    modmask |= mod;
472  }
473
474  input_enqueue_mouse(code, (uint8_t)modmask, (int)grid, (int)row, (int)col);
475  return;
476
477error:
478  api_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)
493  FUNC_API_SINCE(1) FUNC_API_FAST FUNC_API_RET_ALLOC
494{
495  if (str.size == 0) {
496    // Empty string
497    return (String) { .data = NULL, .size = 0 };
498  }
499
500  int flags = 0;
501  if (from_part) {
502    flags |= REPTERM_FROM_PART;
503  }
504  if (do_lt) {
505    flags |= REPTERM_DO_LT;
506  }
507  if (!special) {
508    flags |= REPTERM_NO_SPECIAL;
509  }
510
511  char *ptr = NULL;
512  replace_termcodes(str.data, str.size, &ptr, 0, flags, NULL, p_cpo);
513  return 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)
540  FUNC_API_SINCE(7)
541  FUNC_API_REMOTE_ONLY
542{
543  // TODO(bfredl): convert directly from msgpack to lua and then back again
544  return 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)
562  FUNC_API_SINCE(14)
563  FUNC_API_REMOTE_ONLY
564  FUNC_API_FAST
565{
566  return 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)
576  FUNC_API_SINCE(1)
577{
578  VALIDATE_S((text.size <= INT_MAX), "text length", "(too long)", {
579    return 0;
580  });
581
582  return (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)
589  FUNC_API_SINCE(1)
590{
591  return nvim_get_runtime_file(NULL_STRING, true, arena, err);
592}
593
594/// @nodoc
595Array nvim__runtime_inspect(Arena *arena)
596{
597  return runtime_inspect(arena);
598}
599
600typedef struct {
601  ArrayBuilder rv;
602  Arena *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)
618  FUNC_API_SINCE(7)
619  FUNC_API_FAST
620{
621  RuntimeCookie cookie = { .rv = ARRAY_DICT_INIT, .arena = arena, };
622  kvi_init(cookie.rv);
623
624  int flags = DIP_DIRFILE | (all ? DIP_ALL : 0);
625
626  TRY_WRAP(err, {
627    do_in_runtimepath((name.size ? name.data : ""), flags, find_runtime_cb, &cookie);
628  });
629
630  return arena_take_arraybuilder(arena, &cookie.rv);
631}
632
633static bool find_runtime_cb(int num_fnames, char **fnames, bool all, void *c)
634{
635  RuntimeCookie *cookie = (RuntimeCookie *)c;
636  for (int i = 0; i < num_fnames; i++) {
637    // TODO(bfredl): consider memory management of gen_expand_wildcards() itself
638    kvi_push(cookie->rv, CSTR_TO_ARENA_OBJ(cookie->arena, fnames[i]));
639    if (!all) {
640      return true;
641    }
642  }
643
644  return num_fnames > 0;
645}
646
647/// @nodoc
648String nvim__get_lib_dir(void)
649  FUNC_API_RET_ALLOC
650{
651  return 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,
661                                  Arena *arena,
662                                  Error *err)
663  FUNC_API_SINCE(8)
664  FUNC_API_FAST
665{
666  VALIDATE(!opts->do_source || nlua_is_deferred_safe(), "%s", "'do_source' used in fast callback",
667           {});
668  if (ERROR_SET(err)) {
669    return (Array)ARRAY_DICT_INIT;
670  }
671
672  ArrayOf(String) res = runtime_get_named(opts->is_lua, pat, all, arena);
673
674  if (opts->do_source) {
675    for (size_t i = 0; i < res.size; i++) {
676      String name = res.items[i].data.string;
677      do_source(name.data, false, DOSO_NONE, NULL);
678    }
679  }
680
681  return 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)
689  FUNC_API_SINCE(1)
690{
691  VALIDATE_S((dir.size < MAXPATHL), "directory name", "(too long)", {
692    return;
693  });
694
695  TRY_WRAP(err, {
696    do_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)
705  FUNC_API_SINCE(1)
706{
707  return 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)
715  FUNC_API_SINCE(1)
716  FUNC_API_TEXTLOCK
717{
718  buffer_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)
725  FUNC_API_SINCE(1)
726  FUNC_API_TEXTLOCK
727{
728  buffer_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)
737  FUNC_API_SINCE(1)
738{
739  dictitem_T *di = tv_dict_find(get_globvar_dict(), name.data, (ptrdiff_t)name.size);
740  if (di == NULL) {  // try to autoload script
741    bool found = script_autoload(name.data, name.size, false) && !aborting();
742    VALIDATE(found, "Key not found: %s", name.data, {
743      return (Object)OBJECT_INIT;
744    });
745    di = tv_dict_find(get_globvar_dict(), name.data, (ptrdiff_t)name.size);
746  }
747  VALIDATE((di != NULL), "Key not found: %s", name.data, {
748    return (Object)OBJECT_INIT;
749  });
750  return 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)
759  FUNC_API_SINCE(1)
760{
761  dict_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)
769  FUNC_API_SINCE(1)
770{
771  dict_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)
780  FUNC_API_SINCE(1)
781{
782  return 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)
791  FUNC_API_SINCE(6)
792{
793  dict_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,
833                                 Dict(echo_opts) *opts, Error *err)
834  FUNC_API_SINCE(7)
835{
836  MsgID id = INTEGER_OBJ(-1);
837  HlMessage hl_msg = parse_hl_msg(chunks, opts->err, err);
838  if (ERROR_SET(err)) {
839    goto error;
840  }
841
842  char *kind = opts->kind.data;
843  if (opts->verbose) {
844    verbose_enter();
845  } else if (kind == NULL) {
846    kind = opts->err ? "echoerr" : history ? "echomsg" : "echo";
847  }
848
849  bool is_progress = strequal(kind, "progress");
850  bool needs_clear = !history;
851
852  VALIDATE(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    goto error;
858  });
859
860  VALIDATE_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    goto error;
866  });
867
868  VALIDATE_RANGE(!is_progress || !HAS_KEY(opts, echo_opts, percent)
869                 || (opts->percent >= 0 && opts->percent <= 100),
870                 "percent", {
871    goto error;
872  });
873
874  VALIDATE_R(!is_progress || opts->source.size != 0, "opts.source", {
875    goto error;
876  });
877  VALIDATE_S(!is_progress || !strequal(opts->source.data, "nvim"), "source", opts->source.data, {
878    goto error;
879  });
880
881  // Message-id may be user-defined only if String, not Integer.
882  VALIDATE_INT(opts->id.type != kObjectTypeInteger || msg_id_exists(opts->id.data.integer),
883               "id", opts->id.data.integer, {
884    goto error;
885  });
886
887  MessageData 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
891  const bool save_nwr = need_wait_return;
892  const int save_lines_left = lines_left;
893  const bool save_msg_didany = msg_didany;
894  // Similar truncation method to showmode().
895  // TODO(justinmk): drop _truncate feature after ui2 graduates?
896  if (opts->_truncate) {
897    no_wait_return++;
898    lines_left = 0;
899    msg_didany = true;
900    msg_no_more = true;
901  }
902  msg_ext_no_fast();
903  id = msg_multihl(opts->id, hl_msg, kind, history, opts->err, &msg_data, &needs_clear);
904  if (opts->_truncate) {
905    msg_no_more = false;
906    msg_didany = save_msg_didany;
907    lines_left = save_lines_left;
908    no_wait_return--;
909    need_wait_return = save_nwr;
910  }
911
912  if (opts->verbose) {
913    verbose_leave();
914    verbose_stop();  // flush now
915  }
916
917  if (!needs_clear) {
918    // history takes ownership of `hl_msg`
919    return id;
920  }
921
922error:
923  hl_msg_free(hl_msg);
924  return 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)
934  FUNC_API_SINCE(1)
935{
936  size_t n = 0;
937
938  FOR_ALL_BUFFERS(b) {
939    n++;
940  }
941
942  Array rv = arena_array(arena, n);
943
944  FOR_ALL_BUFFERS(b) {
945    ADD_C(rv, BUFFER_OBJ(b->handle));
946  }
947
948  return rv;
949}
950
951/// Gets the current buffer.
952///
953/// @return Buffer id
954Buffer nvim_get_current_buf(void)
955  FUNC_API_SINCE(1)
956{
957  return 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)
965  FUNC_API_SINCE(1)
966  FUNC_API_TEXTLOCK
967{
968  buf_T *b = find_buffer_by_handle(buf, err);
969
970  if (!b) {
971    return;
972  }
973
974  TRY_WRAP(err, {
975    do_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)
983  FUNC_API_SINCE(1)
984{
985  size_t n = 0;
986
987  FOR_ALL_TAB_WINDOWS(tp, wp) {
988    n++;
989  }
990
991  Array rv = arena_array(arena, n);
992
993  FOR_ALL_TAB_WINDOWS(tp, wp) {
994    ADD_C(rv, WINDOW_OBJ(wp->handle));
995  }
996
997  return rv;
998}
999
1000/// Gets the current window.
1001///
1002/// @return |window-ID|
1003Window nvim_get_current_win(void)
1004  FUNC_API_SINCE(1)
1005{
1006  return 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)
1014  FUNC_API_SINCE(1)
1015  FUNC_API_TEXTLOCK
1016{
1017  win_T *w = find_window_by_handle(win, err);
1018
1019  if (!w) {
1020    return;
1021  }
1022
1023  TRY_WRAP(err, {
1024    if (w->w_buffer != curbuf) {
1025      reset_VIsual_and_resel();
1026    }
1027    goto_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)
1039  FUNC_API_SINCE(6)
1040{
1041  Buffer ret = 0;
1042
1043  TRY_WRAP(err, {
1044    // Block autocommands for now so they don't mess with the buffer before we
1045    // finish configuring it.
1046    block_autocmds();
1047
1048    buf_T *buf = buflist_new(NULL, NULL, 0,
1049                             BLN_NOOPT | BLN_NEW | (listed ? BLN_LISTED : 0));
1050    if (buf == NULL) {
1051      unblock_autocmds();
1052      goto fail;
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.
1057    if (ml_open(buf) == FAIL) {
1058      unblock_autocmds();
1059      goto fail;
1060    }
1061
1062    // Set last_changedtick to avoid triggering a TextChanged autocommand right
1063    // after it was added.
1064    buf->b_last_changedtick = buf_get_changedtick(buf);
1065    buf->b_last_changedtick_i = buf_get_changedtick(buf);
1066    buf->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() ..
1071    buf_copy_options(buf, BCO_ENTER | BCO_NOHELP);
1072
1073    if (scratch) {
1074      set_option_direct_for(kOptBufhidden, STATIC_CSTR_AS_OBJ("hide"), OPT_LOCAL, 0,
1075                            kOptScopeBuf, buf);
1076      set_option_direct_for(kOptBuftype, STATIC_CSTR_AS_OBJ("nofile"), OPT_LOCAL, 0,
1077                            kOptScopeBuf, buf);
1078      assert(buf->b_ml.ml_mfp->mf_fd < 0);  // ml_open() should not have opened swapfile already
1079      buf->b_p_swf = false;
1080      buf->b_p_ml = false;
1081    }
1082
1083    unblock_autocmds();
1084
1085    bufref_T bufref;
1086    set_bufref(&bufref, buf);
1087    if (apply_autocmds(EVENT_BUFNEW, NULL, NULL, false, buf)
1088        && !bufref_valid(&bufref)) {
1089      goto fail;
1090    }
1091    if (listed
1092        && apply_autocmds(EVENT_BUFADD, NULL, NULL, false, buf)
1093        && !bufref_valid(&bufref)) {
1094      goto fail;
1095    }
1096
1097    ret = buf->b_fnum;
1098    fail:;
1099  });
1100
1101  if (ret == 0 && !ERROR_SET(err)) {
1102    api_set_error(err, kErrorTypeException, "Failed to create buffer");
1103  }
1104  return 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)
1143  FUNC_API_SINCE(7)
1144  FUNC_API_TEXTLOCK
1145{
1146  buf_T *b = api_buf_ensure_loaded(buf, err);
1147  if (!b) {
1148    return 0;
1149  }
1150
1151  bool may_read_buffer = true;
1152  if (b->terminal) {
1153    if (terminal_running(b->terminal)) {
1154      api_set_error(err, kErrorTypeException,
1155                    "Terminal already connected to buffer %d", b->handle);
1156      return 0;
1157    }
1158    buf_close_terminal(b);
1159    may_read_buffer = false;
1160  }
1161
1162  LuaRef cb = LUA_NOREF;
1163  if (HAS_KEY(opts, open_term, on_input)) {
1164    cb = opts->on_input;
1165    opts->on_input = LUA_NOREF;
1166  }
1167
1168  Channel *chan = channel_alloc(kChannelStreamInternal);
1169  chan->stream.internal.cb = cb;
1170  chan->stream.internal.closed = false;
1171  TerminalOptions 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)
1186  StringBuilder contents = KV_INITIAL_VALUE;
1187  if (may_read_buffer) {
1188    read_buffer_into(b, 1, b->b_ml.ml_line_count, &contents);
1189  }
1190
1191  channel_incref(chan);
1192  chan->term = terminal_alloc(b, topts);
1193  terminal_open(&chan->term, b);
1194  if (chan->term != NULL) {
1195    terminal_check_size(chan->term);
1196  }
1197  channel_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.
1201  if (contents.size > 0) {
1202    const char *error = NULL;
1203    channel_send(chan->id, contents.items, contents.size, true, &error);
1204    VALIDATE(!error, "%s", error, {});
1205  }
1206
1207  return (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{
1217  Channel *chan = data;
1218  LuaRef cb = chan->stream.internal.cb;
1219  if (cb == LUA_NOREF) {
1220    return;
1221  }
1222  MAXSIZE_TEMP_ARRAY(args, 3);
1223  ADD_C(args, INTEGER_OBJ((Integer)chan->id));
1224  ADD_C(args, BUFFER_OBJ(terminal_buf(chan->term)));
1225  ADD_C(args, STRING_OBJ(((String){ .data = (char *)buf, .size = size })));
1226  textlock++;
1227  nlua_call_ref(cb, "input", args, kRetNilBool, NULL, NULL);
1228  textlock--;
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{
1242  Channel *chan = data;
1243  terminal_destroy(&chan->term);
1244  api_free_luaref(chan->stream.internal.cb);
1245  chan->stream.internal.cb = LUA_NOREF;
1246  channel_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)
1263  FUNC_API_SINCE(7) FUNC_API_REMOTE_ONLY FUNC_API_LUA_ONLY
1264{
1265  const char *error = NULL;
1266  if (!data.size) {
1267    return;
1268  }
1269
1270  channel_send((uint64_t)chan, data.data, data.size,
1271               false, &error);
1272  VALIDATE(!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)
1279  FUNC_API_SINCE(1)
1280{
1281  size_t n = 0;
1282
1283  FOR_ALL_TABS(tp) {
1284    n++;
1285  }
1286
1287  Array rv = arena_array(arena, n);
1288
1289  FOR_ALL_TABS(tp) {
1290    ADD_C(rv, TABPAGE_OBJ(tp->handle));
1291  }
1292
1293  return rv;
1294}
1295
1296/// Gets the current tabpage.
1297///
1298/// @return |tab-ID|
1299Tabpage nvim_get_current_tabpage(void)
1300  FUNC_API_SINCE(1)
1301{
1302  return 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)
1310  FUNC_API_SINCE(1)
1311  FUNC_API_TEXTLOCK
1312{
1313  tabpage_T *tp = find_tab_by_handle(tabpage, err);
1314
1315  if (!tp) {
1316    return;
1317  }
1318
1319  TRY_WRAP(err, {
1320    goto_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,
1360                   Error *err)
1361  FUNC_API_SINCE(6)
1362  FUNC_API_TEXTLOCK
1363{
1364  static bool cancelled = false;
1365
1366  VALIDATE_INT((phase >= -1 && phase <= 3), "phase", phase, {
1367    return false;
1368  });
1369  if (phase == -1 || phase == 1) {  // Start of paste-stream.
1370    cancelled = false;
1371    if (curbuf->terminal) {
1372      terminal_set_streamed_paste(curbuf->terminal, true);
1373    }
1374  } else if (cancelled) {
1375    // Skip remaining chunks.  Report error only once per "stream".
1376    goto theend;
1377  }
1378  Array lines = string_to_array(data, crlf, arena);
1379  MAXSIZE_TEMP_ARRAY(args, 2);
1380  ADD_C(args, ARRAY_OBJ(lines));
1381  ADD_C(args, INTEGER_OBJ(phase));
1382  Object rv = NLUA_EXEC_STATIC("return vim.paste(...)", args, kRetNilBool, arena, err);
1383  // vim.paste() decides if client should cancel.
1384  if (ERROR_SET(err) || (rv.type == kObjectTypeBoolean && !rv.data.boolean)) {
1385    cancelled = true;
1386  }
1387  if ((phase == -1 || phase == 3 || cancelled) && curbuf->terminal) {
1388    terminal_set_streamed_paste(curbuf->terminal, false);
1389  }
1390  if (!cancelled && (phase == -1 || phase == 1)) {
1391    paste_store(channel_id, kFalse, NULL_STRING, crlf);
1392  }
1393  if (!cancelled) {
1394    paste_store(channel_id, kNone, data, crlf);
1395  }
1396  if (phase == 3 || phase == (cancelled ? 2 : -1)) {
1397    paste_store(channel_id, kTrue, NULL_STRING, crlf);
1398  }
1399theend:
1400  ;
1401  bool retval = !cancelled;
1402  if (phase == -1 || phase == 3) {  // End of paste-stream.
1403    cancelled = false;
1404  }
1405  return 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,
1422              Error *err)
1423  FUNC_API_SINCE(6)
1424  FUNC_API_TEXTLOCK
1425{
1426  yankreg_T reg[1] = { 0 };
1427  VALIDATE_S((prepare_yankreg_from_object(reg, type, lines.size)), "type", type.data, {
1428    return;
1429  });
1430  if (lines.size == 0) {
1431    return;  // Nothing to do.
1432  }
1433
1434  reg->y_array = arena_alloc(arena, lines.size * sizeof(String), true);
1435  reg->y_size = lines.size;
1436  for (size_t i = 0; i < lines.size; i++) {
1437    VALIDATE_T("line", kObjectTypeString, lines.items[i].type, {
1438      return;
1439    });
1440    String line = lines.items[i].data.string;
1441    reg->y_array[i] = copy_string(line, arena);
1442    memchrsub(reg->y_array[i].data, NUL, NL, line.size);
1443  }
1444
1445  finish_yankreg_from_object(reg, false);
1446
1447  TRY_WRAP(err, {
1448    bool VIsual_was_active = Visual.active;
1449    msg_silent++;  // Avoid "N more lines" message.
1450    do_put('_', reg, after ? FORWARD : BACKWARD, 1, follow ? PUT_CURSEND : 0);
1451    msg_silent--;
1452    Visual.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)
1469  FUNC_API_SINCE(1)
1470{
1471  int dummy;
1472  return 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)
1482  FUNC_API_SINCE(1)
1483{
1484  DictOf(Integer) colors = arena_dict(arena, ARRAY_SIZE(color_name_table));
1485
1486  for (int i = 0; color_name_table[i].name != NULL; i++) {
1487    PUT_C(colors, color_name_table[i].name, INTEGER_OBJ(color_name_table[i].color));
1488  }
1489  return 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)
1507  FUNC_API_SINCE(6)
1508{
1509  Array types = ARRAY_DICT_INIT;
1510  if (HAS_KEY(opts, context, types)) {
1511    types = opts->types;
1512  }
1513
1514  CtxStateFlags int_types = types.size > 0 ? 0 : kCtxAll;
1515  if (types.size > 0) {
1516    for (size_t i = 0; i < types.size; i++) {
1517      if (types.items[i].type == kObjectTypeString) {
1518        const char *const s = types.items[i].data.string.data;
1519        if (strequal(s, "regs")) {
1520          int_types |= kCtxRegs;
1521        } else if (strequal(s, "jumps")) {
1522          int_types |= kCtxJumps;
1523        } else if (strequal(s, "bufs")) {
1524          int_types |= kCtxBufs;
1525        } else if (strequal(s, "gvars")) {
1526          int_types |= kCtxGVars;
1527        } else if (strequal(s, "sfuncs")) {
1528          int_types |= kCtxSFuncs;
1529        } else if (strequal(s, "funcs")) {
1530          int_types |= kCtxFuncs;
1531        } else {
1532          VALIDATE_S(false, "type", s, {
1533            return (Dict)ARRAY_DICT_INIT;
1534          });
1535        }
1536      }
1537    }
1538  }
1539
1540  Context ctx = CONTEXT_INIT;
1541  ctx_save(&ctx, int_types);
1542  Dict dict = ctx_to_dict(&ctx, arena);
1543  ctx_free(&ctx);
1544  return 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)
1551  FUNC_API_SINCE(6)
1552{
1553  Context ctx = CONTEXT_INIT;
1554
1555  int save_did_emsg = did_emsg;
1556  did_emsg = false;
1557
1558  ctx_from_dict(dict, &ctx, err);
1559  if (!ERROR_SET(err)) {
1560    ctx_load(&ctx, kCtxAll, 0);
1561  }
1562
1563  ctx_free(&ctx);
1564
1565  did_emsg = save_did_emsg;
1566  return (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)
1574  FUNC_API_SINCE(2) FUNC_API_FAST
1575{
1576  Dict rv = arena_dict(arena, 2);
1577  char *modestr = arena_alloc(arena, MODE_MAX_LENGTH, false);
1578  get_mode(modestr);
1579  bool blocked = input_blocking();
1580
1581  PUT_C(rv, "mode", CSTR_AS_OBJ(modestr));
1582  PUT_C(rv, "blocking", BOOLEAN_OBJ(blocked));
1583
1584  return 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)
1593  FUNC_API_SINCE(3)
1594{
1595  return 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,
1633                     Error *err)
1634  FUNC_API_SINCE(6)
1635{
1636  modify_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,
1650                     Error *err)
1651  FUNC_API_SINCE(6)
1652{
1653  nvim_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)
1661  FUNC_API_SINCE(1) FUNC_API_FAST FUNC_API_REMOTE_ONLY
1662{
1663  Array rv = arena_array(arena, 2);
1664
1665  assert(channel_id <= INT64_MAX);
1666  ADD_C(rv, INTEGER_OBJ((int64_t)channel_id));
1667  ADD_C(rv, api_metadata());
1668
1669  return 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,
1724                          Dict attributes, Arena *arena, Error *err)
1725  FUNC_API_SINCE(4) FUNC_API_REMOTE_ONLY
1726{
1727  MAXSIZE_TEMP_DICT(info, 5);
1728  PUT_C(info, "name", STRING_OBJ(name));
1729
1730  bool has_major = false;
1731  for (size_t i = 0; i < version.size; i++) {
1732    if (strequal(version.items[i].key.data, "major")) {
1733      has_major = true;
1734      break;
1735    }
1736  }
1737  if (!has_major) {
1738    Dict v = arena_dict(arena, version.size + 1);
1739    if (version.size) {
1740      memcpy(v.items, version.items, version.size * sizeof(v.items[0]));
1741      v.size = version.size;
1742    }
1743    PUT_C(v, "major", INTEGER_OBJ(0));
1744    version = v;
1745  }
1746  PUT_C(info, "version", DICT_OBJ(version));
1747
1748  PUT_C(info, "type", STRING_OBJ(type));
1749  PUT_C(info, "methods", DICT_OBJ(methods));
1750  PUT_C(info, "attributes", DICT_OBJ(attributes));
1751
1752  rpc_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)
1763  FUNC_API_SINCE(14) FUNC_API_REMOTE_ONLY
1764{
1765  Channel *chan = find_channel(channel_id);
1766  VALIDATE(chan != NULL, "%s", e_invchan, {
1767    return;
1768  });
1769
1770  chan->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)
1779  FUNC_API_SINCE(14)
1780{
1781  if (type.size == 0 || buf == 0) {
1782    cmdwin_type = 0;
1783    cmdwin_buf = NULL;
1784    return;
1785  }
1786  buf_T *b = find_buffer_by_handle(buf, err);
1787  if (ERROR_SET(err)) {
1788    return;
1789  }
1790  cmdwin_type = (uint8_t)type.data[0];
1791  cmdwin_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)
1821  FUNC_API_SINCE(4)
1822{
1823  if (chan < 0) {
1824    return (Dict)ARRAY_DICT_INIT;
1825  }
1826
1827  if (chan == 0 && !is_internal_call(channel_id)) {
1828    assert(channel_id <= INT64_MAX);
1829    chan = (Integer)channel_id;
1830  }
1831  return 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)
1839  FUNC_API_SINCE(4)
1840{
1841  return 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{
1856  return 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{
1869  return 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{
1882  return 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{
1895  return flt;
1896}
1897
1898/// Gets internal stats.
1899///
1900/// @return Map of various internal stats.
1901Dict nvim__stats(Arena *arena)
1902{
1903  Dict rv = arena_dict(arena, 6);
1904  PUT_C(rv, "fsync", INTEGER_OBJ(g_stats.fsync));
1905  PUT_C(rv, "log_skip", INTEGER_OBJ(g_stats.log_skip));
1906  PUT_C(rv, "lua_refcount", INTEGER_OBJ(nlua_get_global_ref_count()));
1907  PUT_C(rv, "redraw", INTEGER_OBJ(g_stats.redraw));
1908  PUT_C(rv, "arena_alloc_count", INTEGER_OBJ((Integer)arena_alloc_count));
1909  PUT_C(rv, "ts_query_parse_count", INTEGER_OBJ((Integer)tslua_query_parse_count));
1910  return 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)
1930  FUNC_API_SINCE(4)
1931{
1932  return 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)
1939  FUNC_API_SINCE(4)
1940{
1941  Array rvobj = ARRAY_DICT_INIT;
1942  int *proc_list = NULL;
1943
1944  VALIDATE_INT((pid > 0 && pid <= INT_MAX), "pid", pid, {
1945    goto end;
1946  });
1947
1948  size_t proc_count;
1949  int rv = os_proc_children((int)pid, &proc_list, &proc_count);
1950  if (rv == 2) {
1951    // syscall failed (possibly because of kernel options), try shelling out.
1952    DLOG("fallback to vim._os_proc_children()");
1953    MAXSIZE_TEMP_ARRAY(a, 1);
1954    ADD_C(a, INTEGER_OBJ(pid));
1955    Object o = NLUA_EXEC_STATIC("return vim._os_proc_children(...)", a, kRetObject, arena, err);
1956    if (o.type == kObjectTypeArray) {
1957      rvobj = o.data.array;
1958    } else if (!ERROR_SET(err)) {
1959      api_set_error(err, kErrorTypeException,
1960                    "Failed to get process children. pid=%" PRId64 " error=%d",
1961                    pid, rv);
1962    }
1963  } else {
1964    rvobj = arena_array(arena, proc_count);
1965    for (size_t i = 0; i < proc_count; i++) {
1966      ADD_C(rvobj, INTEGER_OBJ(proc_list[i]));
1967    }
1968  }
1969
1970end:
1971  xfree(proc_list);
1972  return 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)
1979  FUNC_API_SINCE(4)
1980{
1981  Object rvobj = NIL;
1982
1983  VALIDATE_INT((pid > 0 && pid <= INT_MAX), "pid", pid, {
1984    return NIL;
1985  });
1986
1987#ifdef MSWIN
1988  rvobj = DICT_OBJ(os_proc_info((int)pid, arena));
1989  if (rvobj.data.dict.size == 0) {  // Process not found.
1990    return NIL;
1991  }
1992#else
1993  // Cross-platform process info APIs are miserable, so use `ps` instead.
1994  MAXSIZE_TEMP_ARRAY(a, 1);
1995  ADD(a, INTEGER_OBJ(pid));
1996  Object o = NLUA_EXEC_STATIC("return vim._os_proc_info(...)", a, kRetObject, arena, err);
1997  if (o.type == kObjectTypeArray && o.data.array.size == 0) {
1998    return NIL;  // Process not found.
1999  } else if (o.type == kObjectTypeDict) {
2000    rvobj = o;
2001  } else if (!ERROR_SET(err)) {
2002    api_set_error(err, kErrorTypeException,
2003                  "Failed to get process info. pid=%" PRId64, pid);
2004  }
2005#endif
2006  return 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,
2025                                Error *err)
2026  FUNC_API_SINCE(6)
2027{
2028  if (finish) {
2029    insert = true;
2030  }
2031
2032  pum_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{
2038  Array 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.
2042  ScreenGrid *g = &default_grid;
2043  if (grid == pum_grid.handle) {
2044    g = &pum_grid;
2045  } else if (grid > 1) {
2046    win_T *wp = get_win_by_grid_handle((handle_T)grid);
2047    VALIDATE_INT((wp != NULL && wp->w_grid_alloc.chars != NULL), "grid handle", grid, {
2048      return ret;
2049    });
2050    g = &wp->w_grid_alloc;
2051  }
2052
2053  if (row < 0 || row >= g->rows
2054      || col < 0 || col >= g->cols) {
2055    return ret;
2056  }
2057  ret = arena_array(arena, 3);
2058  size_t off = g->line_offset[(size_t)row] + (size_t)col;
2059  char *sc_buf = arena_alloc(arena, MAX_SCHAR_SIZE, false);
2060  schar_get(sc_buf, g->chars[off]);
2061  ADD_C(ret, CSTR_AS_OBJ(sc_buf));
2062  int attr = g->attrs[off];
2063  ADD_C(ret, DICT_OBJ(hl_get_attr_by_id(attr, true, arena, err)));
2064  // will not work first time
2065  if (!highlight_use_hlstate()) {
2066    ADD_C(ret, ARRAY_OBJ(hl_inspect(attr, arena)));
2067  }
2068  return ret;
2069}
2070
2071/// @nodoc
2072void nvim__screenshot(String path)
2073  FUNC_API_FAST
2074{
2075  ui_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{
2082  schar_cache_clear();
2083  must_redraw = UPD_CLEAR;
2084}
2085
2086/// @nodoc
2087/// Returns true if a multicursor cascade is in-progress.
2088Boolean nvim__mcursor_cascading(void)
2089  FUNC_API_SINCE(15) FUNC_API_FAST
2090{
2091  return mc_replaying();
2092}
2093
2094/// @nodoc
2095Object nvim__unpack(String str, Arena *arena, Error *err)
2096  FUNC_API_FAST
2097{
2098  return 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)
2109  FUNC_API_SINCE(8)
2110{
2111  bool res = false;
2112  VALIDATE_S((name.size == 1), "mark name (must be a single char)", name.data, {
2113    return res;
2114  });
2115  // Only allow file/uppercase marks
2116  // TODO(muniter): Refactor this ASCII_ISUPPER macro to a proper function
2117  VALIDATE_S((ASCII_ISUPPER(*name.data) || ascii_isdigit(*name.data)),
2118             "mark name (must be file/uppercase)", name.data, {
2119    return res;
2120  });
2121  res = set_mark(NULL, name, 0, 0, err);
2122  return 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,
2139                                                      Error *err)
2140  FUNC_API_SINCE(8)
2141{
2142  Array rv = ARRAY_DICT_INIT;
2143
2144  VALIDATE_S((name.size == 1), "mark name (must be a single char)", name.data, {
2145    return rv;
2146  });
2147  VALIDATE_S((ASCII_ISUPPER(*name.data) || ascii_isdigit(*name.data)),
2148             "mark name (must be file/uppercase)", name.data, {
2149    return rv;
2150  });
2151
2152  xfmark_T *mark = mark_get_global(false, *name.data);  // false avoids loading the mark buffer
2153  pos_T pos = mark->fmark.mark;
2154  bool allocated = false;
2155  int bufnr;
2156  char *filename;
2157
2158  // Marks are from an open buffer it fnum is non zero
2159  if (mark->fmark.fnum != 0) {
2160    bufnr = mark->fmark.fnum;
2161    filename = buflist_nr2name(bufnr, true, true);
2162    allocated = true;
2163    // Marks comes from shada
2164  } else {
2165    filename = mark->fname;
2166    bufnr = 0;
2167  }
2168
2169  bool exists = filename != NULL;
2170  Integer row;
2171  Integer col;
2172
2173  if (!exists || pos.lnum <= 0) {
2174    if (allocated) {
2175      xfree(filename);
2176      allocated = false;
2177    }
2178    filename = "";
2179    bufnr = 0;
2180    row = 0;
2181    col = 0;
2182  } else {
2183    row = pos.lnum;
2184    col = pos.col;
2185  }
2186
2187  rv = arena_array(arena, 4);
2188  ADD_C(rv, INTEGER_OBJ(row));
2189  ADD_C(rv, INTEGER_OBJ(col));
2190  ADD_C(rv, INTEGER_OBJ(bufnr));
2191  ADD_C(rv, CSTR_TO_ARENA_OBJ(arena, filename));
2192
2193  if (allocated) {
2194    xfree(filename);
2195  }
2196
2197  return 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,
2225                                                 Arena *arena, Error *err)
2226  FUNC_API_SINCE(8) FUNC_API_FAST
2227{
2228  Dict result = ARRAY_DICT_INIT;
2229
2230  int maxwidth;
2231  schar_T fillchar = 0;
2232  int statuscol_lnum = 0;
2233
2234  if (str.size < 2 || memcmp(str.data, "%!", 2) != 0) {
2235    const CharBuf errbuf = { (char[ERR_BUFLEN]){ 0 }, ERR_BUFLEN };
2236    const char *const errmsg = check_stl_option(str.data, &errbuf);
2237    VALIDATE(!errmsg, "%s", errmsg, {
2238      return result;
2239    });
2240  }
2241
2242  Window window = opts->winid;
2243
2244  if (HAS_KEY(opts, eval_statusline, fillchar)) {
2245    VALIDATE_EXP((*opts->fillchar.data != 0
2246                  && ((size_t)utfc_ptr2len(opts->fillchar.data) == opts->fillchar.size)),
2247                 "fillchar", "single character", NULL, {
2248      return result;
2249    });
2250    int c;
2251    fillchar = utfc_ptr2schar(opts->fillchar.data, &c);
2252    // TODO(bfredl): actually check c is single width
2253  }
2254
2255  int use_bools = (int)opts->use_winbar + (int)opts->use_tabline;
2256
2257  win_T *wp = opts->use_tabline ? curwin : find_window_by_handle(window, err);
2258  if (wp == NULL) {
2259    return result;
2260  }
2261
2262  if (HAS_KEY(opts, eval_statusline, use_statuscol_lnum)) {
2263    statuscol_lnum = (int)opts->use_statuscol_lnum;
2264    VALIDATE_RANGE(statuscol_lnum > 0 && statuscol_lnum <= wp->w_buffer->b_ml.ml_line_count,
2265                   "use_statuscol_lnum", {
2266      return result;
2267    });
2268    use_bools++;
2269  }
2270  VALIDATE(use_bools <= 1, "%s",
2271           "Can only use one of 'use_winbar', 'use_tabline' and 'use_statuscol_lnum'", {
2272    return result;
2273  });
2274
2275  int stc_hl_id = 0;
2276  int scl_hl_id = 0;
2277  statuscol_T statuscol = { 0 };
2278  SignTextAttrs sattrs[SIGN_SHOW_MAX] = { 0 };
2279
2280  if (statuscol_lnum) {
2281    int line_id = 0;
2282    int cul_id = 0;
2283    int num_id = 0;
2284    linenr_T lnum = statuscol_lnum;
2285    foldinfo_T cursorline_fi = { 0 };
2286    decor_redraw_signs(wp, wp->w_buffer, lnum - 1, sattrs, &line_id, &cul_id, &num_id);
2287
2288    statuscol.sattrs = sattrs;
2289    statuscol.foldinfo = fold_info(wp, lnum);
2290    win_update_cursorline(wp, &cursorline_fi);
2291    statuscol.sign_cul_id = use_cursor_line_highlight(wp, lnum) ? cul_id : 0;
2292    scl_hl_id = use_cursor_line_highlight(wp, lnum) ? HLF_CLS : HLF_SC;
2293
2294    if (num_id) {
2295      stc_hl_id = num_id;
2296    } else if (use_cursor_line_highlight(wp, lnum)) {
2297      stc_hl_id = HLF_CLN;
2298    } else if (wp->w_p_rnu) {
2299      stc_hl_id = (lnum < wp->w_cursor.lnum ? HLF_LNA : HLF_LNB);
2300    } else {
2301      stc_hl_id = HLF_N;
2302    }
2303
2304    set_vim_var_nr(VV_LNUM, lnum);
2305    set_vim_var_nr(VV_RELNUM, labs(get_cursor_rel_lnum(wp, lnum)));
2306    set_vim_var_nr(VV_VIRTNUM, 0);
2307  } else if (fillchar == 0 && !opts->use_tabline) {
2308    if (opts->use_winbar) {
2309      fillchar = wp->w_p_fcs_chars.wbr;
2310    } else {
2311      hlf_T group;
2312      fillchar = fillchar_status(&group, wp);
2313    }
2314  }
2315
2316  if (HAS_KEY(opts, eval_statusline, maxwidth)) {
2317    maxwidth = (int)opts->maxwidth;
2318  } else {
2319    maxwidth = 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
2325  result = arena_dict(arena, 3);
2326  const CharBuf buf = { arena_alloc(arena, MAXPATHL, false), MAXPATHL };
2327  stl_hlrec_t *hltab;
2328  size_t hltab_len = 0;
2329
2330  // Temporarily reset 'cursorbind' to prevent side effects from moving the cursor away and back.
2331  int p_crb_save = wp->w_p_crb;
2332  wp->w_p_crb = false;
2333
2334  int width = build_stl_str_hl(wp, buf, str.data, -1, 0, fillchar, maxwidth,
2335                               opts->highlights ? &hltab : NULL, &hltab_len, NULL,
2336                               statuscol_lnum ? &statuscol : NULL);
2337
2338  PUT_C(result, "width", INTEGER_OBJ(width));
2339
2340  // Restore original value of 'cursorbind'
2341  wp->w_p_crb = p_crb_save;
2342
2343  if (opts->highlights) {
2344    Array hl_values = arena_array(arena, hltab_len + 1);
2345    char 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
2349    const char *dfltname = get_default_stl_hl(opts->use_tabline ? NULL : wp,
2350                                              opts->use_winbar, stc_hl_id);
2351    if (hltab->start == NULL || (hltab->start - buf.data) != 0) {
2352      Dict hl_info = arena_dict(arena, 3);
2353      PUT_C(hl_info, "start", INTEGER_OBJ(0));
2354      PUT_C(hl_info, "group", CSTR_AS_OBJ(dfltname));
2355      Array groups = arena_array(arena, 1);
2356      ADD_C(groups, CSTR_AS_OBJ(dfltname));
2357      PUT_C(hl_info, "groups", ARRAY_OBJ(groups));
2358      ADD_C(hl_values, DICT_OBJ(hl_info));
2359    }
2360
2361    for (stl_hlrec_t *sp = hltab; sp->start != NULL; sp++) {
2362      const char *grpname;
2363      if (sp->userhl == 0) {
2364        grpname = get_default_stl_hl(opts->use_tabline ? NULL : wp, opts->use_winbar, stc_hl_id);
2365      } else if (sp->userhl < 0) {
2366        grpname = syn_id2name(-sp->userhl);
2367      } else {
2368        snprintf(user_group, sizeof(user_group), "User%d", sp->userhl);
2369        grpname = arena_strdup(arena, user_group);
2370      }
2371
2372      const char *combine = sp->item == STL_SIGNCOL ? syn_id2name(scl_hl_id)
2373                                                    : sp->item == STL_FOLDCOL ? grpname : dfltname;
2374      Dict hl_info = arena_dict(arena, 3);
2375      PUT_C(hl_info, "start", INTEGER_OBJ(sp->start - buf.data));
2376      PUT_C(hl_info, "group", CSTR_AS_OBJ(grpname));
2377      Array groups = arena_array(arena, 1 + (combine != grpname));
2378      if (combine != grpname) {
2379        ADD_C(groups, CSTR_AS_OBJ(combine));
2380      }
2381      ADD_C(groups, CSTR_AS_OBJ(grpname));
2382      PUT_C(hl_info, "groups", ARRAY_OBJ(groups));
2383      ADD_C(hl_values, DICT_OBJ(hl_info));
2384    }
2385    PUT_C(result, "highlights", ARRAY_OBJ(hl_values));
2386  }
2387  PUT_C(result, "str", CSTR_AS_OBJ(buf.data));
2388
2389  return 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,
2402                                   Error *err)
2403{
2404  Dict rv = arena_dict(arena, 2);
2405  if ((get_cot_flags() & kOptCotFlagPopup) == 0) {
2406    api_set_error(err, kErrorTypeException, "completeopt option does not include popup");
2407    return rv;
2408  }
2409  if (HAS_KEY(opts, complete_set, info)) {
2410    win_T *wp = pum_set_info((int)index, opts->info.data);
2411    if (wp) {
2412      PUT_C(rv, "winid", WINDOW_OBJ(wp->handle));
2413      PUT_C(rv, "bufnr", BUFFER_OBJ(wp->w_buffer->handle));
2414    }
2415  }
2416  return rv;
2417}
2418
2419static void redraw_status(win_T *wp, Dict(redraw) *opts, bool *flush)
2420{
2421  if (opts->statuscolumn && *wp->w_p_stc != NUL) {
2422    wp->w_nrwidth_line_count = 0;
2423    changed_window_setting(wp);
2424  }
2425
2426  int old_row_offset = wp->w_grid.row_offset;
2427  win_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.
2431  if (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.
2436  if (*flush && (opts->statusline || opts->winbar)) {
2437    wp->w_redr_status = true;
2438  } else if (opts->statusline || opts->winbar) {
2439    win_check_ns_hl(wp);
2440    if (opts->winbar) {
2441      win_redr_winbar(wp);
2442    }
2443    if (opts->statusline) {
2444      win_redr_status(wp);
2445    }
2446    win_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)
2474  FUNC_API_SINCE(12)
2475{
2476  win_T *win = NULL;
2477  buf_T *buf = NULL;
2478
2479  if (HAS_KEY(opts, redraw, win)) {
2480    win = find_window_by_handle(opts->win, err);
2481    if (ERROR_SET(err)) {
2482      return;
2483    }
2484  }
2485
2486  if (HAS_KEY(opts, redraw, buf)) {
2487    VALIDATE(win == NULL, "%s", "cannot use both 'buf' and 'win'", {
2488      return;
2489    });
2490    buf = find_buffer_by_handle(opts->buf, err);
2491    if (ERROR_SET(err)) {
2492      return;
2493    }
2494  }
2495
2496  unsigned count = (win != NULL) + (buf != NULL);
2497  VALIDATE(xpopcount(opts->is_set__redraw_) > count, "%s", "at least one action required", {
2498    return;
2499  });
2500
2501  if (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".
2506    int type = opts->valid ? UPD_VALID : UPD_NOT_VALID;
2507    if (win != NULL) {
2508      redraw_later(win, type);
2509    } else if (buf != NULL) {
2510      redraw_buf_later(buf, type);
2511    } else {
2512      redraw_all_later(type);
2513    }
2514  }
2515
2516  if (HAS_KEY(opts, redraw, range)) {
2517    VALIDATE(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", {
2523      return;
2524    });
2525    int64_t begin_raw = kv_A(opts->range, 0).data.integer;
2526    int64_t end_raw = kv_A(opts->range, 1).data.integer;
2527
2528    buf_T *rbuf = win ? win->w_buffer : (buf ? buf : curbuf);
2529    linenr_T line_count = rbuf->b_ml.ml_line_count;
2530
2531    int begin = (int)MIN(begin_raw, line_count);
2532    int end;
2533    if (end_raw == -1) {
2534      end = line_count;
2535    } else {
2536      end = (int)MIN(MAX(begin, end_raw), line_count);
2537    }
2538
2539    if (begin < end) {
2540      redraw_buf_range_later(rbuf, 1 + begin, end);
2541    }
2542  }
2543
2544  // Redraw later types require update_screen() so call implicitly unless set to false.
2545  if (HAS_KEY(opts, redraw, valid) || HAS_KEY(opts, redraw, range)) {
2546    opts->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.
2551  bool flush_ui = opts->flush;
2552  if (opts->tabline) {
2553    // Flush later in case tabline was just hidden or shown for the first time.
2554    if (redraw_tabline && firstwin->w_lines_valid == 0) {
2555      opts->flush = true;
2556    } else {
2557      draw_tabline();
2558    }
2559    flush_ui = true;
2560  }
2561
2562  bool save_lz = p_lz;
2563  int save_rd = RedrawingDisabled;
2564  RedrawingDisabled = 0;
2565  p_lz = false;
2566  if (opts->statuscolumn || opts->statusline || opts->winbar) {
2567    if (win == NULL) {
2568      FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
2569        if (buf == NULL || wp->w_buffer == buf) {
2570          redraw_status(wp, opts, &opts->flush);
2571        }
2572      }
2573    } else {
2574      redraw_status(win, opts, &opts->flush);
2575    }
2576    flush_ui = true;
2577  }
2578
2579  win_T *cwin = win ? win : curwin;
2580  // Allow moving cursor to recently opened window and make sure it is drawn #28868.
2581  if (opts->cursor && (!cwin->w_grid.target || !cwin->w_grid.target->valid)) {
2582    opts->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.
2587  if (opts->flush && !cmdpreview) {
2588    validate_cursor(curwin);
2589    update_topline(curwin);
2590    update_screen();
2591  }
2592
2593  if (opts->cursor) {
2594    setcursor_mayforce(cwin, true);
2595    flush_ui = true;
2596  }
2597
2598  if (flush_ui) {
2599    ui_flush();
2600  }
2601
2602  RedrawingDisabled = save_rd;
2603  p_lz = save_lz;
2604}
2605
2606void nvim__set_restart_on_crash(String progpath, Array argv)
2607{
2608  ui_call__set_restart_on_crash_exit(progpath, argv);
2609}