Reputation: 2814
for example, I'd like to yank hello/world
and paste that into a search for other instances of hello/world
I've tried yanking, then typing /\v ctr-r 0
and in the search bar it places the entire hello/world
but practically, it only searched for hello
.
Is there a way to automatically escape special character during paste in the search?
Upvotes: 5
Views: 529
Reputation: 196476
You might be interested in this:
" return a representation of the selected text
" suitable for use as a search pattern
function GetVisualSelection()
let old_reg = @a
normal! gv"ay
let raw_search = @a
let @a = old_reg
return substitute(escape(raw_search, '\/.*$^~[]'), "\n", '\\n', "g")
endfunction
xnoremap <leader>r :<C-u>%s/<C-r>=GetVisualSelection()<CR>/
It uses more or less the same strategy as above but in a slightly cleaner and reusable way.
hello/world
.<leader>r
.:%s/hello\/world/
, ready for you to…<CR>
.Upvotes: 4
Reputation: 2814
Adding this to the vimrc file allows you to visually select something, press *, and it will search with escaped characters
vnoremap <silent> * :<C-U>
\let old_reg=getreg('"')<Bar>let old_regtype=getregtype('"')<CR>
\gvy/<C-R><C-R>=substitute(
\escape(@", '/\.*$^~['), '\_s\+', '\\_s\\+', 'g')<CR><CR>
\gV:call setreg('"', old_reg, old_regtype)<CR>
vnoremap <silent> # :<C-U>
\let old_reg=getreg('"')<Bar>let old_regtype=getregtype('"')<CR>
\gvy?<C-R><C-R>=substitute(
\escape(@", '?\.*$^~['), '\_s\+', '\\_s\\+', 'g')<CR><CR>
\gV:call setreg('"', old_reg, old_regtype)<CR>
Upvotes: 0