Vim - select text highlighted by search?

In vim, I often perform searches to hop to a word or phrase instead of navigating there with h/j/k/l. Then I hit n to hop between occurrences.

Say I've got this text:

Time flies like an arrow; fruit flies like a banana. - Groucho Marx

I type /an arrow and hit enter. That phrase is highlighted, and I jump to it with n.

Now I want to visually select that text, maybe to change it or delete it. (Yes, I'm aware of the :s substitution command.)

Since my cursor is at the letter "a" at the beginning of "an arrow," I can hit v, then press e a couple of times to highlight the entire phrase. But I have a feeling there's a shorter and more semantic way. After all, I've already specified the text I'm interested in.

How might I compose a command to say "visually select the current search selection?"


You can use gn in version 7.4 onwards (and gN to go backwards). It replaces the v//e trick.

Search forward for the last used search pattern, like with `n`, and start Visual mode to select the match.

See :help gn or this Vimcast for more information.


Try this:

/an arrow
v//e

It goes into visual mode, repeats the last search and selects until the end.


I found that v//e by itself is insufficient because after you exit visual mode, jumping to the next/previous search result puts the cursor at the end of the result, instead of at its beginning as you would normally expect.

To fix this, we should first jump to the end of the search result (//e) and then visually select to its beginning (v??):

" visually select a search result
nnoremap g/ //e<Enter>v??<Enter>

Cheers.


There is now a Vim-Search-Objects plugin that makes Vim treat search matches as regular text objects, so you can simply va/ (visual-select a match) after you perform a search.