Tip 464 Printable Monobook Previous Next

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 procedureEdit

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) then bar then press Escape.
  • Press n (move to next occurrence) then . (repeat change).
  • 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 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 changesEdit

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 blue words:


The replacement is <&> where & 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 alsoEdit


Ad blocker interference detected!

Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.