107.07.21 vim 檔案外部修改刷新

如何不關掉 vim 就刷新外部對此檔案的更新?
這其實是頗常見的問題
完成如 gif (在右方更新內容儲存後左邊馬上刷新)



就是 vim 編輯檔案到一半,如果外面有其他程式也更新了這份檔案時
vim 是不會刷新的更新的內容的
舊方法就是重開這個檔案
但就是不合我意(?
之前有找到可以設定 autoread,但是好像沒有差別一樣不會更新
主要是因為 vim 不知道何時要去更新
不過這很正常因為如果一直去更新就會影響效能
網路上有人解法是利用 autocmd 去偵測游標移動,但就沒有那麼即時
而且用 autocmd 過於頻繁會讓游標移動有些延遲
沒有 vim8 或不想多開一個平行任務的可以參考這裡
code 也貼出來好了 (怕連結失效
註解有點多=''=,放在 .vimrc 中
" Triger `autoread` when files changes on disk "
" https://unix.stackexchange.com/questions/149209/refresh-changed-content-of-file-opened-in-vim/383044#383044 "
" https://vi.stackexchange.com/questions/13692/prevent-focusgained-autocmd-running-in-command-line-editing-mode "
autocmd FocusGained,BufEnter,CursorHold,CursorHoldI * if mode() != 'c' | checktime | endif
" Notification after file change "
" https://vi.stackexchange.com/questions/13091/autocmd-event-for-autoread "
autocmd FileChangedShellPost *
  \ echohl WarningMsg | echo "File changed on disk. Buffer reloaded." | echohl None


那....
既然我們有 vim8 所以不擔心效能(?
直接上程式碼 (第一行是查到最簡易的 timer 用法)

" Ref: http://vimhelp.appspot.com/eval.txt.html#timer_start%28%29 "
set autoread
function Fresh(arg)
    execute 'checktime'
endfunction
let timer = timer_start(500, 'Fresh', {'repeat': -1})
想增加提示的話也可以順便加入下面的程式碼
autocmd FileChangedShellPost *
  \ echohl WarningMsg | echo "File changed on disk. Buffer reloaded." | echohl None


參考資料:
refresh changed content of file opened in vi(m)

沒有留言:

張貼留言

^ Top