我有以下defun
(defun a-test-save-hook()
"Test of save hook"
(message "banana")
)
我通过以下钩子使用
(add-hook 'after-save-hook 'a-test-save-hook)
这可以按预期工作。我想做的是将钩子限制到特定模式,在这种情况下是组织模式。关于我将如何处理的任何想法?
提前致谢。
答案 0 :(得分:43)
如果您查看add-hook
(或 Ch f add-hook RET )的文档,您会看到一个可能的解决方案是将钩子置于本地你想要的主要模式。这比vderyagin的answer稍微复杂一些,看起来像这样:
(add-hook 'org-mode-hook
(lambda ()
(add-hook 'after-save-hook 'a-test-save-hook nil 'make-it-local)))
'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.
答案 1 :(得分: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)