fixed stuff and improved the rendering engine by making inline math available using $$ and for ml $$\ncontent\n$$

This commit is contained in:
2025-10-10 17:25:31 +02:00
parent a74d482d7a
commit 3494298330
5 changed files with 205 additions and 117 deletions

View File

@@ -1,29 +1,41 @@
# latex_extension.py
import marko
import marko.block
import marko.inline
from marko.md_renderer import MarkdownRenderer
import re
from log.Logger import Logger
logger = Logger()
class BlockFormula(marko.block.BlockElement):
pattern = re.compile(r"\$\$ *\n([\s\S]+?)^\$\$ *$", re.MULTILINE)
pattern = re.compile(r"^\$\$\s*\n?([\s\S]+?)\n?\$\$\s*$", re.MULTILINE)
def __init__(self, match):
logger.log_debug("Did shit at __init__ for blockformula")
self.children = [marko.inline.RawText(match.group(1))]
self.children = [marko.inline.RawText(match.group(1).strip())]
@classmethod
def match(cls, source):
return source.expect_re(cls.pattern)
@classmethod
def parse(cls, source):
logger.log_debug("Did some shit with Latex")
match = source.match
source.consume()
return match
class InlineFormula(marko.inline.InlineElement):
pattern = re.compile(r"\$(?!\$)([^\$]+?)\$")
parse_children = False # Math content is raw text
def __init__(self, match):
self.children = [marko.inline.RawText(match.group(1).strip())]
@classmethod
def match(cls, source):
return source.expect_re(cls.pattern)
class Paragraph(marko.block.Paragraph):
override = True
@classmethod
def break_paragraph(cls, source, lazy=False):
if BlockFormula.match(source):
@@ -32,11 +44,16 @@ class Paragraph(marko.block.Paragraph):
class Renderer:
def render_block_formula(self, element):
# Render as HTML with MathJax-compatible format
return '\n<div class="math-block">$$\n' + self.render_children(element) + '$$</div>\n'
# MathJax compatible block math
logger.log_debug(f"render_block_formula@LaTeXRenderer.py returned => {element}")
return f'\n<div class="math-block">$$\n{self.render_children(element)}\n$$</div>\n'
def render_inline_formula(self, element):
# MathJax compatible inline math
logger.log_debug(f"render_inline_formula@LaTeXRenderer.py returned => {element}")
return f'\\({self.render_children(element)}\\)'
class LaTeXExtension:
logger.log_debug("Did shit at __init__ for latexextension")
elements = [BlockFormula, Paragraph]
elements = [BlockFormula, InlineFormula, Paragraph]
parser_mixins = []
renderer_mixins = [Renderer]
renderer_mixins = [Renderer]