robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
11.5 KiB432 linesraw
1--- @class (private) vim.undotree.tree.entry
2--- @field child integer[]
3--- @field time integer
4
5--- @alias vim.undotree.tree {[integer]: vim.undotree.tree.entry}
6
7local M = {}
8
9local ns = vim.api.nvim_create_namespace('nvim.undotree')
10
11--- @param buf integer
12--- @return vim.fn.undotree.entry[]
13--- @return integer
14local function get_undotree_entries(buf)
15  local undotree = vim.fn.undotree(buf)
16  local entries = undotree.entries
17
18  --Maybe: `:undo 0` and then `undotree` to get seq 0 time
19  table.insert(entries, 1, { seq = 0, time = -1 })
20
21  return entries, undotree.seq_cur
22end
23
24--- @param ent vim.fn.undotree.entry[]
25--- @param _tree vim.undotree.tree?
26--- @param _last integer?
27--- @return vim.undotree.tree
28local function treefy(ent, _tree, _last)
29  local tree = _tree or {}
30  local last = _last or nil
31
32  for idx, v in ipairs(ent) do
33    local seq = v.seq
34
35    if last then
36      table.insert(tree[last].child, seq)
37    else
38      assert(idx == 1 and not _tree)
39    end
40
41    tree[seq] = { child = {}, time = v.time }
42    if v.alt then
43      assert(last)
44      treefy(v.alt, tree, last)
45    end
46    last = seq
47  end
48
49  return tree
50end
51
52--- @class (private) vim.undotree.graph_line.base
53--- @field index integer
54--- @field node_count integer
55
56--- @class (private) vim.undotree.graph_line.node: vim.undotree.graph_line.base
57--- @field kind 'node'|'remove'|'nochange_remove'
58--- @field node integer
59
60--- @class (private) vim.undotree.graph_line.branch: vim.undotree.graph_line.base
61--- @field kind 'branch'
62--- @field node integer[]
63
64--- @class (private) vim.undotree.graph_line.remove_branch: vim.undotree.graph_line.base
65--- @field kind 'remove+branch'
66--- @field node integer
67--- @field index2 integer
68
69--- @alias vim.undotree.graph_line
70--- | vim.undotree.graph_line.node
71--- | vim.undotree.graph_line.branch
72--- | vim.undotree.graph_line.remove_branch
73
74--- @param tree vim.undotree.tree
75--- @return vim.undotree.graph_line[]
76local function tree_to_graph_lines(tree)
77  --- @type vim.undotree.graph_line[]
78  local graph_lines = {}
79
80  --- @type (integer[]|integer)[]
81  local nodes = { 0 }
82
83  while #nodes > 0 do
84    local minseq = math.huge
85    --- @type integer
86    local index
87    --- @type integer
88    local node_index
89
90    for k, v in ipairs(nodes) do
91      if type(v) == 'table' then
92        for i, j in ipairs(v) do
93          if j < minseq then
94            minseq = j
95            index = k
96            node_index = i
97          end
98        end
99      elseif v < minseq then
100        assert(type(v) == 'number')
101        minseq = v
102        index = k
103      end
104    end
105
106    local node = nodes[index]
107
108    --- @param kind 'node'|'remove'|'branch'|'nochange_remove'
109    local function add_graph_line(kind)
110      table.insert(graph_lines, { kind = kind, index = index, node_count = #nodes, node = node })
111    end
112
113    if type(node) == 'number' then
114      add_graph_line('node')
115
116      local child = tree[node].child
117      if #child == 0 then
118        if index ~= #nodes then
119          add_graph_line('remove')
120        else
121          add_graph_line('nochange_remove')
122        end
123
124        table.remove(nodes, index)
125      elseif #child == 1 then
126        nodes[index] = child[1]
127      else
128        nodes[index] = child
129      end
130    else
131      assert(type(node) == 'table')
132
133      add_graph_line('branch')
134
135      table.remove(nodes, index)
136      if #node == 2 then
137        --- @cast node [integer, integer]
138        table.insert(nodes, index, math.min(unpack(node)))
139        table.insert(nodes, index, math.max(unpack(node)))
140      elseif #node > 2 then
141        table.insert(nodes, index, node[node_index])
142        table.insert(nodes, index, node)
143        table.remove(node, node_index)
144      end
145    end
146  end
147
148  for k, v in ipairs(graph_lines) do
149    local next_line = graph_lines[k + 1]
150    if v.kind == 'remove' and next_line and next_line.kind == 'branch' then
151      v.kind = 'remove+branch'
152      v.index2 = next_line.index
153      table.remove(graph_lines, k + 1)
154    end
155  end
156
157  return graph_lines
158end
159
160--- @param time integer
161--- @return string
162local function undo_fmt_time(time)
163  if time == -1 then
164    return 'origin'
165  end
166
167  local diff = os.time() - time
168
169  if diff >= 100 then
170    if diff < (60 * 60 * 12) then
171      return os.date('%H:%M:%S', time) --[[@as string]]
172    else
173      return os.date('%Y/%m/%d %H:%M:%S', time) --[[@as string]]
174    end
175  else
176    return ('%d second%s ago'):format(diff, diff == 1 and '' or 's')
177  end
178end
179
180--- @param tree vim.undotree.tree
181--- @param graph_lines vim.undotree.graph_line[]
182--- @param buf integer
183--- @param meta {[integer]:integer}
184--- @param find_seq? integer
185--- @return integer?
186local function buf_apply_graph_lines(tree, graph_lines, buf, meta, find_seq)
187  -- As in io-buffer, not vim-buffer
188  local line_buffer = {}
189  local extmark_buffer = {}
190
191  --- @type integer?
192  local found_seq
193
194  for k, v in ipairs(graph_lines) do
195    local is_last = k == #graph_lines
196
197    --- @type string?
198    local line
199    if v.kind == 'node' then
200      -- Work around tagged union narrowing: EmmyLuaLs/emmylua-analyzer-rust#1241.
201      local seq = v.node --[[@as integer]]
202      line = ('| '):rep(v.index - 1)
203        .. '*'
204        .. (' |'):rep(v.node_count - v.index)
205        .. '    '
206        .. seq
207        .. '    ('
208        .. undo_fmt_time(tree[seq].time)
209        .. ')'
210    elseif v.kind == 'remove' then
211      line = ('| '):rep(v.index - 1) .. (' /'):rep(v.node_count - v.index)
212    elseif v.kind == 'branch' then
213      line = ('| '):rep(v.index - 1) .. '|\\' .. (' \\'):rep(v.node_count - v.index)
214    elseif v.kind == 'remove+branch' then
215      assert(v.index2)
216      if v.index2 < v.index then
217        line = ('| '):rep(v.index2 - 1)
218          .. '|\\'
219          .. (' \\'):rep(v.index - v.index2 - 1)
220          .. ' '
221          .. (' |'):rep(v.node_count - v.index)
222      else
223        line = ('| '):rep(v.index - 1)
224          .. (' /'):rep(v.index2 - v.index)
225          .. ' /|'
226          .. (' |'):rep(v.node_count - v.index2 - 1)
227      end
228    elseif v.kind == 'nochange_remove' then
229      line = nil
230    else
231      error 'unreachable'
232    end
233
234    if v.kind == 'node' then
235      table.insert(line_buffer, line)
236      table.insert(meta, v.node)
237
238      if v.node == find_seq then
239        found_seq = #meta
240      end
241    elseif line then
242      table.insert(extmark_buffer, { { line, 'Normal' } })
243    end
244
245    if next(extmark_buffer) and (v.kind == 'node' or is_last) then
246      local row = vim.api.nvim_buf_line_count(buf)
247      vim.api.nvim_buf_set_extmark(buf, ns, row - 1, 0, { virt_lines = extmark_buffer })
248      extmark_buffer = {}
249    end
250
251    if next(line_buffer) and (v.kind ~= 'node' or is_last) then
252      vim.api.nvim_buf_set_lines(buf, -1, -1, true, line_buffer)
253
254      if #line_buffer > 3 then
255        local end_ = vim.api.nvim_buf_line_count(buf) - 1
256        local start = end_ - #line_buffer + 3
257        vim.api.nvim_buf_call(buf, function()
258          local w = vim.b[buf].nvim_is_undotree
259          if vim.api.nvim_win_is_valid(w) and vim.wo[w].foldmethod == 'manual' then
260            vim.cmd.fold { range = { start, end_ } }
261          end
262        end)
263      end
264
265      line_buffer = {}
266    end
267  end
268
269  vim.api.nvim_buf_set_lines(buf, 0, 1, true, {})
270
271  return found_seq
272end
273
274---@param inbuf integer
275---@param outbuf integer
276---@return {[integer]:integer}
277local function draw(inbuf, outbuf)
278  local entries, curseq = get_undotree_entries(inbuf)
279  local tree = treefy(entries)
280  local graph_lines = tree_to_graph_lines(tree)
281
282  local meta = {}
283  vim.bo[outbuf].modifiable = true
284  vim.api.nvim_buf_set_lines(outbuf, 0, -1, true, {})
285  vim.api.nvim_buf_clear_namespace(outbuf, ns, 0, -1)
286  local curseq_line = buf_apply_graph_lines(tree, graph_lines, outbuf, meta, curseq)
287  vim.bo[outbuf].modifiable = false
288
289  vim.schedule(function()
290    if vim.api.nvim_win_is_valid(vim.b[outbuf].nvim_is_undotree) then
291      vim.api.nvim_win_set_cursor(vim.b[outbuf].nvim_is_undotree, { assert(curseq_line), 0 })
292    end
293  end)
294
295  return meta
296end
297
298--- @class vim.undotree.opts
299--- @inlinedoc
300---
301--- Buffer to draw the tree into. If omitted, a new buffer is created.
302--- @field bufnr integer?
303---
304--- Window id to display the tree buffer in. If omitted, a new window is
305--- created with {command}.
306--- @field winid integer?
307---
308--- Vimscript command to create the window. Default value is "30vnew".
309--- Only used when {winid} is nil.
310--- @field command string?
311---
312--- Title of the window. If a function, it accepts the buffer number of the
313--- source buffer as its only argument and should return a string.
314--- @field title (string|fun(bufnr:integer):string|nil)?
315
316--- Open a window that displays a textual representation of the [undo-tree], or closes the window if
317--- it is already open. Can also be shown with `:Undotree`. [:Undotree]()
318---
319--- While in the window, moving the cursor changes the undo.
320---
321--- The plugin is not loaded by default; use `:packadd` to activate it:
322--- ```
323--- :packadd nvim.undotree
324--- ```
325---
326--- @param opts vim.undotree.opts?
327--- @return boolean? Returns true if the window was already open, nil otherwise
328function M.open(opts)
329  -- The following lines of code was copied from
330  -- `vim.treesitter.dev.inspect_tree` and then modified to fit
331
332  vim.validate('opts', opts, 'table', true)
333
334  opts = opts or {}
335
336  local buf = vim.api.nvim_get_current_buf()
337
338  if vim.b[buf].nvim_undotree then
339    local w = vim.b[buf].nvim_undotree
340    if vim.api.nvim_win_is_valid(w) then
341      vim.api.nvim_win_close(w, true)
342      return true
343    end
344  elseif vim.b[buf].nvim_is_undotree then
345    local w = vim.b[buf].nvim_is_undotree
346    if vim.api.nvim_win_is_valid(w) then
347      vim.api.nvim_win_close(w, true)
348      return true
349    end
350  end
351
352  local w = opts.winid
353  if not w then
354    vim.cmd(opts.command or '30vnew')
355    w = vim.api.nvim_get_current_win()
356  end
357
358  local b = opts.bufnr
359  if b then
360    vim.api.nvim_win_set_buf(w, b)
361  else
362    b = vim.api.nvim_win_get_buf(w)
363  end
364
365  vim.b[buf].nvim_undotree = w
366  vim.b[b].nvim_is_undotree = w
367
368  local title --- @type string?
369  local opts_title = opts.title
370  if not opts_title then
371    local bufname = vim.api.nvim_buf_get_name(buf)
372    title = string.format('Undo tree for %s', vim.fn.fnamemodify(bufname, ':.'))
373  elseif type(opts_title) == 'function' then
374    title = opts_title(buf)
375  elseif type(opts_title) == 'string' then
376    title = opts_title
377  end
378
379  assert(type(title) == 'string', 'Window title must be a string')
380  vim.api.nvim_buf_set_name(b, title)
381
382  vim.wo[w][0].scrolloff = 5
383  vim.wo[w][0].wrap = false
384  vim.wo[w][0].foldmethod = 'manual'
385  vim.wo[w][0].foldenable = true
386  vim.wo[w][0].cursorline = true
387  vim.bo[b].buflisted = false
388  vim.bo[b].buftype = 'nofile'
389  vim.bo[b].bufhidden = 'wipe'
390  vim.bo[b].swapfile = false
391
392  local meta = draw(buf, b)
393
394  vim.api.nvim_win_set_cursor(w, { vim.api.nvim_buf_line_count(b), 0 })
395
396  local group = vim.api.nvim_create_augroup('nvim.undotree', {})
397
398  vim.api.nvim_win_call(w, function()
399    vim.cmd.syntax('region Comment start="(" end=")"')
400  end)
401
402  vim.api.nvim_create_autocmd('CursorMoved', {
403    group = group,
404    buffer = b,
405    callback = function()
406      local row = vim.fn.line('.')
407      vim.api.nvim_buf_call(buf, function()
408        vim.cmd.undo { meta[row], mods = { silent = true } }
409      end)
410    end,
411  })
412
413  vim.api.nvim_create_autocmd({ 'TextChanged', 'InsertLeave' }, {
414    group = group,
415    buffer = buf,
416    callback = function()
417      if not vim.api.nvim_buf_is_valid(b) then
418        return true
419      end
420
421      meta = draw(buf, b)
422
423      if vim.api.nvim_win_is_valid(w) then
424        vim.wo[w][0].foldlevel = 99
425      end
426    end,
427  })
428
429  vim.bo[b].filetype = 'nvim-undotree'
430end
431
432return M