Detect file change, offer to reload file

Viewed 24108

I normally use gVim for editing, but I sometimes use vim when remotely connecting to my machine.

When I have a file opened in gVim and it has changed from outside (e.g. new updates from repository), gVim offers to reload it.

However when such a thing happens with Vim, it does nothing until you try to save the file. It just warns you that file has changed, but does not offer to reload it.

It there a setting to make Vim's behavior match gVim?

6 Answers

As ashcatch said, the :checktime command will check for changes on disk and prompt you to reload. So set Vim to run checktime automatically after some event. Which event to use is up to you. One possibility is to use CursorHold, which fires after you move the cursor and then let it sit still for updatetime milliseconds. (Default 4 seconds.)

:au CursorHold * checktime

You could also set it on WinEnter or BufWinEnter so it changes every time you switch between buffers/windows. If you're really paranoid you could set it on CursorMoved so it checks the file on disk every time you move the cursor, but that's probably overkill and may lag a bit.

See :h checktime, :h updatetime, :h autocmd-events-abc.

This is done using an auto command called FileChangedShell. I'm too new to post links, but your best bet would be to read the autocmd part of the vim documentation (Google for that)

but the gist is to set something like the following line in your vimrc

:au FileChangedShell * echo "Warning: File changed on disk"

You can manually trigger the checking with :checktime. gvim does this everytime it regains focus, so it is not necessary that often to do the manual checking.

I don't know if there is a different approach (like automatically checking in a certain time interval).

from this answer (refering to an answer by PhanHaiQuang and a comment by flukus)

One can run this oneliner from ex (whithin vim) when needed (or put each command in vimrc, for when log-files are opened.)

:set autoread | au CursorHold * checktime | call feedkeys("lh")

Explanation:
- autoread: reads the file when changed from the outside (but it doesnt work on its own, there is no internal timer or something like that. It will only read the file when vim does an action, like a command in ex :!
- CursorHold * checktime: when the cursor isn't moved by the user for the time specified in 'updatetime' (which is 4000 miliseconds by default) checktime is executed, which checks for changes from outside the file
- call feedkeys("lh"): the cursor is moved once, right and back left. and then nothing happens (... which means, that CursorHold is triggered, which means we have a loop)

Related