math.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. from typing import TYPE_CHECKING, Match
  2. if TYPE_CHECKING:
  3. from ..block_parser import BlockParser
  4. from ..core import BaseRenderer, BlockState, InlineState
  5. from ..inline_parser import InlineParser
  6. from ..markdown import Markdown
  7. __all__ = ["math", "math_in_quote", "math_in_list"]
  8. BLOCK_MATH_PATTERN = r"^ {0,3}\$\$[ \t]*\n(?P<math_text>[\s\S]+?)\n\$\$[ \t]*$"
  9. INLINE_MATH_PATTERN = r"\$(?!\s)(?P<math_text>.+?)(?!\s)\$"
  10. def parse_block_math(block: "BlockParser", m: Match[str], state: "BlockState") -> int:
  11. text = m.group("math_text")
  12. state.append_token({"type": "block_math", "raw": text})
  13. return m.end() + 1
  14. def parse_inline_math(inline: "InlineParser", m: Match[str], state: "InlineState") -> int:
  15. text = m.group("math_text")
  16. state.append_token({"type": "inline_math", "raw": text})
  17. return m.end()
  18. def render_block_math(renderer: "BaseRenderer", text: str) -> str:
  19. return '<div class="math">$$\n' + text + "\n$$</div>\n"
  20. def render_inline_math(renderer: "BaseRenderer", text: str) -> str:
  21. return r'<span class="math">\(' + text + r"\)</span>"
  22. def math(md: "Markdown") -> None:
  23. """A mistune plugin to support math. The syntax is used
  24. by many markdown extensions:
  25. .. code-block:: text
  26. Block math is surrounded by $$:
  27. $$
  28. f(a)=f(b)
  29. $$
  30. Inline math is surrounded by `$`, such as $f(a)=f(b)$
  31. :param md: Markdown instance
  32. """
  33. md.block.register("block_math", BLOCK_MATH_PATTERN, parse_block_math, before="list")
  34. md.inline.register("inline_math", INLINE_MATH_PATTERN, parse_inline_math, before="link")
  35. if md.renderer and md.renderer.NAME == "html":
  36. md.renderer.register("block_math", render_block_math)
  37. md.renderer.register("inline_math", render_inline_math)
  38. def math_in_quote(md: "Markdown") -> None:
  39. """Enable block math plugin in block quote."""
  40. md.block.insert_rule(md.block.block_quote_rules, "block_math", before="list")
  41. def math_in_list(md: "Markdown") -> None:
  42. """Enable block math plugin in list."""
  43. md.block.insert_rule(md.block.list_rules, "block_math", before="list")