md2site-cli 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
md2site/markdown.py ADDED
@@ -0,0 +1,408 @@
1
+ """Markdown engine, alerts, fences, headings, and text extraction."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import html
6
+ import re
7
+ from collections.abc import Sequence
8
+ from typing import Any
9
+
10
+ from markdown_it import MarkdownIt
11
+ from markdown_it.rules_core import StateCore
12
+ from markdown_it.token import Token
13
+ from mdit_py_plugins.footnote import footnote_plugin
14
+ from mdit_py_plugins.front_matter import front_matter_plugin
15
+ from mdit_py_plugins.tasklists import tasklists_plugin
16
+ from pygments import highlight
17
+ from pygments.formatters import HtmlFormatter
18
+ from pygments.lexer import Lexer
19
+ from pygments.lexers import get_lexer_by_name
20
+ from pygments.styles import get_all_styles, get_style_by_name
21
+ from pygments.util import ClassNotFound
22
+
23
+ from md2site.config import Config, ConfigError
24
+ from md2site.frontmatter import split_front_matter
25
+ from md2site.model import Heading, Page
26
+ from md2site.slug import Slugger
27
+ from md2site.wikilinks import wikilinks_plugin
28
+
29
+ _ALERT_RE = re.compile(r"^\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\](?:[ \t]+(.*)|$)", re.IGNORECASE)
30
+ _ALERT_TITLES = {
31
+ "note": "Note",
32
+ "tip": "Tip",
33
+ "important": "Important",
34
+ "warning": "Warning",
35
+ "caution": "Caution",
36
+ }
37
+
38
+
39
+ def _extract_heading_text(inline_token: Token) -> str:
40
+ """Extract clean plain text from a heading's inline token."""
41
+ if not inline_token.children:
42
+ return inline_token.content.strip()
43
+ parts: list[str] = []
44
+ for child in inline_token.children:
45
+ if child.type in ("text", "code_inline"):
46
+ parts.append(child.content)
47
+ elif child.type in ("softbreak", "hardbreak"):
48
+ parts.append(" ")
49
+ elif child.type == "image" and child.content:
50
+ parts.append(child.content)
51
+ return "".join(parts).strip()
52
+
53
+
54
+ def _headings_core_rule(state: StateCore) -> None:
55
+ """Assign unique GitHub-compatible IDs to headings and record them in env."""
56
+ slugger = Slugger()
57
+ headings: list[Heading] = state.env.setdefault("headings", [])
58
+ tokens = state.tokens
59
+
60
+ for idx, token in enumerate(tokens):
61
+ if token.type != "heading_open":
62
+ continue
63
+ level = int(token.tag[1:])
64
+ text = ""
65
+ if idx + 1 < len(tokens) and tokens[idx + 1].type == "inline":
66
+ text = _extract_heading_text(tokens[idx + 1])
67
+ hid = slugger.slug(text)
68
+ token.attrSet("id", hid)
69
+ headings.append(Heading(level=level, text=text, id=hid))
70
+
71
+
72
+ def _find_matching_blockquote_close(tokens: list[Token], open_idx: int) -> int:
73
+ """Find the matching ``blockquote_close`` index for ``tokens[open_idx]``."""
74
+ depth = 0
75
+ for idx in range(open_idx, len(tokens)):
76
+ tok = tokens[idx]
77
+ if tok.type == "blockquote_open":
78
+ depth += 1
79
+ elif tok.type == "blockquote_close":
80
+ depth -= 1
81
+ if depth == 0:
82
+ return idx
83
+ return len(tokens) - 1
84
+
85
+
86
+ def _alerts_core_rule(state: StateCore) -> None:
87
+ """Convert GitHub-style ``> [!NOTE]`` blockquotes into callout tokens."""
88
+ tokens = state.tokens
89
+ idx = 0
90
+ while idx < len(tokens):
91
+ tok = tokens[idx]
92
+ if tok.type != "blockquote_open":
93
+ idx += 1
94
+ continue
95
+
96
+ close_idx = _find_matching_blockquote_close(tokens, idx)
97
+ if (
98
+ idx + 3 <= close_idx
99
+ and tokens[idx + 1].type == "paragraph_open"
100
+ and tokens[idx + 2].type == "inline"
101
+ and tokens[idx + 3].type == "paragraph_close"
102
+ ):
103
+ inline_tok = tokens[idx + 2]
104
+ children = inline_tok.children or []
105
+ if children and children[0].type == "text":
106
+ first_text = children[0]
107
+ match = _ALERT_RE.match(first_text.content)
108
+ has_line_break_next = len(children) > 1 and children[1].type in (
109
+ "softbreak",
110
+ "hardbreak",
111
+ )
112
+ valid_boundary = match is not None and (
113
+ match.group(2) is not None or len(children) == 1 or has_line_break_next
114
+ )
115
+ if match is not None and valid_boundary:
116
+ kind = match.group(1).lower()
117
+ remainder = match.group(2) or ""
118
+
119
+ tok.type = "callout_open"
120
+ tok.tag = "div"
121
+ tok.meta = {**tok.meta, "alert_type": kind}
122
+
123
+ if close_idx < len(tokens) and tokens[close_idx].type == "blockquote_close":
124
+ tokens[close_idx].type = "callout_close"
125
+ tokens[close_idx].tag = "div"
126
+
127
+ if remainder:
128
+ first_text.content = remainder
129
+ elif has_line_break_next:
130
+ # Remove "[!KIND]" and the immediately following break.
131
+ del children[0:2]
132
+ if inline_tok.map is not None:
133
+ inline_tok.map = [inline_tok.map[0] + 1, inline_tok.map[1]]
134
+ else:
135
+ del children[0]
136
+
137
+ if not children:
138
+ # Strip the now-empty first paragraph inside the callout.
139
+ del tokens[idx + 1 : idx + 4]
140
+ else:
141
+ inline_tok.content = "".join(c.content for c in children)
142
+
143
+ idx += 1
144
+
145
+
146
+ def _make_fence_renderer(
147
+ *,
148
+ mermaid_enabled: bool = True,
149
+ max_highlight_bytes: int = 262144,
150
+ ) -> Any:
151
+ """Build a stateful-per-engine fence renderer with a local lexer cache."""
152
+ lexer_cache: dict[str, Lexer | None] = {}
153
+ formatter = HtmlFormatter(nowrap=False, cssclass="highlight")
154
+
155
+ def _get_lexer(lang: str) -> Lexer | None:
156
+ key = lang.lower()
157
+ if key not in lexer_cache:
158
+ try:
159
+ lexer_cache[key] = get_lexer_by_name(key, stripall=False)
160
+ except ClassNotFound:
161
+ lexer_cache[key] = None
162
+ return lexer_cache[key]
163
+
164
+ def _render_fence(
165
+ self: Any,
166
+ tokens: Sequence[Token],
167
+ idx: int,
168
+ options: Any,
169
+ env: dict[str, Any],
170
+ ) -> str:
171
+ token = tokens[idx]
172
+ info = token.info.strip()
173
+ lang = info.split()[0] if info else ""
174
+ lang_lower = lang.lower()
175
+
176
+ if mermaid_enabled and lang_lower == "mermaid":
177
+ escaped = html.escape(token.content, quote=True)
178
+ return f'<pre class="mermaid" data-src="{escaped}">{escaped}</pre>\n'
179
+
180
+ escaped_lang = html.escape(lang, quote=True)
181
+ within_highlight_budget = (
182
+ max_highlight_bytes == 0 or len(token.content.encode("utf-8")) <= max_highlight_bytes
183
+ )
184
+ lexer = (
185
+ _get_lexer(lang)
186
+ if (lang and within_highlight_budget and (mermaid_enabled or lang_lower != "mermaid"))
187
+ else None
188
+ )
189
+ if lexer is not None:
190
+ highlighted = highlight(token.content, lexer, formatter)
191
+ return f'<div class="code-block" data-lang="{escaped_lang}">{highlighted}</div>\n'
192
+
193
+ escaped_code = html.escape(token.content, quote=False)
194
+ return (
195
+ f'<div class="code-block" data-lang="{escaped_lang}">'
196
+ f"<pre><code>{escaped_code}</code></pre></div>\n"
197
+ )
198
+
199
+ return _render_fence
200
+
201
+
202
+ def make_engine(config: Config) -> MarkdownIt:
203
+ """Construct and configure a reusable ``MarkdownIt`` engine instance."""
204
+ md = MarkdownIt(
205
+ "commonmark",
206
+ {"html": config.allow_html, "md2site_mermaid": config.mermaid},
207
+ ).enable(["table", "strikethrough"])
208
+ md.use(front_matter_plugin)
209
+ md.use(footnote_plugin)
210
+ md.use(tasklists_plugin)
211
+ if config.wikilinks:
212
+ md.use(wikilinks_plugin)
213
+
214
+ md.core.ruler.push("md2site_alerts", _alerts_core_rule)
215
+ md.core.ruler.push("md2site_headings", _headings_core_rule)
216
+
217
+ orig_heading_open = md.renderer.rules.get("heading_open")
218
+ orig_heading_close = md.renderer.rules.get("heading_close")
219
+ orig_table_open = md.renderer.rules.get("table_open")
220
+ orig_table_close = md.renderer.rules.get("table_close")
221
+
222
+ def _render_heading_open(
223
+ tokens: Sequence[Token], idx: int, options: Any, env: dict[str, Any]
224
+ ) -> str:
225
+ hid = tokens[idx].attrGet("id") or ""
226
+ stack: list[str] = env.setdefault("_heading_stack", [])
227
+ stack.append(str(hid))
228
+ if orig_heading_open is not None:
229
+ return str(orig_heading_open(tokens, idx, options, env))
230
+ return md.renderer.renderToken(tokens, idx, options, env)
231
+
232
+ def _render_heading_close(
233
+ tokens: Sequence[Token], idx: int, options: Any, env: dict[str, Any]
234
+ ) -> str:
235
+ stack: list[str] = env.setdefault("_heading_stack", [])
236
+ hid = stack.pop() if stack else ""
237
+ anchor = (
238
+ f'<a class="anchor" href="#{html.escape(hid, quote=True)}" '
239
+ f'aria-label="Link to this section">#</a>'
240
+ if hid
241
+ else ""
242
+ )
243
+ if orig_heading_close is not None:
244
+ close_html = str(orig_heading_close(tokens, idx, options, env))
245
+ else:
246
+ close_html = md.renderer.renderToken(tokens, idx, options, env)
247
+ return f"{anchor}{close_html}"
248
+
249
+ def _render_callout_open(
250
+ tokens: Sequence[Token], idx: int, options: Any, env: dict[str, Any]
251
+ ) -> str:
252
+ kind = str(tokens[idx].meta.get("alert_type", "note"))
253
+ title = _ALERT_TITLES.get(kind, kind.capitalize())
254
+ return (
255
+ f'<div class="callout callout-{html.escape(kind, quote=True)}" role="note">'
256
+ f'<p class="callout-title">{html.escape(title)}</p>\n'
257
+ )
258
+
259
+ def _render_callout_close(
260
+ tokens: Sequence[Token], idx: int, options: Any, env: dict[str, Any]
261
+ ) -> str:
262
+ return "</div>\n"
263
+
264
+ def _render_table_open(
265
+ tokens: Sequence[Token], idx: int, options: Any, env: dict[str, Any]
266
+ ) -> str:
267
+ inner = (
268
+ str(orig_table_open(tokens, idx, options, env))
269
+ if orig_table_open is not None
270
+ else md.renderer.renderToken(tokens, idx, options, env)
271
+ )
272
+ return f'<div class="table-wrap">\n{inner}'
273
+
274
+ def _render_table_close(
275
+ tokens: Sequence[Token], idx: int, options: Any, env: dict[str, Any]
276
+ ) -> str:
277
+ inner = (
278
+ str(orig_table_close(tokens, idx, options, env))
279
+ if orig_table_close is not None
280
+ else md.renderer.renderToken(tokens, idx, options, env)
281
+ )
282
+ return f"{inner}</div>\n"
283
+
284
+ fence_renderer = _make_fence_renderer(
285
+ mermaid_enabled=config.mermaid,
286
+ max_highlight_bytes=config.max_highlight_bytes,
287
+ )
288
+
289
+ def _render_fence_rule(
290
+ tokens: Sequence[Token], idx: int, options: Any, env: dict[str, Any]
291
+ ) -> str:
292
+ return str(fence_renderer(md.renderer, tokens, idx, options, env))
293
+
294
+ md.renderer.rules["heading_open"] = _render_heading_open
295
+ md.renderer.rules["heading_close"] = _render_heading_close
296
+ md.renderer.rules["callout_open"] = _render_callout_open
297
+ md.renderer.rules["callout_close"] = _render_callout_close
298
+ md.renderer.rules["table_open"] = _render_table_open
299
+ md.renderer.rules["table_close"] = _render_table_close
300
+ md.renderer.rules["fence"] = _render_fence_rule
301
+
302
+ return md
303
+
304
+
305
+ def _offset_token_maps(tokens: Sequence[Token], offset: int) -> bool:
306
+ """Shift top-level token ``.map`` line ranges by ``offset`` and detect Mermaid fences."""
307
+ has_mermaid = False
308
+ for token in tokens:
309
+ if offset and token.map is not None:
310
+ token.map = [token.map[0] + offset, token.map[1] + offset]
311
+ if token.type == "fence":
312
+ info = token.info.strip()
313
+ if info and info.split(None, 1)[0].lower() == "mermaid":
314
+ has_mermaid = True
315
+ return has_mermaid
316
+
317
+
318
+ def _extract_plain_text(tokens: Sequence[Token]) -> str:
319
+ """Extract collapsed plain text for search, dropping code fences and HTML."""
320
+ chunks: list[str] = []
321
+ for token in tokens:
322
+ if token.type != "inline":
323
+ continue
324
+ if token.children:
325
+ inline_parts: list[str] = []
326
+ for child in token.children:
327
+ ctype = child.type
328
+ if ctype in ("text", "code_inline"):
329
+ inline_parts.append(child.content)
330
+ elif ctype in ("softbreak", "hardbreak"):
331
+ inline_parts.append(" ")
332
+ elif ctype == "image" and child.content:
333
+ inline_parts.append(child.content)
334
+ text = " ".join("".join(inline_parts).split())
335
+ if text:
336
+ chunks.append(text)
337
+ else:
338
+ text = " ".join(token.content.split())
339
+ if text:
340
+ chunks.append(text)
341
+ return " ".join(chunks)
342
+
343
+
344
+ def parse(
345
+ page: Page,
346
+ text: str,
347
+ engine: MarkdownIt,
348
+ *,
349
+ body_line_offset: int | None = None,
350
+ ) -> None:
351
+ """Parse ``text`` into ``page.tokens``, ``page.headings``, and ``page.text``."""
352
+ if body_line_offset is None:
353
+ _, body, offset, _ = split_front_matter(text)
354
+ else:
355
+ body = text
356
+ offset = body_line_offset
357
+
358
+ env: dict[str, Any] = {"headings": []}
359
+ tokens = engine.parse(body, env)
360
+ has_mermaid = _offset_token_maps(tokens, offset) and bool(
361
+ engine.options.get("md2site_mermaid", True)
362
+ )
363
+
364
+ page.tokens = tokens
365
+ page.headings = env["headings"]
366
+ page.text = _extract_plain_text(tokens)
367
+ if has_mermaid:
368
+ page.meta["_has_mermaid"] = True
369
+ else:
370
+ page.meta.pop("_has_mermaid", None)
371
+
372
+
373
+ def render(page: Page, engine: MarkdownIt) -> str:
374
+ """Render ``page.tokens`` to HTML without mutating tokens or page state."""
375
+ env: dict[str, Any] = {}
376
+ return str(engine.renderer.render(page.tokens, engine.options, env))
377
+
378
+
379
+ def _validate_pygments_style(name: str, role: str) -> None:
380
+ try:
381
+ get_style_by_name(name)
382
+ except ClassNotFound as exc:
383
+ valid_sample = ", ".join(sorted(get_all_styles())[:8])
384
+ raise ConfigError(
385
+ f"Invalid Pygments style {name!r} for '{role}'. "
386
+ f"Valid styles include: {valid_sample}, ..."
387
+ ) from exc
388
+
389
+
390
+ def pygments_css(light: str, dark: str) -> str:
391
+ """Return scoped Pygments CSS rules for light and dark themes."""
392
+ _validate_pygments_style(light, "theme.code_theme_light")
393
+ _validate_pygments_style(dark, "theme.code_theme_dark")
394
+
395
+ light_defs = HtmlFormatter(style=light).get_style_defs('[data-theme="light"] .highlight')
396
+ dark_defs = HtmlFormatter(style=dark).get_style_defs('[data-theme="dark"] .highlight')
397
+
398
+ light_lines = [line for line in light_defs.splitlines() if line.startswith("[data-theme=")]
399
+ dark_lines = [line for line in dark_defs.splitlines() if line.startswith("[data-theme=")]
400
+
401
+ return "\n".join(
402
+ [
403
+ "pre { line-height: 125%; }",
404
+ *light_lines,
405
+ *dark_lines,
406
+ "",
407
+ ]
408
+ )
md2site/model.py ADDED
@@ -0,0 +1,80 @@
1
+ """Core shared data model types for md2site."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from pathlib import Path, PurePosixPath
7
+ from typing import Any
8
+
9
+ from md2site.config import Config
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class Heading:
14
+ """A parsed Markdown heading with its generated anchor ID."""
15
+
16
+ level: int
17
+ text: str
18
+ id: str
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class AssetCopy:
23
+ """An asset file scheduled to be copied into the output directory."""
24
+
25
+ src: Path
26
+ dest_rel: PurePosixPath
27
+
28
+
29
+ @dataclass
30
+ class Page:
31
+ """A single Markdown page and its parsed/resolved artifacts."""
32
+
33
+ src: Path
34
+ rel: PurePosixPath
35
+ out_rel: PurePosixPath
36
+ title: str
37
+ order: float | None
38
+ hidden: bool
39
+ draft: bool
40
+ aliases: tuple[str, ...]
41
+ tags: tuple[str, ...]
42
+ meta: dict[str, Any]
43
+ headings: list[Heading] = field(default_factory=list)
44
+ tokens: list[Any] = field(default_factory=list)
45
+ text: str = ""
46
+
47
+
48
+ @dataclass
49
+ class NavNode:
50
+ """A node in the hierarchical navigation tree."""
51
+
52
+ label: str
53
+ page: Page | None
54
+ children: list[NavNode]
55
+ is_dir: bool
56
+
57
+
58
+ @dataclass(frozen=True)
59
+ class Diagnostic:
60
+ """A structured warning or error produced during build or check."""
61
+
62
+ level: str
63
+ code: str
64
+ file: str
65
+ line: int | None
66
+ message: str
67
+ target: str | None = None
68
+ suggestion: str | None = None
69
+
70
+
71
+ @dataclass
72
+ class Site:
73
+ """Aggregated site state passed across pipeline stages."""
74
+
75
+ config: Config
76
+ pages: list[Page]
77
+ nav: list[NavNode]
78
+ by_rel: dict[PurePosixPath, Page]
79
+ assets: list[AssetCopy]
80
+ diagnostics: list[Diagnostic]