问题
I have a script that reads an HTML file and replaces occurrences of ~%foo%~
with a value set by Perl. Something like this:
<span class="~%classname%~">~%hi_mom%~</span>
Would produce something like this in the browser:
<span class="classyclass">Hello World</span>
Right so I want to use Vim syntax highlighting to distinguish the occurrences ~%foo%~
in the HTML. By default, the HTML syntax highlighting will make an HTML element's attribute values Magenta
and I want the ~%foo%~
portion to be DarkMagenta
. I'm on the right track because if I comment out the tokenQuoted
lines (or token lines) I get the desired results but with both matches and highlights uncommented the token highlighting overrides the tokenQuoted
highlighting.
syntax match token containedin=ALLBUT,htmlString,htmlValue '\~%[^%]\+%\~'
syntax match tokenQuoted containedin=htmlString,htmlValue '\~%[^%]\+%\~'
" tokenQuoted assumes htmlString/htmlValue (:highlight String) is Magenta
highlight token term=none ctermfg=White guifg=White
highlight tokenQuoted term=none ctermfg=DarkMagenta guifg=DarkMagenta
The file I'm working in is sourced after the default html.vim
is sourced via
autocmd *.html ~/.vim/syntax/html.vim
in .vimrc
.
回答1:
The problem is that token
match is not being excluded from being contained in the tokenQuoted
match. To get the desired results, i.e. highlighting quoted tokens different from non quoted tokens, use the following in your syntax file.
syntax match token containedin=ALLBUT,htmlString,htmlValue,tokenQuoted '\~%[^%]\+%\~'
syntax match tokenQuoted containedin=htmlString,htmlValue '\~%[^%]\+%\~'
highlight token term=none ctermfg=White guifg=White
highlight tokenQuoted term=none ctermfg=DarkMagenta guifg=DarkMagenta
Or if it makes sense to use a syntax region rather than a match, replace the syntax match lines above with the following.
syntax region token contained start=+\~%+ end=+%\~+ containedin=ALLBUT,htmlString,tokenQuoted
syntax region tokenQuoted contained start=+\~%+ end=+%\~+ containedin=htmlString
I guess I should also mention that when I was testing this I just created the file ~/.vim/syntax/html.vim
and added the above content. There was no need to add anything to my .vimrc file.
来源:https://stackoverflow.com/questions/5267205/custom-vim-html-syntax