1
0
Fork 0
mirror of https://github.com/Findus23/RPGnotes.git synced 2024-09-19 15:43:45 +02:00
RPGnotes/utils/markdown.py

57 lines
1.2 KiB
Python
Raw Normal View History

import re
2022-06-19 16:03:59 +02:00
from html.parser import HTMLParser
2021-08-22 20:10:29 +02:00
import bleach
import markdown
from bleach_allowlist import markdown_tags, markdown_attrs
2021-12-09 15:07:22 +01:00
custom_allowed_tags = ["del", "ins"]
2021-08-22 20:10:29 +02:00
2022-07-03 00:14:51 +02:00
def md_to_html(md: str, replacements=None) -> str:
md = autolink(md, replacements=replacements)
2021-08-22 20:10:29 +02:00
html = markdown.markdown(
md,
output_format="html",
extensions=[
"nl2br",
]
)
html = bleach.clean(
html,
2021-12-09 15:07:22 +01:00
tags=markdown_tags + custom_allowed_tags,
2021-08-22 20:10:29 +02:00
attributes=markdown_attrs
)
return html
2021-09-26 19:02:25 +02:00
2022-07-03 00:14:51 +02:00
def autolink(md: str, replacements=None) -> str:
2022-07-05 18:37:21 +02:00
if replacements is None:
2022-07-03 00:14:51 +02:00
from utils.urls import name2url
replacements = name2url()
links = {}
i = 0
2022-07-03 00:14:51 +02:00
for name, url in replacements.items():
regex = r"\bWORD\b".replace("WORD", name)
placeholder = f"SOME{i}LINK"
md = re.sub(regex, placeholder, md)
links[placeholder] = f"[{name}]({url})"
i += 1
for placeholder, value in links.items():
md = md.replace(placeholder, value)
2021-09-26 19:02:25 +02:00
return md
2022-06-19 16:03:59 +02:00
class HTMLFilter(HTMLParser):
text = ""
def handle_data(self, data):
self.text += data
def html_to_text(html: str) -> str:
f = HTMLFilter()
f.feed(html)
return f.text