Skip to content

Loading packages conditionally

The :if, :when, and :unless keywords predicates the loading and initialization of packages. They all accept one argument, an Emacs Lisp form that is evaluated at run-time.

If the argument of the :if keyword evaluates to non-nil, the package will be loaded and initialized. The :when keyword is provided as an alias for :if. Finally, the :unless keyword is the inverse of :if, such that :unless foo means the same thing as :if (not foo).

For example, if you only want to load ‘foo’ in graphical Emacs sessions, you could use the following:

emacs-lisp
(use-package foo
  :if (display-graphic-p))

Some common use cases

Here are some common cases for conditional loading, and how to achieve them.

  • Operating system

    The following example loads a package only on GNU/Linux. See the docstring of system-type for other valid values.

    :if (eq system-type 'gnu/linux)
  • Window system

    The example below loads a package only on macOS and X. See the docstring of window-system for valid values.

    :if (memq window-system '(ns x))
  • Installed package

    The following example loads a package only when the ‘foo’ package is installed.

    :if (package-installed-p 'foo)
  • Libraries in load-path

    The example below loads a package only when foo.el is available in your load-path (for example, if you installed that file manually):

    bash
    :if (locate-library "foo.el")

Making conditional loading affect :preface and :ensure

If you need to make a use-package form conditional so that the condition occurs before even :ensure (see Installing package) or :preface (see :preface is evaluated first), use when around the use-package form itself. For example:

emacs-lisp
(when (memq window-system '(mac ns))
  (use-package foo
    :ensure t))