1import os
2from html.parser import HTMLParser
3from typing import TYPE_CHECKING, Any, cast
4from urllib.parse import urlparse, urlunparse
5
6import mistune
7from plain.urls import reverse
8from plain.utils.text import slugify
9from pygments import highlight
10from pygments.formatters import html
11from pygments.lexers import get_lexer_by_name
12
13if TYPE_CHECKING:
14 from .registry import PagesRegistry
15
16
17class PagesRenderer(mistune.HTMLRenderer):
18 def __init__(
19 self, current_page_path: str, pages_registry: PagesRegistry, **kwargs: Any
20 ):
21 super().__init__(**kwargs)
22 self.current_page_path = current_page_path
23 self.pages_registry = pages_registry
24
25 def link(self, text: str, url: str, title: str | None = None) -> str:
26 """Convert relative markdown links to proper page URLs."""
27 # Check if it's a relative link (starts with ./ or ../, or is just a filename)
28 is_relative = url.startswith(("./", "../")) or (
29 not url.startswith(("http://", "https://", "/", "#")) and ":" not in url
30 )
31
32 if is_relative:
33 # Parse URL to extract components
34 parsed_url = urlparse(url)
35
36 # Resolve relative to current page's directory using just the path component
37 current_dir = os.path.dirname(self.current_page_path)
38 resolved_path = os.path.normpath(os.path.join(current_dir, parsed_url.path))
39 page = self.pages_registry.get_page_from_path(resolved_path)
40
41 # Get the primary URL name for link conversion
42 url_name = page.get_url_name()
43 if url_name:
44 base_url = reverse(f"pages:{url_name}")
45 # Reconstruct URL with preserved query params and fragment
46 url = str(
47 urlunparse(
48 (
49 parsed_url.scheme, # scheme (empty for relative)
50 parsed_url.netloc, # netloc (empty for relative)
51 base_url, # path (our converted URL)
52 parsed_url.params, # params
53 parsed_url.query, # query
54 parsed_url.fragment, # fragment
55 )
56 )
57 )
58
59 return super().link(text, url, title)
60
61 def heading(self, text: str, level: int, **attrs: Any) -> str:
62 """Automatically add an ID to headings if one is not provided."""
63
64 if "id" not in attrs:
65 inner_text = get_inner_text(text)
66 inner_text = inner_text.replace(
67 ".", "-"
68 ) # Replace dots with hyphens (slugify won't)
69 attrs["id"] = slugify(inner_text)
70
71 return super().heading(text, level, **attrs)
72
73 def block_code(self, code: str, info: str | None = None) -> str:
74 """Highlight code blocks using Pygments."""
75
76 if info:
77 lexer = get_lexer_by_name(info, stripall=True)
78 formatter = html.HtmlFormatter(wrapcode=True)
79 return highlight(code, lexer, formatter)
80
81 return "<pre><code>" + mistune.escape(code) + "</code></pre>"
82
83
84def render_markdown(content: str, current_page_path: str) -> str:
85 from .registry import pages_registry
86
87 renderer = PagesRenderer(
88 current_page_path=current_page_path, pages_registry=pages_registry, escape=False
89 )
90 markdown = mistune.create_markdown(
91 renderer=renderer, plugins=["strikethrough", "table"]
92 )
93 return cast(str, markdown(content))
94
95
96class InnerTextParser(HTMLParser):
97 def __init__(self):
98 super().__init__()
99 self.text_content: list[str] = []
100
101 def handle_data(self, data: str) -> None:
102 # Collect all text data
103 self.text_content.append(data.strip())
104
105
106def get_inner_text(html_content: str) -> str:
107 parser = InnerTextParser()
108 parser.feed(html_content)
109 return " ".join([text for text in parser.text_content if text])