Use Ctrl-O instead of Esc in insert mode mappings
From Vim Tips Wiki
(Redirected from VimTip459)
Tip 459 Previous Next created 2003 · complexity basic · author Yeti · version 6.0
In insert mode, pressing Ctrl-O switches to normal mode for one command, then switches back to insert mode when the command is finished.
For example, do not write mappings like this:
:imap <F5> <Esc>:set number!<CR>a
Instead, use:
:imap <F5> <C-o>:set number!<CR>
One problem with the first mapping is that the cursor moves one character right when it is in the first column. By contrast, the Ctrl-O version has no side effects.
Often you also have a normal-mode mapping, in which case you can write:
:map <F5> :set number!<CR> :imap <F5> <c-o><F5>
When you need to do more than one thing in the mapping, you can
- Use more Ctrl-O, one before each command, or
- Use | to run more commands at once, or
- Define a command (or function) doing everything and map a key to call it.
