Subscribe for free with iTunes, Twitter, or RSS (Ogg or Quicktime).

Vimcasts

Pasting from Insert mode

#55

We don’t have to be in Normal mode to paste the contents of a register. The <C-r>{reg} command lets us paste a register from Insert mode (and it works in commandline mode too!) Using this command allows us to make changes that can be repeated with the dot command.

Download

OGG 5.4 MB

Quicktime 8.7 MB

In Insert mode, we can use the <C-r>{reg} command to paste the contents from any of Vim’s registers. For example, pressing <C-r>a would insert the contents of named register ‘a’, while pressing <C-r>0 would insert the contents of the yank register. In Vim’s documentation, it lists a few more registers that can be useful in this context:

register description
" the default register
% the current file name
# the alternate file name
* the clipboard contents (X11: primary selection)
+ the clipboard contents
/ the last search pattern
: the last command-line
. the last inserted text
- the last small (less than a line) delete

Note that the <C-r>{reg} commands can also be used at Vim’s command line.

Variations on <C-r>{reg}

The <C-r>{reg} command comes with a few variations, including <C-r><C-r>{reg}, <C-r><C-o>{reg}, <C-r><C-p>{reg}. In the video tutorial, I demonstrate the the difference between <C-r>{reg} and <C-r><C-o>{reg}, by attempting to complete the Vimgolf challenge, Words in parens.

We can use <C-r>" to insert the text that was just deleted with the cw command. That works fine for a one off change, but if we attempt to repeat the change with the dot command, it reproduces the result of the last insertion. In the example, that means using the dot command on two produces (one), when we actually want (two).

If we use <C-r><C-o>" instead, Vim inserts the contents of the default register literally, using the current value of the default register. In this case, we can use the dot command to repeat the remaining changes.

Further reading