Skip to content

Commit

Permalink
feat: make more data available when firing events
Browse files Browse the repository at this point in the history
  • Loading branch information
olimorris committed Dec 21, 2023
1 parent 4310da8 commit dfb79ff
Show file tree
Hide file tree
Showing 4 changed files with 122 additions and 69 deletions.
61 changes: 35 additions & 26 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,14 @@ The plugin comes with a number of commands:

### Telescope extension

<!-- panvimdoc-ignore-start -->

<p align="center">
<img src="https://user-images.githubusercontent.com/9512444/177375482-3bc9bd0d-42c8-4755-a36c-08ea5f954525.png" alt="Telescope">
</p>

<!-- panvimdoc-ignore-end -->

The Telescope extension may be opened via `:Telescope persisted`. The available actions are:

- `<CR>` - Open/source the session file
Expand Down Expand Up @@ -163,7 +171,7 @@ require("persisted").setup({
As the plugin uses Vim's `:mksession` command then you may change the `vim.o.sessionoptions` value to determine what to write into the session. Please see `:h sessionoptions` for more information.

> **Note**: The author uses:
> `vim.o.sessionoptions = "buffers,curdir,folds,globals,tabpages,winpos,winsize"`
> `vim.o.sessionoptions = "buffers,curdir,folds,tabpages,winpos,winsize"`
### Session save location

Expand All @@ -187,8 +195,6 @@ require("persisted").setup({
})
```

> **Note**: If you initiate git in a repository which has an existing session file, you'll need to add it's branch name to the session name. To do this from within Neovim, use the `:Sessions` command, navigate to the session and press `<C-a>`.
### Autosaving

By default, the plugin will automatically save a Neovim session to disk when the `VimLeavePre` event is triggered. Autosaving can be turned off by:
Expand Down Expand Up @@ -307,7 +313,7 @@ In this setup, `~/.config` and `~/.local/nvim` are still going to behave in thei

### Events / Callbacks

The plugin fires events at various points during its lifecycle, which users can hook into:
The plugin fires events at various points during its lifecycle:

- `PersistedLoadPre` - For _before_ a session is loaded
- `PersistedLoadPost` - For _after_ a session is loaded
Expand All @@ -320,21 +326,11 @@ The plugin fires events at various points during its lifecycle, which users can
- `PersistedStateChange` - For when a session is _started_ or _stopped_
- `PersistedToggled` - For when a session is toggled

For example, to ensure that the excellent [minimap](https://github.com/wfxr/minimap.vim) plugin is not saved into a session, an autocmd can be created to hook into the `PersistedSavePre` event:
These events can be consumed anywhere within your configuration by utilising the `vim.api.nvim_create_autocmd` function.

```lua
local group = vim.api.nvim_create_augroup("PersistedHooks", {})

vim.api.nvim_create_autocmd({ "User" }, {
pattern = "PersistedSavePre",
group = group,
callback = function()
pcall(vim.cmd, "bw minimap")
end,
})
```
#### Example use case

Another and more commonly requested example is to use the Telescope extension to load a session, saving the current session before clearing all of the open buffers. This can be achieved by utilising some of the session data that is made available to the callbacks:
A commonly requested example is to use the Telescope extension to load a session, saving the current session before clearing all of the open buffers:

```lua
local group = vim.api.nvim_create_augroup("PersistedHooks", {})
Expand All @@ -343,7 +339,7 @@ vim.api.nvim_create_autocmd({ "User" }, {
pattern = "PersistedTelescopeLoadPre",
group = group,
callback = function(session)
-- Save the currently loaded session
-- Save the currently loaded session using a global variable
require("persisted").save({ session = vim.g.persisted_loaded_session })

-- Delete all of the open buffers
Expand All @@ -352,19 +348,32 @@ vim.api.nvim_create_autocmd({ "User" }, {
})
```

The session data available differs depending on the events that are hooked into. For non-telescope events, only the session's full path is available (via `session.data`). However for telescope events, the `branch`, `name`, `file_path` and `dir_path` are available.
#### Using callback data

### Telescope extension
When certain events are fired, session data is made available for the user to consume, for example:

<!-- panvimdoc-ignore-start -->
```lua
{
branch = "main",
dir_path = "Code/Neovim/persisted.nvim",
file_path = "/Users/Oli/.local/share/nvim/sessions/%Users%Oli%Code%Neovim%persisted.nvim@@main.vim",
name = "Code/Neovim/persisted.nvim@@main",
}
```

<p align="center">
<img src="https://user-images.githubusercontent.com/9512444/177375482-3bc9bd0d-42c8-4755-a36c-08ea5f954525.png" alt="Telescope">
</p>
To consume this data, use the `session.data` table in your autocmd:

<!-- panvimdoc-ignore-end -->
```lua
vim.api.nvim_create_autocmd({ "User" }, {
pattern = "PersistedLoadPost",
group = group,
callback = function(session)
print(session.data.branch)
end,
})
```

The plugin contains an extension for [telescope.nvim](https://github.com/nvim-telescope/telescope.nvim) which allows the user to list all of the saved session files and source them via `:Telescope persisted`.
> **Note**: This data is available for the `PersistedLoad`, `PersistedDelete` and `PersistedTelescope` events
## :page_with_curl: License

Expand Down
78 changes: 39 additions & 39 deletions doc/persisted.nvim.txt
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,12 @@ Table of Contents *persisted.nvim-table-of-contents*
FEATURES *persisted.nvim-features*


- Automatically saves the active session under `.local/share/nvim/sessions` on exiting Neovim
- Supports sessions across multiple git branches
- Supports autosaving and autoloading of sessions with allowed/ignored directories
- Simple API to save/stop/restore/delete/list the current session(s)
- Custom events which users can hook into for greater integration
- Telescope extension to work with saved sessions
- Custom events which users can hook into for tighter integration
- Simple API to save/stop/restore/delete/list the current session(s)
- Supports autosaving and autoloading of sessions with allowed/ignored directories
- Automatically saves the active session under `.local/share/nvim/sessions` on exiting Neovim


REQUIREMENTS *persisted.nvim-requirements*
Expand Down Expand Up @@ -175,7 +175,7 @@ Please see `:h sessionoptions` for more information.


**Note**The author uses: `vim.o.sessionoptions =
"buffers,curdir,folds,globals,tabpages,winpos,winsize"`
"buffers,curdir,folds,tabpages,winpos,winsize"`

SESSION SAVE LOCATION ~

Expand Down Expand Up @@ -204,11 +204,6 @@ files for a given project, by using git branches. To enable git branching:
<


**Note**If you initiate git in a repository which has an existing session file,
you’ll need to add it’s branch name to the session name. To do this from
within Neovim, use the `:Sessions` command, navigate to the session and press
`<C-a>`.

AUTOSAVING ~

By default, the plugin will automatically save a Neovim session to disk when
Expand Down Expand Up @@ -359,8 +354,7 @@ their default setting (ignoring all listed directory and its children), however

EVENTS / CALLBACKS ~

The plugin fires events at various points during its lifecycle, which users can
hook into:
The plugin fires events at various points during its lifecycle:


- `PersistedLoadPre` - For _before_ a session is loaded
Expand All @@ -374,26 +368,14 @@ hook into:
- `PersistedStateChange` - For when a session is _started_ or _stopped_
- `PersistedToggled` - For when a session is toggled

For example, to ensure that the excellent minimap
<https://github.com/wfxr/minimap.vim> plugin is not saved into a session, an
autocmd can be created to hook into the `PersistedSavePre` event:
These events can be consumed anywhere within your configuration by utilising
the `vim.api.nvim_create_autocmd` function.

>lua
local group = vim.api.nvim_create_augroup("PersistedHooks", {})

vim.api.nvim_create_autocmd({ "User" }, {
pattern = "PersistedSavePre",
group = group,
callback = function()
pcall(vim.cmd, "bw minimap")
end,
})
<

Another and more commonly requested example is to use the Telescope extension
to load a session, saving the current session before clearing all of the open
buffers. This can be achieved by utilising some of the session data that is
made available to the callbacks:
EXAMPLE USE CASE

A commonly requested example is to use the Telescope extension to load a
session, saving the current session before clearing all of the open buffers:

>lua
local group = vim.api.nvim_create_augroup("PersistedHooks", {})
Expand All @@ -402,7 +384,7 @@ made available to the callbacks:
pattern = "PersistedTelescopeLoadPre",
group = group,
callback = function(session)
-- Save the currently loaded session
-- Save the currently loaded session using a global variable
require("persisted").save({ session = vim.g.persisted_loaded_session })

-- Delete all of the open buffers
Expand All @@ -411,18 +393,36 @@ made available to the callbacks:
})
<

The session data available differs depending on the events that are hooked
into. For non-telescope events, only the session’s full path is available
(via `session.data`). However for telescope events, the `branch`, `name`,
`file_path` and `dir_path` are available.

USING CALLBACK DATA

TELESCOPE EXTENSION ~
When certain events are fired, session data is made available for the user to
consume, for example:

>lua
{
branch = "main",
dir_path = "Code/Neovim/persisted.nvim",
file_path = "/Users/Oli/.local/share/nvim/sessions/%Users%Oli%Code%Neovim%persisted.nvim@@main.vim",
name = "Code/Neovim/persisted.nvim@@main",
}
<

To consume this data, use the `session.data` table in your autocmd:

>lua
vim.api.nvim_create_autocmd({ "User" }, {
pattern = "PersistedLoadPost",
group = group,
callback = function(session)
print(session.data.branch)
end,
})
<

The plugin contains an extension for telescope.nvim
<https://github.com/nvim-telescope/telescope.nvim> which allows the user to
list all of the saved session files and source them via `:Telescope persisted`.

**Note**This data is available for the `PersistedLoad`, `PersistedDelete` and
`PersistedTelescope` events

LICENSE *persisted.nvim-license*

Expand Down
8 changes: 6 additions & 2 deletions lua/persisted/init.lua
Original file line number Diff line number Diff line change
Expand Up @@ -270,14 +270,16 @@ function M.delete(dir)
local session = get_current(dir)

if session and vim.loop.fs_stat(session) ~= 0 then
vim.api.nvim_exec_autocmds("User", { pattern = "PersistedDeletePre", data = { name = session } })
local session_data = utils.make_session_data(session)

vim.api.nvim_exec_autocmds("User", { pattern = "PersistedDeletePre", data = session_data })

vim.schedule(function()
M.stop()
vim.fn.system("rm " .. e(session))
end)

vim.api.nvim_exec_autocmds("User", { pattern = "PersistedDeletePost", data = { name = session } })
vim.api.nvim_exec_autocmds("User", { pattern = "PersistedDeletePost", data = session_data })
end
end

Expand All @@ -291,9 +293,11 @@ function M.toggle(dir)
if vim.g.persisting == nil then
return M.load({}, dir)
end

if vim.g.persisting then
return M.stop()
end

return M.start()
end

Expand Down
44 changes: 42 additions & 2 deletions lua/persisted/utils.lua
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,44 @@ local function escape_pattern(input)
return input
end

---Form a table of session data
---@param session string
---@return table
function M.make_session_data(session)
local config = require("persisted.config").options

local home
if os.getenv("HOME") then
home = os.getenv("HOME") -- Unix-based systems (Linux, macOS)
elseif os.getenv("USERPROFILE") then
home = os.getenv("USERPROFILE") -- Windows
else
home = ""
end

-- Form the branch
local pattern = config.branch_separator .. "(.-)%.vim"
local branch = session:match(pattern) or ""

-- Form the name
local name = session:gsub(config.save_dir, ""):gsub("%%", "/"):gsub(home, "")
name = name:sub(1, #name - 4) -- Remove the .vim extension

if name:sub(1, 1) == "/" then
name = name:sub(2)
end

-- Form the dir_path
local dir_path = name:gsub(branch, ""):gsub(config.branch_separator, ""):gsub(home, "")

return {
name = name,
dir_path = dir_path,
file_path = session,
branch = branch,
}
end

--- Get the last element in a table
---@param table table
---@return string
Expand Down Expand Up @@ -76,7 +114,9 @@ end
---@param silent boolean Load the session silently?
---@return nil|string
function M.load_session(session, silent)
vim.api.nvim_exec_autocmds("User", { pattern = "PersistedLoadPre", data = session })
local session_data = M.make_session_data(session)

vim.api.nvim_exec_autocmds("User", { pattern = "PersistedLoadPre", data = session_data })

local ok, result = pcall(vim.cmd, (silent and "silent " or "") .. "source " .. e(session))
if not ok then
Expand All @@ -86,7 +126,7 @@ function M.load_session(session, silent)
vim.g.persisted_exists = true
vim.g.persisted_loaded_session = session

vim.api.nvim_exec_autocmds("User", { pattern = "PersistedLoadPost", data = session })
vim.api.nvim_exec_autocmds("User", { pattern = "PersistedLoadPost", data = session_data })
end

return M

0 comments on commit dfb79ff

Please sign in to comment.