Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VIM incremental search, how to copy the matched string under cursor?

Tags:

vim

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


Edit:

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

like image 726
Just a learner Avatar asked Jan 01 '12 16:01

Just a learner


2 Answers

You want to execute the following

y//e

Overview:

The basic idea is after you search or press n or N the cursor will be at the beginning of the matched text. Then you yank to the end of the last search.

Explanation

  • y will yank from the current position through the following motion
  • // searches using the last search pattern.
  • //e The e flag will position the cursor at the end of the matched text

As a word of warning this will change the current search pattern, because it adds the /e flag. Therefore following n and/or N will move the cursor to the end of the match.

This is very similar to the following post.

like image 147
Peter Rincker Avatar answered Oct 04 '22 20:10

Peter Rincker


One can write a function extracting the match of the last search pattern around the cursor, and create 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

The function above determines the starting and ending positions of the match and carefully takes out the matching text, correctly handling multiline patterns and multibyte characters.

Another option is to create text object mappings (see :help text-object) for operating on the last search pattern match under the cursor.

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

To copy the current match using these mappings, use yi/. As for other text objects, it is also possible, for example, to visually select it using vi/, or delete it using di/.

like image 39
ib. Avatar answered Oct 04 '22 20:10

ib.