I like my vim to get itself into command mode as often as possible. I think losing focus would be a good event to make that happen. Everything I found is for saving on lost focus.
I'd like it to auto-return to cmd mode when switching tabs in macvim or when cmd+tabbing to another app.
The following autocommand would be the "obvious" choice.
au FocusLost,TabLeave * stopinsert
Unfortunately, it only seems to be working properly for TabLeave. The FocusLost event is triggering but for some reason the stopinsert command isn't actually taking effect until after a key event is received once Vim has regained focus.
Instead, you can take advantage of feedkeys and the "Get me to normal mode no matter what!" key combo:
au FocusLost,TabLeave * call feedkeys("\<C-\>\<C-n>")
The only downside is that feedkeys()
requires at least Vim 7. This shouldn't be a big deal, though, since Vim 7 was released back in 2006.
I would have added a comment, but I can't format the solution.
The feedkeys solution is great, with the small hitch that it ALWAYS goes back to normal mode, regardless of what other mode you were in. I don't want to cancel command line mode (for drag&drop files in Windows) and I don't need to cancel visual mode, I just wanted to cancel insert mode.
The solution, then, appears as:
autocmd FocusLost * call PopOutOfInsertMode()
function! PopOutOfInsertMode()
if v:insertmode
feedkeys("\<C-\>\<C-n>")
endif
endfunction
In other words, only pop out if you're in an insert mode. This could be further refined, since v:insertmode will be 'i' in "normal insert", 'r' in Replace mode, and 'v' in Virtual Replace mode. For me, popping out regardless is good, but the user may want to edit to suit.
If this isn't working for you in MacVim, replace the contents of PopOutOfInsertMode
with:
if v:insertmode == 'i' | call feedkeys("\<C-\>\<C-n>") | endif
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With