SimLeek
SimLeek

Reputation: 131

Vim: Incsearch for replace queries

I noticed I could use regex functions with search in vim, and I could see hilights while I typed by setting incsearch. But that didn't work for search and replace queries like this one:

:%s/std::regex\s\([_a-zA-Z]*\)(/regex_t \1 = dregc(/gc

That one surprised me when it actually worked.


Are there settings or plugins for vim that, like incsearch but better, will highlight your replace query as you type? Just highlighting the matches would be pretty neat, but putting the old and new strings next to eachother in different highlighting colors would be a godsend, because I might not be sure about the backreference.

Upvotes: 2

Views: 1049

Answers (2)

Andy Ray
Andy Ray

Reputation: 32066

Not a direct answer to your question, but traditionally in Vim you craft your search regex first, as in:

/regex

Then you hit enter to execute it. The settings :set hlsearch and :set incsearch make this easy to see visually. Then you can just do:

:%s//replace

With no search specified, :%s (substitute acting on %, a shorctut meaning all lines in the file) will use the last search term you specified.

Going one step further, you could then do

:%s/~/replace2

Which replaces your last substitution (in this case, replace1) with replace2.

Unrelated, it may be useful for you to put this in your .vimrc:

set gdefault

Which will make all replaces global by default, so you don't need the /g flag after every :%s command.

Upvotes: 7

Yosh
Yosh

Reputation: 2742

You might be looking for vim-over?

This is a plugin that: (to clarify, let's say we're doing :%s/foo/bar/g.) i) highlights matches for substitutions in the buffer (foo) and optionally ii) previews what's after replacement (bar).

Upvotes: 6

Related Questions