How to auto-save a file every 1 second in vim?

后端 未结 3 1660
暖寄归人
暖寄归人 2020-12-08 04:30

I don\'t want to know about why you should not auto-save or there is swap file etc or whatever reason to not auto-save.

I simply want to auto-save the current workin

相关标签:
3条回答
  • 2020-12-08 04:49

    This saves the buffer whenever text is changed. (Vim 7.4)

    autocmd TextChanged,TextChangedI <buffer> silent write

    0 讨论(0)
  • 2020-12-08 05:04

    The vim-workspace plugin has a fairly customizable auto-save feature that may suit your needs (with autoread so you get last writer wins behaviour). You can set it to always autosave (by default, it only autosaves while in a workspace session) and set your updatetime accordingly.

    let g:workspace_autosave_always = 1
    updatetime=1000
    
    0 讨论(0)
  • 2020-12-08 05:06

    When you start reading a file, set a buffer variable to the current time:

    au BufRead,BufNewFile * let b:save_time = localtime()
    

    Set an event to check if enough time has elapsed since the last save and update if not:

    au CursorHold * call UpdateFile()
    

    Set the auto-save period, in seconds:

    let g:autosave_time = 1
    

    Define a function to save the file if needed:

    " save if needed / update the save_time after the save
    function! UpdateFile()
      if((localtime() - b:save_time) >= g:autosave_time)
          update
          let b:save_time = localtime()
      else
          " just debugging info
          echo "[+] ". (localtime() - b:save_time) ." seconds have elapsed so far."
      endif
    endfunction
    

    Then, to reset the save time explicitly:

    au BufWritePre * let b:save_time = localtime()
    

    I have not tested the above on vim 7.0 and later. Also, the CursorHold event is unlikely to be enough for such a small auto-save period (it also doesn't trigger when recording) - maybe you should also call UpdateFile() on CursorMoved as well.

    Also, consider using swap files. By default a swap file is writen to after either 200 characters typed or 4 seconds of inactivity. Recovery from swap is quite simple and maybe more reliable, in case something goes wrong.

    0 讨论(0)
提交回复
热议问题