Tomasz W
Tomasz W

Reputation: 2101

Vim: match qualified identifier under cursor

How can I match fully qualified identifier under cursor?

I'm searching for a way to collect from a script something like ::std::unique_ptr or MyNamespace::MyClassName depending where cursor is located when editing line ::std::unique_ptr<MyNamespace::MyClassName>

Thanks!

Upvotes: 1

Views: 672

Answers (3)

Dummy00001
Dummy00001

Reputation: 17460

One of the most flexible ways to find anything arbitrary under/before/after cursor is to use the VIM's regexp \%# token which match current cursor position. For example:

[a-z]*\%#[a-z]*

(I use here [a-z] only as an example.)

The regexp would match letters before and after the cursor.

Since the * matches 0 or more, that would also match empty space, which is sometimes undesirable. To solve the problem I have used the brute force:

[a-z]*\%#[a-z]\+\|[a-z]\+\%#[a-z]*

Though the approach is more verbose than the expand(<cword>), it has the advantage of being independent of the iskeyword option.

Upvotes: 3

flyingfoxlee
flyingfoxlee

Reputation: 1794

Maybe you could add : in iskeyword, like

nnoremap * :set iskeyword+=:<CR>*:set iskeyword-=:<CR>
nnoremap # :set iskeyword+=:<CR>#:set iskeyword-=:<CR>

Put this in your vimrc file, then when trigger #/*, it will also include :: as part of a word. One pitfall is that it will consider True:False as a single word.

See also Set iskeyword selectively

Upvotes: 0

Ingo Karkat
Ingo Karkat

Reputation: 172788

Built into Vim are only :echo expand('<cWORD>') (matching anything whitespace-delimited) and :echo expand('<cword>') (probably matching too little). You could fix the latter by including more characters in 'iskeyword', but that affects movement and maybe even syntax highlighting.

Alternatively, you could use a function from my ingo-library plugin to implement your own extractor, based on a regular expression:

if search('[:_[:alnum:]]\+', 'bcW') | echo ingo#text#frompattern#GetHere('[:_[:alnum:]]\+') | endif

Upvotes: 0

Related Questions