Emacs 如何添加一个仅在特定模式下运行的钩子?

Emacs 如何添加一个仅在特定模式下运行的钩子?,emacs,hook,Emacs,Hook,我有以下的理由 (defun a-test-save-hook() "Test of save hook" (message "banana") ) 我通过下面的钩子使用 (add-hook 'after-save-hook 'a-test-save-hook) 这正如预期的那样有效。我想做的是将钩子限制为特定模式,在本例中是org模式。我该怎么做呢 提前感谢。我想最简单的解决方案是在钩子本身中添加主模式检查: (defun a-test-save-hook() "Test

我有以下的理由

(defun a-test-save-hook()
  "Test of save hook"
  (message "banana")
  )
我通过下面的钩子使用

(add-hook 'after-save-hook 'a-test-save-hook)
这正如预期的那样有效。我想做的是将钩子限制为特定模式,在本例中是org模式。我该怎么做呢


提前感谢。

我想最简单的解决方案是在钩子本身中添加主模式检查:

(defun a-test-save-hook()
  "Test of save hook"
  (when (eq major-mode 'org-mode)
    (message "banana")))

(add-hook 'after-save-hook 'a-test-save-hook)

如果您查看(或C-h f add hook RET)的文档,您会发现一个可能的解决方案是使钩子成为您想要的主要模式的本地钩子。这比vderyagin的稍微复杂一些,如下所示:

(add-hook 'org-mode-hook 
          (lambda () 
             (add-hook 'after-save-hook 'a-test-save-hook nil 'make-it-local)))
'make-it-local
是一个标志(可以是非
nil
的任何内容),它告诉
addhook
仅在当前缓冲区中添加钩子。通过以上操作,您只能在组织模式下添加
a-test-save-hook

如果您想在多个模式下使用
a-test-save-hook
,这很好

addhook
的文档如下:

add-hook is a compiled Lisp function in `subr.el'.

(add-hook HOOK FUNCTION &optional APPEND LOCAL)

Add to the value of HOOK the function FUNCTION.
FUNCTION is not added if already present.
FUNCTION is added (if necessary) at the beginning of the hook list
unless the optional argument APPEND is non-nil, in which case
FUNCTION is added at the end.

The optional fourth argument, LOCAL, if non-nil, says to modify
the hook's buffer-local value rather than its default value.
This makes the hook buffer-local if needed, and it makes t a member
of the buffer-local value.  That acts as a flag to run the hook
functions in the default value as well as in the local value.

HOOK should be a symbol, and FUNCTION may be any valid function.  If
HOOK is void, it is first set to nil.  If HOOK's value is a single
function, it is changed to a list of functions.

lambda不是应该被引用吗?@kindahero,
(lambda()…)
的计算结果是自身的,所以引用没有什么区别。谢谢,这是我想要的信息。我们会回到文档中。