Interactive clojure code snippets with MDX, SCI and Codemirror

May 17, 2020

Today is the 17th of May and Norway is currently celebrating its Constitution Day. It is a festive day with lots of celebrations and flag waving, and some people start celebrating eating breakfast (really lunch) with friends. The breakfast is often accompanied by various bubbly wines like Champagne.

Not that I do not enjoy such occations myself, but there is also fun to be had in making my blog even better! So to start of the day I sat down and finished the interactive Clojure code snippet feature for my website. It is based around three core technologies:

The Small Clojure Interpreter (sci) is a Clojure interpreter written in Clojure by Michiel Borkent. He has written a number of Clojure libraries and software and sci has become widely used counting 377 stars on GitHub. That is no small feat for a Clojure library. sci is built to expose only the pure APIs from Clojure to ensure untrusted scripts can be read and executed. This makes it an ideal library to use for code snippets running in the browser.

Codemirror is a web based editor for code that features syntax highlighting, line counts, and other features pratical for coding. It has a number of modes (language highlighting support) and themes, including a mode for Clojure and a theme fitting nicely with my website's design. I use a React wrapper around Codemirror and the state is handled using react hooks.

Markdown for the component era

MDX is a new document format that builds on Markdown and JSX. The allure of the MDX format is that you can write the simple things like heading and paragraphs in Markdown's simple format. When you need more advanced markup or interactive content you can reach into JSX components. By rewriting my blog setup to allow posts to be written in the MDX format it is now possible for me to embed interactive Clojure snippets.

Below you see a simple Clojure snippet generating a number sequence from 0 to 99 and then finding out which of them is divisible by two. Feel free to play around with Clojure code in the editing area. The code is evaluated shortly after you stop typing for immediate feedback. No warranties provided, you may end up locking your browser thread with an infinite sequence or something similar. Preventing this is on my roadmap as it is built into sci and should be easy to activate.

This concludes the description of my new interactive Clojure snippets setup. Going forward I will try to post Clojure snippets I find interesting. By embedding interactive code within blog posts I hope to enable readers to walk away with a deeper understanding of the code. Thank you for reading!

© 2020 Snorre Magnus Davøen. Built with Gatsby. Hosted by Cloudflare. This page is opensource. Its source code is available on GitHub.