Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make Vim autosave files when it loses focus?

Tags:

vim

I'm used to my editors autosaving files when they lose focus. I recently switched to MacVim, and I can't recreate that behavior. I tried this:

autocmd BufLeave,FocusLost * wall 

but if a buffer is unnamed when the window or MacVim loses focus, I get an error like the following:

Error detected while processing BufLeave Auto commands for "*": E141: No file name for buffer 1 

I'm confused, because :wall's documentation says:

Write all changed buffers.  Buffers without a file name or which are readonly are not written. 

so I'd expect it to skip unnamed buffers. Is there a better way to do this?

Edit:

I'm pretty sure that the better way to do what I intended by using BufLeave -- saving buffers when I switch between them, so I don't get "No write since last change" -- is to set 'autowriteall'. The question still stands for when MacVim loses focus to other applications (FocusLost).

like image 983
Peeja Avatar asked Jan 09 '11 03:01

Peeja


People also ask

How do I turn on AutoSave in Vim?

AutoSave is disabled by default, run :AutoSaveToggle to enable/disable AutoSave. If you want plugin to be always enabled it can be done with g:auto_save option (place 'let g:auto_save = 1' in your . vimrc). Inspired by the same feature in RubyMine text editor.

How do I save a buffer in Vim?

I edit it, then I use ':w' to save it and ':bd' to close the buffer and move on to the next one. This ':w:bd' to save and close the buffer feels long to me, and I suspect there's a more Vim ninja way of doing it.


1 Answers

You don’t care about errors in those circumstances since there is nothing you can reasonably do about them anyway – especially when losing focus. So just swallow them:

autocmd BufLeave,FocusLost * silent! wall 

Much simpler than an elaborate dance to figure out where there would be an error in order to avoid it.

like image 160
Aristotle Pagaltzis Avatar answered Sep 20 '22 20:09

Aristotle Pagaltzis