robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
15.4 KiB463 linesraw
1local ts = vim.treesitter
2
3local Range = require('vim.treesitter._range')
4
5local api = vim.api
6local nvim_on = require('vim._core.util').nvim_on
7
8---Treesitter folding is done in two steps:
9---(1) compute the fold levels with the syntax tree and cache the result (`compute_folds_levels`)
10---(2) evaluate foldexpr for each window, which reads from the cache (`foldupdate`)
11---@class TS.FoldInfo
12---
13---@field levels string[] the cached foldexpr result for each line
14---@field levels0 integer[] the cached raw fold levels
15---
16---The range edited since the last invocation of the callback scheduled in on_bytes.
17---Should compute fold levels in this range.
18---@field on_bytes_range? Range2
19---
20---The range on which to evaluate foldexpr.
21---When in insert mode, the evaluation is deferred to InsertLeave.
22---@field foldupdate_range? Range2
23---
24---The treesitter parser associated with this buffer.
25---@field parser? vim.treesitter.LanguageTree
26local FoldInfo = {}
27FoldInfo.__index = FoldInfo
28
29---@private
30---@param buf integer
31function FoldInfo.new(buf)
32  return setmetatable({
33    levels0 = {},
34    levels = {},
35    parser = ts.get_parser(buf, nil),
36  }, FoldInfo)
37end
38
39---@package
40---@param srow integer
41---@param erow integer 0-indexed, exclusive
42function FoldInfo:remove_range(srow, erow)
43  vim._list_remove(self.levels, srow + 1, erow)
44  vim._list_remove(self.levels0, srow + 1, erow)
45end
46
47---@package
48---@param srow integer
49---@param erow integer 0-indexed, exclusive
50function FoldInfo:add_range(srow, erow)
51  vim._list_insert(self.levels, srow + 1, erow, -1)
52  vim._list_insert(self.levels0, srow + 1, erow, -1)
53end
54
55---@param range Range2
56---@param srow integer
57---@param erow_old integer
58---@param erow_new integer 0-indexed, exclusive
59local function edit_range(range, srow, erow_old, erow_new)
60  range[1] = math.min(srow, range[1])
61  if erow_old <= range[2] then
62    range[2] = range[2] + (erow_new - erow_old)
63  end
64  range[2] = math.max(range[2], erow_new)
65end
66
67-- TODO(lewis6991): Setup a decor provider so injections folds can be parsed
68-- as the window is redrawn
69---@param bufnr integer
70---@param info TS.FoldInfo
71---@param srow integer?
72---@param erow integer? 0-indexed, exclusive
73---@param callback function?
74local function compute_folds_levels(bufnr, info, srow, erow, callback)
75  srow = srow or 0
76  erow = erow or api.nvim_buf_line_count(bufnr)
77
78  local parser = info.parser
79  if
80    not parser
81    -- Parsing an empty buffer results in problems with the parsing state,
82    -- resulting in both a broken highlighter and foldexpr.
83    or api.nvim_buf_line_count(bufnr) == 1
84      and api.nvim_buf_call(bufnr, function()
85        return vim.fn.line2byte(1) <= 0
86      end)
87  then
88    return
89  end
90
91  parser:parse(nil, function(_, trees)
92    if not trees then
93      return
94    end
95
96    local enter_counts = {} ---@type table<integer, integer>
97    local leave_counts = {} ---@type table<integer, integer>
98    local prev_start = -1
99    local prev_stop = -1
100
101    parser:for_each_tree(function(tree, ltree)
102      local query = ts.query.get(ltree:lang(), 'folds')
103      if not query then
104        return
105      end
106
107      -- Collect folds starting from srow - 1, because we should first subtract the folds that end at
108      -- srow - 1 from the level of srow - 1 to get accurate level of srow.
109      for _, match, metadata in query:iter_matches(tree:root(), bufnr, math.max(srow - 1, 0), erow) do
110        for id, nodes in pairs(match) do
111          if query.captures[id] == 'fold' then
112            local range = ts.get_range(assert(nodes[1]), bufnr, metadata[id])
113            local start, _, stop, stop_col = Range.unpack4(range)
114
115            if #nodes > 1 then
116              -- assumes nodes are ordered by range
117              local end_range = ts.get_range(nodes[#nodes], bufnr, metadata[id])
118              local _, _, end_stop, end_stop_col = Range.unpack4(end_range)
119              stop = end_stop
120              stop_col = end_stop_col
121            end
122
123            if stop_col == 0 then
124              stop = stop - 1
125            end
126
127            local fold_length = stop - start + 1
128
129            -- Fold only multiline nodes that are not exactly the same as previously met folds
130            -- Checking against just the previously found fold is sufficient if nodes
131            -- are returned in preorder or postorder when traversing tree
132            if
133              fold_length > vim.wo.foldminlines and not (start == prev_start and stop == prev_stop)
134            then
135              enter_counts[start + 1] = (enter_counts[start + 1] or 0) + 1
136              leave_counts[stop + 1] = (leave_counts[stop + 1] or 0) + 1
137              prev_start = start
138              prev_stop = stop
139            end
140          end
141        end
142      end
143    end)
144
145    local nestmax = vim.wo.foldnestmax
146    local level0_prev = info.levels0[srow] or 0
147    local leave_prev = leave_counts[srow] or 0
148
149    -- We now have the list of fold opening and closing, fill the gaps and mark where fold start
150    for lnum = srow + 1, erow do
151      local enter_line = enter_counts[lnum] or 0
152      local leave_line = leave_counts[lnum] or 0
153      local level0 = level0_prev - leave_prev + enter_line
154
155      -- Determine if it's the start/end of a fold
156      -- NB: vim's fold-expr interface does not have a mechanism to indicate that
157      -- two (or more) folds start at this line, so it cannot distinguish between
158      --  ( \n ( \n )) \n (( \n ) \n )
159      -- versus
160      --  ( \n ( \n ) \n ( \n ) \n )
161      -- Both are represented by ['>1', '>2', '2', '>2', '2', '1'], and
162      -- vim interprets as the second case.
163      -- If it did have such a mechanism, (clamped - clamped_prev)
164      -- would be the correct number of starts to pass on.
165      local adjusted = level0 ---@type integer
166      local prefix = ''
167      if enter_line > 0 then
168        prefix = '>'
169        if leave_line > 0 then
170          -- If this line ends a fold f1 and starts a fold f2, then move f1's end to the previous line
171          -- so that f2 gets the correct level on this line. This may reduce the size of f1 below
172          -- foldminlines, but we don't handle it for simplicity.
173          --- @type integer avoid flaky error
174          adjusted = level0 - leave_line
175          leave_line = 0
176        end
177      end
178
179      -- Clamp at foldnestmax.
180      local clamped = adjusted
181      if adjusted > nestmax then
182        prefix = ''
183        clamped = nestmax
184      end
185
186      -- Record the "real" level, so that it can be used as "base" of later compute_folds_levels().
187      info.levels0[lnum] = adjusted
188      info.levels[lnum] = prefix .. tostring(clamped)
189
190      leave_prev = leave_line
191      level0_prev = adjusted
192    end
193
194    if callback then
195      callback()
196    end
197  end)
198end
199
200local M = {}
201
202---@type table<integer,TS.FoldInfo>
203local foldinfos = {}
204
205local group = api.nvim_create_augroup('nvim.treesitter.fold')
206
207--- Update the folds in the windows that contain the buffer and use expr foldmethod (assuming that
208--- the user doesn't use different foldexpr for the same buffer).
209---
210--- Nvim usually automatically updates folds when text changes, but it doesn't work here because
211--- FoldInfo update is scheduled. So we do it manually.
212---@package
213---@param srow integer
214---@param erow integer 0-indexed, exclusive
215---@param bufnr integer
216function FoldInfo:foldupdate(bufnr, srow, erow)
217  if self.foldupdate_range then
218    edit_range(self.foldupdate_range, srow, erow, erow)
219  else
220    self.foldupdate_range = { srow, erow }
221  end
222
223  if api.nvim_get_mode().mode:match('^i') then
224    -- foldUpdate() is guarded in insert mode. So update folds on InsertLeave
225    if #(api.nvim_get_autocmds({
226      group = group,
227      buf = bufnr,
228    })) > 0 then
229      return
230    end
231    nvim_on('InsertLeave', group, { buf = bufnr, once = true }, function()
232      self:do_foldupdate(bufnr)
233    end)
234    return
235  end
236
237  self:do_foldupdate(bufnr)
238end
239
240---@package
241---@param bufnr integer
242function FoldInfo:do_foldupdate(bufnr)
243  -- InsertLeave is not executed when <C-C> is used for exiting the insert mode, leaving
244  -- do_foldupdate untouched. If another execution of foldupdate consumes foldupdate_range, the
245  -- InsertLeave do_foldupdate gets nil foldupdate_range. In that case, skip the update. This is
246  -- correct because the update that consumed the range must have incorporated the range that
247  -- InsertLeave meant to update.
248  if not self.foldupdate_range then
249    return
250  end
251
252  local srow, erow = self.foldupdate_range[1], self.foldupdate_range[2]
253  self.foldupdate_range = nil
254  for _, win in ipairs(vim.fn.win_findbuf(bufnr)) do
255    if vim.wo[win].foldmethod == 'expr' then
256      vim._foldupdate(win, srow, erow)
257    end
258  end
259end
260
261--- Schedule a function only if bufnr is loaded.
262--- We schedule fold level computation for the following reasons:
263--- * queries seem to use the old buffer state in on_bytes for some unknown reason;
264--- * to avoid textlock;
265--- * to avoid infinite recursion:
266---   compute_folds_levels → parse → _do_callback → on_changedtree → compute_folds_levels.
267---@param bufnr integer
268---@param fn function
269local function schedule_if_loaded(bufnr, fn)
270  vim.schedule(function()
271    if not api.nvim_buf_is_loaded(bufnr) then
272      return
273    end
274    fn()
275  end)
276end
277
278---@param bufnr integer
279---@param tree_changes Range4[]
280local function on_changedtree(bufnr, tree_changes)
281  schedule_if_loaded(bufnr, function()
282    -- Buffer reload clears `foldinfos[bufnr]`, which may still be nil when callback is invoked.
283    local foldinfo = foldinfos[bufnr]
284    if not foldinfo then
285      return
286    end
287
288    local srow_upd, erow_upd ---@type integer?, integer?
289    local max_erow = api.nvim_buf_line_count(bufnr)
290    -- TODO(ribru17): Replace this with a proper .all() awaiter once #19624 is resolved
291    local iterations = 0
292    for _, change in ipairs(tree_changes) do
293      local srow, _, erow, ecol = Range.unpack4(change)
294      -- If a parser doesn't have any ranges explicitly set, treesitter will
295      -- return a range with end_row and end_bytes with a value of UINT32_MAX,
296      -- which is represented as -1 on 32-bit platforms, so clip end_row to
297      -- the max buffer line.
298      -- TODO(lewis6991): Handle this generally
299      if erow > max_erow or erow < 0 then
300        erow = max_erow
301      elseif ecol > 0 then
302        erow = erow + 1
303      end
304      -- Start from `srow - foldminlines`, because this edit may have shrunken the fold below limit.
305      srow = math.max(srow - vim.wo.foldminlines, 0)
306      srow_upd = srow_upd and math.min(srow_upd, srow) or srow
307      erow_upd = erow_upd and math.max(erow_upd, erow) or erow
308      compute_folds_levels(bufnr, foldinfo, srow, erow, function()
309        iterations = iterations + 1
310        if iterations == #tree_changes then
311          foldinfo:foldupdate(bufnr, srow_upd, erow_upd)
312        end
313      end)
314    end
315  end)
316end
317
318---@param bufnr integer
319---@param start_row integer
320---@param old_row integer
321---@param old_col integer
322---@param new_row integer
323---@param new_col integer
324---@param start_col integer
325local function on_bytes(bufnr, start_row, start_col, old_row, old_col, new_row, new_col)
326  -- Buffer reload clears `foldinfos[bufnr]`, which may still be nil when callback is invoked.
327  local foldinfo = foldinfos[bufnr]
328  if not foldinfo then
329    return
330  end
331
332  -- extend the end to fully include the range
333  local end_row_old = start_row + old_row + 1
334  local end_row_new = start_row + new_row + 1
335
336  if new_row ~= old_row then
337    -- foldexpr can be evaluated before the scheduled callback is invoked. So it may observe the
338    -- outdated levels, which may spuriously open the folds that didn't change. So we should shift
339    -- folds as accurately as possible. For this to be perfectly accurate, we should track the
340    -- actual TSNodes that account for each fold, and compare the node's range with the edited
341    -- range. But for simplicity, we just check whether the start row is completely removed (e.g.,
342    -- `dd`) or shifted (e.g., `o`).
343    if new_row < old_row then
344      if start_col == 0 and new_row == 0 and new_col == 0 then
345        foldinfo:remove_range(start_row, start_row + (end_row_old - end_row_new))
346      else
347        foldinfo:remove_range(end_row_new, end_row_old)
348      end
349    else
350      if start_col == 0 and old_row == 0 and old_col == 0 then
351        foldinfo:add_range(start_row, start_row + (end_row_new - end_row_old))
352      else
353        foldinfo:add_range(end_row_old, end_row_new)
354      end
355    end
356
357    if foldinfo.on_bytes_range then
358      edit_range(foldinfo.on_bytes_range, start_row, end_row_old, end_row_new)
359    else
360      foldinfo.on_bytes_range = { start_row, end_row_new }
361    end
362    if foldinfo.foldupdate_range then
363      edit_range(foldinfo.foldupdate_range, start_row, end_row_old, end_row_new)
364    end
365
366    -- This callback must not use on_bytes arguments, because they can be outdated when the callback
367    -- is invoked. For example, `J` with non-zero count triggers multiple on_bytes before executing
368    -- the scheduled callback. So we accumulate the edited ranges in `on_bytes_range`.
369    schedule_if_loaded(bufnr, function()
370      if not (foldinfo.on_bytes_range and foldinfos[bufnr]) then
371        return
372      end
373      local srow, erow = foldinfo.on_bytes_range[1], foldinfo.on_bytes_range[2]
374      foldinfo.on_bytes_range = nil
375      -- Start from `srow - foldminlines`, because this edit may have shrunken the fold below limit.
376      srow = math.max(srow - vim.wo.foldminlines, 0)
377      compute_folds_levels(bufnr, foldinfo, srow, erow, function()
378        foldinfo:foldupdate(bufnr, srow, erow)
379      end)
380    end)
381  end
382end
383
384local registered_cbs = {} ---@type table<integer, boolean>
385
386---@param lnum integer|nil
387---@return string
388function M.foldexpr(lnum)
389  lnum = lnum or vim.v.lnum
390  local bufnr = api.nvim_get_current_buf()
391
392  if not foldinfos[bufnr] then
393    foldinfos[bufnr] = FoldInfo.new(bufnr)
394    nvim_on({ 'BufUnload', 'VimEnter', 'FileType' }, nil, { buf = bufnr, once = true }, function()
395      foldinfos[bufnr] = nil
396    end)
397
398    local parser = foldinfos[bufnr].parser
399    if not parser then
400      return '0'
401    end
402
403    compute_folds_levels(bufnr, foldinfos[bufnr])
404
405    if not registered_cbs[bufnr] then
406      parser:register_cbs({
407        on_changedtree = function(tree_changes)
408          on_changedtree(bufnr, tree_changes)
409        end,
410
411        on_bytes = function(
412          _,
413          _,
414          start_row,
415          start_col,
416          _,
417          old_row,
418          old_col,
419          _,
420          new_row,
421          new_col,
422          _
423        )
424          on_bytes(bufnr, start_row, start_col, old_row, old_col, new_row, new_col)
425        end,
426
427        on_detach = function()
428          foldinfos[bufnr] = nil
429          registered_cbs[bufnr] = nil
430        end,
431      })
432
433      registered_cbs[bufnr] = true
434    end
435  end
436
437  return foldinfos[bufnr].levels[lnum] or '0'
438end
439
440nvim_on('OptionSet', group, {
441  pattern = { 'foldminlines', 'foldnestmax' },
442  desc = 'Refresh treesitter folds',
443}, function()
444  local buf = api.nvim_get_current_buf()
445  local bufs = vim.v.option_type == 'global' and vim.tbl_keys(foldinfos)
446    or foldinfos[buf] and { buf }
447    or {}
448  for _, bufnr in ipairs(bufs) do
449    local foldinfo = FoldInfo.new(bufnr)
450    foldinfos[bufnr] = foldinfo
451    api.nvim_buf_call(bufnr, function()
452      compute_folds_levels(bufnr, foldinfo, nil, nil, function()
453        -- FileType/BufUnload can clear or replace the fold state while this
454        -- async parse is in flight. Ignore callbacks for stale generations.
455        if foldinfos[bufnr] ~= foldinfo then
456          return
457        end
458        foldinfo:foldupdate(bufnr, 0, api.nvim_buf_line_count(bufnr))
459      end)
460    end)
461  end
462end)
463return M