Session Management in Neovim
Did you know that Neovim comes with built-in session management?
It's not intrinsically ergonomic and requires a bit of manual configuration but it automatically saves and restores your session without any plugins. Here's all the configuration you'll ever need:
local session_file = ".git/session.vim"
vim.opt.sessionoptions = "buffers,curdir,folds,winsize"
vim.api.nvim_create_autocmd("VimEnter", {
nested = true,
callback = function(e)
local file = vim.fn.resolve(e.file .. "/" .. session_file)
if vim.fn.isdirectory(e.file) == 1 then
vim.g.opened_with_dir = true
if vim.fn.filereadable(file) == 1 then
vim.api.nvim_buf_delete(e.buf, {}) -- delete netrw buffer
vim.cmd("so " .. file)
end
end
end,
})
vim.api.nvim_create_autocmd("VimLeave", {
callback = function()
if vim.g.opened_with_dir then
vim.fn.mkdir(".git", "p")
vim.cmd("mks! " .. session_file)
end
end,
})
This configuration allows Neovim to automatically save and restore your session in .git/session.vim when closing and reopening the editor. mksession saves the session to a file and source loads the file to restore it. The autocommands VimEnter and VimLeave automate this process when the editor is opened and closed. If you'd like to configure what variables and buffers are saved per session, you can configure sessionoptions.