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
|
--[[ 50-autoreload.lua — opt-in reloading of buffers changed outside Neovim.
When enabled, buffers whose file changed on disk are reloaded silently, in one batch, on focus / idle /
buffer-enter — no per-file change prompt. Conflicts (the buffer was also edited in Neovim) and
deletions still defer to Neovim's usual prompt. Off by default; the state lives in
`vim.g.autoreload` and shows as the `+R` flag in the statusline (see 50-color.lua).
User commands:
`AutoreloadToggle`: toggle disk-change autoreload for this Neovim instance
]]
vim.g.autoreload = false
-- Re-stat every loaded buffer in one pass; the FileChangedShell handler below decides per buffer.
local function check_all_buffers()
if vim.g.autoreload then
vim.cmd.checktime() -- no argument → all loaded buffers at once
end
end
vim.api.nvim_create_autocmd(
{ "FocusGained", "BufEnter", "CursorHold", "CursorHoldI", "TermLeave" },
{
group = vim.g.dotfiles.augroup,
callback = check_all_buffers,
}
)
--[[ Decide what happens when Neovim notices a file changed under it. While autoreload is on, a plain
on-disk change reloads the buffer with no prompt (batched, since `checktime` fires this for each
changed buffer in a single pass); conflicts and deletions fall back to `ask`. While off, everything
falls back to `ask`, i.e. Neovim's default handling. See <nvim-help://v:fcs_choice>. ]]
vim.api.nvim_create_autocmd("FileChangedShell", {
group = vim.g.dotfiles.augroup,
callback = function()
if vim.g.autoreload and vim.v.fcs_reason == "changed" then
vim.v.fcs_choice = "reload"
else
vim.v.fcs_choice = "ask"
end
end,
})
-- Flip autoreload for this instance; check immediately when turning it on so pending changes catch up.
local function toggle_autoreload()
vim.g.autoreload = not vim.g.autoreload
vim.notify("Buffer autoreload " .. (vim.g.autoreload and "enabled" or "disabled"))
check_all_buffers()
vim.cmd.redrawstatus()
end
vim.api.nvim_create_user_command(
"AutoreloadToggle",
toggle_autoreload,
{ desc = "Toggle buffer autoreload" }
)
|