Vim Sessions
Tip 23. Saving and Restoring Sessions
Sometimes you have to restart Vim. Usually this means losing your list of open buffers, as well as any open tab pages or windows. Fortunately, Vim’s session management allows you to save your current workspace so that you can restore it again later.
Saving and Loading Sessions Manually
:mksession!
vim -S
:source Session.vim
:mksession! mysession.vim
vim -S mysession.vim
:source mysession.vim
Vim sessions 101 for beginners.
Saving Sessions Automatically
If you like the idea of having your session recorded automatically when using Neovim, you should try installing the auto-session plugin.
Create a auto-session.lua file in your plugin config folder:
return {
"rmagatti/auto-session",
config = function()
local auto_session = require("auto-session")
auto_session.setup({
auto_restore = false,
suppress_dirs = { "~/", "~/Dev/", "~/Downloads", "~/Documents", "~/Desktop/" },
})
local keymap = vim.keymap
keymap.set("n", "<leader>wr", "<cmd>SessionRestore<CR>", { desc = "Restore session for cwd" }) -- restore last workspace session for current directory
keymap.set("n", "<leader>ws", "<cmd>SessionSave<CR>", { desc = "Save session for auto session root dir" }) -- save workspace session for current working directory
keymap.set("n", "<leader>wa", "<cmd>SessionToggleAutoSave<CR>", { desc = "Toggle autosave" })
end,
}
After installation, your Neovim should have the following behaviors:
- When starting
nvim
with no arguments, AutoSession will try to restore an existing session for the currentcwd
if one exists - When starting
nvim .
(or another directory), AutoSession will not restore the session for that directory - When starting
nvim some_file.txt
(or multiple files), by default, AutoSession won't do anything - Even after starting
nvim
with a file argument, a session can still be manually restored by running:SessionRestore
- Any session saving and restoration takes into consideration the current working directory
cwd
- When piping to
nvim
, e.g:cat myfile | nvim
, AutoSession won't do anything
That's to say, use nvim
to get back to where you left off, and use nvim .
to start anew with nvim-tree explorer.
WARNING
Please note that if there are errors in your config, restoring the session might fail, if that happens, auto session will then disable auto saving for the current session. Manually saving a session can still be done by calling :SessionSave
.
All session files are saved at nvim-data/sessions/
.