Vim: return to command mode when focus is lost

I like it when my vim gets as often as possible in command mode. I think that loss of attention will be a good event to make this happen. All I have found is maintaining lost focus.

I would like it to automatically return to cmd mode when switching tabs in macvim or when cmd + tabbing in another application.

+6
vim macvim
source share
2 answers

The next auto command will be the “obvious” choice.

au FocusLost,TabLeave * stopinsert 

Unfortunately, it seems to work correctly for TabLeave. The FocusLost event is fired, but for some reason the stopinsert command does not actually take effect until a key event is received after Vim regains focus.

Instead, you can use feedkeys and "Get me in normal mode, no matter what!" key combo :

 au FocusLost,TabLeave * call feedkeys("\<C-\>\<Cn>") 

The only drawback is that feedkeys() requires at least Vim 7. This should not be a big problem, although Vim 7 was released back in 2006.

+16
source share

I would add a comment, but I can not format the solution.

The feedkeys solution is excellent, with a little clue, that it ALWAYS returns to normal mode, no matter what other mode you were in. I don’t want to cancel the command line mode (for dragging and dropping files on Windows) and I don’t need to cancel the visual mode, I just wanted to cancel the insert mode.

Then the solution appears as:

 autocmd FocusLost * call PopOutOfInsertMode() function! PopOutOfInsertMode() if v:insertmode feedkeys("\<C-\>\<Cn>") endif endfunction 

In other words, exit only if you are in insert mode. This could be clarified, since v: insertmode will be "i" in "normal insertion", "r" in "Replace" mode, and "v" in virtual replacement mode. It pops up for me independently, which is good, but the user may want to edit it.

If this does not work for you on MacVim, replace the contents of PopOutOfInsertMode with:

 if v:insertmode == 'i' | call feedkeys("\<C-\>\<Cn>") | endif 
+7
source share

All Articles