Check is_dirty to prevent invoking auto-save when file is reloaded from disk #13
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Hi James,
First, thank you for this wonderful ST plug-in. I use it pretty much every day when taking notes at work to make sure all changes are saved.
I noticed an issue caused by auto-save's callback being called when the file is reloaded from disk. In my case, this happens if I change the file on another computer and the file is then synced via Dropbox. But it can also happen if a local program is appending the file while it is open in Sublime Text (and auto-save is active). What happens is that when a file is changed on disk, Sublime Text will automatically reload it. When reloading a file, Sublime Text will call EventListeners' on_modified. (It actually calls it twice, although that might be a bug.)
Calling EventListeners' on_modified may be desired for other plugins. However, we do not want auto-save to save the view after the file has been reloaded. First, because the file is already in sync with the disk (since it has just been reloaded). And second, because if another program is actively updating a file, and Sublime Text then also tries to save the file every time it is reloaded, this can produce conflicting versions.
The issues can be resolved by checking whether the view actually needs to be saved using view.is_dirty(). I've also added a check for view.is_loading(), which becomes relevant for very large files (larger than 5-10 MB on my system).
I've placed the is_dirty() check both in the callback() function and in the EventListener's on_modified() method. The check in the callback() function is the most important. However, as mentioned, on_modified is called twice when a file is reloaded (at least in the current version of Sublime). The first time on_modified() is called, is_dirty() returns True. The second time, is_dirty() returns False. Checking is_dirty() before scheduling debounce_save simply prevents the second of these two calls (i.e. it is just an optimization). Once the callback is called, view.is_dirty() will return False (at least in all my tests).