7

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.

Greg Reynolds
  • 9,736
  • 13
  • 49
  • 60

1 Answers1

16

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
sehe
  • 374,641
  • 47
  • 450
  • 633
  • 1
    according to `:h %V`, you should wrap the whole search pattern in `\%V` if you want to ensure the pattern is inside the selection. Like: `:s/\%Vlongpattern\%V/short/`. – m0tive Dec 19 '11 at 13:50
  • @m0tive: I did quote the documentation on that. And, when the pattern is as single character that isn't useful – sehe Dec 19 '11 at 13:50
  • you're just too quick for me ;-) – m0tive Dec 19 '11 at 13:52
  • Thanks for that. My actual pattern is more than one character, so learning about \%V was what I needed. – Greg Reynolds Dec 19 '11 at 14:31