Yank&Search selection/motion as plain-text

1 Point

Rom Grk Rom Grk

1 year ago

Search visual-selection/motion as plain text. Yank visual-selection/motion as an escaped search pattern. Eg. mapping 2-3-4 yank the visual-selection to the search register & trigger highlighting. Mapping 2 also moves cursor to next match. Use case: need to search for an identique expression/snippet of code, ignoring any special characters.
" Yank selected text as an escaped search-pattern
map <silent><Plug>(visual-yank-plaintext)  :<C-U>call setreg(v:register, '\V'.escape(s:visualText(), '\/'))<CR>

" Eg.
vmap <M-y>           <Plug>(visual-yank-plaintext)
vmap <A-/>         "/<Plug>(visual-yank-plaintext)n
vmap <silent><C-F> "/<Plug>(visual-yank-plaintext):set hls<CR>
nmap z*         viw"/<Plug>(visual-yank-plaintext):set hls<CR>

" credits: xolox
function! s:visualText()
    " Why is this not a built-in Vim script function?!
    let [lnum1, col1] = getpos("'<")[1:2]
    let [lnum2, col2] = getpos("'>")[1:2]
    let lines = getline(lnum1, lnum2)
    let lines[-1] = lines[-1][: col2 - (&selection == 'inclusive' ? 1 : 2)]
    let lines[0] = lines[0][col1 - 1:]
    return join(lines, "\n")
endfunction