vimhighlightcolor-scheme

How to properly extend a highlighting group in Vim?


I want to create a highlighting group named Italic to be exactly like Normal but with text in italic. Currently, my Normal highlighting is set to

ctermfg=251 ctermbg=234 guifg=#cccccc guibg=#242424

My questions are:

  1. Is adding term=italic to the Normal attributes the right way to do that?

    :hi Italic term=italic ctermfg=251 ctermbg=234 guifg=#cccccc guibg=#242424
    
  2. Is it possible to do that in a generic fashion, i.e., define the new highlighting group to match the style of the base one for any color scheme (the above does only for my current color scheme)? Something like

    :hi Italic extends Normal term=italic
    

Solution

  • To solve this issue you can create the highlighting group by script. The function below takes three string arguments: the name of the group to base highlighting on, the name of the group to create, and a string containing highlighting attributes to add or overwrite.

    func! ExtendHighlight(base, new, extra)
        redir => attrs | sil! exec 'highlight' a:base | redir END
        let attrs = substitute(split(attrs, '\n')[0], '^\S\+\s\+xxx\s*', '', '')
        sil exec 'highlight' a:new attrs a:extra
    endfunc
    

    Thus, the call

    :call ExtendHighlight('Normal', 'Italic', 'term=italic')
    

    creates a new group called Italic that extends Normal highlighting by the term=italic attribute string.

    Note that custom highlighting groups remain unchanged on color scheme switching. To correct this behavior you can update the group when the current color scheme changes:

    :autocmd ColorScheme * call ExtendHighlight('Normal', 'Italic', 'term=italic')