|
9 | 9 |
|
10 | 10 | __all__ = ["math", "math_in_quote", "math_in_list"] |
11 | 11 |
|
12 | | -BLOCK_MATH_PATTERN = r"^ {0,3}\$\$[ \t]*\n(?P<math_text>[\s\S]+?)\n\$\$[ \t]*$" |
13 | | -INLINE_MATH_PATTERN = r"\$(?!\$)(?!\s)(?P<math_text>(?:[^$\\\n]|\\.)+?)\$(?!\d)" |
| 12 | +BLOCK_MATH_PATTERN = ( |
| 13 | + r"^ {0,3}\$\$(?P<math_text_single>[^\n]*?)\$\$[ \t]*(?:\n|$)|" |
| 14 | + r"^ {0,3}\$\$[ \t]*\n(?P<math_text_multi>[\s\S]*?)\n\$\$[ \t]*(?:\n|$)" |
| 15 | +) |
| 16 | +INLINE_MATH_PATTERN = ( |
| 17 | + r"\$\$(?P<display_math_text>(?:[^$\\]|\\.)*?)\$\$|" |
| 18 | + r"\$(?P<backtick_math_marker>`+)(?P<backtick_math_text>[\s\S]*?)(?P=backtick_math_marker)\$|" |
| 19 | + r"\$(?!\$)(?!\s)(?P<math_text>(?:[^$\\\n]|\\.)+?)\$(?!\d)" |
| 20 | +) |
14 | 21 |
|
15 | 22 |
|
16 | 23 | def parse_block_math(block: "BlockParser", m: Match[str], state: "BlockState") -> int: |
17 | | - text = m.group("math_text") |
| 24 | + text = m.group("math_text_single") |
| 25 | + if text is None: |
| 26 | + text = m.group("math_text_multi") |
| 27 | + assert text is not None |
18 | 28 | state.append_token({"type": "block_math", "raw": text}) |
19 | | - return m.end() + 1 |
| 29 | + return m.end() |
20 | 30 |
|
21 | 31 |
|
22 | 32 | def parse_inline_math(inline: "InlineParser", m: Match[str], state: "InlineState") -> int: |
23 | | - text = m.group("math_text") |
| 33 | + display_text = m.group("display_math_text") |
| 34 | + if display_text is not None: |
| 35 | + state.append_token({"type": "block_math", "raw": display_text}) |
| 36 | + return m.end() |
| 37 | + |
| 38 | + text = m.group("backtick_math_text") |
| 39 | + if text is None: |
| 40 | + text = m.group("math_text") |
| 41 | + assert text is not None |
24 | 42 | state.append_token({"type": "inline_math", "raw": text}) |
25 | 43 | return m.end() |
26 | 44 |
|
@@ -50,7 +68,7 @@ def math(md: "Markdown") -> None: |
50 | 68 | :param md: Markdown instance |
51 | 69 | """ |
52 | 70 | md.block.register("block_math", BLOCK_MATH_PATTERN, parse_block_math, before="list") |
53 | | - md.inline.register("inline_math", INLINE_MATH_PATTERN, parse_inline_math, before="link") |
| 71 | + md.inline.register("inline_math", INLINE_MATH_PATTERN, parse_inline_math, before="codespan") |
54 | 72 | if md.renderer and md.renderer.NAME == "html": |
55 | 73 | md.renderer.register("block_math", render_block_math) |
56 | 74 | md.renderer.register("inline_math", render_inline_math) |
|
0 commit comments