如何添加一个挂钩以仅在特定模式下运行?

| 我有以下defun
(defun a-test-save-hook()
  \"Test of save hook\"
  (message \"banana\")
  )
我通过以下钩子使用
(add-hook \'after-save-hook \'a-test-save-hook)
这按预期工作。我想做的是将钩子限制为特定模式,在这种情况下为org-mode。关于我将如何处理的任何想法? 提前致谢。     
已邀请:
如果您看一下
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)))
\'make-it-local
是标志(可以是anything5ѭ以外的任何东西),它告诉
add-hook
仅将钩子添加到当前缓冲区中。使用上述方法,您只会在
org-mode
中添加
a-test-save-hook
。 如果您想在多种模式下使用
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.
    
我想,最简单的解决方案是在钩子本身中添加主模式检查:
(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)
    

要回复问题请先登录注册