ICYROCK.COM

Home

Using SyntaxHighlighter from Clojure

2015-Oct-18 20:16
clojuresyntax-highlighting

There exists a well-known syntax highlighting library for Javascript:

There is also a port of it to Java:

with a problem however - the brushes are re-written in Java, which means two things:

One option to use Syntax Highlighter in Clojure is to run the Javascript version using embedded Rhino or Nashorn instance, see:

and:

for more details. This also allows for using other Javascript-based syntax highlighters, such as:

The previous post explains how to execute Javascript from Clojure. Building on top of that, we just need some Javascript that will actually run SyntaxHighlighter given the source code.

Setup ScriptEngine instance with SyntaxHiglighter scripts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
(def sh-script-engine
  (let [se (-> (ScriptEngineManager.)
               (.getEngineByMimeType "application/javascript"))
        files [
               "XRegExp.js"
               "shCore.js"
               "shBrushBash.js"
               "shBrushClojure.js"
               "shBrushJScript.js"
               "shBrushXml.js"
               ]]
    (doseq [f files]
      (.eval se (slurp-src-file (str "syntax-highlighter/syntaxhighlighter/scripts/" f))))
    se))

The version I am using is SyntaxHighlighter 3.0.83. Be sure to include all the brushes you need. E.g. if you need Java source highlighting, include shBrushJava.js. I am using this Clojure brush:

SyntaxHighlighter bootstrap Javascript

1
2
3
4
5
6
7
8
9
10
var ShBrush = SyntaxHighlighter.findBrush(brush);
 
var inst = new ShBrush();
inst.init({className: '', toolbar: false});
 
try {
  inst.getHtml(code);
} catch(e) {
  "<pre>" + e.stack + "</pre>"
}

This Javascript lives in syntax-highlighter-bootstrap.js and is used by the client below.

Client interface

1
2
3
4
5
6
7
(defn syntax-highlight [file brush]
  (let [se sh-script-engine
        shb (slurp "syntax-highlighter/syntax-highlighter-bootstrap.js")
        code (slurp file)]
    (.put se "brush" brush)
    (.put se "code" code)
    (.eval se shb)))

Sample invocation

If we have a file called hello.clj, we can get the Clojure syntax highlighted version like this:

1
(syntax-highlight "hello.clj" "clojure")

This will return the HTML itself which can be put into hello.htm and loaded directly into the browser. It is important to include SyntaxHighlighter CSS files:

1
2
3
4
5
6
<html>
  <head>
    <link rel="stylesheet" href="syntaxhighlighter/shCore.css" />
    <link rel="stylesheet" href="syntaxhighlighter/shThemeDefault.css" />
  </head>
</html>