Friday, July 01, 2011

Automatically byte compile your Emacs configuration file

I like the ability to automatically byte compile my .emacs file but never had Emacs behave in a way that was acceptable to me. In particular, the interaction between debugging a .emacs file and automatic byte compile sometimes is troublesome. The solution for me which is least bad is to automatically byte compile on save of the .emacs buffer. To do this, add the following code to your .emacs.

(defun auto-recompile-emacs-file ()
  (interactive)
  (when (and buffer-file-name (string-match "\\.emacs" buffer-file-name))
    (let ((byte-file (concat buffer-file-name "\\.elc")))
      (if (or (not (file-exists-p byte-file))
              (file-newer-than-file-p buffer-file-name byte-file))
          (byte-compile-file buffer-file-name)))))

(add-hook 'after-save-hook 'auto-recompile-emacs-file)

Sam Morar suggests a more general solution of automatically compiling after saving a lisp-mode buffer.

(add-hook 'emacs-lisp-mode-hook '(lambda ()
  (add-hook 'after-save-hook 'emacs-lisp-byte-compile t t))
)

Michael Hoffman points out that one might not want to compile all lisp files. His suggestion is to compile only if a corresponding .elc file already exists.

8 comments:

Michael Markert said...

Using `byte-recompile-file' (and with an option to force):

(defun auto-recompile-emacs-file (&optional force)
(interactive "P")
(when (and buffer-file-name (string-match "\\.emacs" buffer-file-name))
(byte-recompile-file buffer-file-name force)))

Sam Morar said...

I use this to byte-compile all lisp files upon save, which obviously includes the emacs config file:

(add-hook 'emacs-lisp-mode-hook '(lambda ()
(add-hook 'after-save-hook 'emacs-lisp-byte-compile t t))
)

tsengf said...

Hi, Michael, I think the optional argument applies only to byte-recompile-directory. Correct me if I'm wrong.

tsengf said...

Thanks Sam for the suggestion of a more general solution.

kiwanami said...

How about auto-async-byte-compile?
One doesn't have to wait for finishing compiling.
http://www.emacswiki.org/emacs/auto-async-byte-compile.el

Michael Hoffman said...

You don't necessarily want to compile all Elisp files. Some should not be compiled. I use this code to automatically compile any where the *.elc file already exists.

tsengf said...

Thanks kiwanami for the automatic and asynchronous solution!

tsengf said...

You are correct Michael H. I guess this depends on individual requirements.