Replacing with Register Contents


It is a common task to search and replace all occurrences of a word within the current buffer.

In some cases it can be convenient to use replacement text that is stored in a register. This tip demonstrates how to do so.

Starting with the following buffer, note that we have already stored the replacement text in register A.

Initial Conditions
Beautiful·is·better·than·ugly.
Explicit·is·better·than·implicit.
Simple·is·better·than·complex.
Complex·is·better·than·complicated.
Flat·is·better·than·nested.
Sparse·is·better·than·dense.
Readability·counts.
NORMALTop1:1
 
:reg aType Name Content  l  "a   is way

Now, to execute the replacement, we follow the standard replacement pattern:,

:s/{pattern}/{replacement}

where the replacement text references the contents of a register. Although in NORMAL mode we access a register's contents using "{register}, the search is executed in COMMAND mode. We can access register contents in COMMAND mode as follows:

CommandAction
C-R {regname}insert the contents of a register or object under the cursor as if typed

In order to access the contents of register a, we would therefore use a replacement spec of

<C-R> a
Search and Replace
Beautiful·is·way·better·than·ugly.
Explicit·is·way·better·than·implicit.
Simple·is·way·better·than·complex.
Complex·is·way·better·than·complicated.
Flat·is·way·better·than·nested.
Sparse·is·way·better·than·dense.
Readability·counts.
NORMAL75%6:1
6 substitutions on 6 lines

Executing this command replaces each occurrence of is with the contents of register a, is way.