Sunday, June 29, 2014

Using htmlize to prettify Clojure source code

I have been trying to figure out the best way to include syntax-highlighted source code in a blog post. One solution is to use htmlize in emacs.

Let's say I want to include the following syntax-highlighted code in my blog:
(defn cheese-ston [a b]
  (println a b))
The first step is to install htmlize. I've already got MELPA added so I just install the htmlize package from that.

Next, I want to configure htmlize to output any CSS inline (so that I can cut and paste HTML snippets into Blogger) so I add the following to my init.el and execute it immediately.
(setq htmlize-output-type 'inline-css)
Next, I highlight the code that I want to export and then do:
M-x htmlize-region
This gives me a new buffer with a complete HTML file containing my text, wonderfully highlighted. I can then copy everything within the body of that HTML page into the raw HTML editor in Blogger:
<pre>
<span style="color: #707183;">(</span><span style="color: #a020f0;">defn</span> <span style="color: #0000ff;">cheese-ston</span> <span style="color: #7388d6;">[</span>a b<span style="color: #7388d6;">]</span>
  <span style="color: #7388d6;">(</span><span style="color: #483d8b;">println</span> a b<span style="color: #7388d6;">)</span><span style="color: #707183;">)</span></pre>
Before switching back to the Compose view, I have to ensure that Blogger is not going to quote my HTML so I hit Options on the right and make sure that Show HTML literally is selected.

Previewing the post, I can now see my Clojure code wonderfully highlighted as above.

This whole process is slightly faffy. What I really want is to remove the step where I have to find the right bit of HTML to copy into Blogger's raw HTML editor. One solution would be to figure out how to get htmlize to output HTML snippets (rather than whole documents). Another alternative would be to use org-mode - which works well with htmlize - to output the whole blog post. I'll write more if I get round to trying that.