Dean
Dean

Reputation: 9128

How can I set a global syntax rule that takes precedent over a file specific one?

I want unexpected characters to have a different background color than the usual ones. I put the following highlighting rule in my .vimrc:

syntax match NotPrintableAscii "[^\x20-\x7F]"
hi NotPrintableAscii ctermbg=236

This words great for some files, but doesn't work with anything that has filetype-specific syntax rules.

Where should I set this so it works with all file types?

Upvotes: 1

Views: 374

Answers (1)

Ingo Karkat
Ingo Karkat

Reputation: 172748

The fact that this only works sometimes is due to these two things:

  • It only matches toplevel elements that aren't yet contained in another syntax group. Add containedin=ALL to embed this everywhere. Note that this may disrupt the existing syntax.
  • The definition in ~/.vimrc is too early; another syntax script will override yours. Prepend :autocmd Syntax * to the :syntax command, and place this after the :syntax on in your ~/.vimrc.

You need two entries, one for files without filetype-specific syntax rules (e.g. files without an extension) and one for files with syntax rules (e.g. .py files):

syntax on

" For files that don't have filetype-specific syntax rules
autocmd BufNewFile,BufRead *syntax match NotPrintableAscii "[^\x20-\x7F]"

" For files that do have filetype-specific syntax rules
autocmd Syntax * syntax match NotPrintableAscii "[^\x20-\x7F]" containedin=ALL

hi NotPrintableAscii ctermbg=236

Upvotes: 3

Related Questions