Permanent: set syntax for a given file type?

I am working on a Symfony2 project that uses Twig, and the file types are myfile.html.twig . Vim does not automatically detect syntax highlighting and therefore does not apply. I can use :set syntax=HTML after I opened the file, but this is a pain when switching between files.

Is there a way to persistently set syntax highlighting for a specific file type in vim?

+73
vim macvim syntax-highlighting twig
Jul 26 '12 at 9:21
source share
5 answers

You can use autocmd for this, autocmd .:

 augroup twig_ft au! autocmd BufNewFile,BufRead *.html.twig set syntax=html augroup END 

It should work.

+93
Jul 26 2018-12-12T00:
source share
— -

Add one of the following snippets to your .vimrc :

 " Set the filetype based on the file extension, overriding any " 'filetype' that has already been set au BufRead,BufNewFile *.html.twig set filetype=html 

or

 " Set the filetype based on the file extension, but only if " 'filetype' has not already been set au BufRead,BufNewFile *.html.twig setfiletype html 
+30
Jan 23 '15 at 19:30
source share
 au BufNewFile,BufRead,BufReadPost *.twig set syntax=HTML 

And add this line to ~/.vimrc to make the settings permanent.

+7
Jul 26 2018-12-12T00:
source share

I know that this does not directly answer the question, however this answers the purpose of the question, which is to get syntax highlighting working with Twig / Symfony 2

I suggest you check out https://github.com/beyondwords/vim-twig (not mine) which provides:

  • syntax highlighting file for * .html.twig,
  • file type detection for it and
  • file type that allows you to change various settings when editing * .html.twig files.

I hope this helps

+1
Aug 27 2018-12-12T00:
source share

This is the simplest case. Typically, complex functions can be used to determine syntax. Unfortunately, they may not work correctly. If you have a simple case when the algorithm gives an error, you need to exclude the extension from one and write separately for this case. For example, I always get vmasm syntax for Mac files. So it really is a clean GNU Assembler macro file. And so I need to manually change the syntax with the command: set syntax = asm every time after opening this file for editing. But after the procedure above, the syntax definition is correct.

0
Nov 22 '17 at 18:46
source share



All Articles