28 lines
954 B
Python
28 lines
954 B
Python
from markdown_it import MarkdownIt
|
|
from mdit_py_plugins.dollarmath import dollarmath_plugin
|
|
from mdit_py_plugins.front_matter import front_matter_plugin
|
|
|
|
|
|
class Parser:
|
|
def __init__(self, md_text: str) -> None:
|
|
self.md_text = md_text
|
|
self.md = (
|
|
MarkdownIt("commonmark", {"breaks": True, "html": True})
|
|
.enable("table")
|
|
.use(front_matter_plugin)
|
|
.use(dollarmath_plugin)
|
|
)
|
|
self.tokens = self.md.parse(md_text)
|
|
self.front_matter = self._extract_front_matter()
|
|
|
|
def _extract_front_matter(self) -> dict[str, str]:
|
|
if not self.tokens or self.tokens[0].type != "front_matter":
|
|
return {}
|
|
raw = self.tokens[0].content.strip()
|
|
result = {}
|
|
for line in raw.splitlines():
|
|
if ":" in line:
|
|
key, _, value = line.partition(":")
|
|
result[key.strip()] = value.strip()
|
|
return result
|