hypermarkdown 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.
- hypermarkdown/__init__.py +31 -0
- hypermarkdown/cli.py +177 -0
- hypermarkdown/config.py +110 -0
- hypermarkdown/diagram.py +169 -0
- hypermarkdown/embed.py +227 -0
- hypermarkdown/frontmatter.py +191 -0
- hypermarkdown/graph.py +74 -0
- hypermarkdown/imports.py +62 -0
- hypermarkdown/lint/__init__.py +6 -0
- hypermarkdown/lint/report.py +44 -0
- hypermarkdown/lint/rules.py +257 -0
- hypermarkdown/mkdocs_plugin.py +337 -0
- hypermarkdown/model.py +155 -0
- hypermarkdown/parse.py +174 -0
- hypermarkdown/render/__init__.py +5 -0
- hypermarkdown/render/flat.py +77 -0
- hypermarkdown/resolve.py +334 -0
- hypermarkdown/scan.py +153 -0
- hypermarkdown/urls.py +60 -0
- hypermarkdown-0.2.0.dist-info/METADATA +303 -0
- hypermarkdown-0.2.0.dist-info/RECORD +25 -0
- hypermarkdown-0.2.0.dist-info/WHEEL +5 -0
- hypermarkdown-0.2.0.dist-info/entry_points.txt +6 -0
- hypermarkdown-0.2.0.dist-info/licenses/LICENSE +21 -0
- hypermarkdown-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
"""The rule set (HMD-0001 §8).
|
|
2
|
+
|
|
3
|
+
Rule IDs are stable and are never renumbered once released; CI configuration and
|
|
4
|
+
suppression will reference them.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from ..embed import MAX_EMBED_DEPTH
|
|
12
|
+
from ..model import ERROR, WARNING, Diagnostic, Document, Link
|
|
13
|
+
from ..resolve import INDEX_STEM, SUFFIX, Outcome, Workspace
|
|
14
|
+
|
|
15
|
+
SEVERITY = {
|
|
16
|
+
"HMD001": WARNING,
|
|
17
|
+
"HMD002": ERROR,
|
|
18
|
+
"HMD003": ERROR,
|
|
19
|
+
"HMD004": ERROR,
|
|
20
|
+
"HMD005": ERROR,
|
|
21
|
+
"HMD006": ERROR,
|
|
22
|
+
"HMD007": ERROR,
|
|
23
|
+
"HMD008": ERROR,
|
|
24
|
+
"HMD009": ERROR,
|
|
25
|
+
"HMD010": ERROR,
|
|
26
|
+
"HMD011": WARNING,
|
|
27
|
+
"HMD012": ERROR,
|
|
28
|
+
"HMD013": ERROR,
|
|
29
|
+
"HMD014": ERROR,
|
|
30
|
+
"HMD015": ERROR,
|
|
31
|
+
"HMD016": WARNING,
|
|
32
|
+
"HMD017": WARNING,
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def check(workspace: Workspace, paths: list[Path] | None = None) -> list[Diagnostic]:
|
|
37
|
+
"""Lint `paths`, or the whole namespace tree."""
|
|
38
|
+
targets = paths if paths is not None else workspace.pages()
|
|
39
|
+
diagnostics: list[Diagnostic] = []
|
|
40
|
+
|
|
41
|
+
for path in targets:
|
|
42
|
+
document = workspace.documents.get(path)
|
|
43
|
+
if document is None:
|
|
44
|
+
continue
|
|
45
|
+
diagnostics.extend(document.diagnostics) # HMD009, HMD010, HMD013, HMD014
|
|
46
|
+
diagnostics.extend(_duplicate_anchors(workspace, document))
|
|
47
|
+
diagnostics.extend(_duplicate_slugs(workspace, document))
|
|
48
|
+
diagnostics.extend(_import_problems(workspace, document))
|
|
49
|
+
diagnostics.extend(_links(workspace, document))
|
|
50
|
+
|
|
51
|
+
diagnostics.extend(_folder_note_collisions(workspace, targets))
|
|
52
|
+
diagnostics.extend(_embed_cycles(workspace, targets))
|
|
53
|
+
|
|
54
|
+
diagnostics.sort(key=Diagnostic.sort_key)
|
|
55
|
+
return diagnostics
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _at(document: Document, rel: str, rule: str, line: int, column: int, message: str, **kw) -> Diagnostic:
|
|
59
|
+
return Diagnostic(rule, SEVERITY[rule], rel, line, column, message, **kw)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
# -- per-document rules --------------------------------------------------
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _duplicate_anchors(workspace: Workspace, document: Document):
|
|
66
|
+
"""HMD006 — a block id must be unique within its page."""
|
|
67
|
+
rel = workspace.rel(document.path)
|
|
68
|
+
seen: dict[str, int] = {}
|
|
69
|
+
for anchor in document.anchors:
|
|
70
|
+
if anchor.block_id in seen:
|
|
71
|
+
yield _at(
|
|
72
|
+
document,
|
|
73
|
+
rel,
|
|
74
|
+
"HMD006",
|
|
75
|
+
anchor.span.line,
|
|
76
|
+
anchor.span.column,
|
|
77
|
+
f"duplicate block anchor '^{anchor.block_id}' (first defined on line {seen[anchor.block_id]})",
|
|
78
|
+
)
|
|
79
|
+
else:
|
|
80
|
+
seen[anchor.block_id] = anchor.span.line
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _duplicate_slugs(workspace: Workspace, document: Document):
|
|
84
|
+
"""HMD011 — two headings sharing a base slug are addressed by `_1` suffixes."""
|
|
85
|
+
rel = workspace.rel(document.path)
|
|
86
|
+
for heading in document.headings:
|
|
87
|
+
base, _, suffix = heading.slug.rpartition("_")
|
|
88
|
+
if base and suffix.isdigit():
|
|
89
|
+
yield _at(
|
|
90
|
+
document,
|
|
91
|
+
rel,
|
|
92
|
+
"HMD011",
|
|
93
|
+
heading.span.line,
|
|
94
|
+
heading.span.column,
|
|
95
|
+
f"heading slug collides with an earlier heading; addressable as '#{heading.slug}'",
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _import_problems(workspace: Workspace, document: Document):
|
|
100
|
+
"""HMD003 and HMD015 raised while building the import table."""
|
|
101
|
+
rel = workspace.rel(document.path)
|
|
102
|
+
for rule, message in workspace.import_table(document.path).problems:
|
|
103
|
+
yield _at(document, rel, rule, 1, 1, message)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _links(workspace: Workspace, document: Document):
|
|
107
|
+
"""HMD001..HMD005 — resolution and fragment checks."""
|
|
108
|
+
rel = workspace.rel(document.path)
|
|
109
|
+
for link in document.links:
|
|
110
|
+
span = link.span
|
|
111
|
+
result = workspace.resolve(document.path, link.page_ref)
|
|
112
|
+
|
|
113
|
+
if result.outcome is Outcome.ESCAPES:
|
|
114
|
+
yield _at(
|
|
115
|
+
document, rel, "HMD003", span.line, span.column,
|
|
116
|
+
f"{link.raw} resolves outside the namespace root",
|
|
117
|
+
)
|
|
118
|
+
continue
|
|
119
|
+
|
|
120
|
+
if result.outcome is Outcome.AMBIGUOUS:
|
|
121
|
+
candidates = tuple(workspace.rel(p) for p in result.candidates)
|
|
122
|
+
yield _at(
|
|
123
|
+
document, rel, "HMD002", span.line, span.column,
|
|
124
|
+
f"{link.raw} matches {len(candidates)} pages; qualify it "
|
|
125
|
+
f"(candidates: {', '.join(candidates)})",
|
|
126
|
+
candidates=candidates,
|
|
127
|
+
)
|
|
128
|
+
continue
|
|
129
|
+
|
|
130
|
+
if result.outcome is Outcome.UNRESOLVED:
|
|
131
|
+
yield _at(
|
|
132
|
+
document, rel, "HMD001", span.line, span.column,
|
|
133
|
+
f"{link.raw} does not resolve to a page",
|
|
134
|
+
)
|
|
135
|
+
continue
|
|
136
|
+
|
|
137
|
+
for diagnostic in _fragment(workspace, document, link, result.path, rel):
|
|
138
|
+
yield diagnostic
|
|
139
|
+
|
|
140
|
+
# HMD017 — a published card reaching into one that is not published.
|
|
141
|
+
# Only from a public card: private cards referring to each other is the
|
|
142
|
+
# ordinary case, and warning about it would bury the real finding.
|
|
143
|
+
if workspace.is_public(document.path) and not workspace.is_public(result.path):
|
|
144
|
+
kind = "embeds" if link.is_embed else "links to"
|
|
145
|
+
yield _at(
|
|
146
|
+
document, rel, "HMD017", span.line, span.column,
|
|
147
|
+
f"{link.raw} {kind} {workspace.rel(result.path)}, which is not "
|
|
148
|
+
f"published; it renders as a red link",
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
if result.shadowed:
|
|
152
|
+
shadowed = tuple(workspace.rel(p) for p in result.shadowed if p)
|
|
153
|
+
yield _at(
|
|
154
|
+
document, rel, "HMD016", span.line, span.column,
|
|
155
|
+
f"{link.raw} also matched {', '.join(shadowed)}; the earlier import won",
|
|
156
|
+
candidates=shadowed,
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _fragment(workspace: Workspace, document: Document, link: Link, target: Path, rel: str):
|
|
161
|
+
"""HMD004 and HMD005 — the fragment must exist in the resolved page."""
|
|
162
|
+
if link.fragment is None:
|
|
163
|
+
return
|
|
164
|
+
resolved = workspace.documents.get(target)
|
|
165
|
+
if resolved is None:
|
|
166
|
+
return
|
|
167
|
+
span = link.span
|
|
168
|
+
|
|
169
|
+
if link.fragment_kind == "block":
|
|
170
|
+
if link.fragment not in resolved.block_ids():
|
|
171
|
+
yield _at(
|
|
172
|
+
document, rel, "HMD005", span.line, span.column,
|
|
173
|
+
f"{workspace.rel(target)} has no block '^{link.fragment}'",
|
|
174
|
+
)
|
|
175
|
+
return
|
|
176
|
+
|
|
177
|
+
from ..parse import slug_for # local import: parse imports the model, not lint
|
|
178
|
+
|
|
179
|
+
wanted = slug_for(link.fragment, set())
|
|
180
|
+
if wanted not in resolved.heading_slugs():
|
|
181
|
+
yield _at(
|
|
182
|
+
document, rel, "HMD004", span.line, span.column,
|
|
183
|
+
f"{workspace.rel(target)} has no heading '#{wanted}'",
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
# -- cross-document rules ------------------------------------------------
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _folder_note_collisions(workspace: Workspace, targets: list[Path]):
|
|
191
|
+
"""HMD012 — `foo.hmd` beside `foo/index.hmd`."""
|
|
192
|
+
wanted = set(targets)
|
|
193
|
+
for page in workspace.pages():
|
|
194
|
+
note = page.with_suffix("") / f"{INDEX_STEM}{SUFFIX}"
|
|
195
|
+
if note not in workspace.documents:
|
|
196
|
+
continue
|
|
197
|
+
if page not in wanted and note not in wanted:
|
|
198
|
+
continue
|
|
199
|
+
rel = workspace.rel(page)
|
|
200
|
+
yield Diagnostic(
|
|
201
|
+
"HMD012",
|
|
202
|
+
SEVERITY["HMD012"],
|
|
203
|
+
rel,
|
|
204
|
+
1,
|
|
205
|
+
1,
|
|
206
|
+
f"{rel} and {workspace.rel(note)} both claim the name "
|
|
207
|
+
f"'{page.with_suffix('').relative_to(workspace.root).as_posix()}'; the file wins",
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _embed_cycles(workspace: Workspace, targets: list[Path]):
|
|
212
|
+
"""HMD007 and HMD008 — cycle detection and the depth bound."""
|
|
213
|
+
wanted = set(targets)
|
|
214
|
+
reported: set[tuple[Path, str | None]] = set()
|
|
215
|
+
|
|
216
|
+
for start in targets:
|
|
217
|
+
if start not in workspace.documents:
|
|
218
|
+
continue
|
|
219
|
+
yield from _walk(workspace, start, None, [], reported, wanted)
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _walk(workspace: Workspace, path: Path, fragment: str | None, stack, reported, wanted):
|
|
223
|
+
key = (path, fragment)
|
|
224
|
+
if key in stack:
|
|
225
|
+
if key not in reported:
|
|
226
|
+
reported.add(key)
|
|
227
|
+
rel = workspace.rel(path)
|
|
228
|
+
chain = " -> ".join(workspace.rel(p) for p, _ in stack[stack.index(key) :])
|
|
229
|
+
yield Diagnostic(
|
|
230
|
+
"HMD007", SEVERITY["HMD007"], rel, 1, 1,
|
|
231
|
+
f"embed cycle: {chain} -> {rel}",
|
|
232
|
+
)
|
|
233
|
+
return
|
|
234
|
+
|
|
235
|
+
if len(stack) >= MAX_EMBED_DEPTH:
|
|
236
|
+
rel = workspace.rel(path)
|
|
237
|
+
if key not in reported:
|
|
238
|
+
reported.add(key)
|
|
239
|
+
yield Diagnostic(
|
|
240
|
+
"HMD008", SEVERITY["HMD008"], rel, 1, 1,
|
|
241
|
+
f"embed depth exceeds the limit of {MAX_EMBED_DEPTH}",
|
|
242
|
+
)
|
|
243
|
+
return
|
|
244
|
+
|
|
245
|
+
document = workspace.documents.get(path)
|
|
246
|
+
if document is None:
|
|
247
|
+
return
|
|
248
|
+
|
|
249
|
+
stack.append(key)
|
|
250
|
+
for link in document.links:
|
|
251
|
+
if not link.is_embed:
|
|
252
|
+
continue
|
|
253
|
+
result = workspace.resolve(path, link.page_ref)
|
|
254
|
+
if result.outcome is not Outcome.RESOLVED or result.path is None:
|
|
255
|
+
continue
|
|
256
|
+
yield from _walk(workspace, result.path, link.fragment, stack, reported, wanted)
|
|
257
|
+
stack.pop()
|
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
"""The MkDocs plugin (HMD-0002).
|
|
2
|
+
|
|
3
|
+
MkDocs is consumed for the code it already provides. The plugin's whole job is
|
|
4
|
+
to make `.hmd` visible to a build and to write down what the resolver has
|
|
5
|
+
already decided — it never resolves anything a second time.
|
|
6
|
+
|
|
7
|
+
Three hooks carry it. `on_files` registers `.hmd` pages under `.md` names, since
|
|
8
|
+
MkDocs matches a fixed extension set. `on_nav`… is not used: nav is built in
|
|
9
|
+
`on_files` instead, because MkDocs needs the config's `nav` before it builds its
|
|
10
|
+
own. `on_page_markdown` expands embeds and rewrites links before Python-Markdown
|
|
11
|
+
runs, so `toc` and `footnotes` see one finished document.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import posixpath
|
|
17
|
+
import re
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
from mkdocs.config import config_options
|
|
21
|
+
from mkdocs.config.base import Config as BaseConfig
|
|
22
|
+
from mkdocs.exceptions import PluginError
|
|
23
|
+
from mkdocs.plugins import BasePlugin
|
|
24
|
+
from mkdocs.structure.files import File, Files
|
|
25
|
+
|
|
26
|
+
from . import config as config_mod
|
|
27
|
+
from . import diagram, scan, urls
|
|
28
|
+
from .embed import expand
|
|
29
|
+
from .model import Link
|
|
30
|
+
from .parse import slug_for
|
|
31
|
+
from .resolve import Workspace
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
#: A nav entry with this value is replaced by the derived wiki section, so an
|
|
35
|
+
#: authored book nav can say *where* the generated pages go.
|
|
36
|
+
NAV_PLACEHOLDER = "hmd://wiki"
|
|
37
|
+
|
|
38
|
+
#: An ordinary markdown link whose target is a `.hmd` file. Book pages and
|
|
39
|
+
#: proposals link to cards this way — a wikilink would not work from outside the
|
|
40
|
+
#: namespace, and the path they write is a real file in the repository.
|
|
41
|
+
_HMD_HREF_RE = re.compile(r"\]\((?P<href>[^)\s#]+\.hmd)(?P<fragment>#[^)\s]*)?\)")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class PluginConfig(BaseConfig):
|
|
45
|
+
#: The namespace root. Defaults to `docs_dir`, but may name a subtree of it:
|
|
46
|
+
#: a site can cover all of `doc/` while `[[…]]` stays restricted to
|
|
47
|
+
#: `doc/wiki`, so a book and its wiki live in one build.
|
|
48
|
+
root = config_options.Optional(config_options.Dir(exists=True))
|
|
49
|
+
build_nav = config_options.Type(bool, default=True)
|
|
50
|
+
#: Render `d2` fences. With no `d2` binary on PATH they degrade to a
|
|
51
|
+
#: labelled placeholder rather than failing the build (HMD-0022 §5).
|
|
52
|
+
diagrams = config_options.Type(bool, default=True)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class HyperMarkDownPlugin(BasePlugin[PluginConfig]):
|
|
56
|
+
"""Collect `.hmd` pages, order them, expand them, rewrite their links."""
|
|
57
|
+
|
|
58
|
+
def __init__(self) -> None:
|
|
59
|
+
self.workspace: Workspace | None = None
|
|
60
|
+
#: MkDocs source path (`a/b.md`) -> the `.hmd` page it came from.
|
|
61
|
+
self.sources: dict[str, Path] = {}
|
|
62
|
+
#: The `.hmd` page -> the MkDocs source path it was registered under.
|
|
63
|
+
self.destinations: dict[Path, str] = {}
|
|
64
|
+
#: Where the namespace root sits inside `docs_dir`, as a URL prefix.
|
|
65
|
+
self.prefix = ""
|
|
66
|
+
self.docs_dir: Path | None = None
|
|
67
|
+
self.engine = diagram.D2Engine()
|
|
68
|
+
|
|
69
|
+
# -- collection ------------------------------------------------------
|
|
70
|
+
|
|
71
|
+
def on_files(self, files: Files, /, *, config) -> Files:
|
|
72
|
+
if not config.use_directory_urls:
|
|
73
|
+
raise PluginError(
|
|
74
|
+
"HyperMarkDown requires use_directory_urls: true — a card and its "
|
|
75
|
+
"folder note share one URL, which page.html cannot express"
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
self.docs_dir = docs_dir = Path(config.docs_dir).resolve()
|
|
79
|
+
root = Path(self.config.root).resolve() if self.config.root else docs_dir
|
|
80
|
+
self.workspace = Workspace(config_mod.load(root_override=root))
|
|
81
|
+
self.prefix = _prefix(docs_dir, self.workspace.root)
|
|
82
|
+
|
|
83
|
+
for path in self.workspace.pages():
|
|
84
|
+
# Publication is opt-in (§2). An unpublished card is not registered
|
|
85
|
+
# at all: no file, no URL, nothing about it in `site/`. Skipping it
|
|
86
|
+
# here is what makes that true everywhere downstream — nav derives
|
|
87
|
+
# from `self.sources`, and link rewriting from `self.destinations`.
|
|
88
|
+
if not self.workspace.is_public(path):
|
|
89
|
+
continue
|
|
90
|
+
dest = self._dest(path)
|
|
91
|
+
self.sources[dest] = path
|
|
92
|
+
self.destinations[path] = dest
|
|
93
|
+
files.append(
|
|
94
|
+
File.generated(
|
|
95
|
+
config,
|
|
96
|
+
dest,
|
|
97
|
+
content=self.workspace.documents[path].text,
|
|
98
|
+
)
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
if not self.config.build_nav:
|
|
102
|
+
return files
|
|
103
|
+
|
|
104
|
+
# An authored nav wins, except where it asks for the wiki by name. That
|
|
105
|
+
# is the whole integration: a book keeps its own order and says where
|
|
106
|
+
# the generated section belongs. A card the book already placed is not
|
|
107
|
+
# derived a second time — MkDocs gives a page one `parent`, so a card
|
|
108
|
+
# promoted into the book *and* listed in the wiki renders twice with
|
|
109
|
+
# the wrong section expanded on its own page.
|
|
110
|
+
if not config.nav:
|
|
111
|
+
config.nav = self._nav()
|
|
112
|
+
return files
|
|
113
|
+
|
|
114
|
+
config.nav = _splice(config.nav, self._nav(claimed=_claimed(config.nav)))
|
|
115
|
+
return files
|
|
116
|
+
|
|
117
|
+
def _dest(self, path: Path) -> str:
|
|
118
|
+
"""The MkDocs source path a card is registered under, prefix included."""
|
|
119
|
+
dest = urls.dest_for(self.workspace.root, path)
|
|
120
|
+
return posixpath.join(self.prefix, dest) if self.prefix else dest
|
|
121
|
+
|
|
122
|
+
# -- §2 nav ----------------------------------------------------------
|
|
123
|
+
|
|
124
|
+
def _nav(self, claimed: frozenset[str] = frozenset()) -> list:
|
|
125
|
+
"""Derive the nav from the namespace tree.
|
|
126
|
+
|
|
127
|
+
Ordering is `nav.order` first, ascending, then root-relative path —
|
|
128
|
+
deterministic and independent of filesystem iteration order (P1).
|
|
129
|
+
`claimed` names the pages an authored nav has already placed; they are
|
|
130
|
+
left out, because a placement made by hand is still a placement.
|
|
131
|
+
"""
|
|
132
|
+
assert self.workspace is not None
|
|
133
|
+
tree: dict = {}
|
|
134
|
+
|
|
135
|
+
for dest, path in sorted(self.sources.items()):
|
|
136
|
+
if dest in claimed:
|
|
137
|
+
continue
|
|
138
|
+
parts = urls.parts_for(self.workspace.root, path)
|
|
139
|
+
node = tree
|
|
140
|
+
for part in parts[:-1] if parts else ():
|
|
141
|
+
node = node.setdefault(part, {})
|
|
142
|
+
if len(parts) <= 1 and parts and parts[0] == urls.INDEX_STEM:
|
|
143
|
+
node["__index__"] = dest
|
|
144
|
+
elif self._is_folder_note(path):
|
|
145
|
+
node.setdefault(parts[-1], {})["__index__"] = dest if parts else dest
|
|
146
|
+
else:
|
|
147
|
+
node[parts[-1] if parts else urls.INDEX_STEM] = dest
|
|
148
|
+
|
|
149
|
+
return self._nav_items(tree)
|
|
150
|
+
|
|
151
|
+
def _is_folder_note(self, path: Path) -> bool:
|
|
152
|
+
return path.stem == urls.INDEX_STEM and path.parent != self.workspace.root
|
|
153
|
+
|
|
154
|
+
def _order(self, dest: str) -> tuple[int, int, str]:
|
|
155
|
+
"""`nav.order` first, ascending; then path. Absent order sorts last."""
|
|
156
|
+
order = self.workspace.documents[self.sources[dest]].card.nav.order
|
|
157
|
+
return (1, 0, dest) if order is None else (0, order, dest)
|
|
158
|
+
|
|
159
|
+
def _nav_items(self, node: dict) -> list:
|
|
160
|
+
items: list = []
|
|
161
|
+
index = node.get("__index__")
|
|
162
|
+
if index is not None:
|
|
163
|
+
items.append({self._title(index): index})
|
|
164
|
+
|
|
165
|
+
entries = [(key, value) for key, value in node.items() if key != "__index__"]
|
|
166
|
+
entries.sort(key=lambda kv: self._order(kv[1]) if isinstance(kv[1], str) else (1, 0.0, kv[0]))
|
|
167
|
+
|
|
168
|
+
for key, value in entries:
|
|
169
|
+
if isinstance(value, str):
|
|
170
|
+
items.append({self._title(value): value})
|
|
171
|
+
else:
|
|
172
|
+
items.append({_titlecase(key): self._nav_items(value)})
|
|
173
|
+
return items
|
|
174
|
+
|
|
175
|
+
def _title(self, dest: str) -> str:
|
|
176
|
+
document = self.workspace.documents[self.sources[dest]]
|
|
177
|
+
for heading in document.headings:
|
|
178
|
+
if heading.level == 1:
|
|
179
|
+
return heading.text
|
|
180
|
+
return _titlecase(Path(dest).stem)
|
|
181
|
+
|
|
182
|
+
# -- §3 expansion and rewriting --------------------------------------
|
|
183
|
+
|
|
184
|
+
def on_page_markdown(self, markdown: str, /, *, page, config, files) -> str:
|
|
185
|
+
"""Expand embeds and rewrite links before Python-Markdown runs."""
|
|
186
|
+
if self.workspace is None:
|
|
187
|
+
return markdown
|
|
188
|
+
|
|
189
|
+
source = self.sources.get(page.file.src_uri)
|
|
190
|
+
if source is None:
|
|
191
|
+
# Not a card. It may still link *to* one — a book page or a proposal
|
|
192
|
+
# writes an ordinary relative link to a `.hmd` file, because a
|
|
193
|
+
# wikilink does not work from outside the namespace — and it may
|
|
194
|
+
# carry diagrams of its own.
|
|
195
|
+
return self._diagrams(self._link_to_cards(markdown, page.file.src_uri))
|
|
196
|
+
|
|
197
|
+
root = self.workspace.root
|
|
198
|
+
|
|
199
|
+
def rewrite(link: Link, target: Path | None) -> str:
|
|
200
|
+
text = link.display or link.page_ref
|
|
201
|
+
if target is None:
|
|
202
|
+
# A red link keeps the build green and marks a page worth
|
|
203
|
+
# writing later; lint tracks it as HMD001.
|
|
204
|
+
return f'<a class="hmd-redlink" title="{link.target} does not resolve">{text}</a>'
|
|
205
|
+
if not self.workspace.is_public(target):
|
|
206
|
+
# The target resolves but was never published, so there is no
|
|
207
|
+
# page to point at. Same red link, different reason — and a
|
|
208
|
+
# distinct title, because "unwritten" and "not for this site"
|
|
209
|
+
# are different problems for whoever reads it. HMD017.
|
|
210
|
+
return (
|
|
211
|
+
f'<a class="hmd-redlink" title="{link.target} is not published">{text}</a>'
|
|
212
|
+
)
|
|
213
|
+
href = urls.href_for(root, source, target)
|
|
214
|
+
if link.fragment is not None and link.fragment_kind == "heading":
|
|
215
|
+
href = f"{href}#{slug_for(link.fragment, set())}"
|
|
216
|
+
return f"[{text}]({href})"
|
|
217
|
+
|
|
218
|
+
expanded = expand(
|
|
219
|
+
self.workspace, source, rewrite=rewrite, can_embed=self.workspace.is_public
|
|
220
|
+
).text
|
|
221
|
+
return self._diagrams(self._link_to_cards(expanded, page.file.src_uri))
|
|
222
|
+
|
|
223
|
+
def _diagrams(self, markdown: str) -> str:
|
|
224
|
+
"""Render `d2` fences to images, or to a labelled placeholder.
|
|
225
|
+
|
|
226
|
+
Runs after expansion, so a diagram embedded from another card renders
|
|
227
|
+
like one written here.
|
|
228
|
+
"""
|
|
229
|
+
if not self.config.diagrams:
|
|
230
|
+
return markdown
|
|
231
|
+
|
|
232
|
+
out: list[str] = []
|
|
233
|
+
cursor = 0
|
|
234
|
+
for info, body, start, end in scan.find_fences(markdown):
|
|
235
|
+
language = info.split()[0].lower() if info.split() else ""
|
|
236
|
+
if language not in diagram.LANGUAGES:
|
|
237
|
+
continue
|
|
238
|
+
out.append(markdown[cursor:start])
|
|
239
|
+
out.append(diagram.to_html(language, body, self.engine) + "\n")
|
|
240
|
+
cursor = end
|
|
241
|
+
|
|
242
|
+
out.append(markdown[cursor:])
|
|
243
|
+
return "".join(out)
|
|
244
|
+
|
|
245
|
+
def _link_to_cards(self, markdown: str, src_uri: str) -> str:
|
|
246
|
+
"""Point ordinary markdown links at the page a `.hmd` file becomes.
|
|
247
|
+
|
|
248
|
+
The written path is a real file, which is what makes it work when the
|
|
249
|
+
repository is browsed on its own. The built site does not serve `.hmd`
|
|
250
|
+
sources, so the same link has to arrive at the rendered card instead of
|
|
251
|
+
404ing.
|
|
252
|
+
|
|
253
|
+
Masked first, so a `.hmd` path quoted inside a fence stays quoted.
|
|
254
|
+
"""
|
|
255
|
+
masked = scan.mask(markdown)
|
|
256
|
+
directory = posixpath.dirname(src_uri)
|
|
257
|
+
out: list[str] = []
|
|
258
|
+
cursor = 0
|
|
259
|
+
|
|
260
|
+
for match in _HMD_HREF_RE.finditer(masked):
|
|
261
|
+
dest = self._card_at(directory, match.group("href"))
|
|
262
|
+
if dest is None:
|
|
263
|
+
continue
|
|
264
|
+
href = posixpath.relpath(dest, directory or ".")
|
|
265
|
+
out.append(markdown[cursor : match.start()])
|
|
266
|
+
out.append(f"]({href}{match.group('fragment') or ''})")
|
|
267
|
+
cursor = match.end()
|
|
268
|
+
|
|
269
|
+
out.append(markdown[cursor:])
|
|
270
|
+
return "".join(out)
|
|
271
|
+
|
|
272
|
+
def _card_at(self, directory: str, href: str) -> str | None:
|
|
273
|
+
"""The registered page for a `.hmd` link, or None if it is not a card."""
|
|
274
|
+
if self.docs_dir is None or href.startswith(("http://", "https://", "/")):
|
|
275
|
+
return None
|
|
276
|
+
target = Path(posixpath.normpath(posixpath.join(directory, href)))
|
|
277
|
+
return self.destinations.get((self.docs_dir / target).resolve())
|
|
278
|
+
|
|
279
|
+
# -- serving ---------------------------------------------------------
|
|
280
|
+
|
|
281
|
+
def on_serve(self, server, /, *, config, builder):
|
|
282
|
+
"""Watch the namespace root, which MkDocs would otherwise ignore."""
|
|
283
|
+
if self.workspace is not None:
|
|
284
|
+
server.watch(str(self.workspace.root))
|
|
285
|
+
return server
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def _prefix(docs_dir: Path, root: Path) -> str:
|
|
289
|
+
"""How far the namespace root sits below `docs_dir`, as a URL prefix.
|
|
290
|
+
|
|
291
|
+
A root outside `docs_dir` gets no prefix: its pages are still generated, they
|
|
292
|
+
simply land at the site root.
|
|
293
|
+
"""
|
|
294
|
+
try:
|
|
295
|
+
relative = root.relative_to(docs_dir).as_posix()
|
|
296
|
+
except ValueError:
|
|
297
|
+
return ""
|
|
298
|
+
return "" if relative == "." else relative
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def _splice(node, derived: list):
|
|
302
|
+
"""Replace every `hmd://wiki` in an authored nav with the derived section.
|
|
303
|
+
|
|
304
|
+
As a mapping value it becomes that entry's children; as a list item it is
|
|
305
|
+
spliced in place, so a section can hold hand-written pages beside generated
|
|
306
|
+
ones.
|
|
307
|
+
"""
|
|
308
|
+
if isinstance(node, list):
|
|
309
|
+
out: list = []
|
|
310
|
+
for item in node:
|
|
311
|
+
if item == NAV_PLACEHOLDER:
|
|
312
|
+
out.extend(derived)
|
|
313
|
+
else:
|
|
314
|
+
out.append(_splice(item, derived))
|
|
315
|
+
return out
|
|
316
|
+
if isinstance(node, dict):
|
|
317
|
+
return {
|
|
318
|
+
key: derived if value == NAV_PLACEHOLDER else _splice(value, derived)
|
|
319
|
+
for key, value in node.items()
|
|
320
|
+
}
|
|
321
|
+
return node
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def _claimed(node) -> frozenset[str]:
|
|
325
|
+
"""Every source path an authored nav names, at any depth.
|
|
326
|
+
|
|
327
|
+
The placeholder is not one of them: it stands for the section about to be
|
|
328
|
+
spliced in, not for a page.
|
|
329
|
+
"""
|
|
330
|
+
if isinstance(node, str):
|
|
331
|
+
return frozenset() if node == NAV_PLACEHOLDER else frozenset({posixpath.normpath(node)})
|
|
332
|
+
values = node.values() if isinstance(node, dict) else node if isinstance(node, list) else ()
|
|
333
|
+
return frozenset().union(*(_claimed(value) for value in values)) if values else frozenset()
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def _titlecase(stem: str) -> str:
|
|
337
|
+
return stem.replace("-", " ").replace("_", " ").strip().capitalize()
|