1234
1234

Reputation: 579

I try to substitute some text in highlighted text in Vim

I try to select some text in a sentence and substitute an character in the range of the highlighted text.

e.g.

This is my masterpiece document $which$ has many dollar signs on it. $For example$

I only highlight $For example$ and try to substitute two dollars signs with '|'

I have tried the following command:

:'<,>'s/\$/\|/gc <CR>

I use 'v' to highlight in normal

But above command replaces all the dollar signs in the sentence with '|' instread This is what I got after above command:

This is my masterpiece document |which| has many signs on it. |For example|

Does anyone have any idea what is wrong with my substitute command?

Upvotes: 0

Views: 54

Answers (1)

Andy Ray
Andy Ray

Reputation: 32066

With the selection made, type

s/\%Vpattern/replace

So in your case

:'<,>'s/\%V\$/\|/gc <CR>

Note if you are doing a very magic search (\v at the beginning of the search), omit the backslash and just type %V

:h \%V explains it pretty well:

Match inside the Visual area.

Vim is not very user friendly in general and things you expect to work, like replacing inside a selection, are not automatic.

If the main thing you do with selected text is a replacement, this mapping might be useful, which always prefixes the search with \%V when you type : when visual mode is active.

" Turn on "match inside visual selection" by default when pressing
" : with text highlighted
vnoremap : :\%V

Upvotes: 1

Related Questions