From d43c41ba1555f6a332dabf7a1bd228bc936b78f7 Mon Sep 17 00:00:00 2001 From: Chris Sewell Date: Thu, 2 Dec 2021 07:17:24 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=91=8C=20IMPROVE:=20Add=20renderer=20opti?= =?UTF-8?q?on=20to=20amsmath=20plugin=20(#30)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Syncs with: https://github.com/executablebooks/markdown-it-amsmath/commit/d20e2fc310767ce53aef2277674d290ade1dddc8 --- mdit_py_plugins/amsmath/__init__.py | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/mdit_py_plugins/amsmath/__init__.py b/mdit_py_plugins/amsmath/__init__.py index 4359808..0b367b5 100644 --- a/mdit_py_plugins/amsmath/__init__.py +++ b/mdit_py_plugins/amsmath/__init__.py @@ -1,5 +1,6 @@ """An extension to capture amsmath latex environments.""" import re +from typing import Callable, Optional from markdown_it import MarkdownIt from markdown_it.common.utils import escapeHtml @@ -46,7 +47,7 @@ RE_OPEN = re.compile(r"\\begin\{(" + "|".join(ENVIRONMENTS) + r")([\*]?)\}") -def amsmath_plugin(md: MarkdownIt): +def amsmath_plugin(md: MarkdownIt, *, renderer: Optional[Callable[[str], str]] = None): """Parses TeX math equations, without any surrounding delimiters, only for top-level `amsmath `__ environments: @@ -57,6 +58,8 @@ def amsmath_plugin(md: MarkdownIt): a_2=b_2+c_2-d_2+e_2 \\end{gather*} + :param renderer: Function to render content, by default escapes HTML + """ md.block.ruler.before( "blockquote", @@ -64,6 +67,16 @@ def amsmath_plugin(md: MarkdownIt): amsmath_block, {"alt": ["paragraph", "reference", "blockquote", "list", "footnote_def"]}, ) + + if renderer is None: + _renderer = lambda content: escapeHtml(content) + else: + _renderer = renderer + + def render_amsmath_block(self, tokens, idx, options, env): + content = _renderer(str(tokens[idx].content)) + return f'
\n{content}\n
\n' + md.add_render_rule("amsmath", render_amsmath_block) @@ -111,8 +124,3 @@ def amsmath_block(state: StateBlock, startLine: int, endLine: int, silent: bool) token.map = [startLine, line] return True - - -def render_amsmath_block(self, tokens, idx, options, env): - token = tokens[idx] - return f'
\n{escapeHtml(token.content)}\n
\n'