force vim to overwrite external changes

2019-05-11 03:24发布

问题:

I use Vim 7.4 (Mac OS) to edit and run Lua scripts. I've mapped a key in my .vimrc to save the current buffer and run an external script.

The key map in .vimrc:

map V :w!<CR> :!python "$HOME/tools/client/concli.py" --lua %<CR>

It works fine but every once in a while the files are 'touched' by Xcode (touch shell command). Then when I hit the mapped key vim warns me that the file has been changed externally and I have to confirm to write to it.

This is quite annoying since the files are often touched. How could I force vim to overwrite external changes without prompting? I tried 'w!' without success.

Thank you, Laurent

回答1:

Indeed, the overwrite confirmation cannot be turned off with :w!, and :set autoread doesn't help in this case, neither. What does work is instructing Vim to explicitly check for changes before the write:

:checktime | w


回答2:

I believe

set autoread

should do it. It tells Vim to automatically re-reads the file changed outside Vim.



回答3:

I saw this in a mailing list. Apparently it is called if the file has changed timestamp, after a call to an external shell command.

function! ProcessFileChangedShell()
    if v:fcs_reason == 'mode' || v:fcs_reason == 'time'
        let v:fcs_choice = ''
    else
        let v:fcs_choice = 'ask'
    endif
endfunction

autocmd FileChangedShell call ProcessFileChangedShell()

But it did not consistently fire for me. (Depending whether or not I had edited the file since the change, which in my case was external.)

There are some more tricks on the VimTips wiki which may help.



回答4:

Add this to your ~/.vimrc file:

set autoread
nnoremap <C-u> :checktime<CR>

Now whenever you want vim to reload external changes, just click CTRL-U :)



标签: vim vi