Search for selection in Vim

VimViemuString Search

Vim Problem Overview


I use Vim and Vim plugins for Visual Studio when writing C++. Often, I find myself wanting to search for a string within a function, for example every call to object->public_member.memberfunc().

I know Vim offers a convenient way to search for a single word, by pressing * and #, and it can also search for typed strings using the ubiquitous slash / command. When trying to search for all the instances of a longer string like the one above, it takes a while to re-type after /.

Is there a way to search for the selection? For example, highlight with v, then copy with y, is there a way to paste after /? Is there an easier shortcut?

Vim Solutions


Solution 1 - Vim

Check this Vim tip: Search for visually selected text

Or you can simply yank the selected text with y and go to search mode /, then you can paste the last yanked text with Ctrl+R 0

Solution 2 - Vim

Answer

  1. Yank the text you want to search for
  2. q/p
  3. Enter

Explanation

q/ works similarly to vanilla search / except you're in command mode so p actually does "paste" instead of typing the character p. So the above will copy the text you're searching for and paste it into a search.

For more details type :help q/

Solution 3 - Vim

Use q / instead of just /. (Same with q :). Now you can VIM-edit through your command and search history! (Try Ctrl-N and Ctrl-P sometime).

Solution 4 - Vim

I just learned (through the excellent book Practical Vim) that there is a plugin for that. You can find the plugin on GitHub.

The plugin lets you search for a visual selection with * and #.

Solution 5 - Vim

You can actually select text visually and press * and # to search for the next occurrence... It will work the same, the only caveat is that:

>Whitespace in the selection matches any whitespace, when searching (searching for "hello world" will also find "hello" at the end of a line, with "world" at the start of the next line).

http://vim.wikia.com/wiki/Search_for_visually_selected_text

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMarcinView Question on Stackoverflow
Solution 1 - VimChristian C. SalvadóView Answer on Stackoverflow
Solution 2 - VimCory KleinView Answer on Stackoverflow
Solution 3 - VimarcanexView Answer on Stackoverflow
Solution 4 - VimcutemachineView Answer on Stackoverflow
Solution 5 - VimAhHatemView Answer on Stackoverflow