编写color groups

syntax match BadWhiteSpace /\s\+$/

hi BadWhiteSpace guifg=gray guibg=red ctermfg=gray ctermbg=red

定义语法规则

文本匹配

syntax keyword potionKeyword loop times to while
syntax keyword potionKeyword if elsif else
syntax keyword potionKeyword class return

syntax keyword potionFunction print join string

highlight link potionKeyword Keyword
highlight link potionFunction Function

正则匹配

比如在Python代码(以ErrorMsg形式)高亮超出80个字符的行:

syntax match OverLength "\v^.{80,}$"

highlight link OverLength ErrorMsg

或定义Python代码中以#开头的行为注释:

syntax match potionComment "\v#.*$"

highlight link potionComment Comment

区域匹配

比如高亮字符串:

syntax region potionString start=/\v"/ skip=/\v\\./ end=/\v"/

highlight link potionString String

帮助

  1. :color查看当前的colorscheme
  2. :hi列出当前的color groups
  3. :hi Statement查看statement的颜色定义(或重新设置它):

检测光标位置处文字的样式名

function! <SID>SynStack()
    echo map(synstack(line('.'),col('.')),'synIDattr(v:val, "name")')
endfunc

nnoremap <leader>yi :call <SID>SynStack()<CR>

文件要求

在编写syntax文件时,应避免每次打开类型符合的文件时都重复加载syntax文件:

if exists("b:current_syntax")
    finish
endif

echom "Our syntax highlighting code will go here."

let b:current_syntax = "code"

在编写colors文件时,注意清除之前的color group和设置g:colors_name

hi clear

if exists("syntax_on")
  syntax reset
endif

let g:colors_name = "solarized"