How to override default syntax highlight in vim?

grigoryvp picture grigoryvp · Jul 31, 2009 · Viewed 8.8k times · Source

In VIM, I need to perform a simple task - highlight "(" and ")". I can do this easily by issuing two commands:

:syn match really_unique_name display "[()]"
:hi really_unique_name guifg=#FF0000

But if I add same commands (without ':' of course) to empty .vimrc and restart VIM - "(" and ")" are not highlighted anymore in .cpp files. It seems that if i create/load .cpp file, VIM loads syntax file for it that overrides my custom highlights. How can i configure highlights in my .vimrc file so it will take place after standard syntax definitions or will not be affected by standard syntax definition?

Answer

DrAl picture DrAl · Jul 31, 2009

There are four options (two of which have been suggested by others):

  1. Use the after structure in vimfiles (~/.vim/after/syntax/cpp.vim):

    :help after-directory
    
  2. Use match for the current window:

    :match really_unique_name "[()]"
    
  3. Use matchadd(), again for the current window, but this allows you to delete individual matches if you later need to:

    :call matchadd('really_unique_name', "[()]")
    " Or
    :let MyMatchID = matchadd('really_unique_name', "[()]")
    " and then if you want to switch it off
    :call matchdelete(MyMatchID)
    
  4. Install Dr Chip's rainbow.vim plugin to get brace highlighting in different colours depending on the indentation level.

For this situation, I'd recommend option 1 as it looks like you want to make it part of the general syntax. If you want to use matches and you want them to be buffer specific (rather than window specific), you'll need something like:

function! CreateBracketMatcher()
    call clearmatches()
    call matchadd('really_unique_name', "[()]")
endfunc
au BufEnter <buffer> call CreateBracketMatcher()

For more information, see:

:help after-directory
:help :match
:help matchadd()
:help matchdelete()
:help clearmatches()
:help function!
:help autocmd
:help autocmd-buffer-local
:help BufEnter

You may also be interested in my answer to this question, which covers more general operator highlighting.