8

I have a situation where sometimes my friend and I are working in the same file at the same time.

Vim will tell me if the file has changed when I try to overwrite it. Can I have vim notify me as soon as the file changes, all by itself, before I save?

Questionmark
  • 335
  • 2
  • 12

3 Answers3

6

Did you try the autoread option? From :help 'autoread':

When a file has been detected to have been changed outside of Vim and it has not been changed inside of Vim, automatically read it again.

Martin Tournoij
  • 62,054
  • 25
  • 192
  • 271
4

This question has been answered in StackOverflow: How does Vim's autoread work?

Solution 1

Follow explanations in Vim Wikia page Have Vim check automatically if the file has changed externally. This solution requires the addition of a function to your vimrc file and that a new command is called on the buffers you want to watch.

Solution 2

This solution was proposed by @GregSexton in the question I linked above. The idea is to force the modification check whenever one of the following happens:

  • Entering the buffer.
  • No key was pressed for 'updatetime'
  • Cursor moved.

You can find the code that implements this below:

augroup checktime
    au!
    if !has("gui_running")
        "silent! necessary otherwise throws errors when using command
        "line window.
        autocmd BufEnter        * silent! checktime
        autocmd CursorHold      * silent! checktime
        autocmd CursorHoldI     * silent! checktime
        "these two _may_ slow things down. Remove if they do.
        autocmd CursorMoved     * silent! checktime
        autocmd CursorMovedI    * silent! checktime
    endif
augroup END

Add and/or remove autocmd as best suits your workflow. Check here for the list of events that can be used.

If autoread is also enabled, file will be automatically read if not modified:

set autoread
Vitor
  • 1,742
  • 10
  • 15
2

There are some modes (eg in ex mode, entered by a command starting with :) in which the check shouldn't fire.

Here's what I came up with to avoid checks in unwanted modes:

" Trigger `checktime` when files changes on disk
autocmd FocusGained,BufEnter,CursorHold,CursorHoldI *
        \ if mode() !~ '\v(c|r.?|!|t)' && getcmdwintype() == '' | checktime | endif
Tom Hale
  • 2,681
  • 14
  • 32