How to write the contents of the current buffer back to file on each key press in Vim?

These hacks are not needed any more. Vim can automatically write a file to disk whenever it is changed. Just add this to your $MYVIMRC:

autocmd TextChanged,TextChangedI <buffer> write

I believe you need Vim 7.4. In contrast to autosave=1, this will save your file as soon as you change it.


One hack is to use your status line:

function! WriteFile() 
  if &buftype == ""
    write
  endif
  return '%f %h%w%m%r%=%-14(%l,%c%V%) %(%P%)'
endfunction
setlocal statusline=%!WriteFile()
set laststatus=2

As long as the status line is visible, it's updated after each change to the file. When updated, the WriteFile() function is called, which writes the file (and returns my approximation at the default status line). With laststatus=2, the status line is shown even when only one window is open.

This will keep the current buffer saved after each change.


There are CursorMoved and CursorMovedI autocmd events, but I don't think there's one that applies every single time you type in Insert mode.

You could also, were you so bold, rebind every single printable character in Insert mode to save and then type the character.

Tags:

Vim

File