songyy
songyy

Reputation: 4573

Search with Visual Select in VIM?

I want to

Upvotes: 7

Views: 2806

Answers (5)

Andrew Cloete
Andrew Cloete

Reputation: 56

Not sure why @romainl reply is not upvoted more. It is faster, automatically escapes characters that will mess up search, and vanilla vim. Combined with cgn followed by ., it is a perfect substitute for those that miss Ctrl-d in vscode.

Upvotes: 1

user7704701
user7704701

Reputation:

Oh, mate, actually you can use the mighty Visual Search originated by the author of the book Practical Vim. It's very lightweight!

Simply add following stuff into your vimrc,

xnoremap * :<C-u>call <SID>VSetSearch()<CR>/<C-R>=@/<CR><CR>
xnoremap # :<C-u>call <SID>VSetSearch()<CR>?<C-R>=@/<CR><CR>

function! s:VSetSearch()
    let temp = @s
    norm! gv"sy
    let @/ = '\V' . substitute(escape(@s, '/\'), '\n', '\\n','g')
    let @s = temp
endfunction

Visual select the content you want to do search, then press the star key *, Voila !

Upvotes: 4

timss
timss

Reputation: 10270

This has been explained in Search for selection in vim.

  1. Select the text using a visual selection, e.g. v
  2. Yank it, y
  3. Search, /
  4. Paste the last yanked text using <C-r>0 (Ctrlr+0)
    Actually inserts the content from register 0, see :h i_ctrl-r (thanks to romainl in the comments)

Another example is using the command line:

  1. Select the text using a visual selection, e.g. v
  2. Yank it, y
  3. Enter command-line mode with editing an Ex command, q/
  4. Paste yanked text, p, and search by pressing Enter

In short: yq/p<Enter>

Upvotes: 13

romainl
romainl

Reputation: 196876

Bairui/Dahu's SearchParty has a couple of nifty mappings that build on the "yank and insert" method but deal cleanly with newlines and such:

* Searches for the next occurrence of the currently selected visual text.

# Searches for the prior occurrence of the currently selected visual text.

& Starts a :substitute using the currently selected visual text. 

If you feel a plugin is overkill, it's easy to pull the relevant line from the script and put it in your ~/.vimrc.

Upvotes: 4

cforbish
cforbish

Reputation: 8829

To search for more than one word at a time, the vim search supports or '\|'. So to search for dog cat and bird you can:

/dog\|cat\|bird

or better (exact word match):

/\<dog\>\|\<cat\>\|\<bird\>

Upvotes: 1

Related Questions