0

I'm writing a function to highlight current word, but on commented out lines, I want a different highlight to apply.

Example: highlight

Notice how the word exists is highlighed, but on a grey commented out line it's too bright: highlight

Here's the function:

function! s:HighlightWordUnderCursor()
  let disabled_ft = [
        \'qf',
        \'fugitive',
        \'nerdtree',
        \'gundo',
        \'diff',
        \'fzf',
        \'floaterm',
        \'vim-plug'
  \]
  let disabled_buftypes = ['terminal', 'quickfix', 'help']
  let nohl_conditions = getline('.')[col('.')-1] =~# '[[:punct:][:blank:]]' || &diff || index(disabled_buftypes, &buftype) >= 0 || index(disabled_ft, &filetype) >= 0

  if !nohl_conditions
    hi MatchWord cterm=undercurl ctermbg=240 gui=undercurl guibg=#665c54
    exec 'match MatchWord /\V\<' . substitute(expand('<cword>'), '/', '\/', 'g') . '\>/'
  else
    match none
  endif
endfunction

augroup MatchWord
  autocmd!
  autocmd! CursorHold,CursorHoldI * call <SID>HighlightWordUnderCursor()
augroup END

Is there a way to identify the highlight of <cword> to have a custom highlighting of commented out lines? Thanks.

5
  • 1
    you need to check the current syntax item at a position and depending on the output (e.g. the syntax item matches Comment). Something along the lines of :echo map(synstack(line("."), col(".")), 'synIDattr(v:val, "name")') Jun 5 at 9:13
  • @ChristianBrabandt this does not echo the applied highlight groups for some reason.. for example, when searching for a word and then running the echo, I expect to see ["Search"] highlight
    – Moshe
    Jun 7 at 14:52
  • the Search highlighting is a totally different highlighting mechanism than syntax highlighting. Same thing for using the match function/commands or sign commands or text property. So yes, that is expected :/ Jun 7 at 15:05
  • Any way to catch those?
    – Moshe
    Jun 7 at 15:07
  • depends on what you want to do. For search highlighting, you may need to check if you are on a search match and v:hlsearch is true. For matches, I don't know of an easy way to do it (again you would need to check whether the cursor is on a match), for text_properties, I don't know at all, for signs I would say it is such a rare use-case, that the line is also highlighted, that I wouldn't bother, for visual mode(), it should be possible to check the mode(). Jun 7 at 15:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.