Syntax highlighting

It is sometimes desirable to add syntax highlighting to code listings. Syntax highlighting adds formatting attributes to keywords and punctuation in a way that makes it easier for the reader to separate code from text.

The DocBook XSL stylesheets provide support for syntax highlighting if you are using the Saxon XSLT processor. Some of the support is integrated into the stylesheets (starting with version 1.71.1), but most of the work is performed by the separate XSLTHL package written in Java that you download and install on your system.

Here are the steps to get syntax highlighting working on your system:

  1. Download and copy to some convenient location the xslthl.jar file from the XSLTHL project's SourceForge page at http://sourceforge.net/projects/xslthl.

  2. In your programlisting elements, add a language attribute to indicate the programming language. For example:

    <programlisting language="java">
    ...

    See the configuration files in the DocBook XSL highlighting subdirectory to see what languages are currently supported.

  3. In your stylesheet customization layer or processing command line, set the stylesheet parameter highlight.source to 1.

    <xsl:param name="highlight.source" select="1"/>
  4. Process your documents with Saxon, configured to include the xslthl.jar file in your CLASSPATH and the XSLTHL configuration file specified as a resource. For example:

    java -cp "c:/java/saxon.jar;c:/java/xslthl.jar" \
        -Dxslthl.config="file:///c:/docbook-xsl/highlighting/xslthl-config.xml" \
        com.icl.saxon.StyleSheet   \
        -o myfile.fo   \
        myfile.xml   \
        docbook-xsl/fo/docbook.xsl

    The configuration file xslthl-config.xml is included with the DocBook XSL distribution in the highlighting subdirectory.

Note these features of the highlighting extension:

If you want to customize the highlighting properties, then you will need to customize copies of the templates in the highlight.xsl stylesheet module from either the fo or html directories. In your customization layer, you will also need to add the the namespace declaration for the xslthl prefix. For example, this customization adds blue color to keywords and grey color to comments for print output.

<?xml version='1.0'?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:fo="http://www.w3.org/1999/XSL/Format"
                xmlns:xslthl="http://xslthl.sf.net"
                exclude-result-prefixes="xslthl"
                version='1.0'>

<xsl:template match='xslthl:keyword'>
  <fo:inline font-weight="bold" color="blue"><xsl:apply-templates/></fo:inline>
</xsl:template>

<xsl:template match='xslthl:comment'>
  <fo:inline font-style="italic" color="grey"><xsl:apply-templates/></fo:inline>
</xsl:template>
...

For XSL-FO output, be sure to set xsl:output indent="no" to make sure the highlighting templates do not accidentally insert unwanted whitespace in the code listing.