Search code examples
htmlvimcoffeescriptsyntax-highlightingvim-syntax-highlighting

How to embed HTML string syntax in CoffeeScript using VIM?


I have looked at how to embed HTML syntax in JavaScript string from HTML syntax highlighting in javascript strings in vim.

However, when I use CoffeeScript I cannot get the same thing working by editing coffee.vim syntax file in a similar way. I got recursive errors which said including html.vim make it too nested.

I have some HTML template in CoffeeScript like the following::

angular.module('m', [])
  .directive(
    'myDirective'
    [
      ->
        template: """
        <div>
          <div>This is <b>bold</b> text</div>
          <div><i>This should be italic.</i></div>
        </div>
        """
    ]
  )

How do I get the template HTML syntax in CoffeeScript string properly highlighted in VIM?


Solution

  • I would proceed as follows:

    Find out the syntax groups that should be highlighted as pure html would be. Add html syntax highlighting to these groups.

    To find the valid syntax group under the cursor you can follow the instructions here.

    In your example the syntax group of interest is coffeeHereDoc.

    To add html highlighting to this group execute the following commands

    unlet b:current_syntax
    syntax include @HTML syntax/html.vim
    syn region HtmlEmbeddedInCoffeeScript start="" end=""
    \    contains=@HTML containedin=coffeeHereDoc
    

    Since vim complains about recursion if you add these lines to coffee.vim i would go with an autocommand:

    function! Coffee_syntax()
        if !empty(b:current_syntax)
            unlet b:current_syntax
        endif
        syn include @HTML syntax/html.vim
        syn region HtmlEmbeddedInCoffeeScript start="" end="" contains=@HTML
    \       containedin=coffeeHereDoc
    endfunction
    
    autocmd BufEnter *.coffee call Coffee_syntax()