# 23.1.2 设置钩子

这是一个示例，它向模式挂钩添加了一个函数，以在 Lisp 交互模式下打开自动填充模式：

```
(add-hook 'lisp-interaction-mode-hook 'auto-fill-mode)
```

钩子变量的值应该是一个函数列表。您可以使用普通的 Lisp 工具操作该列表，但通常情况下，使用下面定义的函数`add-hook和` `remove-hook`。这两个函数会小心处理一些不寻常的情况，避免出现问题。

用户可以将lambda 函数放入钩子中，但 Emacs 并不建议这样做，因为这很容易引起混淆。如果用户向一个钩子添加了两个功能上等价，但编写上略有不同，那么用户会在挂钩上获得两个等效但不同的函数。如果用户随后删除其中一个，另一个仍将保留在其上。

Function: add-hook hook function \&option depth loacl

此函数手动将 function 加入 钩子hook中。用户可以将它用于异常钩子以及正常钩子。function可以是任何 Lisp 函数，它可以接受适当数量的参数。例如，

```
（add-hook 'text-mode-hook 'my-text-hook-function）
```

将函数`my-text-hook-function`添加到名为`text-mode-hook`的钩子中。

如果钩子中已经存在函数（使用equal比较 ），则不会再次添加它。

如果函数的`permanent-local-hook`属性的值为 非nil，则`kill-all-local-variables`（或更改主要模式）不会将这个函数从钩子变量中删除。

对于普通的钩子，钩子函数的设计原则应该使它们的执行顺序无关紧要。任何对顺序的依赖都是自找麻烦。但是，顺序预料中的：通常，依次运行钩子中靠前的函数（除非再次`add-hook`调用）。

在某些情况下，控制钩子上函数的相对位置很重要。这时可选参数depth允许您指示函数应在列表中的哪个位置插入。depth 应当是一个介于 -100 和 100 之间的数字，其值越大，函数就越靠近列表的末尾。depth的默认值为0，为了向后兼容，当depth是一个非零符号时，它会被被解释为90。更进一步，如果depth 是一个严格大于0的数，那么这个函数会被放在同等depth 函数之后，而不是之前。此外，永远不要使用 100（或 -100）的depth，因为我们无法确定在那个函数位置之前（或之后）不需要其他函数。

`add-hook`可以处理hook为void或其值为单个函数的情况，它会将其值重设或更改为函数列表。

如果参数local为 non- `nil`，则表示将函数添加到缓冲区本地钩子列表而不是全局钩子列表。这使挂钩缓冲区本地化并添加`t`到缓冲区本地值。后者充当在默认值和本地值中运行钩子函数的标志。

Function: remove-hook hook function \&option local

此函数从钩子变量hook 中删除函数function。它使用`equal`比较函数，因此这个函数同时也适用于 符号 和 lambda 表达式。

如果local值为 non- `nil`，则表示从缓冲区本地钩子列表中删除函数而不是全局钩子列表。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://emacs-lisp.ivory.cafe/23.1-gou-zi/untitled-1.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
