Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim visual selection and regexp

Tags:

vim

I am having a problem with the visual selection and running a regular expression replace. When I select some text that does not contain the whole row, and hit : to bring the command line up, and do something like

:s/T/t/

Then the first match on the line (whether it's selected or not) is changed. So, for example, I have the text

Test Text here

and I visually select the word Text, then run the above substitution, I end up with

test Text here

which is not what I want.

Any ideas how to achieve the right result?

Edit: The actual command line is

'<,'>s/T/t/

as defaulted by Vim when you press : with a visual selection.

like image 430
Greg Reynolds Avatar asked Dec 19 '11 13:12

Greg Reynolds


1 Answers

You can use \%V (see http://vimdoc.sourceforge.net/htmldoc/pattern.html#//%V)

\%V   Match inside the Visual area.  When Visual mode has already been
    stopped match in the area that |gv| would reselect.
    This is a |/zero-width| match.  To make sure the whole pattern is
    inside the Visual area put it at the start and end of the pattern,
    e.g.:
        /\%Vfoo.*bar\%V
    Only works for the current buffer.

So:

:s/\%VT/t/

If you want to replace multiple hits, add /g

:s/\%VT/t/g
like image 115
sehe Avatar answered Sep 18 '22 18:09

sehe