tags:

views:

90

answers:

2

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.

+8  A: 

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.

jamessan
Perfect, thanks!
Trevor Hartman
Cool- never knew about `Ctrl-\_Ctrl-N`. I had the stopinsert line in my vimrc but always was bugged by the fact that it took one more character when returning to the buffer...:wq
dash-tom-bang
I would have commented, but my comment comes with formatting. See below. :) I must thank @jamessan for guidance on this.
dash-tom-bang
+2  A: 

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.

dash-tom-bang
Thanks for the additional info! I discovered the same problem with the original solution. Tabbing away while in command mode to look something up then coming back and finding it cleared was frustrating.
Trevor Hartman