在Lisp中,使用require时避免“无法打开加载文件”

时间:2010-05-12 03:52:58

标签: emacs lisp elisp dot-emacs

我正在开发一个自定义的.emacs文件,我可以在几台不同的计算机上使用它。我希望能够加载一个模式,如果它存在于系统上。如果它不存在,我希望Emacs停止显示错误:File error: Cannot open load file, X

例如:

(require 'darkroom-mode)

结果:

File error: Cannot open load file, darkroom-mode

我正在使用file-exists-p来测试是否存在某些其他文件,但对于此测试,我认为我需要搜索我的加载路径。我是Lisp的新手,所以这让我很难过。

1 个答案:

答案 0 :(得分:26)

如果您只想让require发出错误,可以执行以下操作:

; third arg non-nil means to not signal an error if file not found
; a symbol provides documentation at the invocation (and is non-nil)
(require 'darkroom-mode nil 'noerror) 

从文档( C-h f require RET ):

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 list `features', 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,
and `load' 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.
If the optional third argument noerror is non-nil,
then return nil if the file is not found instead of signaling an error.