How to write the contents of the current buffer back to file on each key press in Vim?
file, vim
Solution
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.
Problem
I’d like Vim to automatically write my file as often as possible. The ideal would be every keystroke. I need to save regularly so that my background build process will see it. It’s a makefile for a LaTeX document, and I’d like the previewer to show me a nearly up-to-date document when I’m finished typing. Eventual solution The answers below helped to make this. ``` " Choose your own statusline here let g:pbstatusline="%F\ %y\ %l:%c\ %m" set statusline=%F\ %y\ %l:%c\ %m autocmd FileType tex setlocal autowriteall " Save the file every 5 keypresses autocmd FileType tex setlocal statusline=%!pb:WriteFileViaStatusLine() " Save the file every time this event fires. autocmd FileType tex :autocmd InsertLeave,CursorHold,CursorHoldI * call pb:WriteFileViaStatusLine("always") " 1 optional param: "always" is only allowed value. let s:writefilecounter = 0 function! pb:WriteFileViaStatusLine(...) if s:writefilecounter > 5 || (a:0 > 0 && a:1 == "always") if &buftype == "" write endif let s:writefilecounter = 0 else let s:writefilecounter = s:writefilecounter + 1 endif return g:pbstatusline endfunction ```