3

I have a Jinja2 template which I'd like Vim to syntax-highlight as a Jinja2 template, but the file - once rendered - will be an Nginx configuration file.

Is there some way of getting Vim to use modelines "conditionally"?

The problem is that I cannot tinker with one modeline alone, because even though I could use a template variable, that would invalidate the modeline as far as Vim is concerned.

So essentially when I open the file as Jinja2 template I want the modeline to be treated as:

# vim: set autoindent smartindent ts=4 sw=4 sts=4 noet filetype=jinja2:

and once rendered as:

# vim: set autoindent smartindent ts=4 sw=4 sts=4 noet filetype=nginx:

Is Vim capable of doing something like that?

5

According to the second modeline format (the one with set) listed in :help modeline, you can put any text after the second :.

# vim: set autoindent smartindent ts=4 sw=4 sts=4 noet :
{# vim: set ft=jinja2: #}# vim: set ft=nginx:

In the template source code, the last line is parsed by vim as

[text][white]vim: set ft=jinja2: [text]

and the trailing text discarded. However, in the rendered output, this appears as

# vim: set ft=nginx:

Note also that you can use multiple modelines as in the example above, up to the value of set modelines (by default 5).

Processing order

Another detail to keep in mind is that vim processes modelines in the following order:

  • 5 lines from the top down.

then of the file lines that have not been processed yet,

  • 5 lines from the bottom up.

Thus, the order of processing of the above code will depend on if the modeline is placed at the top or bottom of the file, so the result could be different if the filetype overrides indentation settings.

  • Great. This answer is spot on. Many thanks for pointing out the trick and moreover for explaining it. – 0xC0000022L Nov 26 '18 at 15:50
  • 1
    In my edit, I really meant there are actually two forms of modeline as specified in :h modeline. The first of them cannot have : after the options. The second form uses set and also can append an optional [TEXT] part after the second :. – Liu Sha Nov 27 '18 at 8:06
  • @LiuSha ah okay, clarified – Mass Nov 27 '18 at 14:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.