How to determine whether a package is installed in elisp?
Why not using "featurep"?
(featurep FEATURE &optional SUBFEATURE)
Return t if FEATURE is present in this Emacs.
(if (featurep 'ecb)
(message "ECB is there!"))
The (require)
will throw an error if it fails. That should really be all you need.
If you want to configure ECB's behavior only when it is available, look primarily into adding stuff to ecb-hook
-- this is the normal way to configure an Emacs package conditionally.
If no hook is available, or you want to roll it by hand for some reason, try something like
(eval-after-load 'ecb '(setq ecb-be-more-like-better-yes-p t))
If you really really want to roll this by hand, you can trap the error from a failed require
like this:
(condition-case nil
(progn
(require 'ecb)
(setq ecb-be-more-like-better-yes-p t) )
(file-error (message "ECB not available; not configuring") ))
Note that the condition-case
will catch any file-error
from inside the progn
so you want to make sure you don't do any other file operations inside. Ultimately you may want to put just the require
inside a condition-case
and use that as the condition for your original if
form, but this is already getting out of hand ...
(if (condition-case nil (require 'ecb) (error nil))
(setq ecb-be-more-like-better-yes-p t)
(message "ECB not available; not configuring") )
tripleee's answer is a handy example of error handling, but unnecessary in this instance.
(when (require 'some-library nil 'noerror)
do-things)
That 'noerror
can be any non-nil value, but of course it's more descriptive this way. I often see :noerror
used as well, but I've no idea if there's any particular advantage to using a keyword argument over a symbol (comments, anyone? I'm quite interested to know).
require is a built-in function in
C source code
.(require FEATURE &optional FILENAME NOERROR)
If feature FEATURE is not loaded, load it from FILENAME.
If FEATURE is not a member of the listfeatures
, then the feature
is not loaded; so load the file FILENAME.
If FILENAME is omitted, the printname of FEATURE is used as the file name,
andload
will try to load this name appended with the suffix.elc
or.el
, in that order. The name without appended suffix will not be used.
Seeget-load-suffixes
for the complete list of suffixes.
If the optional third argument NOERROR is non-nil,
then return nil if the file is not found instead of signaling an error.
Normally the return value is FEATURE.
The normal messages at start and end of loading FILENAME are suppressed.