robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
2.5 KiB81 linesraw
1if vim.g.loaded_shada_plugin then
2  return
3end
4vim.g.loaded_shada_plugin = 1
5
6local augroup = vim.api.nvim_create_augroup('nvim.shada', {})
7
8---@type fun(binstrings: string[]): string[]
9local shada_get_strings = vim.fn['shada#get_strings']
10
11---@type fun(strings: string[]): string[]
12local shada_get_binstrings = vim.fn['shada#get_binstrings']
13
14---Ensures that pattern and augroup are set correctly.
15---@param event vim.api.keyset.events|vim.api.keyset.events[]
16---@param opts vim.api.keyset.create_autocmd
17---@param fn fun(args: vim.api.keyset.create_autocmd.callback_args): boolean?
18local function def_autocmd(event, opts, fn)
19  opts = opts or {}
20  opts.group = augroup
21  opts.pattern = { '*.shada', '*.shada.tmp.[a-z]' }
22  opts.callback = function(ev)
23    if vim.v.cmdarg ~= '' then
24      error('++opt not supported')
25    end
26    fn(ev)
27  end
28  vim.api.nvim_create_autocmd(event, opts)
29end
30
31---Read shada strings from file.
32---@param file string Filename
33---@return string[] # lines from shada file
34local function read_strings(file)
35  local f = assert(io.open(file, 'rb'))
36  local strings = f:read('*a')
37  f:close()
38  return shada_get_strings(strings)
39end
40
41def_autocmd('BufReadCmd', {}, function(ev)
42  local lines = read_strings(ev.file)
43  vim.api.nvim_buf_set_lines(ev.buf, 0, -1, false, lines)
44  vim.bo[ev.buf].filetype = 'shada'
45end)
46
47def_autocmd('FileReadCmd', {}, function(ev)
48  local lines = read_strings(ev.file)
49  local lnum = vim.fn.line("'[")
50  vim.api.nvim_buf_set_lines(ev.buf, lnum, lnum, true, lines)
51end)
52
53def_autocmd('BufWriteCmd', {}, function(ev)
54  local buflines = vim.api.nvim_buf_get_lines(0, 0, -1, false)
55  local ret = vim.fn.writefile(shada_get_binstrings(buflines), ev.file, 'b')
56  if ret == 0 then
57    -- To check that we are not saving into a different file, we must compare ev.match (always an
58    -- absolute path), and not ev.file (can be relative), against nvim_buf_get_name() (always
59    -- returns an absolute path).
60    if ev.match == vim.api.nvim_buf_get_name(ev.buf) or vim.o.cpoptions:find('%+') then
61      vim.bo[ev.buf].modified = false
62    end
63  end
64end)
65
66def_autocmd({ 'FileWriteCmd', 'FileAppendCmd' }, {}, function(ev)
67  vim.fn.writefile(
68    shada_get_binstrings(
69      vim.fn.getline(
70        math.min(vim.fn.line("'["), vim.fn.line("']")),
71        math.max(vim.fn.line("'["), vim.fn.line("']"))
72      ) --[=[@as string[] ]=]
73    ),
74    ev.file,
75    ev.event == 'FileAppendCmd' and 'ab' or 'b'
76  )
77end)
78
79def_autocmd('SourceCmd', {}, function(ev)
80  vim.cmd.rshada(vim.fn.fnameescape(ev.file))
81end)