I use the following plugin to search for visually selected text:
function! VisualSelection()
" Save register content and type.
let old_reg = getreg('"')
let old_regmode = getregtype('"')
" Calling this function has ended visual mode, so it must be started
" again before the selection can be yanked into the unnamed register.
normal! gvy
let selection = @"
" Restore register content and type.
call setreg('"', old_reg, old_regmode)
return selection
endfunction
function! Escaped(text)
call inputsave()
let result = escape(a:text, '\\/.*$^~[]')
let result = substitute(result, "\n$", "", "")
let result = substitute(result, "\n", '\\n', "g")
call inputrestore()
return result
endfunction
xnoremap <silent> <unique> * :<C-U><cr>/<C-R><C-R>=Escaped(VisualSelection())<cr><cr>
xnoremap <silent> <unique> # :<C-U><cr>?<C-R><C-R>=Escaped(VisualSelection())<cr><cr>
This overrides the default behavior of *
and +
which would extend the visual selection to the next occurrence of the word under the cursor.
For replacement you can define a third mapping which creates a substitute command for the whole buffer and prefills the search text with the visually selected text:
xnoremap <silent> <unique> g* :<C-U>%s/<C-R><C-R>=Escaped(VisualSelection()) . '/'<cr>