diff options
| author | nsfisis <nsfisis@gmail.com> | 2021-12-04 13:09:34 +0900 |
|---|---|---|
| committer | nsfisis <nsfisis@gmail.com> | 2021-12-04 15:38:47 +0900 |
| commit | 7482bb03a7943a3fd9049c7ba61033b42387fac2 (patch) | |
| tree | c5dcb4a27b723ca6fc14a22366e4d2b9477c694a /.config/nvim/lua/autosave.lua | |
| parent | 12f18a076f79470941f7ed54ac2de7effcbff740 (diff) | |
| download | dotfiles-7482bb03a7943a3fd9049c7ba61033b42387fac2.tar.gz dotfiles-7482bb03a7943a3fd9049c7ba61033b42387fac2.tar.zst dotfiles-7482bb03a7943a3fd9049c7ba61033b42387fac2.zip | |
neovim: refactor
Diffstat (limited to '.config/nvim/lua/autosave.lua')
| -rw-r--r-- | .config/nvim/lua/autosave.lua | 80 |
1 files changed, 80 insertions, 0 deletions
diff --git a/.config/nvim/lua/autosave.lua b/.config/nvim/lua/autosave.lua new file mode 100644 index 0000000..ae481ed --- /dev/null +++ b/.config/nvim/lua/autosave.lua @@ -0,0 +1,80 @@ +local M = {} + + +local INTERVAL_MS = 10 * 1000 +local SILENT = true + + +-- Because a timer cannot be converted to Vim value, +-- store indice of timers instead of timer instances. +local timers = {} + + +local function handler() + if not vim.bo.modified then + return + end + if vim.bo.readonly then + return + end + if vim.bo.buftype ~= '' then + return + end + if vim.fn.bufname() == '' then + return + end + + if not SILENT then + vim.cmd([[echohl Comment]]) + vim.cmd([[echo 'Auto-saving...']]) + vim.cmd([[echohl None]]) + end + + vim.cmd([[silent! write]]) + + if not SILENT then + vim.cmd([[echohl Comment]]) + vim.cmd([[echo 'Saved.']]) + vim.cmd([[echohl None]]) + end +end + + +function M.enable() + if vim.b.autosave_timer_id then + return + end + + local timer = vim.loop.new_timer() + timer:start(INTERVAL_MS, INTERVAL_MS, vim.schedule_wrap(handler)) + local tid = #timers + 1 + timers[tid] = timer + vim.b.autosave_timer_id = tid +end + + +function M.disable() + if not vim.b.autosave_timer_id then + return + end + + local tid = vim.b.autosave_timer_id + vim.b.autosave_timer_id = nil + if not timers[tid] then + return + end + timers[tid]:close() + timers[tid] = nil +end + + +function M.toggle() + if vim.b.autosave_timer_id then + M.disable() + else + M.enable() + end +end + + +return M |
