### Setup Auto-Session with Other Plugin Managers Source: https://github.com/rmagatti/auto-session/blob/main/doc/auto-session.txt This snippet shows how to set up the Auto-Session plugin when using a plugin manager other than lazy.nvim. It requires calling the `setup` function with an optional configuration table. ```lua require("auto-session").setup({}) ``` -------------------------------- ### Install Auto-Session with Lazy.nvim Source: https://github.com/rmagatti/auto-session/blob/main/doc/auto-session.txt This code snippet demonstrates how to install the Auto-Session plugin using the lazy.nvim package manager. It includes basic configuration options such as suppressing certain directories and setting the log level. ```lua return { "rmagatti/auto-session", lazy = false, ---enables autocomplete for opts ---@module "auto-session" ---@type AutoSession.Config opts = { suppressed_dirs = { "~//", "~//Projects", "~//Downloads", "/" }, -- log_level = 'debug', }, } ``` -------------------------------- ### Lazy.nvim Installation for AutoSession Source: https://github.com/rmagatti/auto-session/blob/main/README.md This code snippet demonstrates how to install the AutoSession Neovim plugin using the Lazy.nvim package manager. It configures AutoSession with suppressed directories and an optional debug log level. ```lua return { "rmagatti/auto-session", lazy = false, -- enables autocomplete for opts --@module "auto-session" --@type AutoSession.Config opts = { suppressed_dirs = { "~.", "~/Projects", "~/Downloads", "/" }, -- log_level = 'debug', }, } ``` -------------------------------- ### Enable Auto Session Restore (Lua) Source: https://github.com/rmagatti/auto-session/wiki/Auto-restore-last-session This configuration enables the automatic restoration of the last session when Neovim starts. It's a simple boolean flag within the auto-session setup. ```lua require("auto-session").setup { auto_restore_last_session = true, } ``` -------------------------------- ### Manual Setup and Configuration for AutoSession Source: https://context7.com/rmagatti/auto-session/llms.txt Manually sets up and configures the AutoSession Neovim plugin without a plugin manager. This includes enabling core features like auto-saving and restoring, defining session root directories, and specifying allowed/suppressed directories, filetypes to bypass, and git integration settings. ```lua require("auto-session").setup({ enabled = true, auto_save = true, auto_restore = true, auto_create = true, root_dir = vim.fn.stdpath("data") .. "/sessions/", suppressed_dirs = { "~.", "~/Downloads" }, allowed_dirs = { "~/projects/*", "~/work/**" }, bypass_save_filetypes = { "alpha", "dashboard", "snacks_dashboard" }, git_use_branch_name = true, git_auto_restore_on_branch_change = true, session_lens = { picker = "telescope", -- "telescope"|"snacks"|"fzf"|"select" load_on_setup = true, }, }) ``` -------------------------------- ### Disable AutoSession via Command-line Argument Source: https://github.com/rmagatti/auto-session/blob/main/README.md This command-line example shows how to disable the AutoSession plugin when starting Neovim. The `--cmd` argument allows setting the `g:auto_session_enabled` option to `v:false` before the plugin is loaded. ```sh nvim --cmd "let g:auto_session_enabled = v:false" ``` -------------------------------- ### Setup AutoSession with Lazy.nvim Source: https://context7.com/rmagatti/auto-session/llms.txt Configures the AutoSession Neovim plugin using the Lazy.nvim package manager. It specifies options for suppressed directories and logging level, ensuring sessions are managed according to the defined preferences. ```lua return { "rmagatti/auto-session", lazy = false, ---@module "auto-session" ---@type AutoSession.Config opts = { suppressed_dirs = { "~.", "~/Projects", "~/Downloads", "/" }, log_level = "error", }, } ``` -------------------------------- ### Filter Directories for AutoSession Operations (Lua) Source: https://context7.com/rmagatti/auto-session/llms.txt This snippet shows how to configure AutoSession to control which directories it operates in using glob patterns for `allowed_dirs` and `suppressed_dirs`. It also includes an example of a custom `auto_create` function to conditionally create sessions, such as only for Git repositories. ```lua require("auto-session").setup({ -- Only auto-save in these directories (supports globs) allowed_dirs = { "~/projects/*", -- Direct children of ~/projects "~/work/**", -- All descendants of ~/work "/var/www/*", -- Direct children of /var/www }, -- Never auto-save in these directories suppressed_dirs = { "~/", "~/Downloads", "/tmp", "/", "~/projects/secret", -- Override allowed pattern }, -- Custom auto_create logic (alternative to allowed_dirs) auto_create = function() local cwd = vim.fn.getcwd() -- Only create sessions for git repositories return vim.fn.isdirectory(cwd .. "/.git") == 1 end, }) ``` -------------------------------- ### Display Current Session Name in Lualine Statusline (Lua) Source: https://github.com/rmagatti/auto-session/blob/main/doc/auto-session.txt This example shows how to integrate auto-session with the Lualine statusline plugin to display the current session name. It uses the `current_session_name(true)` function to show only the last directory in the path. ```lua require("lualine").setup({ options = { theme = "tokyonight", }, sections = { lualine_x = { function() return require("auto-session.lib").current_session_name(true) end, }, }, }) ``` -------------------------------- ### Disable AutoSession Plugin via Command Line Source: https://github.com/rmagatti/auto-session/blob/main/doc/auto-session.txt This shell command shows how to disable the 'auto-session' plugin when starting Neovim. By using the `--cmd` option, you can execute a Vim command, such as setting `g:auto_session_enabled` to false, before the configuration is fully loaded. ```sh nvim --cmd "let g:auto_session_enabled = v:false" ``` -------------------------------- ### Configure Session Lens UI Integration Source: https://github.com/rmagatti/auto-session/blob/main/doc/auto-session.txt Customize the Session Lens UI, including the picker (Telescope, fzf, etc.), picker options, previewer type, and key mappings for session actions within the picker. ```lua session_lens = { picker = "telescope", load_on_setup = true, picker_opts = { -- Example for Telescope layout_strategy = "vertical", sorting_strategy = "ascending", }, previewer = "summary", mappings = { delete_session = { "i", "" }, alternate_session = { "i", "" }, copy_session = { "i", "" }, }, } ``` -------------------------------- ### Configure AutoSession Picker Options Source: https://github.com/rmagatti/auto-session/blob/main/doc/auto-session.txt This snippet shows how to configure the session picker options for AutoSession. It demonstrates setting allowed and suppressed directories using glob patterns. Glob patterns like '*', '**', '?', and '~' are supported for flexible directory matching. ```lua opts = { allowed_dirs = { "/some/dir/", "/projects/*", "~/work/**" }, suppressed_dirs = { "/projects/secret" }, } ``` -------------------------------- ### Get Current Session Name (Lua) Source: https://context7.com/rmagatti/auto-session/llms.txt Retrieves the name of the currently active session. It can return the full path for auto-saved sessions or just the last directory name for convenience, making it ideal for statusline integrations. ```lua local Lib = require("auto-session.lib") -- Get full session name (full path for auto sessions) local full_name = Lib.current_session_name() -- Returns: "/home/user/projects/myapp" -- Get shortened name (last directory only) local short_name = Lib.current_session_name(true) -- Returns: "myapp" -- Lualine integration require("lualine").setup({ sections = { lualine_x = { function() return require("auto-session.lib").current_session_name(true) end, }, }, }) ``` -------------------------------- ### Configure Session Saving Options Source: https://github.com/rmagatti/auto-session/blob/main/doc/auto-session.txt Customize how sessions are saved, including which filetypes to close before saving, whether to close unsupported windows, and options for preserving buffers. ```lua close_filetypes_on_save = { "checkhealth" }, close_unsupported_windows = true, preserve_buffer_on_restore = nil ``` -------------------------------- ### Configure Session Picker and Keymaps in Lua Source: https://github.com/rmagatti/auto-session/blob/main/README.md This Lua configuration snippet sets up the Auto-Session plugin, defining keybindings for session management and configuring the session picker. It allows integration with Telescope, Snacks, or Fzf-Lua, with fallback to vim.ui.select. Picker-specific options can also be customized. ```lua return { "rmagatti/auto-session", lazy = false, keys = { -- Will use Telescope if installed or a vim.ui.select picker otherwise { "wr", "AutoSession search", desc = "Session search" }, { "ws", "AutoSession save", desc = "Save session" }, { "wa", "AutoSession toggle", desc = "Toggle autosave" }, }, --- enables autocomplete for opts --@module "auto-session" --@type AutoSession.Config opts = { -- The following are already the default values, no need to provide them if these are already the settings you want. session_lens = { picker = nil, -- "telescope"|"snacks"|"fzf"|"select"|nil Pickers are detected automatically but you can also manually choose one. Falls back to vim.ui.select mappings = { -- Mode can be a string or a table, e.g. {"i", "n"} for both insert and normal mode delete_session = { "i", "" }, alternate_session = { "i", "" }, copy_session = { "i", "" }, }, picker_opts = { -- For Telescope, you can set theme options here, see: -- https://github.com/nvim-telescope/telescope.nvim/blob/master/doc/telescope.txt#L112 -- https://github.com/nvim-telescope/telescope.nvim/blob/master/lua/telescope/themes.lua -- -- border = true, -- layout_config = { -- width = 0.8, -- Can set width and height as percent of window -- height = 0.5, -- }, -- For Snacks, you can set layout options here, see: -- https://github.com/folke/snacks.nvim/blob/main/docs/picker.md#%EF%B8%8F-layouts -- -- preset = "dropdown", -- preview = false, -- layout = { -- width = 0.4, -- height = 0.4, -- }, -- For Fzf-Lua, picker_opts just turns into winopts, see: -- https://github.com/ibhagwan/fzf-lua#customization -- -- height = 0.8, -- width = 0.50, }, -- Telescope only: If load_on_setup is false, make sure you use `:AutoSession search` to open the picker as it will initialize everything first load_on_setup = true, }, }, } ``` -------------------------------- ### Configure Session Lens Previewer and Mappings (Lua) Source: https://github.com/rmagatti/auto-session/blob/main/README.md This snippet shows how to configure the Session Lens plugin's previewer and mappings within the Auto Session configuration. The previewer can be set to 'summary', 'active_buffer', or a custom function. Mappings are defined for actions like deleting, alternating, and copying sessions, specifying the mode and keybindings. ```lua previewer = "summary", -- 'summary'|'active_buffer'|function - How to display session preview. 'summary' shows a summary of the session, 'active_buffer' shows the contents of the active buffer in the session, or a custom function --- --@type SessionLensMappings mappings = { -- Mode can be a string or a table, e.g. {"i", "n"} for both insert and normal mode delete_session = { "i", "" }, -- mode and key for deleting a session from the picker alternate_session = { "i", "" }, -- mode and key for swapping to alternate session from the picker copy_session = { "i", "" }, -- mode and key for copying a session from the picker } ``` -------------------------------- ### AutoSession Commands Source: https://github.com/rmagatti/auto-session/blob/main/README.md This section lists the available commands for the AutoSession plugin. These commands allow users to save, restore, delete, enable, disable, and purge sessions. Some commands also support interactive selection via pickers. ```viml :AutoSession save " saves a session based on the `cwd` in `root_dir` :AutoSession save my_session " saves a session called `my_session` in `root_dir` :AutoSession restore " restores a session based on the `cwd` from `root_dir` :AutoSession restore my_session " restores `my_session` from `root_dir` :AutoSession delete " deletes a session based on the `cwd` from `root_dir` :AutoSession delete my_session " deletes `my_session` from `root_dir` :AutoSession disable " disables autosave :AutoSession enable " enables autosave (still does all checks in the config) :AutoSession toggle" toggles autosave :AutoSession purgeOrphaned " removes all orphaned sessions with no working directory left. :AutoSession search " opens a session picker, see Config.session_lens.picker :AutoSession deletePicker " opens a vim.ui.select picker to choose a session to delete. ``` -------------------------------- ### Configure AutoSession Argument Handling (Lua) Source: https://github.com/rmagatti/auto-session/wiki/Argument-Handling Sets configuration options for AutoSession to control its behavior when Neovim is launched with directory or file arguments. `args_allow_single_directory` determines if session logic applies to single directory launches, while `args_allow_files_auto_save` controls session saving with file arguments. ```lua opts = { args_allow_single_directory = true, -- boolean Follow normal session save/load logic if launched with a single directory as the only argument args_allow_files_auto_save = false, -- boolean|function Allow saving a session even when launched with a file argument (or multiple files/dirs). It does not load any existing session first. While you can just set this to true, you probably want to set it to a function that decides when to save a session when launched with file args. See documentation for more detail } ``` -------------------------------- ### Configure AutoSession with Session Picker Options (Lua) Source: https://github.com/rmagatti/auto-session/blob/main/doc/auto-session.txt This Lua code snippet demonstrates how to configure the AutoSession plugin, specifically focusing on the `session_lens` options. It shows how to enable the plugin, define keybindings for session management, and customize the session picker's behavior for different backend plugins like Telescope, snacks.nvim, and Fzf-Lua. ```lua return { "rmagatti/auto-session", lazy = false, keys = { -- Will use Telescope if installed or a vim.ui.select picker otherwise { "wr", "AutoSession search", desc = "Session search" }, { "ws", "AutoSession save", desc = "Save session" }, { "wa", "AutoSession toggle", desc = "Toggle autosave" }, }, ---enables autocomplete for opts ---@module "auto-session" ---@type AutoSession.Config opts = { -- The following are already the default values, no need to provide them if these are already the settings you want. session_lens = { picker = nil, -- "telescope"|"snacks"|"fzf"|"select"|nil Pickers are detected automatically but you can also manually choose one. Falls back to vim.ui.select mappings = { -- Mode can be a string or a table, e.g. {"i", "n"} for both insert and normal mode delete_session = { "i", "" }, alternate_session = { "i", "" }, copy_session = { "i", "" }, }, picker_opts = { -- For Telescope, you can set theme options here, see: -- https://github.com/nvim-telescope/telescope.nvim/blob/master/doc/telescope.txt#L112 -- https://github.com/nvim-telescope/telescope.nvim/blob/master/lua/telescope/themes.lua -- -- border = true, -- layout_config = { -- width = 0.8, -- Can set width and height as percent of window -- height = 0.5, -- }, -- For Snacks, you can set layout options here, see: -- https://github.com/folke/snacks.nvim/blob/main/docs/picker.md#%EF%B8%8F-layouts -- -- preset = "dropdown", -- preview = false, -- layout = { -- width = 0.4, -- height = 0.4, -- }, -- For Fzf-Lua, picker_opts just turns into winopts, see: -- https://github.com/ibhagwan/fzf-lua#customization -- -- height = 0.8, -- width = 0.50, }, -- Telescope only: If load_on_setup is false, make sure you use `:AutoSession search` to open the picker as it will initialize everything first load_on_setup = true, }, }, } ``` -------------------------------- ### Configure AutoSession Directory Change Handling Source: https://github.com/rmagatti/auto-session/blob/main/doc/auto-session.txt This snippet demonstrates how to configure AutoSession to handle current working directory (cwd) changes. It includes enabling `cwd_change_handling` and defining custom commands to run before (`pre_cwd_changed_cmds`) and after (`post_cwd_changed_cmds`) the cwd changes. ```lua 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, }, } ``` -------------------------------- ### Configure Argument Handling for Session Operations Source: https://github.com/rmagatti/auto-session/blob/main/doc/auto-session.txt Control how the plugin handles command-line arguments during session save and load operations. This includes allowing single directory arguments and files for auto-saving. ```lua args_allow_single_directory = true, args_allow_files_auto_save = false ``` -------------------------------- ### Search and Delete Picker Commands in VimL Source: https://github.com/rmagatti/auto-session/blob/main/doc/auto-session.txt Provides commands to interactively search for and delete sessions. The search command opens a session picker, while deletePicker opens a selection UI for deletion. ```viml :AutoSession search " opens a session picker, see Config.session_lens.picker :AutoSession deletePicker " opens a vim.ui.select picker to choose a session to delete. ``` -------------------------------- ### Configure Miscellaneous Auto-Session Settings Source: https://github.com/rmagatti/auto-session/blob/main/doc/auto-session.txt Adjust various other settings such as log level, session storage directory, notifications, error handling, LSP behavior, and legacy command definitions. ```lua log_level = "error", root_dir = vim.fn.stdpath("data") .. "/sessions/", show_auto_restore_notif = false, restore_error_handler = nil, continue_restore_on_error = true, lsp_stop_on_restore = false, lazy_support = true, legacy_cmds = true ``` -------------------------------- ### Open Session Picker (Lua) Source: https://context7.com/rmagatti/auto-session/llms.txt Opens an interactive picker to browse, load, or delete saved sessions. It intelligently uses available picker plugins like Telescope, Snacks, or Fzf-Lua, falling back to a basic `vim.ui.select` if none are found. Configuration options allow specifying the picker and its behavior. ```lua local auto_session = require("auto-session") -- Open session picker auto_session.search() -- Configure picker in setup require("auto-session").setup({ session_lens = { picker = "telescope", -- Force specific picker load_on_setup = true, -- Register Telescope extension at startup previewer = "summary", -- "summary"|"active_buffer"|function picker_opts = { -- Telescope-specific options layout_config = { width = 0.8, height = 0.5, }, }, mappings = { delete_session = { "i", "" }, alternate_session = { "i", "" }, copy_session = { "i", "" }, }, }, }) -- Command usage -- :AutoSession search -- Keybinding example vim.keymap.set("n", "wr", "AutoSession search", { desc = "Session search" }) ``` -------------------------------- ### Configure Session Control Directory and Filename (Lua) Source: https://github.com/rmagatti/auto-session/blob/main/README.md This snippet demonstrates how to configure the session control directory and filename for the Session Lens plugin. The `control_dir` specifies the location for control files, and `control_filename` sets the name of the session control file, typically used for alternating between sessions. ```lua --- --@type SessionControl session_control = { control_dir = vim.fn.stdpath("data") .. "/auto_session/", -- Auto session control dir, for control files, like alternating between two sessions with session-lens control_filename = "session_control.json", -- File name of the session control file } ``` -------------------------------- ### Configure Directory Change Handling in AutoSession (Lua) Source: https://context7.com/rmagatti/auto-session/llms.txt This configuration enables automatic session saving and restoring when changing directories using `:cd`. It includes options to run custom commands or functions before and after the directory change, allowing for cleanup or re-initialization of project-specific settings. ```lua require("auto-session").setup({ cwd_change_handling = true, -- Run before directory change pre_cwd_changed_cmds = { "tabdo NERDTreeClose", function() -- Clean up before changing directories vim.lsp.stop_client(vim.lsp.get_clients()) end, }, -- Run after directory change post_cwd_changed_cmds = { function() require("lualine").refresh() -- Re-initialize project-specific settings end, }, }) ``` -------------------------------- ### Configure Git Integration for Session Naming Source: https://github.com/rmagatti/auto-session/blob/main/doc/auto-session.txt Integrate Git information into session names. Options include using the branch name and automatically restoring sessions when the branch changes. A custom function can also provide session names. ```lua git_use_branch_name = false, git_auto_restore_on_branch_change = false, custom_session_tag = nil ``` -------------------------------- ### Configure Command Hooks (Lua) Source: https://context7.com/rmagatti/auto-session/llms.txt Allows executing custom Lua functions or Vim commands at specific points in the session lifecycle, such as before saving, after saving, before restoring, after restoring, or when no session is restored. This enables advanced customization and integration with other plugins. ```lua require("auto-session").setup({ -- Execute before saving a session (return false to cancel auto-save) pre_save_cmds = { "tabdo NERDTreeClose", function(session_name) if vim.bo.filetype == "oil" then return false -- Don't auto-save if oil.nvim is active end end, }, -- Execute after saving a session post_save_cmds = { function(session_name) vim.notify("Session saved: " .. session_name) end, }, -- Execute before restoring (return false to cancel auto-restore) pre_restore_cmds = { function(session_name) -- Clear any existing state before restore vim.cmd("silent! %bdelete") end, }, -- Execute after restoring a session post_restore_cmds = { function() -- Restore nvim-tree after session restore local nvim_tree_api = require("nvim-tree.api") nvim_tree_api.tree.open() nvim_tree_api.tree.change_root(vim.fn.getcwd()) end, }, -- Execute when no session is restored no_restore_cmds = { function(is_startup) if is_startup then -- Show dashboard or start screen vim.cmd("Alpha") end end, }, -- Save extra data with session (for quickfix, etc.) save_extra_cmds = { function() local qflist = vim.fn.getqflist() if #qflist == 0 then return nil end return "copen" -- Reopen quickfix on restore end, }, }) ``` -------------------------------- ### Configure Session Lens Control Directory Source: https://github.com/rmagatti/auto-session/blob/main/doc/auto-session.txt Specify the directory and filename for session control files used by Session Lens. This is relevant for features like alternating between two sessions. ```lua session_lens = { session_control = { control_dir = vim.fn.stdpath("data") .. "/auto_session/", control_filename = "session_control.json", }, } ``` -------------------------------- ### Lua Configuration Defaults for Auto-Session Source: https://github.com/rmagatti/auto-session/blob/main/README.md This Lua code block defines the default configuration settings for the auto-session plugin. It covers various aspects of session management, including enabling/disabling features, directory filtering, Git integration, session deletion, saving extra data, argument handling, and logging. ```lua local defaults = { -- Saving / restoring enabled = true, -- Enables/disables auto creating, saving and restoring auto_save = true, -- Enables/disables auto saving session on exit auto_restore = true, -- Enables/disables auto restoring session on start auto_create = true, -- Enables/disables auto creating new session files. Can be a function that returns true if a new session file should be allowed auto_restore_last_session = false, -- On startup, loads the last saved session if session for cwd does not exist cwd_change_handling = false, -- Automatically save/restore sessions when changing directories single_session_mode = false, -- Enable single session mode to keep all work in one session regardless of cwd changes. When enabled, prevents creation of separate sessions for different directories and maintains one unified session. Does not work with cwd_change_handling -- Filtering suppressed_dirs = nil, -- Suppress session restore/create in certain directories allowed_dirs = nil, -- Allow session restore/create in certain directories bypass_save_filetypes = nil, -- List of filetypes to bypass auto save when the only buffer open is one of the file types listed, useful to ignore dashboards close_filetypes_on_save = { "checkhealth" }, -- Buffers with matching filetypes will be closed before saving close_unsupported_windows = true, -- Close windows that aren't backed by normal file before autosaving a session preserve_buffer_on_restore = nil, -- Function that returns true if a buffer should be preserved when restoring a session -- Git / Session naming git_use_branch_name = false, -- Include git branch name in session name, can also be a function that takes an optional path and returns the name of the branch git_auto_restore_on_branch_change = false, -- Should we auto-restore the session when the git branch changes. Requires git_use_branch_name custom_session_tag = nil, -- Function that can return a string to be used as part of the session name -- Deleting auto_delete_empty_sessions = true, -- Enables/disables deleting the session if there are only unnamed/empty buffers when auto-saving purge_after_minutes = nil, -- Sessions older than purge_after_minutes will be deleted asynchronously on startup, e.g. set to 14400 to delete sessions that haven't been accessed for more than 10 days, defaults to off (no purging), requires >= nvim 0.10 -- Saving extra data save_extra_data = nil, -- Function that returns extra data that should be saved with the session. Will be passed to restore_extra_data on restore restore_extra_data = nil, -- Function called when there's extra data saved for a session -- Argument handling args_allow_single_directory = true, -- Follow normal session save/load logic if launched with a single directory as the only argument args_allow_files_auto_save = false, -- Allow saving a session even when launched with a file argument (or multiple files/dirs). It does not load any existing session first. Can be true or a function that returns true when saving is allowed. See documentation for more detail -- Misc log_level = "error", -- Sets the log level of the plugin (debug, info, warn, error). root_dir = vim.fn.stdpath("data") .. "/sessions/", -- Root dir where sessions will be stored show_auto_restore_notif = false, -- Whether to show a notification when auto-restoring restore_error_handler = nil, -- Function called when there's an error restoring. By default, it ignores fold and help errors otherwise it displays the error and returns false to disable auto_save. Default handler is accessible as require('auto-session').default_restore_error_handler continue_restore_on_error = true, -- Keep loading the session even if there's an error lsp_stop_on_restore = false, -- Should language servers be stopped when restoring a session. Can also be a function that will be called if set. Not called on autorestore from startup lazy_support = true, -- Automatically detect if Lazy.nvim is being used and wait until Lazy is done to make sure session is restored correctly. Does nothing if Lazy isn't being used legacy_cmds = true, -- Define legacy commands: Session*, Autosession (lowercase s), currently true. Set to false to prevent defining them ---@type SessionLens session_lens = { picker = nil, -- "telescope"|"snacks"|"fzf"|"select"|nil Pickers are detected automatically but you can also set one manually. Falls back to vim.ui.select load_on_setup = true, -- Only used for telescope, registers the telescope extension at startup so you can use :Telescope session-lens picker_opts = nil, -- Table passed to Telescope / Snacks / Fzf-Lua to configure the picker. See below for more information } } ``` -------------------------------- ### Configure Auto-Session Behavior Source: https://github.com/rmagatti/auto-session/blob/main/doc/auto-session.txt Control core functionalities like enabling/disabling auto-save, auto-restore, and auto-creation of sessions. Auto-creation can be a boolean or a function that determines if a session should be created. ```lua auto_save = true, auto_restore = true, auto_create = function() return true end ``` -------------------------------- ### Configure Session Management Hooks in Lua Source: https://github.com/rmagatti/auto-session/blob/main/README.md This Lua code configures various command hooks for session management in auto-session. It allows execution of Vim commands or Lua functions before and after session saving, restoring, and deletion. It also demonstrates saving and restoring custom data like the quickfix list. ```lua opts = { -- {hook_name}_cmds = {"{hook_command1}", "{hook_command2}"} pre_save_cmds = { "tabdo NERDTreeClose", -- Close NERDTree before saving session function(session_name) if some_test() then -- don't auto-save if some_test() is true return false end end, }, pre_restore_cmds = { function(session_name) if some_test() then -- don't auto-restore if some_test() is true return false end end, }, post_restore_cmds = { "someOtherVimCommand", function() -- Restore nvim-tree after a session is restored local nvim_tree_api = require("nvim-tree.api") nvim_tree_api.tree.open() nvim_tree_api.tree.change_root(vim.fn.getcwd()) nvim_tree_api.tree.reload() end, }, -- Save quickfix list and open it when restoring the session save_extra_cmds = { function() local qflist = vim.fn.getqflist() -- return nil to clear any old qflist if #qflist == 0 then return nil end local qfinfo = vim.fn.getqflist({ title = 1 }) for _, entry in ipairs(qflist) do -- use filename instead of bufnr so it can be reloaded entry.filename = vim.api.nvim_buf_get_name(entry.bufnr) entry.bufnr = nil end local setqflist = "call setqflist(" .. vim.fn.string(qflist) .. ")" local setqfinfo = 'call setqflist([], "a", ' .. vim.fn.string(qfinfo) .. ")" return { setqflist, setqfinfo, "copen" } end, }, } ``` -------------------------------- ### Default Auto-Session Configuration Options Source: https://github.com/rmagatti/auto-session/blob/main/doc/auto-session.txt This Lua code block outlines the default configuration settings for the Auto-Session plugin. It covers options for enabling/disabling features like auto-saving and restoring, handling directory changes, and filtering sessions based on directories or filetypes. ```lua local defaults = { -- Saving / restoring enabled = true, -- Enables/disables auto creating, saving and restoring auto_save = true, -- Enables/disables auto saving session on exit auto_restore = true, -- Enables/disables auto restoring session on start auto_create = true, -- Enables/disables auto creating new session files. Can be a function that returns true if a new session file should be allowed auto_restore_last_session = false, -- On startup, loads the last saved session if session for cwd does not exist cwd_change_handling = false, -- Automatically save/restore sessions when changing directories single_session_mode = false, -- Enable single session mode to keep all work in one session regardless of cwd changes. When enabled, prevents creation of separate sessions for different directories and maintains one unified session. Does not work with cwd_change_handling -- Filtering suppressed_dirs = nil, -- Suppress session restore/create in certain directories allowed_dirs = nil, -- Allow session restore/create in certain directories bypass_save_filetypes = nil, -- List of filetypes to bypass auto save when the only buffer open is one of the file types listed, useful to ignore dashboards } ``` -------------------------------- ### Configure Saving and Restoring Extra Session Data Source: https://github.com/rmagatti/auto-session/blob/main/doc/auto-session.txt Define functions to save and restore custom data alongside session information. This allows for richer session state management. ```lua save_extra_data = function() return { my_data = "value" } end, restore_extra_data = function(data) print(data.my_data) end ``` -------------------------------- ### Configure AutoSession Git Branch Integration Source: https://github.com/rmagatti/auto-session/blob/main/doc/auto-session.txt This snippet shows how to configure AutoSession to integrate with Git. It includes options to use the current Git branch name in the session name and to automatically restore sessions when switching Git branches. ```lua git_use_branch_name = true, git_auto_restore_on_branch_change = true, ``` -------------------------------- ### Save and Restore Extra Data with AutoSession (Lua) Source: https://context7.com/rmagatti/auto-session/llms.txt This snippet demonstrates how to use the `save_extra_data` and `restore_extra_data` callbacks in AutoSession to save and restore arbitrary data, such as DAP breakpoints. It requires the `dap` plugin and uses JSON encoding/decoding for data transfer. ```lua require("auto-session").setup({ -- Save DAP breakpoints with session save_extra_data = function(session_name) local ok, breakpoints = pcall(require, "dap.breakpoints") if not ok then return nil end local bps = {} for buf, buf_bps in pairs(breakpoints.get()) do bps[vim.api.nvim_buf_get_name(buf)] = buf_bps end if vim.tbl_isempty(bps) then return nil end return vim.fn.json_encode({ breakpoints = bps }) end, -- Restore DAP breakpoints from session restore_extra_data = function(session_name, extra_data) local json = vim.fn.json_decode(extra_data) if not json.breakpoints then return end local ok, breakpoints = pcall(require, "dap.breakpoints") if not ok then return end for buf_name, buf_bps in pairs(json.breakpoints) do for _, bp in pairs(buf_bps) do local bufnr = vim.fn.bufnr(buf_name, true) if vim.fn.bufloaded(bufnr) == 0 then vim.api.nvim_buf_call(bufnr, vim.cmd.edit) end breakpoints.set({ condition = bp.condition, log_message = bp.logMessage, hit_condition = bp.hitCondition, }, bufnr, bp.line) end end end, }) ``` -------------------------------- ### Configure Git Branch Sessions (Lua) Source: https://context7.com/rmagatti/auto-session/llms.txt Enables the creation of separate sessions for each Git branch, identified by including the branch name in the session name. It can also automatically restore the correct session when switching branches, simplifying workflow for projects with multiple branches. ```lua require("auto-session").setup({ -- Include branch name in session name git_use_branch_name = true, -- Auto-restore session when git branch changes git_auto_restore_on_branch_change = true, -- Custom branch name function git_use_branch_name = function(path) local branch = vim.fn.systemlist("git -C " .. (path or ".") .. " branch --show-current")[1] if vim.v.shell_error == 0 then return branch:gsub("/", "_") -- Replace slashes for safety end return nil end, }) -- Sessions will be named like: /home/user/project|main.vim -- Switching from 'main' to 'feature-x' auto-restores feature-x session ``` -------------------------------- ### Configure Session Deletion Source: https://github.com/rmagatti/auto-session/blob/main/doc/auto-session.txt Manage the automatic deletion of sessions. This includes deleting empty sessions upon saving and purging old sessions after a specified duration. ```lua auto_delete_empty_sessions = true, purge_after_minutes = 14400 ``` -------------------------------- ### Define AutoSession.Config Type (Lua) Source: https://github.com/rmagatti/auto-session/blob/main/README.md This snippet defines the Lua type for the AutoSession configuration. It includes numerous fields for controlling various aspects of session management, such as enabling/disabling features, handling directory changes, filtering files, Git integration, and saving/restoring extra data. ```lua --- --@class AutoSession.Config -- --Saving / restoring --@field enabled? boolean --@field auto_save? boolean --@field auto_restore? boolean --@field auto_create? boolean|fun(): should_create_session:boolean --@field auto_restore_last_session? boolean --@field cwd_change_handling? boolean --@field single_session_mode? boolean -- --Filtering --@field suppressed_dirs? table --@field allowed_dirs? table --@field bypass_save_filetypes? table --@field close_filetypes_on_save? table --@field close_unsupported_windows? boolean --@field preserve_buffer_on_restore? fun(bufnr:number): preserve_buffer:boolean -- --Git / Session naming --@field git_use_branch_name? boolean|fun(path:string?): branch_name:string|nil --@field git_auto_restore_on_branch_change? boolean --@field custom_session_tag? fun(session_name:string): tag:string -- --Deleting --@field auto_delete_empty_sessions? boolean --@field purge_after_minutes? number -- --Saving extra data --@field save_extra_data? fun(session_name:string): extra_data:string|nil --@field restore_extra_data? fun(session_name:string, extra_data:string) -- --Argument handling --@field args_allow_single_directory? boolean --@field args_allow_files_auto_save? boolean|fun(): disable_auto_save:boolean -- --Misc --@field log_level? string|integer --@field root_dir? string --@field show_auto_restore_notif? boolean --@field restore_error_handler? fun(error_msg:string): disable_auto_save:boolean --@field continue_restore_on_error? boolean --@field lsp_stop_on_restore? boolean|fun() --@field lazy_support? boolean --@field legacy_cmds? boolean -- --@field session_lens? SessionLens -- --Session Lens Config --@class SessionLens --@field picker? "telescope"|"snacks"|"fzf"|"select" --@field load_on_setup? boolean --@field picker_opts? table --@field previewer? 'summary'|'active_buffer'|fun(session_name:string, session_filename:string, session_lines:string[]):lines:string[],filetype:string? --@field mappings? SessionLensMappings --@field session_control? SessionControl -- --@class SessionLensMappings --@field delete_session? table --@field alternate_session? table --@field copy_session? table -- --@class SessionControl --@field control_dir? string --@field control_filename? string -- --Hooks --@field pre_save_cmds? (string|fun(session_name:string): boolean)[] executes before a session is saved, return false to stop auto-saving --@field post_save_cmds? (string|fun(session_name:string))[] executes after a session is saved --@field pre_restore_cmds? (string|fun(session_name:string): boolean)[] executes before a session is restored, return false to stop auto-restoring --@field post_restore_cmds? (string|fun(session_name:string))[] executes after a session is restored --@field pre_delete_cmds? (string|fun(session_name:string))[] executes before a session is deleted --@field post_delete_cmds? (string|fun(session_name:string))[] executes after a session is deleted --@field no_restore_cmds? (string|fun(is_startup:boolean))[] executes when no session is restored when auto-restoring, happens on startup or possibly on cwd/git branch changes --@field pre_cwd_changed_cmds? (string|fun())[] executes before cwd is changed if cwd_change_handling is true --@field post_cwd_changed_cmds? (string|fun())[] executes after cwd is changed if cwd_change_handling is true --@field save_extra_cmds? (string|fun(session_name:string): string|table|nil)[] executes to get extra data to save with the session ``` -------------------------------- ### Save Session Periodically with Lua Timer Source: https://github.com/rmagatti/auto-session/wiki/Autosaving-periodically This Lua code snippet sets up a timer that triggers the `AutoSaveSession` function from the `auto-session` plugin every 5 minutes (300,000 milliseconds). It utilizes `vim.loop.new_timer` for asynchronous operation and `vim.schedule_wrap` to ensure the callback is executed safely within Neovim's event loop. No external dependencies beyond the `auto-session` plugin are required. ```lua local timer = vim.loop.new_timer() timer:start(0, 300000, vim.schedule_wrap( function() require('auto-session').AutoSaveSession() end )) ``` -------------------------------- ### Conditionally Enable Auto Session Restore (Lua) Source: https://github.com/rmagatti/auto-session/wiki/Auto-restore-last-session This configuration conditionally enables the restoration of the last session only when Neovim is launched in the home directory. This is achieved by checking the current working directory against the OS home directory. ```lua require("auto-session").setup { auto_restore_last_session = vim.loop.cwd() == vim.loop.os_homedir(), } ``` -------------------------------- ### Toggle Autosave Command in VimL Source: https://github.com/rmagatti/auto-session/blob/main/doc/auto-session.txt Manages the autosave feature of the auto-session plugin. Commands include enable, disable, and toggle. ```viml :AutoSession disable " disables autosave :AutoSession enable " enables autosave (still does all checks in the config) :AutoSession toggle" toggles autosave ``` -------------------------------- ### Configure Auto Session Branch Handling (Lua) Source: https://github.com/rmagatti/auto-session/blob/main/doc/auto-session.txt This configuration enables auto-session to use the Git branch name for session management and automatically restore sessions when the branch changes. It's useful for maintaining distinct sessions per branch. ```lua opts = { git_use_branch_name = true, git_auto_restore_on_branch_change = true, } ``` -------------------------------- ### Conditional AutoSession Save Based on Buffer Count (Lua) Source: https://github.com/rmagatti/auto-session/wiki/Argument-Handling Sets a custom function for `args_allow_files_auto_save` to conditionally save a session. The session is saved only if Neovim is launched with arguments and at least two valid, loaded buffers are present. ```lua require("auto-session").setup { args_allow_files_auto_save = function() local supported = 0 local buffers = vim.api.nvim_list_bufs() for _, buf in ipairs(buffers) do -- Check if the buffer is valid and loaded if vim.api.nvim_buf_is_valid(buf) and vim.api.nvim_buf_is_loaded(buf) then local path = vim.api.nvim_buf_get_name(buf) if vim.fn.filereadable(path) ~= 0 then supported = supported + 1 end end end -- If we have more 2 or more supported buffers, save the session return supported >= 2 end, } ``` -------------------------------- ### Bypass Dashboard Filetypes for Session Saving (Lua) Source: https://github.com/rmagatti/auto-session/blob/main/doc/auto-session.txt This configuration option allows you to specify filetypes that should be ignored when saving sessions. This is particularly useful for dashboards to prevent them from being included in session saves. ```lua opts = { bypass_save_filetypes = { "alpha", "dashboard", "snacks_dashboard" }, -- or whatever dashboard you use } ``` -------------------------------- ### Check for Existing Session in Current Directory Source: https://context7.com/rmagatti/auto-session/llms.txt Checks if a session file exists for the current working directory. This is useful for conditional logic, such as enabling or disabling a 'restore session' option in starter plugins or dashboards. ```lua local auto_session = require("auto-session") -- Check before showing restore option in a dashboard if auto_session.session_exists_for_cwd() then -- Show "Restore Session" button/option print("Session available for this directory") else -- Hide restore option or show "No session" print("No session found") end -- Example: Conditional dashboard action local function dashboard_restore_action() if require("auto-session").session_exists_for_cwd() then require("auto-session").restore_session() else vim.notify("No session found for current directory") end end ``` -------------------------------- ### Conditional AutoSession Save Based on Window Count (Lua) Source: https://github.com/rmagatti/auto-session/wiki/Argument-Handling Configures `args_allow_files_auto_save` with a function to save sessions based on the number of windows with file-backed buffers. A session is saved if there are at least two such windows across all tab pages. ```lua require("auto-session").setup { args_allow_files_auto_save = function() local supported = 0 local tabpages = vim.api.nvim_list_tabpages() for _, tabpage in ipairs(tabpages) do local windows = vim.api.nvim_tabpage_list_wins(tabpage) for _, window in ipairs(windows) do local buffer = vim.api.nvim_win_get_buf(window) local file_name = vim.api.nvim_buf_get_name(buffer) if vim.fn.filereadable(file_name) ~= 0 then supported = supported + 1 end end end -- If we have 2 or more windows with supported buffers, save the session return supported >= 2 end, } ```