vim search and replace limited to the highlight in

2019-03-10 20:25发布

问题:

I often have text in columns and need to replace some things without clobbering similar stuff on the same line... a simple example follows:

Suppose I have highlighted the text in grey with vim visual block mode, and want to replace 80 with 81; however, I only want replacements within the highlighted visual block.

I have already tried Cntlv : s/80/81/g; however, that replaces text inside and outside the visual block. (based on Randy's feedback, it's because : s is a line-wise command).

I know I could use a line-wise visual block replace in this particular instance ( Shiftv : s/80\.1/81.1/g ); however, I'm trying to find a general solution for the problem of having no easy means to replace within a non line-wise visual block (isn't this the kind problem that visual block mode is supposed to help solve?). Answers requiring confirmation like : s/80/81/gc, are not what I am looking for.

I will restate the question for clarity: How can I replace 80 with 81 by using vim's visual block mode highlight?

回答1:

You need to add \%V to your pattern. From :help \%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.

OP EDIT: the explicit solution is to to use : s/\%V8\%V0/81/g



回答2:

The solution is obviously the \%V regex atom, but note, that this it still a little bit buggy.

Update: It's no bug. This thread explains the behaviour.



回答3:

The visual selection block should be identifiable with %V

:'<,'>s/\%V80/81/g