Jim Hurne
Jim Hurne

Reputation: 7359

How to syntax-highlight XML in CDATA elements in Vim?

Vim's syntax highlighting for XML/XSL is great, except it turns off all syntax highlighting in CDATA regions. Is there a way to turn on syntax highlighting on in CDATA regions?

At work, we have a lot of XSL code embedded within other XML documents. It would be great if I could get all of the goodness of XML editing for the embedded XSL code as well without having to temporarily remove the CDATA tags, or copy the CDATA content into a temporary file.

Example:

<root>
  <with type="xsl"><![CDATA[
      <xsl:template match="/">
          <!-- XSL content here -->
      </xsl:template>
   ]]>
  </with>
</root>

The XSL is always contained within , so there is something to match against.

We also sometimes embed Javascript inside CDATA regions as well. It would be nice to turn on Javascript syntax highlighting for those regions.

Upvotes: 2

Views: 1753

Answers (3)

Apocalisp
Apocalisp

Reputation: 35054

The syntax include directive is specifically intended to accomplish this kind of thing, and xml.vim (in recent versions, yours may differ) has a "hook" cluster called xmlCdataHook that you can override with your own syntax files.

Open your xml.vim syntax file and add this line:

syn include @xmlCdataHook <sfile>

This gives you xml syntax highlighting inside CDATA sections. Point to another file like <sfile>:p:h/javascript.vim in order to get javascript highlighting.

Alternatively, you can avoid editing the xml.vim file and just add your own syntax hook for CDATA sections:

syntax include @JS $VIMRUNTIME/syntax/javascript.vim
syntax region start=/\V<![CDATA[/ end=/\V]]>/ contains=@JS

Upvotes: 2

Jim Hurne
Jim Hurne

Reputation: 7359

It isn't possible.

I've left this question open for 9 months with no progress, and my own research has found nothing useful. Thus, I have no choice but to conclude that it simply isn't possible.

Upvotes: 0

Nic Gibson
Nic Gibson

Reputation: 7143

You would need to modify the syntax highlighting script that comes with vim (it's in /usr/share/vim/vim72/syntax/xml.vim on my system). However, I'm pretty sure this is a bad idea - you will be operating under the 'illusion' that the content of the CDATA section is actually XML and it's definitely not - as it's in a CDATA section it's just text.

In order to handle embedded javascript (which seems less risky to me) you will also need to create a modified syntax highlighter. A good place to start looking for information on how to do this would be the XHTML syntax highlighter for vim - that supports embedded languages

Upvotes: 0

Related Questions