5

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?

bzupnick
  • 2,646
  • 4
  • 25
  • 34
  • 1
    The answers here will help: http://stackoverflow.com/q/6870902. A good solution is at https://github.com/nelstrom/vim-visual-star-search – glts Oct 03 '13 at 09:57
  • possible duplicate of [VIM editor: How can i search a word after selecting it in visual mode in vim?](http://stackoverflow.com/questions/6870902/vim-editor-how-can-i-search-a-word-after-selecting-it-in-visual-mode-in-vim) – bzupnick Oct 03 '13 at 09:58
  • Thank you! Do I delete the question? – bzupnick Oct 03 '13 at 09:58
  • unfortunately it didn't but I can answer my own question now – bzupnick Oct 03 '13 at 10:05

2 Answers2

4

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>.
romainl
  • 186,200
  • 21
  • 280
  • 313
  • @glts, no, it works on Mac OS X and Windows too (on those platforms, it's an exact synonym with `@+` and I wouldn't have it in my cross-platform config if that wasn't the case as I use that command dozens of times a day ;-)) but it doesn't work anywhere when there's no clipboard support. A regular `A-Z` register should be used instead. I'll edit my answer (and the function in my config) to fix that oversight. – romainl Oct 03 '13 at 10:39
0

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

bzupnick
  • 2,646
  • 4
  • 25
  • 34