Implement a Syntax Highlighter Adapter

A syntax highlighter must implement the interface org.asciidoctor.syntaxhighlighter.SyntaxHighlighterAdapter. This has to be registered at the Asciidoctor instance, so that it can be used by using the corresponding value for the attribute :source-highlighter.

A SyntaxHighlighterAdapter must implement methods to add stylesheets and scripts to the resulting HTML document. This is considered as a core functionality that every syntax highlighter requires.

The following example shows a very simplistic syntax highlighter that uses highlight.js:

import org.asciidoctor.extension.LocationType;
import org.asciidoctor.syntaxhighlighter.SyntaxHighlighterAdapter;

import java.util.Map;

public class HighlightJsHighlighter implements SyntaxHighlighterAdapter { (1)

    @Override
    public boolean hasDocInfo(LocationType location) {
        return location == LocationType.FOOTER;         (2)
    }

    @Override
    public String getDocinfo(LocationType location, Document document, Map<String, Object> options) { (3)
        return "<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.6/styles/github.min.css\">\n" +
            "<script src=\"https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.6/highlight.min.js\"></script>\n" +
            "<script>hljs.initHighlighting()</script>";
    }

}
1 Every syntax highlighter must implement the interface org.asciidoctor.syntaxhighlighter.SyntaxHighlighterAdapter.
2 The method hasDocInfo indicates that this highlighter only wants to add DocInfo to the footer of the document.
3 The method getDocInfo is only called to return the DocInfo for the footer of the document. It returns references to the required css and js sources and starts highlight.js.

Let’s say we want to convert this document:

sources.adoc
= Syntax Highlighter Test

== Some sources

[source,java]
----
public static class Test {
  public static void main(String[] args) {
    System.out.println("Hello World");
  }
}
----

Now this document can be converted using our highlighter after registering it with Asciidoctor:

        File sources_adoc = //...

        asciidoctor.syntaxHighlighterRegistry()
            .register(HighlightJsHighlighter.class, "myhighlightjs"); (1)

        String result = asciidoctor.convertFile(sources_adoc,
            Options.builder()
                .standalone(true) (2)
                .toFile(false)
                .attributes(Attributes.builder().sourceHighlighter("myhighlightjs").build()) (3)
                .build());

        assertThat(result,
            containsString("<script>hljs.initHighlighting()</script>"));
1 Register the adapter class using a well defined name.
2 Docinfo is only written if the document is converted with the option :header_footer.
3 The well defined name that was used to register the syntax highlighter must be used in the attribute :source-highlighter.