Search code examples
vimcolor-scheme

How to highlight only keywords in vim?


I want to only highlight keywords and leave everything else black.

Something like this obviously highlights the keywords the way I want, but doesn't disable everything else:

hi keyword ctermfg=DarkBlue

So far I only managed to achieve this by manually listing all keys:

sy off
sy reset
sy keyword myKeyword if for while
hi link myKeyword Keyword
hi keyword ctermfg=DarkBlue

But I'd like to re-use all predefined keys. Is that possible?


Solution

  • To my knowledge, there's no way to do it easily; maybe I missed something, but it seems that vim lacks the possibility of getting full infos (with functions) about the highlight config.

    To get exactly what you want, one idea would be to parse the output of the :syn list command to get a list of the keywords used for a certain highlight group; but it's quite impossible to parse it in a good way, because special meanings in the output are differenciated only by the color, not by a parsable pattern.

    Some possible workarounds:

    • To set a list with the names of every highlight group you don't want, and then discard them when you need, maybe depending on the current filetype; for example:

      let s:discard_hi_filetypes = {
      \   'vim' : [ 'Comment', 'Identifier', 'Constant', 'PreProc', 'Special', 'Type', 'vimOper' ],
      \   'cpp' : [ 'cComment', 'cInclude', 'cIncluded', 'cppSTLtype', 'cCppString', 'cTodo', 'cDefine', 'cNumber', 'cType' ],
      \ }
      
      function! KWHighlight()
          " Applies to all buffers; run ':syn on' to reset
          if !has_key(s:discard_hi_filetypes, &ft) | return | endif
          for g in s:discard_hi_filetypes[&ft]
              exe "hi clear " . g
              exe "hi link " . g . " NONE"
          endfor
      endf
      

      The following can greatly help to quickly find the names of highlight groups:

      command! ShowHL augroup ShowHL | exe "au! ShowHL" | au CursorMoved * echo synIDattr(synID(line('.'), col('.'), 1), 'name') | augroup END
      command! HideHL au! ShowHL
      
    • The following code lets you quickly, (but) manually discard a highlight group, the current one under the cursor:

      command! HLDisable exe "hi clear " . synIDattr(synIDtrans(synID(line('.'), col('.'), 1)), 'name')
      noremap __ :HLDisable<cr>
      

      Typing __ a few times, on different unwanted highlighted words, let's you get the desired result, but it's not automatic at all.