Reputation: 4965
I'm on a highlighted complex syntax element and would like to get it's content. Can you think of any way to do this?
Maybe there's some way to search for a regular expression so that it contains the cursor?
EDIT
Okay, example. The cursor is inside a string, and I want to get the text, the content of this syntactic element. Consider the following line:
String myString = "Foobar, [CURSOR]cool \"string\""; // And some other "rubbish"
I want to write a function that returns
"Foobar, cool \"string\""
Upvotes: 9
Views: 3327
Reputation: 4216
This is a good use for text objects (:help text-objects
). To get the content you're looking for (Foobar, cool \"string\"
), you can just do:
yi"
y = yank
i" = the text object "inner quoted string"
The yank command by default uses the unnamed register (""
, see :help registers
), so you can access the yanked contents programmatically using the getreg()
function or the shorthand @{register-name}
:
:echo 'String last yanked was:' getreg('"')
:echo 'String last yanked was:' @"
Or you can yank the contents into a different register:
"qyi"
yanks the inner quoted string into the "q
register, so it doesn't conflict with standard register usage (and can be accessed as the @q
variable).
Upvotes: 1
Reputation: 4965
EDIT: Seeing that the plugin mentioned by nelstrom works similar to my original approach, I settled on this slightly more elegant solution:
fu s:OnLink()
let stack = synstack(line("."), col("."))
return !empty(stack)
endf
normal mc
normal $
let lineLength = col(".")
normal `c
while col(".") > 1
normal h
if !s:OnLink()
normal l
break
endif
endwhile
normal ma`c
while col(".") < lineLength
normal l
if !s:OnLink()
normal h
break
endif
endwhile
normal mb`av`by
Upvotes: 0
Reputation: 19542
The textobj-syntax plugin might help. It creates a custom text object, so that you can run viy
to visually select the current syntax highlighted element. The plugin depends on the textobj-user plugin, which is a framework for creating custom text objects.
Upvotes: 5
Reputation: 883
if I understood the question. I found this gem some time ago and don't remember where but i used to understand how syntax hilighting works in vim:
" Show syntax highlighting groups for word under cursor
nmap <leader>z :call <SID>SynStack()<CR>
function! <SID>SynStack()
if !exists("*synstack")
return
endif
echo map(synstack(line('.'), col('.')), 'synIDattr(v:val, "name")')
endfunc
Upvotes: 10