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.html import HtmlFormatter
from pygments.lexers import get_lexer_by_name
from pygments.lexers.special import TextLexer
from pygments.util import ClassNotFound
from .code_structure import extract_code_headings
from .markdown_utils import Heading, slugify_heading
from .media import is_qt_video_player_url, 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,
wheel_scroll_speed: float = 1.0,
document_width_scale: float = 1.0,
document_font_family: str = "",
document_font_size: int | None = None,
document_style_css: str = "",
math_engine: str = "katex",
include_reader_toc: bool = False,
include_reader_progress: bool = False,
) -> str:
source = markdown_path.read_text(encoding="utf-8")
env: dict[str, Any] = {"path": str(markdown_path), "headings": []}
body = self.markdown.render(source, env)
headings = self._env_headings(env)
return self._wrap_html(
body=body,
title=markdown_path.name,
theme=theme,
font_scale=font_scale,
wheel_scroll_speed=wheel_scroll_speed,
document_width_scale=document_width_scale,
document_font_family=document_font_family,
document_font_size=document_font_size,
document_style_css=document_style_css,
math_engine=math_engine,
headings=headings,
include_reader_toc=include_reader_toc,
include_reader_progress=include_reader_progress,
)
def render_source(
self,
source: str,
markdown_path: Path,
theme: str = "light",
font_scale: float = 1.0,
wheel_scroll_speed: float = 1.0,
document_width_scale: float = 1.0,
document_font_family: str = "",
document_font_size: int | None = None,
document_style_css: str = "",
math_engine: str = "katex",
include_reader_toc: bool = False,
include_reader_progress: bool = False,
) -> str:
env: dict[str, Any] = {"path": str(markdown_path), "headings": []}
body = self.markdown.render(source, env)
headings = self._env_headings(env)
return self._wrap_html(
body=body,
title=markdown_path.name,
theme=theme,
font_scale=font_scale,
wheel_scroll_speed=wheel_scroll_speed,
document_width_scale=document_width_scale,
document_font_family=document_font_family,
document_font_size=document_font_size,
document_style_css=document_style_css,
math_engine=math_engine,
headings=headings,
include_reader_toc=include_reader_toc,
include_reader_progress=include_reader_progress,
)
def render_code_source(
self,
source: str,
code_path: Path,
language: str = "text",
theme: str = "light",
font_scale: float = 1.0,
wheel_scroll_speed: float = 1.0,
document_width_scale: float = 1.0,
document_font_family: str = "",
document_font_size: int | None = None,
document_style_css: str = "",
math_engine: str = "katex",
include_reader_toc: bool = False,
include_reader_progress: bool = False,
) -> str:
label = html.escape(language or code_path.suffix.lstrip(".") or "text")
language_class = f" language-{html.escape(language)}" if language else ""
highlighted = self._highlight_code(source, language, line_anchors=True)
headings = extract_code_headings(code_path, source)
title = html.escape(code_path.name)
body = (
f"
{title}
"
''
f'
{label}
'
f'
{highlighted}
'
"
"
)
return self._wrap_html(
body=body,
title=code_path.name,
theme=theme,
font_scale=font_scale,
wheel_scroll_speed=wheel_scroll_speed,
document_width_scale=document_width_scale,
document_font_family=document_font_family,
document_font_size=document_font_size,
document_style_css=document_style_css,
math_engine=math_engine,
headings=headings,
include_reader_toc=include_reader_toc,
include_reader_progress=include_reader_progress,
)
def wrap_body_for_display(
self,
body: str,
title: str,
theme: str = "light",
font_scale: float = 1.0,
wheel_scroll_speed: float = 1.0,
document_width_scale: float = 1.0,
document_font_family: str = "",
document_font_size: int | None = None,
document_style_css: str = "",
math_engine: str = "katex",
headings: list[Heading] | None = None,
include_reader_toc: bool = False,
include_reader_progress: bool = False,
) -> str:
return self._wrap_html(
body=body,
title=title,
theme=theme,
font_scale=font_scale,
wheel_scroll_speed=wheel_scroll_speed,
document_width_scale=document_width_scale,
document_font_family=document_font_family,
document_font_size=document_font_size,
document_style_css=document_style_css,
math_engine=math_engine,
headings=headings or [],
include_reader_toc=include_reader_toc,
include_reader_progress=include_reader_progress,
)
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":
if is_qt_video_player_url(resolved_src):
player_href = html.escape(f"{resolved_src}?mdhelper-open=player-new-tab", quote=True)
external_href = html.escape(f"{resolved_src}?mdhelper-open=external", quote=True)
return (
f''
'"
f"{caption}"
)
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, line_anchors: bool = False) -> str:
normalized = language.lower()
if normalized in {"pseudocode", "pseudo"}:
highlighted = self._highlight_pseudocode(code)
return self._add_line_anchors(highlighted) if line_anchors else highlighted
try:
lexer = get_lexer_by_name(normalized) if normalized else TextLexer()
except ClassNotFound:
lexer = TextLexer()
highlighted = highlight(code, lexer, self.formatter)
return self._add_line_anchors(highlighted) if line_anchors else highlighted
def _add_line_anchors(self, highlighted: str) -> str:
lines = highlighted.splitlines(keepends=True)
return "".join(
f'{line}'
for index, line in enumerate(lines, start=1)
)
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
headings = state.env.setdefault("headings", [])
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)
if isinstance(headings, list):
try:
level = int(token.tag[1:])
except (TypeError, ValueError):
level = 1
headings.append({"level": level, "title": inline.content, "slug": 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,
wheel_scroll_speed: float,
document_width_scale: float,
document_font_family: str,
document_font_size: int | None,
document_style_css: str,
math_engine: str,
headings: list[Heading] | None = None,
include_reader_toc: bool = False,
include_reader_progress: bool = False,
) -> 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)
try:
normalized_wheel_speed = max(0.5, min(3.0, float(wheel_scroll_speed)))
except (TypeError, ValueError):
normalized_wheel_speed = 1.0
try:
normalized_width_scale = min((1.0, 1.25, 1.5, 1.75, 2.0), key=lambda candidate: abs(candidate - float(document_width_scale)))
except (TypeError, ValueError):
normalized_width_scale = 1.0
paper_width_px = int(round(794 * normalized_width_scale))
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)
reader_shell = self._reader_shell_html(body, headings or [], include_reader_toc, include_reader_progress)
toc_flag = "1" if include_reader_toc and headings else "0"
progress_flag = "1" if include_reader_progress else "0"
return f"""
{escaped_title}
{math_assets["css"]}
{reader_shell}
{math_assets["js"]}
{mermaid_script}
"""
def _env_headings(self, env: dict[str, Any]) -> list[Heading]:
raw_headings = env.get("headings", [])
headings: list[Heading] = []
if not isinstance(raw_headings, list):
return headings
for item in raw_headings:
if not isinstance(item, dict):
continue
try:
level = max(1, min(6, int(item.get("level", 1))))
except (TypeError, ValueError):
level = 1
title = str(item.get("title", "")).strip()
slug = str(item.get("slug", "")).strip()
if title and slug:
headings.append(Heading(level=level, title=title, slug=slug))
return headings
def _reader_shell_html(
self,
body: str,
headings: list[Heading],
include_reader_toc: bool,
include_reader_progress: bool,
) -> str:
progress = ""
if include_reader_progress:
progress = (
' \n'
)
toc = self._reader_toc_html(headings) if include_reader_toc and headings else ""
shell_class = "reader-shell has-reader-toc" if toc else "reader-shell"
return f'{progress} \n{toc} \n{body}\n \n
'
def _reader_toc_html(self, headings: list[Heading]) -> str:
links = []
for heading in headings:
level = max(1, min(6, int(heading.level)))
title = html.escape(heading.title)
slug = html.escape(heading.slug, quote=True)
links.append(
f'{title}'
)
links_html = "\n".join(links)
return (
' \n'
)
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"