Tracing emacs init from an org-mode file

At about the same time I discovered Artur Malabarba's elisp-bug-hunter, which automatically does a bisection search to find a problem in an Emacs init file, I had my own init file problem to debug. Although the bug hunter looks very interesting, I had a couple of complications in using it, so I looked for another way to debug the file.

The main thing I needed to know was where in my long init file the problem was occurring. I keep my Emacs init code in an org-mode file, with a little hook to initialize org-mode and load the file with org-babel-load-file. That seems to be pretty common these days. The obvious candidate for tracing is just the headline on the org block containing the code; that's probably enough to localize the problem enough to chase it down.

It turns out by playing games with the comments that org-babel generates, we can do just that. We can tell org to insert comments that link back to the org source file into the output Emacs Lisp file with the header

  #+PROPERTY: header-args :comments link

(or an equivalent setting elsewhere; see the Org manual for details).

Then we change the way the comments are formatted, turning them into code that simply logs a message. Here's the code for that, wrapping org-babel-load-file:

  (let ((org-babel-tangle-comment-format-beg
         "(message "%file: %source-name")n")
        (org-babel-tangle-comment-format-end "")
        (org-babel-tangle-uncomment-comments t))
    (org-babel-load-file "my-emacs-init.org"))

Using let means that these changes to the variables are only in effect during the load.

Now, after Emacs starts up, we can look in the *Messages* buffer to see if any unexpected messages occurred, and they will appear under the headline of the offending code.

Happy hacking!