4

In :highlight command, colors of some groups are shown as this:

:hi vim9Comment
vim9Comment    xxx links to Comment

I then have to invoke another :hi command, this time with the linked group as the argument. This quickly gets cumbersome if the links go on for three, four, or five levels of depth.

Is there any way to follow the links automatically?

2

2 Answers 2

2

We can write a function that parses the output of :highlight command for "links to" string and follows the link recursively.

function! HiThere(group) abort
  let out = trim(execute('hi ' .. a:group))
  let splits = split(out, ' \+')
  echon splits[0] .. ' '
  execute 'echohl ' .. splits[0]
  echon splits[1] .. ' '
  echohl None
  echon join(splits[2:])
  if out =~ 'links to'
    echom ''
    call HiThere(split(out, ' \+')[-1])
  endif
endfunction
command! -nargs=1 -complete=highlight HiThere call HiThere(<q-args>)

If we don't want the links in the output, i.e., if we only want the colors of the deepest highlight-group, we can bring the echo block in the else part of the if condition below it. I'll leave that for others unless and until someone expresses the need for it.

3
  • in newer vim there is :h hlget() function you can use instead of redirecting hi command.
    – Maxim Kim
    Commented Oct 16, 2022 at 11:41
  • i.imgur.com/WtS4mCv.png
    – Maxim Kim
    Commented Oct 16, 2022 at 13:27
  • @MaximKim ah, sorry. I must've used single quotes with grep (don't ask; Windows cmd thing). Found it now.
    – 3N4N
    Commented Oct 16, 2022 at 13:48
0

To get the highlight group that a group links to, you can use this function:

function! GetLinkTarget(group)
    let l:groupID = hlID(a:group)
    " Get the group this highlight group links to
    let l:linkedGroupID = synIDtrans(l:groupID)
    let l:linkedGroupName = synIDattr(l:linkedGroupID, 'name')
    echom a:group . " → " . l:linkedGroupName
endfunction

Example usage:

:call GetLinkTarget("vim9Comment")

Output:

vim9Comment → Comment

Explanation:

  1. hlID gets the ID of the highlight group whose linked to highlight group we want to find out.
  2. synIDtrans(l:groupID) gets the ID of the linked to group.
  3. synIDattr(l:linkedGroupID, 'name') translates the ID of the linked to group to its name.
1
  • Explanation would make this answer better.
    – D. Ben Knoble
    Commented Oct 30, 2023 at 14:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.