Custom Syntax Highlighter Adapter

You can integrate additional syntax highlighters by implementing a syntax highlighter adapter.

To implement an adapter, you must create a class that extends the Asciidoctor::SyntaxHighlighter::Base class, register the adapter for a value of the source-highlighter attribute, and implement the required methods depending on whether the highlight step runs in the converter or in the client (i.e., browser).

Here’s an example of how to write and register a syntax highlighter adapter for the Prism.js syntax highlighting library. This library runs in the browser, so the methods focus on loading the library.

Example 1. Syntax highlighter adapter for Prism.js
class PrismSyntaxHighlighter < Asciidoctor::SyntaxHighlighter::Base
  register_for 'prism'

  def format node, lang, opts
    opts[:transform] = proc do |pre, code|
      code['class'] = %(language-#{lang}) if lang

  def docinfo? location
    location == :footer

  def docinfo location, doc, opts
    base_url = doc.attr 'prismdir', %(#{opts[:cdn_base_url]}/prism/1.15.0)
    slash = opts[:self_closing_tag_slash]
    unless (theme_name = doc.attr 'prism-style', 'prism') == 'prism'
      theme_name = %(prism-#{theme_name})
    %(<link rel="stylesheet" href="#{base_url}/themes/#{theme_name}.min.css"#{slash}>
<script src="#{base_url}/prism.min.js"></script>
<script src="#{base_url}/components/prism-ruby.min.js"></script>)

Save this code to a file named syntax-highlighter-prism.rb. Then require this file when invoking Asciidoctor and set the source-highlighter to prism to activate it:

$ asciidoctor -r ./syntax-highlighter-prism -a source-highlighter=prism document.adoc

You can also define an adapter for a syntax highlighter that runs during conversion.