bzupnick
bzupnick

Reputation: 2814

search for a yanked text and automatically escape special characters

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

Answers (2)

romainl
romainl

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.

  1. Select hello/world.
  2. Hit <leader>r.
  3. The command-line is populated with :%s/hello\/world/, ready for you to…
  4. type the replacement text and…
  5. hit <CR>.

Upvotes: 4

bzupnick
bzupnick

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>

source

Upvotes: 0

Related Questions