Skip to content
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

👌 IMPROVE: Add renderer option to amsmath plugin #30

Merged
merged 1 commit into from
Dec 2, 2021
Merged
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
20 changes: 14 additions & 6 deletions mdit_py_plugins/amsmath/__init__.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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 <https://ctan.org/pkg/amsmath>`__ environments:

Expand All @@ -57,13 +58,25 @@ 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",
"amsmath",
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'<div class="math amsmath">\n{content}\n</div>\n'

md.add_render_rule("amsmath", render_amsmath_block)


Expand Down Expand Up @@ -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'<div class="math amsmath">\n{escapeHtml(token.content)}\n</div>\n'