86 lines
2.4 KiB
Python
86 lines
2.4 KiB
Python
"""Custom markdown renderers."""
|
|
from mistune import escape_html
|
|
from mistune.renderers import BaseRenderer
|
|
from mistune.renderers import HTMLRenderer
|
|
|
|
|
|
class TextRenderer(BaseRenderer): # noqa: D102
|
|
"""Turn markdown from plain text into even planer text."""
|
|
|
|
NAME = 'text'
|
|
|
|
def image(self, src, alt="", title=None):
|
|
return ''
|
|
|
|
def text(self, text): # noqa: D102
|
|
return text
|
|
|
|
def heading(self, text, level): # noqa: D102
|
|
return text.strip() + '\n'
|
|
|
|
def list(self, text, ordered, level, start=None): # noqa: D102
|
|
return text
|
|
|
|
def list_item(self, text, level): # noqa: D102
|
|
return ' ' * (level - 1) + '- ' + text + '\n'
|
|
|
|
def block_text(self, text): # noqa: D102
|
|
return text
|
|
|
|
def thematic_break(self): # noqa: D102
|
|
return '\n---\n\n'
|
|
|
|
def paragraph(self, text): # noqa: D102
|
|
return text.strip('\n') + '\n\n'
|
|
|
|
def link(self, link, text=None, title=None): # noqa: D102
|
|
return link
|
|
|
|
def block_quote(self, text): # noqa: D102
|
|
return '\n'.join(['> ' + line for line in text.strip().splitlines()]) + '\n'
|
|
|
|
def newline(self): # noqa: D102
|
|
return '\n'
|
|
|
|
def block_code(self, code, info=None): # noqa: D102
|
|
return '\n' + code.strip('\n') + "\n\n"
|
|
|
|
def block_html(self, value, **kwargs): # noqa: D102
|
|
from common.markdown import sanitize
|
|
|
|
return sanitize(value)
|
|
|
|
def codespan(self, text): # noqa: D102
|
|
return '`{text}`'.format(text=text)
|
|
|
|
def strong(self, text): # noqa: D102
|
|
return '**' + text + '**'
|
|
|
|
def linebreak(self): # noqa: D102
|
|
return '\n'
|
|
|
|
def table(self, text): # noqa: D102
|
|
# FIXME: this rule isn't used, figure out how to strip tables
|
|
return ''
|
|
|
|
def emphasis(self, text): # noqa: D102
|
|
return text
|
|
|
|
def finalize(self, data):
|
|
return ''.join(data)
|
|
|
|
|
|
class LinkRendererWithRel(HTMLRenderer):
|
|
"""Rendering class that sets the `rel` and `target` attributes on all the links."""
|
|
|
|
rel_value = "nofollow noopener noreferrer external"
|
|
|
|
def link(self, link, text=None, title=None) -> str:
|
|
if text is None:
|
|
text = link
|
|
|
|
s = f'<a rel="{self.rel_value}" target="_blank" href="{self._safe_url(link)}"'
|
|
if title:
|
|
s += ' title="' + escape_html(title) + '"'
|
|
return s + '>' + (text or link) + '</a>'
|