88 lines
1.9 KiB
Lua
Raw Normal View History

2021-07-12 10:47:09 +02:00
local Config = require("persistence.config")
local uv = vim.uv or vim.loop
2021-07-02 08:55:37 +02:00
local M = {}
---@type string?
M._current = nil
2021-07-02 08:55:37 +02:00
local e = vim.fn.fnameescape
function M.current()
local name = vim.fn.getcwd():gsub("[\\/:]", "%%")
2021-07-12 10:47:09 +02:00
return Config.options.dir .. name .. ".vim"
2021-07-02 08:55:37 +02:00
end
2021-07-12 10:47:09 +02:00
function M.setup(opts)
Config.setup(opts)
M.start()
end
function M.fire(event)
vim.api.nvim_exec_autocmds("User", {
pattern = "Persistence" .. event,
})
end
2021-07-02 08:55:37 +02:00
function M.start()
M._current = M.current()
vim.api.nvim_create_autocmd("VimLeavePre", {
group = vim.api.nvim_create_augroup("persistence", { clear = true }),
callback = function()
M.fire("SavePre")
if not Config.options.save_empty then
local bufs = vim.tbl_filter(function(b)
if vim.bo[b].buftype ~= "" or vim.bo[b].filetype == "gitcommit" or vim.bo[b].filetype == "gitrebase" then
return false
end
return vim.api.nvim_buf_get_name(b) ~= ""
end, vim.api.nvim_list_bufs())
if #bufs == 0 then
return
end
end
M.save()
M.fire("SavePost")
end,
})
2021-07-02 08:55:37 +02:00
end
function M.stop()
M._current = nil
pcall(vim.api.nvim_del_augroup_by_name, "persistence")
2021-07-02 08:55:37 +02:00
end
function M.save()
vim.cmd("mks! " .. e(M._current or M.current()))
2021-07-02 08:55:37 +02:00
end
---@param opts? { last?: boolean, file?: string }
function M.load(opts)
opts = opts or {}
local file = opts.file or opts.last and M.last() or M.current()
if file and vim.fn.filereadable(file) ~= 0 then
M.fire("LoadPre")
vim.cmd("silent! source " .. e(file))
M.fire("LoadPost")
if M._current then
M.start()
end
2021-07-02 08:55:37 +02:00
end
end
---@return string[]
2021-07-02 08:55:37 +02:00
function M.list()
local sessions = vim.fn.glob(Config.options.dir .. "*.vim", true, true)
table.sort(sessions, function(a, b)
return uv.fs_stat(a).mtime.sec > uv.fs_stat(b).mtime.sec
end)
return sessions
end
function M.last()
return M.list()[1]
2021-07-02 08:55:37 +02:00
end
return M