robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

Justin M. Keyesfix(autoread): 'autoread' error if file goes missing #402764ed844be59

master
6.0 KiB203 linesraw
1--- Provides 'autoread' via OS filewatchers: watches 'autoread' buffer files for external changes
2--- using vim._watch. Complements the existing FocusGained/:checktime approach.
3
4local uv = vim.uv
5local watch = vim._watch
6local nvim_on = require('vim._core.util').nvim_on
7
8local M = {}
9
10local debounce_ms = 100
11--- @type table<integer, fun()> bufnr -> cancel function
12local watchers = {}
13--- @type table<integer, uv.uv_timer_t> bufnr -> debounce timer
14local timers = {}
15--- @type table<integer, true> bufnr -> true. Tracks pending autoreads (debounce window, or :checktime in flight),
16--- so we can surface activity via the 'busy' flag.
17local pending = {}
18--- @type table<integer, true> bufnr -> true. Tracks which `pending` buffers have set 'busy'.
19local pending_busy = {}
20
21--- @private
22--- Test-only: override the debounce window so tests can run faster.
23--- @param ms integer
24function M._set_debounce(ms)
25  debounce_ms = ms
26end
27
28--- @private
29--- @param bufnr integer
30--- @return boolean
31function M._is_watching(bufnr)
32  return watchers[bufnr] ~= nil
33end
34
35--- Sets the 'busy' option on a `pending` buffer. Idempotent: if `pending` and `pending_busy`
36--- already agree, it's a no-op. Must run on main thread.
37---
38--- @param bufnr integer
39local function sync_busy(bufnr)
40  if not vim.api.nvim_buf_is_valid(bufnr) then
41    pending_busy[bufnr] = nil
42    return
43  end
44  local want = pending[bufnr] ~= nil
45  local have = pending_busy[bufnr] ~= nil
46  if want == have then
47    return
48  end
49  vim.bo[bufnr].busy = math.max(0, vim.bo[bufnr].busy + (want and 1 or -1))
50  pending_busy[bufnr] = want or nil
51end
52
53--- Sends `pending` state for `bufnr`.
54---
55--- @param bufnr integer
56--- @param is_pending boolean
57local function set_pending(bufnr, is_pending)
58  pending[bufnr] = is_pending or nil
59  vim.schedule(function()
60    sync_busy(bufnr)
61  end)
62end
63
64--- Returns the effective 'autoread' value for a buffer.
65--- 'autoread' is global-local: vim.bo[bufnr].autoread is nil when not set locally,
66--- so we must fall back to the global value.
67--- @param bufnr integer
68--- @return boolean
69local function buf_autoread(bufnr)
70  local local_val = vim.bo[bufnr].autoread
71  if local_val ~= nil then
72    return local_val
73  end
74  return vim.go.autoread
75end
76
77--- Returns true if the buffer should be watched.
78--- @param bufnr integer
79--- @return boolean
80local function should_watch(bufnr)
81  if not vim.api.nvim_buf_is_loaded(bufnr) then
82    return false
83  end
84  -- Skip special buffers (terminal, help, quickfix, etc.)
85  if vim.bo[bufnr].buftype ~= '' then
86    return false
87  end
88  -- Must have a file name that exists on disk
89  local name = vim.api.nvim_buf_get_name(bufnr)
90  if name == '' or not uv.fs_stat(name) then
91    return false
92  end
93  if not buf_autoread(bufnr) then
94    return false
95  end
96  return true
97end
98
99--- Stops and cleans up the watcher for a buffer.
100--- @param bufnr integer
101local function stop_watcher(bufnr)
102  set_pending(bufnr, false)
103  local cancel = watchers[bufnr]
104  if cancel then
105    cancel()
106    watchers[bufnr] = nil
107  end
108  local timer = timers[bufnr]
109  if timer then
110    timer:stop()
111    timer:close()
112    timers[bufnr] = nil
113  end
114end
115
116--- Ensures the buffer has an active file watcher if appropriate, or stops
117--- an existing one if the buffer should no longer be watched.
118--- @param bufnr integer
119local function ensure_watcher(bufnr)
120  stop_watcher(bufnr)
121
122  if not should_watch(bufnr) then
123    return
124  end
125
126  local name = vim.api.nvim_buf_get_name(bufnr)
127  local timer = assert(uv.new_timer())
128  timers[bufnr] = timer
129
130  local cancel = watch.watch(name, {}, function(_, change_type)
131    -- Set the 'busy' buffer option for the duration of the pending cycle. This is a small, "best
132    -- effort" UX hint, not intended to be noticeable except when filewatcher activity is "noisy".
133    set_pending(bufnr, true)
134    -- Debounce: restart the same timer on each event, so only the last
135    -- event in a rapid series (e.g. truncate + write) triggers checktime.
136    timer:start(debounce_ms, 0, function()
137      vim.schedule(function()
138        sync_busy(bufnr)
139        if not vim.api.nvim_buf_is_loaded(bufnr) or not buf_autoread(bufnr) then
140          set_pending(bufnr, false)
141          return
142        end
143
144        -- :checktime may throw if file was deleted (E211), or if reload triggers a buggy autocmd.
145        local ok, err = pcall(vim.cmd.checktime, bufnr) ---@type any, any
146        local file_missing = tostring(err):find('E211:', 1, true)
147
148        set_pending(bufnr, false)
149        -- Update the watcher if it's now stale: "rename" events (watcher pointing to old inode), or
150        -- file deleted between event-and-:checktime.
151        if change_type ~= watch.FileChangeType.Changed or file_missing then
152          ensure_watcher(bufnr)
153        end
154        if not ok and not file_missing then
155          vim.api.nvim_echo({
156            { ('autoread: :checktime failed for buffer %d: %s'):format(bufnr, err) },
157          }, true, { err = true })
158        end
159      end)
160    end)
161  end)
162
163  watchers[bufnr] = cancel
164end
165
166function M.enable()
167  local group = vim.api.nvim_create_augroup('nvim.autoread', { clear = true })
168
169  -- (Re)start watcher when a file is loaded or written.
170  nvim_on({ 'BufReadPost', 'BufWritePost' }, group, function(args)
171    ensure_watcher(args.buf)
172  end)
173
174  -- Stop watcher when buffer is unloaded or wiped out.
175  nvim_on({ 'BufUnload', 'BufWipeout' }, group, function(args)
176    stop_watcher(args.buf)
177  end)
178
179  -- Clean up all watchers on exit to avoid dangling handles in the event loop.
180  nvim_on('VimLeavePre', group, function()
181    for bufnr in pairs(watchers) do
182      stop_watcher(bufnr)
183    end
184  end)
185
186  -- React to 'autoread' option changes.
187  nvim_on('OptionSet', group, { pattern = 'autoread' }, function()
188    if vim.v.option_type == 'global' then
189      for _, bufnr in ipairs(vim.api.nvim_list_bufs()) do
190        ensure_watcher(bufnr)
191      end
192    else
193      ensure_watcher(vim.api.nvim_get_current_buf())
194    end
195  end)
196
197  -- Attach to buffers that were already loaded before enable() ran.
198  for _, bufnr in ipairs(vim.api.nvim_list_bufs()) do
199    ensure_watcher(bufnr)
200  end
201end
202
203return M