6

我喜欢我的 vim 尽可能多地进入命令模式。我认为失去焦点将是实现这一目标的好事件。我发现的一切都是为了节省注意力。

我希望它在 macvim 中切换选项卡或 cmd+tabbing 到另一个应用程序时自动返回到 cmd 模式。

4

2 回答 2

17

以下自动命令将是“显而易见的”选择。

au FocusLost,TabLeave * stopinsert

不幸的是,它似乎只适用于 TabLeave。FocusLost 事件正在触发,但由于某种原因,stopinsert命令直到 Vim 重新获得焦点后收到键事件后才真正生效。

相反,您可以利用feedkeys和“无论如何都让我进入正常模式!” 组合键

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

唯一的缺点是feedkeys()至少需要 Vim 7。不过,这应该没什么大不了的,因为 Vim 7 早在 2006 年就发布了。

于 2010-06-03T19:19:46.923 回答
7

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
于 2010-10-18T18:18:19.317 回答