Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

file

vim

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
like image 412
Paul Biggar Avatar asked Aug 21 '09 17:08

Paul Biggar


People also ask

How do I manage buffers in Vim?

Plugins. script, and place the following in your vimrc. Pressing Alt-F12 opens a window listing the buffers, and you can press Enter on a buffer name to go to that buffer. Or, press F12 (next) or Shift-F12 (previous) to cycle through the buffers.

What does Ctrl-o do in Vim?

In insert mode, Ctrl-o escapes user to do one normal-mode command, and then return to the insert mode. The same effect can be achieved by <ESC> ing to normal mode, doing the single command and then entering back to insert mode. Ctrl-i is simply a <Tab> in insert mode.

What does buffer mean in Vim?

A buffer is an area of Vim's memory used to hold text read from a file. In addition, an empty buffer with no associated file can be created to allow the entry of text. The :e filename command can edit an existing file or a new file.

How do I close all buffers in Vim?

Just put it to your . vim/plugin directory and then use :BufOnly command to close all buffers but the active one.


1 Answers

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.

like image 142
Sameer Avatar answered Oct 10 '22 01:10

Sameer