Skip to content

Add support for persistent macros between renders #55

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,13 @@ const str = "Euler\'s identity $e^{i\\pi}+1=0$ is a beautiful formula in $\\RR^2

md.render(str);
```
If you want to persist macros between multiple renders, you can pass `macros` to `render()`'s second argument:
```js
const macros = {};
md.render('$$\\gdef\\RR{\\mathbb{R}}$$', { macros });
console.debug(macros); // { '\\RR': '\\mathbb{R}' }
md.render('$$\\RR^2$$', { macros }); // $$\\mathbb{R}^2$$
```

## Use in Browser
```html
Expand Down
21 changes: 18 additions & 3 deletions texmath.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,28 @@ function texmath(md, options) {
for (const rule of delimiters.inline) {
if (!!outerSpace && 'outerSpace' in rule) rule.outerSpace = true;
md.inline.ruler.before('escape', rule.name, texmath.inline(rule)); // ! important
md.renderer.rules[rule.name] = (tokens, idx) => rule.tmpl.replace(/\$1/,texmath.render(tokens[idx].content,!!rule.displayMode,katexOptions));
md.renderer.rules[rule.name] = (tokens, idx, _opts, env) => {
const options = {
...katexOptions,
macros: env.macros || katexOptions.macros,
};
return rule.tmpl.replace(
/\$1/,
texmath.render(tokens[idx].content, !!rule.displayMode, options)
);
};
}
// inject block rules to markdown-it
for (const rule of delimiters.block) {
md.block.ruler.before('fence', rule.name, texmath.block(rule)); // ! important for ```math delimiters
md.renderer.rules[rule.name] = (tokens, idx) => rule.tmpl.replace(/\$2/,escapeHTML(tokens[idx].info)) // equation number .. ?
.replace(/\$1/,texmath.render(tokens[idx].content,true,katexOptions));
md.renderer.rules[rule.name] = (tokens, idx, _opts, env) => {
const options = {
...katexOptions,
macros: env.macros || katexOptions.macros,
};
return rule.tmpl.replace(/\$2/, escapeHTML(tokens[idx].info)) // equation number .. ?
.replace(/\$1/, texmath.render(tokens[idx].content, true, options));
};
}
}

Expand Down