Skip to content

Commit d43c41b

Browse files
authored
👌 IMPROVE: Add renderer option to amsmath plugin (#30)
Syncs with: executablebooks/markdown-it-amsmath@d20e2fc
1 parent ff1f230 commit d43c41b

1 file changed

Lines changed: 14 additions & 6 deletions

File tree

‎mdit_py_plugins/amsmath/__init__.py‎

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
"""An extension to capture amsmath latex environments."""
22
import re
3+
from typing import Callable, Optional
34

45
from markdown_it import MarkdownIt
56
from markdown_it.common.utils import escapeHtml
@@ -46,7 +47,7 @@
4647
RE_OPEN = re.compile(r"\\begin\{(" + "|".join(ENVIRONMENTS) + r")([\*]?)\}")
4748

4849

49-
def amsmath_plugin(md: MarkdownIt):
50+
def amsmath_plugin(md: MarkdownIt, *, renderer: Optional[Callable[[str], str]] = None):
5051
"""Parses TeX math equations, without any surrounding delimiters,
5152
only for top-level `amsmath <https://ctan.org/pkg/amsmath>`__ environments:
5253
@@ -57,13 +58,25 @@ def amsmath_plugin(md: MarkdownIt):
5758
a_2=b_2+c_2-d_2+e_2
5859
\\end{gather*}
5960
61+
:param renderer: Function to render content, by default escapes HTML
62+
6063
"""
6164
md.block.ruler.before(
6265
"blockquote",
6366
"amsmath",
6467
amsmath_block,
6568
{"alt": ["paragraph", "reference", "blockquote", "list", "footnote_def"]},
6669
)
70+
71+
if renderer is None:
72+
_renderer = lambda content: escapeHtml(content)
73+
else:
74+
_renderer = renderer
75+
76+
def render_amsmath_block(self, tokens, idx, options, env):
77+
content = _renderer(str(tokens[idx].content))
78+
return f'<div class="math amsmath">\n{content}\n</div>\n'
79+
6780
md.add_render_rule("amsmath", render_amsmath_block)
6881

6982

@@ -111,8 +124,3 @@ def amsmath_block(state: StateBlock, startLine: int, endLine: int, silent: bool)
111124
token.map = [startLine, line]
112125

113126
return True
114-
115-
116-
def render_amsmath_block(self, tokens, idx, options, env):
117-
token = tokens[idx]
118-
return f'<div class="math amsmath">\n{escapeHtml(token.content)}\n</div>\n'

0 commit comments

Comments
 (0)