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 ""))
;; tangle it
;; 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, 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 '' the code-blocks are
  tangled, and the tangled file is compiled."
  (when (equal (buffer-file-name)
              (expand-file-name (concat user-emacs-directory "")))
  ;; Avoid running hooks when tangling.
  (let ((prog-mode-hook nil))
    (byte-compile-file (concat user-emacs-directory "init.el")))))

(add-hook 'after-save-hook 'tangle-init)

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