dotfiles/.config/nvim/lua/session.lua

48 lines
1.4 KiB
Lua
Raw Normal View History

2024-10-15 18:57:02 +00:00
local session_dir = vim.env.HOME .. "/.local/share/nvim/sessions/"
local function session_file(workdir)
local basename = workdir:gsub("([ \\%%~$])", "\\%1"):gsub("/", "\\%%")
return session_dir .. basename
end
local function unescape(session)
return session:sub(#session_dir+1):gsub("%%", "/")
end
local function save_session()
vim.cmd("silent !mkdir -p " .. session_dir)
vim.cmd("mksession! " .. session_file(vim.fn.getcwd()))
end
local function load_session(dir)
vim.cmd.source(session_file(dir))
end
local function del_session(dir)
vim.cmd("silent !rm " .. session_file(dir))
end
local function list_sessions()
local sessions = vim.split(vim.fn.glob(session_dir .. "*"), '\n', { trimempty=true })
local dated_sessions = {}
for _, item in pairs(sessions) do
table.insert(dated_sessions, { unescape(item), vim.fn.getftime(item) })
end
table.sort(dated_sessions, function(l, r) return l[2] > r[2] end)
return dated_sessions
end
vim.api.nvim_create_autocmd({"BufWritePost"}, {
callback = save_session
})
vim.api.nvim_create_user_command("SessionSave", function(opts) save_session(opts.args) end, { nargs=0 })
vim.api.nvim_create_user_command("SessionLoad", function(opts) load_session(opts.args) end, { nargs=1 })
vim.api.nvim_create_user_command("SessionDel", function(opts) del_session(opts.args) end, { nargs=1 })
return {
load_session = load_session,
save_session = save_session,
list_sessions = list_sessions,
}