auto-session

repository·main·Indexed 23 days ago

https://github.com/rmagatti/auto-session

A Neovim plugin that automatically saves and restores workspace sessions (buffers, windows, and layout) based on the current working directory and git branch. It features support for session pickers (Telescope, snacks, fzf, select), directory filtering via allowed and suppressed lists, and command hooks for automating session lifecycle stages. Requires Neovim >= 0.10.

Tokens
4.2K
Snippets
11
Records
16
Agent score
34%

What's inside auto-session

  1. Track directory changes (cwd_change_handling)

    main

    By default, AutoSession does not track cwd changes. When enabled via cwd_change_handling = true, changing the directory with :cd triggers a workflow:

    1. Pre-change: Saves the current session, clears all buffers (%bw!), clears jumps, and runs pre_cwd_changed_cmds.
    2. Post-change: Restores the session for the new cwd and runs post_cwd_changed_cmds.

    This prevents buffer/jump bleeding between different project sessions.

    opts = {
      cwd_change_handling = true,
    
      pre_cwd_changed_cmds = {
        "tabdo NERDTreeClose", -- Close NERDTree before saving session
      },
    
      post_cwd_changed_cmds = {
        function()
          require("lualine").refresh() -- example refreshing the lualine status line _after_ the cwd changes
        end,
      },
    }
  2. How AutoSession works

    main

    AutoSession automates the management of your workspace state based on your current working directory (cwd):

    1. On Startup: AutoSession checks if a session exists for the current cwd. If found, it reopens all buffers and windows associated with that directory.
    2. On Exit: When you quit Neovim, AutoSession automatically saves a session for the current cwd so you can resume your work later.

    This behavior can be customized using auto_save, auto_restore, and auto_create settings.

  3. Configure AutoSession sessionoptions

    main

    For the best experience with session restoration (including folds, terminals, and window positions), it is recommended to update your Neovim sessionoptions setting.

    -- Lua
    vim.o.sessionoptions = "blank,buffers,curdir,folds,help,tabpages,winsize,winpos,terminal,localoptions"

    Or using VimL:

    set sessionoptions+=winpos,terminal,folds
  4. Install AutoSession via Lazy.nvim

    main

    To install AutoSession using the lazy.nvim plugin manager, add the following configuration to your plugin list. Setting lazy = false is required to ensure sessions are restored correctly on startup. You can configure suppressed_dirs to prevent session creation in specific directories like your home folder or downloads.

    return {
      "rmagatti/auto-session",
      lazy = false,
    
      ---enables autocomplete for opts
      ---@module "auto-session"
      ---@type AutoSession.Config
      opts = {
        suppressed_dirs = { "~/", "~/Projects", "~/Downloads", "/" },
        -- log_level = 'debug',
      },
    }
  5. Disable AutoSession

    main

    If you need to disable AutoSession based on specific conditions (e.g., when using Firenvim or VSCode), you can use the following methods:

    1. Using a plugin manager (e.g., lazy.nvim): Use the cond property to prevent the plugin from loading.

    2. Using VimScript: Set the g:auto_session_enabled global variable to v:false.

    3. Using CLI flag: Pass the command directly when starting Neovim.

    -- lazy.nvim example
    return {
      "rmagatti/auto-session",
      lazy = false,
      cond = not vim.g.started_by_firenvim and not vim.g.vscode,
    }
    " VimScript example
    if exists('g:started_by_firenvim')
      let g:auto_session_enabled = v:false
    endif
    # CLI example
    nvim --cmd "let g:auto_session_enabled = v:false"
  6. Configure the Session Picker (session_lens)

    main

    AutoSession supports advanced pickers like Telescope, snacks.nvim, and Fzf-Lua. If none are installed, it falls back to vim.ui.select. Use :AutoSession search to launch the picker.

    Keybindings in the Picker

    When the picker is open, the following default mappings are available:

    • <CR>: Load the highlighted session.
    • <C-s>: Swap to the previously opened session (useful for switching between two projects).
    • <C-d>: Delete the highlighted session.
    • <C-y>: Copy the highlighted session.

    Configuration Example

    Configure the picker type, custom mappings, and picker-specific options (like Telescope themes or Snacks layouts) via the session_lens key in your opts.

    return {
      "rmagatti/auto-session",
      lazy = false,
      keys = {
        { "<leader>wr", "<cmd>AutoSession search<CR>", desc = "Session search" },
        { "<leader>ws", "<cmd>AutoSession save<CR>", desc = "Save session" },
        { "<leader>wa", "<cmd>AutoSession toggle<CR>", desc = "Toggle autosave" },
      },
    
      ---@module "auto-session"
      ---@type AutoSession.Config
      opts = {
        session_lens = {
          picker = nil, -- "telescope"|"snacks"|"fzf"|"select"|nil
          mappings = {
            delete_session = { "i", "<C-d>" },
            alternate_session = { "i", "<C-s>" },
            copy_session = { "i", "<C-y>" },
          },
          picker_opts = {
            -- Pass specific picker options here (e.g., Telescope themes or Snacks layouts)
          },
          load_on_setup = true,
        },
      },
    }
  7. Configure Git integration for sessions

    main

    AutoSession can integrate with Git to improve session naming and restoration:

    • git_use_branch_name = true: Includes the current Git branch in the session name.
    • git_auto_restore_on_branch_change = true: Automatically restores the session associated with the branch you just switched to. If you have modified files, AutoSession will prompt you to close them before restoring.
    opts = {
      git_use_branch_name = true,
      git_auto_restore_on_branch_change = true,
    }
  8. Control session auto-saving with allowed and suppressed directories

    main

    You can restrict where AutoSession automatically saves sessions using allowed_dirs and suppressed_dirs. Both accept tables of strings and support glob patterns.

    • allowed_dirs: If set, sessions are only auto-saved in matching directories.
    • suppressed_dirs: If set, sessions in these directories will never be auto-saved.

    Glob Pattern Syntax

    • *: Matches characters in a single directory level (e.g., /projects/* matches /projects/foo but not /projects/foo/bar).
    • **: Matches characters including directory separators (e.g., /projects/** matches all subdirectories).
    • ?: Matches exactly one character.
    • ~: Expands to your home directory.
    opts = {
      allowed_dirs = { "/some/dir/", "/projects/*", "~/work/**" },
      suppressed_dirs = { "/projects/secret" },
    }
  9. Configure AutoSession options

    main

    AutoSession is highly configurable via the opts table passed to .setup(). Key configuration groups include:

    Saving / Restoring

    • enabled: Enables/disables auto creating, saving and restoring.
    • auto_save: Enables/disables auto saving session on exit.
    • auto_restore: Enables/disables auto restoring session on start.
    • auto_create: Enables/disables auto creating new session files. Can be a function returning a boolean.
    • auto_restore_last_session: If true, loads the last saved session if no session exists for the current cwd.
    • cwd_change_handling: Automatically save/restore sessions when changing directories.
    • single_session_mode: Keeps all work in one session regardless of cwd changes. (Note: Does not work with cwd_change_handling).

    Filtering

    • suppressed_dirs: Directories where session restore/create is suppressed.
    • allowed_dirs: Directories where session restore/create is only allowed.
    • bypass_save_filetypes: Filetypes to bypass auto save when they are the only buffer open (e.g., dashboards).
    • close_filetypes_on_save: Buffers with these filetypes will be closed before saving.
    • close_unsupported_windows: Closes windows not backed by a normal file before autosaving.
    • preserve_buffer_on_restore: A function that returns true if a buffer should be preserved during restoration.

    Git / Session Naming

    • git_use_branch_name: Includes the git branch name in the session name. Can be a function.
    • git_auto_restore_on_branch_change: Auto-restores the session when the git branch changes (requires git_use_branch_name).
    • custom_session_tag: A function that returns a string to be used as part of the session name.

    Deleting

    • auto_delete_empty_sessions: Deletes the session if only unnamed/empty buffers are present during autosave.
    • purge_after_minutes: Asynchronously deletes sessions older than this value on startup (requires Neovim >= 0.10).

    Extra Data

    • save_extra_data: A function that returns extra data to be saved with the session.
    • restore_extra_data: A function called when extra data is restored.

    Session Lens (Picker)

    • picker: Choose between "telescope", "snacks", "fzf", or "select". Defaults to vim.ui.select if nil.
    • previewer: 'summary', 'active_buffer', or a custom function.
    • mappings: Define keys for delete_session, alternate_session, and copy_session within the mappings table.
  10. Save and restore custom data with save_extra_data and restore_extra_data

    main

    You can persist arbitrary data (like DAP breakpoints, quickfix lists, or other plugin states) by implementing the save_extra_data and restore_extra_data functions in your configuration.

    • save_extra_data(session_name): Should return a string (e.g., JSON encoded) or a table representing the data to be saved.
    • restore_extra_data(session_name, extra_data): Receives the data saved by the previous function and is responsible for restoring the state.