File Watcher for Neovim

· Nano Tips for Vim


For automation purposes, you may want to control neovim via an external application. While neovim has tons of APIs and commands for everything, there are not really many options for communication for outside apps.

To make third-party-apps read information about your neovim session, you could use the title option. To have third-party-apps trigger events in neovim, the only method I could find is to use a file watcher from the luv-library, exposed via vim.loop. There, we have four commands for file-system-events, allowing us to use a designated file as intermediary: The external app writes to the file, the file watcher picks up changes, and in turns triggers a function in neovim. The documentation is pretty sparse, but the minimal code for should be this:

 1-- minimal hello-world-style example
 2local watchedFile = "/tmp/nvim"
 3local w = vim.loop.new_fs_event()
 4local function on_change(err)
 5	print("file has changed")
 7w:start(watchedFile, {}, on_change)
 9-- with error-handling
10local watchedFile = "/tmp/nvim"
11local w = vim.loop.new_fs_event()
12local function on_change(err)
13	if err then
14		print(err)
15		return
16	end
17	print("file has changed")
18	if w then 
19		w:stop()
20		w:start()
21	end
24if w then
25	w:start(watchedFile, {}, on_change)