Asciidoctor has built-in support for a couple of source syntax highlighting libraries like Coderay, Pygments, highlight.js and prettify. In this post we learn how to use the Javascript library Prism to do the syntax highlighting for our source blocks. Because Prism is a Javascript library we must remember this only works for the HTML backend of Asciidoctor.

In the following markup we have two source code listings in Java and Groovy:

= Source highlights with Prism
// Set default language for source code listings to java.
:source-language: java
// Include docinfo.html for Prism CSS file and
// include docinfo-footer.html for Prism Javascript.
:docinfo1:

== Creating an application

To create a simple Ratpack application we write
the following code:

.Simple Java Ratpack application
[source]
----
package com.mrhaki;

import ratpack.server.RatpackServer;

public class Main {
    public static void main(String... args) throws Exception {
        RatpackServer.start(server ->
            server
                .handlers(chain ->
                    chain
                        .get(ctx -> ctx.render("Hello World!"))));
    }
}
----

.Simple Groovy Ratpack application
[source,groovy]
----
package com.mrhaki

import static ratpack.groovy.Groovy.ratpack

ratpack {
    handlers {
        get {
            render "Hello World!"
        }
    }
}
----

Each source listing is transformed to HTML with the following structure:

{code}

This fits perfectly with Prism. Prism expects this format to apply the syntax highlighting. So we only have to add the Prism Javascript and CSS files to the generated HTML file. We download the Prism Javascript and CSS file from the Prism download site. We save the Javascript file as prism.js and the CSS file as prism.css. Next we create a docinfo.html to include a reference to the prism.css file:

 /* Override Asciidoctor CSS to get the correct background */
.listingblock pre[class^="highlight "] {
    background: #272822;
} 

We also create the file docinfo-footer.html to reference prism.js:

In our markup we have the document attribute docinfo1 set. This means the files docinfo.html and docinfo-footer.html are included in the generated HTML output. Let's see the result in a web browser:

Written with Asciidoctor 1.5.4.

Original blog post

shadow-left