In this post I will describe the setup I use to keep my Emacs configuration file in an org-mode document, and extracting and compiling the configuration automatically when I save the file.

I keep my configuration files in a git repository. There I also have an init.el file that will run the first time the repository is checked out. This file looks as follows:

;; This file replaces itself with the actual configuration at first run.

;; We can't tangle without org!
(require 'org)
;; Open the configuration
(find-file (concat user-emacs-directory "init.org"))
;; tangle it
(org-babel-tangle)
;; load it
(load-file (concat user-emacs-directory "init.el"))
;; finally byte-compile it
(byte-compile-file (concat user-emacs-directory "init.el"))

I don’t want to track any changes to this file, so I run the following git command to make sure that later changes to this file will be ignored. git update-index --assume-unchanged init.el

To automatically tangle and compile the org-mode document (which I call init.org), I have the following code section in the org document. It defines function that tangles (extracts) the lisp code and byte compiles it.

#+BEGIN_SRC emacs-lisp
(defun tangle-init ()
  "If the current buffer is 'init.org' the code-blocks are
  tangled, and the tangled file is compiled."
  (when (equal (buffer-file-name)
              (expand-file-name (concat user-emacs-directory "init.org")))
  ;; Avoid running hooks when tangling.
  (let ((prog-mode-hook nil))
    (org-babel-tangle)
    (byte-compile-file (concat user-emacs-directory "init.el")))))

(add-hook 'after-save-hook 'tangle-init)
#+END_SRC

This function is added to the after-save-hook, and will be executed when the init.org file is saved. This will produce the init.elc file that Emacs will read when it starts.