Reloading init.lua when it gets modified across nvim instances

I used to have some vimscript which used fswatch to monitor init.vim and reload it when it gets modified. I’ve been trying to do the same for my init.lua but failing so far with weird errors. Here’s a minimal init.lua:

if FS_event then FS_event:stop() end
local path = vim.fn.expand('~/.config/nvim/init.lua')
FS_event = vim.loop.new_fs_event()
FS_event:start(path, {}, nvim.schedule_wrap(function()
    notif.notify('Sourcing init.lua') -- just prints the msg to the screen

To test this I’ve opened up 3 terminal tabs, one of which has my init.lua open and the other two just with nvim open. If I edit my init.lua, I would expect both nvim instances to show my Sourcing init.lua message and repeat this behaviour each time I edit my init.lua. However, I get unpredictable results. Sometimes it works as expected, sometimes it works for one but nothing happens for the other one, sometimes one (or both) of them prints the error message Error executing vim.schedule lua callback: cannot open /Users/rethy/.config/nvim/init.lua: No such file or directory which is puzzling lol. Anyone know what I’m doing wrong?

I’m on osx but I don’t think that should matter.

Seems like fs_event doesn’t work well on osx, I’ve switched to polling which works fine:

if not Config_watcher then
    Config_watcher = vim.loop.new_fs_poll()
    local init_path = vim.fn.stdpath('config')..'/init.lua'
    Config_watcher:start(init_path, 1500, vim.schedule_wrap(function()
        notif.notify('Sourcing init.lua')
1 Like