Search code examples
vim

Use visual character-wise selection as auto-fill for Vim substitute command


Imagine that [ ] represents a selection. So given

This is pi with the 10th through 20th digits obscured: 3.14159265[3589793238]46264338327950288419716939937510...

the visual selection would be 3589793238.

In Sublime Text, when you have some text selected, and then press Ctrl+h to start the search/replace feature, it will auto-fill the search box with the currently selected text. Is there a way to emulate this in Vim? That is, assuming I am in character-wise visual mode and have made the selection indicated above, I would then press some shortcut combo and Vim would yield :%s/3589793238/ in the command line. That way I could simply complete it like so :%s/3589793238/___/ to replace 3589793238 with ___ throughout the currently open file (without having to manually type 3589793238 into the Vim command-line).


Solution

  • In command mode, you can input the content of any register with <C-R> followed by its name. So you could yank the currently selected text (yanked text is stored in register 0) and then input it with <C-R>0 when writing your substitute command.

    To fully automate this, you could add a mapping like so:

    xmap <leader>s y:%s/<C-R>0/