Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search with Visual Select in VIM?

Tags:

vim

I want to

  • Select a word with VISUAL mode
  • Press a key to search for the selected word
like image 375
songyy Avatar asked Jul 11 '26 13:07

songyy


2 Answers

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>

like image 139
timss Avatar answered Jul 14 '26 08:07

timss


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 !


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!