Publishing Code in a Blog Post

As regular Irreal readers know, I prepare all my blog posts with org2blog. One of the nice features of that is that any code I include in a post is automatically fontified in a language appropriate way. Recently, both Xah Lee and Magnar Sveen have published short pieces on how they include source code in their blog posts. They both use a strategy of calling htmlize to do the heavy lifting of fontifying the code.

Sveen's method is specialized for his What the .emacs.d!? blog. He calls htmlize-region to mark up the selected code with appropriate <span> tags for use with CSS. The result is inserted into a template for the blog post and written to a buffer associated with a file for that post. It's simple, direct, and purpose-built for writing What the .emacs.d!? blog posts. He can mark some code from his configuration files, call what-the-emacsd-post to htmlize it and insert the result into a post template ready to be completed and published.

Lee's solution is more comprehensive. He writes about many languages so his strategy is different. With his code you put the cursor between the <pre> tags for code you want to include and call htmlize-pre-block. The language of the source code is extracted from the <pre> tag and then the code in the pre block is inserted into a temporary buffer that is set to the appropriate mode according to the language extracted from the <pre> tag. Next htmlize-buffer is called to mark up the code and the result replaces the original code between the <pre> tags.

This is a nice solution because it can handle a large range of languages and is reasonably flexible. Notice that Lee's method assumes you already have the code in a pre block and that you just want to fontify it. In a sense, it's the reverse of what Sveen does: extract the code from a source file and insert it into a new HTML file.

Both of these solutions are useful. Which one you should use depends on your work flow and whether you are dealing with one language or many. For my part, I have always written my posts in Org mode. Before I started using WordPress and org2blog, I wrote my posts in Org mode and called

(defun blog-post ()
  "Export an org buffer as HTML but only export the body."
  (org-export-as-html 3 nil nil "*blog-post*" t))

to turn the whole buffer into HTML. Then I pasted that into the Blogger control panel to publish the post. A little clunky but much better than typing in posts to the control panel.

I like to see how other bloggers handle the writing and publishing of their posts so I always enjoy posts like Lee's and Sveen's. Besides, it's always nice to see Emacs in action.

This entry was posted in General and tagged . Bookmark the permalink.