svg

Make Lazyvim Write Session.vim In CWD

neovim lazyvim tmux

I use LazyVim combined with Tmux, specifically utilizing the tmux-resurrect and tmux-continuum plugins to automatically save and restore my terminal sessions.

According to the tmux-resurrect documentation, Neovim sessions can be restored automatically if a Session.vim file is present in the working directory. However, LazyVim uses the persistence.nvim plugin to manage sessions, which doesn’t create this file by default.

To bridge this gap, I created an autocommand that generates a Session.vim file whenever I exit Neovim. Add the following code to $HOME/.config/nvim/lua/config/autocmds.lua:

-- Generate Session.vim in the CWD so tmux-resurrect can restore the session
vim.api.nvim_create_autocmd("VimLeave", {
  group = vim.api.nvim_create_augroup("PersistenceCWD", { clear = true }),
  callback = function()
    local session_file = "Session.vim"

    -- The file content: a command to trigger Session.nvim's load function
    local content = "lua require('persistence').load()"

    local f = io.open(session_file, "w")
    if f then
      f:write(content)
      f:close()
    end
  end,
})

Now, whenever I launch Tmux, it successfully auto-restores my Neovim session.

Note: To keep my repositories clean, I have globally excluded Session.vim via my $HOME/.config/git/ignore file, which I manage using home-manager.