from __future__ import annotations
import html
import re
from pathlib import Path
from typing import Any
from urllib.parse import unquote, urlsplit
from markdown_it import MarkdownIt
from markdown_it.token import Token
from pygments import highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import TextLexer, get_lexer_by_name
from pygments.util import ClassNotFound
from .markdown_utils import slugify_heading
from .media import media_kind, media_mime_type
class MarkdownRenderer:
def __init__(self, project_root: Path) -> None:
self.project_root = project_root
self.resources_dir = Path(__file__).resolve().parent / "resources"
self.formatter = HtmlFormatter(nowrap=True)
self.markdown = MarkdownIt(
"commonmark",
{
"html": True,
"typographer": False,
"breaks": False,
},
).enable(["table", "strikethrough"])
self.markdown.renderer.rules["fence"] = self._render_fence
self.markdown.renderer.rules["code_block"] = self._render_code_block
self.markdown.renderer.rules["image"] = self._render_image
self.markdown.renderer.rules["link_open"] = self._render_link_open
self.markdown.core.ruler.push("mdhelper_heading_ids", self._add_heading_ids)
self.markdown.core.ruler.push("mdhelper_admonitions", self._convert_admonitions)
self.markdown.core.ruler.push("mdhelper_task_lists", self._convert_task_lists)
def render_file(
self,
markdown_path: Path,
theme: str = "light",
font_scale: float = 1.0,
document_font_family: str = "",
document_font_size: int | None = None,
math_engine: str = "katex",
) -> str:
source = markdown_path.read_text(encoding="utf-8")
body = self.markdown.render(source, {"path": str(markdown_path)})
return self._wrap_html(
body=body,
title=markdown_path.name,
theme=theme,
font_scale=font_scale,
document_font_family=document_font_family,
document_font_size=document_font_size,
math_engine=math_engine,
)
def wrap_body_for_display(
self,
body: str,
title: str,
theme: str = "light",
font_scale: float = 1.0,
document_font_family: str = "",
document_font_size: int | None = None,
math_engine: str = "katex",
) -> str:
return self._wrap_html(
body=body,
title=title,
theme=theme,
font_scale=font_scale,
document_font_family=document_font_family,
document_font_size=document_font_size,
math_engine=math_engine,
)
def _render_fence(
self,
tokens: list[Token],
idx: int,
options: dict[str, Any],
env: dict[str, Any],
) -> str:
token = tokens[idx]
language = token.info.strip().split(maxsplit=1)[0] if token.info else ""
normalized_language = language.lower()
if normalized_language == "mermaid":
return (
'
'
'
mermaid
'
f'
{html.escape(token.content)}'
"
\n"
)
if normalized_language in {"math", "tex", "latex"}:
return f'$$\n{html.escape(token.content)}\n$$
\n'
language_class = f" language-{html.escape(language)}" if language else ""
code = self._highlight_code(token.content, language)
label = html.escape(language or "text")
return (
f''
f'
{label}
'
f'
{code}
'
f"
\n"
)
def _render_code_block(
self,
tokens: list[Token],
idx: int,
options: dict[str, Any],
env: dict[str, Any],
) -> str:
token = tokens[idx]
return (
''
'
'
f"{html.escape(token.content)}"
"
"
"
\n"
)
def _render_image(
self,
tokens: list[Token],
idx: int,
options: dict[str, Any],
env: dict[str, Any],
) -> str:
token = tokens[idx]
src = token.attrGet("src") or ""
title = token.attrGet("title") or ""
alt = token.content or title or Path(src).name
kind = media_kind(src)
resolved_src = self._resolve_local_media_src(src, env)
escaped_src = html.escape(resolved_src, quote=True)
escaped_alt = html.escape(alt, quote=True)
mime_type = media_mime_type(src)
source_type = f' type="{html.escape(mime_type, quote=True)}"' if mime_type else ""
caption = f"{html.escape(alt)}" if alt else ""
if kind == "audio":
return (
f''
f'"
f"{caption}"
)
if kind == "video":
return (
f''
f'"
f"{caption}"
)
if kind == "gif":
return (
''
f'
'
f"{caption}"
)
return f'
'
def _render_link_open(
self,
tokens: list[Token],
idx: int,
options: dict[str, Any],
env: dict[str, Any],
) -> str:
token = tokens[idx]
href = token.attrGet("href") or ""
resolved_href = self._resolve_local_href(href, env)
if resolved_href != href:
token.attrSet("href", resolved_href)
return self.markdown.renderer.renderToken(tokens, idx, options, env)
def _resolve_local_media_src(self, src: str, env: dict[str, Any]) -> str:
if src.startswith("#"):
return src
parsed = urlsplit(src)
if parsed.scheme:
return src
markdown_path_value = env.get("path")
if not markdown_path_value:
return src
local_path = (Path(str(markdown_path_value)).parent / unquote(parsed.path)).resolve()
if not local_path.exists():
return src
uri = local_path.as_uri()
if parsed.fragment:
uri = f"{uri}#{parsed.fragment}"
return uri
def _resolve_local_href(self, href: str, env: dict[str, Any]) -> str:
if href.startswith("#"):
return href
parsed = urlsplit(href)
if parsed.scheme:
return href
markdown_path_value = env.get("path")
if not markdown_path_value:
return href
local_path = (Path(str(markdown_path_value)).parent / unquote(parsed.path)).resolve()
if not local_path.exists():
return href
uri = local_path.as_uri()
if parsed.fragment:
uri = f"{uri}#{parsed.fragment}"
return uri
def _highlight_code(self, code: str, language: str) -> str:
normalized = language.lower()
if normalized in {"pseudocode", "pseudo"}:
return self._highlight_pseudocode(code)
try:
lexer = get_lexer_by_name(normalized) if normalized else TextLexer()
except ClassNotFound:
lexer = TextLexer()
return highlight(code, lexer, self.formatter)
def _highlight_pseudocode(self, code: str) -> str:
escaped = html.escape(code)
keywords = (
"BEGIN",
"END",
"SET",
"FOR",
"TO",
"DO",
"IF",
"THEN",
"ELSE",
"RETURN",
"WHILE",
"REPEAT",
"UNTIL",
)
def replace_keyword(match: re.Match[str]) -> str:
return f'{match.group(0)}'
pattern = r"\b(" + "|".join(keywords) + r")\b"
return re.sub(pattern, replace_keyword, escaped)
def _add_heading_ids(self, state: Any) -> None:
seen: dict[str, int] = {}
tokens = state.tokens
for index, token in enumerate(tokens):
if token.type != "heading_open" or index + 1 >= len(tokens):
continue
inline = tokens[index + 1]
if inline.type != "inline":
continue
slug = slugify_heading(inline.content)
if not slug:
continue
count = seen.get(slug, 0)
seen[slug] = count + 1
if count:
slug = f"{slug}-{count + 1}"
token.attrSet("id", slug)
def _convert_admonitions(self, state: Any) -> None:
labels = {
"NOTE": "注意",
"TIP": "提示",
"IMPORTANT": "重要",
"WARNING": "警告",
"CAUTION": "小心",
}
tokens = state.tokens
for index, token in enumerate(tokens):
if token.type != "blockquote_open":
continue
inline_index = self._first_inline_in_blockquote(tokens, index)
if inline_index is None:
continue
inline = tokens[inline_index]
marker = re.match(
r"^\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]\s*([^\n]*)(?:\n(.*))?$",
inline.content,
re.DOTALL,
)
if not marker:
continue
kind = marker.group(1)
title = marker.group(2).strip() or labels[kind]
rest = (marker.group(3) or "").lstrip()
close_index = self._matching_close_index(tokens, index, "blockquote_close")
if close_index is None:
continue
token.tag = "aside"
token.attrJoin("class", f"admonition admonition-{kind.lower()}")
tokens[close_index].tag = "aside"
title_node = Token("html_inline", "", 0)
title_node.content = f'{html.escape(title)}'
children = [title_node]
if rest:
break_node = Token("html_inline", "", 0)
break_node.content = "
"
text = Token("text", "", 0)
text.content = rest
children.extend([break_node, text])
inline.content = f"{title}\n{rest}" if rest else title
inline.children = children
def _convert_task_lists(self, state: Any) -> None:
tokens = state.tokens
for index, token in enumerate(tokens):
if token.type != "inline" or not token.children:
continue
first_child = token.children[0]
if first_child.type != "text":
continue
marker = re.match(r"^\[([ xX])\]\s+", first_child.content)
if not marker:
continue
list_item = self._nearest_open_token(tokens, index, "list_item_open")
if list_item is None:
continue
bullet_list = self._nearest_open_token(tokens, index, "bullet_list_open")
if bullet_list is not None:
bullet_list.attrJoin("class", "task-list")
checked = marker.group(1).lower() == "x"
list_item.attrJoin("class", "task-list-item")
checkbox = Token("html_inline", "", 0)
checked_attr = " checked" if checked else ""
checkbox.content = (
' "
)
first_child.content = first_child.content[marker.end() :]
token.children.insert(0, checkbox)
def _first_inline_in_blockquote(self, tokens: list[Token], start_index: int) -> int | None:
start_level = tokens[start_index].level
for index in range(start_index + 1, len(tokens)):
token = tokens[index]
if token.type == "blockquote_close" and token.level == start_level:
return None
if token.type == "inline":
return index
return None
def _matching_close_index(self, tokens: list[Token], start_index: int, close_type: str) -> int | None:
start_level = tokens[start_index].level
for index in range(start_index + 1, len(tokens)):
token = tokens[index]
if token.type == close_type and token.level == start_level:
return index
return None
def _nearest_open_token(self, tokens: list[Token], start_index: int, token_type: str) -> Token | None:
inline_level = tokens[start_index].level
for token in reversed(tokens[:start_index]):
if token.type == token_type and token.level < inline_level:
return token
return None
def _wrap_html(
self,
body: str,
title: str,
theme: str,
font_scale: float,
document_font_family: str,
document_font_size: int | None,
math_engine: str,
) -> str:
css = (self.resources_dir / "reader.css").read_text(encoding="utf-8")
js = (self.resources_dir / "reader.js").read_text(encoding="utf-8")
math_assets = self._math_assets(math_engine)
mermaid_script = self._script_tag(self._resource_uri("vendor/mermaid/mermaid.min.js"))
pygments_css = HtmlFormatter().get_style_defs(".highlight")
escaped_title = html.escape(title)
escaped_theme = html.escape(theme, quote=True)
escaped_math_engine = html.escape(self._normalized_math_engine(math_engine), quote=True)
fallback_font_size = int(round(max(0.8, min(font_scale, 1.6)) * 16))
font_size = max(12, min(int(document_font_size or fallback_font_size), 28))
font_family = self._css_font_family(document_font_family)
escaped_font_family = html.escape(font_family, quote=False)
return f"""
{escaped_title}
{math_assets["css"]}
{body}
{math_assets["js"]}
{mermaid_script}
"""
def _resource_uri(self, relative_path: str) -> str:
path = self.resources_dir / relative_path
if not path.exists():
return ""
return path.as_uri()
def _script_tag(self, uri: str) -> str:
if not uri:
return ""
return f''
def _stylesheet_tag(self, uri: str) -> str:
if not uri:
return ""
return f''
def _css_font_family(self, font_family: str) -> str:
name = font_family.strip()
if not name:
return '"Segoe UI", "Microsoft YaHei UI", "Microsoft YaHei", Arial, sans-serif'
escaped_name = name.replace("\\", "\\\\").replace('"', '\\"')
return f'"{escaped_name}", "Microsoft YaHei UI", Arial, sans-serif'
def _math_assets(self, math_engine: str) -> dict[str, str]:
normalized = self._normalized_math_engine(math_engine)
if normalized == "mathjax":
config = (
"window.MathJax = {"
"tex: {inlineMath: [['$', '$'], ['\\\\(', '\\\\)']], "
"displayMath: [['$$', '$$'], ['\\\\[', '\\\\]']], processEscapes: true},"
"svg: {fontCache: 'none'}"
"};"
)
return {
"css": "",
"config": config,
"js": self._script_tag(self._resource_uri("vendor/mathjax/tex-svg-full.js")),
}
return {
"css": self._stylesheet_tag(self._resource_uri("vendor/katex/katex.min.css")),
"config": "",
"js": "\n".join(
[
self._script_tag(self._resource_uri("vendor/katex/katex.min.js")),
self._script_tag(self._resource_uri("vendor/katex/auto-render.min.js")),
]
),
}
def _normalized_math_engine(self, math_engine: str) -> str:
return "mathjax" if str(math_engine).lower() == "mathjax" else "katex"