robin/laufey

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

Freddie Haddadfix(decor): highlight without 'hl_eol' bleeds into wrap gaps #41160a8da01f8e6

master
43.5 KiB1434 linesraw
1#include <assert.h>
2#include <limits.h>
3#include <stddef.h>
4#include <stdlib.h>
5#include <string.h>
6
7#include "nvim/api/extmark.h"
8#include "nvim/api/private/defs.h"
9#include "nvim/api/private/helpers.h"
10#include "nvim/ascii_defs.h"
11#include "nvim/buffer.h"
12#include "nvim/buffer_defs.h"
13#include "nvim/change.h"
14#include "nvim/decoration.h"
15#include "nvim/decoration_provider.h"
16#include "nvim/drawscreen.h"
17#include "nvim/extmark.h"
18#include "nvim/fold.h"
19#include "nvim/globals.h"
20#include "nvim/grid.h"
21#include "nvim/highlight.h"
22#include "nvim/highlight_group.h"
23#include "nvim/indent.h"
24#include "nvim/marktree.h"
25#include "nvim/mbyte.h"
26#include "nvim/memory.h"
27#include "nvim/memory_defs.h"
28#include "nvim/move.h"
29#include "nvim/option_vars.h"
30#include "nvim/pos_defs.h"
31#include "nvim/sign.h"
32
33#include "decoration.c.generated.h"
34
35static uint32_t decor_freelist = UINT32_MAX;
36
37// Decorations might be requested to be deleted in a callback in the middle of redrawing.
38// In this case, there might still be live references to the memory allocated for the decoration.
39// Keep a "to free" list which can be safely processed when redrawing is done.
40static DecorVirtText *to_free_virt = NULL;
41static uint32_t to_free_sh = UINT32_MAX;
42
43/// Add highlighting to a buffer, bounded by two cursor positions,
44/// with an offset.
45///
46/// TODO(bfredl): make decoration powerful enough so that this
47/// can be done with a single ephemeral decoration.
48///
49/// @param buf Buffer to add highlights to
50/// @param src_id src_id to use or 0 to use a new src_id group,
51///               or -1 for ungrouped highlight.
52/// @param hl_id Highlight group id
53/// @param pos_start Cursor position to start the highlighting at
54/// @param pos_end Cursor position to end the highlighting at
55/// @param offset Move the whole highlighting this many columns to the right
56void bufhl_add_hl_pos_offset(buf_T *buf, int src_id, int hl_id, lpos_T pos_start, lpos_T pos_end,
57                             colnr_T offset)
58{
59  colnr_T hl_start = 0;
60  colnr_T hl_end = 0;
61  DecorInline decor = DECOR_INLINE_INIT;
62  decor.data.hl.hl_id = hl_id;
63
64  // TODO(bfredl): if decoration had blocky mode, we could avoid this loop
65  for (linenr_T lnum = pos_start.lnum; lnum <= pos_end.lnum; lnum++) {
66    int end_off = 0;
67    if (pos_start.lnum < lnum && lnum < pos_end.lnum) {
68      // TODO(bfredl): This is quite ad-hoc, but the space between |num| and
69      // text being highlighted is the indication of \n being part of the
70      // substituted text. But it would be more consistent to highlight
71      // a space _after_ the previous line instead (like highlight EOL list
72      // char)
73      hl_start = MAX(offset - 1, 0);
74      end_off = 1;
75      hl_end = 0;
76    } else if (lnum == pos_start.lnum && lnum < pos_end.lnum) {
77      hl_start = pos_start.col + offset;
78      end_off = 1;
79      hl_end = 0;
80    } else if (pos_start.lnum < lnum && lnum == pos_end.lnum) {
81      hl_start = MAX(offset - 1, 0);
82      hl_end = pos_end.col + offset;
83    } else if (pos_start.lnum == lnum && pos_end.lnum == lnum) {
84      hl_start = pos_start.col + offset;
85      hl_end = pos_end.col + offset;
86    }
87
88    extmark_set(buf, (uint32_t)src_id, NULL,
89                (int)lnum - 1, hl_start, (int)lnum - 1 + end_off, hl_end,
90                decor, MT_FLAG_DECOR_HL, true, false, true, false, NULL);
91  }
92}
93
94void decor_redraw(buf_T *buf, int row1, int row2, int col1, DecorInline decor)
95{
96  if (decor.ext) {
97    DecorVirtText *vt = decor.data.ext.vt;
98    while (vt) {
99      bool below = (vt->flags & kVTIsLines) && !(vt->flags & kVTLinesAbove);
100      linenr_T vt_lnum = row1 + 1 + below;
101      redraw_buf_line_later(buf, vt_lnum, true);
102      if (vt->flags & kVTIsLines || vt->pos == kVPosInline) {
103        // changed_lines_redraw_buf(buf, vt_lnum, vt_lnum + 1, 0);
104        colnr_T vt_col = vt->flags & kVTIsLines ? 0 : col1;
105        changed_lines_invalidate_buf(buf, vt_lnum, vt_col, vt_lnum + 1, 0);
106      }
107      vt = vt->next;
108    }
109
110    uint32_t idx = decor.data.ext.sh_idx;
111    while (idx != DECOR_ID_INVALID) {
112      DecorSignHighlight *sh = &kv_A(decor_items, idx);
113      decor_redraw_sh(buf, row1, row2, *sh);
114      idx = sh->next;
115    }
116  } else {
117    decor_redraw_sh(buf, row1, row2, decor_sh_from_inline(decor.data.hl));
118  }
119}
120
121void decor_redraw_sh(buf_T *buf, int row1, int row2, DecorSignHighlight sh)
122{
123  if (sh.hl_id || (sh.url != NULL)
124      || (sh.flags & (kSHIsSign | kSHSpellOn | kSHSpellOff | kSHConceal | kSHConcealOff))) {
125    if (row2 >= row1) {
126      redraw_buf_range_later(buf, row1 + 1, row2 + 1);
127    }
128  }
129  if (sh.flags & kSHConcealLines) {
130    FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
131      // TODO(luukvbaal): redraw only unconcealed lines, and scroll lines below
132      // it up or down. Also when opening/closing a fold.
133      if (wp->w_buffer == buf) {
134        changed_window_setting(wp);
135      }
136    }
137  }
138  if (sh.flags & kSHUIWatched) {
139    redraw_buf_line_later(buf, row1 + 1, false);
140  }
141}
142
143uint32_t decor_put_sh(DecorSignHighlight item)
144{
145  if (decor_freelist != UINT32_MAX) {
146    uint32_t pos = decor_freelist;
147    decor_freelist = kv_A(decor_items, decor_freelist).next;
148    kv_A(decor_items, pos) = item;
149    return pos;
150  } else {
151    uint32_t pos = (uint32_t)kv_size(decor_items);
152    kv_push(decor_items, item);
153    return pos;
154  }
155}
156
157DecorVirtText *decor_put_vt(DecorVirtText vt, DecorVirtText *next)
158{
159  DecorVirtText *decor_alloc = xmalloc(sizeof *decor_alloc);
160  *decor_alloc = vt;
161  decor_alloc->next = next;
162  return decor_alloc;
163}
164
165DecorSignHighlight decor_sh_from_inline(DecorHighlightInline item)
166{
167  // TODO(bfredl): Eventually simple signs will be inlinable as well
168  assert(!(item.flags & kSHIsSign));
169  DecorSignHighlight conv = {
170    .flags = item.flags,
171    .priority = item.priority,
172    .text[0] = item.conceal_char,
173    .hl_id = item.hl_id,
174    .number_hl_id = 0,
175    .line_hl_id = 0,
176    .cursorline_hl_id = 0,
177    .next = DECOR_ID_INVALID,
178  };
179
180  return conv;
181}
182
183void buf_put_decor(buf_T *buf, DecorInline decor, int row, int row2)
184{
185  if (decor.ext && row < buf->b_ml.ml_line_count) {
186    uint32_t idx = decor.data.ext.sh_idx;
187    row2 = MIN(buf->b_ml.ml_line_count - 1, row2);
188    while (idx != DECOR_ID_INVALID) {
189      DecorSignHighlight *sh = &kv_A(decor_items, idx);
190      buf_put_decor_sh(buf, sh, row, row2);
191      idx = sh->next;
192    }
193  }
194}
195
196/// When displaying signs in the 'number' column, if the width of the number
197/// column is less than 2, then force recomputing the width after placing or
198/// unplacing the first sign in "buf".
199static void may_force_numberwidth_recompute(buf_T *buf, bool unplace)
200{
201  FOR_ALL_TAB_WINDOWS(tp, wp) {
202    if (wp->w_buffer == buf
203        && wp->w_minscwidth == SCL_NUM
204        && (wp->w_p_nu || wp->w_p_rnu)
205        && (unplace || wp->w_nrwidth_width < 2)) {
206      wp->w_nrwidth_line_count = 0;
207    }
208  }
209}
210
211static int sign_add_id = 0;
212void buf_put_decor_sh(buf_T *buf, DecorSignHighlight *sh, int row1, int row2)
213{
214  if (sh->flags & kSHIsSign) {
215    sh->sign_add_id = sign_add_id++;
216    if (sh->text[0]) {
217      buf_signcols_count_range(buf, row1, row2, 1, kFalse);
218      may_force_numberwidth_recompute(buf, false);
219    }
220  }
221}
222
223void buf_decor_remove(buf_T *buf, int row1, int row2, int col1, DecorInline decor, bool free)
224{
225  decor_redraw(buf, row1, row2, col1, decor);
226  if (decor.ext && row1 < buf->b_ml.ml_line_count) {
227    uint32_t idx = decor.data.ext.sh_idx;
228    row2 = MIN(buf->b_ml.ml_line_count - 1, row2);
229    while (idx != DECOR_ID_INVALID) {
230      DecorSignHighlight *sh = &kv_A(decor_items, idx);
231      buf_remove_decor_sh(buf, row1, row2, sh);
232      idx = sh->next;
233    }
234  }
235  if (free) {
236    decor_free(decor);
237  }
238}
239
240void buf_remove_decor_sh(buf_T *buf, int row1, int row2, DecorSignHighlight *sh)
241{
242  if (sh->flags & kSHIsSign) {
243    if (sh->text[0]) {
244      if (buf_meta_total(buf, kMTMetaSignText)) {
245        buf_signcols_count_range(buf, row1, row2, -1, kFalse);
246      } else {
247        may_force_numberwidth_recompute(buf, true);
248        buf->b_signcols.count[0] = 0;
249        buf->b_signcols.max = 0;
250      }
251    }
252  }
253}
254
255void decor_free(DecorInline decor)
256{
257  if (!decor.ext) {
258    return;
259  }
260  DecorVirtText *vt = decor.data.ext.vt;
261  uint32_t idx = decor.data.ext.sh_idx;
262
263  if (decor_state.running_decor_provider) {
264    while (vt) {
265      if (vt->next == NULL) {
266        vt->next = to_free_virt;
267        to_free_virt = decor.data.ext.vt;
268        break;
269      }
270      vt = vt->next;
271    }
272    while (idx != DECOR_ID_INVALID) {
273      DecorSignHighlight *sh = &kv_A(decor_items, idx);
274      if (sh->next == DECOR_ID_INVALID) {
275        sh->next = to_free_sh;
276        to_free_sh = decor.data.ext.sh_idx;
277        break;
278      }
279      idx = sh->next;
280    }
281  } else {
282    // safe to delete right now
283    decor_free_inner(vt, idx);
284  }
285}
286
287static void decor_free_inner(DecorVirtText *vt, uint32_t first_idx)
288{
289  while (vt) {
290    if (vt->flags & kVTIsLines) {
291      clear_virtlines(&vt->data.virt_lines);
292    } else {
293      clear_virttext(&vt->data.virt_text);
294    }
295    DecorVirtText *tofree = vt;
296    vt = vt->next;
297    xfree(tofree);
298  }
299
300  uint32_t idx = first_idx;
301  while (idx != DECOR_ID_INVALID) {
302    DecorSignHighlight *sh = &kv_A(decor_items, idx);
303    if (sh->flags & kSHIsSign) {
304      XFREE_CLEAR(sh->sign_name);
305    }
306    sh->flags = 0;
307    if (sh->url != NULL) {
308      XFREE_CLEAR(sh->url);
309    }
310    if (sh->next == DECOR_ID_INVALID) {
311      sh->next = decor_freelist;
312      decor_freelist = first_idx;
313      break;
314    }
315    idx = sh->next;
316  }
317}
318
319/// Check if we are in a callback while drawing, which might invalidate the marktree iterator.
320///
321/// This should be called whenever a structural modification has been done to a
322/// marktree in a public API function (i e any change which adds or deletes marks).
323void decor_state_invalidate(buf_T *buf)
324{
325  if (decor_state.win && decor_state.win->w_buffer == buf) {
326    decor_state.itr_valid = false;
327  }
328}
329
330void decor_check_to_be_deleted(void)
331{
332  assert(!decor_state.running_decor_provider);
333  decor_free_inner(to_free_virt, to_free_sh);
334  to_free_virt = NULL;
335  to_free_sh = DECOR_ID_INVALID;
336  decor_state.win = NULL;
337}
338
339void decor_state_free(DecorState *state)
340{
341  kv_destroy(state->slots);
342  kv_destroy(state->ranges_i);
343}
344
345void clear_virttext(VirtText *text)
346{
347  for (size_t i = 0; i < kv_size(*text); i++) {
348    xfree(kv_A(*text, i).text);
349  }
350  kv_destroy(*text);
351  *text = (VirtText)KV_INITIAL_VALUE;
352}
353
354void clear_virtlines(VirtLines *lines)
355{
356  for (size_t i = 0; i < kv_size(*lines); i++) {
357    clear_virttext(&kv_A(*lines, i).line);
358  }
359  kv_destroy(*lines);
360  *lines = (VirtLines)KV_INITIAL_VALUE;
361}
362
363void decor_check_invalid_glyphs(void)
364{
365  for (size_t i = 0; i < kv_size(decor_items); i++) {
366    DecorSignHighlight *it = &kv_A(decor_items, i);
367    int width = (it->flags & kSHIsSign) ? SIGN_WIDTH : ((it->flags & kSHConceal) ? 1 : 0);
368    for (int j = 0; j < width; j++) {
369      if (schar_high(it->text[j])) {
370        it->text[j] = schar_from_char(schar_get_first_codepoint(it->text[j]));
371      }
372    }
373  }
374}
375
376/// Get the next chunk of a virtual text item.
377///
378/// @param[in]     vt    The virtual text item
379/// @param[in,out] pos   Position in the virtual text item
380/// @param[in,out] attr  Highlight attribute
381///
382/// @return  The text of the chunk, or NULL if there are no more chunks
383char *next_virt_text_chunk(VirtText vt, size_t *pos, int *attr)
384{
385  char *text = NULL;
386  for (; text == NULL && *pos < kv_size(vt); (*pos)++) {
387    text = kv_A(vt, *pos).text;
388    int hl_id = kv_A(vt, *pos).hl_id;
389    if (hl_id >= 0) {
390      *attr = MAX(*attr, 0);
391      if (hl_id > 0) {
392        *attr = hl_combine_attr(*attr, syn_id2attr(hl_id));
393      }
394    }
395  }
396  return text;
397}
398
399DecorVirtText *decor_find_virttext(buf_T *buf, int row, uint64_t ns_id)
400{
401  MarkTreeIter itr[1] = { 0 };
402  marktree_itr_get(buf->b_marktree, row, 0,  itr);
403  while (true) {
404    MTKey mark = marktree_itr_current(itr);
405    if (mark.pos.row < 0 || mark.pos.row > row) {
406      break;
407    } else if (mt_invalid(mark)) {
408      goto next_mark;
409    }
410    DecorVirtText *decor = mt_decor_virt(mark);
411    while (decor && (decor->flags & kVTIsLines)) {
412      decor = decor->next;
413    }
414    if ((ns_id == 0 || ns_id == mark.ns) && decor) {
415      return decor;
416    }
417next_mark:
418    marktree_itr_next(buf->b_marktree, itr);
419  }
420  return NULL;
421}
422
423bool decor_redraw_reset(win_T *wp, DecorState *state)
424{
425  state->row = -1;
426  state->win = wp;
427
428  int *const indices = state->ranges_i.items;
429  DecorRangeSlot *const slots = state->slots.items;
430
431  int const beg_pos[] = { 0, state->future_begin };
432  int const end_pos[] = { state->current_end, (int)kv_size(state->ranges_i) };
433
434  for (int pos_i = 0; pos_i < 2; pos_i++) {
435    for (int i = beg_pos[pos_i]; i < end_pos[pos_i]; i++) {
436      DecorRange *const r = &slots[indices[i]].range;
437      if (r->owned && r->kind == kDecorKindVirtText) {
438        clear_virttext(&r->data.vt->data.virt_text);
439        xfree(r->data.vt);
440      }
441    }
442  }
443
444  kv_size(state->slots) = 0;
445  kv_size(state->ranges_i) = 0;
446  state->free_slot_i = -1;
447  state->current_end = 0;
448  state->future_begin = 0;
449  state->new_range_ordering = 0;
450
451  return wp->w_buffer->b_marktree->n_keys;
452}
453
454/// @return true if decor has a virtual position (virtual text or ui_watched)
455bool decor_virt_pos(const DecorRange *decor)
456{
457  return (decor->kind == kDecorKindVirtText || decor->kind == kDecorKindUIWatched);
458}
459
460VirtTextPos decor_virt_pos_kind(const DecorRange *decor)
461{
462  if (decor->kind == kDecorKindVirtText) {
463    return decor->data.vt->pos;
464  }
465  if (decor->kind == kDecorKindUIWatched) {
466    return decor->data.ui.pos;
467  }
468  return kVPosEndOfLine;  // not used; return whatever
469}
470
471bool decor_redraw_start(win_T *wp, int top_row, DecorState *state)
472{
473  buf_T *buf = wp->w_buffer;
474  state->top_row = top_row;
475  state->itr_valid = true;
476
477  if (!marktree_itr_get_overlap(buf->b_marktree, top_row, 0, state->itr)) {
478    return false;
479  }
480  MTPair pair;
481
482  while (marktree_itr_step_overlap(buf->b_marktree, state->itr, &pair)) {
483    MTKey m = pair.start;
484    if (mt_invalid(m) || !mt_decor_any(m)) {
485      continue;
486    }
487
488    decor_range_add_from_inline(state, pair.start.pos.row, pair.start.pos.col, pair.end_pos.row,
489                                pair.end_pos.col,
490                                mt_decor(m), false, m.ns, m.id);
491  }
492
493  return true;  // TODO(bfredl): check if available in the region
494}
495
496static void decor_state_pack(DecorState *state)
497{
498  int count = (int)kv_size(state->ranges_i);
499  int const cur_end = state->current_end;
500  int fut_beg = state->future_begin;
501
502  // Move future ranges to start right after current ranges.
503  // Otherwise future ranges will grow forward indefinitely.
504  if (fut_beg == count) {
505    fut_beg = count = cur_end;
506  } else if (fut_beg != cur_end) {
507    int *const indices = state->ranges_i.items;
508    memmove(indices + cur_end, indices + fut_beg, (size_t)(count - fut_beg) * sizeof(indices[0]));
509
510    count = cur_end + (count - fut_beg);
511    fut_beg = cur_end;
512  }
513
514  kv_size(state->ranges_i) = (size_t)count;
515  state->future_begin = fut_beg;
516}
517
518void decor_redraw_line(win_T *wp, int row, DecorState *state)
519{
520  decor_state_pack(state);
521
522  if (state->row == -1) {
523    decor_redraw_start(wp, row, state);
524  } else if (!state->itr_valid) {
525    marktree_itr_get(wp->w_buffer->b_marktree, row, 0, state->itr);
526    state->itr_valid = true;
527  }
528
529  state->row = row;
530  state->col_last = -1;
531  state->eol_col = -1;
532}
533
534// Checks if there are (likely) more decorations on the current line.
535bool decor_has_more_decorations(DecorState *state, int row)
536{
537  if (state->current_end != 0 || state->future_begin != (int)kv_size(state->ranges_i)) {
538    return true;
539  }
540
541  MTKey k = marktree_itr_current(state->itr);
542  return (k.pos.row >= 0 && k.pos.row <= row);
543}
544
545static void decor_range_add_from_inline(DecorState *state, int start_row, int start_col,
546                                        int end_row, int end_col, DecorInline decor, bool owned,
547                                        uint32_t ns, uint32_t mark_id)
548{
549  if (decor.ext) {
550    DecorVirtText *vt = decor.data.ext.vt;
551    while (vt) {
552      decor_range_add_virt(state, start_row, start_col, end_row, end_col, vt, owned);
553      vt = vt->next;
554    }
555    uint32_t idx = decor.data.ext.sh_idx;
556    while (idx != DECOR_ID_INVALID) {
557      DecorSignHighlight *sh = &kv_A(decor_items, idx);
558      decor_range_add_sh(state, start_row, start_col, end_row, end_col, sh, owned, ns, mark_id, 0);
559      idx = sh->next;
560    }
561  } else {
562    DecorSignHighlight sh = decor_sh_from_inline(decor.data.hl);
563    decor_range_add_sh(state, start_row, start_col, end_row, end_col, &sh, owned, ns, mark_id, 0);
564  }
565}
566
567static void decor_range_insert(DecorState *state, DecorRange *range)
568{
569  range->ordering = state->new_range_ordering++;
570
571  int index;
572  // Get space for a new `DecorRange` from the freelist or allocate.
573  if (state->free_slot_i >= 0) {
574    index = state->free_slot_i;
575    DecorRangeSlot *slot = &kv_A(state->slots, index);
576    state->free_slot_i = slot->next_free_i;
577    slot->range = *range;
578  } else {
579    index = (int)kv_size(state->slots);
580    kv_pushp(state->slots)->range = *range;
581  }
582
583  int const row = range->start_row;
584  int const col = range->start_col;
585
586  int const count = (int)kv_size(state->ranges_i);
587  int *const indices = state->ranges_i.items;
588  DecorRangeSlot *const slots = state->slots.items;
589
590  int begin = state->future_begin;
591  int end = count;
592  while (begin < end) {
593    int const mid = begin + ((end - begin) >> 1);
594    DecorRange *const mr = &slots[indices[mid]].range;
595
596    int const mrow = mr->start_row;
597    int const mcol = mr->start_col;
598    if (mrow < row || (mrow == row && mcol <= col)) {
599      begin = mid + 1;
600      if (mrow == row && mcol == col) {
601        break;
602      }
603    } else {
604      end = mid;
605    }
606  }
607
608  kv_pushp(state->ranges_i);
609  int *const item = &kv_A(state->ranges_i, begin);
610  memmove(item + 1, item, (size_t)(count - begin) * sizeof(*item));
611  *item = index;
612}
613
614void decor_range_add_virt(DecorState *state, int start_row, int start_col, int end_row, int end_col,
615                          DecorVirtText *vt, bool owned)
616{
617  bool is_lines = vt->flags & kVTIsLines;
618  DecorRange range = {
619    .start_row = start_row, .start_col = start_col, .end_row = end_row, .end_col = end_col,
620    .kind = is_lines ? kDecorKindVirtLines : kDecorKindVirtText,
621    .data.vt = vt,
622    .attr_id = 0,
623    .owned = owned,
624    .priority_internal = ((DecorPriorityInternal)vt->priority << 16),
625    .draw_col = -10,
626  };
627  decor_range_insert(state, &range);
628}
629
630void decor_range_add_sh(DecorState *state, int start_row, int start_col, int end_row, int end_col,
631                        DecorSignHighlight *sh, bool owned, uint32_t ns, uint32_t mark_id,
632                        DecorPriority subpriority)
633{
634  if (sh->flags & kSHIsSign) {
635    return;
636  }
637
638  DecorRange range = {
639    .start_row = start_row, .start_col = start_col, .end_row = end_row, .end_col = end_col,
640    .kind = kDecorKindHighlight,
641    .data.sh = *sh,
642    .attr_id = 0,
643    .owned = owned,
644    .priority_internal = ((DecorPriorityInternal)sh->priority << 16) + subpriority,
645    .draw_col = -10,
646  };
647
648  if (sh->hl_id || (sh->url != NULL)
649      || (sh->flags & (kSHConcealOff | kSHConceal | kSHSpellOn | kSHSpellOff))) {
650    if (sh->hl_id) {
651      range.attr_id = syn_id2attr(sh->hl_id);
652    }
653    decor_range_insert(state, &range);
654  }
655
656  if (sh->flags & kSHUIWatched) {
657    range.kind = kDecorKindUIWatched;
658    range.data.ui.ns_id = ns;
659    range.data.ui.mark_id = mark_id;
660    range.data.ui.pos = (sh->flags & kSHUIWatchedOverlay) ? kVPosOverlay : kVPosEndOfLine;
661    decor_range_insert(state, &range);
662  }
663}
664
665/// Initialize the draw_col of a newly-added virtual text item.
666void decor_init_draw_col(int win_col, bool hidden, DecorRange *item)
667{
668  DecorVirtText *vt = item->kind == kDecorKindVirtText ? item->data.vt : NULL;
669  VirtTextPos pos = decor_virt_pos_kind(item);
670  if (win_col < 0 && pos != kVPosInline) {
671    item->draw_col = win_col;
672  } else if (pos == kVPosOverlay) {
673    item->draw_col = (vt && (vt->flags & kVTHide) && hidden) ? INT_MIN : win_col;
674  } else {
675    item->draw_col = -1;
676  }
677}
678
679void decor_recheck_draw_col(int win_col, bool hidden, DecorState *state)
680{
681  int const end = state->current_end;
682  int *const indices = state->ranges_i.items;
683  DecorRangeSlot *const slots = state->slots.items;
684
685  for (int i = 0; i < end; i++) {
686    DecorRange *const r = &slots[indices[i]].range;
687    if (r->draw_col == -3) {
688      decor_init_draw_col(win_col, hidden, r);
689    }
690  }
691}
692
693int decor_redraw_col_impl(win_T *wp, int col, int win_col, bool hidden, DecorState *state,
694                          int max_col_last)
695{
696  buf_T *const buf = wp->w_buffer;
697  int const row = state->row;
698  int col_last = max_col_last;
699
700  while (true) {
701    // TODO(bfredl): check duplicate entry in "intersection"
702    // branch
703    MTKey mark = marktree_itr_current(state->itr);
704    if (mark.pos.row < 0 || mark.pos.row > row) {
705      break;
706    } else if (mark.pos.row == row && mark.pos.col > col) {
707      col_last = MIN(col_last, mark.pos.col - 1);
708      break;
709    }
710
711    if (mt_invalid(mark) || mt_end(mark) || !mt_decor_any(mark) || !ns_in_win(mark.ns, wp)) {
712      goto next_mark;
713    }
714
715    MTPos endpos = marktree_get_altpos(buf->b_marktree, mark, NULL);
716    decor_range_add_from_inline(state, mark.pos.row, mark.pos.col, endpos.row, endpos.col,
717                                mt_decor(mark), false, mark.ns, mark.id);
718
719next_mark:
720    marktree_itr_next(buf->b_marktree, state->itr);
721  }
722
723  int *const indices = state->ranges_i.items;
724  DecorRangeSlot *const slots = state->slots.items;
725
726  int count = (int)kv_size(state->ranges_i);
727  int cur_end = state->current_end;
728  int fut_beg = state->future_begin;
729
730  // Promote future ranges before the cursor to active.
731  for (; fut_beg < count; fut_beg++) {
732    int const index = indices[fut_beg];
733    DecorRange *const r = &slots[index].range;
734    if (r->start_row > row || (r->start_row == row && r->start_col > col)) {
735      break;
736    }
737    int const ordering = r->ordering;
738    DecorPriorityInternal const priority = r->priority_internal;
739
740    int begin = 0;
741    int end = cur_end;
742    while (begin < end) {
743      int mid = begin + ((end - begin) >> 1);
744      int mi = indices[mid];
745      DecorRange *mr = &slots[mi].range;
746      if (mr->priority_internal < priority
747          || (mr->priority_internal == priority && mr->ordering < ordering)) {
748        begin = mid + 1;
749      } else {
750        end = mid;
751      }
752    }
753
754    int *const item = indices + begin;
755    memmove(item + 1, item, (size_t)(cur_end - begin) * sizeof(*item));
756    *item = index;
757    cur_end++;
758  }
759
760  if (fut_beg < count) {
761    DecorRange *r = &slots[indices[fut_beg]].range;
762    if (r->start_row == row) {
763      col_last = MIN(col_last, r->start_col - 1);
764    }
765  }
766
767  int new_cur_end = 0;
768
769  int attr = 0;
770  int hl_eol_attr = 0;
771  int conceal = 0;
772  schar_T conceal_char = 0;
773  int conceal_attr = 0;
774  TriState spell = kNone;
775
776  for (int i = 0; i < cur_end; i++) {
777    int const index = indices[i];
778    DecorRangeSlot *const slot = slots + index;
779    DecorRange *const r = &slot->range;
780
781    bool keep;
782    if (r->end_row < row || (r->end_row == row && r->end_col <= col)) {
783      keep = r->start_row >= row && decor_virt_pos(r);
784    } else {
785      keep = true;
786
787      if (r->end_row == row && r->end_col > col) {
788        col_last = MIN(col_last, r->end_col - 1);
789      }
790
791      if (r->attr_id > 0) {
792        attr = hl_combine_attr(attr, r->attr_id);
793        if (r->kind == kDecorKindHighlight && (r->data.sh.flags & kSHHlEol)) {
794          hl_eol_attr = hl_combine_attr(hl_eol_attr, r->attr_id);
795        }
796      }
797
798      if (r->kind == kDecorKindHighlight && (r->data.sh.flags & kSHConceal)) {
799        conceal = 1;
800        if (r->start_row == row && r->start_col == col) {
801          DecorSignHighlight *sh = &r->data.sh;
802          conceal = 2;
803          conceal_char = sh->text[0];
804          col_last = MIN(col_last, r->start_col);
805          conceal_attr = r->attr_id;
806        }
807      }
808
809      if (r->kind == kDecorKindHighlight && (r->data.sh.flags & kSHConcealOff)) {
810        conceal = 0;
811      }
812
813      if (r->kind == kDecorKindHighlight) {
814        if (r->data.sh.flags & kSHSpellOn) {
815          spell = kTrue;
816        } else if (r->data.sh.flags & kSHSpellOff) {
817          spell = kFalse;
818        }
819        if (r->data.sh.url != NULL) {
820          attr = hl_add_url(attr, r->data.sh.url);
821        }
822      }
823    }
824
825    if (r->start_row == row && r->start_col <= col
826        && decor_virt_pos(r) && r->draw_col == -10) {
827      decor_init_draw_col(win_col, hidden, r);
828    }
829
830    if (keep) {
831      indices[new_cur_end++] = index;
832    } else {
833      if (r->owned) {
834        if (r->kind == kDecorKindVirtText) {
835          clear_virttext(&r->data.vt->data.virt_text);
836          xfree(r->data.vt);
837        } else if (r->kind == kDecorKindHighlight) {
838          xfree((void *)r->data.sh.url);
839        }
840      }
841
842      int *fi = &state->free_slot_i;
843      slot->next_free_i = *fi;
844      *fi = index;
845    }
846  }
847  cur_end = new_cur_end;
848
849  if (fut_beg == count) {
850    fut_beg = count = cur_end;
851  }
852
853  kv_size(state->ranges_i) = (size_t)count;
854  state->future_begin = fut_beg;
855  state->current_end = cur_end;
856  state->col_last = col_last;
857
858  state->current = attr;
859  state->current_hl_eol = hl_eol_attr;
860  state->conceal = conceal;
861  state->conceal_char = conceal_char;
862  state->conceal_attr = conceal_attr;
863  state->spell = spell;
864  return attr;
865}
866
867static const uint32_t conceal_filter[kMTMetaCount] = {[kMTMetaConcealLines] = kMTFilterSelect };
868
869/// Called by draw, move and plines code to determine whether a line is concealed.
870/// Scans the marktree for conceal_line marks on "row" and invokes any
871/// _on_conceal_line decoration provider callbacks, if necessary.
872///
873/// @param check_cursor If true, avoid an early return for an unconcealed cursorline.
874///                     Depending on the callsite, we still want to know whether the
875///                     cursor line would be concealed if it was not the cursorline.
876///
877/// @return whether "row" is concealed
878bool decor_conceal_line(win_T *wp, int row, bool check_cursor)
879{
880  if (row < 0 || wp->w_p_cole < 2
881      || (!check_cursor && wp == curwin && row + 1 == wp->w_cursor.lnum
882          && !conceal_cursor_line(wp))) {
883    return false;
884  }
885
886  // No need to scan the marktree if there are no conceal_line marks.
887  if (!buf_meta_total(wp->w_buffer, kMTMetaConcealLines)) {
888    return decor_providers_invoke_conceal_line(wp, row);
889  }
890
891  // Scan the marktree for any conceal_line marks on this row.
892  MTPair pair;
893  MarkTreeIter itr[1];
894  marktree_itr_get_overlap(wp->w_buffer->b_marktree, row, 0, itr);
895  while (marktree_itr_step_overlap(wp->w_buffer->b_marktree, itr, &pair)) {
896    if (mt_conceal_lines(pair.start) && ns_in_win(pair.start.ns, wp)) {
897      return true;
898    }
899  }
900
901  marktree_itr_step_out_filter(wp->w_buffer->b_marktree, itr, conceal_filter);
902
903  while (itr->x) {
904    MTKey mark = marktree_itr_current(itr);
905    if (mark.pos.row > row) {
906      break;
907    }
908    if (mt_conceal_lines(mark) && ns_in_win(mark.ns, wp)) {
909      return true;
910    }
911    marktree_itr_next_filter(wp->w_buffer->b_marktree, itr, row + 1, 0, conceal_filter);
912  }
913
914  return decor_providers_invoke_conceal_line(wp, row);
915}
916
917/// @return whether a window may have folded or concealed lines
918bool win_lines_concealed(win_T *wp)
919{
920  return hasAnyFolding(wp) || wp->w_p_cole >= 2;
921}
922
923int sign_item_cmp(const void *p1, const void *p2)
924{
925  const SignItem *s1 = (SignItem *)p1;
926  const SignItem *s2 = (SignItem *)p2;
927
928  if (s1->sh->priority != s2->sh->priority) {
929    return s1->sh->priority < s2->sh->priority ? 1 : -1;
930  }
931
932  if (s1->id != s2->id) {
933    return s1->id < s2->id ? 1 : -1;
934  }
935
936  if (s1->sh->sign_add_id != s2->sh->sign_add_id) {
937    return s1->sh->sign_add_id < s2->sh->sign_add_id ? 1 : -1;
938  }
939
940  return 0;
941}
942
943static const uint32_t sign_filter[kMTMetaCount] = {[kMTMetaSignText] = kMTFilterSelect,
944                                                   [kMTMetaSignHL] = kMTFilterSelect };
945
946/// Return the signs and highest priority sign attributes on a row.
947///
948/// @param[out] sattrs Output array for sign text and texthl id
949/// @param[out] line_id Highest priority linehl id
950/// @param[out] cul_id Highest priority culhl id
951/// @param[out] num_id Highest priority numhl id
952void decor_redraw_signs(win_T *wp, buf_T *buf, int row, SignTextAttrs sattrs[], int *line_id,
953                        int *cul_id, int *num_id)
954{
955  if (!buf_has_signs(buf)) {
956    return;
957  }
958
959  MTPair pair;
960  int num_text = 0;
961  MarkTreeIter itr[1];
962  kvec_t(SignItem) signs = KV_INITIAL_VALUE;
963  // TODO(bfredl): integrate with main decor loop.
964  marktree_itr_get_overlap(buf->b_marktree, row, 0, itr);
965  while (marktree_itr_step_overlap(buf->b_marktree, itr, &pair)) {
966    if (!mt_invalid(pair.start) && mt_decor_sign(pair.start) && ns_in_win(pair.start.ns, wp)) {
967      DecorSignHighlight *sh = decor_find_sign(mt_decor(pair.start));
968      num_text += (sh->text[0] != NUL);
969      kv_push(signs, ((SignItem){ sh, pair.start.id }));
970    }
971  }
972
973  marktree_itr_step_out_filter(buf->b_marktree, itr, sign_filter);
974
975  while (itr->x) {
976    MTKey mark = marktree_itr_current(itr);
977    if (mark.pos.row != row) {
978      break;
979    }
980    if (!mt_invalid(mark) && !mt_end(mark) && mt_decor_sign(mark) && ns_in_win(mark.ns, wp)) {
981      DecorSignHighlight *sh = decor_find_sign(mt_decor(mark));
982      num_text += (sh->text[0] != NUL);
983      kv_push(signs, ((SignItem){ sh, mark.id }));
984    }
985
986    marktree_itr_next_filter(buf->b_marktree, itr, row + 1, 0, sign_filter);
987  }
988
989  if (kv_size(signs)) {
990    int width = wp->w_minscwidth == SCL_NUM ? 1 : wp->w_scwidth;
991    int len = MIN(width, num_text);
992    int idx = 0;
993    qsort((void *)&kv_A(signs, 0), kv_size(signs), sizeof(kv_A(signs, 0)), sign_item_cmp);
994
995    for (size_t i = 0; i < kv_size(signs); i++) {
996      DecorSignHighlight *sh = kv_A(signs, i).sh;
997      if (sattrs && idx < len && sh->text[0]) {
998        memcpy(sattrs[idx].text, sh->text, SIGN_WIDTH * sizeof(sattr_T));
999        sattrs[idx++].hl_id = sh->hl_id;
1000      }
1001      if (num_id != NULL && *num_id <= 0) {
1002        *num_id = sh->number_hl_id;
1003      }
1004      if (line_id != NULL && *line_id <= 0) {
1005        *line_id = sh->line_hl_id;
1006      }
1007      if (cul_id != NULL && *cul_id <= 0) {
1008        *cul_id = sh->cursorline_hl_id;
1009      }
1010    }
1011    kv_destroy(signs);
1012  }
1013}
1014
1015DecorSignHighlight *decor_find_sign(DecorInline decor)
1016{
1017  if (!decor.ext) {
1018    return NULL;
1019  }
1020  uint32_t decor_id = decor.data.ext.sh_idx;
1021  while (true) {
1022    if (decor_id == DECOR_ID_INVALID) {
1023      return NULL;
1024    }
1025    DecorSignHighlight *sh = &kv_A(decor_items, decor_id);
1026    if (sh->flags & kSHIsSign) {
1027      return sh;
1028    }
1029    decor_id = sh->next;
1030  }
1031}
1032
1033static const uint32_t signtext_filter[kMTMetaCount] = {[kMTMetaSignText] = kMTFilterSelect };
1034
1035/// Count the number of signs in a range after adding/removing a sign, or to
1036/// (re-)initialize a range in "b_signcols.count".
1037///
1038/// @param add  1, -1 or 0 for an added, deleted or initialized range.
1039/// @param clear  kFalse, kTrue or kNone for an, added/deleted, cleared, or initialized range.
1040void buf_signcols_count_range(buf_T *buf, int row1, int row2, int add, TriState clear)
1041{
1042  if (!buf->b_signcols.autom || row2 < row1 || !buf_meta_total(buf, kMTMetaSignText)) {
1043    return;
1044  }
1045
1046  // Allocate an array of integers holding the number of signs in the range.
1047  int *count = xcalloc((size_t)(row2 + 1 - row1), sizeof(int));
1048  MarkTreeIter itr[1];
1049  MTPair pair = { 0 };
1050
1051  // Increment count array for signs that start before "row1" but do overlap the range.
1052  marktree_itr_get_overlap(buf->b_marktree, row1, 0, itr);
1053  while (marktree_itr_step_overlap(buf->b_marktree, itr, &pair)) {
1054    if ((pair.start.flags & MT_FLAG_DECOR_SIGNTEXT) && !mt_invalid(pair.start)) {
1055      for (int i = row1; i <= MIN(row2, pair.end_pos.row); i++) {
1056        count[i - row1]++;
1057      }
1058    }
1059  }
1060
1061  marktree_itr_step_out_filter(buf->b_marktree, itr, signtext_filter);
1062
1063  // Continue traversing the marktree until beyond "row2".
1064  while (itr->x) {
1065    MTKey mark = marktree_itr_current(itr);
1066    if (mark.pos.row > row2) {
1067      break;
1068    }
1069    if ((mark.flags & MT_FLAG_DECOR_SIGNTEXT) && !mt_invalid(mark) && !mt_end(mark)) {
1070      // Increment count array for the range of a paired sign mark.
1071      MTPos end = marktree_get_altpos(buf->b_marktree, mark, NULL);
1072      for (int i = mark.pos.row; i <= MIN(row2, end.row); i++) {
1073        count[i - row1]++;
1074      }
1075    }
1076
1077    marktree_itr_next_filter(buf->b_marktree, itr, row2 + 1, 0, signtext_filter);
1078  }
1079
1080  // For each row increment "b_signcols.count" at the number of counted signs,
1081  // and decrement at the previous number of signs. These two operations are
1082  // split in separate calls if "clear" is not kFalse (surrounding a marktree splice).
1083  for (int i = 0; i < row2 + 1 - row1; i++) {
1084    int prevwidth = MIN(SIGN_SHOW_MAX, count[i] - add);
1085    if (clear != kNone && prevwidth > 0) {
1086      buf->b_signcols.count[prevwidth - 1]--;
1087#ifndef RELDEBUG
1088      // TODO(bfredl): correct marktree splicing so that this doesn't fail
1089      assert(buf->b_signcols.count[prevwidth - 1] >= 0);
1090#endif
1091    }
1092    int width = MIN(SIGN_SHOW_MAX, count[i]);
1093    if (clear != kTrue && width > 0) {
1094      buf->b_signcols.count[width - 1]++;
1095      if (width > buf->b_signcols.max) {
1096        buf->b_signcols.max = width;
1097      }
1098    }
1099  }
1100
1101  xfree(count);
1102}
1103
1104void decor_redraw_end(DecorState *state)
1105{
1106  state->win = NULL;
1107}
1108
1109bool decor_redraw_eol(win_T *wp, DecorState *state, int *eol_attr, int eol_col)
1110{
1111  decor_redraw_col(wp, MAXCOL, MAXCOL, false, state, MAXCOL);
1112  state->eol_col = eol_col;
1113
1114  int const count = state->current_end;
1115  int *const indices = state->ranges_i.items;
1116  DecorRangeSlot *const slots = state->slots.items;
1117
1118  bool has_virt_pos = false;
1119  for (int i = 0; i < count; i++) {
1120    DecorRange *r = &slots[indices[i]].range;
1121    has_virt_pos |= r->start_row == state->row && decor_virt_pos(r);
1122
1123    if (r->kind == kDecorKindHighlight && (r->data.sh.flags & kSHHlEol)) {
1124      *eol_attr = hl_combine_attr(*eol_attr, r->attr_id);
1125    }
1126  }
1127  return has_virt_pos;
1128}
1129
1130static const uint32_t lines_filter[kMTMetaCount] = {[kMTMetaLines] = kMTFilterSelect };
1131
1132static inline bool decor_virt_line_wrap(win_T *wp, VirtLineOverflow overflow)
1133{
1134  return overflow == kVLOverflowWrap || (overflow == kVLOverflowAuto && wp->w_p_wrap);
1135}
1136
1137/// Counts the number of rows occupied by a virtual line. When skip_cells is non-NULL, sets it to
1138/// the cell offset where target_row begins.
1139///
1140/// @param target_row Row relative to the virtual line that skip_cells is computed for.
1141/// @param skip_cells Cell offset for the target_row. Pass NULL when only the row count is needed.
1142///
1143/// @return Number of rows occupied by the virtual line.
1144int decor_virt_line_rows(win_T *wp, const struct virt_line *vl, int target_row, int *skip_cells)
1145{
1146  if (skip_cells != NULL) {
1147    *skip_cells = 0;
1148  }
1149  if (!decor_virt_line_wrap(wp, vl->overflow)) {
1150    return 1;
1151  }
1152  int row_width = wp->w_view_width - ((vl->flags & kVLLeftcol) ? 0 : win_col_off(wp));
1153  if (row_width <= 0) {
1154    return 1;
1155  }
1156  VirtText vt = vl->line;
1157  buf_T *buf = wp->w_buffer;
1158  int vcol = 0;
1159  int row_cells = 0;
1160  int row = 0;
1161  for (int i = 0; i < (int)kv_size(vt); i++) {
1162    const char *virt_str = kv_A(vt, i).text;
1163    if (virt_str == NULL) {
1164      continue;
1165    }
1166    while (*virt_str != NUL) {
1167      int bytes_to_next_char = utfc_ptr2len(virt_str);
1168      // Need to compute cell width due to TAB & double width cell chars
1169      int cells = (*virt_str == TAB)
1170                  ? tabstop_padding(vcol, buf->b_p_ts, buf->b_p_vts_array)
1171                  : utf_ptr2cells(virt_str);
1172      virt_str += bytes_to_next_char;
1173      // Wrap before total row cell length would exceed the window size
1174      // to protect against double width cell chars being split at the boundary
1175      if (row_cells + cells > row_width) {
1176        row++;
1177        if (skip_cells != NULL && row == target_row) {
1178          *skip_cells = vcol;
1179        }
1180        row_cells = 0;
1181      }
1182      row_cells += cells;
1183      vcol += cells;
1184    }
1185  }
1186
1187  return row + 1;
1188}
1189
1190/// @param apply_folds Only count virtual lines that are not in folds.
1191/// @return Number of rows occupied by the virtual lines.
1192int decor_virt_lines(win_T *wp, int start_row, int end_row, int *num_below, VirtLines *lines,
1193                     bool apply_folds)
1194{
1195  buf_T *buf = wp->w_buffer;
1196  if (!buf_meta_total(buf, kMTMetaLines)) {
1197    // Only pay for what you use: in case virt_lines feature is not active
1198    // in a buffer, plines do not need to access the marktree at all
1199    return 0;
1200  }
1201
1202  MarkTreeIter itr[1] = { 0 };
1203  if (!marktree_itr_get_filter(buf->b_marktree, MAX(start_row - 1, 0), 0, end_row, 0,
1204                               lines_filter, itr)) {
1205    return 0;
1206  }
1207
1208  assert(start_row >= 0);
1209
1210  int n_virt_lines = 0;
1211  while (true) {
1212    MTKey mark = marktree_itr_current(itr);
1213    DecorVirtText *vt = mt_decor_virt(mark);
1214    if (!mt_invalid(mark) && ns_in_win(mark.ns, wp)) {
1215      while (vt) {
1216        VirtLines virt_lines = vt->data.virt_lines;
1217        if ((vt->flags & kVTIsLines) && kv_size(virt_lines) > 0) {
1218          bool above = vt->flags & kVTLinesAbove;
1219          int mrow = mark.pos.row;
1220          int draw_row = mrow + (above ? 0 : 1);
1221          if (draw_row >= start_row && draw_row < end_row
1222              && (!apply_folds || !(hasFolding(wp, mrow + 1, NULL, NULL)
1223                                    || decor_conceal_line(wp, mrow, false)))) {
1224            // All virtual lines from the same extmark have the same overflow flag.
1225            if (decor_virt_line_wrap(wp, kv_A(virt_lines, 0).overflow)) {
1226              // Iterates over each virtual line summing number of rows.
1227              // Rows belonging to previous line are accumulated in num_below.
1228              for (int i = 0; i < (int)kv_size(virt_lines); i++) {
1229                int rows = decor_virt_line_rows(wp, &kv_A(virt_lines, i), 0, NULL);
1230                n_virt_lines += rows;
1231                if (num_below && !above) {
1232                  (*num_below) += rows;
1233                }
1234              }
1235            } else {
1236              // If virtual lines don't wrap there is no need to iterate over them.
1237              n_virt_lines += (int)kv_size(virt_lines);
1238              if (num_below && !above) {
1239                (*num_below) += (int)kv_size(virt_lines);
1240              }
1241            }
1242            if (lines) {
1243              kv_splice(*lines, virt_lines);
1244            }
1245          }
1246        }
1247        vt = vt->next;
1248      }
1249    }
1250
1251    if (!marktree_itr_next_filter(buf->b_marktree, itr, end_row, 0, lines_filter)) {
1252      break;
1253    }
1254  }
1255
1256  return n_virt_lines;
1257}
1258
1259/// This assumes maximum one entry of each kind, which will not always be the case.
1260///
1261/// NB: assumes caller has allocated enough space in dict for all fields!
1262void decor_to_dict_legacy(Dict *dict, DecorInline decor, bool hl_name, Arena *arena)
1263{
1264  DecorSignHighlight sh_hl = DECOR_SIGN_HIGHLIGHT_INIT;
1265  DecorSignHighlight sh_sign = DECOR_SIGN_HIGHLIGHT_INIT;
1266  DecorVirtText *virt_text = NULL;
1267  DecorVirtText *virt_lines = NULL;
1268  int32_t priority = -1;  // sentinel value which cannot actually be set
1269
1270  if (decor.ext) {
1271    DecorVirtText *vt = decor.data.ext.vt;
1272    while (vt) {
1273      if (vt->flags & kVTIsLines) {
1274        virt_lines = vt;
1275      } else {
1276        virt_text = vt;
1277      }
1278      vt = vt->next;
1279    }
1280
1281    uint32_t idx = decor.data.ext.sh_idx;
1282    while (idx != DECOR_ID_INVALID) {
1283      DecorSignHighlight *sh = &kv_A(decor_items, idx);
1284      if (sh->flags & kSHIsSign) {
1285        sh_sign = *sh;
1286      } else {
1287        sh_hl = *sh;
1288      }
1289      idx = sh->next;
1290    }
1291  } else {
1292    sh_hl = decor_sh_from_inline(decor.data.hl);
1293  }
1294
1295  if (sh_hl.hl_id) {
1296    PUT_C(*dict, "hl_group", hl_group_name(sh_hl.hl_id, hl_name));
1297    PUT_C(*dict, "hl_eol", BOOLEAN_OBJ(sh_hl.flags & kSHHlEol));
1298    priority = sh_hl.priority;
1299  }
1300
1301  if (sh_hl.flags & kSHConcealOff) {
1302    PUT_C(*dict, "conceal", BOOLEAN_OBJ(false));
1303  } else if (sh_hl.flags & kSHConceal) {
1304    char buf[MAX_SCHAR_SIZE];
1305    schar_get(buf, sh_hl.text[0]);
1306    PUT_C(*dict, "conceal", CSTR_TO_ARENA_OBJ(arena, buf));
1307  }
1308
1309  if (sh_hl.flags & kSHConcealLines) {
1310    PUT_C(*dict, "conceal_lines", STRING_OBJ(cstr_as_string("")));
1311  }
1312
1313  if (sh_hl.flags & kSHSpellOn) {
1314    PUT_C(*dict, "spell", BOOLEAN_OBJ(true));
1315  } else if (sh_hl.flags & kSHSpellOff) {
1316    PUT_C(*dict, "spell", BOOLEAN_OBJ(false));
1317  }
1318
1319  if (sh_hl.flags & kSHUIWatched) {
1320    PUT_C(*dict, "ui_watched", BOOLEAN_OBJ(true));
1321  }
1322
1323  if (sh_hl.url != NULL) {
1324    PUT_C(*dict, "url", STRING_OBJ(cstr_as_string(sh_hl.url)));
1325  }
1326
1327  if (virt_text) {
1328    if (virt_text->hl_mode) {
1329      PUT_C(*dict, "hl_mode", CSTR_AS_OBJ(hl_mode_str[virt_text->hl_mode]));
1330    }
1331
1332    Array chunks = virt_text_to_array(virt_text->data.virt_text, hl_name, arena);
1333    PUT_C(*dict, "virt_text", ARRAY_OBJ(chunks));
1334    PUT_C(*dict, "virt_text_hide", BOOLEAN_OBJ(virt_text->flags & kVTHide));
1335    PUT_C(*dict, "virt_text_repeat_linebreak", BOOLEAN_OBJ(virt_text->flags & kVTRepeatLinebreak));
1336    if (virt_text->pos == kVPosWinCol) {
1337      PUT_C(*dict, "virt_text_win_col", INTEGER_OBJ(virt_text->col));
1338    }
1339    PUT_C(*dict, "virt_text_pos", CSTR_AS_OBJ(virt_text_pos_str[virt_text->pos]));
1340    priority = virt_text->priority;
1341  }
1342
1343  if (virt_lines) {
1344    Array all_chunks = arena_array(arena, kv_size(virt_lines->data.virt_lines));
1345    int virt_lines_flags = 0;
1346    VirtLineOverflow virt_lines_overflow = kVLOverflowTrunc;
1347    for (size_t i = 0; i < kv_size(virt_lines->data.virt_lines); i++) {
1348      virt_lines_flags = kv_A(virt_lines->data.virt_lines, i).flags;
1349      virt_lines_overflow = kv_A(virt_lines->data.virt_lines, i).overflow;
1350      Array chunks = virt_text_to_array(kv_A(virt_lines->data.virt_lines, i).line, hl_name, arena);
1351      ADD(all_chunks, ARRAY_OBJ(chunks));
1352    }
1353    PUT_C(*dict, "virt_lines", ARRAY_OBJ(all_chunks));
1354    PUT_C(*dict, "virt_lines_above", BOOLEAN_OBJ(virt_lines->flags & kVTLinesAbove));
1355    PUT_C(*dict, "virt_lines_leftcol", BOOLEAN_OBJ(virt_lines_flags & kVLLeftcol));
1356
1357    char *overflow = "trunc";
1358    if (virt_lines_overflow == kVLOverflowScroll) {
1359      overflow = "scroll";
1360    } else if (virt_lines_overflow == kVLOverflowWrap) {
1361      overflow = "wrap";
1362    } else if (virt_lines_overflow == kVLOverflowAuto) {
1363      overflow = "auto";
1364    }
1365
1366    PUT_C(*dict, "virt_lines_overflow", CSTR_AS_OBJ(overflow));
1367    priority = virt_lines->priority;
1368  }
1369
1370  if (sh_sign.flags & kSHIsSign) {
1371    if (sh_sign.text[0]) {
1372      char buf[SIGN_WIDTH * MAX_SCHAR_SIZE];
1373      describe_sign_text(buf, sh_sign.text);
1374      PUT_C(*dict, "sign_text", CSTR_TO_ARENA_OBJ(arena, buf));
1375    }
1376
1377    if (sh_sign.sign_name) {
1378      PUT_C(*dict, "sign_name", CSTR_AS_OBJ(sh_sign.sign_name));
1379    }
1380
1381    // uncrustify:off
1382
1383    struct { char *name; const int val; } hls[] = {
1384      { "sign_hl_group"      , sh_sign.hl_id            },
1385      { "number_hl_group"    , sh_sign.number_hl_id     },
1386      { "line_hl_group"      , sh_sign.line_hl_id       },
1387      { "cursorline_hl_group", sh_sign.cursorline_hl_id },
1388      { NULL, 0 },
1389    };
1390
1391    // uncrustify:on
1392
1393    for (int j = 0; hls[j].name; j++) {
1394      if (hls[j].val) {
1395        PUT_C(*dict, hls[j].name, hl_group_name(hls[j].val, hl_name));
1396      }
1397    }
1398    priority = sh_sign.priority;
1399  }
1400
1401  if (priority != -1) {
1402    PUT_C(*dict, "priority", INTEGER_OBJ(priority));
1403  }
1404}
1405
1406uint16_t decor_type_flags(DecorInline decor)
1407{
1408  if (decor.ext) {
1409    uint16_t type_flags = kExtmarkNone;
1410    DecorVirtText *vt = decor.data.ext.vt;
1411    while (vt) {
1412      type_flags |= (vt->flags & kVTIsLines) ? kExtmarkVirtLines : kExtmarkVirtText;
1413      vt = vt->next;
1414    }
1415    uint32_t idx = decor.data.ext.sh_idx;
1416    while (idx != DECOR_ID_INVALID) {
1417      DecorSignHighlight *sh = &kv_A(decor_items, idx);
1418      type_flags |= (sh->flags & kSHIsSign) ? kExtmarkSign : kExtmarkHighlight;
1419      idx = sh->next;
1420    }
1421    return type_flags;
1422  } else {
1423    return (decor.data.hl.flags & kSHIsSign) ? kExtmarkSign : kExtmarkHighlight;
1424  }
1425}
1426
1427Object hl_group_name(int hl_id, bool hl_name)
1428{
1429  if (hl_name) {
1430    return CSTR_AS_OBJ(syn_id2name(hl_id));
1431  } else {
1432    return INTEGER_OBJ(hl_id);
1433  }
1434}