Tip 91: Replace with the Contents of a Register
Return to the top: <<Practical Vim>>
Pass by Value
-
insert the contents of a register by typing
<C-r>{register}
:%s//<C-r>0/g
-
Problems:
- If the text in register 0 contains any characters that have special meaning within the replacement field (such as & or ~, for example), we would have to edit the string by hand to escape those characters.
- If register 0 contained a multiline excerpt of text, it might not fit on the command line.
Pass by Reference
:%s//\=@0/g
-
\=
: evaluate a Vim script expression. -
@{register}
: reference the contents of a register (@0
returns the contents of the yank register, while@"
returns the contents of the default register.)
Comparison
Example:
:%s/Pragmatic Vim/Practical Vim/g
equivalent to:
:let @/='Pragmatic Vim' :let @a='Practical Vim' :%s//\=@a/g
-
:let @/='Pragmatic Vim'
: sets the search pattern-
equivalent to:
/Pragmatic Vim <CR>
- does not create a record in the search history
-
equivalent to:
-
:let @a='Practical Vim'
: sets the contents of thea
register-
equivalent to: visually selected the text "Practical Vim" and then typed
"ay
to yank the selection into registera
.
-
equivalent to: visually selected the text "Practical Vim" and then typed