CodeMirror NodeJS Runmode for Syntax Highlighting

This is a quick demo on how to use CodeMirror's nodejs runmode to generate html, useable for example in blog posts, for syntax highlighted code snippets.

Setup

apt-get update && apt-get install nodejs npm
22.2s
Bash
npm install codemirror
2.8s
Bash

The source we want to syntax highlight

(defn foo [a]
  (str "hello")
  (+ 1 2))
sample.clj
Clojure

A simple CodeMirror Runmode NodeJS script

For available modes, see the Github repo, we use clojure in the example

const cm = require("codemirror/addon/runmode/runmode.node.js");
require("codemirror/mode/clojure/clojure");
const fs = require('fs');
const src = fs.readFileSync("sample.clj", {encoding: "utf8"});
var html = "<pre class=\"cm-s-default\">\n";
const outf = function(token, tokenClass) {
 html = html + "<span class=\"pm-" + tokenClass + "\">" + token + "</span>\n"
}
cm.runMode(src, "clojure", outf);
html = html + "</pre>\n";
fs.writeFileSync("results/out.html", html);
console.log(html);
tohtml.js
JavaScript

Make it so!

node tohtml.js
1.3s
Bash
out.html

Display this HTML using the Codemirror CSS or any of the available themes: https://github.com/codemirror/CodeMirror/blob/master/lib/codemirror.css

Runtimes (1)