How to get group name of highlighting under cursor in vim?

Here's a mapping that will show the hierarchy of the synstack() and also show the highlight links. press gm to use it.

function! SynStack ()
    for i1 in synstack(line("."), col("."))
        let i2 = synIDtrans(i1)
        let n1 = synIDattr(i1, "name")
        let n2 = synIDattr(i2, "name")
        echo n1 "->" n2
    endfor
endfunction
map gm :call SynStack()<CR>

The following function will output both the name of the syntax group, and the translated syntax group of the character the cursor is on:

function! SynGroup()
    let l:s = synID(line('.'), col('.'), 1)
    echo synIDattr(l:s, 'name') . ' -> ' . synIDattr(synIDtrans(l:s), 'name')
endfun

To make this more convenient it can be wrapped in a custom command or key binding.

How this works:

  • line('.') and col('.') return the current position
  • synID(...) returns a numeric syntax ID
  • synIDtrans(l:s) translates the numeric syntax id l:s by following highlight links
  • synIDattr(l:s, 'name') returns the name corresponding to the numeric syntax ID

This will echo something like:

vimMapModKey -> Special

There is this function that was floating around the web when I was doing the same thing:

function! SynStack()
  if !exists("*synstack")
    return
  endif
  echo map(synstack(line('.'), col('.')), 'synIDattr(v:val, "name")')
endfunc

Tags:

Vim