I'm searching for a way to copy match result to local variable in vim script.
The issue is that I want to match text that includes cursor position atom \\%#
, that is, for example: [A-Za-z:]*\\%#[A-Za-z:]\\+
, which matches identifiers like ::namespace::ParentClass::SubClass
text under cursor (so <cword>
does not work for me).
I would like to use this later in a script, but the more I dig the more I start to wonder if that's even possible (or: if I should do it differently, by collecting current line, cursor position and then just extract the identifier under cursor manually).
If that's not possible from within the vim script - what would be the idea behind the \\%#
atom? what is its use?
You have two options:
getline()
, strpart()
, and matchstr()
, and is just like what you've hinted at in your question. search()
twice from the current position, once to find the end of the match after the cursor, once to find the begin of the match before / on the cursor, then use getline()
and strpart()
to extract the matching text: function! GetMatch(pattern)
let start = searchpos(a:pattern, 'bcnW')[1]
if start == 0
return ''
endif
let end = searchpos(a:pattern, 'cenW')[1]
if end == 0
return ''
endif
return strpart(getline('.'), start - 1, end - start + 1)
endfunction
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.