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
hypermarkdown/model.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
"""Core data model for HyperMarkDown documents.
|
|
2
|
+
|
|
3
|
+
Every construct carries an exact source `Span`, so a diagnostic can point at it
|
|
4
|
+
and a future language server can reuse the same positions (HMD-0001 §1).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
# Severities.
|
|
13
|
+
ERROR = "error"
|
|
14
|
+
WARNING = "warning"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True)
|
|
18
|
+
class Span:
|
|
19
|
+
"""A byte range in a source file, with a 1-indexed line and column."""
|
|
20
|
+
|
|
21
|
+
start: int
|
|
22
|
+
end: int
|
|
23
|
+
line: int
|
|
24
|
+
column: int
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(frozen=True)
|
|
28
|
+
class Heading:
|
|
29
|
+
level: int
|
|
30
|
+
text: str
|
|
31
|
+
slug: str
|
|
32
|
+
span: Span
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(frozen=True)
|
|
36
|
+
class Anchor:
|
|
37
|
+
"""A trailing ``^block-id`` marker (HMD-0001 §2)."""
|
|
38
|
+
|
|
39
|
+
block_id: str
|
|
40
|
+
span: Span
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True)
|
|
44
|
+
class Link:
|
|
45
|
+
"""A ``[[wikilink]]`` or, when `is_embed`, a ``![[embed]]``."""
|
|
46
|
+
|
|
47
|
+
page_ref: str
|
|
48
|
+
fragment: str | None
|
|
49
|
+
fragment_kind: str | None # "heading" | "block" | None
|
|
50
|
+
display: str | None
|
|
51
|
+
is_embed: bool
|
|
52
|
+
raw: str
|
|
53
|
+
span: Span
|
|
54
|
+
|
|
55
|
+
@property
|
|
56
|
+
def target(self) -> str:
|
|
57
|
+
"""The link as written, minus any display text — for diagnostics."""
|
|
58
|
+
if self.fragment is None:
|
|
59
|
+
return self.page_ref
|
|
60
|
+
marker = "#^" if self.fragment_kind == "block" else "#"
|
|
61
|
+
return f"{self.page_ref}{marker}{self.fragment}"
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass(frozen=True)
|
|
65
|
+
class ImportStmt:
|
|
66
|
+
"""One parsed ``from <ref> import <names>`` statement (HMD-0001 §5.3)."""
|
|
67
|
+
|
|
68
|
+
ref: str
|
|
69
|
+
wildcard: bool
|
|
70
|
+
bindings: tuple[tuple[str, str], ...] # (name, local_name)
|
|
71
|
+
raw: str
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
# `nav.visibility` values. Publication is opt-in: a card reaches a built site
|
|
75
|
+
# only if it resolves to PUBLIC, and the resolved default is PRIVATE. Absent
|
|
76
|
+
# means "inherit" so a folder note can govern its subtree.
|
|
77
|
+
PUBLIC = "public"
|
|
78
|
+
PRIVATE = "private"
|
|
79
|
+
VISIBILITIES = frozenset({PUBLIC, PRIVATE})
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@dataclass(frozen=True)
|
|
83
|
+
class NavConfig:
|
|
84
|
+
"""The `nav` mapping: how a card places itself in a published site.
|
|
85
|
+
|
|
86
|
+
A mapping rather than a bare number because placement has more than one
|
|
87
|
+
dimension — order was simply the one that existed first. A scalar would have
|
|
88
|
+
had to grow a second spelling the moment `visibility` was wanted.
|
|
89
|
+
"""
|
|
90
|
+
|
|
91
|
+
#: Sort position within the card's directory. None sorts after every keyed
|
|
92
|
+
#: sibling, so ordering one card does not reshuffle the rest.
|
|
93
|
+
order: int | None = None
|
|
94
|
+
#: `public` or `private`. None means inherit — from the nearest ancestor
|
|
95
|
+
#: folder note, and failing that from the default, which is private.
|
|
96
|
+
visibility: str | None = None
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
@dataclass
|
|
100
|
+
class CardConfig:
|
|
101
|
+
"""The reserved frontmatter keys: `tags`, `use`, `import`, `nav`."""
|
|
102
|
+
|
|
103
|
+
tags: tuple[str, ...] = ()
|
|
104
|
+
# Feature name -> enabled. Absent means "inherit".
|
|
105
|
+
use: dict[str, bool] = field(default_factory=dict)
|
|
106
|
+
imports: tuple[ImportStmt, ...] = ()
|
|
107
|
+
nav: NavConfig = field(default_factory=NavConfig)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
@dataclass
|
|
111
|
+
class Diagnostic:
|
|
112
|
+
rule: str
|
|
113
|
+
severity: str
|
|
114
|
+
path: str # root-relative, POSIX separators
|
|
115
|
+
line: int
|
|
116
|
+
column: int
|
|
117
|
+
message: str
|
|
118
|
+
candidates: tuple[str, ...] = ()
|
|
119
|
+
|
|
120
|
+
def sort_key(self) -> tuple:
|
|
121
|
+
return (self.path, self.line, self.column, self.rule)
|
|
122
|
+
|
|
123
|
+
def to_dict(self) -> dict:
|
|
124
|
+
out = {
|
|
125
|
+
"rule": self.rule,
|
|
126
|
+
"severity": self.severity,
|
|
127
|
+
"path": self.path,
|
|
128
|
+
"line": self.line,
|
|
129
|
+
"column": self.column,
|
|
130
|
+
"message": self.message,
|
|
131
|
+
}
|
|
132
|
+
if self.candidates:
|
|
133
|
+
out["candidates"] = list(self.candidates)
|
|
134
|
+
return out
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
@dataclass
|
|
138
|
+
class Document:
|
|
139
|
+
"""One parsed `.hmd` file."""
|
|
140
|
+
|
|
141
|
+
path: Path
|
|
142
|
+
text: str
|
|
143
|
+
frontmatter: dict
|
|
144
|
+
card: CardConfig
|
|
145
|
+
headings: tuple[Heading, ...] = ()
|
|
146
|
+
anchors: tuple[Anchor, ...] = ()
|
|
147
|
+
links: tuple[Link, ...] = ()
|
|
148
|
+
# Diagnostics discovered at parse time (HMD009, HMD010, HMD013, HMD014).
|
|
149
|
+
diagnostics: list[Diagnostic] = field(default_factory=list)
|
|
150
|
+
|
|
151
|
+
def heading_slugs(self) -> set[str]:
|
|
152
|
+
return {h.slug for h in self.headings}
|
|
153
|
+
|
|
154
|
+
def block_ids(self) -> set[str]:
|
|
155
|
+
return {a.block_id for a in self.anchors}
|
hypermarkdown/parse.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
"""Source bytes -> `Document` (HMD-0001 §1, §2, §3)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from markdown.extensions.toc import slugify, unique
|
|
9
|
+
|
|
10
|
+
from . import scan
|
|
11
|
+
from .frontmatter import parse_card_config, parse_yaml, split_frontmatter
|
|
12
|
+
from .model import (
|
|
13
|
+
ERROR,
|
|
14
|
+
Anchor,
|
|
15
|
+
CardConfig,
|
|
16
|
+
Diagnostic,
|
|
17
|
+
Document,
|
|
18
|
+
Heading,
|
|
19
|
+
Link,
|
|
20
|
+
Span,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
#: Characters that may not appear literally in a link target (HMD-0001 §2).
|
|
24
|
+
RESERVED_CHARS = frozenset("[]|#^\n")
|
|
25
|
+
|
|
26
|
+
_BLOCK_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def slug_for(text: str, used: set[str]) -> str:
|
|
30
|
+
"""Assign a heading slug the way Python-Markdown's `toc` extension does.
|
|
31
|
+
|
|
32
|
+
Delegated rather than invented: a link and its rendered destination cannot
|
|
33
|
+
disagree if both sides use the same rule (HMD-0001 §3).
|
|
34
|
+
"""
|
|
35
|
+
return unique(slugify(text, "-"), used)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def parse(path: Path, text: str, rel: str) -> Document:
|
|
39
|
+
"""Parse one `.hmd` file. `rel` is the root-relative path for diagnostics."""
|
|
40
|
+
diagnostics: list[Diagnostic] = []
|
|
41
|
+
|
|
42
|
+
raw_yaml, _body, body_offset = split_frontmatter(text)
|
|
43
|
+
frontmatter: dict = {}
|
|
44
|
+
card = CardConfig()
|
|
45
|
+
|
|
46
|
+
if raw_yaml is not None:
|
|
47
|
+
try:
|
|
48
|
+
frontmatter = parse_yaml(raw_yaml)
|
|
49
|
+
except ValueError as exc:
|
|
50
|
+
diagnostics.append(Diagnostic("HMD009", ERROR, rel, 1, 1, str(exc)))
|
|
51
|
+
else:
|
|
52
|
+
card, problems = parse_card_config(frontmatter)
|
|
53
|
+
for rule, message in problems:
|
|
54
|
+
diagnostics.append(Diagnostic(rule, ERROR, rel, 1, 1, message))
|
|
55
|
+
|
|
56
|
+
# Mask the body only; frontmatter is YAML, not markdown.
|
|
57
|
+
masked = " " * body_offset + scan.mask(text[body_offset:])
|
|
58
|
+
|
|
59
|
+
headings = _headings(text, masked)
|
|
60
|
+
anchors = _anchors(text, masked)
|
|
61
|
+
links, link_diagnostics = _links(text, masked, rel)
|
|
62
|
+
diagnostics.extend(link_diagnostics)
|
|
63
|
+
|
|
64
|
+
return Document(
|
|
65
|
+
path=path,
|
|
66
|
+
text=text,
|
|
67
|
+
frontmatter=frontmatter,
|
|
68
|
+
card=card,
|
|
69
|
+
headings=headings,
|
|
70
|
+
anchors=anchors,
|
|
71
|
+
links=links,
|
|
72
|
+
diagnostics=diagnostics,
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _span(text: str, start: int, end: int) -> Span:
|
|
77
|
+
line, column = scan.line_col(text, start)
|
|
78
|
+
return Span(start=start, end=end, line=line, column=column)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _headings(text: str, masked: str) -> tuple[Heading, ...]:
|
|
82
|
+
used: set[str] = set()
|
|
83
|
+
out = []
|
|
84
|
+
for level, heading_text, start, end in scan.find_headings(masked):
|
|
85
|
+
# Slug from the ORIGINAL text: masking blanks inline code, and a heading
|
|
86
|
+
# such as `## The \`hmd\` CLI` must slug from what the renderer sees.
|
|
87
|
+
original = text[start:end]
|
|
88
|
+
m = re.match(r"^[ \t]{0,3}#{1,6}[ \t]+(.*?)[ \t]*$", original)
|
|
89
|
+
display = m.group(1) if m else heading_text
|
|
90
|
+
display = re.sub(r"[ \t]+#+[ \t]*$", "", display)
|
|
91
|
+
display = re.sub(r"[ \t]+\^[A-Za-z0-9][A-Za-z0-9_-]{0,63}[ \t]*$", "", display).strip()
|
|
92
|
+
out.append(
|
|
93
|
+
Heading(level=level, text=display, slug=slug_for(display, used), span=_span(text, start, end))
|
|
94
|
+
)
|
|
95
|
+
return tuple(out)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _anchors(text: str, masked: str) -> tuple[Anchor, ...]:
|
|
99
|
+
return tuple(
|
|
100
|
+
Anchor(block_id=block_id, span=_span(text, start, end))
|
|
101
|
+
for block_id, start, end in scan.find_anchors(masked)
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _links(text: str, masked: str, rel: str) -> tuple[tuple[Link, ...], list[Diagnostic]]:
|
|
106
|
+
links: list[Link] = []
|
|
107
|
+
diagnostics: list[Diagnostic] = []
|
|
108
|
+
|
|
109
|
+
for is_embed, inner, start, end in scan.find_links(masked):
|
|
110
|
+
span = _span(text, start, end)
|
|
111
|
+
raw = text[start:end]
|
|
112
|
+
try:
|
|
113
|
+
page_ref, fragment, fragment_kind, display = _parse_target(inner)
|
|
114
|
+
except ValueError as exc:
|
|
115
|
+
diagnostics.append(Diagnostic("HMD010", ERROR, rel, span.line, span.column, f"{exc} in {raw}"))
|
|
116
|
+
continue
|
|
117
|
+
links.append(
|
|
118
|
+
Link(
|
|
119
|
+
page_ref=page_ref,
|
|
120
|
+
fragment=fragment,
|
|
121
|
+
fragment_kind=fragment_kind,
|
|
122
|
+
display=display,
|
|
123
|
+
is_embed=is_embed,
|
|
124
|
+
raw=raw,
|
|
125
|
+
span=span,
|
|
126
|
+
)
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
for start in scan.find_unterminated(masked):
|
|
130
|
+
line, column = scan.line_col(text, start)
|
|
131
|
+
diagnostics.append(Diagnostic("HMD010", ERROR, rel, line, column, "unterminated '[[' — expected ']]'"))
|
|
132
|
+
|
|
133
|
+
return tuple(links), diagnostics
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _parse_target(inner: str) -> tuple[str, str | None, str | None, str | None]:
|
|
137
|
+
"""Split a link body into (page_ref, fragment, fragment_kind, display).
|
|
138
|
+
|
|
139
|
+
Raises `ValueError` for anything malformed (HMD010).
|
|
140
|
+
"""
|
|
141
|
+
if not inner.strip():
|
|
142
|
+
raise ValueError("empty link target")
|
|
143
|
+
|
|
144
|
+
# Display text comes last and may itself contain '|', so split once only.
|
|
145
|
+
display: str | None = None
|
|
146
|
+
if "|" in inner:
|
|
147
|
+
inner, display = inner.split("|", 1)
|
|
148
|
+
if not display.strip():
|
|
149
|
+
raise ValueError("empty display text")
|
|
150
|
+
|
|
151
|
+
fragment: str | None = None
|
|
152
|
+
fragment_kind: str | None = None
|
|
153
|
+
if "#" in inner:
|
|
154
|
+
inner, fragment = inner.split("#", 1)
|
|
155
|
+
if fragment.startswith("^"):
|
|
156
|
+
fragment_kind, fragment = "block", fragment[1:]
|
|
157
|
+
if not _BLOCK_ID_RE.match(fragment):
|
|
158
|
+
raise ValueError(f"invalid block id {fragment!r}")
|
|
159
|
+
else:
|
|
160
|
+
fragment_kind = "heading"
|
|
161
|
+
if not fragment.strip():
|
|
162
|
+
raise ValueError("empty heading fragment")
|
|
163
|
+
|
|
164
|
+
page_ref = inner.strip()
|
|
165
|
+
if not page_ref:
|
|
166
|
+
# Covers `[[#tag]]`: a tag is never a link target, because '#' is
|
|
167
|
+
# reserved for fragments (HMD-0001 §5.3).
|
|
168
|
+
raise ValueError("link target has no page reference")
|
|
169
|
+
|
|
170
|
+
bad = RESERVED_CHARS.intersection(page_ref)
|
|
171
|
+
if bad:
|
|
172
|
+
raise ValueError(f"reserved character {''.join(sorted(bad))!r} in target")
|
|
173
|
+
|
|
174
|
+
return page_ref, fragment, fragment_kind, display
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""Flat markdown: erasure of the HyperMarkDown layer (HMD-0002 §5).
|
|
2
|
+
|
|
3
|
+
Every embed is inlined and every resolved link becomes an ordinary relative
|
|
4
|
+
markdown link, leaving output that GitHub or a plain renderer reads without
|
|
5
|
+
knowing the format exists. This is a one-way build product. The output no longer
|
|
6
|
+
records where a link came from — spine, named import, or sweep — and no longer
|
|
7
|
+
marks where an embedded card began and ended.
|
|
8
|
+
|
|
9
|
+
An unresolved link is left as written. There is nothing to erase it to, and a
|
|
10
|
+
`[[name]]` surviving in the output is a truthful statement that the page does
|
|
11
|
+
not exist yet.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import os
|
|
17
|
+
import posixpath
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
import markdown
|
|
21
|
+
|
|
22
|
+
from ..embed import Expansion, expand
|
|
23
|
+
from ..model import Link
|
|
24
|
+
from ..parse import slug_for
|
|
25
|
+
from ..resolve import Workspace
|
|
26
|
+
|
|
27
|
+
#: The "free" half of the syntax — everything the format does not own itself
|
|
28
|
+
#: (HMD-0001 §9). Consumed as a dependency, never reimplemented.
|
|
29
|
+
EXTENSIONS = [
|
|
30
|
+
"admonition",
|
|
31
|
+
"footnotes",
|
|
32
|
+
"tables",
|
|
33
|
+
"toc",
|
|
34
|
+
"pymdownx.arithmatex",
|
|
35
|
+
"pymdownx.details",
|
|
36
|
+
"pymdownx.superfences",
|
|
37
|
+
"pymdownx.tasklist",
|
|
38
|
+
"pymdownx.tilde",
|
|
39
|
+
]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def render(workspace: Workspace, path: Path, suffix: str = ".md") -> Expansion:
|
|
43
|
+
"""Expand `path` and rewrite its resolved links to relative `suffix` paths."""
|
|
44
|
+
home = path.parent
|
|
45
|
+
|
|
46
|
+
def rewrite(link: Link, target: Path | None) -> str:
|
|
47
|
+
if target is None:
|
|
48
|
+
return link.raw
|
|
49
|
+
return f"[{_text(link)}]({_href(home, target, link, suffix)})"
|
|
50
|
+
|
|
51
|
+
return expand(workspace, path, rewrite=rewrite)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def to_html(workspace: Workspace, path: Path) -> Expansion:
|
|
55
|
+
"""Render `path` to HTML through the Python-Markdown pipeline."""
|
|
56
|
+
flat = render(workspace, path, suffix=".html")
|
|
57
|
+
flat.text = markdown.Markdown(extensions=EXTENSIONS).convert(flat.text)
|
|
58
|
+
return flat
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _text(link: Link) -> str:
|
|
62
|
+
if link.display:
|
|
63
|
+
return link.display
|
|
64
|
+
# A block fragment is dropped from the href, so showing it in the link text
|
|
65
|
+
# would promise an anchor the output does not have.
|
|
66
|
+
return link.page_ref if link.fragment_kind == "block" else link.target
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _href(home: Path, target: Path, link: Link, suffix: str) -> str:
|
|
70
|
+
relative = os.path.relpath(target.with_suffix(suffix), home)
|
|
71
|
+
href = posixpath.join(*Path(relative).parts) if relative != "." else ""
|
|
72
|
+
|
|
73
|
+
# A block id has no anchor in plain markdown, so the fragment is dropped
|
|
74
|
+
# rather than emitted as a link that goes nowhere.
|
|
75
|
+
if link.fragment is not None and link.fragment_kind == "heading":
|
|
76
|
+
href = f"{href}#{slug_for(link.fragment, set())}"
|
|
77
|
+
return href
|