Can I make the visual block the current search term?

Suppose there is some block of text that I want to find in a file. Is there a way to make the visual block select this text, and then make it the current search term? That way, I can do s // replacementText / g without typing all the text on the left side of the substitute command.

+7
source share
2 answers

You have to forgive me, I canโ€™t remember where I found this, but it works wonders. Just add to .vimrc . Use typical * and # after visual selection:

 " Search for selected text, forwards or backwards. vnoremap <silent> * :<CU> \let old_reg=getreg('"')<Bar>let old_regtype=getregtype('"')<CR> \gvy/<CR><CR>=substitute( \escape(@", '/\.*$^~['), '\_s\+', '\\_s\\+', 'g')<CR><CR> \gV:call setreg('"', old_reg, old_regtype)<CR> vnoremap <silent> # :<CU> \let old_reg=getreg('"')<Bar>let old_regtype=getregtype('"')<CR> \gvy?<CR><CR>=substitute( \escape(@", '?\.*$^~['), '\_s\+', '\\_s\\+', 'g')<CR><CR> \gV:call setreg('"', old_reg, old_regtype)<CR> 

The real advantage here is that it eludes any special characters, rather than just inserting it into the search command. It is also less than keystrokes, which maximizes the vimness of your task.

+3
source

Make a visual block and pull it into the unnamed register "" : with the selected visual block, enter y in yank. Start the search with / - or :s/ and type Ctrl-r , then " to insert the contents of the unnamed case as a search term.

This will not block the current search, but it is almost as easy.

Ctrl-r can be used anywhere on the command line, so you can also use this, for example. to fill in replacement or replacement text or in insert mode.

+4
source