From 689c6d7f4ec1aeee3d0f9950a21571e04c913786 Mon Sep 17 00:00:00 2001 From: altaf-creator Date: Mon, 6 Jul 2026 11:36:40 +0800 Subject: markdown support done --- markdown_renderer.py | 71 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 markdown_renderer.py (limited to 'markdown_renderer.py') diff --git a/markdown_renderer.py b/markdown_renderer.py new file mode 100644 index 0000000..cf3a05c --- /dev/null +++ b/markdown_renderer.py @@ -0,0 +1,71 @@ +import markdown +import frontmatter +import markdown.treeprocessors +import markdown.extensions + + +class DefaultClassTreeprocessor(markdown.treeprocessors.Treeprocessor): + def run(self, root): + for element in root.iter("a"): + print(element.attrib) + if "class" not in element.attrib: + element.set("class", "link") + elif "button" not in element.attrib["class"]: + element.set("class", element.attrib["class"] + " link") + if "href" in element.attrib and element.attrib["href"] == "": + del element.attrib["href"] + for element in root.iter("img"): + element.set("class", "img") + + +class DefaultClassExtension(markdown.extensions.Extension): + def extendMarkdown(self, md): + md.treeprocessors.register(DefaultClassTreeprocessor(md), "link_class", 2) + + +def strict_identity_slugify(value, separator): + return value + + +def md_to_html(raw_content: str, text_mode: bool = False) -> str: + metadata, content = frontmatter.parse(raw_content) + html_text = markdown.markdown( + content, + output_format="html", + extensions=["attr_list", "fenced_code", "tables", DefaultClassExtension(), "md_in_html", "pymdownx.tilde", "footnotes", "codehilite", "mdx_wikilink_plus", "toc", "pymdownx.mark", "pymdownx.arithmatex"], + extension_configs={ + "toc": { + "slugify": strict_identity_slugify + }, + "pymdownx.arithmatex": { + "generic": True + } + } + ) + + section_class = "" + section_class_only = "" + + if text_mode: + section_class = ' class="text-section"' + section_class_only = ' text-section' + + html_text = html_text.replace("

+-+-+-

", f'
') + html_text = html_text.replace("

+-+-+-", f'

') + html_text = html_text.replace("+-+-+-

", f'
') + html_text = html_text.replace("-+-+-+

", "
") + html_text = html_text.replace("

-+-+-+", "

") + html_text = html_text.replace("

+=+=+=

", f'
') + html_text = html_text.replace("

+=+=+=", f'

') + html_text = html_text.replace("+=+=+=

", f'
') + html_text = html_text.replace("

{{{

", '
') + html_text = html_text.replace("

{{{", '

') + html_text = html_text.replace("{{{

", '
') + html_text = html_text.replace("

}}}

", '
') + html_text = html_text.replace("}}}

", '
') + html_text = html_text.replace("

}}}", '

') + html_text = html_text.replace("

{&{

", '
') + html_text = html_text.replace("

{&{", '

') + html_text = html_text.replace("{&{

", '
') + + return (metadata, html_text) -- cgit v1.2.3