How can I make vim check automatically if the file has changed externally?
I usually open many files in tabs with vim -p
. Is it possible to check if any of the files was changed outside of Vim since e开发者_运维百科diting started?
Add these lines to your .vimrc
:
au FocusGained,BufEnter * :silent! checktime
au FocusLost,WinLeave * :silent! w
Basically, check for and reload (or discard) external changes when Vim or the current buffer gains focus, and optionally, auto-save when leaving focus.
Source: Vim Wiki.
I came across an interesting find related to this question today...
Hidden in /usr/share/vim/vim71/vimrc_example.vim
there is this command:
" Convenient command to see the difference between the current buffer and the
" file it was loaded from, thus the changes you made.
command DiffOrig vert new | set bt=nofile | r # | 0d_ | diffthis
\ | wincmd p | diffthis
It will open a vimdiff
-like window with the current buffer and the underlying file highlighting all of the changes between the two.
vim usually warns me automatically if it detects an external change to a file; however, from perusing the documentation it looks like you can invoke that check manually with :checktime
Unfortunately I don't know how to disable that aforementioned automatic check to test and see if checktime does the right thing, so this answer might be completely off-base.
Use :edit
:help :edit
for more info.
You can find out if the buffer in the active window is modified by running the command:
:set mod?
If it returns nomodified
, then the contents of the buffer match those of the corresponding file. If it returns modified
, then the buffer has unsaved changes.
By default, the status-line shows a [+]
symbol if the current buffer has been modified. The status line is generally only visible if you have split windows. If you want to show the status line, even when you have just a single window, run:
:set laststatus=2
There's a good article about customizing your status line on Vim Recipes.
let s:pid=system("ps -p $$ -o ppid=")+0
if !exists('g:watches')
let g:watches={}
else
finish
endif
function! ModWatch(fname, match)
let fname=fnamemodify(a:fname, ':p')
if has_key(g:watches, fname)
return
endif
let shellscript=
\"while true ; do".
\" inotifywait ".shellescape(fname)." ; ".
\" kill -WINCH ".s:pid." ; ".
\"done"
echo shellscript
echo shellescape(shellscript)
let pid=system("sh -c ".shellescape(shellscript)." &>/dev/null & echo $!")+0
call extend(g:watches, { fname : pid })
augroup ModWatch
execute "autocmd! BufWipeOut ".a:match
execute "autocmd BufWipeOut ".a:match.' call DeleteWatch("'.
\escape(fname, '\"|').'")'
augroup END
endfunction
function! DeleteWatch(fname)
call system("kill ".g:watches[a:fname])
unlet g:watches[a:fname]
endfunction
augroup ModWatch
autocmd!
autocmd VimResized * checktime
autocmd BufNew * call ModWatch(expand("<afile>"), expand("<amatch>"))
augroup END
精彩评论