Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In VIM, how can I mix syntax/ident rules of both jinja and javascript in the same file?

Tags:

vim

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?

like image 602
Thiago Padilha Avatar asked Oct 19 '10 13:10

Thiago Padilha


2 Answers

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.

like image 109
Herbert Sitz Avatar answered Oct 22 '22 19:10

Herbert Sitz


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.

like image 20
Ingo Karkat Avatar answered Oct 22 '22 19:10

Ingo Karkat