11"""An extension to capture amsmath latex environments."""
22import re
3+ from typing import Callable , Optional
34
45from markdown_it import MarkdownIt
56from markdown_it .common .utils import escapeHtml
4647RE_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