views:

350

answers:

3

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 answer (the answers below helped 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
+5  A: 

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.

Eevee
I replied to the why in an edit.
Paul Biggar
I think Eevee is right that CursorMoved see this Vim tip which does something on every cursor move: http://vim.wikia.com/wiki/Highlight_cursor_line_after_cursor_jump
Drew Stephens
If you could move the last 2 paragraphs to the top, I would mark this correct. Thanks.
Paul Biggar
Yeah, swap file doesn't help you much here. Done.
Eevee
Ta. I also added CursorHold and CursorHoldI
Paul Biggar
The other answer was a great answer, so had to change the one I picked. Sorry.
Paul Biggar
Oh, don't worry about it; that's a very clever answer.
Eevee
+4  A: 

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.

rampion
Changed this to the right answer. This is by far the best way I've heard of.
Paul Biggar
Those who wants to use rampion's semi-default formatting string in a `set statusline` command, don't forget to escape the spaces with blackslashes - I've lost nearly an hour on that!
pestaa