243 lines
8.1 KiB
Python
243 lines
8.1 KiB
Python
import re
|
|
from functools import lru_cache
|
|
|
|
|
|
class MarkdownParser:
|
|
def __init__(self):
|
|
self._placeholders = {}
|
|
|
|
def render(self, text):
|
|
if not text:
|
|
return ''
|
|
text = text.replace('\r\n', '\n').replace('\r', '\n')
|
|
text = text.replace('\\n', '\n')
|
|
self._placeholders = {}
|
|
text = self._protect_code_blocks(text)
|
|
text = self._render_block_elements(text)
|
|
text = self._restore_code_blocks(text)
|
|
return text
|
|
|
|
def _protect_code_blocks(self, text):
|
|
lines = text.split('\n')
|
|
result = []
|
|
i = 0
|
|
in_code = False
|
|
code_buffer = []
|
|
code_lang = ''
|
|
idx = 0
|
|
while i < len(lines):
|
|
line = lines[i]
|
|
if line.strip().startswith('```'):
|
|
if in_code:
|
|
lang_attr = ' class="lang-{}"'.format(code_lang) if code_lang else ''
|
|
code_content = self._escape('\n'.join(code_buffer))
|
|
html = '<pre><code{}>\n{}\n</code></pre>'.format(lang_attr, code_content)
|
|
key = '%%%CODE_{}%%%'.format(idx)
|
|
self._placeholders[key] = html
|
|
result.append(key)
|
|
code_buffer = []
|
|
code_lang = ''
|
|
in_code = False
|
|
idx += 1
|
|
else:
|
|
in_code = True
|
|
code_lang = line.strip()[3:].strip()
|
|
elif in_code:
|
|
code_buffer.append(line)
|
|
else:
|
|
result.append(line)
|
|
i += 1
|
|
if in_code:
|
|
lang_attr = ' class="lang-{}"'.format(code_lang) if code_lang else ''
|
|
code_content = self._escape('\n'.join(code_buffer))
|
|
html = '<pre><code{}>\n{}\n</code></pre>'.format(lang_attr, code_content)
|
|
key = '%%%CODE_{}%%%'.format(idx)
|
|
self._placeholders[key] = html
|
|
result.append(key)
|
|
return '\n'.join(result)
|
|
|
|
def _restore_code_blocks(self, text):
|
|
for key, html in self._placeholders.items():
|
|
text = text.replace(key, html)
|
|
return text
|
|
|
|
def _render_block_elements(self, text):
|
|
lines = text.split('\n')
|
|
result = []
|
|
i = 0
|
|
in_table = False
|
|
table_header = []
|
|
table_rows = []
|
|
in_list = False
|
|
list_type = None
|
|
list_buffer = []
|
|
|
|
def flush_list():
|
|
nonlocal in_list, list_type, list_buffer
|
|
if list_buffer:
|
|
tag = 'ol' if list_type == 'ol' else 'ul'
|
|
result.append('<{}>'.format(tag))
|
|
for item in list_buffer:
|
|
if '<' in item:
|
|
result.append('<li>{}</li>'.format(item))
|
|
else:
|
|
result.append('<li>{}</li>'.format(self._render_inline(item)))
|
|
result.append('</{}>'.format(tag))
|
|
list_buffer = []
|
|
in_list = False
|
|
list_type = None
|
|
|
|
def flush_table():
|
|
nonlocal in_table, table_header, table_rows
|
|
if table_header:
|
|
result.append('<div class="table-wrap"><table><thead><tr>')
|
|
for h in table_header:
|
|
result.append('<th>{}</th>'.format(self._render_inline(h)))
|
|
result.append('</tr></thead><tbody>')
|
|
for row in table_rows:
|
|
result.append('<tr>')
|
|
for cell in row:
|
|
result.append('<td>{}</td>'.format(self._render_inline(cell)))
|
|
result.append('</tr>')
|
|
result.append('</tbody></table></div>')
|
|
table_header = []
|
|
table_rows = []
|
|
in_table = False
|
|
|
|
while i < len(lines):
|
|
line = lines[i]
|
|
stripped = line.strip()
|
|
|
|
if not stripped:
|
|
flush_list()
|
|
flush_table()
|
|
if i > 0 and lines[i-1].strip():
|
|
result.append('')
|
|
i += 1
|
|
continue
|
|
|
|
if '%%%CODE_' in stripped:
|
|
flush_list()
|
|
flush_table()
|
|
result.append(stripped)
|
|
i += 1
|
|
continue
|
|
|
|
if stripped.startswith('|') and stripped.endswith('|'):
|
|
flush_list()
|
|
cells = [c.strip() for c in stripped.split('|')[1:-1]]
|
|
if not in_table:
|
|
in_table = True
|
|
table_header = cells
|
|
else:
|
|
if re.match(r'^[\s:|:-]+$', stripped):
|
|
i += 1
|
|
continue
|
|
table_rows.append(cells)
|
|
i += 1
|
|
continue
|
|
|
|
flush_table()
|
|
|
|
heading = re.match(r'^(#{1,6})\s+(.+)$', stripped)
|
|
if heading:
|
|
flush_list()
|
|
level = len(heading.group(1))
|
|
text_content = self._render_inline(heading.group(2))
|
|
result.append('<h{0}>{1}</h{0}>'.format(level, text_content))
|
|
i += 1
|
|
continue
|
|
|
|
if stripped.startswith('> '):
|
|
flush_list()
|
|
quote_text = self._render_inline(stripped[2:])
|
|
result.append('<blockquote><p>{}</p></blockquote>'.format(quote_text))
|
|
i += 1
|
|
continue
|
|
|
|
if re.match(r'^-{3,}$', stripped) or re.match(r'^\*{3,}$', stripped):
|
|
flush_list()
|
|
result.append('<hr>')
|
|
i += 1
|
|
continue
|
|
|
|
list_match = re.match(r'^(\d+)\.\s+(.+)$', stripped)
|
|
if list_match:
|
|
if not in_list:
|
|
in_list = True
|
|
list_type = 'ol'
|
|
list_buffer.append(list_match.group(2))
|
|
i += 1
|
|
continue
|
|
|
|
if stripped.startswith('- ') or stripped.startswith('* '):
|
|
content = stripped[2:].strip()
|
|
if content.startswith('[ ] '):
|
|
content = self._render_inline(content[4:])
|
|
content = '<input type="checkbox" disabled> ' + content
|
|
elif content.startswith('[x] '):
|
|
content = self._render_inline(content[4:])
|
|
content = '<input type="checkbox" disabled checked> ' + content
|
|
if not in_list:
|
|
in_list = True
|
|
list_type = 'ul'
|
|
list_buffer.append(content)
|
|
i += 1
|
|
continue
|
|
|
|
flush_list()
|
|
result.append('<p>{}</p>'.format(self._render_inline(stripped)))
|
|
i += 1
|
|
|
|
flush_list()
|
|
flush_table()
|
|
return '\n'.join(result)
|
|
|
|
def _render_inline(self, text):
|
|
text = self._escape_basic(text)
|
|
text = re.sub(r'!\[([^\]]*)\]\(([^)]+)\)', r'<img src="\2" alt="\1" style="max-width:100%">', text)
|
|
text = re.sub(r'\[([^\]]+)\]\(([^)]+)\)', r'<a href="\2" target="_blank" rel="noopener">\1</a>', text)
|
|
text = re.sub(r'`([^`]+)`', r'<code>\1</code>', text)
|
|
text = re.sub(r'\*\*\*(.+?)\*\*\*', r'<strong><em>\1</em></strong>', text)
|
|
text = re.sub(r'\*\*(.+?)\*\*', r'<strong>\1</strong>', text)
|
|
text = re.sub(r'\*(.+?)\*', r'<em>\1</em>', text)
|
|
return text
|
|
|
|
def _escape(self, text):
|
|
text = text.replace('&', '&')
|
|
text = text.replace('<', '<')
|
|
text = text.replace('>', '>')
|
|
return text
|
|
|
|
def _escape_basic(self, text):
|
|
text = text.replace('&', '&')
|
|
text = text.replace('<', '<')
|
|
text = text.replace('>', '>')
|
|
return text
|
|
|
|
|
|
markdown_parser = MarkdownParser()
|
|
|
|
|
|
class MarkdownHTML:
|
|
def __init__(self, html):
|
|
self._html = str(html)
|
|
|
|
def __html__(self):
|
|
return self._html
|
|
|
|
def __str__(self):
|
|
return self._html
|
|
|
|
|
|
@lru_cache(maxsize=256)
|
|
def _cached_render(text):
|
|
return markdown_parser.render(text)
|
|
|
|
|
|
def render_markdown(text):
|
|
return _cached_render(text)
|
|
|
|
|
|
def render_markdown_safe(text):
|
|
return MarkdownHTML(_cached_render(text)) |