仅在 emacs elisp 库存在时才加载它

Load emacs elisp library only if it is present

我有一个标准的 .emacs 文件,我想在多台机器上使用。有些机器我无法加载我所有的 elisp 库。

现在,我在 wc-mode-0.2.el 不存在的机器上遇到此错误:

Cannot open load file: wc-mode-0.2.el

有什么方法可以让 .emacs 文件在此时不出错?通过:

  1. 在尝试加载库之前检查库是否存在。
  2. 捕获错误条件。

loadrequire 都可以在找不到文件时不发出错误信号。

(load FILE &optional NOERROR NOMESSAGE NOSUFFIX MUST-SUFFIX)
(require FEATURE &optional FILENAME NOERROR)

所以你可以这样做:

;; using load
(when (load "myfile.el" t)
       (do-my-thing))
;;using require
(when (require "myfeature" nil t)
       (do-my-thing))

虽然@yorodm 的回答可能更正确(已投票!),但我多年来一直使用的一种形式是:

;; load & configure myfeature if it's available
(cond ((locate-library "myfeature")
       (require 'myfeature)
       (setq myfeature-variable "stuff")
       (do-my-thing))