Is it possible to make Vim automatically exit whatever mode it's in and return to normal mode when the terminal window loses focus?


Add this to your vimrc:

autocmd FocusLost * call feedkeys("\<esc>")

This essentially means "If we lose focus (autocmd FocusLost) on any filetype (*), then type an escape key as if I pressed it (call feedkeys("\<esc>")

Recommended reading: :help FocusLost and :help autocommand

As Statox pointed out in the comments, this will only work for GVim, and certain terminals.

  • this didn't work
    – ewok
    Jul 7 '16 at 21:12
  • 4
    If I may point it out, the doc says Only for the GUI version and a few console versions where this can be detected. so in some cases this might not work.
    – statox
    Jul 7 '16 at 21:12
  • @ewok What OS and terminal are you using?
    – DJMcMayhem
    Jul 7 '16 at 21:19
  • Windows7, Cygwin. but I'm looking for a cross-platform solution I can use anywhere
    – ewok
    Jul 7 '16 at 21:23
  • 5
    @ewok - a cross platform solution is impossible. Vim runs on raw tty's and inside things like screen and tmux. All these three options have no access to anything like a focus, by design.
    – grochmal
    Jul 7 '16 at 22:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.