Replace Word Under Cursor


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

For example, given the following buffer:

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
 

Suppose one wants to change all occurrences of is better to is way better. The first step in the example if to move the cursor to the word we want to replace:

w
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:11
 

then press & to select all occurrences of the word under the cursor. In addition to selecting all occurrences of is, the cursor moves to the next occurrence.

*
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.
NORMAL25%2:10
 

The general template for searching and replacing is:

:[range]s/{pattern}/{replacement}/[flags]

where

Template Value Description
: Puts Vim into Command Mode
[range] % Applies this command to the entire file
s/ Indicates that this is a search and replace operation
{pattern}/ Not needed, since the words to replace are already selected.
{replacement}/ is way  Specifies the text to replace the search pattern with.
[flags] No flags are specified.

Putting this all together and executing the command:

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

As expected, each occurrence of is has been replaced with is way.