VIM incremental search, how to copy a line under the heading under the cursor?

In VIM, you can search for a specified string. Then you can press nor nto go to the next or previous match. When you press nor n, the cursor will be moved to the matched text. My question is how to quickly copy the matched text under the cursor?


Edit:

I need the current match under the cursor, and not all matches in the document.

Thank,

+5
source share
4 answers

You can write a function that extracts the match of the last search pattern around the cursor and creates a mapping to call it.

nnoremap <silent> <leader>y :call setreg('"', MatchAround(@/), 'c')<cr>
function! MatchAround(pat)
    let [sl, sc] = searchpos(a:pat, 'bcnW')
    let [el, ec] = searchpos(a:pat, 'cenW')
    let t = map(getline(sl ? sl : -1, el), 'v:val."\n"')
    if len(t) > 0
        let t[0] = t[0][sc-1:]
        let ec -= len(t) == 1 ? sc-1 : 0
        let t[-1] = t[-1][:matchend(t[-1], '.', ec-1)-1]
    end
    return join(t, '')
endfunction

, .

(. :help text-object) .

vnoremap <silent> i/ :<c-u>call SelectMatch()<cr>
onoremap <silent> i/ :call SelectMatch()<cr>
function! SelectMatch()
    if search(@/, 'bcW')
        norm! v
        call search(@/, 'ceW')
    else
        norm! gv
    endif
endfunction

, yi/. , , , vi/, di/.

+3

y//e

:

- n n . .

  • y .
  • // .
  • //e e

, , /e. n / n .

.

+6

y, , p .

0

, :

command! -register CopyExactMatchUnderCursor call s:CopyExactMatchUnderCursor('<reg>')

function! s:CopyExactMatchUnderCursor(reg)
    let cpos = getpos('.')
    let line = cpos[1]
    let idx = cpos[2] - 1
    let txt = getline(line)

    let mend = matchend(txt, @/, idx)

    if mend > idx
        let sel = strpart(txt, idx, mend - idx)

        let reg = empty(a:reg) ? '"' : a:reg
        execute 'let @' . reg . ' = sel . "\n"'
    end
endfunction

getpos, ( , matchend), - " .

@eckes.

0

All Articles