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>athrough<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:
- Place your cursor on
myLongVariableNameand yank it:yiw - Start a substitution command:
:%s/ - Press
Ctrl-R 0to insert the yanked text::%s/myLongVariableName - Complete the command:
:%s/myLongVariableName/newName/g
Another common use is inserting the current filename into a command:
- Type
:echo " - Press
Ctrl-R %to insert the filename - The command line now shows
:echo "myfile.txt
This technique saves typing and eliminates errors from retyping long strings.