rktjmp / fwatch.nvim

fwatch.nvim lets you watch files or directories for changes and then run vim commands or lua functions.
MIT License
88 stars 2 forks source link

Tripple events #2

Closed Davincible closed 2 years ago

Davincible commented 2 years ago

I use this plugin to watch my pywal cache file to trigger a colorscheme change. I just noticed that I get three events rather than one, on every colorscheme change. I'm not sure if this is a problem with pywal or with this plugin.

Any idea how to debug this?

rktjmp commented 2 years ago

Often programs modify a file more than we think. pywal may be doing something like move file to file.backup create new file write file which might come as 3 events. You can see the same effect when you watch a file you save in vim.

See also https://github.com/luvit/luv/blob/master/docs.md#uv_fs_event_t--fs-event-handle and https://github.com/rktjmp/fwatch.nvim#warnings

FS Event handles allow the user to monitor a given path for changes, for example, if the file was renamed or there was a generic change in it. This handle uses the best backend for the job on each platform.

The callback function will be called with the event as an argument so you can inspect to see whats going on. You can maybe only trigger on a change, not a rename, or schedule a function to run in the future via vim.defer_fn and only setup the defer once.

Vaguely:

local defer = nil
on_event(function()
  if not defer then -- only set once in window
    defer = vim.defer_fn(function()
      defer = nil -- clear for next event out side of window
      apply_something() -- do work
    end), 100)  -- run in 100 ms, probably this can be much lower.
  end
end)
Davincible commented 2 years ago

That defer clearing is genius. Was already using a defer, and was wondering if there's a way I could make it only schedule once but couldn't find anything in the docs. This is exactly it, thanks!

The explanation also makes sense.