Search code examples
emacsreplaceselectionevil-mode

Emacs, Evil-Mode: Replace only in visual selection/visual block?


By default, :s/[search-term]/[replace-term] works on whole lines rather than on visual selections. For example, if you select between c and e, as such:

a b |c d e| f g

and do :s/ //g, the result is:

abcdefg

rather than

a b cde f g

Similarly, in a visual block selection:

a b |c d e| f g
0 1 |2 3 4| 5 6

:s/ //g yields

abcdefg
0123456

rather than

a b cde f g
0 1 234 5 6

Does anyone have a way to make evil-mode's :s/ work only on the selection (preferably by default, or alternatively with a keyword like vim's \%V)?

(:s/\%V //g does not seem to work in this case; it leads to 0 matches.)

Thanks beforehand.


Solution

  • You can do the replacement in a visual selection by specifying the range. '<,'> works on the first line to the last line of the selection, and `<,`> works on the first character to the last character. So in your first example of

    a b |c d e| f g`, 
    

    using :`<,`>s/ //g will give you

    a b cde f g
    

    Unfortunately, Evil doesn't seem to currently support replacement in a Visual Block, so there's no easy way to do that replacement.