hypermarkdown 0.3.1__tar.gz → 0.4.0__tar.gz

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.
Files changed (32) hide show
  1. {hypermarkdown-0.3.1 → hypermarkdown-0.4.0}/CHANGELOG.md +46 -0
  2. {hypermarkdown-0.3.1/src/hypermarkdown.egg-info → hypermarkdown-0.4.0}/PKG-INFO +7 -5
  3. {hypermarkdown-0.3.1 → hypermarkdown-0.4.0}/README.md +6 -4
  4. {hypermarkdown-0.3.1 → hypermarkdown-0.4.0}/src/hypermarkdown/__init__.py +1 -1
  5. {hypermarkdown-0.3.1 → hypermarkdown-0.4.0}/src/hypermarkdown/cli.py +3 -3
  6. {hypermarkdown-0.3.1 → hypermarkdown-0.4.0}/src/hypermarkdown/config.py +2 -1
  7. {hypermarkdown-0.3.1 → hypermarkdown-0.4.0}/src/hypermarkdown/embed.py +7 -2
  8. {hypermarkdown-0.3.1 → hypermarkdown-0.4.0}/src/hypermarkdown/lint/rules.py +42 -5
  9. {hypermarkdown-0.3.1 → hypermarkdown-0.4.0}/src/hypermarkdown/mkdocs_plugin.py +135 -25
  10. {hypermarkdown-0.3.1 → hypermarkdown-0.4.0}/src/hypermarkdown/model.py +13 -1
  11. {hypermarkdown-0.3.1 → hypermarkdown-0.4.0}/src/hypermarkdown/parse.py +38 -1
  12. {hypermarkdown-0.3.1 → hypermarkdown-0.4.0}/src/hypermarkdown/resolve.py +75 -26
  13. {hypermarkdown-0.3.1 → hypermarkdown-0.4.0/src/hypermarkdown.egg-info}/PKG-INFO +7 -5
  14. {hypermarkdown-0.3.1 → hypermarkdown-0.4.0}/LICENSE +0 -0
  15. {hypermarkdown-0.3.1 → hypermarkdown-0.4.0}/MANIFEST.in +0 -0
  16. {hypermarkdown-0.3.1 → hypermarkdown-0.4.0}/pyproject.toml +0 -0
  17. {hypermarkdown-0.3.1 → hypermarkdown-0.4.0}/setup.cfg +0 -0
  18. {hypermarkdown-0.3.1 → hypermarkdown-0.4.0}/src/hypermarkdown/diagram.py +0 -0
  19. {hypermarkdown-0.3.1 → hypermarkdown-0.4.0}/src/hypermarkdown/frontmatter.py +0 -0
  20. {hypermarkdown-0.3.1 → hypermarkdown-0.4.0}/src/hypermarkdown/graph.py +0 -0
  21. {hypermarkdown-0.3.1 → hypermarkdown-0.4.0}/src/hypermarkdown/imports.py +0 -0
  22. {hypermarkdown-0.3.1 → hypermarkdown-0.4.0}/src/hypermarkdown/lint/__init__.py +0 -0
  23. {hypermarkdown-0.3.1 → hypermarkdown-0.4.0}/src/hypermarkdown/lint/report.py +0 -0
  24. {hypermarkdown-0.3.1 → hypermarkdown-0.4.0}/src/hypermarkdown/render/__init__.py +0 -0
  25. {hypermarkdown-0.3.1 → hypermarkdown-0.4.0}/src/hypermarkdown/render/flat.py +0 -0
  26. {hypermarkdown-0.3.1 → hypermarkdown-0.4.0}/src/hypermarkdown/scan.py +0 -0
  27. {hypermarkdown-0.3.1 → hypermarkdown-0.4.0}/src/hypermarkdown/urls.py +0 -0
  28. {hypermarkdown-0.3.1 → hypermarkdown-0.4.0}/src/hypermarkdown.egg-info/SOURCES.txt +0 -0
  29. {hypermarkdown-0.3.1 → hypermarkdown-0.4.0}/src/hypermarkdown.egg-info/dependency_links.txt +0 -0
  30. {hypermarkdown-0.3.1 → hypermarkdown-0.4.0}/src/hypermarkdown.egg-info/entry_points.txt +0 -0
  31. {hypermarkdown-0.3.1 → hypermarkdown-0.4.0}/src/hypermarkdown.egg-info/requires.txt +0 -0
  32. {hypermarkdown-0.3.1 → hypermarkdown-0.4.0}/src/hypermarkdown.egg-info/top_level.txt +0 -0
@@ -13,6 +13,34 @@ only for the Python API.
13
13
 
14
14
  ## [Unreleased]
15
15
 
