Skip to content

[idea] Per-project session persistence via :mksession / SessionLoadPost #171

Description

@stanfish06

What

Automatically save and restore the window layout, open buffers, and LCD working directory per git root using Neovim's built-in :mksession. Session file is keyed to the git root path so each project gets its own saved state.

Where

New autocmd block in lua/config/options.lua (near the existing vim.g.netrw_keepdir line), or a new lua/config/session.lua module loaded from init.lua.

Why it matters

server.lua handles connecting to live Neovim instances, but nothing survives a full restart (:ZR, crash, system reboot). After a restart, all window splits, open files, and lcd state are gone. Given that the config:

…restoring a prior session eliminates the friction of re-opening files and waiting for LSPs to attach.

Suggested implementation

local function session_file()
    local git_root = vim.fn.finddir(".git", ".;")
    if git_root == "" then return nil end
    local dir = vim.fn.fnamemodify(git_root, ":p:h")
    local encoded = dir:gsub("[/\\]", "%%")
    vim.fn.mkdir(vim.fn.stdpath("data") .. "/sessions", "p")
    return vim.fn.stdpath("data") .. "/sessions/" .. encoded .. ".vim"
end

-- Save on exit
vim.api.nvim_create_autocmd("VimLeavePre", {
    callback = function()
        local f = session_file()
        if f then vim.cmd("mksession! " .. vim.fn.fnameescape(f)) end
    end,
})

-- Restore on startup (only if no files were given on the CLI)
if vim.fn.argc() == 0 then
    vim.api.nvim_create_autocmd("VimEnter", {
        once = true,
        callback = function()
            local f = session_file()
            if f and vim.fn.filereadable(f) == 1 then
                vim.cmd("source " .. vim.fn.fnameescape(f))
            end
        end,
    })
end

Pairs with #165 (auto-lcd): if cwd is always the git root on BufEnter, the session file lookup is stable across working-directory changes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions