Search code examples
vim

Vim search and replace selected text


Let's say we have a text, and I enter visual mode and select some text. How do I quickly do a search for the highlighted text and replace it with something else?


Solution

  • Try execute the following or put in into your .vimrc

    vnoremap <C-r> "hy:%s/<C-r>h//gc<left><left><left>
    

    By pressing ctrl+r in visual mode, you will be prompted to enter text to replace with. Press enter and then confirm each change you agree with y or decline with n.

    This command will override your register h so you can choose other one (by changing h in the command above to another lower case letter) that you don't use.