I'm using jinja template language to generate html and javascript for a website. How can I make vim understand that everything between '{{'/'}}'
and '{%'/'%}'
is Jinja code and the rest it javascript code? Is there a simple way of doing that?
There is a relatively easy way to have different regions in your code that use different syntax files, by using the "syntax include" command and a "syntax region" command to define each region. Below is some code I have to syntax highlight different regions of Perl, R, and Python in a single document. The 'unlet' statments are necessary because the syntax files often depend on b:current_syntax not existing when they are first run. Yours would be similar, but define the 'start' and 'end' for the jinja and javascript regions using the delimiters you listed in your question. Check help for "syn-region" and "syn-include" to get more info:
let b:current_syntax = ''
unlet b:current_syntax
syntax include @Perlcode $VIMRUNTIME\syntax\perl.vim
syntax region rgnPerl start='^src-Perl' end='^end-Perl' contains=@Perlcode
let b:current_syntax = ''
unlet b:current_syntax
syntax include @rinvim $VIMRUNTIME\syntax\r.vim
syntax region rgnR matchgroup=Snip start="^src-R" end="^end-R" keepend contains=@rinvim
let b:current_syntax = ''
unlet b:current_syntax
syntax include @python $VIMRUNTIME\syntax\python.vim
syntax region rgnPython matchgroup=Snip start="^src-Python" end="^end-Python" keepend contains=@python
let b:current_syntax='combined'
I'm not sure about how to get different auto-indenting in the regions, that's a question I was going to look into myself. I think one solution would be to consolidate all of the languages indent files into one and have an if structure that processes according to which region it finds itself in. Maybe there's a simpler way than that, though.
For the syntax, my SyntaxRange plugin makes the setup as simple as a single function call.
For different filetype settings like indentation options, you have to install an :autocmd CursorMoved,CursorMovedI
that checks into which region the current line falls (maybe using the syntax for hints, e.g. with synID()
), and then swaps the option values depending on the result.
Edit: For your particular use case, that would be something like:
:call SyntaxRange#Include('{{', '}}', 'jinja')
:call SyntaxRange#Include('{%', '%}', 'jinja')
which you could put into ~/.vim/after/syntax/javascript.vim
to apply it automatically to all JavaScript files.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With