Endless Parentheses

Ramblings on productivity and technical subjects.

profile for Malabarba on Stack Exchange

Require Feature or Install Package

A gentleman (or woman) by the name of baam_waak recently asked on /r/emacs how can one make sure a package gets installed in case requireing it fails. Sadly, this predicament has no perfect solution, for you require features, not packages. Fortunately, it has plenty of solutions that are good enough, since features commonly share the name of their package.

Motivated by the question, I saw it fit to add this functionality to paradox's arsenal.

(defun paradox-require (feature &optional filename noerror package refresh)
  "A replacement for `require' which also installs the feature if it is absent.
- If FEATURE is present, `require' it and return t.

- If FEATURE is not present, install PACKAGE with `package-install'.
If PACKAGE is nil, assume FEATURE is the package name.
After installation, `require' FEATURE.

FILENAME is passed to `require'.

If NOERROR is non-nil, don't complain if the feature couldn't be
installed, just return nil.

By default, the current package database (stored in
`package-archive-contents') is only updated if it is empty.
Passing a non-nil REFRESH argument forces this update."
  (or (require feature filename t)
      (let ((package (or package
                         (if (stringp feature)
                             (intern feature)
                           feature))))
        (require 'package)
        (unless (and package-archive-contents (null refresh))
          (package-refresh-contents))
        (and (condition-case e
                 (package-install package)
               (error (if noerror nil (error (cadr e)))))
             (require feature filename noerror)))))

Just use (paradox-require 'dash) instead of (require 'dash) and the package will be installed if necessary.

comments powered by Disqus