# 23.1 钩子

钩子(hook)是一个变量，其中可以存储一个或多个函数，这些函数会在特定的时候被调用。Emacs 提供钩子是为了实现定制化。大多数情况下，钩子设置在 init 文件中（参见[Init File](https://devdocs.io/elisp/init-file)），但 Lisp 脚本也可以设置它们。[标准钩子](https://devdocs.io/elisp/standard-hooks)中列出了一系列标准的钩子变量。

Emacs 中的大多数钩子都是*普通钩子 (normal hooks)*。这些钩子中的函数都不需要参数。按照惯例，普通钩子名称以 ' -hook' 结尾。Emacs 尽可能将的将钩子以普通钩子的方式实现，以便用户能使用同一的方式去使用它们。

每个主模式都应该运行一个称为*模式挂钩*的普通挂钩，作为模式初始化的最后一步。通过覆盖预设的缓冲区局部变量，用户可以轻松自定义模式的行为。大多数次要模式也会在初始化的最后一步运行各自的模式钩子。不过也有钩子在其他时候运行。例如，钩子`suspend-hook`在 Emacs 挂起自身之前运行（参见[Suspending Emacs](https://devdocs.io/elisp/suspending-emacs)）。

向钩子(hook)添加钩子函数(hook-function)的推荐方法是调用`add-hook`（参见[设置钩子](https://devdocs.io/elisp/setting-hooks)）。钩子函数可以是任何可以被`funcall`调用的合法函数（请参阅[什么是函数](https://devdocs.io/elisp/what-is-a-function)）。大多数普通钩子变量最初是无效的；`add-hook`知道如何处理这个问题。使用`add-hook`用户可以全局性或缓冲区局部性的添加钩子。

如果钩子变量的名称不以 ' -hook' 结尾，这表明它可能是一个*异常的钩子*。这意味着这个钩子中的钩子函数的调用是需要参数的，或者这些钩子函数会返回一些有用的值。钩子的文档说明了函数是如何被调用的。用户可以使用`add-hook`将函数添加到异常钩子中，但您必须按照钩子的调用约定编写函数。按照惯例，异常钩子名称以 ' -functions'结尾。

如果变量的名称以 ' -function'结尾，那么它的值就只是一个函数，而不是一个函数列表。`add-hook`不能用于修改这样的*单个函数 hook*，用户必须改用`add-function`（请参阅[建议函数](https://devdocs.io/elisp/advising-functions)）。


---

# 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.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.
