1from __future__ import annotations
2
3from collections.abc import Callable, Sequence
4import re
5from re import Match
6from typing import TYPE_CHECKING, Any, TypedDict
7
8from markdown_it import MarkdownIt
9from markdown_it.common.utils import charCodeAt, escapeHtml
10
11if TYPE_CHECKING:
12 from markdown_it.renderer import RendererProtocol
13 from markdown_it.rules_block import StateBlock
14 from markdown_it.rules_inline import StateInline
15 from markdown_it.token import Token
16 from markdown_it.utils import EnvType, OptionsDict
17
18
19def texmath_plugin(
20 md: MarkdownIt, delimiters: str = "dollars", macros: Any = None
21) -> None:
22 """Plugin ported from
23 `markdown-it-texmath <https://github.com/goessner/markdown-it-texmath>`__.
24
25 It parses TeX math equations set inside opening and closing delimiters:
26
27 .. code-block:: md
28
29 $\\alpha = \\frac{1}{2}$
30
31 :param delimiters: one of: brackets, dollars, gitlab, julia, kramdown
32
33 """
34 macros = macros or {}
35
36 if delimiters in rules:
37 for rule_inline in rules[delimiters]["inline"]:
38 md.inline.ruler.before(
39 "escape", rule_inline["name"], make_inline_func(rule_inline)
40 )
41
42 def render_math_inline(
43 self: RendererProtocol,
44 tokens: Sequence[Token],
45 idx: int,
46 options: OptionsDict,
47 env: EnvType,
48 ) -> str:
49 return rule_inline["tmpl"].format( # noqa: B023
50 render(tokens[idx].content, False, macros)
51 )
52
53 md.add_render_rule(rule_inline["name"], render_math_inline)
54
55 for rule_block in rules[delimiters]["block"]:
56 md.block.ruler.before(
57 "fence", rule_block["name"], make_block_func(rule_block)
58 )
59
60 def render_math_block(
61 self: RendererProtocol,
62 tokens: Sequence[Token],
63 idx: int,
64 options: OptionsDict,
65 env: EnvType,
66 ) -> str:
67 return rule_block["tmpl"].format( # noqa: B023
68 render(tokens[idx].content, True, macros),
69 escapeHtml(tokens[idx].info),
70 )
71
72 md.add_render_rule(rule_block["name"], render_math_block)
73
74
75class _RuleDictReqType(TypedDict):
76 name: str
77 rex: re.Pattern[str]
78 tmpl: str
79 tag: str
80
81
82class RuleDictType(_RuleDictReqType, total=False):
83 # Note in Python 3.10+ could use Req annotation
84 pre: Any
85 post: Any
86
87
88def applyRule(
89 rule: RuleDictType, string: str, begin: int, inBlockquote: bool
90) -> Match[str] | None:
91 if not (
92 string.startswith(rule["tag"], begin)
93 and (rule["pre"](string, begin) if "pre" in rule else True)
94 ):
95 return None
96
97 match = rule["rex"].match(string[begin:])
98
99 if not match or match.start() != 0:
100 return None
101
102 lastIndex = match.end() + begin - 1
103 if "post" in rule and not (
104 rule["post"](string, lastIndex) # valid post-condition
105 # remove evil blockquote bug (https:#github.com/goessner/mdmath/issues/50)
106 and (not inBlockquote or "\n" not in match.group(1))
107 ):
108 return None
109 return match
110
111
112def make_inline_func(rule: RuleDictType) -> Callable[[StateInline, bool], bool]:
113 def _func(state: StateInline, silent: bool) -> bool:
114 res = applyRule(rule, state.src, state.pos, False)
115 if res:
116 if not silent:
117 token = state.push(rule["name"], "math", 0)
118 token.content = res[1] # group 1 from regex ..
119 token.markup = rule["tag"]
120
121 state.pos += res.end()
122
123 return bool(res)
124
125 return _func
126
127
128def make_block_func(rule: RuleDictType) -> Callable[[StateBlock, int, int, bool], bool]:
129 def _func(state: StateBlock, begLine: int, endLine: int, silent: bool) -> bool:
130 begin = state.bMarks[begLine] + state.tShift[begLine]
131 res = applyRule(rule, state.src, begin, state.parentType == "blockquote")
132 if not res:
133 return False
134
135 # find the line holding the end of the match, within this block only
136 endpos = begin + res.end() - 1
137 line = begLine
138 while line < endLine and endpos > state.eMarks[line]:
139 line += 1
140 if line >= endLine or endpos < state.bMarks[line]:
141 # the closing delimiter lies outside the current block,
142 # e.g. math opened inside a blockquote and closed after it
143 return False
144
145 if not silent:
146 token = state.push(rule["name"], "math", 0)
147 token.block = True
148 token.content = res[1]
149 token.info = res[len(res.groups())]
150 token.markup = rule["tag"]
151
152 state.line = line + 1
153 return True
154
155 return _func
156
157
158def dollar_pre(src: str, beg: int) -> bool:
159 prv = charCodeAt(src[beg - 1], 0) if beg > 0 else False
160 return (
161 (not prv) or (prv != 0x5C and (prv < 0x30 or prv > 0x39)) # no backslash,
162 ) # no decimal digit .. before opening '$'
163
164
165def dollar_post(src: str, end: int) -> bool:
166 try:
167 nxt = src[end + 1] and charCodeAt(src[end + 1], 0)
168 except IndexError:
169 return True
170 return (
171 (not nxt) or (nxt < 0x30) or (nxt > 0x39)
172 ) # no decimal digit .. after closing '$'
173
174
175def render(tex: str, displayMode: bool, macros: Any) -> str:
176 return escapeHtml(tex)
177 # TODO better HTML renderer port for math
178 # try:
179 # res = katex.renderToString(tex,{throwOnError:False,displayMode,macros})
180 # except:
181 # res = tex+": "+err.message.replace("<","<")
182 # return res
183
184
185# def use(katex): # math renderer used ...
186# texmath.katex = katex; # ... katex solely at current ...
187# return texmath;
188# }
189
190
191# All regexes areg global (g) and sticky (y), see:
192# https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/sticky
193
194
195# The ```math block patterns capture what markdown-it-texmath's r"\s+?([^`]+?)\s+?`{3}"
196# captures, but the body must start after one whitespace character and end on a
197# non-whitespace one, so a long whitespace run with no closing fence is matched in
198# linear time (#143); the |\s branch is the single character that pattern captures
199# from a body that is only whitespace.
200rules: dict[str, dict[str, list[RuleDictType]]] = {
201 "brackets": {
202 "inline": [
203 {
204 "name": "math_inline",
205 "rex": re.compile(r"^\\\((.+?)\\\)", re.DOTALL),
206 "tmpl": "<eq>{0}</eq>",
207 "tag": "\\(",
208 }
209 ],
210 "block": [
211 {
212 "name": "math_block_eqno",
213 "rex": re.compile(
214 r"^\\\[(((?!\\\]|\\\[)[\s\S])+?)\\\]\s*?\(([^)$\r\n]+?)\)",
215 re.MULTILINE,
216 ),
217 "tmpl": '<section class="eqno"><eqn>{0}</eqn><span>({1})</span></section>',
218 "tag": "\\[",
219 },
220 {
221 "name": "math_block",
222 "rex": re.compile(r"^\\\[([\s\S]+?)\\\]", re.MULTILINE),
223 "tmpl": "<section>\n<eqn>{0}</eqn>\n</section>\n",
224 "tag": "\\[",
225 },
226 ],
227 },
228 "gitlab": {
229 "inline": [
230 {
231 "name": "math_inline",
232 "rex": re.compile(r"^\$`(.+?)`\$"),
233 "tmpl": "<eq>{0}</eq>",
234 "tag": "$`",
235 }
236 ],
237 "block": [
238 {
239 "name": "math_block_eqno",
240 "rex": re.compile(
241 r"^`{3}math\s(\s*[^`\s](?:[^`]*[^`\s])?|\s)\s+`{3}\s*?\(([^)$\r\n]+?)\)",
242 re.MULTILINE,
243 ),
244 "tmpl": '<section class="eqno">\n<eqn>{0}</eqn><span>({1})</span>\n</section>\n',
245 "tag": "```math",
246 },
247 {
248 "name": "math_block",
249 "rex": re.compile(
250 r"^`{3}math\s(\s*[^`\s](?:[^`]*[^`\s])?|\s)\s+`{3}", re.MULTILINE
251 ),
252 "tmpl": "<section>\n<eqn>{0}</eqn>\n</section>\n",
253 "tag": "```math",
254 },
255 ],
256 },
257 "julia": {
258 "inline": [
259 {
260 "name": "math_inline",
261 "rex": re.compile(r"^`{2}([^`]+?)`{2}"),
262 "tmpl": "<eq>{0}</eq>",
263 "tag": "``",
264 },
265 {
266 "name": "math_inline",
267 "rex": re.compile(r"^\$(\S[^$\r\n]*?[^\s\\]{1}?)\$"),
268 "tmpl": "<eq>{0}</eq>",
269 "tag": "$",
270 "pre": dollar_pre,
271 "post": dollar_post,
272 },
273 {
274 "name": "math_single",
275 "rex": re.compile(r"^\$([^$\s\\]{1}?)\$"),
276 "tmpl": "<eq>{0}</eq>",
277 "tag": "$",
278 "pre": dollar_pre,
279 "post": dollar_post,
280 },
281 ],
282 "block": [
283 {
284 "name": "math_block_eqno",
285 "rex": re.compile(
286 r"^`{3}math\s(\s*[^`\s](?:[^`]*[^`\s])?|\s)\s+`{3}\s*?\(([^)$\r\n]+?)\)",
287 re.MULTILINE,
288 ),
289 "tmpl": '<section class="eqno"><eqn>{0}</eqn><span>({1})</span></section>',
290 "tag": "```math",
291 },
292 {
293 "name": "math_block",
294 "rex": re.compile(
295 r"^`{3}math\s(\s*[^`\s](?:[^`]*[^`\s])?|\s)\s+`{3}", re.MULTILINE
296 ),
297 "tmpl": "<section><eqn>{0}</eqn></section>",
298 "tag": "```math",
299 },
300 ],
301 },
302 "kramdown": {
303 "inline": [
304 {
305 "name": "math_inline",
306 "rex": re.compile(r"^\${2}([^$\r\n]*?)\${2}"),
307 "tmpl": "<eq>{0}</eq>",
308 "tag": "$$",
309 }
310 ],
311 "block": [
312 {
313 "name": "math_block_eqno",
314 "rex": re.compile(
315 r"^\${2}([^$]*?)\${2}\s*?\(([^)$\r\n]+?)\)", re.MULTILINE
316 ),
317 "tmpl": '<section class="eqno"><eqn>{0}</eqn><span>({1})</span></section>',
318 "tag": "$$",
319 },
320 {
321 "name": "math_block",
322 "rex": re.compile(r"^\${2}([^$]*?)\${2}", re.MULTILINE),
323 "tmpl": "<section><eqn>{0}</eqn></section>",
324 "tag": "$$",
325 },
326 ],
327 },
328 "dollars": {
329 "inline": [
330 {
331 "name": "math_inline",
332 "rex": re.compile(r"^\$(\S[^$]*?[^\s\\]{1}?)\$"),
333 "tmpl": "<eq>{0}</eq>",
334 "tag": "$",
335 "pre": dollar_pre,
336 "post": dollar_post,
337 },
338 {
339 "name": "math_single",
340 "rex": re.compile(r"^\$([^$\s\\]{1}?)\$"),
341 "tmpl": "<eq>{0}</eq>",
342 "tag": "$",
343 "pre": dollar_pre,
344 "post": dollar_post,
345 },
346 ],
347 "block": [
348 {
349 "name": "math_block_eqno",
350 "rex": re.compile(
351 r"^\${2}([^$]*?)\${2}\s*?\(([^)$\r\n]+?)\)", re.MULTILINE
352 ),
353 "tmpl": '<section class="eqno">\n<eqn>{0}</eqn><span>({1})</span>\n</section>\n',
354 "tag": "$$",
355 },
356 {
357 "name": "math_block",
358 "rex": re.compile(r"^\${2}([^$]*?)\${2}", re.MULTILINE),
359 "tmpl": "<section>\n<eqn>{0}</eqn>\n</section>\n",
360 "tag": "$$",
361 },
362 ],
363 },
364}