robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
19.0 KiB623 linesraw
1local api = vim.api
2local query = vim.treesitter.query
3local Range = require('vim.treesitter._range')
4local cmp_lt = Range.cmp_pos.lt
5
6local ns = api.nvim_create_namespace('nvim.treesitter.highlighter')
7
8---@alias vim.treesitter.highlighter.Iter fun(end_line: integer|nil, end_col: integer|nil): integer, TSNode, vim.treesitter.query.TSMetadata, TSQueryMatch, TSTree
9
10---@class (private) vim.treesitter.highlighter.Query
11---@field private _query vim.treesitter.Query?
12---@field private lang string
13---@field private hl_cache table<integer,integer>
14local TSHighlighterQuery = {}
15TSHighlighterQuery.__index = TSHighlighterQuery
16
17---@private
18---@param lang string
19---@param query_string string?
20---@return vim.treesitter.highlighter.Query
21function TSHighlighterQuery.new(lang, query_string)
22  local self = setmetatable({}, TSHighlighterQuery)
23  self.lang = lang
24  self.hl_cache = {}
25
26  if query_string then
27    self._query = query.parse(lang, query_string)
28  else
29    self._query = query.get(lang, 'highlights')
30  end
31
32  return self
33end
34
35---@package
36---@param capture integer
37---@return integer?
38function TSHighlighterQuery:get_hl_from_capture(capture)
39  if not self.hl_cache[capture] then
40    local name = assert(assert(self._query).captures[capture])
41    local id = 0
42    if not vim.startswith(name, '_') then
43      id = api.nvim_get_hl_id_by_name('@' .. name .. '.' .. self.lang)
44    end
45    self.hl_cache[capture] = id
46  end
47
48  return self.hl_cache[capture]
49end
50
51---@nodoc
52function TSHighlighterQuery:query()
53  return self._query
54end
55
56---@class (private) vim.treesitter.highlighter.State
57---@field tstree TSTree
58---@field next_row integer
59---@field next_col integer
60---@field iter vim.treesitter.highlighter.Iter?
61---@field highlighter_query vim.treesitter.highlighter.Query
62
63---@nodoc
64---@class vim.treesitter.highlighter
65---@field active table<integer,vim.treesitter.highlighter>
66---@field bufnr integer
67---@field private orig_spelloptions string
68--- A map from window ID to highlight states.
69--- This state is kept during rendering across each line update.
70---@field private _highlight_states vim.treesitter.highlighter.State[]
71---@field private _queries table<string,vim.treesitter.highlighter.Query>
72---@field  _conceal_line boolean?
73---@field  _conceal_checked table<integer, boolean>
74---@field tree vim.treesitter.LanguageTree
75---@field private redraw_count integer
76--- A map from window ID to whether we are currently parsing that window asynchronously
77---@field parsing boolean
78local TSHighlighter = {
79  active = {},
80}
81
82TSHighlighter.__index = TSHighlighter
83
84---@nodoc
85---
86--- Creates a highlighter for `tree`.
87---
88---@param tree vim.treesitter.LanguageTree parser object to use for highlighting
89---@param opts (table|nil) Configuration of the highlighter:
90---           - queries table overwrite queries used by the highlighter
91---@return vim.treesitter.highlighter Created highlighter object
92function TSHighlighter.new(tree, opts)
93  local source = tree:source()
94  if type(source) ~= 'number' then
95    error('TSHighlighter can not be used with a string parser source.')
96  end
97
98  -- Calling start() again on an already-highlighted buffer must be a no-op: a second instance
99  -- would register duplicate on_bytes/on_changedtree/on_detach callbacks that destroy() never
100  -- unregisters, leaking callbacks that keep firing for the orphaned instance.
101  local existing = TSHighlighter.active[source]
102  if existing then
103    if existing.tree == tree then
104      return existing
105    end
106    -- Different tree (e.g. a language switch): the old instance would otherwise be silently
107    -- orphaned with the same leaked callbacks, so destroy() it first, matching stop() semantics.
108    existing:destroy()
109  end
110
111  local self = setmetatable({}, TSHighlighter)
112
113  opts = opts or {} ---@type { queries: table<string,string> }
114  self.tree = tree
115  tree:register_cbs({
116    on_detach = function()
117      self:on_detach()
118    end,
119  })
120
121  --- Enable conceal_lines if query exists for lang and has conceal_lines metadata.
122  --- @param lang string
123  local function set_conceal_lines(lang)
124    local hl_query = not self._conceal_line and self:get_query(lang):query()
125    if hl_query then
126      self._conceal_line = hl_query.has_conceal_line
127    end
128  end
129
130  tree:register_cbs({
131    on_bytes = function(buf)
132      -- Clear conceal_lines marks whenever the buffer text changes. Marks are added
133      -- back as either the _conceal_line or on_win callback comes across them.
134      local hl = TSHighlighter.active[buf]
135      if hl and next(hl._conceal_checked) then
136        api.nvim_buf_clear_namespace(buf, ns, 0, -1)
137        hl._conceal_checked = {}
138      end
139    end,
140    on_changedtree = function(...)
141      self:on_changedtree(...)
142    end,
143    on_child_removed = function(child)
144      child:for_each_tree(function(t)
145        self:on_changedtree(t:included_ranges(true))
146      end)
147    end,
148    on_child_added = function(child)
149      child:for_each_tree(function(t)
150        set_conceal_lines(t:lang())
151      end)
152    end,
153  }, true)
154
155  self.bufnr = source
156  self.redraw_count = 0
157  self._conceal_checked = {}
158  self._queries = {}
159  self._highlight_states = {}
160  self.parsing = false
161
162  -- Queries for a specific language can be overridden by a custom
163  -- string query... if one is not provided it will be looked up by file.
164  if opts.queries then
165    for lang, query_string in pairs(opts.queries) do
166      self._queries[lang] = TSHighlighterQuery.new(lang, query_string)
167      set_conceal_lines(lang)
168    end
169  end
170  set_conceal_lines(tree:lang())
171  self.orig_spelloptions = vim.bo[self.bufnr].spelloptions
172
173  vim.bo[self.bufnr].syntax = ''
174  vim.b[self.bufnr].ts_highlight = true
175
176  TSHighlighter.active[self.bufnr] = self
177
178  -- Tricky: if syntax hasn't been enabled, we need to reload color scheme
179  -- but use synload.vim rather than syntax.vim to not enable
180  -- syntax FileType autocmds. Later on we should integrate with the
181  -- `:syntax` and `set syntax=...` machinery properly.
182  -- Still need to ensure that syntaxset augroup exists, so that calling :destroy()
183  -- immediately afterwards will not error.
184  if vim.g.syntax_on ~= 1 then
185    vim.cmd.runtime({ 'syntax/synload.vim', bang = true })
186    api.nvim_create_augroup('syntaxset', { clear = false })
187  end
188
189  vim._with({ buf = self.bufnr }, function()
190    vim.opt_local.spelloptions:append('noplainbuffer')
191  end)
192
193  return self
194end
195
196--- @nodoc
197--- Removes all internal references to the highlighter
198function TSHighlighter:destroy()
199  TSHighlighter.active[self.bufnr] = nil
200
201  if api.nvim_buf_is_loaded(self.bufnr) then
202    vim.bo[self.bufnr].spelloptions = self.orig_spelloptions
203    vim.b[self.bufnr].ts_highlight = nil
204    api.nvim_buf_clear_namespace(self.bufnr, ns, 0, -1)
205    if vim.g.syntax_on == 1 then
206      api.nvim_exec_autocmds(
207        'FileType',
208        { group = 'syntaxset', buf = self.bufnr, modeline = false }
209      )
210    end
211  end
212end
213
214---@param srow integer
215---@param erow integer exclusive
216---@private
217function TSHighlighter:prepare_highlight_states(srow, erow)
218  self._highlight_states = {}
219
220  self.tree:for_each_tree(function(tstree, tree)
221    if not tstree then
222      return
223    end
224
225    local root_node = tstree:root()
226    local root_start_row, _, root_end_row, _ = root_node:range()
227
228    -- Only consider trees within the visible range
229    if root_start_row > erow or root_end_row < srow then
230      return
231    end
232
233    local hl_query = self:get_query(tree:lang())
234    -- Some injected languages may not have highlight queries.
235    if not hl_query:query() then
236      return
237    end
238
239    -- _highlight_states should be a list so that the highlights are added in the same order as
240    -- for_each_tree traversal. This ensures that parents' highlight don't override children's.
241    table.insert(self._highlight_states, {
242      tstree = tstree,
243      next_row = 0,
244      next_col = 0,
245      iter = nil,
246      highlighter_query = hl_query,
247    })
248  end)
249end
250
251---@param fn fun(state: vim.treesitter.highlighter.State)
252---@package
253function TSHighlighter:for_each_highlight_state(fn)
254  for _, state in ipairs(self._highlight_states) do
255    fn(state)
256  end
257end
258
259---@package
260function TSHighlighter:on_detach()
261  self:destroy()
262end
263
264---@package
265---@param changes Range6[]
266function TSHighlighter:on_changedtree(changes)
267  for _, ch in ipairs(changes) do
268    api.nvim__redraw({ buf = self.bufnr, range = { ch[1], ch[4] + 1 }, flush = false })
269    -- Only invalidate the _conceal_checked range if _conceal_line is set and
270    -- ch[4] is not UINT32_MAX (empty range on first changedtree).
271    if ch[4] == 2 ^ 32 - 1 then
272      self._conceal_checked = {}
273    end
274    for i = ch[1], self._conceal_line and ch[4] ~= 2 ^ 32 - 1 and ch[4] or 0 do
275      self._conceal_checked[i] = false
276    end
277  end
278end
279
280--- Gets the query used for @param lang
281---@nodoc
282---@param lang string Language used by the highlighter.
283---@return vim.treesitter.highlighter.Query
284function TSHighlighter:get_query(lang)
285  if not self._queries[lang] then
286    local success, result = pcall(TSHighlighterQuery.new, lang)
287    if not success then
288      self:destroy()
289      error(result)
290    end
291    self._queries[lang] = result
292  end
293
294  return self._queries[lang]
295end
296
297--- @param match TSQueryMatch
298--- @param bufnr integer
299--- @param capture integer
300--- @param metadata vim.treesitter.query.TSMetadata
301--- @return string?
302local function get_url(match, bufnr, capture, metadata)
303  ---@type string|integer|nil
304  local url = metadata[capture] and metadata[capture].url
305
306  if not url or type(url) == 'string' then
307    return url
308  end
309
310  local captures = match:captures()
311
312  if not captures[url] then
313    return
314  end
315
316  -- Assume there is only one matching node. If there is more than one, take the URL
317  -- from the first.
318  local other_node = assert(captures[url][1])
319
320  return vim.treesitter.get_node_text(other_node, bufnr, {
321    metadata = metadata[url],
322  })
323end
324
325--- @param capture_name string
326--- @return boolean?, integer
327local function get_spell(capture_name)
328  if capture_name == 'spell' then
329    return true, 0
330  elseif capture_name == 'nospell' then
331    -- Give nospell a higher priority so it always overrides spell captures.
332    return false, 1
333  end
334  return nil, 0
335end
336
337---@param self vim.treesitter.highlighter
338---@param buf integer
339---@param range_start_row integer
340---@param range_start_col integer
341---@param range_end_row integer
342---@param range_end_col integer
343---@param on_spell boolean
344---@param on_conceal boolean
345local function on_range_impl(
346  self,
347  buf,
348  range_start_row,
349  range_start_col,
350  range_end_row,
351  range_end_col,
352  on_spell,
353  on_conceal
354)
355  if self._conceal_line then
356    range_start_col = 0
357    if range_end_col ~= 0 then
358      range_end_row = range_end_row + 1
359      range_end_col = 0
360    end
361  end
362  for i = range_start_row, range_end_row - 1 do
363    self._conceal_checked[i] = self._conceal_line or nil
364  end
365
366  local MAX_ROW = 2147483647 -- sentinel for skipping to the end of file
367  local skip_until_row = MAX_ROW
368  local skip_until_col = 0
369
370  local subtree_counter = 0
371  self:for_each_highlight_state(function(state)
372    subtree_counter = subtree_counter + 1
373    local root_node = state.tstree:root()
374    local root_range = { root_node:range() }
375
376    if
377      not Range.intercepts(
378        root_range,
379        { range_start_row, range_start_col, range_end_row, range_end_col }
380      )
381    then
382      if cmp_lt(root_range[1], root_range[2], skip_until_row, skip_until_col) then
383        skip_until_row = root_range[1]
384        skip_until_col = root_range[2]
385      end
386      return
387    end
388
389    local tree_region = state.tstree:included_ranges(true)
390
391    local next_row = state.next_row
392    local next_col = state.next_col
393    local hl_query = assert(state.highlighter_query:query())
394
395    if state.iter == nil or cmp_lt(next_row, next_col, range_start_row, range_start_col) then
396      -- Mainly used to skip over folds
397
398      -- TODO(lewis6991): Creating a new iterator loses the cached predicate results for query
399      -- matches. Move this logic inside iter_captures() so we can maintain the cache.
400      state.iter = hl_query:iter_captures(
401        root_node,
402        self.bufnr,
403        range_start_row,
404        root_range[3],
405        { start_col = range_start_col, end_col = root_range[4] }
406      )
407    end
408
409    local captures = hl_query.captures
410
411    while cmp_lt(next_row, next_col, range_end_row, range_end_col) do
412      local capture, node, metadata, match = state.iter(range_end_row, range_end_col)
413      if not node then
414        next_row = vim._maxint
415        next_col = vim._maxint
416        break
417      end
418
419      local outer_range = vim.treesitter.get_range(node, buf, metadata and metadata[capture])
420      if cmp_lt(next_row, next_col, outer_range[1], outer_range[2]) then
421        next_row = outer_range[1]
422        next_col = outer_range[2]
423      end
424
425      if not capture then
426        break
427      end
428
429      for _, range in ipairs(tree_region) do
430        local intersection = Range.intersection(range, outer_range)
431        if intersection then
432          local start_row, start_col, end_row, end_col = Range.unpack4(intersection)
433
434          local hl = state.highlighter_query:get_hl_from_capture(capture)
435
436          local capture_name = assert(captures[capture])
437
438          local spell, spell_pri_offset = get_spell(capture_name)
439
440          local is_noconceal = capture_name == 'noconceal'
441          -- The "conceal" attribute can be set at the pattern level or on a particular capture
442          local conceal_attr = (metadata.conceal ~= nil and metadata.conceal)
443            or (metadata[capture] and metadata[capture].conceal)
444          local conceal ---@type boolean|string?
445          if is_noconceal then
446            conceal = false
447          else
448            conceal = conceal_attr
449            if conceal_attr == false then
450              is_noconceal = true
451            end
452          end
453          is_noconceal = is_noconceal or conceal_attr == false
454          local conceal_pri_offset = is_noconceal and 1 or 0
455
456          -- The "priority" attribute can be set at the pattern level or on a particular capture
457          local priority = (
458            vim._tointeger(metadata.priority or metadata[capture] and metadata[capture].priority)
459            or vim.hl.priorities.treesitter
460          )
461            + spell_pri_offset
462            + conceal_pri_offset
463
464          local url = get_url(match, buf, capture, metadata)
465
466          if hl and not on_conceal and (not on_spell or spell ~= nil) then
467            -- Workaround for #35814: ensure the range is within buffer bounds,
468            -- allowing the last line if end_col is 0.
469            -- TODO(skewb1k): investigate a proper concurrency-safe handling of extmarks.
470            if (end_row + (end_col > 0 and 1 or 0)) <= api.nvim_buf_line_count(buf) then
471              api.nvim_buf_set_extmark(buf, ns, start_row, start_col, {
472                end_row = end_row,
473                end_col = end_col,
474                hl_group = hl,
475                ephemeral = true,
476                priority = priority,
477                conceal = conceal,
478                spell = spell,
479                url = url,
480                _subpriority = subtree_counter,
481              })
482            end
483          end
484
485          if
486            (metadata.conceal_lines or metadata[capture] and metadata[capture].conceal_lines)
487            and #api.nvim_buf_get_extmarks(buf, ns, { start_row, 0 }, { start_row, 0 }) == 0
488          then
489            api.nvim_buf_set_extmark(buf, ns, start_row, 0, {
490              end_line = end_row,
491              conceal_lines = '',
492            })
493          end
494        end
495      end
496    end
497
498    state.next_row = next_row
499    state.next_col = next_col
500    if cmp_lt(next_row, next_col, skip_until_row, skip_until_col) then
501      skip_until_row = next_row
502      skip_until_col = next_col
503    end
504  end)
505  return skip_until_row, skip_until_col
506end
507
508---@private
509---@param buf integer
510---@param br integer
511---@param bc integer
512---@param er integer
513---@param ec integer
514function TSHighlighter._on_range(_, _, buf, br, bc, er, ec, _)
515  local self = TSHighlighter.active[buf]
516  if not self then
517    return
518  end
519
520  return on_range_impl(self, buf, br, bc, er, ec, false, false)
521end
522
523---@private
524---@param buf integer
525---@param srow integer
526---@param erow integer
527function TSHighlighter._on_spell_nav(_, _, buf, srow, _, erow, _)
528  local self = TSHighlighter.active[buf]
529  if not self then
530    return
531  end
532
533  -- Do not affect potentially populated highlight state. Here we just want a temporary
534  -- empty state so the C code can detect whether the region should be spell checked.
535  local highlight_states = self._highlight_states
536  local search_erow = math.max(erow, srow + 1)
537  self:prepare_highlight_states(srow, erow)
538
539  on_range_impl(self, buf, srow, 0, search_erow, 0, true, false)
540  self._highlight_states = highlight_states
541end
542
543---@private
544---@param buf integer
545---@param row integer
546function TSHighlighter._on_conceal_line(_, _, buf, row)
547  local self = TSHighlighter.active[buf]
548  if not self or not self._conceal_line or self._conceal_checked[row] then
549    return
550  end
551
552  -- Do not affect potentially populated highlight state.
553  local highlight_states = self._highlight_states
554  self.tree:parse({ row, row + 1 })
555  self:prepare_highlight_states(row, row)
556  on_range_impl(self, buf, row, 0, row + 1, 0, false, true)
557  self._highlight_states = highlight_states
558end
559
560---@private
561---@param buf integer
562---@param topline integer
563---@param botline integer
564function TSHighlighter._on_win(_, _, buf, topline, botline)
565  local self = TSHighlighter.active[buf]
566  if not self then
567    return false
568  end
569  if not self.parsing then
570    self.redraw_count = self.redraw_count + 1
571    self:prepare_highlight_states(topline, botline)
572  else
573    self:for_each_highlight_state(function(state)
574      state.iter = nil
575      state.next_row = 0
576      state.next_col = 0
577    end)
578  end
579  return next(self._highlight_states) ~= nil
580end
581
582function TSHighlighter._on_start()
583  local buf_ranges = {} ---@type table<integer, Range[]>
584  for _, win in ipairs(api.nvim_tabpage_list_wins(0)) do
585    local buf = api.nvim_win_get_buf(win)
586    if TSHighlighter.active[buf] then
587      if not buf_ranges[buf] then
588        buf_ranges[buf] = {}
589      end
590      local topline = vim.fn.line('w0', win) - 1
591      -- +1 because w$ is the last completely displayed line (w_botline - 1), which may be -1 of the
592      -- last line that is at least partially visible.
593      local botline = vim.fn.line('w$', win) + 1
594      table.insert(buf_ranges[buf], { topline, botline })
595    end
596  end
597  for buf, ranges in pairs(buf_ranges) do
598    local highlighter = TSHighlighter.active[buf]
599    if not highlighter.parsing then
600      table.sort(ranges, function(a, b)
601        return a[1] < b[1]
602      end)
603      highlighter.parsing = highlighter.parsing
604        or nil
605          == highlighter.tree:parse(ranges, function(_, trees)
606            if trees and highlighter.parsing then
607              highlighter.parsing = false
608              api.nvim__redraw({ buf = buf, valid = false, flush = false })
609            end
610          end)
611    end
612  end
613end
614
615api.nvim_set_decoration_provider(ns, {
616  on_win = TSHighlighter._on_win,
617  on_start = TSHighlighter._on_start,
618  on_range = TSHighlighter._on_range,
619  _on_spell_nav = TSHighlighter._on_spell_nav,
620  _on_conceal_line = TSHighlighter._on_conceal_line,
621})
622
623return TSHighlighter