如何添加仅在特定模式下运行的钩子? [英] How to add a hook to only run in a particular mode?

查看:16
本文介绍了如何添加仅在特定模式下运行的钩子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下定义

(defun a-test-save-hook()
  "Test of save hook"
  (message "banana")
  )

我通过以下钩子使用

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

这按预期工作.我想做的是将钩子限制为特定模式,在本例中为 org-mode.关于我将如何进行的任何想法?

This works as expected. What I would like to do is to limit the hook to particular mode, in this case org-mode. Any ideas as to how I would go about this?

提前致谢.

推荐答案

如果您查看 add-hook(或 Ch f add-hook RET),你会看到一种可能的解决方案是使钩子局部于您想要的主要模式.这比 vderyagin 的 answer,看起来像这样:

If you take a look at the documentation for add-hook (or C-h f add-hook RET), you'll see that one possible solution is to make the hook local to the major modes you want. This is slightly more involved than vderyagin's answer, and looks like this:

(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仅在当前缓冲区中添加钩子.有了上面的内容,您只会在 org-mode 中添加 a-test-save-hook.

The 'make-it-local is the flag (can be anything that isn't nil) that tells add-hook to add the hook only in the current buffer. With the above, you'll only get the a-test-save-hook added in org-mode.

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

This is nice if you want to use a-test-save-hook in more than one mode.

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.

这篇关于如何添加仅在特定模式下运行的钩子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