Literate programming with org-babel

As part of my ongoing love affair with emacs, I've started annotating my dotfiles with org-babel. This may on the surface sound syncing these things would be a tedious task, but thanks to literate programming, its not too bad.

Literate programming?

Literate programming is a concept in which you write prose and embed in it source code. You can see examples of it in my article on git. It has the benefit of being written for humans in the first place. I haven't spent enough time with it to know if this is true, but I suspect it also makes updating the documentation with a given change a little easier as well.

I was first exposed to the concept of literate programming via docco and the javascript community. The concept was novel, I thought, but not particularly useful for a "serious" programmer like me. It all seemed a bit like too much work to be of real benefit.

Having converted this website to being generated with emacs and org-mode, I definitely needed to talk about source code. Thanks to org-babel this was possible. Inspired by this post on tmux, I decided to talk about it as well. I thought it a good idea to embed my tmux config in the post and talk about it. Fearing these would get out of sync, I assumed org had some way of referencing a standalone file for inclusion. Turns out, it has something way better: tangling.

What the heck is tangling?

Tangling is a literate programming term which basically means exporting the "for-computers" version of the file. This is in opposite to the "woven" code, which is the "for-humans" version of the documentation. org-babel has built-in support for tangling source blocks in your code, allowing you to effectively compile down to a machine readable state. It supports multiple files as well. For instance, my post on zsh contains multiple source files that, when tangled, will end up in their correct files.

What it looks like

Enough about all of this theory. Let's get down to practice. We effectively just need emacs source code constructs.

We start a source block, defining the language as python. This should setup syntax highlighting for export purposes. We then can pass flags to org-babel. The one of interest is :tangle <filename> which says where the file will output when you C-c C-v C-t or org-babel-tangle the file, which exports these blocks to their relevant files.

I type some prose here.

#+begin_src python :tangle
,#!/usr/bin/env python

,print "This is my python file."

More prose can go here.

There are quite a few more things you can do from here. You can set your entire org document to export to a single file. You can evaluate all of these source blocks during tangling and export the results to files. This is in contrast with exporting raw files as I do with my dotfiles. This is interesting if you're doing data processing with R or something similar.


© 2012 - 2023 · Home — Theme Simpleness