How can I make Vim autosave files when it loses focus?

前端 未结 4 695
梦谈多话
梦谈多话 2020-12-25 11:02

I\'m used to my editors autosaving files when they lose focus. I recently switched to MacVim, and I can\'t recreate that behavior. I tried this:

autocmd Bu         


        
相关标签:
4条回答
  • 2020-12-25 11:42
    autocmd BufLeave,FocusLost * bufdo! call WriteFile()
    
    function WriteFile()
       if (&buftype=="") && (expand("%:r") > "") && (&readonly==0)
          write
       endif
    endfunction
    

    This method has a side-effect that, you can only open one unamed buffer. If you open the second one, it would automatically be synced to the content of the first unamed buffer.

    0 讨论(0)
  • 2020-12-25 11:44

    I suspect when docs for wall say "without a file name" they may be referring to buffers with buftype=nofile . One way to get what you want would be to have the autocmd have bufdo call a simple function. E.g., some untested code to give the idea:

    autocmd BufLeave,FocusLost * bufdo! call WriteFile()
    
    function WriteFile()
       if (&buftype=="") && (expand("%:r") > "") && (&readonly==0)
          write
       endif
    endfunction
    

    I think the standard way of getting something like this automatic saving of buffers would be to set the autosave option in Vim.

    0 讨论(0)
  • 2020-12-25 11:48

    You don’t care about errors in those circumstances since there is nothing you can reasonably do about them anyway – especially when losing focus. So just swallow them:

    autocmd BufLeave,FocusLost * silent! wall
    

    Much simpler than an elaborate dance to figure out where there would be an error in order to avoid it.

    0 讨论(0)
  • 2020-12-25 11:53

    just put this in .vimrc

    set updatetime=1000
    autocmd CursorHoldI * silent w
    
    0 讨论(0)
提交回复
热议问题