Home » Questions » Computers [ Ask a new question ]

How to search for selected text in Vim?

How to search for selected text in Vim?

I'm aware that I can use / followed by a regex to search something. And I can use ? to search backwards. And I can use n and N to repeat the search forward and backward.

Asked by: Guest | Views: 305
Total answers/comments: 5
Guest [Entry]

"The following sequence will do what you want, given an already selected block of text:

y (yank the selected text, into the "" register by default)
/ (enter search mode)
(\ V) (optional, enter ""very no magic"" mode*)
Ctrl+r "" (insert text from "" register)
Enter (Engage!)

(*) ""very no magic"" mode interprets the following text as plain text instead of as a regex. note however that \ and / are still special and will have to be handled in other ways. If the text does not have any characters considered special, you can skip this step.

Source: Vim Tips Wiki"
Guest [Entry]

"I never felt the need for such a feature but, considering you can find a need for any feature on Vim, I think this from the Vim Wiki should help:

vnoremap // y/\V<C-R>=escape(@"",'/\')<CR><CR>

I didn't test it but, looking at the code, it seems to be exactly what you're searching for."
Guest [Entry]

"The other answers here break p paste, since they override the unnamed register "". Here is a solution that doesn't have this problem:
vnoremap ml :<c-u>let temp_variable=@""<CR>gvy:<c-u>let @/='\V<C-R>=escape(@"",'/\')<CR>'<CR>:let @""=temp_variable<CR>:<c-u>set hlsearch<CR>

This solution also doesn't jump to the next instance of the pattern, which I find disruptive if it is out of frame in the current window."
Guest [Entry]

In my configurations on two separate machines, if I select text and then hit / it automatically searches for the selected text.
Guest [Entry]

"This solution empowers your vim search visually selected context even with multiline and escape characters.

Add the following code in you .vimrc, and search your visually selected content by //. You can also globally substitute the selected content by /s. Or Locally substitute the selected context by // first, and then visually select a region and :'<,'>s//{new_text}.

set incsearch
set hlsearch
set ignorecase
function GetVisualSelection()
let raw_search = @""
let @/=substitute(escape(raw_search, '\/.*$^~[]'), ""\n"", '\\n', ""g"")
endfunction
xnoremap // """"y:call GetVisualSelection()<bar>:set hls<cr>
if has('nvim')
set inccommand=nosplit
xnoremap /s """"y:call GetVisualSelection()<cr><bar>:%s/
else
xnoremap /s """"y:call GetVisualSelection()<cr><bar>:%s//
endif

The above configuration is only about searching. For all my vim configuration, please visit .vimrc"