From 26ed77f598fc930ddd77ac555dd61a04c27dd81b Mon Sep 17 00:00:00 2001 From: Ron Kok Date: Sun, 27 Dec 2020 12:34:20 -0800 Subject: [PATCH] docs: Explain how to make macros persist. (#2702) * docs: Explain how make macros persist. * Revise per comments. * Pick up comments. --- docs/api.md | 22 ++++++++++++++++++++++ docs/supported.md | 4 +++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/docs/api.md b/docs/api.md index ff040141..8b15923e 100644 --- a/docs/api.md +++ b/docs/api.md @@ -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 + +KaTeX’s [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. diff --git a/docs/supported.md b/docs/supported.md index c5b296af..2c7e0e45 100644 --- a/docs/supported.md +++ b/docs/supported.md @@ -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. +
+ +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.