Skip to content

Instantly share code, notes, and snippets.

@bostonaholic
Created March 23, 2012 20:17
Show Gist options
  • Save bostonaholic/2174549 to your computer and use it in GitHub Desktop.
Save bostonaholic/2174549 to your computer and use it in GitHub Desktop.
#emacs #protip: buffer-file-name is nil when not viewing a file
;; I wanted to setup a hook which would compile the user init file upon exit or save.
;; So I wrote the code below to do so:
(defun my-emacs-lisp-mode-hook ()
(when (files-equal-p buffer-file-name user-init-file)
(add-hook 'after-save-hook 'byte-compile-user-init-file t t)))
(add-hook 'emacs-lisp-mode-hook 'my-emacs-lisp-mode-hook)
(add-hook 'kill-emacs-hook 'byte-compile-user-init-file t t)
;; When evaluating this directly, it worked fine.
;; However, when opening emacs it would fail and I got the following message:
;; files-equal-p: Wrong type argument: stringp, nil
;; It turns out that buffer-file-name is nil when not visiting a file, e.g. opening emacs.
;; So here is my code change to fix the issue:
(defun my-emacs-lisp-mode-hook ()
(when (files-equal-p (or buffer-file-name "") user-init-file)
(add-hook 'after-save-hook 'byte-compile-user-init-file t t)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment