import re class MarkdownParser: def __init__(self): self._placeholders = {} def render(self, text): if not text: return '' text = text.replace('\r\n', '\n').replace('\r', '\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 = '
\n{}\n
'.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 = '
\n{}\n
'.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: result.append('
  • {}
  • '.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('
    ') for h in table_header: result.append(''.format(self._render_inline(h))) result.append('') for row in table_rows: result.append('') for cell in row: result.append(''.format(self._render_inline(cell))) result.append('') result.append('
    {}
    {}
    ') 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('{1}'.format(level, text_content)) i += 1 continue if stripped.startswith('> '): flush_list() quote_text = self._render_inline(stripped[2:]) result.append('

    {}

    '.format(quote_text)) i += 1 continue if re.match(r'^-{3,}$', stripped) or re.match(r'^\*{3,}$', stripped): flush_list() result.append('
    ') 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 = ' ' + content elif content.startswith('[x] '): content = self._render_inline(content[4:]) content = ' ' + content if not in_list: in_list = True list_type = 'ul' list_buffer.append(content) i += 1 continue flush_list() result.append('

    {}

    '.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'\1', text) text = re.sub(r'\[([^\]]+)\]\(([^)]+)\)', r'\1', text) text = re.sub(r'`([^`]+)`', r'\1', text) text = re.sub(r'\*\*\*(.+?)\*\*\*', r'\1', text) text = re.sub(r'\*\*(.+?)\*\*', r'\1', text) text = re.sub(r'\*(.+?)\*', r'\1', 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 def render_markdown(text): return markdown_parser.render(text) def render_markdown_safe(text): return MarkdownHTML(render_markdown(text))