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 plugins. Here's all the configuration you 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 = e.file .. session_file
if vim.fn.isdirectory(e.file) == 1 then
vim.api.nvim_set_current_dir(e.file)
vim.g.opened_dir = e.file
if vim.fn.filereadable(file) == 1 then
vim.cmd("so " .. file)
end
end
end,
})
vim.api.nvim_create_autocmd("VimLeave", {
callback = function()
if vim.g.opened_dir then
vim.fn.mkdir(vim.g.opened_dir .. "/.git", "p")
vim.cmd("mks! " .. vim.g.opened_dir .. 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 on a directory. 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. All you have to do is start Neovim with nvim . or nvim your-directory/.
If you'd like to configure what variables and buffers are saved in each session, you can modify sessionoptions.
Edit: I updated some of the paths that were overcomplicated. It's also not really necessary to delete the netrw buffer so I removed that line.