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.
@@ -0,0 +1,334 @@
1
+ """The workspace and the four-phase resolver (HMD-0001 §5).
2
+
3
+ Resolution order is named import, then spine, then imported search paths, then
4
+ autodiscovery. Precedence follows explicitness: a named import may shadow a
5
+ local card because that is what it is for, while an imported search path may
6
+ not — so adding `import *` can only resolve links that were previously red, and
7
+ can never change what an already-working link means.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from dataclasses import dataclass, field
13
+ from enum import Enum
14
+ from pathlib import Path
15
+
16
+ from .config import Config
17
+ from .model import PRIVATE, PUBLIC, Document, ImportStmt
18
+ from .parse import parse
19
+
20
+ SUFFIX = ".hmd"
21
+ INDEX_STEM = "index"
22
+
23
+
24
+ class Outcome(Enum):
25
+ RESOLVED = "resolved"
26
+ UNRESOLVED = "unresolved"
27
+ AMBIGUOUS = "ambiguous"
28
+ ESCAPES = "escapes"
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class Resolution:
33
+ outcome: Outcome
34
+ path: Path | None = None
35
+ candidates: tuple[Path, ...] = ()
36
+ #: Which phase produced a RESOLVED result, for diagnostics and tests.
37
+ phase: int | None = None
38
+ #: Origins that also held the name but lost on declaration order (HMD016).
39
+ shadowed: tuple[Path, ...] = ()
40
+
41
+
42
+ @dataclass
43
+ class ImportTable:
44
+ bindings: dict[str, Path] = field(default_factory=dict)
45
+ search_paths: tuple[Path, ...] = ()
46
+ #: (rule, message) problems found while building the table.
47
+ problems: list[tuple[str, str]] = field(default_factory=list)
48
+
49
+
50
+ class Workspace:
51
+ """Every `.hmd` file under the namespace root, plus resolution over them."""
52
+
53
+ def __init__(self, config: Config):
54
+ self.config = config
55
+ self.root = config.root
56
+ self.documents: dict[Path, Document] = {}
57
+ self._pages: list[Path] = []
58
+ #: Root-relative parts -> the pages addressable under them, for phase 3.
59
+ self._by_parts: dict[tuple[str, ...], list[Path]] = {}
60
+ self._import_tables: dict[Path, ImportTable] = {}
61
+ self._load()
62
+
63
+ # -- loading ---------------------------------------------------------
64
+
65
+ def _load(self) -> None:
66
+ for path in sorted(self.root.rglob(f"*{SUFFIX}")):
67
+ if not path.is_file() or self._hidden(path):
68
+ continue
69
+ self._pages.append(path)
70
+ text = path.read_text(encoding="utf-8")
71
+ self.documents[path] = parse(path, text, self.rel(path))
72
+
73
+ for path in self._pages:
74
+ parts = self.parts(path)
75
+ self._by_parts.setdefault(parts, []).append(path)
76
+ # A folder note is also addressable by its directory's name, so a
77
+ # bare name means the same thing in phase 1 and phase 3.
78
+ if parts and parts[-1] == INDEX_STEM and len(parts) > 1:
79
+ self._by_parts.setdefault(parts[:-1], []).append(path)
80
+
81
+ def _hidden(self, path: Path) -> bool:
82
+ return any(part.startswith(".") for part in path.relative_to(self.root).parts)
83
+
84
+ # -- naming ----------------------------------------------------------
85
+
86
+ def rel(self, path: Path) -> str:
87
+ return path.relative_to(self.root).as_posix()
88
+
89
+ def parts(self, path: Path) -> tuple[str, ...]:
90
+ return path.relative_to(self.root).with_suffix("").parts
91
+
92
+ def pages(self) -> list[Path]:
93
+ return list(self._pages)
94
+
95
+ # -- §5.1 binding ----------------------------------------------------
96
+
97
+ def bind(self, directory: Path, parts: tuple[str, ...]) -> Path | None:
98
+ """Bind `parts` in one directory, honouring folder notes.
99
+
100
+ A target naming a directory resolves to that directory's `index.hmd`,
101
+ which is what makes a folder note the namespace's landing page. When
102
+ both `foo.hmd` and `foo/index.hmd` exist the file wins; the collision is
103
+ reported separately as HMD012.
104
+ """
105
+ if not parts:
106
+ return None
107
+ candidate = directory.joinpath(*parts).with_suffix(SUFFIX)
108
+ if candidate in self.documents:
109
+ return candidate
110
+ folder_note = directory.joinpath(*parts) / f"{INDEX_STEM}{SUFFIX}"
111
+ if folder_note in self.documents:
112
+ return folder_note
113
+ return None
114
+
115
+ # -- imports ---------------------------------------------------------
116
+
117
+ def import_table(self, source: Path) -> ImportTable:
118
+ if source not in self._import_tables:
119
+ self._import_tables[source] = self._build_import_table(source)
120
+ return self._import_tables[source]
121
+
122
+ def _build_import_table(self, source: Path) -> ImportTable:
123
+ table = ImportTable()
124
+ document = self.documents.get(source)
125
+ if document is None:
126
+ return table
127
+
128
+ search: list[Path] = []
129
+ for stmt in document.card.imports:
130
+ directory = self._import_dir(source, stmt)
131
+ if directory is None:
132
+ table.problems.append(
133
+ ("HMD003", f"import ref {stmt.ref!r} resolves outside the namespace root")
134
+ )
135
+ continue
136
+ if not directory.is_dir():
137
+ table.problems.append(("HMD015", f"import ref {stmt.ref!r} does not exist"))
138
+ continue
139
+
140
+ if stmt.wildcard:
141
+ search.append(directory)
142
+ continue
143
+
144
+ for name, local in stmt.bindings:
145
+ target = self.bind(directory, (name,))
146
+ if target is None:
147
+ table.problems.append(
148
+ ("HMD015", f"cannot import {name!r} from {stmt.ref!r}: no such page")
149
+ )
150
+ continue
151
+ if local in table.bindings and table.bindings[local] != target:
152
+ table.problems.append(
153
+ (
154
+ "HMD015",
155
+ f"{local!r} is bound twice by imports "
156
+ f"({self.rel(table.bindings[local])} and {self.rel(target)})",
157
+ )
158
+ )
159
+ continue
160
+ table.bindings[local] = target
161
+
162
+ table.search_paths = tuple(search)
163
+ return table
164
+
165
+ def _import_dir(self, source: Path, stmt: ImportStmt) -> Path | None:
166
+ if stmt.ref.startswith("/"):
167
+ directory = self.root.joinpath(*_split(stmt.ref))
168
+ else:
169
+ directory = source.parent.joinpath(stmt.ref)
170
+ directory = _normalize(directory)
171
+ return directory if self._inside_root(directory) else None
172
+
173
+ # -- §5.3 effective feature toggles ----------------------------------
174
+
175
+ def autodiscovery_enabled(self, source: Path) -> bool:
176
+ """Card `use`, then the nearest ancestor `index.hmd`, then config.
177
+
178
+ Frontmatter always beats configuration, because the card is the most
179
+ local place an author can say what they mean.
180
+ """
181
+ document = self.documents.get(source)
182
+ if document is not None and "autodiscovery" in document.card.use:
183
+ return document.card.use["autodiscovery"]
184
+
185
+ directory = source.parent
186
+ while True:
187
+ note = directory / f"{INDEX_STEM}{SUFFIX}"
188
+ if note != source and note in self.documents:
189
+ use = self.documents[note].card.use
190
+ if "autodiscovery" in use:
191
+ return use["autodiscovery"]
192
+ if directory == self.root or self.root not in directory.parents:
193
+ break
194
+ directory = directory.parent
195
+
196
+ return self.config.autodiscovery
197
+
198
+ # -- HMD-0002 §2 publication -----------------------------------------
199
+
200
+ def visibility(self, source: Path) -> str:
201
+ """Card `nav.visibility`, then the nearest ancestor `index.hmd`, then
202
+ the default — which is `private`.
203
+
204
+ Same walk as `autodiscovery_enabled`, and for the same reason: a folder
205
+ is a unit an author thinks in, so publishing one should not mean editing
206
+ every card inside it. The default is the strict end on purpose. A card
207
+ that says nothing about itself has not asked to be published, and the
208
+ failure mode of guessing the other way is a leak rather than a 404.
209
+ """
210
+ document = self.documents.get(source)
211
+ if document is not None and document.card.nav.visibility is not None:
212
+ return document.card.nav.visibility
213
+
214
+ directory = source.parent
215
+ while True:
216
+ note = directory / f"{INDEX_STEM}{SUFFIX}"
217
+ if note != source and note in self.documents:
218
+ inherited = self.documents[note].card.nav.visibility
219
+ if inherited is not None:
220
+ return inherited
221
+ if directory == self.root or self.root not in directory.parents:
222
+ break
223
+ directory = directory.parent
224
+
225
+ return PRIVATE
226
+
227
+ def is_public(self, source: Path) -> bool:
228
+ return self.visibility(source) == PUBLIC
229
+
230
+ # -- §5.2 the algorithm ----------------------------------------------
231
+
232
+ def resolve(self, source: Path, page_ref: str) -> Resolution:
233
+ stem = page_ref[: -len(SUFFIX)] if page_ref.endswith(SUFFIX) else page_ref
234
+
235
+ if stem.startswith("/"):
236
+ parts = _split(stem)
237
+ target = self.bind(self.root, parts)
238
+ return _hit(target, phase=None) if target else Resolution(Outcome.UNRESOLVED)
239
+
240
+ if stem.startswith("./") or stem.startswith("../"):
241
+ base = _normalize(source.parent.joinpath(stem))
242
+ if not self._inside_root(base):
243
+ return Resolution(Outcome.ESCAPES)
244
+ target = self.bind(base.parent, (base.name,))
245
+ return _hit(target, phase=None) if target else Resolution(Outcome.UNRESOLVED)
246
+
247
+ parts = _split(stem)
248
+ if not parts:
249
+ return Resolution(Outcome.UNRESOLVED)
250
+
251
+ table = self.import_table(source)
252
+
253
+ # Phase 0 — named imports. A binding names a page, not a namespace, so
254
+ # it applies to single-segment targets only.
255
+ if len(parts) == 1 and parts[0] in table.bindings:
256
+ return Resolution(Outcome.RESOLVED, table.bindings[parts[0]], phase=0)
257
+
258
+ # Phase 1 — spine walk, non-recursive, nearest first.
259
+ for directory in self._spine(source):
260
+ target = self.bind(directory, parts)
261
+ if target is not None:
262
+ return Resolution(Outcome.RESOLVED, target, phase=1)
263
+
264
+ # Phase 2 — imported search paths, in declaration order.
265
+ hits = [d for d in table.search_paths if self.bind(d, parts) is not None]
266
+ if hits:
267
+ winner = self.bind(hits[0], parts)
268
+ shadowed = tuple(self.bind(d, parts) for d in hits[1:])
269
+ return Resolution(Outcome.RESOLVED, winner, phase=2, shadowed=shadowed)
270
+
271
+ if not self.autodiscovery_enabled(source):
272
+ return Resolution(Outcome.UNRESOLVED)
273
+
274
+ # Phase 3 — autodiscovery, at most once.
275
+ matches = self._sweep(source, parts)
276
+ if len(matches) == 1:
277
+ return Resolution(Outcome.RESOLVED, matches[0], phase=3)
278
+ if len(matches) > 1:
279
+ return Resolution(Outcome.AMBIGUOUS, candidates=tuple(matches))
280
+ return Resolution(Outcome.UNRESOLVED)
281
+
282
+ def _spine(self, source: Path) -> list[Path]:
283
+ """The source's own directory outward to the root, inclusive."""
284
+ spine = []
285
+ directory = source.parent
286
+ while True:
287
+ spine.append(directory)
288
+ if directory == self.root:
289
+ break
290
+ if self.root not in directory.parents:
291
+ break
292
+ directory = directory.parent
293
+ return spine
294
+
295
+ def _sweep(self, source: Path, parts: tuple[str, ...]) -> list[Path]:
296
+ scope = source.parent if self.config.mode == "recursive" else self.root
297
+ matches = {
298
+ page
299
+ for key, pages in self._by_parts.items()
300
+ if key[-len(parts) :] == parts
301
+ for page in pages
302
+ if scope == self.root or scope in page.parents
303
+ }
304
+ # Sorted by root-relative POSIX path, so diagnostics are byte-identical
305
+ # across platforms and runs (P1).
306
+ return sorted(matches, key=self.rel)
307
+
308
+ def _inside_root(self, path: Path) -> bool:
309
+ return path == self.root or self.root in path.parents
310
+
311
+
312
+ def _hit(target: Path, phase: int | None) -> Resolution:
313
+ return Resolution(Outcome.RESOLVED, target, phase=phase)
314
+
315
+
316
+ def _split(ref: str) -> tuple[str, ...]:
317
+ return tuple(part for part in ref.strip("/").split("/") if part)
318
+
319
+
320
+ def _normalize(path: Path) -> Path:
321
+ """Collapse `.` and `..` without touching the filesystem.
322
+
323
+ `Path.resolve()` follows symlinks, which must not be able to carry a target
324
+ out of the root (HMD-0001 §4).
325
+ """
326
+ parts: list[str] = []
327
+ for part in path.parts:
328
+ if part == ".":
329
+ continue
330
+ if part == ".." and parts and parts[-1] not in ("..", path.anchor):
331
+ parts.pop()
332
+ continue
333
+ parts.append(part)
334
+ return Path(*parts) if parts else path
hypermarkdown/scan.py ADDED
@@ -0,0 +1,153 @@
1
+ """Masking scanner: find the constructs the format owns (HMD-0001 §1, §2).
2
+
3
+ The scanner does not parse CommonMark. It masks the regions where markup must
4
+ not be interpreted, then extracts constructs from what is left. Masking replaces
5
+ characters with spaces and preserves newlines, so every byte offset, line, and
6
+ column in the masked text still refers to the original source.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import re
12
+
13
+ # A fence opener/closer: three or more backticks or tildes, optionally indented.
14
+ _FENCE_RE = re.compile(r"^(?P<indent>[ \t]*)(?P<fence>`{3,}|~{3,})(?P<info>.*)$")
15
+ _HTML_COMMENT_RE = re.compile(r"<!--.*?-->", re.DOTALL)
16
+ # A code span: a run of N backticks, then the shortest text, then N backticks.
17
+ _CODE_SPAN_RE = re.compile(r"(?P<ticks>`+)(?P<body>.+?)(?P=ticks)", re.DOTALL)
18
+
19
+ _ATX_HEADING_RE = re.compile(r"^[ \t]{0,3}(?P<hashes>#{1,6})[ \t]+(?P<text>.*?)[ \t]*$", re.MULTILINE)
20
+ _ANCHOR_RE = re.compile(r"[ \t]+\^(?P<id>[A-Za-z0-9][A-Za-z0-9_-]{0,63})[ \t]*$", re.MULTILINE)
21
+ # A wikilink target may not contain "[", "]" or a newline (HMD-0001 §2).
22
+ _LINK_RE = re.compile(r"(?P<bang>!?)\[\[(?P<inner>[^\[\]\n]*)\]\]")
23
+ _OPEN_RE = re.compile(r"!?\[\[")
24
+
25
+
26
+ def mask(text: str) -> str:
27
+ """Return `text` with uninterpreted regions blanked out, offsets preserved.
28
+
29
+ Masked: fenced code blocks, HTML comments, and inline code spans.
30
+
31
+ Indented code blocks are deliberately NOT masked. This tree ships the
32
+ `admonition` and `footnotes` extensions, under which a four-space indent
33
+ marks callout bodies and footnote continuations rather than code; masking it
34
+ would silently drop real links from ordinary prose.
35
+ """
36
+ chars = list(text)
37
+ for start, end in _masked_regions(text):
38
+ for i in range(start, end):
39
+ if chars[i] != "\n":
40
+ chars[i] = " "
41
+ return "".join(chars)
42
+
43
+
44
+ def _masked_regions(text: str) -> list[tuple[int, int]]:
45
+ regions = list(_fenced_regions(text))
46
+ blanked = _blank(text, regions)
47
+
48
+ # Comments and code spans are found in text that already has fences removed,
49
+ # so a "<!--" inside a code block cannot open a comment.
50
+ for m in _HTML_COMMENT_RE.finditer(blanked):
51
+ regions.append((m.start(), m.end()))
52
+ blanked = _blank(blanked, regions)
53
+
54
+ for m in _CODE_SPAN_RE.finditer(blanked):
55
+ if "\n\n" in m.group(0): # a code span cannot span a blank line
56
+ continue
57
+ regions.append((m.start(), m.end()))
58
+ return regions
59
+
60
+
61
+ def _blank(text: str, regions: list[tuple[int, int]]) -> str:
62
+ chars = list(text)
63
+ for start, end in regions:
64
+ for i in range(start, end):
65
+ if chars[i] != "\n":
66
+ chars[i] = " "
67
+ return "".join(chars)
68
+
69
+
70
+ def _fenced_regions(text: str):
71
+ """Yield (start, end) for each fenced code block, closed or not."""
72
+ open_fence: str | None = None
73
+ open_start = 0
74
+ offset = 0
75
+ for line in text.splitlines(keepends=True):
76
+ stripped = line.rstrip("\r\n")
77
+ m = _FENCE_RE.match(stripped)
78
+ if open_fence is None:
79
+ if m and not m.group("info").strip().startswith(m.group("fence")[0]):
80
+ open_fence = m.group("fence")
81
+ open_start = offset
82
+ else:
83
+ # A closer is the same character, at least as long, with no info string.
84
+ if (
85
+ m
86
+ and m.group("fence")[0] == open_fence[0]
87
+ and len(m.group("fence")) >= len(open_fence)
88
+ and not m.group("info").strip()
89
+ ):
90
+ yield (open_start, offset + len(line))
91
+ open_fence = None
92
+ offset += len(line)
93
+ if open_fence is not None: # unterminated fence runs to end of file
94
+ yield (open_start, len(text))
95
+
96
+
97
+ def find_fences(text: str):
98
+ """Yield (info, body, span_start, span_end) for each fenced code block.
99
+
100
+ Runs on unmasked text, since the point is to look *inside* a fence. Nested
101
+ fences are not reported separately: `_fenced_regions` already pairs an
102
+ opener with its closer, so an inner fence is part of the outer body.
103
+ """
104
+ for start, end in _fenced_regions(text):
105
+ block = text[start:end]
106
+ lines = block.splitlines(keepends=True)
107
+ if not lines:
108
+ continue
109
+ opener = _FENCE_RE.match(lines[0].rstrip("\r\n"))
110
+ if opener is None:
111
+ continue
112
+ # The closing fence is the last line unless the block is unterminated.
113
+ closes = len(lines) > 1 and _FENCE_RE.match(lines[-1].rstrip("\r\n"))
114
+ body = "".join(lines[1:-1] if closes else lines[1:])
115
+ yield opener.group("info").strip(), body, start, end
116
+
117
+
118
+ def line_col(text: str, offset: int) -> tuple[int, int]:
119
+ """1-indexed line and column for a byte offset."""
120
+ line = text.count("\n", 0, offset) + 1
121
+ last_nl = text.rfind("\n", 0, offset)
122
+ return line, offset - last_nl
123
+
124
+
125
+ def find_headings(masked: str):
126
+ """Yield (level, text, span_start, span_end) for each ATX heading."""
127
+ for m in _ATX_HEADING_RE.finditer(masked):
128
+ text = m.group("text")
129
+ # Drop a closing hash run, then any trailing block anchor.
130
+ text = re.sub(r"[ \t]+#+[ \t]*$", "", text)
131
+ text = re.sub(r"[ \t]+\^[A-Za-z0-9][A-Za-z0-9_-]{0,63}[ \t]*$", "", text)
132
+ yield len(m.group("hashes")), text.strip(), m.start(), m.end()
133
+
134
+
135
+ def find_anchors(masked: str):
136
+ """Yield (block_id, span_start, span_end) for each trailing ``^id``."""
137
+ for m in _ANCHOR_RE.finditer(masked):
138
+ yield m.group("id"), m.start(), m.end()
139
+
140
+
141
+ def find_links(masked: str):
142
+ """Yield (bang, inner, span_start, span_end) for each well-formed link."""
143
+ for m in _LINK_RE.finditer(masked):
144
+ yield m.group("bang") == "!", m.group("inner"), m.start(), m.end()
145
+
146
+
147
+ def find_unterminated(masked: str):
148
+ """Yield the offset of every ``[[`` that does not open a complete link."""
149
+ closed = {m.start() + (1 if m.group("bang") else 0) for m in _LINK_RE.finditer(masked)}
150
+ for m in _OPEN_RE.finditer(masked):
151
+ start = m.start() + (1 if m.group(0).startswith("!") else 0)
152
+ if start not in closed:
153
+ yield m.start()
hypermarkdown/urls.py ADDED
@@ -0,0 +1,60 @@
1
+ """The URL policy (HMD-0002 §1).
2
+
3
+ One card, one URL, computed in exactly one place. A card at `a/b.hmd` and a
4
+ folder note at `a/b/index.hmd` both serve at `a/b/`, because §5.1 of HMD-0001
5
+ already makes the two names address the same page — two names for one page must
6
+ not become two URLs for one page.
7
+
8
+ Everything here is pure path arithmetic on root-relative parts. Nothing touches
9
+ the filesystem, so a URL is the same on every platform and in every run (P1).
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import posixpath
15
+ from pathlib import Path
16
+
17
+ INDEX_STEM = "index"
18
+
19
+
20
+ def parts_for(root: Path, path: Path) -> tuple[str, ...]:
21
+ """The addressable parts of a page: root-relative, suffix and `index` gone."""
22
+ parts = path.relative_to(root).with_suffix("").parts
23
+ if len(parts) > 1 and parts[-1] == INDEX_STEM:
24
+ parts = parts[:-1]
25
+ return parts
26
+
27
+
28
+ def url_for(root: Path, path: Path) -> str:
29
+ """The site path of a page, as an absolute URL path: `a/b/` or `` for home."""
30
+ parts = parts_for(root, path)
31
+ if not parts or parts == (INDEX_STEM,):
32
+ return ""
33
+ return "/".join(parts) + "/"
34
+
35
+
36
+ def dest_for(root: Path, path: Path) -> str:
37
+ """The MkDocs source path a page is registered under: always a `.md` file.
38
+
39
+ MkDocs matches a fixed extension set that does not include `.hmd`, so a page
40
+ enters the build under a name MkDocs already understands. Directory URLs then
41
+ turn `a/b.md` into `a/b/index.html` on their own.
42
+ """
43
+ parts = parts_for(root, path)
44
+ if not parts:
45
+ return f"{INDEX_STEM}.md"
46
+ return "/".join(parts) + ".md"
47
+
48
+
49
+ def href_for(root: Path, source: Path, target: Path) -> str:
50
+ """A link from one page to another, relative to the *source path*.
51
+
52
+ Deliberately not relative to `url_for`. MkDocs resolves and validates every
53
+ link against the source tree and computes the final URL itself, so handing
54
+ it a source-relative `.md` path gets `../kanban/` for free — and gets the
55
+ link checked. Emitting the finished URL instead would bypass validation and
56
+ duplicate arithmetic MkDocs is already doing.
57
+ """
58
+ destination = dest_for(root, target)
59
+ directory = posixpath.dirname(dest_for(root, source))
60
+ return posixpath.relpath(destination, directory or ".")