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.
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 textAs 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.
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/
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With