I want to run a :command in vim when I exit insert mode. Specifically I want to run :GoFmt to format my code when I exit insert mode. Currently it runs when I save the file but sometimes I want to format before I do a syntax check (which happens when I save the file).

My current solution was to map <esc> to <esc>:GoFmt<enter> but this breaks the behavior of the arrow keys because the arrow keys start with an escape sequence. Is there a better solution?

autocmd FileType go imap <esc> <esc>:GoFmt<enter>
  • 3
    You might get a more in-depth answer to this over at the vi/Vim stack exchange, just FYI. vi.stackexchange.com :)
    – Wildcard
    Commented Nov 19, 2016 at 3:02

1 Answer 1


Well first, I strongly support Wildcards suggestion to go to the vim site... :)

But second, there is definitely a better solution. You can use an InsertLeave autocommand. Just do this:

autocommand InsertLeave go GoFmt

The advantage is that this doesn't require any mappings at all, and running the command is also simpler because GoFmt is already an ex command, so you do not need the :...<cr>.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .