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

2.5k views Asked by At

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.

2

There are 2 answers

1
resueman On BEST ANSWER

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.

0
2e0byo On

There is now a package evil-visual-replace to accomplish replacement in blocks:

https://github.com/troyp/evil-visual-replace

It would be nice if the underlying logic were integrated with evil, so that pressing : with a visual block just worked, but it's better than nothing.