馃尡 tiny neovim plugin keeping your session safe
1local nivvie = {}
2
3---@param cfg? nivvie.config.proto
4function nivvie.setup(cfg)
5 cfg = cfg or {}
6 require('nivvie.config').set(cfg)
7end
8
9nivvie.autorestored = false
10nivvie.stdin = false
11
12function nivvie.get_uri()
13 return string.gsub(vim.fn.getcwd(), '[^a-zA-Z0-9_.-]', function(s)
14 return '<' .. vim.fn.char2nr(s)
15 end)
16end
17
18---@param name? string
19function nivvie.get_path(name)
20 local sessiondir = require('nivvie.config').get().session_dir
21 return vim.fs.joinpath(sessiondir, (name or nivvie.get_uri()) .. '.vim')
22end
23
24---@param name? string
25function nivvie.save(name)
26 local session_file = nivvie.get_path(name)
27
28 local sessiondir = require('nivvie.config').get().session_dir
29 vim.fn.mkdir(sessiondir, 'p')
30
31 vim.api.nvim_cmd({
32 cmd = 'mksession',
33 bang = true,
34 args = { session_file },
35 }, {})
36end
37
38function nivvie.clean()
39 vim.iter(ipairs(vim.api.nvim_list_bufs())):each(function(_, bufnr)
40 if vim.bo[bufnr].buftype ~= '' then
41 vim.api.nvim_buf_delete(bufnr, { force = true })
42 end
43 end)
44end
45
46---@param name? string
47function nivvie.restore(name)
48 local path = nivvie.get_path(name)
49 if vim.uv.fs_stat(path) then
50 vim.api.nvim_cmd({
51 cmd = 'source',
52 args = { path },
53 }, {})
54 vim.v.this_session = path
55 vim.api.nvim_exec_autocmds('SessionLoadPost', {})
56 end
57end
58
59----
60
61function nivvie.isemptysession()
62 -- whether StdinReadPost was handled or ttyin was set
63 if nivvie.stdin or vim.fn.has 'ttyin' == 0 then
64 return false
65 end
66
67 if vim.fn.argc() > 0 then
68 return false
69 end
70
71 local bufs = vim.api.nvim_list_bufs()
72 bufs = vim
73 .iter(bufs)
74 :filter(function(buf)
75 return vim.api.nvim_buf_is_valid(buf)
76 and vim.bo[buf].buftype == ''
77 and #vim.api.nvim_buf_get_name(buf) > 0
78 end)
79 :totable()
80
81 return #bufs == 0
82end
83
84--- only restore if necessary
85function nivvie.autorestore()
86 if not require('nivvie.config').get().autorestore then
87 return
88 end
89
90 if not nivvie.isemptysession() then
91 return
92 end
93
94 nivvie.autorestored = true
95
96 nivvie.restore()
97end
98
99-- only save if nvim was not started with file arguments/stdin
100function nivvie.autosave()
101 if not nivvie.autorestored then
102 return
103 end
104
105 if not require('nivvie.config').get().autosave then
106 return
107 end
108
109 require('nivvie').clean()
110 require('nivvie').save()
111end
112
113return nivvie