如何添加钩子只能在特定模式下运行?

Aar*_*lay 26 emacs hook

我有以下defun

(defun a-test-save-hook()
  "Test of save hook"
  (message "banana")
  )
Run Code Online (Sandbox Code Playgroud)

我通过以下钩子使用

(add-hook 'after-save-hook 'a-test-save-hook)
Run Code Online (Sandbox Code Playgroud)

这按预期工作.我想做的是将钩子限制到特定模式,在这种情况下是组织模式.关于我如何做到这一点的任何想法?

提前致谢.

Tre*_*son 45

如果你看一下add-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)))
Run Code Online (Sandbox Code Playgroud)

'make-it-local是标志(可以是任何东西,是不是nil)告诉add-hook仅在当前缓冲区增加了钩.有了上述内容,您只需a-test-save-hook添加org-mode.

如果要a-test-save-hook在多种模式下使用,这很好.

文档add-hook是:

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.
Run Code Online (Sandbox Code Playgroud)

  • @kindahero,`(lambda()...)`无论如何都要评估自己,所以引用并没有什么区别. (2认同)

Vic*_*gin 6

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

(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)
Run Code Online (Sandbox Code Playgroud)