Use Ctrl-O instead of Esc in insert mode mappings
From Vim Tips Wiki
Tip 459 • Previous Tip • Next Tip
Created: April 20, 2003 Complexity: basic Author: Yeti Minimum version: 5.7 Karma: 68/25 Imported from: Tip#459
Theory: Ctrl-O in insert mode switches to normal mode for one command and then switches back to insert mode.
Practice: Mappings like
:imap <f5> <esc>:set number!<cr>a
move the cursor one character right when it's in the first column. Use
:imap <f5> <c-o>:set number!<cr>
instead, it has no side-effects. If you have <f5> mapped in normal mode too (to do the same thing),
:imap <f5> <c-o><f5>
is even better.
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 <f5> to it.
[edit] Comments
I've had this mapping for awhile,
" always make F8 toggle paste mode map <F8> :set invpaste<CR>:set paste?<cr>
but it requires I press F8 before I enter insert mode. Well, that's backwards to my brain, so this tip helped me realize I needed this mapping,
imap <F8> <c-o>:set invpaste<cr>
which allows me to enter insert mode, then press F8 (in case I had forgotten to do that), click paste with my mouse, then press ESC and press F8 again, and I've quickly pasted text in my buffer without having my indent settings mess up the pasted text. Sweet.
You can do the same with this in your vimrc:
:set pastetoggle=<F8>
