Vim Tips Wiki
Advertisement
Tip 459 Printable Monobook 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.

Ctrl-O sometimes has weird side effects when at the end of the line, in which case you can use <C-\><C-O> instead.

Comments[]

Anonymous user posted:

You can use Ctrl-O to remap Ctrl-h/j/k/l to move the cursor while in insert mode without using the arrow keys:

:imap <C-h> <C-o>h
:imap <C-j> <C-o>j
:imap <C-k> <C-o>k
:imap <C-l> <C-o>l
Sure you can, but why? Remapping <C-l> to <Left>, etc. seems to make more sense, and won't do things like move the cursor twice when in the last column in a line. I guess you could get around this with <C-\><C-O>l, but why not just use <Left> in the mapping instead? --Fritzophrenic 22:10, February 5, 2010 (UTC)
Anonymous comment: Also with <Left>, <Right>, etc. It is possible to use this binding elsewhere (for example in completion candidates list instead of <C-n> and <C-p>), which might be useful.
I don't understand why you would map <C-L> to <Left>, rather than to <Right>. Why not be consistent with normal mode hjkl movements? Although <C-h> deletes backwards -- too useful an action to sacrifice, imo.
Advertisement