-
Notifications
You must be signed in to change notification settings - Fork 13
/
init.lua
561 lines (533 loc) · 16 KB
/
init.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
local M = {}
local has_setup = false
local pending_config
local current_session
local tab_sessions = {}
local session_configs = {}
local hooks = setmetatable({
pre_load = {},
post_load = {},
pre_save = {},
post_save = {},
}, {
__index = function(t, key)
error(string.format("Unrecognized hook '%s'", key))
end,
})
local function do_setup()
if pending_config then
local conf = pending_config
pending_config = nil
require("resession.config").setup(conf)
has_setup = true
end
end
local function dispatch(name, ...)
for _, cb in ipairs(hooks[name]) do
cb(...)
end
end
---Initialize resession with configuration options
---@param config table
M.setup = function(config)
pending_config = config or {}
if has_setup then
do_setup()
end
end
---Load an extension some time after calling setup()
---@param name string Name of the extension
---@param opts table Configuration options for extension
M.load_extension = function(name, opts)
if has_setup then
local config = require("resession.config")
local util = require("resession.util")
config.extensions[name] = opts
local ext = util.get_extension(name)
if ext and ext.config then
ext.config(opts)
end
elseif pending_config then
pending_config.extensions = pending_config.extensions or {}
pending_config.extensions[name] = opts
else
error("Cannot call resession.load_extension() before resession.setup()")
end
end
---Get the name of the current session
---@return nil|string
M.get_current = function()
local tabpage = vim.api.nvim_get_current_tabpage()
return tab_sessions[tabpage] or current_session
end
---Detach from the current session
M.detach = function()
current_session = nil
local tabpage = vim.api.nvim_get_current_tabpage()
tab_sessions[tabpage] = nil
end
---List all available saved sessions
---@param opts nil|resession.ListOpts
--- dir nil|string Name of directory to save to (overrides config.dir)
---@return string[]
M.list = function(opts)
opts = opts or {}
local files = require("resession.files")
local util = require("resession.util")
local session_dir = util.get_session_dir(opts.dir)
if not files.exists(session_dir) then
return {}
end
local fd = vim.loop.fs_opendir(session_dir, nil, 32)
local entries = vim.loop.fs_readdir(fd)
local ret = {}
while entries do
for _, entry in ipairs(entries) do
if entry.type == "file" then
local name = entry.name:match("^(.+)%.json$")
if name then
table.insert(ret, name)
end
end
end
entries = vim.loop.fs_readdir(fd)
end
vim.loop.fs_closedir(fd)
return ret
end
local function remove_tabpage_session(name)
for k, v in pairs(tab_sessions) do
if v == name then
tab_sessions[k] = nil
break
end
end
end
---Delete a saved session
---@param name string
---@param opts nil|resession.DeleteOpts
--- dir nil|string Name of directory to save to (overrides config.dir)
M.delete = function(name, opts)
opts = opts or {}
local files = require("resession.files")
local util = require("resession.util")
if not name then
local sessions = M.list()
if vim.tbl_isempty(sessions) then
vim.notify("No saved sessions", vim.log.levels.WARN)
return
end
vim.ui.select(sessions, { prompt = "Delete session" }, function(selected)
if selected then
M.delete(selected)
end
end)
return
end
local filename = util.get_session_file(name, opts.dir)
if not files.delete_file(filename) then
error(string.format("No session '%s'", filename))
end
if current_session == name then
current_session = nil
end
remove_tabpage_session(name)
end
---@param name string
---@param opts resession.SaveOpts
--- attach nil|boolean Stay attached to session after saving (default true)
--- notify nil|boolean Notify on success
--- dir nil|string Name of directory to save to (overrides config.dir)
---@param target_tabpage nil|integer
local function save(name, opts, target_tabpage)
local config = require("resession.config")
local files = require("resession.files")
local layout = require("resession.layout")
local util = require("resession.util")
local filename = util.get_session_file(name, opts.dir)
dispatch("pre_save", name, opts, target_tabpage)
local data = {
buffers = {},
tabs = {},
tab_scoped = target_tabpage ~= nil,
global = {
cwd = vim.fn.getcwd(-1, -1),
height = vim.o.lines - vim.o.cmdheight,
width = vim.o.columns,
-- Don't save global options for tab-scoped session
options = target_tabpage and {} or util.save_global_options(),
},
}
local tabpage_bufs = {}
if target_tabpage then
for _, winid in ipairs(vim.api.nvim_tabpage_list_wins(target_tabpage)) do
local bufnr = vim.api.nvim_win_get_buf(winid)
tabpage_bufs[bufnr] = true
end
end
for _, bufnr in ipairs(vim.api.nvim_list_bufs()) do
if util.include_buf(target_tabpage, bufnr, tabpage_bufs) then
local buf = {
name = vim.api.nvim_buf_get_name(bufnr),
loaded = vim.api.nvim_buf_is_loaded(bufnr),
options = util.save_buf_options(bufnr),
last_pos = vim.api.nvim_buf_get_mark(bufnr, '"'),
}
table.insert(data.buffers, buf)
end
end
local tabpages = target_tabpage and { target_tabpage } or vim.api.nvim_list_tabpages()
for _, tabpage in ipairs(tabpages) do
local tab = {}
local tabnr = vim.api.nvim_tabpage_get_number(tabpage)
if target_tabpage or vim.fn.haslocaldir(-1, tabnr) == 1 then
tab.cwd = vim.fn.getcwd(-1, tabnr)
end
table.insert(data.tabs, tab)
local winlayout = vim.fn.winlayout(tabnr)
tab.wins = layout.add_win_info_to_layout(tabnr, winlayout)
end
for ext_name, ext_config in pairs(config.extensions) do
local ext = util.get_extension(ext_name)
if ext and ext.on_save and (ext_config.enable_in_tab or not target_tabpage) then
local ok, ext_data = pcall(ext.on_save)
if ok then
data[ext_name] = ext_data
else
vim.notify(
string.format("[resession] Extension %s save error: %s", ext_name, ext_data),
vim.log.levels.ERROR
)
end
end
end
files.write_json_file(filename, data)
if opts.notify then
vim.notify(string.format("Saved session %s", name))
end
if opts.attach then
session_configs[name] = {
dir = opts.dir,
}
end
dispatch("post_save", name, opts, target_tabpage)
end
---Save a session to disk
---@param name nil|string
---@param opts nil|resession.SaveOpts
--- attach nil|boolean Stay attached to session after saving (default true)
--- notify nil|boolean Notify on success
--- dir nil|string Name of directory to save to (overrides config.dir)
M.save = function(name, opts)
opts = vim.tbl_extend("keep", opts or {}, {
notify = true,
attach = true,
})
if not name then
-- If no name, default to the current session
name = current_session
end
if not name then
vim.ui.input({ prompt = "Session name" }, function(selected)
if selected then
M.save(selected, opts)
end
end)
return
end
save(name, opts)
tab_sessions = {}
if opts.attach then
current_session = name
else
current_session = nil
end
end
---Save a tab-scoped session
---@param name string
---@param opts nil|resession.SaveOpts
--- attach nil|boolean Stay attached to session after saving (default true)
--- notify nil|boolean Notify on success
--- dir nil|string Name of directory to save to (overrides config.dir)
M.save_tab = function(name, opts)
opts = vim.tbl_extend("keep", opts or {}, {
notify = true,
attach = true,
})
local cur_tabpage = vim.api.nvim_get_current_tabpage()
if not name then
name = tab_sessions[cur_tabpage]
end
if not name then
vim.ui.input({ prompt = "Session name" }, function(selected)
if selected then
M.save_tab(selected, opts)
end
end)
return
end
save(name, opts, cur_tabpage)
current_session = nil
remove_tabpage_session(name)
if opts.attach then
tab_sessions[cur_tabpage] = name
else
tab_sessions[cur_tabpage] = nil
end
end
---Save all current sessions to disk
---@param opts nil|table
--- notify nil|boolean
M.save_all = function(opts)
opts = vim.tbl_extend("keep", opts or {}, {
notify = true,
})
if current_session then
save(current_session, vim.tbl_extend("keep", opts, session_configs[current_session]))
else
-- First prune tab-scoped sessions for closed tabs
local invalid_tabpages = vim.tbl_filter(function(tabpage)
return not vim.api.nvim_tabpage_is_valid(tabpage)
end, vim.tbl_keys(tab_sessions))
for _, tabpage in ipairs(invalid_tabpages) do
tab_sessions[tabpage] = nil
end
-- Save all tab-scoped sessions
for tabpage, name in pairs(tab_sessions) do
save(name, vim.tbl_extend("keep", opts, session_configs[name]), tabpage)
end
end
end
local function open_clean_tab()
-- Detect if we're already in a "clean" tab
-- (one window, and one empty scratch buffer)
if #vim.api.nvim_tabpage_list_wins(0) == 1 then
if vim.api.nvim_buf_get_name(0) == "" then
local lines = vim.api.nvim_buf_get_lines(0, -1, 2, false)
if vim.tbl_isempty(lines) then
vim.api.nvim_buf_set_option(0, "buflisted", false)
vim.api.nvim_buf_set_option(0, "bufhidden", "wipe")
return
end
end
end
vim.cmd("tabnew")
end
local function close_everything()
local scratch = vim.api.nvim_create_buf(false, true)
vim.api.nvim_buf_set_option(scratch, "buflisted", false)
vim.api.nvim_buf_set_option(scratch, "bufhidden", "wipe")
vim.api.nvim_win_set_buf(0, scratch)
for _, bufnr in ipairs(vim.api.nvim_list_bufs()) do
if vim.bo[bufnr].buflisted then
vim.api.nvim_buf_delete(bufnr, { force = true })
end
end
vim.cmd("silent! tabonly")
vim.cmd("silent! only")
end
local _is_loading = false
---Load a session
---@param name nil|string
---@param opts nil|resession.LoadOpts
--- attach nil|boolean Stay attached to session after loading (default true)
--- reset nil|boolean|"auto" Close everthing before loading the session (default "auto")
--- silence_errors nil|boolean Don't error when trying to load a missing session
--- dir nil|string Name of directory to load from (overrides config.dir)
---@note
--- The default value of `reset = "auto"` will reset when loading a normal session, but _not_ when
--- loading a tab-scoped session.
M.load = function(name, opts)
opts = vim.tbl_extend("keep", opts or {}, {
reset = "auto",
attach = true,
})
local config = require("resession.config")
local files = require("resession.files")
local layout = require("resession.layout")
local util = require("resession.util")
if not name then
local sessions = M.list()
if vim.tbl_isempty(sessions) then
vim.notify("No saved sessions", vim.log.levels.WARN)
return
end
local select_opts = { prompt = "Load session" }
if config.load_detail then
local session_data = {}
for _, session_name in ipairs(sessions) do
local filename = util.get_session_file(session_name, opts.dir)
local data = files.load_json_file(filename)
session_data[session_name] = data
end
select_opts.format_item = function(session_name)
local data = session_data[session_name]
local formatted = session_name
if data then
if data.tab_scoped then
local tab_cwd = data.tabs[1].cwd
formatted = formatted .. string.format(" (tab) [%s]", util.shorten_path(tab_cwd))
else
formatted = formatted .. string.format(" [%s]", util.shorten_path(data.global.cwd))
end
end
return formatted
end
end
vim.ui.select(sessions, select_opts, function(selected)
if selected then
M.load(selected, opts)
end
end)
return
end
local filename = util.get_session_file(name, opts.dir)
local data = files.load_json_file(filename)
if not data then
if not opts.silence_errors then
error(string.format("Could not find session %s", name))
end
return
end
dispatch("pre_load", name, opts)
_is_loading = true
if opts.reset == "auto" then
opts.reset = not data.tab_scoped
end
if opts.reset then
close_everything()
else
open_clean_tab()
end
if not data.tab_scoped then
-- Set the options immediately
util.restore_global_options(data.global.options)
vim.cmd(string.format("cd %s", data.global.cwd))
end
local scale = {
vim.o.columns / data.global.width,
(vim.o.lines - vim.o.cmdheight) / data.global.height,
}
for _, buf in ipairs(data.buffers) do
local bufnr = vim.fn.bufadd(buf.name)
if buf.loaded then
vim.fn.bufload(bufnr)
vim.api.nvim_create_autocmd("BufWinEnter", {
desc = "Resession: complete setup of restored buffer",
callback = function(args)
pcall(vim.api.nvim_win_set_cursor, 0, buf.last_pos)
-- After showing the buffer in a window, manually set the filetype to trigger syntax highlighting
vim.api.nvim_buf_set_option(bufnr, "filetype", vim.bo[bufnr].filetype)
end,
buffer = bufnr,
once = true,
nested = true,
})
end
util.restore_buf_options(bufnr, buf.options)
end
local curwin
for i, tab in ipairs(data.tabs) do
if i > 1 then
vim.cmd("tabnew")
-- Tabnew creates a new empty buffer. Dispose of it when hidden.
vim.bo.buflisted = false
vim.bo.bufhidden = "wipe"
end
if tab.cwd then
vim.cmd(string.format("tcd %s", tab.cwd))
end
local win = layout.set_winlayout(tab.wins, scale)
if win then
curwin = win
end
end
-- This can be nil if we saved a session in a window with an unsupported buffer
if curwin then
vim.api.nvim_set_current_win(curwin)
end
for ext_name in pairs(config.extensions) do
if data[ext_name] then
local ext = util.get_extension(ext_name)
if ext then
local ok, err = pcall(ext.on_load, data[ext_name])
if not ok then
vim.notify(
string.format("[resession] Extension %s load error: %s", ext_name, err),
vim.log.levels.ERROR
)
end
end
end
end
-- We re-apply the options because sometimes the cmdheight gets messed up for some reason
for k, v in pairs(data.global.options) do
vim.o[k] = v
end
current_session = nil
if opts.reset then
tab_sessions = {}
end
remove_tabpage_session(name)
if opts.attach then
if data.tab_scoped then
tab_sessions[vim.api.nvim_get_current_tabpage()] = name
else
current_session = name
end
session_configs[name] = {
dir = opts.dir,
}
end
_is_loading = false
dispatch("post_load", name, opts)
end
---Add a callback that runs at a specific time
---@param name "pre_save"|"post_save"|"pre_load"|"post_load"
---@param callback fun()
M.add_hook = function(name, callback)
table.insert(hooks[name], callback)
end
---Remove a hook callback
---@param name "pre_save"|"post_save"|"pre_load"|"post_load"
---@param callback fun()
M.remove_hook = function(name, callback)
local cbs = hooks[name]
for i, cb in ipairs(cbs) do
if cb == callback then
table.remove(cbs, i)
break
end
end
end
---The default config.buf_filter (takes all buflisted files with "", "acwrite", or "help" buftype)
---@param bufnr integer
---@return boolean
M.default_buf_filter = function(bufnr)
local buftype = vim.bo[bufnr].buftype
if buftype == "help" then
return true
end
if buftype ~= "" and buftype ~= "acwrite" then
return false
end
if vim.api.nvim_buf_get_name(bufnr) == "" then
return false
end
return vim.bo[bufnr].buflisted
end
---Returns true if a session is currently being loaded
---@return boolean
M.is_loading = function()
return _is_loading
end
-- Make sure all the API functions trigger the lazy load
for k, v in pairs(M) do
if type(v) == "function" and k ~= "setup" then
M[k] = function(...)
do_setup()
return v(...)
end
end
end
return M