robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
46.1 KiB1343 linesraw
1#include <assert.h>
2#include <lauxlib.h>
3#include <stdbool.h>
4#include <stdint.h>
5#include <string.h>
6
7#include "klib/kvec.h"
8#include "nvim/api/extmark.h"
9#include "nvim/api/keysets_defs.h"
10#include "nvim/api/private/defs.h"
11#include "nvim/api/private/dispatch.h"
12#include "nvim/api/private/helpers.h"
13#include "nvim/api/private/validate.h"
14#include "nvim/buffer_defs.h"
15#include "nvim/charset.h"
16#include "nvim/decoration.h"
17#include "nvim/decoration_defs.h"
18#include "nvim/decoration_provider.h"
19#include "nvim/drawscreen.h"
20#include "nvim/extmark.h"
21#include "nvim/globals.h"
22#include "nvim/grid.h"
23#include "nvim/highlight_group.h"
24#include "nvim/map_defs.h"
25#include "nvim/marktree.h"
26#include "nvim/marktree_defs.h"
27#include "nvim/mbyte.h"
28#include "nvim/memline.h"
29#include "nvim/memory.h"
30#include "nvim/memory_defs.h"
31#include "nvim/move.h"
32#include "nvim/pos_defs.h"
33#include "nvim/sign.h"
34
35#include "api/extmark.c.generated.h"
36
37void api_extmark_free_all_mem(void)
38{
39  String name;
40  map_foreach_key(&namespace_ids, name, {
41    xfree(name.data);
42  })
43  map_destroy(String, &namespace_ids);
44  set_destroy(uint32_t, &namespace_localscope);
45}
46
47/// Creates a new namespace or gets an existing one. [namespace]()
48///
49/// Namespaces are used for buffer highlights and virtual text, see
50/// |nvim_buf_set_extmark()|.
51///
52/// Namespaces can be named or anonymous. If `name` matches an existing
53/// namespace, the associated id is returned. If `name` is an empty string
54/// a new, anonymous namespace is created.
55///
56/// @param name Namespace name or empty string
57/// @return Namespace id
58Integer nvim_create_namespace(String name)
59  FUNC_API_SINCE(5)
60{
61  handle_T id = map_get(String, int)(&namespace_ids, name);
62  if (id > 0) {
63    return (Integer)id;
64  }
65  id = next_namespace_id++;
66  if (name.size > 0) {
67    String name_alloc = copy_string(name, NULL);
68    map_put(String, int)(&namespace_ids, name_alloc, id);
69  }
70  return (Integer)id;
71}
72
73/// Gets existing, non-anonymous |namespace|s.
74///
75/// @return dict that maps from names to namespace ids.
76DictOf(Integer) nvim_get_namespaces(Arena *arena)
77  FUNC_API_SINCE(5)
78{
79  Dict retval = arena_dict(arena, map_size(&namespace_ids));
80  String name;
81  handle_T id;
82
83  map_foreach(&namespace_ids, name, id, {
84    PUT_C(retval, name.data, INTEGER_OBJ(id));
85  })
86
87  return retval;
88}
89
90const char *describe_ns(NS ns_id, const char *unknown)
91{
92  String name;
93  handle_T id;
94  map_foreach(&namespace_ids, name, id, {
95    if ((NS)id == ns_id && name.size) {
96      return name.data;
97    }
98  })
99  return unknown;
100}
101
102// Is the Namespace in use?
103bool ns_initialized(uint32_t ns)
104{
105  if (ns < 1) {
106    return false;
107  }
108  return ns < (uint32_t)next_namespace_id;
109}
110
111Array virt_text_to_array(VirtText vt, bool hl_name, Arena *arena)
112{
113  Array chunks = arena_array(arena, kv_size(vt));
114  for (size_t i = 0; i < kv_size(vt); i++) {
115    size_t j = i;
116    for (; j < kv_size(vt); j++) {
117      if (kv_A(vt, j).text != NULL) {
118        break;
119      }
120    }
121
122    Array hl_array = arena_array(arena, i < j ? j - i + 1 : 0);
123    for (; i < j; i++) {
124      int hl_id = kv_A(vt, i).hl_id;
125      if (hl_id >= 0) {
126        ADD_C(hl_array, hl_group_name(hl_id, hl_name));
127      }
128    }
129
130    char *text = kv_A(vt, i).text;
131    int hl_id = kv_A(vt, i).hl_id;
132    Array chunk = arena_array(arena, 2);
133    ADD_C(chunk, CSTR_AS_OBJ(text));
134    if (hl_array.size > 0) {
135      if (hl_id >= 0) {
136        ADD_C(hl_array, hl_group_name(hl_id, hl_name));
137      }
138      ADD_C(chunk, ARRAY_OBJ(hl_array));
139    } else if (hl_id >= 0) {
140      ADD_C(chunk, hl_group_name(hl_id, hl_name));
141    }
142    ADD_C(chunks, ARRAY_OBJ(chunk));
143  }
144  return chunks;
145}
146
147static Array extmark_to_array(MTPair extmark, bool id, bool add_dict, bool hl_name, Arena *arena)
148{
149  MTKey start = extmark.start;
150  Array rv = arena_array(arena, 4);
151  if (id) {
152    ADD_C(rv, INTEGER_OBJ((Integer)start.id));
153  }
154  ADD_C(rv, INTEGER_OBJ(start.pos.row));
155  ADD_C(rv, INTEGER_OBJ(start.pos.col));
156
157  if (add_dict) {
158    // TODO(bfredl): coding the size like this is a bit fragile.
159    // We want ArrayOf(Dict(set_extmark)) as the return type..
160    Dict dict = arena_dict(arena, ARRAY_SIZE(set_extmark_table));
161
162    PUT_C(dict, "ns_id", INTEGER_OBJ((Integer)start.ns));
163
164    PUT_C(dict, "right_gravity", BOOLEAN_OBJ(mt_right(start)));
165
166    if (mt_paired(start)) {
167      PUT_C(dict, "end_row", INTEGER_OBJ(extmark.end_pos.row));
168      PUT_C(dict, "end_col", INTEGER_OBJ(extmark.end_pos.col));
169      PUT_C(dict, "end_right_gravity", BOOLEAN_OBJ(extmark.end_right_gravity));
170    }
171
172    if (mt_no_undo(start)) {
173      PUT_C(dict, "undo_restore", BOOLEAN_OBJ(false));
174    }
175
176    if (mt_invalidate(start)) {
177      PUT_C(dict, "invalidate", BOOLEAN_OBJ(true));
178    }
179    if (mt_invalid(start)) {
180      PUT_C(dict, "invalid", BOOLEAN_OBJ(true));
181    }
182
183    decor_to_dict_legacy(&dict, mt_decor(start), hl_name, arena);
184
185    ADD_C(rv, DICT_OBJ(dict));
186  }
187
188  return rv;
189}
190
191/// Gets the position (0-indexed) of an |extmark|.
192///
193/// @param buf  Buffer id, or 0 for current buffer
194/// @param ns_id  |namespace| id
195/// @param id  Extmark id
196/// @param opts  Optional parameters. Keys:
197///          - details: Whether to include the details dict
198///          - hl_name: Whether to include highlight group name instead of id, true if omitted
199/// @param[out] err   Error details, if any
200/// @return 0-indexed (row, col, details?) tuple or empty list () if extmark id was absent.  The
201/// optional `details` dictionary contains the same keys as `opts` in |nvim_buf_set_extmark()|,
202/// except for `id`, `conceal_lines` and `ephemeral`. It also contains the following keys:
203///
204/// - ns_id: |namespace| id
205/// - invalid: boolean that indicates whether the mark is hidden because the entirety of
206/// text span range is deleted. See also the key `invalidate` in |nvim_buf_set_extmark()|.
207Tuple(Integer, Integer, *DictAs(extmark_details))
208nvim_buf_get_extmark_by_id(Buffer buf, Integer ns_id, Integer id, Dict(get_extmark) * opts,
209                           Arena *arena, Error *err)
210  FUNC_API_SINCE(7)
211{
212  Array rv = ARRAY_DICT_INIT;
213
214  buf_T *b = find_buffer_by_handle(buf, err);
215
216  if (!b) {
217    return rv;
218  }
219
220  VALIDATE_INT(ns_initialized((uint32_t)ns_id), "ns_id", ns_id, {
221    return rv;
222  });
223
224  bool details = opts->details;
225
226  bool hl_name = GET_BOOL_OR_TRUE(opts, get_extmark, hl_name);
227
228  MTPair extmark = extmark_from_id(b, (uint32_t)ns_id, (uint32_t)id);
229  if (extmark.start.pos.row < 0) {
230    return rv;
231  }
232  return extmark_to_array(extmark, false, details, hl_name, arena);
233}
234
235/// Gets |extmarks| in "traversal order" from a |charwise| region defined by buffer positions
236/// (inclusive, 0-indexed |api-indexing|).
237///
238/// Region can be given as (row,col) tuples, or valid extmark ids (whose
239/// positions define the bounds). 0 and -1 are understood as (0,0) and (-1,-1)
240/// respectively, thus the following are equivalent:
241///
242/// ```lua
243/// vim.api.nvim_buf_get_extmarks(0, my_ns, 0, -1)
244/// vim.api.nvim_buf_get_extmarks(0, my_ns, {0,0}, {-1,-1})
245/// ```
246///
247/// If `end` is less than `start`, marks are returned in reverse order.
248/// (Useful with `limit`, to get the first marks prior to a given position.)
249///
250/// Note:
251/// - For a reverse range, `limit` does not actually affect the traversed range, just how many marks
252///   are returned
253/// - When using extmark ranges (marks with a end_row/end_col position) the `overlap` option might
254///   be useful. Otherwise only the start position of an extmark will be considered.
255/// - The |:marks| command can list extmarks.
256/// - Legacy signs placed through the |:sign| commands are implemented as extmarks. Their details
257///   array will contain a `sign_name` field.
258///
259/// Example:
260///
261/// ```lua
262/// local api = vim.api
263/// local pos = api.nvim_win_get_cursor(0)
264/// local ns  = api.nvim_create_namespace('my-plugin')
265/// -- Create new extmark at line 1, column 1.
266/// local m1  = api.nvim_buf_set_extmark(0, ns, 0, 0)
267/// -- Create new extmark at line 3, column 1.
268/// local m2  = api.nvim_buf_set_extmark(0, ns, 2, 0)
269/// -- Get extmarks only from line 3.
270/// local ms  = api.nvim_buf_get_extmarks(0, ns, {2,0}, {2,0})
271/// -- Get all marks in this buffer + namespace.
272/// local all = api.nvim_buf_get_extmarks(0, ns, 0, -1)
273/// vim.print(ms)
274/// ```
275///
276/// @param buf  Buffer id, or 0 for current buffer
277/// @param ns_id  |namespace| id, or -1 for all namespaces
278/// @param start  Start of range: a 0-indexed (row, col) or valid extmark id
279/// (whose position defines the bound). |api-indexing|
280/// @param end  End of range (inclusive): a 0-indexed (row, col) or valid
281/// extmark id (whose position defines the bound). |api-indexing|
282/// @param opts  Optional parameters. Keys:
283///          - details: Whether to include the details dict
284///          - hl_name: Whether to include highlight group name instead of id, true if omitted
285///          - limit:  Maximum number of marks to return
286///          - overlap: Also include marks which overlap the range, even if
287///                     their start position is less than `start`
288///          - type: Filter marks by type: "highlight", "sign", "virt_text" and "virt_lines"
289/// @param[out] err   Error details, if any
290/// @return List of `[extmark_id, row, col, details?]` tuples in "traversal order". For the
291/// `details` dictionary, see |nvim_buf_get_extmark_by_id()|.
292ArrayOf(DictAs(get_extmark_item)) nvim_buf_get_extmarks(Buffer buf, Integer ns_id, Object start,
293                                                        Object end,
294                                                        Dict(get_extmarks) *opts, Arena *arena,
295                                                        Error *err)
296  FUNC_API_SINCE(7)
297{
298  Array rv = ARRAY_DICT_INIT;
299
300  buf_T *b = find_buffer_by_handle(buf, err);
301  if (!b) {
302    return rv;
303  }
304
305  VALIDATE_INT(ns_id == -1 || ns_initialized((uint32_t)ns_id), "ns_id", ns_id, {
306    return rv;
307  });
308
309  bool details = opts->details;
310  bool hl_name = GET_BOOL_OR_TRUE(opts, get_extmarks, hl_name);
311
312  ExtmarkType type = kExtmarkNone;
313  if (HAS_KEY(opts, get_extmarks, type)) {
314    if (strequal(opts->type.data, "sign")) {
315      type = kExtmarkSign;
316    } else if (strequal(opts->type.data, "virt_text")) {
317      type = kExtmarkVirtText;
318    } else if (strequal(opts->type.data, "virt_lines")) {
319      type = kExtmarkVirtLines;
320    } else if (strequal(opts->type.data, "highlight")) {
321      type = kExtmarkHighlight;
322    } else {
323      VALIDATE_EXP(false, "type", "sign, virt_text, virt_lines or highlight", opts->type.data, {
324        return rv;
325      });
326    }
327  }
328
329  Integer limit = HAS_KEY(opts, get_extmarks, limit) ? opts->limit : -1;
330
331  if (limit == 0) {
332    return rv;
333  } else if (limit < 0) {
334    limit = INT64_MAX;
335  }
336
337  int l_row;
338  colnr_T l_col;
339  if (!extmark_get_index_from_obj(b, ns_id, start, &l_row, &l_col, err)) {
340    return rv;
341  }
342
343  int u_row;
344  colnr_T u_col;
345  if (!extmark_get_index_from_obj(b, ns_id, end, &u_row, &u_col, err)) {
346    return rv;
347  }
348
349  size_t rv_limit = (size_t)limit;
350  bool reverse = l_row > u_row || (l_row == u_row && l_col > u_col);
351  if (reverse) {
352    limit = INT64_MAX;  // limit the return value instead
353    int row = l_row;
354    l_row = u_row;
355    u_row = row;
356    colnr_T col = l_col;
357    l_col = u_col;
358    u_col = col;
359  }
360
361  // note: ns_id=-1 allowed, represented as UINT32_MAX
362  ExtmarkInfoArray marks = extmark_get(b, (uint32_t)ns_id, l_row, l_col, u_row,
363                                       u_col, (int64_t)limit, type, opts->overlap);
364
365  rv = arena_array(arena, MIN(kv_size(marks), rv_limit));
366  if (reverse) {
367    for (int i = (int)kv_size(marks) - 1; i >= 0 && kv_size(rv) < rv_limit; i--) {
368      ADD_C(rv, ARRAY_OBJ(extmark_to_array(kv_A(marks, i), true, details, hl_name, arena)));
369    }
370  } else {
371    for (size_t i = 0; i < kv_size(marks); i++) {
372      ADD_C(rv, ARRAY_OBJ(extmark_to_array(kv_A(marks, i), true, details, hl_name, arena)));
373    }
374  }
375
376  kv_destroy(marks);
377  return rv;
378}
379
380/// Creates or updates an |extmark|.
381///
382/// By default a new extmark is created when no id is passed in, but it is also
383/// possible to create a new mark by passing in a previously unused id or move
384/// an existing mark by passing in its id. The caller must then keep track of
385/// existing and unused ids itself. (Useful over RPC, to avoid waiting for the
386/// return value.)
387///
388/// Using the optional arguments, it is possible to use this to highlight
389/// a range of text, and also to associate virtual text to the mark.
390///
391/// If present, the position defined by `end_col` and `end_row` should be after
392/// the start position in order for the extmark to cover a range.
393/// An earlier end position is not an error, but then it behaves like an empty
394/// range (no highlighting).
395///
396/// @param buf  Buffer id, or 0 for current buffer
397/// @param ns_id  |namespace| id
398/// @param line  Line where to place the mark, 0-based. |api-indexing|
399/// @param col  Column where to place the mark, 0-based. |api-indexing|
400/// @param opts  Optional parameters:
401///               - conceal: (boolean|string)
402///                   - string: Single char or empty string, enables conceal similar to |:syn-conceal|.
403///                     Non-empty char is used as |:syn-cchar|. Highlighted with "hl_group" if
404///                     defined, else defaults to |hl-Conceal|.
405///                   - boolean: true is equivalent to "", false removes any existing conceal.
406///               - conceal_lines: (string) Line-level conceal. When set to an empty string (other
407///                 values reserved for future use), the lines in the extmark range are not drawn;
408///                 the next non-concealed line is drawn in their place. Requires 'conceallevel' >=
409///                 2; subject to 'concealcursor' on the cursor line.
410///               - cursorline_hl_group: Highlight group used for the 'signcolumn' text when the
411///                 cursor is on the same line as the mark and 'cursorline' is enabled.
412///               - end_col: End-column of the mark, 0-based exclusive, or -1 to extend the range to
413///                 end of line (if strict=false).
414///               - end_right_gravity: (boolean, default: false) Indicates which direction the extmark
415///                 end-position (if any) will be shifted when new text is inserted (true=right, false=left).
416///               - end_row: End-line of the mark, 0-based inclusive.
417///               - ephemeral: For use with |nvim_set_decoration_provider()| callbacks. The mark
418///                 will only be used for the current redraw cycle, and not stored in the buffer.
419///               - hl_eol: When true, for a multiline highlight covering the EOL of a line,
420///                 continue the highlight for the rest of the screen line (just like for diff and
421///                 cursorline highlight).
422///               - hl_group: Highlight group for the text range. This and below highlight groups
423///                 can be given as a string or as an integer (|nvim_get_hl_id_by_name()|). Multiple
424///                 highlight groups can be stacked by passing an array (highest-priority last).
425///               - hl_mode: Controls how highlights are combined with the highlights of the text.
426///                 Only affects virt_text highlights, but might affect `hl_group` in the future.
427///                 - "replace": Only show the virt_text color. This is the default.
428///                 - "combine": Combine with background text color.
429///                 - "blend": Blend with background text color. Not supported for "inline" virt_text.
430///               - id: Update this extmark instead of creating a new one.
431///               - invalidate: (boolean) Indicates whether to hide the extmark if the entirety of
432///                 its range is deleted. For hidden marks, an "invalid" key is added to the
433///                 "details" array of |nvim_buf_get_extmarks()| and family. If "undo_restore" is
434///                 false, the extmark is deleted instead.
435///               - line_hl_group: Highlight group used for the whole line.
436///               - number_hl_group: Highlight group used for the number column.
437///               - priority: Priority of the highlight group, sign attribute or virtual text. For
438///                 virtual text, the highest-priority item is drawn last. For example treesitter
439///                 highlighting uses a value of 100.
440///               - right_gravity: (boolean, default: true) Indicates which direction the extmark
441///                 will be shifted when new text is inserted (true=right, false=left).
442///               - sign_hl_group: Highlight group for `sign_text`.
443///               - sign_text: (string, length 1-2) Displayed in 'signcolumn'.
444///               - spell: (boolean) Indicates that spell checking should be performed within this
445///                 extmark.
446///               - strict: (boolean, default: true) Indicates extmark should not be placed if the
447///                 line or column value is past end-of-buffer or end-of-line respectively.
448///               - ui_watched: (boolean) Indicates the mark should be drawn by a UI; activates
449///                 `win_extmark` [ui-multigrid] events. Note: the mark is positioned by virt_text
450///                 attributes. Can be used with virt_text.
451///               - undo_restore: (default: true) Restore the exact position of the mark if text
452///                 around the mark was deleted and then restored by undo.
453///               - url: URL stored on this extmark. In the TUI, the OSC 8 control
454///                   sequence is used to generate a clickable hyperlink to this URL.
455///               - virt_lines: List of virtual lines to place next to the mark, where each line is
456///                 a list of `[text_chunk, hl]` tuples. Buffer and window options do not affect the
457///                 display of the text, except 'tabstop' is used for hard tabs. The 'wrap' and
458///                 'linebreak' options do not take effect, so the number of extra screen lines will
459///                 match the list-size (but see `virt_lines_overflow`). By default lines are placed
460///                 below the marked line. Special case: If the last `text_chunk` is empty,
461///                 the corresponding `hl` will extend to the end of the line.
462///               - virt_lines_above: Place virtual lines above instead.
463///               - virt_lines_leftcol: Place virtual lines in the leftmost column of the window,
464///                 bypassing sign and number columns.
465///               - virt_lines_overflow: Controls display of virtual lines exceeding the viewport:
466///                 - "auto": Decided by the 'wrap' option.
467///                 - "scroll": Scroll horizontally with 'nowrap', otherwise the same as "trunc".
468///                 - "trunc": Truncate on the right (default).
469///                 - "wrap": Always wrap (regardless of the 'wrap' option).
470///               - virt_text: [](virtual-text) stored and displayed by this mark. List of `[text, hl]`
471///                 tuples, each representing a text chunk with a highlight `hl` which may be
472///                 a single highlight group or a list of stacked highlight groups (highest-priority
473///                 last).
474///               - virt_text_hide: Hide the virtual text when the background text is selected or
475///                 hidden because of scrolling with 'nowrap' or 'smoothscroll'. Currently only
476///                 affects "overlay" virt_text.
477///               - virt_text_pos: Position of virtual text:
478///                 - "eol": Right after EOL character (default).
479///                 - "eol_right_align": Display right-aligned in the window unless the virtual text
480///                   is longer than the space available. If the virtual text is too long, it is
481///                   truncated to fit in the window after the EOL character. If the line is
482///                   wrapped, the virtual text is shown after the end of the line rather than the
483///                   previous screen line.
484///                 - "overlay": Display over the specified column, without shifting the underlying text.
485///                 - "right_align": Display right-aligned in the window.
486///                 - "inline": Display at the specified column, and right-shift the buffer text as needed.
487///               - virt_text_repeat_linebreak: Repeat the virtual text on wrapped lines.
488///               - virt_text_win_col: Position the virtual text at a fixed window column (starting
489///                 from the first text column of the screen line) instead of "virt_text_pos".
490///
491/// @param[out]  err   Error details, if any
492/// @return Id of the created/updated extmark
493Integer nvim_buf_set_extmark(Buffer buf, Integer ns_id, Integer line, Integer col,
494                             Dict(set_extmark) *opts, Error *err)
495  FUNC_API_SINCE(7)
496{
497  DecorHighlightInline hl = DECOR_HIGHLIGHT_INLINE_INIT;
498  // TODO(bfredl): in principle signs with max one (1) hl group and max 4 bytes of text.
499  // should be a candidate for inlining as well.
500  DecorSignHighlight sign = DECOR_SIGN_HIGHLIGHT_INIT;
501  DecorVirtText virt_text = DECOR_VIRT_TEXT_INIT;
502  DecorVirtText virt_lines = DECOR_VIRT_LINES_INIT;
503  char *url = NULL;
504  bool has_hl = false;
505  bool has_hl_multiple = false;
506
507  buf_T *b = find_buffer_by_handle(buf, err);
508  if (!b) {
509    goto error;
510  }
511
512  VALIDATE_INT(ns_initialized((uint32_t)ns_id), "ns_id", ns_id, {
513    goto error;
514  });
515
516  uint32_t id = 0;
517  if (HAS_KEY(opts, set_extmark, id)) {
518    VALIDATE_EXP((opts->id > 0), "id", "positive Integer", NULL, {
519      goto error;
520    });
521
522    id = (uint32_t)opts->id;
523  }
524
525  int line2 = -1;
526  bool did_end_line = false;
527
528  // For backward compatibility we support "end_line" as an alias for "end_row"
529  if (HAS_KEY(opts, set_extmark, end_line)) {
530    VALIDATE(!HAS_KEY(opts, set_extmark, end_row),
531             "%s", "cannot use both 'end_row' and 'end_line'", {
532      goto error;
533    });
534
535    opts->end_row = opts->end_line;
536    did_end_line = true;
537  }
538
539  bool strict = GET_BOOL_OR_TRUE(opts, set_extmark, strict);
540
541  if (HAS_KEY(opts, set_extmark, end_row) || did_end_line) {
542    Integer val = opts->end_row;
543    VALIDATE_RANGE((val >= 0 && !(val > b->b_ml.ml_line_count && strict)), "end_row", {
544      goto error;
545    });
546    line2 = (int)val;
547  }
548
549  colnr_T col2 = -1;
550  if (HAS_KEY(opts, set_extmark, end_col)) {
551    Integer val = opts->end_col;
552    VALIDATE_RANGE((val >= -1 && val <= MAXCOL), "end_col", {
553      goto error;
554    });
555    if (val == -1) {
556      val = MAXCOL;
557    }
558
559    col2 = (int)val;
560  }
561
562  if (HAS_KEY(opts, set_extmark, hl_group)) {
563    if (opts->hl_group.type == kObjectTypeArray) {
564      Array arr = opts->hl_group.data.array;
565      if (arr.size >= 1) {
566        hl.hl_id = object_to_hl_id(arr.items[0], "hl_group item", err);
567        if (ERROR_SET(err)) {
568          goto error;
569        }
570      }
571      for (size_t i = 1; i < arr.size; i++) {
572        int hl_id = object_to_hl_id(arr.items[i], "hl_group item", err);
573        if (ERROR_SET(err)) {
574          goto error;
575        }
576        if (hl_id) {
577          has_hl_multiple = true;
578        }
579      }
580    } else {
581      hl.hl_id = object_to_hl_id(opts->hl_group, "hl_group", err);
582      if (ERROR_SET(err)) {
583        goto error;
584      }
585    }
586    has_hl = hl.hl_id > 0;
587  }
588
589  sign.hl_id = (int)opts->sign_hl_group;
590  sign.cursorline_hl_id = (int)opts->cursorline_hl_group;
591  sign.number_hl_id = (int)opts->number_hl_group;
592  sign.line_hl_id = (int)opts->line_hl_group;
593
594  if (sign.hl_id || sign.cursorline_hl_id || sign.number_hl_id || sign.line_hl_id) {
595    sign.flags |= kSHIsSign;
596  }
597
598  if (HAS_KEY(opts, set_extmark, conceal)) {
599    VALIDATE_EXP((opts->conceal.type == kObjectTypeBoolean
600                  || opts->conceal.type == kObjectTypeString),
601                 "conceal", "String or Boolean", api_typename(opts->conceal.type), {
602      goto error;
603    });
604
605    has_hl = true;
606    if (opts->conceal.type == kObjectTypeBoolean) {
607      hl.flags |= opts->conceal.data.boolean ? kSHConceal : kSHConcealOff;
608    } else {
609      String conceal_str = opts->conceal.data.string;
610      hl.flags |= kSHConceal;
611      if (conceal_str.size > 0) {
612        int ch;
613        hl.conceal_char = utfc_ptr2schar(conceal_str.data, &ch);
614        VALIDATE(hl.conceal_char && vim_isprintc(ch), "%s", "conceal char must be printable", {
615          goto error;
616        });
617      }
618    }
619  }
620
621  if (HAS_KEY(opts, set_extmark, conceal_lines)) {
622    hl.flags |= kSHConcealLines;
623    has_hl = true;
624    if (opts->conceal_lines.size > 0) {
625      VALIDATE(*opts->conceal_lines.data == NUL, "%s", "conceal_lines has to be an empty string", {
626        goto error;
627      });
628    }
629  }
630
631  if (HAS_KEY(opts, set_extmark, virt_text)) {
632    virt_text.data.virt_text = parse_virt_text(opts->virt_text, err, &virt_text.width, false);
633    if (ERROR_SET(err)) {
634      goto error;
635    }
636  }
637
638  if (HAS_KEY(opts, set_extmark, virt_text_pos)) {
639    String str = opts->virt_text_pos;
640    if (strequal("eol", str.data)) {
641      virt_text.pos = kVPosEndOfLine;
642    } else if (strequal("overlay", str.data)) {
643      virt_text.pos = kVPosOverlay;
644    } else if (strequal("right_align", str.data)) {
645      virt_text.pos = kVPosRightAlign;
646    } else if (strequal("eol_right_align", str.data)) {
647      virt_text.pos = kVPosEndOfLineRightAlign;
648    } else if (strequal("inline", str.data)) {
649      virt_text.pos = kVPosInline;
650    } else {
651      VALIDATE_S(false, "virt_text_pos", str.data, {
652        goto error;
653      });
654    }
655  }
656
657  if (HAS_KEY(opts, set_extmark, virt_text_win_col)) {
658    virt_text.col = (int)opts->virt_text_win_col;
659    virt_text.pos = kVPosWinCol;
660  }
661
662  hl.flags |= opts->hl_eol ? kSHHlEol : 0;
663  virt_text.flags |= ((opts->virt_text_hide ? kVTHide : 0)
664                      | (opts->virt_text_repeat_linebreak ? kVTRepeatLinebreak : 0));
665
666  if (HAS_KEY(opts, set_extmark, hl_mode)) {
667    String str = opts->hl_mode;
668    if (strequal("replace", str.data)) {
669      virt_text.hl_mode = kHlModeReplace;
670    } else if (strequal("combine", str.data)) {
671      virt_text.hl_mode = kHlModeCombine;
672    } else if (strequal("blend", str.data)) {
673      if (virt_text.pos == kVPosInline) {
674        VALIDATE(false, "%s", "cannot use 'blend' hl_mode with inline virtual text", {
675          goto error;
676        });
677      }
678      virt_text.hl_mode = kHlModeBlend;
679    } else {
680      VALIDATE_S(false, "hl_mode", str.data, {
681        goto error;
682      });
683    }
684  }
685
686  int virt_lines_flags = opts->virt_lines_leftcol ? kVLLeftcol : 0;
687  VirtLineOverflow virt_lines_overflow = kVLOverflowTrunc;
688  if (HAS_KEY(opts, set_extmark, virt_lines_overflow)) {
689    String str = opts->virt_lines_overflow;
690    if (strequal("scroll", str.data)) {
691      virt_lines_overflow = kVLOverflowScroll;
692    } else if (strequal("wrap", str.data)) {
693      virt_lines_overflow = kVLOverflowWrap;
694    } else if (strequal("auto", str.data)) {
695      virt_lines_overflow = kVLOverflowAuto;
696    } else if (!strequal("trunc", str.data)) {
697      VALIDATE_S(false, "virt_lines_overflow", str.data, {
698        goto error;
699      });
700    }
701  }
702
703  if (HAS_KEY(opts, set_extmark, virt_lines)) {
704    Array a = opts->virt_lines;
705    for (size_t j = 0; j < a.size; j++) {
706      VALIDATE_T("virt_text_line", kObjectTypeArray, a.items[j].type, {
707        goto error;
708      });
709      int dummig;
710      VirtText jtem = parse_virt_text(a.items[j].data.array, err, &dummig, false);
711      kv_push(virt_lines.data.virt_lines,
712              ((struct virt_line){ jtem, virt_lines_flags, virt_lines_overflow }));
713      if (ERROR_SET(err)) {
714        goto error;
715      }
716    }
717  }
718
719  virt_lines.flags |= opts->virt_lines_above ? kVTLinesAbove : 0;
720
721  if (HAS_KEY(opts, set_extmark, priority)) {
722    VALIDATE_RANGE((opts->priority >= 0 && opts->priority <= UINT16_MAX), "priority", {
723      goto error;
724    });
725    hl.priority = (DecorPriority)opts->priority;
726    sign.priority = (DecorPriority)opts->priority;
727    virt_text.priority = (DecorPriority)opts->priority;
728    virt_lines.priority = (DecorPriority)opts->priority;
729  }
730
731  if (HAS_KEY(opts, set_extmark, sign_text)) {
732    sign.text[0] = 0;
733    VALIDATE_S(init_sign_text(NULL, sign.text, opts->sign_text.data), "sign_text", "", {
734      goto error;
735    });
736    sign.flags |= kSHIsSign;
737  }
738
739  bool right_gravity = GET_BOOL_OR_TRUE(opts, set_extmark, right_gravity);
740
741  // Only error out if they try to set end_right_gravity without
742  // setting end_col or end_row
743  VALIDATE(!(line2 == -1 && col2 == -1 && HAS_KEY(opts, set_extmark, end_right_gravity)),
744           "%s", "cannot set end_right_gravity without end_row or end_col", {
745    goto error;
746  });
747
748  colnr_T len = 0;
749
750  if (HAS_KEY(opts, set_extmark, spell)) {
751    hl.flags |= (opts->spell) ? kSHSpellOn : kSHSpellOff;
752    has_hl = true;
753  }
754
755  if (HAS_KEY(opts, set_extmark, url)) {
756    url = string_to_cstr(opts->url);
757    has_hl = true;
758  }
759
760  if (opts->ui_watched) {
761    hl.flags |= kSHUIWatched;
762    if (virt_text.pos == kVPosOverlay) {
763      // TODO(bfredl): in a revised interface this should be the default.
764      hl.flags |= kSHUIWatchedOverlay;
765    }
766    has_hl = true;
767  }
768
769  VALIDATE_RANGE((line >= 0), "line", {
770    goto error;
771  });
772
773  if (line > b->b_ml.ml_line_count) {
774    VALIDATE_RANGE(!strict, "line", {
775      goto error;
776    });
777    line = b->b_ml.ml_line_count;
778  } else if (line < b->b_ml.ml_line_count) {
779    len = opts->ephemeral ? MAXCOL : ml_get_buf_len(b, (linenr_T)line + 1);
780  }
781
782  if (col == -1) {
783    col = len;
784  } else if (col > len) {
785    VALIDATE_RANGE(!strict, "col", {
786      goto error;
787    });
788    col = len;
789  } else if (col < -1) {
790    VALIDATE_RANGE(false, "col", {
791      goto error;
792    });
793  }
794
795  if (col2 >= 0) {
796    if (line2 >= 0 && line2 < b->b_ml.ml_line_count) {
797      len = opts->ephemeral ? MAXCOL : ml_get_buf_len(b, (linenr_T)line2 + 1);
798    } else if (line2 == b->b_ml.ml_line_count) {
799      // We are trying to add an extmark past final newline
800      len = 0;
801    } else {
802      // reuse len from before
803      line2 = (int)line;
804    }
805    if (col2 > len) {
806      VALIDATE_RANGE(!strict, "end_col", {
807        goto error;
808      });
809      col2 = len;
810    }
811  } else if (line2 >= 0) {
812    col2 = 0;
813  }
814
815  if (opts->ephemeral && decor_state.win && decor_state.win->w_buffer == b) {
816    int r = (int)line;
817    int c = (int)col;
818    if (line2 == -1) {
819      line2 = r;
820      col2 = c;
821    }
822
823    DecorPriority subpriority = 0;
824    if (HAS_KEY(opts, set_extmark, _subpriority)) {
825      VALIDATE_RANGE((opts->_subpriority >= 0 && opts->_subpriority <= UINT16_MAX),
826                     "_subpriority", {
827        goto error;
828      });
829      subpriority = (DecorPriority)opts->_subpriority;
830    }
831
832    if (kv_size(virt_text.data.virt_text)) {
833      decor_range_add_virt(&decor_state, r, c, line2, col2, decor_put_vt(virt_text, NULL), true);
834    }
835    if (kv_size(virt_lines.data.virt_lines)) {
836      decor_range_add_virt(&decor_state, r, c, line2, col2, decor_put_vt(virt_lines, NULL), true);
837    }
838    if (has_hl) {
839      DecorSignHighlight sh = decor_sh_from_inline(hl);
840      sh.url = url;
841      decor_range_add_sh(&decor_state, r, c, line2, col2, &sh, true, (uint32_t)ns_id, id,
842                         subpriority);
843    }
844  } else {
845    if (opts->ephemeral) {
846      api_set_error(err, kErrorTypeException,
847                    "cannot set emphemeral mark outside of a decoration provider");
848      goto error;
849    }
850
851    uint16_t decor_flags = 0;
852
853    DecorVirtText *decor_alloc = NULL;
854    if (kv_size(virt_text.data.virt_text)) {
855      decor_alloc = decor_put_vt(virt_text, decor_alloc);
856      if (virt_text.pos == kVPosInline) {
857        decor_flags |= MT_FLAG_DECOR_VIRT_TEXT_INLINE;
858      }
859    }
860    if (kv_size(virt_lines.data.virt_lines)) {
861      decor_alloc = decor_put_vt(virt_lines, decor_alloc);
862      decor_flags |= MT_FLAG_DECOR_VIRT_LINES;
863    }
864
865    uint32_t decor_indexed = DECOR_ID_INVALID;
866
867    if (sign.flags & kSHIsSign) {
868      sign.next = decor_indexed;
869      decor_indexed = decor_put_sh(sign);
870      if (sign.text[0]) {
871        decor_flags |= MT_FLAG_DECOR_SIGNTEXT;
872      }
873      if (sign.number_hl_id || sign.line_hl_id || sign.cursorline_hl_id) {
874        decor_flags |= MT_FLAG_DECOR_SIGNHL;
875      }
876    }
877
878    if (has_hl_multiple) {
879      Array arr = opts->hl_group.data.array;
880      for (size_t i = arr.size - 1; i > 0; i--) {  // skip hl_group[0], handled as hl.hl_id below
881        int hl_id = object_to_hl_id(arr.items[i], "hl_group item", err);
882        if (hl_id > 0) {
883          DecorSignHighlight sh = DECOR_SIGN_HIGHLIGHT_INIT;
884          sh.hl_id = hl_id;
885          sh.flags = opts->hl_eol ? kSHHlEol : 0;
886          sh.next = decor_indexed;
887          decor_indexed = decor_put_sh(sh);
888          decor_flags |= MT_FLAG_DECOR_HL;
889        }
890      }
891    }
892
893    if (hl.flags & kSHConcealLines) {
894      decor_flags |= MT_FLAG_DECOR_CONCEAL_LINES;
895    }
896
897    DecorInline decor = DECOR_INLINE_INIT;
898    if (decor_alloc || decor_indexed != DECOR_ID_INVALID || url != NULL
899        || schar_high(hl.conceal_char)) {
900      if (has_hl) {
901        DecorSignHighlight sh = decor_sh_from_inline(hl);
902        sh.url = url;
903        sh.next = decor_indexed;
904        decor_indexed = decor_put_sh(sh);
905      }
906      decor.ext = true;
907      decor.data.ext = (DecorExt){ .sh_idx = decor_indexed, .vt = decor_alloc };
908    } else {
909      decor.data.hl = hl;
910    }
911
912    if (has_hl) {
913      decor_flags |= MT_FLAG_DECOR_HL;
914    }
915
916    extmark_set(b, (uint32_t)ns_id, &id, (int)line, (colnr_T)col, line2, col2,
917                decor, decor_flags, right_gravity, opts->end_right_gravity,
918                !GET_BOOL_OR_TRUE(opts, set_extmark, undo_restore),
919                opts->invalidate, err);
920    if (ERROR_SET(err)) {
921      decor_free(decor);
922      return 0;
923    }
924  }
925
926  return (Integer)id;
927
928error:
929  clear_virttext(&virt_text.data.virt_text);
930  clear_virtlines(&virt_lines.data.virt_lines);
931  if (url != NULL) {
932    xfree(url);
933  }
934
935  return 0;
936}
937
938/// Removes an |extmark|.
939///
940/// @param buf Buffer id, or 0 for current buffer
941/// @param ns_id |namespace| id
942/// @param id Extmark id
943/// @param[out] err   Error details, if any
944/// @return true if the extmark was found, else false
945Boolean nvim_buf_del_extmark(Buffer buf, Integer ns_id, Integer id, Error *err)
946  FUNC_API_SINCE(7)
947{
948  buf_T *b = find_buffer_by_handle(buf, err);
949
950  if (!b) {
951    return false;
952  }
953  VALIDATE_INT(ns_initialized((uint32_t)ns_id), "ns_id", ns_id, {
954    return false;
955  });
956
957  return extmark_del_id(b, (uint32_t)ns_id, (uint32_t)id);
958}
959
960/// Clears |namespace|d objects (highlights, |extmarks|, virtual text) from
961/// a region.
962///
963/// Lines are 0-indexed. |api-indexing|  To clear the namespace in the entire
964/// buffer, specify line_start=0 and line_end=-1.
965///
966/// @param buf     Buffer id, or 0 for current buffer
967/// @param ns_id      Namespace to clear, or -1 to clear all namespaces.
968/// @param line_start Start of range of lines to clear
969/// @param line_end   End of range of lines to clear (exclusive) or -1 to clear
970///                   to end of buffer.
971/// @param[out] err   Error details, if any
972void nvim_buf_clear_namespace(Buffer buf, Integer ns_id, Integer line_start, Integer line_end,
973                              Error *err)
974  FUNC_API_SINCE(5)
975{
976  buf_T *b = find_buffer_by_handle(buf, err);
977  if (!b) {
978    return;
979  }
980
981  VALIDATE_RANGE((line_start >= 0 && line_start < MAXLNUM), "line number", {
982    return;
983  });
984
985  if (line_end < 0 || line_end > MAXLNUM) {
986    line_end = MAXLNUM;
987  }
988  extmark_clear(b, (ns_id < 0 ? 0 : (uint32_t)ns_id),
989                (int)line_start, 0,
990                (int)line_end - 1, MAXCOL);
991}
992
993/// Set or change decoration provider for a |namespace|
994///
995/// This is a very general purpose interface for having Lua callbacks
996/// being triggered during the redraw code.
997///
998/// The expected usage is to set |extmarks| for the currently
999/// redrawn buffer. |nvim_buf_set_extmark()| can be called to add marks
1000/// on a per-window or per-lines basis. Use the `ephemeral` key to only
1001/// use the mark for the current screen redraw (the callback will be called
1002/// again for the next redraw).
1003///
1004/// Note: this function should not be called often. Rather, the callbacks
1005/// themselves can be used to throttle unneeded callbacks. the `on_start`
1006/// callback can return `false` to disable the provider until the next redraw.
1007/// Similarly, return `false` in `on_win` will skip the `on_line` and `on_range` calls
1008/// for that window (but any extmarks set in `on_win` will still be used).
1009/// A plugin managing multiple sources of decoration should ideally only set
1010/// one provider, and merge the sources internally. You can use multiple `ns_id`
1011/// for the extmarks set/modified inside the callback anyway.
1012///
1013/// Note: doing anything other than setting extmarks is considered experimental.
1014/// Doing things like changing options are not explicitly forbidden, but is
1015/// likely to have unexpected consequences (such as 100% CPU consumption).
1016/// Doing `vim.rpcnotify` should be OK, but `vim.rpcrequest` is quite dubious
1017/// for the moment.
1018///
1019/// Note: It is not allowed to remove or update extmarks in `on_line` or `on_range` callbacks.
1020///
1021/// Note: Callbacks will not run for |window-hidden|, as they are not redrawn.
1022///
1023/// @param ns_id  |namespace| id
1024/// @param opts  Table of callbacks:
1025///             - on_buf: called for each buffer being redrawn (once per edit,
1026///               before window callbacks)
1027///               ```
1028///                 ["buf", bufnr, tick]
1029///               ```
1030///             - on_end: called at the end of a redraw cycle
1031///               ```
1032///                 ["end", tick]
1033///               ```
1034///             - on_line: (deprecated, use on_range instead)
1035///               ```
1036///                 ["line", winid, bufnr, row]
1037///               ```
1038///             - on_range: called for each buffer range being redrawn.
1039///               Range is end-exclusive and may span multiple lines. Range
1040///               bounds point to the first byte of a character. An end position
1041///               of the form (lnum, 0), including (number of lines, 0), is valid
1042///               and indicates that EOL of the preceding line is included.
1043///               ```
1044///                 ["range", winid, bufnr, begin_row, begin_col, end_row, end_col]
1045///               ```
1046///
1047///               In addition to returning a boolean, it is also allowed to
1048///               return a `skip_row, skip_col` pair of integers. This implies
1049///               that this function does not need to be called until a range
1050///               which continues beyond the skipped position. A single integer
1051///               return value `skip_row` is short for `skip_row, 0`
1052///
1053///             - on_start: called first on each screen redraw
1054///               ```
1055///                 ["start", tick]
1056///               ```
1057///             - on_win: called when starting to redraw a specific window.
1058///               ```
1059///                 ["win", winid, bufnr, toprow, botrow]
1060///               ```
1061void nvim_set_decoration_provider(Integer ns_id, Dict(set_decoration_provider) *opts, Error *err)
1062  FUNC_API_SINCE(7) FUNC_API_LUA_ONLY
1063{
1064  DecorProvider *p = get_decor_provider((NS)ns_id, true);
1065  assert(p != NULL);
1066  decor_provider_clear(p);
1067
1068  // regardless of what happens, it seems good idea to redraw
1069  redraw_all_later(UPD_NOT_VALID);  // TODO(bfredl): too soon?
1070
1071  struct {
1072    const char *name;
1073    LuaRef *source;
1074    LuaRef *dest;
1075  } cbs[] = {
1076    { "on_start", &opts->on_start, &p->redraw_start },
1077    { "on_buf", &opts->on_buf, &p->redraw_buf },
1078    { "on_win", &opts->on_win, &p->redraw_win },
1079    { "on_line", &opts->on_line, &p->redraw_line },
1080    { "on_range", &opts->on_range, &p->redraw_range },
1081    { "on_end", &opts->on_end, &p->redraw_end },
1082    { "_on_hl_def", &opts->_on_hl_def, &p->hl_def },
1083    { "_on_spell_nav", &opts->_on_spell_nav, &p->spell_nav },
1084    { "_on_conceal_line", &opts->_on_conceal_line, &p->conceal_line },
1085    { NULL, NULL, NULL },
1086  };
1087
1088  for (size_t i = 0; cbs[i].source && cbs[i].dest && cbs[i].name; i++) {
1089    LuaRef *v = cbs[i].source;
1090    if (*v <= 0) {
1091      continue;
1092    }
1093
1094    *(cbs[i].dest) = *v;
1095    *v = LUA_NOREF;
1096  }
1097
1098  p->state = kDecorProviderActive;
1099  p->hl_valid++;
1100  p->hl_cached = false;
1101}
1102
1103/// Gets the line and column of an |extmark|.
1104///
1105/// Extmarks may be queried by position, name or even special names
1106/// in the future such as "cursor".
1107///
1108/// @param[out] lnum extmark line
1109/// @param[out] colnr extmark column
1110///
1111/// @return true if the extmark was found, else false
1112static bool extmark_get_index_from_obj(buf_T *buf, Integer ns_id, Object obj, int *row,
1113                                       colnr_T *col, Error *err)
1114{
1115  // Check if it is mark id
1116  if (obj.type == kObjectTypeInteger) {
1117    Integer id = obj.data.integer;
1118    if (id == 0) {
1119      *row = 0;
1120      *col = 0;
1121      return true;
1122    } else if (id == -1) {
1123      *row = MAXLNUM;
1124      *col = MAXCOL;
1125      return true;
1126    } else if (id < 0) {
1127      VALIDATE_INT(false, "mark id", id, {
1128        return false;
1129      });
1130    }
1131
1132    MTPair extmark = extmark_from_id(buf, (uint32_t)ns_id, (uint32_t)id);
1133
1134    VALIDATE_INT((extmark.start.pos.row >= 0), "mark id (not found)", id, {
1135      return false;
1136    });
1137    *row = extmark.start.pos.row;
1138    *col = extmark.start.pos.col;
1139    return true;
1140
1141    // Check if it is a position
1142  } else if (obj.type == kObjectTypeArray) {
1143    Array pos = obj.data.array;
1144    VALIDATE_EXP((pos.size == 2
1145                  && pos.items[0].type == kObjectTypeInteger
1146                  && pos.items[1].type == kObjectTypeInteger),
1147                 "mark position", "2 Integer items", NULL, {
1148      return false;
1149    });
1150
1151    Integer pos_row = pos.items[0].data.integer;
1152    Integer pos_col = pos.items[1].data.integer;
1153    *row = (int)(pos_row >= 0 ? pos_row : MAXLNUM);
1154    *col = (colnr_T)(pos_col >= 0 ? pos_col : MAXCOL);
1155    return true;
1156  } else {
1157    VALIDATE_EXP(false, "mark position", "mark id Integer or 2-item Array", NULL, {
1158      return false;
1159    });
1160  }
1161}
1162
1163VirtText parse_virt_text(Array chunks, Error *err, int *width, bool untab)
1164{
1165  VirtText virt_text = KV_INITIAL_VALUE;
1166  int w = 0;
1167  for (size_t i = 0; i < chunks.size; i++) {
1168    VALIDATE_T("chunk", kObjectTypeArray, chunks.items[i].type, {
1169      goto free_exit;
1170    });
1171    Array chunk = chunks.items[i].data.array;
1172    VALIDATE((chunk.size > 0 && chunk.size <= 2 && chunk.items[0].type == kObjectTypeString),
1173             "%s", "Invalid chunk: expected Array with 1 or 2 Strings", {
1174      goto free_exit;
1175    });
1176
1177    String str = chunk.items[0].data.string;
1178
1179    int hl_id = -1;
1180    if (chunk.size == 2) {
1181      Object hl = chunk.items[1];
1182      if (hl.type == kObjectTypeArray) {
1183        Array arr = hl.data.array;
1184        for (size_t j = 0; j < arr.size; j++) {
1185          hl_id = object_to_hl_id(arr.items[j], "virt_text highlight", err);
1186          if (ERROR_SET(err)) {
1187            goto free_exit;
1188          }
1189          if (j < arr.size - 1) {
1190            kv_push(virt_text, ((VirtTextChunk){ .text = NULL, .hl_id = hl_id }));
1191          }
1192        }
1193      } else {
1194        hl_id = object_to_hl_id(hl, "virt_text highlight", err);
1195        if (ERROR_SET(err)) {
1196          goto free_exit;
1197        }
1198      }
1199    }
1200
1201    char *text = transstr(str.size > 0 ? str.data : "", untab);  // allocates
1202    w += (int)mb_string2cells(text);
1203
1204    kv_push(virt_text, ((VirtTextChunk){ .text = text, .hl_id = hl_id }));
1205  }
1206
1207  if (width != NULL) {
1208    *width = w;
1209  }
1210  return virt_text;
1211
1212free_exit:
1213  clear_virttext(&virt_text);
1214  return virt_text;
1215}
1216
1217/// @nodoc
1218String nvim__buf_debug_extmarks(Buffer buf, Boolean keys, Boolean dot, Error *err)
1219  FUNC_API_SINCE(7) FUNC_API_RET_ALLOC
1220{
1221  buf_T *b = find_buffer_by_handle(buf, err);
1222  if (!b) {
1223    return NULL_STRING;
1224  }
1225
1226  return mt_inspect(b->b_marktree, keys, dot);
1227}
1228
1229/// Set some properties for namespace
1230///
1231/// @param ns_id Namespace
1232/// @param opts Optional parameters to set:
1233///           - wins: a list of windows to be scoped in
1234///
1235void nvim__ns_set(Integer ns_id, Dict(ns_opts) *opts, Error *err)
1236{
1237  VALIDATE_INT(ns_initialized((uint32_t)ns_id), "ns_id", ns_id, {
1238    return;
1239  });
1240
1241  bool set_scoped = true;
1242
1243  if (HAS_KEY(opts, ns_opts, wins)) {
1244    if (opts->wins.size == 0) {
1245      set_scoped = false;
1246    }
1247
1248    Set(ptr_t) windows = SET_INIT;
1249    for (size_t i = 0; i < opts->wins.size; i++) {
1250      Integer win = opts->wins.items[i].data.integer;
1251
1252      win_T *wp = find_window_by_handle((Window)win, err);
1253      if (!wp) {
1254        set_destroy(ptr_t, &windows);
1255        return;
1256      }
1257
1258      set_put(ptr_t, &windows, wp);
1259    }
1260
1261    FOR_ALL_TAB_WINDOWS(tp, wp) {
1262      if (set_has(ptr_t, &windows, wp) && !set_has(uint32_t, &wp->w_ns_set, (uint32_t)ns_id)) {
1263        set_put(uint32_t, &wp->w_ns_set, (uint32_t)ns_id);
1264
1265        if (map_has(uint32_t, wp->w_buffer->b_extmark_ns, (uint32_t)ns_id)) {
1266          changed_window_setting(wp);
1267        }
1268      }
1269
1270      if (set_has(uint32_t, &wp->w_ns_set, (uint32_t)ns_id) && !set_has(ptr_t, &windows, wp)) {
1271        set_del(uint32_t, &wp->w_ns_set, (uint32_t)ns_id);
1272
1273        if (map_has(uint32_t, wp->w_buffer->b_extmark_ns, (uint32_t)ns_id)) {
1274          changed_window_setting(wp);
1275        }
1276      }
1277    }
1278
1279    set_destroy(ptr_t, &windows);
1280  }
1281
1282  if (set_scoped && !set_has(uint32_t, &namespace_localscope, (uint32_t)ns_id)) {
1283    set_put(uint32_t, &namespace_localscope, (uint32_t)ns_id);
1284
1285    // When a namespace becomes scoped, any window which contains
1286    // elements associated with namespace needs to be redrawn
1287    FOR_ALL_TAB_WINDOWS(tp, wp) {
1288      if (map_has(uint32_t, wp->w_buffer->b_extmark_ns, (uint32_t)ns_id)) {
1289        changed_window_setting(wp);
1290      }
1291    }
1292  } else if (!set_scoped && set_has(uint32_t, &namespace_localscope, (uint32_t)ns_id)) {
1293    set_del(uint32_t, &namespace_localscope, (uint32_t)ns_id);
1294
1295    // When a namespace becomes unscoped, any window which does not
1296    // contain elements associated with namespace needs to be redrawn
1297    FOR_ALL_TAB_WINDOWS(tp, wp) {
1298      if (map_has(uint32_t, wp->w_buffer->b_extmark_ns, (uint32_t)ns_id)) {
1299        changed_window_setting(wp);
1300      }
1301    }
1302  }
1303}
1304
1305/// Get the properties for namespace
1306///
1307/// @param ns_id Namespace
1308/// @return  Map defining the namespace properties, see |nvim__ns_set()|
1309Dict(ns_opts) nvim__ns_get(Integer ns_id, Arena *arena, Error *err)
1310{
1311  Dict(ns_opts) opts = KEYDICT_INIT;
1312
1313  Array windows = ARRAY_DICT_INIT;
1314
1315  PUT_KEY(opts, ns_opts, wins, windows);
1316
1317  VALIDATE_INT(ns_initialized((uint32_t)ns_id), "ns_id", ns_id, {
1318    return opts;
1319  });
1320
1321  if (!set_has(uint32_t, &namespace_localscope, (uint32_t)ns_id)) {
1322    return opts;
1323  }
1324
1325  size_t count = 0;
1326  FOR_ALL_TAB_WINDOWS(tp, wp) {
1327    if (set_has(uint32_t, &wp->w_ns_set, (uint32_t)ns_id)) {
1328      count++;
1329    }
1330  }
1331
1332  windows = arena_array(arena, count);
1333
1334  FOR_ALL_TAB_WINDOWS(tp, wp) {
1335    if (set_has(uint32_t, &wp->w_ns_set, (uint32_t)ns_id)) {
1336      ADD(windows, INTEGER_OBJ(wp->handle));
1337    }
1338  }
1339
1340  PUT_KEY(opts, ns_opts, wins, windows);
1341
1342  return opts;
1343}