Zamansky 19: Conditional Loading of Emacs Config

Mike Zamansky has another video in his Using Emacs Series. This video addresses a problem he has while making the videos. A theme of the series is building an Emacs configuration. Each video considers 1 or 2 packages or features and how to configure and use them. The problem is he needs his entire configuration to get his other work done and it’s a pain to move between the partial and complete configurations.

Zamansky solves this problem by conditionally loading the rest of his configuration. Thus, he can put the partial configuration on GitHub for anyone who’s following along to use but when he uses it for his real work, the rest of his configuration will be loaded. The only wrinkle is what to do if the rest of the configuration is not present as will be the case when those following along at home use his config. His solution is to wrap the loading of the rest of his configuration in an if statement that tests if the file is present:

(defun load-if-exists (f)
  (if (file-readable-p f)
      (load-file f)))

Then he can conditionally load other files with

(load-if-exists "some-file.el")

This has the additional benefit of introducing a bit of Elisp, something that every serious Emacs user will eventually have to get comfortable with.

Most of us won’t have this problem but it does show how to conditionally load files, something that’s useful for us all. Here, for example, is how I load OS and machine specific configuration items

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Pull in system and platform specific configurations                    ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; Just keep on going if the requisite file isn't there.
;; Manipulations in second load is for "gnu/linux" --> "linux"

(load (car (split-string (system-name) "\\.")) t)
(load (car (reverse (split-string (symbol-name system-type) "/"))) t)

Using load with a second argument of t is functionally equivalent to Zamansky’s load-if-exists.

This is a short video so there’s no reason not to watch it. Even if you’re an experienced Emacser, it’s interesting to see how others solve common problems.

UPDATE [2016-11-12 Sat 12:16]: loadload-file

This entry was posted in General and tagged . Bookmark the permalink.