vim - Autosave file to disk, efficiently

1

I keep a log file, and want it to be written to disk without having to manually save it after every edit.

I've used the :au! CursorHoldI,CursorHold <buffer> silent! :update command that I found somewhere, and that works well, and is efficient: with 'updatetime' of 4 seconds by default, it will write the file to disk (only if changed, hence :update, not :write) after the cursor has been in the same place for 4 seconds, in both insert and normal modes. (While the buffer has focus within Vim. Whether or not Vim has focus, which is a subtle point. That is, if Vim loses focus, the file is still saved after 4 seconds.)

The only problem is that if I have another file open with :split, and click or Ctrl+W,k there, then the original file is not saved after 'updatetime' ms. How can this be corrected?

Evgeni Sergeev

Posted 2014-02-03T01:57:24.423

Reputation: 1 704

Answers

1

The :wall command (more commonly used by the abbreviated :wa) will, just like :update, only write a file if it is saved. The difference is, it will write ALL open files, not just the current one.

You could use the same autocmd you have, and just use :wa in place of :update.

Ben

Posted 2014-02-03T01:57:24.423

Reputation: 2 050

Right! I didn't realise that :wa will only write changed files. It should really be called ":updateall". Also, then silent! is not necessary — :wall checks for non-file and read-only buffers. – Evgeni Sergeev – 2014-02-05T05:18:18.323

0

One solution is to add the BufLeave event, making a command like this:

:au! CursorHoldI,CursorHold,BufLeave <buffer> silent! :update

In my .vimrc (aka _vimrc), I've defined

noremap <C-S-F5> :au! CursorHoldI,CursorHold,BufLeave <buffer> silent! :update<CR>

So that I press Ctrl+Shift+F5 in that buffer to put it into autosave mode.

Note: the silent will not print any message, and silent! will also not print any errors, and ignore them. This is for buffers that do not have associated files, and read-only files.

Evgeni Sergeev

Posted 2014-02-03T01:57:24.423

Reputation: 1 704