docs: Explain how to make macros persist. (#2702)

* docs: Explain how make macros persist.

* Revise per comments.

* Pick up comments.
This commit is contained in:
Ron Kok
2020-12-27 12:34:20 -08:00
committed by GitHub
parent 75a3af9725
commit 26ed77f598
2 changed files with 25 additions and 1 deletions

View File

@@ -41,3 +41,25 @@ hover text. Without this option, invalid LaTeX will cause a
The last argument to `katex.render` and `katex.renderToString` can contain
[a variety of rendering options](options.md).
## Persistent Macros
KaTeXs [macro documentation](supported.html#gdef) tells the author that `\gdef` will create a macro that persists between KaTeX elements. In order to enable that persistence, you must create one shared `macros` object that you pass into every call to `katex.render` or `katex.renderToString`. (Do not create a fresh `macros` object for each call.)
For example, suppose that you have an array `mathElements` of DOM elements that contain math. Then you could write this code:
```js
const macros = {};
for (let element of mathElements) {
katex.render(element.textContent, element, {
throwOnError: false,
macros
};
}
```
Notice that you create the `macros` object outside the loop. If an author uses `\gdef`, KaTeX will insert that macro definition into the `macros` object and since `macros` continues to exist between calls to `katex.render`, `\gdef` macros will persist between `mathElements`.
### Security of Persistent Macros
Persistent macros can change the behavior of KaTeX (e.g. redefining standard commands), so for security, such a setup should be used only for multiple elements of common trust. For example, you might enable persistent macros within a message posted by a single user (by creating a `macros` object for that message), but you probably should not enable persistent macros across multiple messages posted by multiple users.

View File

@@ -332,7 +332,9 @@ Macros can also be defined in the KaTeX [rendering options](options.md).
Macros accept up to nine arguments: #1, #2, etc.
`\gdef`, `\xdef`, `\global\def`, `\global\edef`, `\global\let`, and `\global\futurelet` will persist between math expressions.
<div id="gdef"></div>
Macros defined by `\gdef`, `\xdef`, `\global\def`, `\global\edef`, `\global\let`, and `\global\futurelet` will persist between math expressions. (Exception: macro persistence may be disabled. There are legitimate security reasons for that.)
KaTeX has no `\par`, so all macros are long by default and `\long` will be ignored.