James Duffy
James Duffy

Reputation: 1387

VIM: Change current highlighted search term matched with /search

Is there any command equivalent to "delete until the end of the current highlighted search match and enter insert mode"?

For example, I search for a term with:

/Element

It finds the string ExampleElementExample, places the cursor on the E in Element, and highlights Element.

I would like a generic command that applies to all searches that is equivalent to c7l or ctE in this particular case. However, I also want to be able to easily repeat this command to the next match by pressing n, ..

c//e basically does what I want, but falls short because it replaces the current search buffer, so n no longer takes me to the next match. Right now I'm using ctE or visual mode, but I feel like there must be a better option.

What is the fastest and most efficient way to execute this command?

Upvotes: 2

Views: 249

Answers (3)

romainl
romainl

Reputation: 196506

If your Vim is recent enough (7.3 with a patch-level above 6xx), you can use gn:

barbazfoobazbar

/foo<CR>

barbaz[foo]bazbar

cgnvim<CR>

barbazvimbazbar

You can hit . to jump to the next foo and change it to vim in one go.

See :help gn.

Upvotes: 3

Ingo Karkat
Ingo Karkat

Reputation: 172520

You can use the following custom text object taken from Copy or change search hit on the Vim Tips Wiki:

" Make a simple "search" text object.
vnoremap <silent> s //e<C-r>=&selection=='exclusive'?'+1':''<CR><CR>
    \:<C-u>call histdel('search',-1)<Bar>let @/=histget('search',-1)<CR>gv
omap s :normal vs<CR>

Upvotes: 1

Bernhard
Bernhard

Reputation: 3694

I think the best option would be to use search and replace with the confirm flag.

:%s//replace/gc

If you leave the search string empty, it will automatically use the current search string. By the c flag, it asks you for permission to replace and upon decision, it will move to the next match. The g flag will find all matches, not just the first on a line, which I hope is what you are looking for.

Upvotes: 2

Related Questions