运行 在标准钩子中带参数的函数

Run function with arguments inside of a standard hook

运行 带参数的函数的最佳方法是什么,例如。一个通常是 运行 和 run-hook-with-args,在一个普通的钩子里,例如。 after-save-hook

作为一个简单的例子,我想在这里将some-function添加到after-save-hook,但允许它有一个额外的参数。

(defun some-function (&optional arg)
  (if arg 'do-this 'otherwise-do-this))

;; how to run `some-function' with argument here?
(add-hook 'after-save-hook 'some-function nil 'local)

所以你得到了这样的东西(我更改了函数名称以减少混淆)。

(add-hook 'after-save-hook 'my-function nil 'local)

但是你问的是当 after-save-hook 调用 my-function 时如何安排它向它传递一个参数。

首先,你不能直接这样做,可能很明显的原因是 after-save-hook 是一个普通的钩子,因此得到 运行 的方式不提供任何便利传递参数。

这意味着您必须向挂钩添加一个函数,该函数实际上可以满足您的需求

可以创建一个函数来执行您想要的操作:

(add-hook 'after-save-hook (apply-partially 'my-function ARG) nil 'local)

但是在以后检查和操作钩子时,沿着这些思路的方法真的很麻烦,所以我建议不要做这样的事情。

老实说,最简洁的方法是定义一个命名函数来执行您想要的操作,然后将 that 添加到钩子中。

(defun my-function-do-this ()
  "Do This"
  'do-this)

(add-hook 'after-save-hook 'my-function-do-this nil 'local)