43 lines
1.2 KiB
Python
43 lines
1.2 KiB
Python
"""Handle cleaning and rendering of markdown."""
|
|
# TODO: consider dropping mistune in favour of more popular python-markdown
|
|
from typing import Optional
|
|
|
|
from markupsafe import Markup
|
|
import bleach
|
|
import bleach.sanitizer
|
|
import mistune
|
|
|
|
from .markdown_renderers import TextRenderer, LinkRendererWithRel
|
|
|
|
_markdown: Optional[mistune.Markdown] = None
|
|
_markdown_to_text: Optional[mistune.Markdown] = None
|
|
|
|
|
|
def sanitize(text: str) -> str:
|
|
"""Remove **all** HTML tags from a given text."""
|
|
return bleach.clean(text, tags=[], attributes={}, strip=True)
|
|
|
|
|
|
def render(text: str) -> Markup:
|
|
"""Render given text as markdown."""
|
|
global _markdown
|
|
|
|
if _markdown is None:
|
|
_markdown = mistune.create_markdown(
|
|
escape=True,
|
|
plugins=[mistune.plugins.extra.plugin_url, 'table'],
|
|
renderer=LinkRendererWithRel(escape=True),
|
|
)
|
|
|
|
return Markup(_markdown(text))
|
|
|
|
|
|
def render_as_text(text: str) -> str:
|
|
"""Turn markdown from plain text into even planer text."""
|
|
global _markdown_to_text
|
|
|
|
if _markdown_to_text is None:
|
|
_markdown_to_text = mistune.Markdown(renderer=TextRenderer(), plugins=[])
|
|
|
|
return _markdown_to_text(sanitize(text))
|