Skip to content

Commit 350abfc

Browse files
committed
feat: add hooks
1 parent 1b6268f commit 350abfc

File tree

2 files changed

+51
-3
lines changed

2 files changed

+51
-3
lines changed

README.md

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,5 @@ This is a work in progress
77
TODO:
88
- periodic saving
99
- tab-scoped sessions
10-
- hooks for plugins
1110
- window size
1211
- documentation

lua/resession/init.lua

Lines changed: 51 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,23 @@ M.setup = function(config)
1414
pending_config = config or {}
1515
end
1616

17+
local hooks = {}
18+
19+
---@class resession.Hook
20+
---@field on_save fun(): any
21+
---@field on_load fun(data: any)
22+
23+
---@param name string
24+
---@param hook resession.Hook
25+
M.add_hook = function(name, hook)
26+
hooks[name] = hook
27+
end
28+
29+
---@param name string
30+
M.remove_hook = function(name)
31+
hooks[name] = nil
32+
end
33+
1734
---@param name string
1835
---@return string
1936
local function get_session_file(name)
@@ -25,12 +42,14 @@ local function get_session_file(name)
2542
)
2643
end
2744

45+
---Get the name of the current session
2846
---@return string|nil
29-
M.get_current_session = function()
47+
M.get_current = function()
3048
return current_session
3149
end
3250

33-
M.detach_session = function()
51+
---Detach from the current session
52+
M.detach = function()
3453
current_session = nil
3554
end
3655

@@ -134,6 +153,26 @@ M.save = function(name, opts)
134153
local winlayout = vim.fn.winlayout(tabnr)
135154
tab.wins = layout.add_win_info_to_layout(tabnr, winlayout)
136155
end
156+
157+
for k, hook in pairs(hooks) do
158+
if data[k] then
159+
vim.notify(
160+
string.format("[resession] Cannot run hook named '%s'; it conflicts with built-in data", k),
161+
vim.log.levels.WARN
162+
)
163+
else
164+
local ok, hookdata = pcall(hook.on_save)
165+
if ok then
166+
data[k] = hookdata
167+
else
168+
vim.notify(
169+
string.format("[resession] Hook %s error: %s", k, hookdata),
170+
vim.log.levels.ERROR
171+
)
172+
end
173+
end
174+
end
175+
137176
files.write_json_file(filename, data)
138177
if not opts.detach then
139178
current_session = name
@@ -214,6 +253,16 @@ M.load = function(name, opts)
214253
end
215254
end
216255
vim.api.nvim_set_current_win(curwin.winid)
256+
257+
for k, hook in pairs(hooks) do
258+
if data[k] then
259+
local ok, err = pcall(hook.on_load)
260+
if not ok then
261+
vim.notify(string.format("[resession] Hook %s error: %s", k, err), vim.log.levels.ERROR)
262+
end
263+
end
264+
end
265+
217266
if not opts.detach then
218267
current_session = name
219268
end

0 commit comments

Comments
 (0)