When one writes programs or TeX documents, it is quite useful to compile the program/document quite often to be sure that there are no syntactical or other errors. I use Emacs and have the F9 key set to invoke the compile command which, by default, calls make and allows easy navigation through the detected errors, if there are some. One disadvantage of this command is that when there is unsaved buffer, it asks whether to save the modified file. This means that one have to either save the file by C-x C-s and then press F9 or press directly F9 and confirm the saving of the file by y. Neither variant is ideal because I do not like pressing unnecessary keys. (Yes, I know that I should switch to vim, but that’s another story.)

For this reason, I was looking for a solution to automatically run compile whenever a file is saved but surprisingly I could not find anything suitable for me. For example, Fredrik Hubinette’s auto-recompile seems unnecessary complicated to me. So I put together the following piece of Elisp which does exactly what I need for many years. Recently I cleaned up the code a bit, so it is good opportunity to publish it.

(defun compile-on-save-start ()
  (let ((buffer (compilation-find-buffer)))
    (unless (get-buffer-process buffer) 

(define-minor-mode compile-on-save-mode
  "Minor mode to automatically call `recompile' whenever the
current buffer is saved. When there is ongoing compilation,
nothing happens."
  :lighter " CoS"
    (if compile-on-save-mode
    (progn  (make-local-variable 'after-save-hook)
        (add-hook 'after-save-hook 'compile-on-save-start nil t))
      (kill-local-variable 'after-save-hook)))

I put this code into my .emacs. Whenever I need to recompile the file, I activate the compile-on-save-mode by M-x compile-on-save-mode and then the file is automatically recompiled whenever I save it (which I do almost automatically and very often). The code uses the recompile command which does nothing if the buffer was not compiled manually at least once. This is fine because for certain projects it is necessary to setup compile command manually and simply calling make (the default compile command) would do a wrong thing.

Posted Tue Dec 28 22:39:55 2010 Tags: