vimtricks.wiki Concise Vim tricks, one at a time.

How do I insert register contents into the command line?

Answer

:<C-r>a

Explanation

How it works

While typing an Ex command on the command line (after pressing :), you can insert the contents of any register by pressing Ctrl-R followed by the register identifier. This is incredibly useful for building commands that reference text you have previously yanked or stored.

The command :<C-r>a inserts the contents of register a at the cursor position on the command line. You can use this with any register:

  • <C-r>a through <C-r>z -- named registers
  • <C-r>" -- unnamed register (last yank/delete)
  • <C-r>0 -- yank register
  • <C-r>/ -- last search pattern
  • <C-r>% -- current filename
  • <C-r>=expr -- expression register (evaluate an expression)

This also works in insert mode and search mode (/ or ?), not just on the Ex command line.

Example

Suppose you want to search and replace a long variable name that you do not want to retype:

  1. Place your cursor on myLongVariableName and yank it: yiw
  2. Start a substitution command: :%s/
  3. Press Ctrl-R 0 to insert the yanked text: :%s/myLongVariableName
  4. Complete the command: :%s/myLongVariableName/newName/g

Another common use is inserting the current filename into a command:

  1. Type :echo "
  2. Press Ctrl-R % to insert the filename
  3. The command line now shows :echo "myfile.txt

This technique saves typing and eliminates errors from retyping long strings.

Next

How do you yank a single word into a named register?