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 bar
:
- Put the cursor on
foo
. - Press
*
to search for the next occurrence. - Type
ciw
(change inner word) thenbar
then press Escape. - Press
n
(move to next occurrence) then.
(repeat change). - Repeat last step.
Mapping[]
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:
:%s/\<foo\>/
If you now type bar/g
and press Enter, you will change all foo
to bar
. The \<
and \>
ensure that only complete words are found (the search finds foo
but not food
).
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 blue
words to <red>
and <blue>
:
:%s/\<red\>\|\<blue\>/<&>/g
or using the very magic option:
:%s/\v<red>|<blue>/<&>/g
The replacement is done via the special character &
which is the matched pattern (same as \0
). See :help s/\&
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>'
References[]
See also[]
- Search and replace (comprehensive "see also" list)
- Keystroke Saving Substituting and Searching
- Substitute last search