Making init files intelligible


One of the issues with an editor as configurable as emacs is that an emacs .init.el file ends up an unmaintanable mess of barely understood code snippets, duplicate and contradictory settings, and a treasure trove of forgotten knowledge.

We can do better.

So in this post I'll show you how to have a documented, human-readable emacs configuration file.

The problem

Emacs is massively customisable. These customisations are stored in elisp source files (e.g. ~/.emacs.d/init.el), which are interpreted by emacs on startup. The difficulty is that these files are usually composed of various snippets from a variety of sources, which results in a configuration that can be hard to read and maintain.

The solution

So how do we avoid this? You can simply comment the elisp code, but in reality this doesn't scale very well. The same setting gets duplicated in multiple locations, and worse. So instead, we want a hierarchical structure, where there's a correct place for each setting. This means that when you decide to fine tune the behaviour of a particular setting, you know where to look for the current setting.

The magic bullet to make this work is org-mode. This allows creating a structured document, which has code snippets in it. Note that we've reversed the sense of the configuration file here: rather than code with a smattering of comments, we're now talking about a document with a smattering of code. But a document for configuration is only useful if it can be interpreted by emacs. This is where org-babel comes in. This translates the org-mode file and extracts all the code blocks. The documentation includes an example that does exactly what we need. This example init.el translates the document into code on starting up emacs, which is then interpreted by emacs. So the init file is always up to date whenever you restart emacs.

I recommend keeping your ~/.emacs.d/ directory as a git repository, synced to Github. As a bonus, github renders the org-mode file in the same fashion that it renders markdown or jupyter notebooks. If you choose to name the main configuration file README.org, then this is the page that renders as the front page of the repository.

Here's some examples:

  • Raw (i.e. unrendered) readme.org - this is the form in which the configuration file is written. Note that org-mode makes this easier to use when opened in emacs rather than a web browser.

  • How Github renders the file. Much more readable. Note that this link and the previous link are to a snapshot in time; the current readme.org may have diverged from this.

  • An example of how well this scales. This is a link to Sacha Chua's config (of emacs news fame).

  • A reminder that you'll need some boilerplate in your ~/.emacs.d/init.el file.

See also