robin/laufey

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

robinmerge: 9a29622b3b00ddb601

master
38.9 KiB1346 linesraw
1// highlight.c: low level code for UI and syntax highlighting
2
3#include <assert.h>
4#include <inttypes.h>
5#include <lauxlib.h>
6#include <string.h>
7
8#include "nvim/api/keysets_defs.h"
9#include "nvim/api/private/defs.h"
10#include "nvim/api/private/dispatch.h"
11#include "nvim/api/private/helpers.h"
12#include "nvim/api/private/validate.h"
13#include "nvim/api/ui.h"
14#include "nvim/decoration_defs.h"
15#include "nvim/decoration_provider.h"
16#include "nvim/drawscreen.h"
17#include "nvim/gettext_defs.h"
18#include "nvim/globals.h"
19#include "nvim/highlight.h"
20#include "nvim/highlight_defs.h"
21#include "nvim/highlight_group.h"
22#include "nvim/lua/executor.h"
23#include "nvim/macros_defs.h"
24#include "nvim/map_defs.h"
25#include "nvim/memory.h"
26#include "nvim/memory_defs.h"
27#include "nvim/message.h"
28#include "nvim/option.h"
29#include "nvim/popupmenu.h"
30#include "nvim/strings.h"
31#include "nvim/types_defs.h"
32#include "nvim/ui.h"
33#include "nvim/vim_defs.h"
34
35#include "highlight.c.generated.h"
36
37static bool hlstate_active = false;
38
39static Set(HlEntry) attr_entries = SET_INIT;
40static Map(uint64_t, int) combine_attr_entries = MAP_INIT;
41static Map(uint64_t, int) blend_attr_entries = MAP_INIT;
42static Map(uint64_t, int) blendthrough_attr_entries = MAP_INIT;
43static Set(cstr_t) urls = SET_INIT;
44/// Interned font names, referenced by index in HlAttrs.font.
45static Set(cstr_t) fonts = SET_INIT;
46
47#define attr_entry(i) attr_entries.keys[i]
48
49/// highlight entries private to a namespace
50static Map(ColorKey, ColorItem) ns_hls;
51typedef int NSHlAttr[HLF_COUNT];
52static PMap(int) ns_hl_attr;
53
54void highlight_init(void)
55{
56  // index 0 is no attribute, add dummy entry:
57  set_put(HlEntry, &attr_entries, ((HlEntry){ .attr = HLATTRS_INIT, .kind = kHlInvalid,
58                                              .id1 = 0, .id2 = 0 }));
59}
60
61/// @return true if hl table was reset
62bool highlight_use_hlstate(void)
63{
64  if (hlstate_active) {
65    return false;
66  }
67  hlstate_active = true;
68  // hl tables must now be rebuilt.
69  clear_hl_tables(true);
70  return true;
71}
72
73/// Return the attr number for a set of colors and font, and optionally
74/// a semantic description (see ext_hlstate documentation).
75/// Add a new entry to the attr_entries array if the combination is new.
76/// @return 0 for error.
77static int get_attr_entry(HlEntry entry)
78{
79  bool retried = false;
80  if (!hlstate_active) {
81    // This information will not be used, erase it and reduce the table size.
82    entry.kind = kHlUnknown;
83    entry.id1 = 0;
84    entry.id2 = 0;
85  }
86
87retry: {}
88  MHPutStatus status;
89  uint32_t k = set_put_idx(HlEntry, &attr_entries, entry, &status);
90  if (status == kMHExisting) {
91    return (int)k;
92  }
93
94  static bool recursive = false;
95  if (set_size(&attr_entries) > MAX_TYPENR) {
96    // Running out of attribute entries!  remove all attributes, and
97    // compute new ones for all groups.
98    // When called recursively, we are really out of numbers.
99    if (recursive || retried) {
100      emsg(_("E424: Too many different highlighting attributes in use"));
101      return 0;
102    }
103    recursive = true;
104
105    clear_hl_tables(true);
106
107    recursive = false;
108    if (entry.kind == kHlCombine) {
109      // This entry is now invalid, don't put it
110      return 0;
111    }
112    retried = true;
113    goto retry;
114  }
115
116  // new attr id, send event to remote ui:s
117  int id = (int)k;
118
119  Arena arena = ARENA_EMPTY;
120  Array inspect = hl_inspect(id, &arena);
121
122  // Note: internally we don't distinguish between cterm and rgb attributes,
123  // remote_ui_hl_attr_define will however.
124  ui_call_hl_attr_define(id, entry.attr, entry.attr, inspect);
125  arena_mem_free(arena_finish(&arena));
126  return id;
127}
128
129/// When a UI connects, we need to send it the table of highlights used so far.
130void ui_send_all_hls(RemoteUI *ui)
131{
132  for (size_t i = 1; i < set_size(&attr_entries); i++) {
133    Arena arena = ARENA_EMPTY;
134    Array inspect = hl_inspect((int)i, &arena);
135    HlAttrs attr = attr_entry(i).attr;
136    remote_ui_hl_attr_define(ui, (Integer)i, attr, attr, inspect);
137    arena_mem_free(arena_finish(&arena));
138  }
139  for (size_t hlf = 0; hlf < HLF_COUNT; hlf++) {
140    remote_ui_hl_group_set(ui, cstr_as_string(hlf_names[hlf]),
141                           highlight_attr[hlf]);
142  }
143}
144
145/// Get attribute code for a syntax group.
146int hl_get_syn_attr(int ns_id, int idx, HlAttrs at_en)
147{
148  // TODO(bfredl): should we do this unconditionally
149  if (at_en.cterm_fg_color != 0 || at_en.cterm_bg_color != 0
150      || at_en.rgb_fg_color != -1 || at_en.rgb_bg_color != -1
151      || at_en.rgb_sp_color != -1 || at_en.cterm_ae_attr != 0
152      || at_en.rgb_ae_attr != 0 || at_en.font >= 0 || ns_id != 0) {
153    return get_attr_entry((HlEntry){ .attr = at_en, .kind = kHlSyntax,
154                                     .id1 = idx, .id2 = ns_id });
155  }
156  // If all the fields are cleared, clear the attr field back to default value
157  return 0;
158}
159
160void ns_hl_def(NS ns_id, int hl_id, HlAttrs attrs, int link_id, Dict(highlight) *dict)
161{
162  if (ns_id == 0) {
163    assert(dict);
164    // set in global (':highlight') namespace
165    set_hl_group(hl_id, attrs, dict, link_id);
166    return;
167  }
168  if ((attrs.rgb_ae_attr & HL_DEFAULT)
169      && map_has(ColorKey, &ns_hls, (ColorKey(ns_id, hl_id)))) {
170    return;
171  }
172  DecorProvider *p = get_decor_provider(ns_id, true);
173  int attr_id = link_id > 0 ? -1 : hl_get_syn_attr(ns_id, hl_id, attrs);
174  ColorItem it = { .attr_id = attr_id,
175                   .link_id = link_id,
176                   .version = p->hl_valid,
177                   .is_default = (attrs.rgb_ae_attr & HL_DEFAULT),
178                   .link_global = (attrs.rgb_ae_attr & HL_GLOBAL) };
179  map_put(ColorKey, ColorItem)(&ns_hls, ColorKey(ns_id, hl_id), it);
180  p->hl_cached = false;
181}
182
183int ns_get_hl(NS *ns_hl, int hl_id, bool link, bool nodefault)
184{
185  static int recursive = 0;
186
187  if (*ns_hl == 0) {
188    // ns=0 (the default namespace) does not have a provider so stop here
189    return -1;
190  }
191
192  if (*ns_hl < 0) {
193    if (ns_hl_active <= 0) {
194      return -1;
195    }
196    *ns_hl = ns_hl_active;
197  }
198
199  int ns_id = *ns_hl;
200
201  DecorProvider *p = get_decor_provider(ns_id, true);
202  ColorItem it = map_get(ColorKey, ColorItem)(&ns_hls, ColorKey(ns_id, hl_id));
203  // TODO(bfredl): map_ref true even this?
204  bool valid_item = it.version >= p->hl_valid;
205
206  if (!valid_item && p->hl_def != LUA_NOREF && !recursive) {
207    MAXSIZE_TEMP_ARRAY(args, 3);
208    ADD_C(args, INTEGER_OBJ((Integer)ns_id));
209    ADD_C(args, CSTR_AS_OBJ(syn_id2name(hl_id)));
210    ADD_C(args, BOOLEAN_OBJ(link));
211    // TODO(bfredl): preload the "global" attr dict?
212
213    Error err = ERROR_INIT;
214    recursive++;
215    Object ret = nlua_call_ref(p->hl_def, "hl_def", args, kRetObject, NULL, &err);
216    recursive--;
217
218    // TODO(bfredl): or "inherit", combine with global value?
219    bool fallback = true;
220    bool tmp = false;
221    HlAttrs attrs = HLATTRS_INIT;
222    if (ret.type == kObjectTypeDict) {
223      fallback = false;
224      Dict(highlight) dict = KEYDICT_INIT;
225      if (api_dict_to_keydict(&dict, KeyDict_highlight_get_field, ret.data.dict, &err)) {
226        attrs = dict2hlattrs(&dict, true, &it.link_id, NULL, &err);
227        fallback = GET_BOOL_OR_TRUE(&dict, highlight, fallback);
228        tmp = dict.fallback;  // or false
229        if (it.link_id >= 0) {
230          fallback = true;
231        }
232      }
233    }
234
235    it.attr_id = fallback ? -1 : hl_get_syn_attr(ns_id, hl_id, attrs);
236    it.version = p->hl_valid - (int)tmp;
237    it.is_default = attrs.rgb_ae_attr & HL_DEFAULT;
238    it.link_global = attrs.rgb_ae_attr & HL_GLOBAL;
239    map_put(ColorKey, ColorItem)(&ns_hls, ColorKey(ns_id, hl_id), it);
240    valid_item = true;
241  }
242
243  if ((it.is_default && nodefault) || !valid_item) {
244    return -1;
245  }
246
247  if (link) {
248    if (it.attr_id >= 0) {
249      return 0;
250    }
251    if (it.link_global) {
252      *ns_hl = 0;
253    }
254    return it.link_id;
255  } else {
256    return it.attr_id;
257  }
258}
259
260bool hl_check_ns(void)
261{
262  int ns = 0;
263  if (ns_hl_fast > 0) {
264    ns = ns_hl_fast;
265  } else if (ns_hl_win >= 0) {
266    ns = ns_hl_win;
267  } else {
268    ns = ns_hl_global;
269  }
270  if (ns_hl_active == ns) {
271    return false;
272  }
273
274  ns_hl_active = ns;
275  hl_attr_active = highlight_attr;
276  if (ns > 0) {
277    update_ns_hl(ns);
278    NSHlAttr *hl_def = (NSHlAttr *)pmap_get(int)(&ns_hl_attr, ns);
279    if (hl_def) {
280      hl_attr_active = *hl_def;
281    }
282  }
283  return true;
284}
285
286/// prepare for drawing window `wp` or global elements if NULL
287///
288/// Note: pum should be drawn in the context of the current window!
289bool win_check_ns_hl(win_T *wp)
290{
291  ns_hl_win = wp ? wp->w_ns_hl : -1;
292  return hl_check_ns();
293}
294
295/// Get highlight attributes for a highlight group
296///
297/// @param ns_id Namespace ID (0 for global namespace)
298/// @param hl_id Highlight group ID (1-based)
299/// @param[in] optional If non-NULL, passed to syn_ns_id2attr to track
300///                      whether the group was explicitly defined in the namespace.
301/// @param[out] attrs Pointer to store the attributes
302/// @return true if highlight group exists and has valid attributes
303bool hl_ns_get_attrs(int ns_id, int hl_id, bool *optional, HlAttrs *attrs)
304{
305  bool opt = optional ? *optional : true;
306  int syn_attr = syn_ns_id2attr(ns_id, hl_id, &opt);
307  if (optional) {
308    *optional = opt;
309  }
310  if (syn_attr <= 0) {
311    return false;
312  }
313  *attrs = syn_attr2entry(syn_attr);
314  return true;
315}
316
317/// Get attribute code for a builtin highlight group.
318///
319/// The final syntax group could be modified by hi-link or 'winhighlight'.
320int hl_get_ui_attr(int ns_id, int idx, int final_id, bool optional)
321{
322  HlAttrs attrs = HLATTRS_INIT;
323  bool available = false;
324
325  if (final_id > 0) {
326    available = hl_ns_get_attrs(ns_id, final_id, &optional, &attrs);
327  }
328
329  if (HLF_PNI <= idx && idx <= HLF_PST) {
330    if (attrs.hl_blend == -1 && p_pb > 0) {
331      attrs.hl_blend = (int)p_pb;
332    }
333    if (pum_drawn()) {
334      must_redraw_pum = true;
335    }
336  }
337
338  if (optional && !available) {
339    return 0;
340  }
341  return get_attr_entry((HlEntry){ .attr = attrs, .kind = kHlUI,
342                                   .id1 = idx, .id2 = final_id });
343}
344
345/// Apply 'winblend' to highlight attributes.
346///
347/// @param winbl The 'winblend' value.
348/// @param attr  The original attribute code.
349///
350/// @return      The attribute code with 'winblend' applied.
351int hl_apply_winblend(int winbl, int attr)
352{
353  HlEntry entry = attr_entry(attr);
354  // if blend= attribute is not set, 'winblend' value overrides it.
355  if (entry.attr.hl_blend == -1 && winbl > 0) {
356    entry.attr.hl_blend = winbl;
357    attr = get_attr_entry(entry);
358  }
359  return attr;
360}
361
362void update_window_hl(win_T *wp, bool invalid)
363{
364  int ns_id = wp->w_ns_hl;
365
366  update_ns_hl(ns_id);
367  if (ns_id != wp->w_ns_hl_active) {
368    wp->w_ns_hl_active = ns_id;
369
370    NSHlAttr *hl_def_ptr = (NSHlAttr *)pmap_get(int)(&ns_hl_attr, ns_id);
371    if (hl_def_ptr) {
372      wp->w_ns_hl_attr = *hl_def_ptr;
373    } else {
374      // No specific highlights, use the defaults.
375      wp->w_ns_hl_attr = NULL;
376    }
377  }
378
379  int *hl_def = wp->w_ns_hl_attr ? wp->w_ns_hl_attr : hl_attr_active;
380
381  if (!wp->w_hl_needs_update && !invalid) {
382    return;
383  }
384  wp->w_hl_needs_update = false;
385
386  // If a floating window is blending it always have a named
387  // wp->w_hl_attr_normal group. HL_ATTR(HLF_NFLOAT) is always named.
388
389  // determine window specific background set in 'winhighlight'
390  bool float_win = wp->w_floating && !wp->w_config.external;
391  if (float_win && hl_def[HLF_NFLOAT] != 0 && ns_id > 0) {
392    wp->w_hl_attr_normal = hl_def[HLF_NFLOAT];
393  } else if (hl_def[HLF_NONE] > 0) {
394    wp->w_hl_attr_normal = hl_def[HLF_NONE];
395  } else if (float_win) {
396    wp->w_hl_attr_normal = HL_ATTR(HLF_NFLOAT) > 0
397                           ? HL_ATTR(HLF_NFLOAT) : highlight_attr[HLF_NFLOAT];
398  } else {
399    wp->w_hl_attr_normal = 0;
400  }
401
402  if (wp->w_floating) {
403    wp->w_hl_attr_normal = hl_apply_winblend((int)wp->w_p_winbl, wp->w_hl_attr_normal);
404  }
405
406  wp->w_config.shadow = false;
407  if (wp->w_floating && wp->w_config.border) {
408    for (int i = 0; i < 8; i++) {
409      int attr = hl_def[HLF_BORDER];
410      if (wp->w_config.border_hl_ids[i]) {
411        attr = hl_get_ui_attr(ns_id, HLF_BORDER,
412                              wp->w_config.border_hl_ids[i], false);
413      }
414      attr = hl_apply_winblend((int)wp->w_p_winbl, attr);
415      if (syn_attr2entry(attr).hl_blend > 0) {
416        wp->w_config.shadow = true;
417      }
418      wp->w_config.border_attr[i] = attr;
419    }
420  }
421
422  // shadow might cause blending
423  check_blending(wp);
424
425  // TODO(bfredl): this a bit ad-hoc. move it from highlight ns logic to 'winhl'
426  // implementation?
427  if (hl_def[HLF_INACTIVE] == 0) {
428    wp->w_hl_attr_normalnc = hl_combine_attr(HL_ATTR(HLF_INACTIVE),
429                                             wp->w_hl_attr_normal);
430  } else {
431    wp->w_hl_attr_normalnc = hl_def[HLF_INACTIVE];
432  }
433
434  if (wp->w_floating) {
435    wp->w_hl_attr_normalnc = hl_apply_winblend((int)wp->w_p_winbl, wp->w_hl_attr_normalnc);
436  }
437}
438
439void update_ns_hl(int ns_id)
440{
441  if (ns_id <= 0) {
442    return;
443  }
444  DecorProvider *p = get_decor_provider(ns_id, true);
445  if (p->hl_cached) {
446    return;
447  }
448
449  NSHlAttr **alloc = (NSHlAttr **)pmap_put_ref(int)(&ns_hl_attr, ns_id, NULL, NULL);
450  if (*alloc == NULL) {
451    *alloc = xmalloc(sizeof(**alloc));
452  }
453  int *hl_attrs = **alloc;
454
455  for (int hlf = 1; hlf < HLF_COUNT; hlf++) {
456    int id = syn_check_group(hlf_names[hlf], strlen(hlf_names[hlf]));
457    bool optional = (hlf == HLF_INACTIVE || hlf == HLF_NFLOAT);
458    hl_attrs[hlf] = hl_get_ui_attr(ns_id, hlf, id, optional);
459  }
460
461  // NOOOO! You cannot just pretend that "Normal" is just like any other
462  // syntax group! It needs at least 10 layers of special casing! Noooooo!
463  //
464  // haha, tema engine go brrr
465  int normality = syn_check_group(S_LEN("Normal"));
466  hl_attrs[HLF_NONE] = hl_get_ui_attr(ns_id, -1, normality, true);
467
468  // hl_get_ui_attr might have invalidated the decor provider
469  p = get_decor_provider(ns_id, true);
470  p->hl_cached = true;
471}
472
473int win_bg_attr(win_T *wp)
474{
475  if (ns_hl_fast < 0) {
476    int local = (wp == curwin) ? wp->w_hl_attr_normal : wp->w_hl_attr_normalnc;
477    if (local) {
478      return local;
479    }
480  }
481
482  if (wp == curwin || hl_attr_active[HLF_INACTIVE] == 0) {
483    return hl_attr_active[HLF_NONE];
484  } else {
485    return hl_attr_active[HLF_INACTIVE];
486  }
487}
488
489/// Gets HL_UNDERLINE highlight.
490int hl_get_underline(void)
491{
492  HlAttrs attrs = HLATTRS_INIT;
493  attrs.cterm_ae_attr = (int16_t)HL_UNDERLINE;
494  attrs.rgb_ae_attr = (int16_t)HL_UNDERLINE;
495  return get_attr_entry((HlEntry){
496    .attr = attrs,
497    .kind = kHlUI,
498    .id1 = 0,
499    .id2 = 0,
500  });
501}
502
503/// Augment an existing attribute with a URL.
504///
505/// @param attr Existing attribute to combine with
506/// @param url The URL to associate with the highlight attribute
507/// @return Combined attribute
508int hl_add_url(int attr, const char *url)
509{
510  HlAttrs attrs = HLATTRS_INIT;
511
512  MHPutStatus status;
513  uint32_t k = set_put_idx(cstr_t, &urls, url, &status);
514  if (status != kMHExisting) {
515    urls.keys[k] = xstrdup(url);
516  }
517
518  attrs.url = (int32_t)k;
519
520  int new = get_attr_entry((HlEntry){
521    .attr = attrs,
522    .kind = kHlUI,
523    .id1 = 0,
524    .id2 = 0,
525  });
526
527  return hl_combine_attr(attr, new);
528}
529
530/// Get a URL by its index.
531///
532/// @param index URL index
533/// @return URL
534const char *hl_get_url(uint32_t index)
535{
536  assert(urls.keys);
537  return urls.keys[index];
538}
539
540// Intern a font name and return its stable index for use in HlAttrs.font.
541///
542/// @param font_name The font name to add
543/// @return Font index, or -1 if font_name is NULL or empty
544int32_t hl_add_font_idx(const char *font_name)
545{
546  if (font_name == NULL || *font_name == '\0') {
547    return -1;
548  }
549
550  MHPutStatus status;
551  uint32_t k = set_put_idx(cstr_t, &fonts, font_name, &status);
552  if (status != kMHExisting) {
553    fonts.keys[k] = xstrdup(font_name);
554  }
555
556  return (int32_t)k;
557}
558
559/// Get a font name by its index.
560///
561/// @param index Font index
562/// @return Font name, or NULL if index is invalid
563const char *hl_get_font(int32_t index)
564{
565  if (index < 0 || !fonts.keys) {
566    return NULL;
567  }
568  return fonts.keys[index];
569}
570
571/// Get attribute code for forwarded :terminal highlights.
572int hl_get_term_attr(HlAttrs *aep)
573{
574  return get_attr_entry((HlEntry){ .attr = *aep, .kind = kHlTerminal,
575                                   .id1 = 0, .id2 = 0 });
576}
577
578/// Clear all highlight tables.
579void clear_hl_tables(bool reinit)
580{
581  const char *url = NULL;
582  set_foreach(&urls, url, {
583    xfree((void *)url);
584  });
585
586  if (reinit) {
587    set_clear(HlEntry, &attr_entries);
588    highlight_init();
589    map_clear(uint64_t, &combine_attr_entries);
590    map_clear(uint64_t, &blend_attr_entries);
591    map_clear(uint64_t, &blendthrough_attr_entries);
592    set_clear(cstr_t, &urls);
593    memset(highlight_attr_last, -1, sizeof(highlight_attr_last));
594    highlight_attr_set_all();
595    highlight_changed();
596    screen_invalidate_highlights();
597  } else {
598    const char *font = NULL;
599    set_foreach(&fonts, font, {
600      xfree((void *)font);
601    });
602    set_destroy(HlEntry, &attr_entries);
603    map_destroy(uint64_t, &combine_attr_entries);
604    map_destroy(uint64_t, &blend_attr_entries);
605    map_destroy(uint64_t, &blendthrough_attr_entries);
606    map_destroy(ColorKey, &ns_hls);
607    set_destroy(cstr_t, &urls);
608    set_destroy(cstr_t, &fonts);
609  }
610}
611
612void hl_invalidate_blends(void)
613{
614  map_clear(uint64_t, &blend_attr_entries);
615  map_clear(uint64_t, &blendthrough_attr_entries);
616  highlight_changed();
617  update_window_hl(curwin, true);
618}
619
620/// Combine HlAttrFlags.
621/// The underline attribute in "prim_ae" overrules the one in "char_ae" if both are present.
622static int32_t hl_combine_ae(int32_t char_ae, int32_t prim_ae)
623{
624  int32_t char_ul = char_ae & HL_UNDERLINE_MASK;
625  int32_t prim_ul = prim_ae & HL_UNDERLINE_MASK;
626  int32_t new_ul = prim_ul ? prim_ul : char_ul;
627  return (char_ae & ~HL_UNDERLINE_MASK) | (prim_ae & ~HL_UNDERLINE_MASK) | new_ul;
628}
629
630// Combine special attributes (e.g., for spelling) with other attributes
631// (e.g., for syntax highlighting).
632// "prim_attr" overrules "char_attr".
633// This creates a new group when required.
634// Since we expect there to be a lot of spelling mistakes we cache the result.
635// Return the resulting attributes.
636int hl_combine_attr(int char_attr, int prim_attr)
637{
638  if (char_attr == 0) {
639    return prim_attr;
640  } else if (prim_attr == 0) {
641    return char_attr;
642  }
643
644  uint64_t combine_tag = HlAttrKey(char_attr, prim_attr);
645  int id = map_get(uint64_t, int)(&combine_attr_entries, combine_tag);
646  if (id > 0) {
647    return id;
648  }
649
650  HlAttrs char_aep = syn_attr2entry(char_attr);
651  HlAttrs prim_aep = syn_attr2entry(prim_attr);
652
653  // start with low-priority attribute, and override colors if present below.
654  HlAttrs new_en = char_aep;
655
656  if (prim_aep.cterm_ae_attr & HL_NOCOMBINE) {
657    new_en.cterm_ae_attr = prim_aep.cterm_ae_attr;
658  } else {
659    new_en.cterm_ae_attr = hl_combine_ae(new_en.cterm_ae_attr, prim_aep.cterm_ae_attr);
660  }
661  if (prim_aep.rgb_ae_attr & HL_NOCOMBINE) {
662    new_en.rgb_ae_attr = prim_aep.rgb_ae_attr;
663  } else {
664    new_en.rgb_ae_attr = hl_combine_ae(new_en.rgb_ae_attr, prim_aep.rgb_ae_attr);
665  }
666
667  if (prim_aep.cterm_fg_color > 0) {
668    new_en.cterm_fg_color = prim_aep.cterm_fg_color;
669    new_en.rgb_ae_attr &= ((~HL_FG_INDEXED)
670                           | (prim_aep.rgb_ae_attr & HL_FG_INDEXED));
671  }
672
673  if (prim_aep.cterm_bg_color > 0) {
674    new_en.cterm_bg_color = prim_aep.cterm_bg_color;
675    new_en.rgb_ae_attr &= ((~HL_BG_INDEXED)
676                           | (prim_aep.rgb_ae_attr & HL_BG_INDEXED));
677  }
678
679  if (prim_aep.rgb_fg_color >= 0) {
680    new_en.rgb_fg_color = prim_aep.rgb_fg_color;
681    new_en.rgb_ae_attr &= ((~HL_FG_INDEXED)
682                           | (prim_aep.rgb_ae_attr & HL_FG_INDEXED));
683  }
684
685  if (prim_aep.rgb_bg_color >= 0) {
686    new_en.rgb_bg_color = prim_aep.rgb_bg_color;
687    new_en.rgb_ae_attr &= ((~HL_BG_INDEXED)
688                           | (prim_aep.rgb_ae_attr & HL_BG_INDEXED));
689  }
690
691  if (prim_aep.rgb_sp_color >= 0) {
692    new_en.rgb_sp_color = prim_aep.rgb_sp_color;
693  }
694
695  if (prim_aep.hl_blend >= 0) {
696    new_en.hl_blend = prim_aep.hl_blend;
697  }
698
699  if ((new_en.url == -1) && (prim_aep.url >= 0)) {
700    new_en.url = prim_aep.url;
701  }
702
703  if (prim_aep.font >= 0) {
704    new_en.font = prim_aep.font;
705  }
706
707  id = get_attr_entry((HlEntry){ .attr = new_en, .kind = kHlCombine,
708                                 .id1 = char_attr, .id2 = prim_attr });
709  if (id > 0) {
710    map_put(uint64_t, int)(&combine_attr_entries, combine_tag, id);
711  }
712
713  return id;
714}
715
716/// Get the used rgb colors for an attr group.
717///
718/// If colors are unset, use builtin default colors. Never returns -1
719/// Cterm colors are unchanged.
720static HlAttrs get_colors_force(HlAttrs attrs)
721{
722  if (attrs.rgb_bg_color == -1) {
723    attrs.rgb_bg_color = normal_bg;
724  }
725  if (attrs.rgb_fg_color == -1) {
726    attrs.rgb_fg_color = normal_fg;
727  }
728  if (attrs.rgb_sp_color == -1) {
729    attrs.rgb_sp_color = normal_sp;
730  }
731  HL_SET_DEFAULT_COLORS(attrs.rgb_fg_color, attrs.rgb_bg_color,
732                        attrs.rgb_sp_color);
733
734  if (attrs.rgb_ae_attr & HL_INVERSE) {
735    int temp = attrs.rgb_bg_color;
736    attrs.rgb_bg_color = attrs.rgb_fg_color;
737    attrs.rgb_fg_color = temp;
738    attrs.rgb_ae_attr &= ~HL_INVERSE;
739  }
740
741  return attrs;
742}
743
744/// Blend overlay attributes (for popupmenu) with other attributes
745///
746/// This creates a new group when required.
747/// This is called per-cell, so cache the result.
748///
749/// @return the resulting attributes.
750int hl_blend_attrs(int back_attr, int front_attr, bool *through)
751{
752  // Cannot blend uninitialized cells, use front_attr for uninitialized background cells.
753  if (front_attr < 0 || back_attr < 0) {
754    return front_attr;
755  }
756
757  HlAttrs fattrs_raw = syn_attr2entry(front_attr);
758  HlAttrs fattrs = get_colors_force(fattrs_raw);
759  int ratio = fattrs.hl_blend;
760  if (ratio <= 0) {
761    *through = false;
762    return front_attr;
763  }
764
765  uint64_t combine_tag = HlAttrKey(back_attr, front_attr);
766  Map(uint64_t, int) *map = (*through
767                             ? &blendthrough_attr_entries
768                             : &blend_attr_entries);
769  int id = map_get(uint64_t, int)(map, combine_tag);
770  if (id > 0) {
771    return id;
772  }
773
774  HlAttrs battrs_raw = syn_attr2entry(back_attr);
775  HlAttrs battrs = get_colors_force(battrs_raw);
776  HlAttrs cattrs;
777
778  if (*through) {
779    cattrs = battrs;
780    cattrs.rgb_fg_color = rgb_blend(ratio, battrs.rgb_fg_color, fattrs.rgb_bg_color);
781    // Blend the special color only when the cell below sets one explicitly, else clear it.
782    if ((cattrs.rgb_ae_attr & HL_UNDERLINE_MASK) && battrs_raw.rgb_sp_color != -1) {
783      cattrs.rgb_sp_color = rgb_blend(ratio, battrs.rgb_sp_color, fattrs.rgb_bg_color);
784    } else {
785      cattrs.rgb_sp_color = -1;
786    }
787
788    cattrs.cterm_bg_color = fattrs.cterm_bg_color;
789    cattrs.cterm_fg_color = (int16_t)cterm_blend(ratio, battrs.cterm_fg_color,
790                                                 fattrs.cterm_bg_color);
791    cattrs.rgb_ae_attr &= ~(HL_FG_INDEXED | HL_BG_INDEXED);
792  } else {
793    cattrs = fattrs;
794    cattrs.rgb_fg_color = rgb_blend(ratio/2, battrs.rgb_fg_color, fattrs.rgb_fg_color);
795    if (cattrs.rgb_ae_attr & HL_UNDERLINE_MASK) {
796      cattrs.rgb_sp_color = rgb_blend(ratio/2, battrs.rgb_bg_color, fattrs.rgb_sp_color);
797    } else {
798      cattrs.rgb_sp_color = -1;
799    }
800
801    cattrs.rgb_ae_attr &= ~(HL_FG_INDEXED | HL_BG_INDEXED);
802  }
803
804  // Check if we should preserve background transparency
805  // Special case for blend=100: preserve back layer background exactly (including bg=NONE)
806  if (ratio == 100 && battrs_raw.rgb_bg_color == -1) {
807    // For 100% blend with transparent background, preserve the transparency
808    cattrs.rgb_bg_color = -1;
809  } else {
810    // Use the raw attributes (before forcing colors) to check original transparency
811    cattrs.rgb_bg_color = (battrs_raw.rgb_bg_color == -1) && (fattrs_raw.rgb_bg_color == -1)
812                          ? -1
813                          : rgb_blend(ratio, battrs.rgb_bg_color, fattrs.rgb_bg_color);
814  }
815  cattrs.hl_blend = -1;  // blend property was consumed
816  HlKind kind = *through ? kHlBlendThrough : kHlBlend;
817  id = get_attr_entry((HlEntry){ .attr = cattrs, .kind = kind,
818                                 .id1 = back_attr, .id2 = front_attr });
819  if (id > 0) {
820    map_put(uint64_t, int)(map, combine_tag, id);
821  }
822  return id;
823}
824
825static int rgb_blend(int ratio, int rgb1, int rgb2)
826{
827  int a = ratio;
828  int b = 100 - ratio;
829  int r1 = (rgb1 & 0xFF0000) >> 16;
830  int g1 = (rgb1 & 0x00FF00) >> 8;
831  int b1 = (rgb1 & 0x0000FF) >> 0;
832  int r2 = (rgb2 & 0xFF0000) >> 16;
833  int g2 = (rgb2 & 0x00FF00) >> 8;
834  int b2 = (rgb2 & 0x0000FF) >> 0;
835  int mr = (a * r1 + b * r2)/100;
836  int mg = (a * g1 + b * g2)/100;
837  int mb = (a * b1 + b * b2)/100;
838  return (mr << 16) + (mg << 8) + mb;
839}
840
841static int cterm_blend(int ratio, int16_t c1, int16_t c2)
842{
843  // 1. Convert cterm color numbers to RGB.
844  // 2. Blend the RGB colors.
845  // 3. Convert the RGB result to a cterm color.
846  int rgb1 = hl_cterm2rgb_color(c1);
847  int rgb2 = hl_cterm2rgb_color(c2);
848  int rgb_blended = rgb_blend(ratio, rgb1, rgb2);
849  return hl_rgb2cterm_color(rgb_blended);
850}
851
852/// Converts RGB color to 8-bit color (0-255).
853static int hl_rgb2cterm_color(int rgb)
854{
855  int r = (rgb & 0xFF0000) >> 16;
856  int g = (rgb & 0x00FF00) >> 8;
857  int b = (rgb & 0x0000FF) >> 0;
858
859  return (r * 6 / 256) * 36 + (g * 6 / 256) * 6 + (b * 6 / 256);
860}
861
862/// Converts 8-bit color (0-255) to RGB color.
863/// This is compatible with xterm.
864static int hl_cterm2rgb_color(int nr)
865{
866  static int cube_value[] = {
867    0x00, 0x5F, 0x87, 0xAF, 0xD7, 0xFF
868  };
869  static int grey_ramp[] = {
870    0x08, 0x12, 0x1C, 0x26, 0x30, 0x3A, 0x44, 0x4E, 0x58, 0x62, 0x6C, 0x76,
871    0x80, 0x8A, 0x94, 0x9E, 0xA8, 0xB2, 0xBC, 0xC6, 0xD0, 0xDA, 0xE4, 0xEE
872  };
873  static uint8_t ansi_table[16][4] = {
874    //  R    G    B   idx
875    {   0,   0,   0,  1 },  // black
876    { 224,   0,   0,  2 },  // dark red
877    {   0, 224,   0,  3 },  // dark green
878    { 224, 224,   0,  4 },  // dark yellow / brown
879    {   0,   0, 224,  5 },  // dark blue
880    { 224,   0, 224,  6 },  // dark magenta
881    {   0, 224, 224,  7 },  // dark cyan
882    { 224, 224, 224,  8 },  // light grey
883
884    { 128, 128, 128,  9 },  // dark grey
885    { 255,  64,  64, 10 },  // light red
886    {  64, 255,  64, 11 },  // light green
887    { 255, 255,  64, 12 },  // yellow
888    {  64,  64, 255, 13 },  // light blue
889    { 255,  64, 255, 14 },  // light magenta
890    {  64, 255, 255, 15 },  // light cyan
891    { 255, 255, 255, 16 },  // white
892  };
893
894  int r = 0;
895  int g = 0;
896  int b = 0;
897  int idx;
898  // *ansi_idx = 0;
899
900  if (nr < 16) {
901    r = ansi_table[nr][0];
902    g = ansi_table[nr][1];
903    b = ansi_table[nr][2];
904    // *ansi_idx = ansi_table[nr][3];
905  } else if (nr < 232) {  // 216 color-cube
906    idx = nr - 16;
907    r = cube_value[idx / 36 % 6];
908    g = cube_value[idx / 6  % 6];
909    b = cube_value[idx      % 6];
910    // *ansi_idx = -1;
911  } else if (nr < 256) {  // 24 greyscale ramp
912    idx = nr - 232;
913    r = grey_ramp[idx];
914    g = grey_ramp[idx];
915    b = grey_ramp[idx];
916    // *ansi_idx = -1;
917  }
918  return (r << 16) + (g << 8) + b;
919}
920
921/// Get highlight attributes for a attribute code
922HlAttrs syn_attr2entry(int attr)
923{
924  if (attr <= 0 || attr >= (int)set_size(&attr_entries)) {
925    // invalid attribute code, or the tables were cleared
926    return HLATTRS_INIT;
927  }
928  return attr_entry(attr).attr;
929}
930
931/// Gets highlight description for id `attr_id` as a map.
932Dict hl_get_attr_by_id(Integer attr_id, Boolean rgb, Arena *arena, Error *err)
933{
934  Dict dic = ARRAY_DICT_INIT;
935
936  if (attr_id == 0) {
937    return dic;
938  }
939
940  if (attr_id < 0 || attr_id >= (int)set_size(&attr_entries)) {
941    api_set_error(err, kErrorTypeException,
942                  "Invalid attribute id: %" PRId64, attr_id);
943    return dic;
944  }
945  Dict retval = arena_dict(arena, HLATTRS_DICT_SIZE);
946  hlattrs2dict(&retval, NULL, syn_attr2entry((int)attr_id), rgb, false);
947  return retval;
948}
949
950/// Converts an HlAttrs into Dict
951///
952/// @param[in/out] hl Dict with pre-allocated space for HLATTRS_DICT_SIZE elements
953/// @param[in] aep data to convert
954/// @param use_rgb use 'gui*' settings if true, else resorts to 'cterm*'
955/// @param short_keys change (foreground, background, special) to (fg, bg, sp) for 'gui*' settings
956///                          (foreground, background) to (ctermfg, ctermbg) for 'cterm*' settings
957void hlattrs2dict(Dict *hl, Dict *hl_attrs, HlAttrs ae, bool use_rgb, bool short_keys)
958{
959  hl_attrs = hl_attrs ? hl_attrs : hl;
960  assert(hl->capacity >= HLATTRS_DICT_SIZE);  // at most 24 items
961  assert(hl_attrs->capacity >= HLATTRS_DICT_SIZE);  // at most 24 items
962  int mask = use_rgb ? ae.rgb_ae_attr : ae.cterm_ae_attr;
963
964  if (mask & HL_INVERSE) {
965    PUT_C(*hl_attrs, "reverse", BOOLEAN_OBJ(true));
966  }
967
968  if (mask & HL_BOLD) {
969    PUT_C(*hl_attrs, "bold", BOOLEAN_OBJ(true));
970  }
971
972  if (mask & HL_ITALIC) {
973    PUT_C(*hl_attrs, "italic", BOOLEAN_OBJ(true));
974  }
975
976  switch (mask & HL_UNDERLINE_MASK) {
977  case HL_UNDERLINE:
978    PUT_C(*hl_attrs, "underline", BOOLEAN_OBJ(true));
979    break;
980
981  case HL_UNDERCURL:
982    PUT_C(*hl_attrs, "undercurl", BOOLEAN_OBJ(true));
983    break;
984
985  case HL_UNDERDOUBLE:
986    PUT_C(*hl_attrs, "underdouble", BOOLEAN_OBJ(true));
987    break;
988
989  case HL_UNDERDOTTED:
990    PUT_C(*hl_attrs, "underdotted", BOOLEAN_OBJ(true));
991    break;
992
993  case HL_UNDERDASHED:
994    PUT_C(*hl_attrs, "underdashed", BOOLEAN_OBJ(true));
995    break;
996  }
997
998  if (mask & HL_STANDOUT) {
999    PUT_C(*hl_attrs, "standout", BOOLEAN_OBJ(true));
1000  }
1001
1002  if (mask & HL_STRIKETHROUGH) {
1003    PUT_C(*hl_attrs, "strikethrough", BOOLEAN_OBJ(true));
1004  }
1005
1006  if (mask & HL_ALTFONT) {
1007    PUT_C(*hl_attrs, "altfont", BOOLEAN_OBJ(true));
1008  }
1009
1010  if (mask & HL_DIM) {
1011    PUT_C(*hl_attrs, "dim", BOOLEAN_OBJ(true));
1012  }
1013
1014  if (mask & HL_BLINK) {
1015    PUT_C(*hl_attrs, "blink", BOOLEAN_OBJ(true));
1016  }
1017
1018  if (mask & HL_CONCEALED) {
1019    PUT_C(*hl_attrs, "conceal", BOOLEAN_OBJ(true));
1020  }
1021
1022  if (mask & HL_OVERLINE) {
1023    PUT_C(*hl_attrs, "overline", BOOLEAN_OBJ(true));
1024  }
1025
1026  if (mask & HL_NOCOMBINE) {
1027    PUT_C(*hl_attrs, "nocombine", BOOLEAN_OBJ(true));
1028  }
1029
1030  if (use_rgb) {
1031    if (ae.rgb_fg_color != -1) {
1032      PUT_C(*hl, short_keys ? "fg" : "foreground", INTEGER_OBJ(ae.rgb_fg_color));
1033    }
1034
1035    if (ae.rgb_bg_color != -1) {
1036      PUT_C(*hl, short_keys ? "bg" : "background", INTEGER_OBJ(ae.rgb_bg_color));
1037    }
1038
1039    if (ae.rgb_sp_color != -1) {
1040      PUT_C(*hl, short_keys ? "sp" : "special", INTEGER_OBJ(ae.rgb_sp_color));
1041    }
1042
1043    if (mask & HL_FG_INDEXED) {
1044      PUT_C(*hl, "fg_indexed", BOOLEAN_OBJ(true));
1045    }
1046
1047    if (mask & HL_BG_INDEXED) {
1048      PUT_C(*hl, "bg_indexed", BOOLEAN_OBJ(true));
1049    }
1050
1051    const char *font = hl_get_font(ae.font);
1052    if (font != NULL) {
1053      PUT_C(*hl, "font", STRING_OBJ(cstr_as_string(font)));
1054    }
1055  } else {
1056    if (ae.cterm_fg_color != 0) {
1057      PUT_C(*hl, short_keys ? "ctermfg" : "foreground", INTEGER_OBJ(ae.cterm_fg_color - 1));
1058    }
1059
1060    if (ae.cterm_bg_color != 0) {
1061      PUT_C(*hl, short_keys ? "ctermbg" : "background", INTEGER_OBJ(ae.cterm_bg_color - 1));
1062    }
1063  }
1064
1065  if (ae.hl_blend > -1 && (use_rgb || !short_keys)) {
1066    PUT_C(*hl, "blend", INTEGER_OBJ(ae.hl_blend));
1067  }
1068}
1069
1070HlAttrs dict2hlattrs(Dict(highlight) *dict, bool use_rgb, int *link_id, HlAttrs *base, Error *err)
1071{
1072#define HAS_KEY_X(d, key) HAS_KEY(d, highlight, key)
1073  HlAttrs hlattrs = HLATTRS_INIT;
1074  int32_t fg = base ? base->rgb_fg_color : -1;
1075  int32_t bg = base ? base->rgb_bg_color : -1;
1076  int32_t ctermfg = base ? (base->cterm_fg_color == 0 ? -1 : base->cterm_fg_color - 1) : -1;
1077  int32_t ctermbg = base ? (base->cterm_bg_color == 0 ? -1 : base->cterm_bg_color - 1) : -1;
1078  int32_t sp = base ? base->rgb_sp_color : -1;
1079  int blend = base ? base->hl_blend : -1;
1080  int32_t mask = base ? base->rgb_ae_attr : 0;
1081  int32_t cterm_mask = base ? base->cterm_ae_attr : 0;
1082  int32_t font = base ? base->font : -1;
1083  bool cterm_mask_provided = false;
1084
1085#define CHECK_FLAG_WITH_KEY(d, m, name, extra, flag) \
1086  if (HAS_KEY_X(d, name)) { \
1087    int32_t flag_ = (flag); \
1088    int32_t cmask_ = (flag_ & HL_UNDERLINE_MASK) ? HL_UNDERLINE_MASK : flag_; \
1089    if (d->name##extra) { \
1090      m = (m & ~cmask_) | flag_; \
1091    } else if ((m & cmask_) == flag_) { \
1092      m &= ~cmask_; \
1093    } \
1094  }
1095
1096  CHECK_FLAG_WITH_KEY(dict, mask, reverse, , HL_INVERSE);
1097  CHECK_FLAG_WITH_KEY(dict, mask, bold, , HL_BOLD);
1098  CHECK_FLAG_WITH_KEY(dict, mask, italic, , HL_ITALIC);
1099  CHECK_FLAG_WITH_KEY(dict, mask, underline, , HL_UNDERLINE);
1100  CHECK_FLAG_WITH_KEY(dict, mask, undercurl, , HL_UNDERCURL);
1101  CHECK_FLAG_WITH_KEY(dict, mask, underdouble, , HL_UNDERDOUBLE);
1102  CHECK_FLAG_WITH_KEY(dict, mask, underdotted, , HL_UNDERDOTTED);
1103  CHECK_FLAG_WITH_KEY(dict, mask, underdashed, , HL_UNDERDASHED);
1104  CHECK_FLAG_WITH_KEY(dict, mask, standout, , HL_STANDOUT);
1105  CHECK_FLAG_WITH_KEY(dict, mask, strikethrough, , HL_STRIKETHROUGH);
1106  CHECK_FLAG_WITH_KEY(dict, mask, altfont, , HL_ALTFONT);
1107  CHECK_FLAG_WITH_KEY(dict, mask, dim, , HL_DIM);
1108  CHECK_FLAG_WITH_KEY(dict, mask, blink, , HL_BLINK);
1109  CHECK_FLAG_WITH_KEY(dict, mask, conceal, , HL_CONCEALED);
1110  CHECK_FLAG_WITH_KEY(dict, mask, overline, , HL_OVERLINE);
1111  if (use_rgb) {
1112    CHECK_FLAG_WITH_KEY(dict, mask, fg_indexed, , HL_FG_INDEXED);
1113    CHECK_FLAG_WITH_KEY(dict, mask, bg_indexed, , HL_BG_INDEXED);
1114  }
1115  CHECK_FLAG_WITH_KEY(dict, mask, nocombine, , HL_NOCOMBINE);
1116  CHECK_FLAG_WITH_KEY(dict, mask, default, _, HL_DEFAULT);
1117
1118  if (HAS_KEY_X(dict, fg)) {
1119    fg = object_to_color(dict->fg, "fg", use_rgb, err);
1120  } else if (HAS_KEY_X(dict, foreground)) {
1121    fg = object_to_color(dict->foreground, "foreground", use_rgb, err);
1122  }
1123  if (ERROR_SET(err)) {
1124    return hlattrs;
1125  }
1126
1127  if (HAS_KEY_X(dict, bg)) {
1128    bg = object_to_color(dict->bg, "bg", use_rgb, err);
1129  } else if (HAS_KEY_X(dict, background)) {
1130    bg = object_to_color(dict->background, "background", use_rgb, err);
1131  }
1132  if (ERROR_SET(err)) {
1133    return hlattrs;
1134  }
1135
1136  if (HAS_KEY_X(dict, sp)) {
1137    sp = object_to_color(dict->sp, "sp", true, err);
1138  } else if (HAS_KEY_X(dict, special)) {
1139    sp = object_to_color(dict->special, "special", true, err);
1140  }
1141  if (ERROR_SET(err)) {
1142    return hlattrs;
1143  }
1144
1145  if (HAS_KEY_X(dict, blend)) {
1146    Integer blend0 = dict->blend;
1147    VALIDATE_RANGE((blend0 >= 0 && blend0 <= 100), "blend", {
1148      return hlattrs;
1149    });
1150    blend = (int)blend0;
1151  }
1152
1153  if (HAS_KEY_X(dict, link) || HAS_KEY_X(dict, link_global)) {
1154    if (!link_id) {
1155      api_set_error(err, kErrorTypeValidation, "Invalid Key: '%s'",
1156                    HAS_KEY_X(dict, link_global) ? "link_global" : "link");
1157      return hlattrs;
1158    }
1159    if (HAS_KEY_X(dict, link_global)) {
1160      *link_id = (int)dict->link_global;
1161      mask |= HL_GLOBAL;
1162    } else {
1163      *link_id = (int)dict->link;
1164    }
1165
1166    if (ERROR_SET(err)) {
1167      return hlattrs;
1168    }
1169  }
1170
1171  // Handle cterm attrs
1172  if (HAS_KEY_X(dict, cterm)) {
1173    Dict(highlight_cterm) cterm[1] = KEYDICT_INIT;
1174    if (!api_dict_to_keydict(cterm, KeyDict_highlight_cterm_get_field,
1175                             dict->cterm, err)) {
1176      return hlattrs;
1177    }
1178
1179    cterm_mask_provided = true;
1180    cterm_mask = 0;
1181
1182#define CHECK_FLAG(d, m, name, extra, flag) \
1183  if (d->name##extra) { \
1184    if (flag & HL_UNDERLINE_MASK) { \
1185      m &= ~HL_UNDERLINE_MASK; \
1186    } \
1187    m |= flag; \
1188  }
1189
1190    CHECK_FLAG(cterm, cterm_mask, reverse, , HL_INVERSE);
1191    CHECK_FLAG(cterm, cterm_mask, bold, , HL_BOLD);
1192    CHECK_FLAG(cterm, cterm_mask, italic, , HL_ITALIC);
1193    CHECK_FLAG(cterm, cterm_mask, underline, , HL_UNDERLINE);
1194    CHECK_FLAG(cterm, cterm_mask, undercurl, , HL_UNDERCURL);
1195    CHECK_FLAG(cterm, cterm_mask, underdouble, , HL_UNDERDOUBLE);
1196    CHECK_FLAG(cterm, cterm_mask, underdotted, , HL_UNDERDOTTED);
1197    CHECK_FLAG(cterm, cterm_mask, underdashed, , HL_UNDERDASHED);
1198    CHECK_FLAG(cterm, cterm_mask, standout, , HL_STANDOUT);
1199    CHECK_FLAG(cterm, cterm_mask, strikethrough, , HL_STRIKETHROUGH);
1200    CHECK_FLAG(cterm, cterm_mask, altfont, , HL_ALTFONT);
1201    CHECK_FLAG(cterm, cterm_mask, dim, , HL_DIM);
1202    CHECK_FLAG(cterm, cterm_mask, blink, , HL_BLINK);
1203    CHECK_FLAG(cterm, cterm_mask, conceal, , HL_CONCEALED);
1204    CHECK_FLAG(cterm, cterm_mask, overline, , HL_OVERLINE);
1205    CHECK_FLAG(cterm, cterm_mask, nocombine, , HL_NOCOMBINE);
1206  }
1207#undef CHECK_FLAG
1208#undef CHECK_FLAG_WITH_KEY
1209
1210  if (HAS_KEY_X(dict, ctermfg)) {
1211    ctermfg = object_to_color(dict->ctermfg, "ctermfg", false, err);
1212    if (ERROR_SET(err)) {
1213      return hlattrs;
1214    }
1215  }
1216
1217  if (HAS_KEY_X(dict, ctermbg)) {
1218    ctermbg = object_to_color(dict->ctermbg, "ctermbg", false, err);
1219    if (ERROR_SET(err)) {
1220      return hlattrs;
1221    }
1222  }
1223
1224  if (use_rgb) {
1225    // apply gui mask as default for cterm mask
1226    if (!cterm_mask_provided) {
1227      cterm_mask = mask;
1228    }
1229    hlattrs.rgb_ae_attr = mask;
1230    hlattrs.rgb_bg_color = bg;
1231    hlattrs.rgb_fg_color = fg;
1232    hlattrs.rgb_sp_color = sp;
1233    hlattrs.hl_blend = blend;
1234    hlattrs.cterm_bg_color = ctermbg == -1 ? 0 : (int16_t)(ctermbg + 1);
1235    hlattrs.cterm_fg_color = ctermfg == -1 ? 0 : (int16_t)(ctermfg + 1);
1236    hlattrs.cterm_ae_attr = cterm_mask;
1237  } else {
1238    hlattrs.cterm_bg_color = bg == -1 ? 0 : (int16_t)(bg + 1);
1239    hlattrs.cterm_fg_color = fg == -1 ? 0 : (int16_t)(fg + 1);
1240    hlattrs.cterm_ae_attr = mask;
1241  }
1242
1243  if (HAS_KEY_X(dict, font)) {
1244    String str = dict->font;
1245    font = (str.size > 0 && STRICMP(str.data, "NONE") != 0) ? hl_add_font_idx(str.data) : -1;
1246  }
1247  hlattrs.font = font;
1248
1249  return hlattrs;
1250#undef HAS_KEY_X
1251}
1252
1253int object_to_color(Object val, char *key, bool rgb, Error *err)
1254{
1255  if (val.type == kObjectTypeInteger) {
1256    return (int)val.data.integer;
1257  } else if (val.type == kObjectTypeString) {
1258    String str = val.data.string;
1259    // TODO(bfredl): be more fancy with "bg", "fg" etc
1260    if (!str.size || STRICMP(str.data, "NONE") == 0) {
1261      return -1;
1262    }
1263    int color;
1264    if (rgb) {
1265      int dummy;
1266      color = name_to_color(str.data, &dummy);
1267    } else {
1268      color = name_to_ctermcolor(str.data);
1269    }
1270    VALIDATE_S((color >= 0), "highlight color", str.data, {
1271      return color;
1272    });
1273    return color;
1274  } else {
1275    VALIDATE_EXP(false, key, "String or Integer", NULL, {
1276      return 0;
1277    });
1278  }
1279}
1280
1281Array hl_inspect(int attr, Arena *arena)
1282{
1283  if (!hlstate_active) {
1284    return (Array)ARRAY_DICT_INIT;
1285  }
1286  Array ret = arena_array(arena, hl_inspect_size(attr));
1287  hl_inspect_impl(&ret, attr, arena);
1288  return ret;
1289}
1290
1291static size_t hl_inspect_size(int attr)
1292{
1293  if (attr <= 0 || attr >= (int)set_size(&attr_entries)) {
1294    return 0;
1295  }
1296
1297  HlEntry e = attr_entry(attr);
1298  if (e.kind == kHlCombine || e.kind == kHlBlend || e.kind == kHlBlendThrough) {
1299    return hl_inspect_size(e.id1) + hl_inspect_size(e.id2);
1300  }
1301  return 1;
1302}
1303
1304static void hl_inspect_impl(Array *arr, int attr, Arena *arena)
1305{
1306  Dict item = ARRAY_DICT_INIT;
1307  if (attr <= 0 || attr >= (int)set_size(&attr_entries)) {
1308    return;
1309  }
1310
1311  HlEntry e = attr_entry(attr);
1312  switch (e.kind) {
1313  case kHlSyntax:
1314    item = arena_dict(arena, 3);
1315    PUT_C(item, "kind", CSTR_AS_OBJ("syntax"));
1316    PUT_C(item, "hi_name", CSTR_AS_OBJ(syn_id2name(e.id1)));
1317    break;
1318
1319  case kHlUI:
1320    item = arena_dict(arena, 4);
1321    PUT_C(item, "kind", CSTR_AS_OBJ("ui"));
1322    const char *ui_name = (e.id1 == -1) ? "Normal" : hlf_names[e.id1];
1323    PUT_C(item, "ui_name", CSTR_AS_OBJ(ui_name));
1324    PUT_C(item, "hi_name", CSTR_AS_OBJ(syn_id2name(e.id2)));
1325    break;
1326
1327  case kHlTerminal:
1328    item = arena_dict(arena, 2);
1329    PUT_C(item, "kind", CSTR_AS_OBJ("term"));
1330    break;
1331
1332  case kHlCombine:
1333  case kHlBlend:
1334  case kHlBlendThrough:
1335    // attribute combination is associative, so flatten to an array
1336    hl_inspect_impl(arr, e.id1, arena);
1337    hl_inspect_impl(arr, e.id2, arena);
1338    return;
1339
1340  case kHlUnknown:
1341  case kHlInvalid:
1342    return;
1343  }
1344  PUT_C(item, "id", INTEGER_OBJ(attr));
1345  ADD_C(*arr, DICT_OBJ(item));
1346}