Search and replace the word under the cursor
From Vim Tips Wiki
created 2003 · complexity intermediate · author maurice · version 6.0
A good way to search and replace the word under the cursor is shown here. This tip simplifies such operations.
 Manual procedure
If you only have a few occurrences to change, you might prefer a manual technique which does not require a mapping. If all
foo words need to be changed to
- Put the cursor on
*to search for the next occurrence.
ciw(change inner word) then
barthen press Escape.
n(move to next occurrence) then
- Repeat last step.
With this mapping in your vimrc, you can easily enter a command to substitute all occurrences of the word under the cursor:
:nnoremap <Leader>s :%s/\<<C-r><C-w>\>/
Given this mapping, if the cursor is on the word
foo and you press
\s (assuming the default backslash Leader key), you will see:
If you now type
bar/g and press Enter, you will change all
\> ensure that only complete words are found (the search finds
foo but not
Alternatively, you could use this mapping so that the final
/g is already entered:
:nnoremap <Leader>s :%s/\<<C-r><C-w>\>//g<Left><Left>
 Similar changes
Sometimes similar changes to several words are needed. For example, you might need
< before each word, and
> after (this specific example is probably best handled with the surround plugin, and is used here just as an illustration). One approach would be to record a macro that performs the operations required. The following alternative uses substitute commands.
If you know in advance what needs to be changed, you could use a suitable pattern. For example, the following changes all
red and all
The replacement is
& has a special meaning: it is replaced by the search match.
The following mapping evaluates an expression to replace all occurrences of the word that is currently under the cursor. Move the cursor to a word, then press F8 to change all occurrences of that word. Then move to another word and press F8 again.
:nnoremap <expr> <F8> ':%s/\<'.expand('<cword>').'\>/<&>/g<CR>'
 See also
- Search and replace (comprehensive "see also" list)
- Keystroke Saving Substituting and Searching
- Substitute last search