16
+ ## [0.4.0] — 2026-11-15
17
+
18
+ ### Added
19
+ - **Markdown files are cards** ([HMD-0029](https://github.com/ewiger/hypermarkdown/blob/main/doc/proposals/HMD-0029/README.md)).
20
+ A `.md` or `.markdown` file below the namespace root loads as a Markdown card:
21
+ `[[guide]]` resolves to `guide.md`, `[[guide#Install]]` checks its headings,
22
+ and `![[guide]]` transcludes its body. Its body is not scanned and not
23
+ linted, and its frontmatter is exposed but not interpreted. Binding tries
24
+ `.hmd`, `.md`, `.markdown`, then the folder note in the same order, and
25
+ `[[owl.md]]` binds only `owl.md`. `hmd lint` accepts `.md` and `.markdown`
26
+ paths.
27
+ - **HMD018**, a warning: a card shadows a card of the same name with a later
28
+ extension, as `owl.hmd` beside `owl.md`.
29
+ - The MkDocs plugin links a card to the page MkDocs builds from a Markdown
30
+ card, and never registers one itself; a Markdown card outside `docs_dir` is
31
+ a red link.
32
+
33
+ ### Changed
34
+ - A `.md` file inside the namespace is no longer invisible: a reference that
35
+ was HMD001 can resolve, and a bare name it shares with a card found by the
36
+ sweep is HMD002.
37
+
38
+ ### Fixed
39
+ - **A heading right below the frontmatter fence is a heading.** The fence was
40
+ blanked together with its line breaks, so the first body line read as
41
+ indented: `# Title` directly under `---` produced no heading, and a fragment
42
+ naming it was HMD004.
43
+
16
44
  ## [0.3.1] — 2026-11-13
17
45
 
18
46
  ### Fixed
@@ -26,6 +54,24 @@ only for the Python API.
26
54
  directory inside a nested vault is HMD015, the same as a missing directory.
27
55
  Linting the nested vault with `--root` set to it, or from a card inside it,
28
56
  is unchanged.
57
+ - **A folder note's ordinary Markdown links reach their targets on a built
58
+ site.** The MkDocs plugin registers `a/b/index.hmd` as the page `a/b.md`, one
59
+ directory above the file, and rewrote its wikilinks for that place but left
60
+ its relative Markdown links as written, so MkDocs resolved them from `a/`.
61
+ A link to a sibling card, such as `` [`Bool`](bool.hmd) ``, reached the site
62
+ as a link to a source file that is not served, and a link to a plain page or
63
+ an image pointed one directory too high. Every relative link in a folder
64
+ note is now resolved from the file's own directory and rewritten for the
65
+ registered page: inline links, images, and reference definitions. A card
66
+ that is not a folder note is unchanged. A site that worked around this by
67
+ writing a folder note's links against the parent directory has to write
68
+ them against the file's own directory again.
69
+
70
+ ### Changed
71
+ - **A Markdown link to a card is repointed in more spellings.** A link to a
72
+ `.hmd` file with a title, `[card](one.hmd "Title")`, and one given as a
73
+ reference definition, `[card]: one.hmd`, now reach the card's page. Before,
74
+ only the bare inline form did.
29
75
 
30
76
  ## [0.3.0] — 2026-09-14
31
77
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: hypermarkdown
3
- Version: 0.3.1
3
+ Version: 0.4.0
4
4
  Summary: A strict, machine-checkable markdown dialect for project knowledge bases.
5
5
  Author: Yauhen Yakimovich
6
6
  License-Expression: MIT
@@ -154,10 +154,12 @@ Every other key is yours, and nothing will inspect it.
154
154
  | `hmd info` | Show the resolved root and discovery policy |
155
155
  | `hmd --version` | Print the installed version |
156
156
 
157
- Every command but `init` takes `--root` to override the namespace root, which
158
- otherwise comes from the `wiki` setting in `.hmd/config.toml` (defaulting to
159
- `doc/wiki`). A `.hmd/` directory doubles as the project root marker, so any
160
- subtree can be self-contained.
157
+ The `wiki` setting in `.hmd/config.toml` is the cards location: where inside
158
+ the vault, the directory holding `.hmd/`, the cards start (`doc/wiki` by
159
+ default, `.` for directly under the vault). The directory it names is the
160
+ namespace root, and every command but `init` takes `--root` to override it. A
161
+ `.hmd/` directory doubles as the project root marker, so any subtree can be
162
+ self-contained.
161
163
 
162
164
  ```bash
163
165
  hmd init # here; the namespace is named after the directory
@@ -116,10 +116,12 @@ Every other key is yours, and nothing will inspect it.
116
116
  | `hmd info` | Show the resolved root and discovery policy |
117
117
  | `hmd --version` | Print the installed version |
118
118
 
119
- Every command but `init` takes `--root` to override the namespace root, which
120
- otherwise comes from the `wiki` setting in `.hmd/config.toml` (defaulting to
121
- `doc/wiki`). A `.hmd/` directory doubles as the project root marker, so any
122
- subtree can be self-contained.
119
+ The `wiki` setting in `.hmd/config.toml` is the cards location: where inside
120
+ the vault, the directory holding `.hmd/`, the cards start (`doc/wiki` by
121
+ default, `.` for directly under the vault). The directory it names is the
122
+ namespace root, and every command but `init` takes `--root` to override it. A
123
+ `.hmd/` directory doubles as the project root marker, so any subtree can be
124
+ self-contained.
123
125
 
124
126
  ```bash
125
127
  hmd init # here; the namespace is named after the directory
@@ -15,7 +15,7 @@ from .config import Config, ConfigError
15
15
  from .model import Diagnostic, Document, Link, Span
16
16
  from .resolve import Outcome, Resolution, Workspace
17
17
 
18
- __version__ = "0.3.1"
18
+ __version__ = "0.4.0"
19
19
 
20
20
  __all__ = [
21
21
  "Config",
@@ -20,7 +20,7 @@ from . import graph as graph_mod
20
20
  from .lint import check, format_json, format_text, summarize
21
21
  from .model import Diagnostic
22
22
  from .render import flat
23
- from .resolve import SUFFIX, Workspace
23
+ from .resolve import CARD_SUFFIXES, Workspace, card_suffix
24
24
 
25
25
  app = typer.Typer(
26
26
  add_completion=False,
@@ -79,13 +79,13 @@ def _selected(workspace: Workspace, paths: list[Path] | None) -> list[Path] | No
79
79
  candidate = raw.resolve()
80
80
  if candidate.is_dir():
81
81
  selected.extend(p for p in workspace.pages() if candidate in p.parents or candidate == p.parent)
82
- elif candidate.suffix == SUFFIX:
82
+ elif card_suffix(candidate.name):
83
83
  if candidate not in workspace.documents:
84
84
  typer.echo(f"hmd: not inside the namespace root: {raw}", err=True)
85
85
  raise typer.Exit(EXIT_USAGE)
86
86
  selected.append(candidate)
87
87
  else:
88
- typer.echo(f"hmd: not a {SUFFIX} file or directory: {raw}", err=True)
88
+ typer.echo(f"hmd: not a card ({', '.join(CARD_SUFFIXES)}) or directory: {raw}", err=True)
89
89
  raise typer.Exit(EXIT_USAGE)
90
90
  return sorted(set(selected))
91
91
 
@@ -36,7 +36,8 @@ CONFIG_TEMPLATE = """\
36
36
  # `.git/`. Only the settings below are read; every other key is ignored, so the
37
37
  # file is safe to extend.
38
38
 
39
- # The namespace root, relative to this project root. Every `.hmd` card beneath
39
+ # The cards location: where inside this project the cards start, relative to
40
+ # this project root. It names the namespace root. Every `.hmd` card beneath
40
41
  # it is a page, and links resolve within it. Nothing outside it is checked.
41
42
  wiki = "{wiki}"
42
43
 
@@ -74,8 +74,13 @@ def expand(
74
74
 
75
75
 
76
76
  def body_region(document: Document) -> tuple[int, int]:
77
- """The document minus its frontmatter fence."""
78
- _raw, _body, offset = split_frontmatter(document.text)
77
+ """The document minus its frontmatter fence.
78
+
79
+ A Markdown card whose fence did not parse kept it as body text (HMD-0029).
80
+ """
81
+ raw, _body, offset = split_frontmatter(document.text)
82
+ if document.is_markdown and raw is not None and not document.frontmatter:
83
+ return 0, len(document.text)
79
84
  return offset, len(document.text)
80
85
 
81
86
 
@@ -10,7 +10,7 @@ from pathlib import Path
10
10
 
11
11
  from ..embed import MAX_EMBED_DEPTH
12
12
  from ..model import ERROR, WARNING, Diagnostic, Document, Link
13
- from ..resolve import INDEX_STEM, SUFFIX, Outcome, Workspace
13
+ from ..resolve import CARD_SUFFIXES, INDEX_STEM, Outcome, Workspace
14
14
 
15
15
  SEVERITY = {
16
16
  "HMD001": WARNING,
@@ -30,6 +30,7 @@ SEVERITY = {
30
30
  "HMD015": ERROR,
31
31
  "HMD016": WARNING,
32
32
  "HMD017": WARNING,
33
+ "HMD018": WARNING,
33
34
  }
34
35
 
35
36
 
@@ -42,6 +43,10 @@ def check(workspace: Workspace, paths: list[Path] | None = None) -> list[Diagnos
42
43
  document = workspace.documents.get(path)
43
44
  if document is None:
44
45
  continue
46
+ if document.is_markdown:
47
+ # HMD-0029: a Markdown card is not checked; no diagnostic comes
48
+ # from its body.
49
+ continue
45
50
  diagnostics.extend(document.diagnostics) # HMD009, HMD010, HMD013, HMD014
46
51
  diagnostics.extend(_duplicate_anchors(workspace, document))
47
52
  diagnostics.extend(_duplicate_slugs(workspace, document))
@@ -49,6 +54,7 @@ def check(workspace: Workspace, paths: list[Path] | None = None) -> list[Diagnos
49
54
  diagnostics.extend(_links(workspace, document))
50
55
 
51
56
  diagnostics.extend(_folder_note_collisions(workspace, targets))
57
+ diagnostics.extend(_shadowed(workspace, targets))
52
58
  diagnostics.extend(_embed_cycles(workspace, targets))
53
59
 
54
60
  diagnostics.sort(key=Diagnostic.sort_key)
@@ -188,11 +194,21 @@ def _fragment(workspace: Workspace, document: Document, link: Link, target: Path
188
194
 
189
195
 
190
196
  def _folder_note_collisions(workspace: Workspace, targets: list[Path]):
191
- """HMD012 — `foo.hmd` beside `foo/index.hmd`."""
197
+ """HMD012 — `foo.hmd` beside `foo/index.hmd`, of any card extensions."""
192
198
  wanted = set(targets)
193
199
  for page in workspace.pages():
194
- note = page.with_suffix("") / f"{INDEX_STEM}{SUFFIX}"
195
- if note not in workspace.documents:
200
+ if page in workspace.shadowed:
201
+ continue
202
+ directory = page.parent / workspace.parts(page)[-1]
203
+ note = next(
204
+ (
205
+ directory / f"{INDEX_STEM}{suffix}"
206
+ for suffix in CARD_SUFFIXES
207
+ if directory / f"{INDEX_STEM}{suffix}" in workspace.documents
208
+ ),
209
+ None,
210
+ )
211
+ if note is None:
196
212
  continue
197
213
  if page not in wanted and note not in wanted:
198
214
  continue
@@ -204,7 +220,28 @@ def _folder_note_collisions(workspace: Workspace, targets: list[Path]):
204
220
  1,
205
221
  1,
206
222
  f"{rel} and {workspace.rel(note)} both claim the name "
207
- f"'{page.with_suffix('').relative_to(workspace.root).as_posix()}'; the file wins",
223
+ f"'{'/'.join(workspace.parts(page))}'; the file wins",
224
+ )
225
+
226
+
227
+ def _shadowed(workspace: Workspace, targets: list[Path]):
228
+ """HMD018 — a card shadows one of the same name with a later extension."""
229
+ wanted = set(targets)
230
+ for loser, winner in sorted(workspace.shadowed.items()):
231
+ if loser not in wanted and winner not in wanted:
232
+ continue
233
+ rel = workspace.rel(loser)
234
+ parts = workspace.parts(loser)
235
+ if len(parts) > 1 and parts[-1] == INDEX_STEM:
236
+ parts = parts[:-1] # a folder note is named by its directory
237
+ name = "/".join(parts)
238
+ yield Diagnostic(
239
+ "HMD018",
240
+ SEVERITY["HMD018"],
241
+ rel,
242
+ 1,
243
+ 1,
244
+ f"{workspace.rel(winner)} shadows {rel}; [[{name}]] means {workspace.rel(winner)}",
208
245
  )
209
246
 
210
247
 
@@ -35,10 +35,19 @@ from .resolve import Workspace
35
35
  #: authored book nav can say *where* the generated pages go.
36
36
  NAV_PLACEHOLDER = "hmd://wiki"
37
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]*)?\)")
38
+ #: The destination of an inline markdown link or image: what follows `](`, up
39
+ #: to a space (where a title starts) or the closing parenthesis. A destination
40
+ #: in angle brackets is not matched, and stays as written.
41
+ _INLINE_HREF_RE = re.compile(r"\]\((?P<href>[^)\s<>]+)")
42
+
43
+ #: The destination of a reference definition, `[label]: path`. A footnote
44
+ #: definition, `[^label]: text`, has the same shape and is not one.
45
+ _REFERENCE_HREF_RE = re.compile(
46
+ r"^[ ]{0,3}\[(?!\^)[^\]\n]+\]:[ \t]*(?P<href>[^\s<>]+)", re.MULTILINE
47
+ )
48
+
49
+ #: `https:`, `mailto:`, and every other scheme: a destination that is not a path.
50
+ _SCHEME_RE = re.compile(r"^[A-Za-z][A-Za-z0-9+.-]*:")
42
51
 
43
52
 
44
53
  class PluginConfig(BaseConfig):
@@ -81,6 +90,11 @@ class HyperMarkDownPlugin(BasePlugin[PluginConfig]):
81
90
  self.prefix = _prefix(docs_dir, self.workspace.root)
82
91
 
83
92
  for path in self.workspace.pages():
93
+ if self.workspace.documents[path].is_markdown:
94
+ # HMD-0029: a Markdown card is never registered by the plugin.
95
+ # MkDocs already builds it if it sits in `docs_dir`, and a
96
+ # second registration would collide with that page.
97
+ continue
84
98
  # Publication is opt-in (§2). An unpublished card is not registered
85
99
  # at all: no file, no URL, nothing about it in `site/`. Skipping it
86
100
  # here is what makes that true everywhere downstream — nav derives
@@ -186,15 +200,21 @@ class HyperMarkDownPlugin(BasePlugin[PluginConfig]):
186
200
  if self.workspace is None:
187
201
  return markdown
188
202
 
203
+ registered = posixpath.dirname(page.file.src_uri)
189
204
  source = self.sources.get(page.file.src_uri)
190
205
  if source is None:
191
206
  # Not a card. It may still link *to* one — a book page or a proposal
192
207
  # writes an ordinary relative link to a `.hmd` file, because a
193
208
  # wikilink does not work from outside the namespace — and it may
194
209
  # carry diagrams of its own.
195
- return self._diagrams(self._link_to_cards(markdown, page.file.src_uri))
210
+ return self._diagrams(self._relink(markdown, registered, registered))
196
211
 
197
212
  root = self.workspace.root
213
+ # A folder note `a/b/index.hmd` is registered as `a/b.md`, one directory
214
+ # above the file. Its ordinary links were written against `a/b/`, so the
215
+ # whole page is kept relative to that directory until `_relink` moves
216
+ # every link at once — the wikilinks rewritten below included.
217
+ written = self._written_dir(source, registered)
198
218
 
199
219
  def rewrite(link: Link, target: Path | None) -> str:
200
220
  text = link.display or link.page_ref
@@ -210,7 +230,20 @@ class HyperMarkDownPlugin(BasePlugin[PluginConfig]):
210
230
  return (
211
231
  f'<a class="hmd-redlink" title="{link.target} is not published">{text}</a>'
212
232
  )
233
+ if self.workspace.documents[target].is_markdown:
234
+ # The page MkDocs builds from the file itself, if it builds one.
235
+ served = self._served(target)
236
+ if served is None:
237
+ return (
238
+ f'<a class="hmd-redlink" title="{link.target} is not published">{text}</a>'
239
+ )
240
+ href = _relative(served, written)
241
+ if link.fragment is not None and link.fragment_kind == "heading":
242
+ href = f"{href}#{slug_for(link.fragment, set())}"
243
+ return f"[{text}]({href})"
213
244
  href = urls.href_for(root, source, target)
245
+ if written != registered:
246
+ href = _relative(posixpath.normpath(posixpath.join(registered, href)), written)
214
247
  if link.fragment is not None and link.fragment_kind == "heading":
215
248
  href = f"{href}#{slug_for(link.fragment, set())}"
216
249
  return f"[{text}]({href})"
@@ -218,7 +251,21 @@ class HyperMarkDownPlugin(BasePlugin[PluginConfig]):
218
251
  expanded = expand(
219
252
  self.workspace, source, rewrite=rewrite, can_embed=self.workspace.is_public
220
253
  ).text
221
- return self._diagrams(self._link_to_cards(expanded, page.file.src_uri))
254
+ return self._diagrams(self._relink(expanded, written, registered))
255
+
256
+ def _written_dir(self, source: Path, registered: str) -> str:
257
+ """The directory a card's own relative links were written against.
258
+
259
+ That is the directory of the `.hmd` file inside `docs_dir`. It differs
260
+ from the registered page's directory for a folder note only. A card
261
+ outside `docs_dir` has no such directory, and keeps the registered one.
262
+ """
263
+ assert self.docs_dir is not None
264
+ try:
265
+ directory = source.parent.relative_to(self.docs_dir).as_posix()
266
+ except ValueError:
267
+ return registered
268
+ return "" if directory == "." else directory
222
269
 
223
270
  def _diagrams(self, markdown: str) -> str:
224
271
  """Render `d2` fences to images, or to a labelled placeholder.
@@ -242,38 +289,86 @@ class HyperMarkDownPlugin(BasePlugin[PluginConfig]):
242
289
  out.append(markdown[cursor:])
243
290
  return "".join(out)
244
291
 
245
- def _link_to_cards(self, markdown: str, src_uri: str) -> str:
246
- """Point ordinary markdown links at the page a `.hmd` file becomes.
292
+ def _relink(self, markdown: str, written: str, registered: str) -> str:
293
+ """Move a page's ordinary relative links to the place it is registered.
247
294
 
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.
295
+ Each link is resolved from `written`, the directory it was written
296
+ against, and rewritten relative to `registered`, the directory of the
297
+ page MkDocs builds. Two things happen on the way:
252
298
 
253
- Masked first, so a `.hmd` path quoted inside a fence stays quoted.
299
+ - A link to a `.hmd` card becomes a link to the page that card is
300
+ registered as. The written path is a real file, which is what makes
301
+ it work when the repository is browsed on its own. The built site
302
+ does not serve `.hmd` sources, so the same link has to arrive at the
303
+ rendered card instead of 404ing.
304
+ - On a folder note, where the two directories differ, a link to any
305
+ other file is rewritten to name the same file from the new place.
306
+
307
+ Inline links, images, and reference definitions are covered. Masked
308
+ first, so a path quoted inside a fence or a code span stays quoted.
254
309
  """
255
310
  masked = scan.mask(markdown)
256
- directory = posixpath.dirname(src_uri)
311
+ matches = sorted(
312
+ (
313
+ *_INLINE_HREF_RE.finditer(masked),
314
+ *_REFERENCE_HREF_RE.finditer(masked),
315
+ ),
316
+ key=lambda match: match.start("href"),
317
+ )
257
318
  out: list[str] = []
258
319
  cursor = 0
259
320
 
260
- for match in _HMD_HREF_RE.finditer(masked):
261
- dest = self._card_at(directory, match.group("href"))
262
- if dest is None:
321
+ for match in matches:
322
+ if match.start("href") < cursor:
323
+ continue
324
+ href = self._moved(match.group("href"), written, registered)
325
+ if href is None:
263
326
  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()
327
+ out.append(markdown[cursor : match.start("href")])
328
+ out.append(href)
329
+ cursor = match.end("href")
268
330
 
269
331
  out.append(markdown[cursor:])
270
332
  return "".join(out)
271
333
 
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://", "/")):
334
+ def _moved(self, href: str, written: str, registered: str) -> str | None:
335
+ """One destination as it reads from `registered`, or None to keep it.
336
+
337
+ A scheme link, a site-absolute path, and a fragment on the same page
338
+ mean the same thing wherever the page sits, so they are kept.
339
+ """
340
+ if _SCHEME_RE.match(href) or href.startswith(("/", "#", "?")):
341
+ return None
342
+ cut = min((i for i in (href.find("#"), href.find("?")) if i != -1), default=len(href))
343
+ path, tail = href[:cut], href[cut:]
344
+ target = posixpath.normpath(posixpath.join(written, path))
345
+
346
+ dest = self._card_at(target)
347
+ if dest is not None:
348
+ return _relative(dest, registered) + tail
349
+ if written == registered:
350
+ return None
351
+ moved = _relative(target, registered)
352
+ if path.endswith("/") and not moved.endswith("/"):
353
+ moved += "/"
354
+ return moved + tail
355
+
356
+ def _served(self, target: Path) -> str | None:
357
+ """The `docs_dir`-relative source path of a Markdown card, or None.
358
+
359
+ None when the file lies outside `docs_dir`, where MkDocs builds no page.
360
+ """
361
+ if self.docs_dir is None:
362
+ return None
363
+ try:
364
+ return target.resolve().relative_to(self.docs_dir).as_posix()
365
+ except ValueError:
366
+ return None
367
+
368
+ def _card_at(self, target: str) -> str | None:
369
+ """The registered page for a `.hmd` file in `docs_dir`, or None."""
370
+ if self.docs_dir is None or not target.endswith(".hmd"):
275
371
  return None
276
- target = Path(posixpath.normpath(posixpath.join(directory, href)))
277
372
  return self.destinations.get((self.docs_dir / target).resolve())
278
373
 
279
374
  # -- serving ---------------------------------------------------------
@@ -298,6 +393,21 @@ def _prefix(docs_dir: Path, root: Path) -> str:
298
393
  return "" if relative == "." else relative
299
394
 
300
395
 
396
+ def _relative(target: str, directory: str) -> str:
397
+ """`target` as a path relative to `directory`, both relative to `docs_dir`.
398
+
399
+ Pure arithmetic on normalized paths. `posixpath.relpath` would anchor both
400
+ at the working directory first, and a target above `docs_dir` then depends
401
+ on how deep that directory happens to be.
402
+ """
403
+ parts = target.split("/")
404
+ base = directory.split("/") if directory else []
405
+ shared = 0
406
+ while shared < min(len(parts), len(base)) and parts[shared] == base[shared]:
407
+ shared += 1
408
+ return "/".join([".."] * (len(base) - shared) + parts[shared:]) or "."
409
+
410
+
301
411
  def _splice(node, derived: list):
302
412
  """Replace every `hmd://wiki` in an authored nav with the derived section.
303
413
 
@@ -134,9 +134,15 @@ class Diagnostic:
134
134
  return out
135
135
 
136
136
 
137
+ # Card kinds (HMD-0029). A HyperMarkdown card is scanned and checked; a
138
+ # Markdown card is addressable and has headings, and its body is CommonMark.
139
+ HMD = "hmd"
140
+ MARKDOWN = "markdown"
141
+
142
+
137
143
  @dataclass
138
144
  class Document:
139
- """One parsed `.hmd` file."""
145
+ """One parsed card: a `.hmd` file, or a `.md` or `.markdown` file."""
140
146
 
141
147
  path: Path
142
148
  text: str
@@ -147,6 +153,12 @@ class Document:
147
153
  links: tuple[Link, ...] = ()
148
154
  # Diagnostics discovered at parse time (HMD009, HMD010, HMD013, HMD014).
149
155
  diagnostics: list[Diagnostic] = field(default_factory=list)
156
+ #: `HMD` or `MARKDOWN`.
157
+ kind: str = HMD
158
+
159
+ @property
160
+ def is_markdown(self) -> bool:
161
+ return self.kind == MARKDOWN
150
162
 
151
163
  def heading_slugs(self) -> set[str]:
152
164
  return {h.slug for h in self.headings}
@@ -15,6 +15,7 @@ from .model import (
15
15
  CardConfig,
16
16
  Diagnostic,
17
17
  Document,
18
+ MARKDOWN,
18
19
  Heading,
19
20
  Link,
20
21
  Span,
@@ -54,7 +55,7 @@ def parse(path: Path, text: str, rel: str) -> Document:
54
55
  diagnostics.append(Diagnostic(rule, ERROR, rel, 1, 1, message))
55
56
 
56
57
  # Mask the body only; frontmatter is YAML, not markdown.
57
- masked = " " * body_offset + scan.mask(text[body_offset:])
58
+ masked = _blank(text[:body_offset]) + scan.mask(text[body_offset:])
58
59
 
59
60
  headings = _headings(text, masked)
60
61
  anchors = _anchors(text, masked)
@@ -73,6 +74,42 @@ def parse(path: Path, text: str, rel: str) -> Document:
73
74
  )
74
75
 
75
76
 
77
+ def parse_markdown(path: Path, text: str, rel: str) -> Document:
78
+ """Read one Markdown card (HMD-0029): frontmatter and headings, nothing else.
79
+
80
+ The body is CommonMark and is not scanned, so it yields no link, embed or
81
+ block anchor. A frontmatter block is exposed as data and none of its keys is
82
+ interpreted; one that does not parse as a mapping is body text, and is not
83
+ reported, because the author did not write HyperMarkdown.
84
+ """
85
+ raw_yaml, _body, body_offset = split_frontmatter(text)
86
+ frontmatter: dict = {}
87
+ if raw_yaml is not None:
88
+ try:
89
+ frontmatter = parse_yaml(raw_yaml)
90
+ except ValueError:
91
+ body_offset = 0
92
+
93
+ masked = _blank(text[:body_offset]) + scan.mask(text[body_offset:])
94
+ return Document(
95
+ path=path,
96
+ text=text,
97
+ frontmatter=frontmatter,
98
+ card=CardConfig(),
99
+ headings=_headings(text, masked),
100
+ kind=MARKDOWN,
101
+ )
102
+
103
+
104
+ def _blank(frontmatter: str) -> str:
105
+ """The frontmatter as blanks of the same length, its line breaks kept.
106
+
107
+ Blanking the line breaks too would join the fence to the first body line,
108
+ which then reads as indented and loses a heading written right below `---`.
109
+ """
110
+ return re.sub(r"[^\r\n]", " ", frontmatter)
111
+
112
+
76
113
  def _span(text: str, start: int, end: int) -> Span:
77
114
  line, column = scan.line_col(text, start)
78
115
  return Span(start=start, end=end, line=line, column=column)
@@ -15,12 +15,23 @@ from pathlib import Path
15
15
 
16
16
  from .config import MARKER_DIR, Config
17
17
  from .model import PRIVATE, PUBLIC, Document, ImportStmt
18
- from .parse import parse
18
+ from .parse import parse, parse_markdown
19
19
 
20
20
  SUFFIX = ".hmd"
21
+ #: The card extensions in priority order (HMD-0029): where two files compete for
22
+ #: one name, the earlier extension wins.
23
+ CARD_SUFFIXES = (".hmd", ".md", ".markdown")
21
24
  INDEX_STEM = "index"
22
25
 
23
26
 
27
+ def card_suffix(name: str) -> str | None:
28
+ """The card extension `name` ends in, or None."""
29
+ for suffix in CARD_SUFFIXES:
30
+ if name.endswith(suffix):
31
+ return suffix
32
+ return None
33
+
34
+
24
35
  class Outcome(Enum):
25
36
  RESOLVED = "resolved"
26
37
  UNRESOLVED = "unresolved"
@@ -48,7 +59,7 @@ class ImportTable:
48
59
 
49
60
 
50
61
  class Workspace:
51
- """Every `.hmd` file under the namespace root, plus resolution over them."""
62
+ """Every card under the namespace root, plus resolution over them."""
52
63
 
53
64
  def __init__(self, config: Config):
54
65
  self.config = config
@@ -58,6 +69,8 @@ class Workspace:
58
69
  #: Root-relative parts -> the pages addressable under them, for phase 3.
59
70
  self._by_parts: dict[tuple[str, ...], list[Path]] = {}
60
71
  self._import_tables: dict[Path, ImportTable] = {}
72
+ #: Shadowed card -> the card of the same name that shadows it (HMD018).
73
+ self.shadowed: dict[Path, Path] = {}
61
74
  #: Roots of the vaults nested below this one; their cards are not ours.
62
75
  self._nested_roots: frozenset[Path] = frozenset()
63
76
  self._load()
@@ -66,14 +79,33 @@ class Workspace:
66
79
 
67
80
  def _load(self) -> None:
68
81
  self._nested_roots = self._find_nested_roots()
69
- for path in sorted(self.root.rglob(f"*{SUFFIX}")):
82
+ for path in sorted(self.root.rglob("*")):
83
+ suffix = card_suffix(path.name)
84
+ if suffix is None or path.name == suffix:
85
+ continue
70
86
  if not path.is_file() or self._hidden(path) or self._in_nested_vault(path):
71
87
  continue
72
88
  self._pages.append(path)
73
89
  text = path.read_text(encoding="utf-8")
74
- self.documents[path] = parse(path, text, self.rel(path))
90
+ read = parse if suffix == SUFFIX else parse_markdown
91
+ self.documents[path] = read(path, text, self.rel(path))
75
92
 
93
+ # Files of one directory whose names differ only in their card
94
+ # extension claim one name; the earliest extension is the card at it.
95
+ claims: dict[tuple[Path, str], list[Path]] = {}
76
96
  for path in self._pages:
97
+ stem = path.name[: -len(card_suffix(path.name))]
98
+ claims.setdefault((path.parent, stem), []).append(path)
99
+ for paths in claims.values():
100
+ ranked = sorted(paths, key=lambda p: CARD_SUFFIXES.index(card_suffix(p.name)))
101
+ for loser in ranked[1:]:
102
+ self.shadowed[loser] = ranked[0]
103
+
104
+ for path in self._pages:
105
+ if path in self.shadowed:
106
+ # Reachable only by a reference that writes its extension, so
107
+ # never a sweep candidate.
108
+ continue
77
109
  parts = self.parts(path)
78
110
  self._by_parts.setdefault(parts, []).append(path)
79
111
  # A folder note is also addressable by its directory's name, so a
@@ -112,29 +144,40 @@ class Workspace:
112
144
  return path.relative_to(self.root).as_posix()
113
145
 
114
146
  def parts(self, path: Path) -> tuple[str, ...]:
115
- return path.relative_to(self.root).with_suffix("").parts
147
+ relative = path.relative_to(self.root).parts
148
+ suffix = card_suffix(relative[-1]) or ""
149
+ return (*relative[:-1], relative[-1][: len(relative[-1]) - len(suffix)])
116
150
 
117
151
  def pages(self) -> list[Path]:
118
152
  return list(self._pages)
119
153
 
120
154
  # -- §5.1 binding ----------------------------------------------------
121
155
 
122
- def bind(self, directory: Path, parts: tuple[str, ...]) -> Path | None:
156
+ def bind(
157
+ self, directory: Path, parts: tuple[str, ...], suffix: str | None = None
158
+ ) -> Path | None:
123
159
  """Bind `parts` in one directory, honouring folder notes.
124
160
 
125
- A target naming a directory resolves to that directory's `index.hmd`,
126
- which is what makes a folder note the namespace's landing page. When
127
- both `foo.hmd` and `foo/index.hmd` exist the file wins; the collision is
128
- reported separately as HMD012.
161
+ The card extensions are tried in priority order, then the folder note
162
+ with the same extensions in the same order (HMD-0029). A target naming
163
+ a directory resolves to that directory's folder note, which is what
164
+ makes it the namespace's landing page. When both `foo.hmd` and
165
+ `foo/index.hmd` exist the file wins; the collision is reported
166
+ separately as HMD012. A `suffix` the reference wrote binds only that
167
+ extension.
129
168
  """
130
169
  if not parts:
131
170
  return None
132
- candidate = directory.joinpath(*parts).with_suffix(SUFFIX)
133
- if candidate in self.documents:
134
- return candidate
135
- folder_note = directory.joinpath(*parts) / f"{INDEX_STEM}{SUFFIX}"
136
- if folder_note in self.documents:
137
- return folder_note
171
+ suffixes = (suffix,) if suffix else CARD_SUFFIXES
172
+ base = directory.joinpath(*parts[:-1])
173
+ for each in suffixes:
174
+ candidate = base / f"{parts[-1]}{each}"
175
+ if candidate in self.documents:
176
+ return candidate
177
+ for each in suffixes:
178
+ folder_note = directory.joinpath(*parts) / f"{INDEX_STEM}{each}"
179
+ if folder_note in self.documents:
180
+ return folder_note
138
181
  return None
139
182
 
140
183
  # -- imports ---------------------------------------------------------
@@ -235,6 +278,10 @@ class Workspace:
235
278
  failure mode of guessing the other way is a leak rather than a 404.
236
279
  """
237
280
  document = self.documents.get(source)
281
+ if document is not None and document.is_markdown:
282
+ # HMD-0029: a Markdown card is published wherever its file is, by
283
+ # whatever publishes Markdown; HyperMarkdown does not gate it.
284
+ return PUBLIC
238
285
  if document is not None and document.card.nav.visibility is not None:
239
286
  return document.card.nav.visibility
240
287
 
@@ -257,18 +304,19 @@ class Workspace:
257
304
  # -- §5.2 the algorithm ----------------------------------------------
258
305
 
259
306
  def resolve(self, source: Path, page_ref: str) -> Resolution:
260
- stem = page_ref[: -len(SUFFIX)] if page_ref.endswith(SUFFIX) else page_ref
307
+ suffix = card_suffix(page_ref)
308
+ stem = page_ref[: -len(suffix)] if suffix else page_ref
261
309
 
262
310
  if stem.startswith("/"):
263
311
  parts = _split(stem)
264
- target = self.bind(self.root, parts)
312
+ target = self.bind(self.root, parts, suffix)
265
313
  return _hit(target, phase=None) if target else Resolution(Outcome.UNRESOLVED)
266
314
 
267
315
  if stem.startswith("./") or stem.startswith("../"):
268
316
  base = _normalize(source.parent.joinpath(stem))
269
317
  if not self._inside_root(base):
270
318
  return Resolution(Outcome.ESCAPES)
271
- target = self.bind(base.parent, (base.name,))
319
+ target = self.bind(base.parent, (base.name,), suffix)
272
320
  return _hit(target, phase=None) if target else Resolution(Outcome.UNRESOLVED)
273
321
 
274
322
  parts = _split(stem)
@@ -284,22 +332,22 @@ class Workspace:
284
332
 
285
333
  # Phase 1 — spine walk, non-recursive, nearest first.
286
334
  for directory in self._spine(source):
287
- target = self.bind(directory, parts)
335
+ target = self.bind(directory, parts, suffix)
288
336
  if target is not None:
289
337
  return Resolution(Outcome.RESOLVED, target, phase=1)
290
338
 
291
339
  # Phase 2 — imported search paths, in declaration order.
292
- hits = [d for d in table.search_paths if self.bind(d, parts) is not None]
340
+ hits = [d for d in table.search_paths if self.bind(d, parts, suffix) is not None]
293
341
  if hits:
294
- winner = self.bind(hits[0], parts)
295
- shadowed = tuple(self.bind(d, parts) for d in hits[1:])
342
+ winner = self.bind(hits[0], parts, suffix)
343
+ shadowed = tuple(self.bind(d, parts, suffix) for d in hits[1:])
296
344
  return Resolution(Outcome.RESOLVED, winner, phase=2, shadowed=shadowed)
297
345
 
298
346
  if not self.autodiscovery_enabled(source):
299
347
  return Resolution(Outcome.UNRESOLVED)
300
348
 
301
349
  # Phase 3 — autodiscovery, at most once.
302
- matches = self._sweep(source, parts)
350
+ matches = self._sweep(source, parts, suffix)
303
351
  if len(matches) == 1:
304
352
  return Resolution(Outcome.RESOLVED, matches[0], phase=3)
305
353
  if len(matches) > 1:
@@ -319,14 +367,15 @@ class Workspace:
319
367
  directory = directory.parent
320
368
  return spine
321
369
 
322
- def _sweep(self, source: Path, parts: tuple[str, ...]) -> list[Path]:
370
+ def _sweep(self, source: Path, parts: tuple[str, ...], suffix: str | None = None) -> list[Path]:
323
371
  scope = source.parent if self.config.mode == "recursive" else self.root
324
372
  matches = {
325
373
  page
326
374
  for key, pages in self._by_parts.items()
327
375
  if key[-len(parts) :] == parts
328
376
  for page in pages
329
- if scope == self.root or scope in page.parents
377
+ if (scope == self.root or scope in page.parents)
378
+ and (suffix is None or card_suffix(page.name) == suffix)
330
379
  }
331
380
  # Sorted by root-relative POSIX path, so diagnostics are byte-identical
332
381
  # across platforms and runs (P1).
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: hypermarkdown
3
- Version: 0.3.1
3
+ Version: 0.4.0
4
4
  Summary: A strict, machine-checkable markdown dialect for project knowledge bases.
5
5
  Author: Yauhen Yakimovich
6
6
  License-Expression: MIT
@@ -154,10 +154,12 @@ Every other key is yours, and nothing will inspect it.
154
154
  | `hmd info` | Show the resolved root and discovery policy |
155
155
  | `hmd --version` | Print the installed version |
156
156
 
157
- Every command but `init` takes `--root` to override the namespace root, which
158
- otherwise comes from the `wiki` setting in `.hmd/config.toml` (defaulting to
159
- `doc/wiki`). A `.hmd/` directory doubles as the project root marker, so any
160
- subtree can be self-contained.
157
+ The `wiki` setting in `.hmd/config.toml` is the cards location: where inside
158
+ the vault, the directory holding `.hmd/`, the cards start (`doc/wiki` by
159
+ default, `.` for directly under the vault). The directory it names is the
160
+ namespace root, and every command but `init` takes `--root` to override it. A
161
+ `.hmd/` directory doubles as the project root marker, so any subtree can be
162
+ self-contained.
161
163
 
162
164
  ```bash
163
165
  hmd init # here; the namespace is named after the directory
File without changes
File without changes
File without changes