Vim: dynamic syntax
I want to dynamically (ie, depending on the content of the current file) adapt syntax highlighting. While this might be useful in general, my specific setting is as follows:
The kind of files I consider may contain (arbitrary many) blocks of the form (VAR ...)
, where such "VAR-blocks" contain a space-separated list of identifiers that should be considered as variables (while identifiers that are not in a VAR-block are considered to be fixed function symbols or constants). Furthermore, there is already a file trs.vim
that takes care of syntax highlighting for such files. In trs.vim
a syntax group trsKeyword
is declared. Now my goal is to highlight all variables using this group.
Consider the following example (lets call it add.trs
):
(VAR x y)(RULES
add(z, y) -> y
add(s(x), y) -> s(add(x, y))
)
When opening add.trs
in vim, I want that x
and y
are printed as keywords (whereas for example z
is not, despite having no arguments).
I already achieved the desired result (but wanted to share it on SO). So here it is (the following snippets should be combined in a file vars.vim
).
First I define a pattern that will recognize VAR-blocks:
" pattern that matches VAR-blocks of *.trs files
let varblock = '(VARs*(.*))'
Then I check the current file (maybe there is a better way than using %
for that?) for VAR-blocks and ignore the case where no match was found.
" create list of variables from all VAR-blocks
try
silent exe "vimgrep /" . varblock . "/j %"
catch /^Vim%((a+))=:E480/ " no match
" do nothing
endtry
The found matches are obtained by getqfilst()
, which I copy. Then I replace every element in this list by the first subgroup that matched the varblock
pattern (which will be a string containing space-separated identifiers). I join all such strings into a single one and then split it at spaces to get a list of identifiers:
let vars = split(join(map(copy(getqflist()), 'matchlist(v:val.text, varblock)[1]')))
Finally I create a pattern matching these identifiers and register it to the trsKeyword
group:
" activate syntax highlighting for variables
exe "syn match trsKeyword "<(" . join(vars, '|') . ")>""
" echo "variables: " . join(vars, ", ")
To make it work together with trs.vim
I created the directory ~/.vim/syntax/trs
and put trs.vim
as well as vars.vim
inside. Then in my ~/.vimrc
I added
" TRS files
au BufNewFile,BufRead,BufWrite *.trs setf trs
which activates syntax highlighting for files ending with .trs
(and also updates the list of variables whenever a buffer is saved).
上一篇: 反引号,解开引号,引号,解开序列?
下一篇: Vim:动态语法