diff --git a/renderer/fifty_ohm_html_renderer.py b/renderer/fifty_ohm_html_renderer.py index 4132691..b382db6 100644 --- a/renderer/fifty_ohm_html_renderer.py +++ b/renderer/fifty_ohm_html_renderer.py @@ -3,6 +3,7 @@ from mistletoe import Document, HtmlRenderer from .comment import BlockComment from .dash import Dash +from .formula import Formula from .halfwidth_spaces import HalfwidthSpaces from .include import Include from .morse import Morse @@ -62,6 +63,7 @@ class FiftyOhmHtmlRenderer(HtmlRenderer): TableBody, Qso, Include, + Formula, *extras, **kwargs, ) @@ -324,3 +326,6 @@ class FiftyOhmHtmlRenderer(HtmlRenderer): def render_include(self, token): return self.include_handler(token.ident) + + def render_formula(self, token): + return f"\n$${token.formula}$$\n" diff --git a/renderer/formula.py b/renderer/formula.py new file mode 100644 index 0000000..ab210be --- /dev/null +++ b/renderer/formula.py @@ -0,0 +1,27 @@ +import re + +from mistletoe.block_token import BlockToken + + +class Formula(BlockToken): + r""" + Block token ("$ a \cdot b $"). + Transfroms a line that contains only a formula enclosed in dollar signs into a Formula token. + """ + + @staticmethod + def start(line): + return re.match(r"^\s*\$[^$]+\$\s*$", line) + + @classmethod + def check_interrupts_paragraph(cls, lines): + return cls.start(lines.peek()) + + @classmethod + def read(cls, lines): + line = next(lines) # Consume the line with the formula + formula = re.match(r"^\s*\$([^$]+)\$\s*$", line).group(1) + return formula + + def __init__(self, match): + self.formula = match diff --git a/test/test_formula.py b/test/test_formula.py new file mode 100644 index 0000000..afa85a6 --- /dev/null +++ b/test/test_formula.py @@ -0,0 +1,19 @@ +import pytest +from mistletoe import Document + +from renderer.fifty_ohm_html_renderer import FiftyOhmHtmlRenderer + + +@pytest.mark.html +def test_formula_html(): + assertions = { + r"$a \cdot b$": "\n" + r"$$a \cdot b$$" + "\n\n", + r" $a \cdot b$ ": "\n" + r"$$a \cdot b$$" + "\n\n", + r"$ a \cdot b $": "\n" + r"$$ a \cdot b $$" + "\n\n", + r"$a \cdot b$" + "\n" + r"$a \cdot b$": "\n" + r"$$a \cdot b$$" + "\n\n\n" + r"$$a \cdot b$$" + "\n\n", + r"Lorem Ipsum" + "\n" + r"$a \cdot b$": "
Lorem Ipsum
\n\n" + r"$$a \cdot b$$" + "\n\n", + } + + with FiftyOhmHtmlRenderer() as renderer: + for assertion in assertions: + assert renderer.render(Document(assertion)) == assertions[assertion]