Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim: Get content of syntax element under cursor

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\""
like image 749
blinry Avatar asked Apr 28 '11 15:04

blinry


3 Answers

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
like image 131
eolo999 Avatar answered Nov 03 '22 11:11

eolo999


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.

like image 45
nelstrom Avatar answered Nov 03 '22 12:11

nelstrom


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).

like image 1
benizi Avatar answered Nov 03 '22 10:11

benizi