bellpress 0.1.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.
Files changed (52) hide show
  1. bellpress-0.1.0.dist-info/METADATA +11 -0
  2. bellpress-0.1.0.dist-info/RECORD +52 -0
  3. bellpress-0.1.0.dist-info/WHEEL +4 -0
  4. bellpress-0.1.0.dist-info/entry_points.txt +4 -0
  5. sitegen/__init__.py +5 -0
  6. sitegen/blocks/__init__.py +152 -0
  7. sitegen/blocks/algo.py +235 -0
  8. sitegen/blocks/callout.py +136 -0
  9. sitegen/blocks/deck.py +229 -0
  10. sitegen/blocks/diagram.py +267 -0
  11. sitegen/blocks/figure.py +52 -0
  12. sitegen/blocks/layout.py +114 -0
  13. sitegen/blocks/subfig.py +116 -0
  14. sitegen/build.py +604 -0
  15. sitegen/cli.py +121 -0
  16. sitegen/content.py +211 -0
  17. sitegen/i18n.py +91 -0
  18. sitegen/markdown.py +269 -0
  19. sitegen/mathml.py +36 -0
  20. sitegen/refs.py +63 -0
  21. sitegen/resources/i18n/en.toml +37 -0
  22. sitegen/resources/i18n/zh.toml +42 -0
  23. sitegen/resources/static/main.js +17 -0
  24. sitegen/resources/static/math/OFL.txt +92 -0
  25. sitegen/resources/static/math/STIX2Math.woff2 +0 -0
  26. sitegen/resources/static/reveal/LICENSE +19 -0
  27. sitegen/resources/static/reveal/embed.js +101 -0
  28. sitegen/resources/static/reveal/notes.js +1 -0
  29. sitegen/resources/static/reveal/reset.css +30 -0
  30. sitegen/resources/static/reveal/reveal.css +8 -0
  31. sitegen/resources/static/reveal/reveal.js +9 -0
  32. sitegen/resources/static/reveal/slides.css +282 -0
  33. sitegen/resources/static/search.js +93 -0
  34. sitegen/resources/static/style.css +757 -0
  35. sitegen/resources/static/tokens.css +68 -0
  36. sitegen/resources/templates/404.html +9 -0
  37. sitegen/resources/templates/archive.html +21 -0
  38. sitegen/resources/templates/base.html +60 -0
  39. sitegen/resources/templates/decks.html +16 -0
  40. sitegen/resources/templates/feed.xml +21 -0
  41. sitegen/resources/templates/index.html +27 -0
  42. sitegen/resources/templates/page.html +22 -0
  43. sitegen/resources/templates/post.html +43 -0
  44. sitegen/resources/templates/search.html +20 -0
  45. sitegen/resources/templates/sitemap.xml +9 -0
  46. sitegen/resources/templates/slides.html +41 -0
  47. sitegen/resources/templates/tag.html +17 -0
  48. sitegen/resources/templates/tags.html +14 -0
  49. sitegen/scaffold.py +83 -0
  50. sitegen/skill_resources/sitegen-markdown/SKILL.md +229 -0
  51. sitegen/skills.py +28 -0
  52. sitegen/slides.py +152 -0
@@ -0,0 +1,11 @@
1
+ Metadata-Version: 2.5
2
+ Name: bellpress
3
+ Version: 0.1.0
4
+ Summary: Markdown -> static site generator with an extensible block-syntax registry.
5
+ Requires-Python: >=3.11
6
+ Requires-Dist: jinja2>=3.1
7
+ Requires-Dist: latex2mathml>=3.77
8
+ Requires-Dist: markdown-it-py>=3.0
9
+ Requires-Dist: mdit-py-plugins>=0.4
10
+ Requires-Dist: pygments>=2.16
11
+ Requires-Dist: pyyaml>=6.0
@@ -0,0 +1,52 @@
1
+ sitegen/__init__.py,sha256=x4wpWi8ogMFSx1QcnOZ_PHTiGL6ILr_BfQY70YnuecY,133
2
+ sitegen/build.py,sha256=QxiaAb3xVaCTvd7Yj0QbgOpXkm9q72LQhqu1j8EV3vo,22612
3
+ sitegen/cli.py,sha256=1K_cAktGMjevGnFfKC56rSm-rTtx3vtsoD1ZPEHA0hE,4369
4
+ sitegen/content.py,sha256=gVagUhEgyQNL3hk-Njnc2moxEwxBLHevd8ARO7OJ1YQ,7444
5
+ sitegen/i18n.py,sha256=xnhUUJyp-H8FiqLh9je9Favm6L0baD_xfmVhtmQtHX0,2687
6
+ sitegen/markdown.py,sha256=OXkKJnYWKNIr9KpSLDGQSmkO1zneG0P6sOjYsQUH0L8,9289
7
+ sitegen/mathml.py,sha256=bIpcAhrxwsGlMGVoos6mirhXRIq16--EX-1Hslhx6iQ,1056
8
+ sitegen/refs.py,sha256=Wan0ZJ6owNNPNeRDI7O3ZCh_KYlx5LiCSoQM1pITtuY,1689
9
+ sitegen/scaffold.py,sha256=V9t8tmTv9URadSbgpWGtva3vrx-mqz9a1AwJa3_YOpo,2230
10
+ sitegen/skills.py,sha256=3OTG388_V1PLf1Jjj6lQanpWcPwbF7AeO-h2nPu4X2w,1127
11
+ sitegen/slides.py,sha256=r2xChyYv4Rxm2DK6vEciKA7N4VrOYfrvbwmqqGBUzVQ,5687
12
+ sitegen/blocks/__init__.py,sha256=Z_bs_uZox6rsX-FJaCiGQQgBKP5bOoJRP7XA8rZRaC4,4918
13
+ sitegen/blocks/algo.py,sha256=SAo4waNdbD5nnzTP2jPnfhTSplFosX1zzbbeAoPpk10,7827
14
+ sitegen/blocks/callout.py,sha256=glw1t_oorlyGvvLCzV6Mx6hgZycIx7NyEUFT5Mu-rnQ,4578
15
+ sitegen/blocks/deck.py,sha256=E6f0o6bhfvu181_XkxMYiVfwwXyT849H8zXj0m91upc,8056
16
+ sitegen/blocks/diagram.py,sha256=ecFyVol9Ut-6t7ugfPjoIAR1-u8_NGmUL7WowyLZ95M,9271
17
+ sitegen/blocks/figure.py,sha256=9Cbyz74bg9rRGhRj218ekSPXMR1MqDaJN7xyBDP4SvM,1830
18
+ sitegen/blocks/layout.py,sha256=O3eMX-7TEeUpgYKP8u825MxYP6wuzVWMVrtOoKuiI1A,4110
19
+ sitegen/blocks/subfig.py,sha256=-0VmTaQSR0KdRKL0LBplXPi1aXPceZQZGS3bfgrDifk,3482
20
+ sitegen/skill_resources/sitegen-markdown/SKILL.md,sha256=A9Y9hvAHKse_3SDwAppRZru8PYMxjPn3Nkm9rm2HpIs,9505
21
+ sitegen/resources/i18n/en.toml,sha256=t5UBfX4y134DZME1q3Ebs98igKJZ7vj2J7ubXMx57bk,854
22
+ sitegen/resources/i18n/zh.toml,sha256=W0qvQSTCvBbGW95LSFIKy-EhC5hRvi0a8G9J8zRL8JI,954
23
+ sitegen/resources/templates/404.html,sha256=0Rkuj3thlquFrSGXl0iDFlLWaxxnjnk3l6KlnoSna3g,333
24
+ sitegen/resources/templates/archive.html,sha256=YHn5rk9QS-dk29De_Ba5KpAmJZVY_m_-vdEPoGLpsAY,564
25
+ sitegen/resources/templates/base.html,sha256=S16nuzBx_CKMg3IRAyOUawSSrbpi7GEs_0PHa5KWrx8,2610
26
+ sitegen/resources/templates/decks.html,sha256=hQ6C3TKDqoigUxS0VqhZhONPvVuvHJh5Uz9WJ13DpbU,405
27
+ sitegen/resources/templates/feed.xml,sha256=8fDgMKkdIOvT9RwpUC9nccEOBqXXLMHRMaqdf8wvHWU,882
28
+ sitegen/resources/templates/index.html,sha256=ApRekpgppXrabdFVDyzJyACVaortBMK-gdq78gPzmvU,628
29
+ sitegen/resources/templates/page.html,sha256=doIpMFajECK5e7lbP7uQuElmG2rcxOT-LnzoyY8x-Ek,849
30
+ sitegen/resources/templates/post.html,sha256=YhRVEdrUBQSmikdUHyd88dhzW75X3_5DFoHz4ekhyco,1470
31
+ sitegen/resources/templates/search.html,sha256=xJdQT2OQVo4KIF6cafKVWJfrb5onsL8Td7AQX99_-wk,866
32
+ sitegen/resources/templates/sitemap.xml,sha256=GHK14ZQom16JsFy-QfRSjxqadm_mS9NI1icw71rxI8w,259
33
+ sitegen/resources/templates/slides.html,sha256=uxmOg_bv3xXcrGtVCZfKjqOoJFzb8i3lr8SD7mKlM0E,1568
34
+ sitegen/resources/templates/tag.html,sha256=MsJDPc4Roz7ri0OmjJ-hDl9walJnl3_FjnW3xVdhbKg,566
35
+ sitegen/resources/templates/tags.html,sha256=mKo95UQPABfF2oPnkeU9kb7KdZBnkpQvaMpt3eGeIxA,475
36
+ sitegen/resources/static/main.js,sha256=ubcqSmC72nluMccr5lraZa5AyWeX7EaG5e19VVtxoUM,693
37
+ sitegen/resources/static/math/OFL.txt,sha256=DIglkTtg2FiqzbM8TKZmCn1ksNZGRwLvuxkxP1dlhho,4519
38
+ sitegen/resources/static/math/STIX2Math.woff2,sha256=UylFanyikeWPKusIl_1kdReX73CIoCdEHHpoL-JAWko,400876
39
+ sitegen/resources/static/reveal/LICENSE,sha256=NAFIAPQSasJSXiJBZvCZ8mYoYS6VxB921whBtjE4yYk,1108
40
+ sitegen/resources/static/reveal/embed.js,sha256=78IzSbxZo8ntsuFWPaQ5hQBNkH8dUpD-0tAp6UtnabE,4442
41
+ sitegen/resources/static/reveal/notes.js,sha256=KI_nyyf_aWo-HBN7IrDNEXOVqE26KnA-K_wxNuZWEqg,68631
42
+ sitegen/resources/static/reveal/reset.css,sha256=GqjoTJyry_5NlbGYef5IucLF5tVFdMvmebwi7bn-ErY,871
43
+ sitegen/resources/static/reveal/reveal.css,sha256=nLxQgnl9k48O54Ayh5ChMa49e8XAnBdud5J8F08p5go,52279
44
+ sitegen/resources/static/reveal/reveal.js,sha256=lza_PYkY45HowHyFxTdzgA1ABNwl-UiRbjGco3HKiBo,107670
45
+ sitegen/resources/static/reveal/slides.css,sha256=fZzrnqA8Mmo5LxMRKDfo7JbVMSUT6PKQJzaSrinPsrk,11801
46
+ sitegen/resources/static/search.js,sha256=Yw8vALEXKr-nxiOwq-IfmC4DzfZhWJFVkr8KQsTmWwI,3120
47
+ sitegen/resources/static/style.css,sha256=dr3xorOgSAHXgNXE7JDWQPvYZ8f4bs9rntxU7V3heb8,23001
48
+ sitegen/resources/static/tokens.css,sha256=_8NxiXaJkeIKAmcJs4Ht_LeKkMYnPof0BniZXZPTsXc,2138
49
+ bellpress-0.1.0.dist-info/METADATA,sha256=8as1lGYlpbQf9h9kGvImaw3LMvhDGcr9oZZVDfwqRn0,351
50
+ bellpress-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
51
+ bellpress-0.1.0.dist-info/entry_points.txt,sha256=W0mi8SHPXXP8GOcDICf6zjvmScQ_FAlUOglKrwXcQqE,102
52
+ bellpress-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,4 @@
1
+ [console_scripts]
2
+ bellpress = sitegen.cli:main
3
+ site-gen = sitegen.cli:main
4
+ sitegen = sitegen.cli:main
sitegen/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Library: Markdown -> deployable static site, with an extensible block layer."""
2
+
3
+ __all__ = ["__version__"]
4
+
5
+ __version__ = "0.1.0"
@@ -0,0 +1,152 @@
1
+ """Fenced-block extension point.
2
+
3
+ Every ```-fence whose info string names a registered language is handed to the
4
+ corresponding renderer instead of the default highlighter. That single seam is
5
+ all you need to teach the generator a new syntax:
6
+
7
+ from sitegen.blocks import block
8
+
9
+ @block("mermaid")
10
+ def render_mermaid(code, ctx):
11
+ return f'<pre class="mermaid">{escape(code)}</pre>'
12
+
13
+ Registration happens on import, so ``sitegen.blocks`` imports every module
14
+ listed at the bottom of this file.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import re
20
+ from dataclasses import dataclass, field
21
+ from typing import Any, Callable
22
+
23
+ __all__ = [
24
+ "BlockContext",
25
+ "Numbered",
26
+ "REGISTRY",
27
+ "block",
28
+ "parse_info",
29
+ "render",
30
+ ]
31
+
32
+
33
+ @dataclass(frozen=True, slots=True)
34
+ class Numbered:
35
+ """What a numbered block needs: its counter value and its anchor id."""
36
+
37
+ number: int
38
+ anchor: str
39
+
40
+
41
+ @dataclass(slots=True)
42
+ class BlockContext:
43
+ """Everything a renderer needs beyond the fence body itself."""
44
+
45
+ language: str = ""
46
+ attrs: dict[str, str] = field(default_factory=dict)
47
+ doc: Any = None
48
+ """The document being rendered, or ``None``."""
49
+ counters: dict[str, int] = field(default_factory=dict)
50
+ """Counters shared by every block of one document (resets per document)."""
51
+ refs: Any = None
52
+ """The build's :class:`sitegen.refs.RefRegistry`, or ``None``."""
53
+ doc_slug: str = ""
54
+ lang: str = ""
55
+ labels: dict[str, str] = field(default_factory=dict)
56
+ """Localised captions: ``{"figure": "图", "algorithm": "算法"}``."""
57
+
58
+ # -- attributes -----------------------------------------------------
59
+ def attr(self, name: str, default: str = "") -> str:
60
+ return self.attrs.get(name, default)
61
+
62
+ def label(self, kind: str) -> str:
63
+ """Caption word for a numbered block, in the page's language."""
64
+ return self.labels.get(kind) or {
65
+ "figure": "Figure",
66
+ "algorithm": "Algorithm",
67
+ "table": "Table",
68
+ }.get(kind, kind.title())
69
+
70
+ def flag(self, name: str) -> bool:
71
+ """A valueless attribute (``line-numbers``) or ``name=true``."""
72
+ return self.attrs.get(name, "false").lower() not in ("false", "0", "no", "")
73
+
74
+ # -- numbering ------------------------------------------------------
75
+ def next_number(self, key: str) -> int:
76
+ self.counters[key] = self.counters.get(key, 0) + 1
77
+ return self.counters[key]
78
+
79
+ def number(self, kind: str, title: str = "") -> Numbered:
80
+ """Number a figure/algorithm and register it for `{{label}}` lookups."""
81
+ number = self.next_number(kind)
82
+ key = self.attr("label").strip()
83
+ anchor = key.replace(":", "-") if key else f"{kind}-{number}"
84
+ if key and self.refs is not None:
85
+ from ..refs import RefEntry
86
+
87
+ self.refs.add(
88
+ RefEntry(
89
+ key=key,
90
+ kind=kind,
91
+ number=number,
92
+ doc_slug=self.doc_slug,
93
+ anchor=anchor,
94
+ title=title,
95
+ doc_url=getattr(self.doc, "url", ""),
96
+ lang=self.lang,
97
+ )
98
+ )
99
+ return Numbered(number, anchor)
100
+
101
+
102
+ Renderer = Callable[[str, BlockContext], str]
103
+
104
+ REGISTRY: dict[str, Renderer] = {}
105
+
106
+
107
+ def block(language: str) -> Callable[[Renderer], Renderer]:
108
+ """Register ``fn`` as the renderer for ```language`` fences."""
109
+
110
+ def register(fn: Renderer) -> Renderer:
111
+ REGISTRY[language] = fn
112
+ return fn
113
+
114
+ return register
115
+
116
+
117
+ _PAIR = re.compile(r"""([\w-]+)=(?:"([^"]*)"|'([^']*)'|(\S+))""")
118
+ _BARE = re.compile(r"([\w-]+)")
119
+
120
+
121
+ def parse_info(info: str) -> tuple[str, dict[str, str]]:
122
+ """Split a fence info string into ``(language, attributes)``.
123
+
124
+ Accepts ``algo title="二分查找"``, ``{algo}`` and ``{.algo}``; both
125
+ ``k="v with space"`` and bare flags (``line-numbers``) are understood.
126
+ """
127
+ info = info.strip()
128
+ if not info:
129
+ return "", {}
130
+ head, _, rest = info.partition(" ")
131
+ language = head.strip().strip("{}").lstrip(".").strip("}")
132
+ attrs: dict[str, str] = {}
133
+ for match in _PAIR.finditer(rest):
134
+ value = match.group(2) or match.group(3) or match.group(4) or ""
135
+ attrs[match.group(1)] = value
136
+ for match in _BARE.finditer(rest):
137
+ attrs.setdefault(match.group(1), "")
138
+ return language, attrs
139
+
140
+
141
+ def render(code: str, info: str, ctx: BlockContext) -> str | None:
142
+ """Render ``code`` with the registered renderer for ``info``, or ``None``."""
143
+ language, attrs = parse_info(info)
144
+ fn = REGISTRY.get(language)
145
+ if fn is None:
146
+ return None
147
+ ctx.language, ctx.attrs = language, attrs
148
+ return fn(code, ctx)
149
+
150
+
151
+ # Importing these populates REGISTRY. Add your own module here.
152
+ from . import algo, callout, deck, diagram, figure, layout, subfig # noqa: E402,F401
sitegen/blocks/algo.py ADDED
@@ -0,0 +1,235 @@
1
+ """Algorithm blocks in the LaTeX ``algorithmicx`` idiom.
2
+
3
+ ```algo title="二分查找" label=alg:bs
4
+ \\REQUIRE 有序数组 $A$,目标值 $x$
5
+ \\ENSURE $A[i] = x$ 的下标,否则 $-1$
6
+ \\STATE $lo \\gets 0$, $hi \\gets n-1$
7
+ \\WHILE{$lo \\leq hi$}
8
+ \\STATE $mid \\gets \\lfloor (lo+hi)/2 \\rfloor$
9
+ \\IF{$A[mid] = x$}
10
+ \\RETURN $mid$
11
+ \\ELSIF{$A[mid] < x$}
12
+ \\STATE $lo \\gets mid+1$
13
+ \\ELSE
14
+ \\STATE $hi \\gets mid-1$
15
+ \\ENDIF
16
+ \\ENDWHILE
17
+ \\RETURN $-1$
18
+ ```
19
+
20
+ Nesting is inferred from the commands, so indentation in the source is purely
21
+ cosmetic and existing LaTeX listings paste in almost unchanged. ``$...$``
22
+ fragments go through the same MathML converter as prose.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import re
28
+ from dataclasses import dataclass, field
29
+ from html import escape
30
+
31
+ from ..mathml import mathml
32
+ from . import BlockContext, block
33
+
34
+ __all__ = ["parse_algo", "render_algo"]
35
+
36
+ _CMD = re.compile(r"^\s*\\([A-Za-z]+)(.*)$")
37
+ _MATH = re.compile(r"\$([^$]+)\$")
38
+
39
+ # command -> (closing command, leading word, trailing word)
40
+ _SIMPLE_BLOCKS = {
41
+ "FOR": ("ENDFOR", "for", "do"),
42
+ "WHILE": ("ENDWHILE", "while", "do"),
43
+ "DO": ("ENDDO", "repeat", ""),
44
+ "FUNCTION": ("ENDFUNCTION", "function", ""),
45
+ "PROCEDURE": ("ENDPROCEDURE", "procedure", ""),
46
+ }
47
+ _CLOSERS = {v[0] for v in _SIMPLE_BLOCKS.values()} | {"ENDIF"}
48
+
49
+ _CLOSE_LABEL = {
50
+ "ENDIF": "end if",
51
+ "ENDFOR": "end for",
52
+ "ENDWHILE": "end while",
53
+ "ENDDO": "until",
54
+ "ENDFUNCTION": "end function",
55
+ "ENDPROCEDURE": "end procedure",
56
+ }
57
+
58
+
59
+ def _inline(text: str) -> str:
60
+ """Escape prose, but leave ``$...$`` for the MathML converter."""
61
+ out: list[str] = []
62
+ pos = 0
63
+ for match in _MATH.finditer(text):
64
+ out.append(escape(text[pos : match.start()]))
65
+ out.append(mathml(match.group(1)))
66
+ pos = match.end()
67
+ out.append(escape(text[pos:]))
68
+ return "".join(out)
69
+
70
+
71
+ def _split_args(rest: str) -> list[str]:
72
+ """Split ``{a}{b}`` into ``["a", "b"]``, respecting nested braces.
73
+
74
+ A command written without braces (``\\REQUIRE arrays are sorted``) is the
75
+ common case in hand-written listings, so the bare remainder becomes the
76
+ single argument instead of being silently dropped.
77
+ """
78
+ args: list[str] = []
79
+ depth = 0
80
+ buf: list[str] = []
81
+ for ch in rest:
82
+ if ch == "{":
83
+ depth += 1
84
+ if depth > 1:
85
+ buf.append(ch)
86
+ elif ch == "}":
87
+ depth -= 1
88
+ if depth == 0:
89
+ args.append("".join(buf))
90
+ buf.clear()
91
+ else:
92
+ buf.append(ch)
93
+ elif depth:
94
+ buf.append(ch)
95
+ if args:
96
+ return args
97
+ bare = rest.strip()
98
+ return [bare] if bare else []
99
+
100
+
101
+ def _kw(word: str, cls: str = "kw") -> str:
102
+ return f'<span class="{cls}">{word}</span>'
103
+
104
+
105
+ def _join(*parts: str) -> str:
106
+ return " ".join(p for p in parts if p)
107
+
108
+
109
+ @dataclass
110
+ class Row:
111
+ html: str
112
+ depth: int = 0
113
+ kind: str = "state"
114
+
115
+ def render(self) -> str:
116
+ cls = "algo-row" if self.kind != "blank" else "algo-row algo-blank"
117
+ return (
118
+ f'<div class="{cls}" style="--depth:{self.depth}">'
119
+ f'<span class="algo-t">{self.html}</span></div>'
120
+ )
121
+
122
+
123
+ @dataclass
124
+ class Nest:
125
+ children: list["Row | Nest"] = field(default_factory=list)
126
+
127
+ def render(self) -> str:
128
+ return f'<div class="algo-nest">{"".join(c.render() for c in self.children)}</div>'
129
+
130
+
131
+ def parse_algo(source: str) -> list[Row | Nest]:
132
+ """Turn the command stream into nested rows."""
133
+ root: list[Row | Nest] = []
134
+ cur: list[Row | Nest] = root
135
+ depth = 0
136
+ frames: list[tuple[list[Row | Nest], int, str]] = []
137
+
138
+ for raw_line in source.splitlines():
139
+ line = raw_line.rstrip()
140
+ if not line.strip():
141
+ continue
142
+ match = _CMD.match(line)
143
+ if not match:
144
+ cur.append(Row(_inline(line.strip()), depth, "state"))
145
+ continue
146
+
147
+ cmd = match.group(1).upper()
148
+ args = _split_args(match.group(2))
149
+ first = args[0] if args else ""
150
+
151
+ if cmd in ("REQUIRE", "INPUT", "ENSURE", "OUTPUT"):
152
+ label = "Require:" if cmd in ("REQUIRE", "INPUT") else "Ensure:"
153
+ cur.append(Row(_join(_kw(label, "kw kw-io"), _inline(first)), depth, "io"))
154
+ elif cmd == "STATE":
155
+ cur.append(Row(_inline(first), depth, "state"))
156
+ elif cmd in ("RETURN", "PRINT"):
157
+ cur.append(Row(_join(_kw(cmd.lower()), _inline(first)), depth, "state"))
158
+ elif cmd in ("BREAK", "CONTINUE"):
159
+ cur.append(Row(_kw(cmd.lower()), depth, "state"))
160
+ elif cmd == "COMMENT":
161
+ cur.append(Row(f'<span class="cmt">&#9655; {_inline(first)}</span>', depth, "comment"))
162
+ elif cmd == "BLANK":
163
+ cur.append(Row("", depth, "blank"))
164
+ elif cmd == "IF":
165
+ cur.append(Row(_join(_kw("if"), _inline(first), _kw("then")), depth, "kw"))
166
+ nest = Nest()
167
+ cur.append(nest)
168
+ frames.append((cur, depth, "ENDIF"))
169
+ cur, depth = nest.children, depth + 1
170
+ elif cmd in ("ELSIF", "ELSEIF", "ELSE"):
171
+ if not frames or frames[-1][2] != "ENDIF":
172
+ cur.append(Row(_inline(line.strip()), depth, "state"))
173
+ continue
174
+ parent, parent_depth, closing = frames.pop()
175
+ head = (
176
+ _kw("else")
177
+ if cmd == "ELSE"
178
+ else _join(_kw("elif"), _inline(first), _kw("then"))
179
+ )
180
+ parent.append(Row(head, parent_depth, "kw"))
181
+ nest = Nest()
182
+ parent.append(nest)
183
+ frames.append((parent, parent_depth, closing))
184
+ cur, depth = nest.children, parent_depth + 1
185
+ elif cmd in _SIMPLE_BLOCKS:
186
+ closing, word, tail = _SIMPLE_BLOCKS[cmd]
187
+ if cmd == "DO":
188
+ head = _kw("repeat")
189
+ elif cmd in ("FUNCTION", "PROCEDURE"):
190
+ params = args[1] if len(args) > 1 else ""
191
+ head = _join(
192
+ _kw(word), f"{_inline(first)}({_inline(params)})".strip()
193
+ )
194
+ else:
195
+ head = _join(_kw(word), _inline(first), _kw(tail))
196
+ cur.append(Row(head, depth, "kw"))
197
+ nest = Nest()
198
+ cur.append(nest)
199
+ frames.append((cur, depth, closing))
200
+ cur, depth = nest.children, depth + 1
201
+ elif cmd in _CLOSERS:
202
+ if frames and frames[-1][2] == cmd:
203
+ parent, parent_depth, _ = frames.pop()
204
+ parent.append(Row(_kw(_CLOSE_LABEL[cmd]), parent_depth, "kw"))
205
+ cur, depth = parent, parent_depth
206
+ else:
207
+ cur.append(Row(_kw(cmd.lower()), depth, "kw"))
208
+ else:
209
+ cur.append(Row(_inline(line.strip().lstrip("\\")), depth, "state"))
210
+
211
+ while frames:
212
+ parent, parent_depth, _ = frames.pop()
213
+ cur, depth = parent, parent_depth
214
+ return root
215
+
216
+
217
+ @block("algo")
218
+ def render_algo(code: str, ctx: BlockContext) -> str:
219
+ title = ctx.attr("title") or ctx.attr("caption")
220
+ numbered = ctx.attr("number", "true").lower() not in ("false", "0", "no")
221
+ ref = ctx.number("algorithm", title)
222
+ body = "".join(node.render() for node in parse_algo(code))
223
+
224
+ pieces = (
225
+ [f'<span class="fig-tag">{ctx.label("algorithm")} {ref.number}</span>']
226
+ if numbered
227
+ else []
228
+ )
229
+ if title:
230
+ pieces.append(f'<span class="algo-title">{escape(title)}</span>')
231
+ caption = f'<figcaption class="algo-cap">{"".join(pieces)}</figcaption>' if pieces else ""
232
+ return (
233
+ f'<figure class="algo" id="{ref.anchor}">{caption}'
234
+ f'<div class="algo-body">{body}</div></figure>'
235
+ )
@@ -0,0 +1,136 @@
1
+ """Callouts, in the two spellings people actually write.
2
+
3
+ GitHub alerts -- portable, render sensibly on GitHub itself::
4
+
5
+ > [!NOTE]
6
+ > Useful information.
7
+
8
+ > [!WARNING]
9
+ > Urgent, needs attention.
10
+
11
+ The older container form is kept for existing posts and for a custom title::
12
+
13
+ ::: note 缓存失效
14
+ ...
15
+ :::
16
+
17
+ Both produce the same markup (``div.callout.callout-<kind>``), so there is one
18
+ set of styles. The five GitHub kinds are NOTE, TIP, IMPORTANT, WARNING and
19
+ CAUTION; ``danger`` is accepted as an alias of CAUTION.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import re
25
+ from html import escape
26
+ from typing import Any
27
+
28
+ from markdown_it import MarkdownIt
29
+ from mdit_py_plugins.container import container_plugin
30
+
31
+ __all__ = ["install"]
32
+
33
+ KINDS = ("note", "tip", "important", "warning", "caution")
34
+ _ALIAS = {"danger": "caution", "key": "important", "quote": "note"}
35
+ _DEFAULT_TITLE = {
36
+ "note": "Note",
37
+ "tip": "Tip",
38
+ "important": "Important",
39
+ "warning": "Warning",
40
+ "caution": "Caution",
41
+ }
42
+ _MARKER = re.compile(r"^\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\][ \t]*", re.IGNORECASE)
43
+
44
+
45
+ def _title(kind: str, env: Any, custom: str = "") -> str:
46
+ if custom:
47
+ return custom
48
+ labels = (env or {}).get("labels") or {}
49
+ return labels.get(kind) or _DEFAULT_TITLE[kind]
50
+
51
+
52
+ def _open_html(kind: str, title: str) -> str:
53
+ return (
54
+ f'<div class="callout callout-{kind}">'
55
+ f'<p class="callout-title">{escape(title)}</p>'
56
+ f'<div class="callout-body">'
57
+ )
58
+
59
+
60
+ # -- container form: ::: note Optional title ------------------------------
61
+ def _make_container_render(kind: str, canonical: str):
62
+ def render(self: Any, tokens: list[Any], idx: int, _options: Any, env: Any) -> str:
63
+ token = tokens[idx]
64
+ if token.nesting != 1:
65
+ return "</div></div>"
66
+ info = (token.info or "").strip()
67
+ custom = info[len(kind) :].strip()
68
+ return _open_html(canonical, _title(canonical, env, custom))
69
+
70
+ return render
71
+
72
+
73
+ # -- GitHub alert form: > [!NOTE] ----------------------------------------
74
+ def _alerts_rule(state: Any) -> None:
75
+ tokens = state.tokens
76
+ for i, token in enumerate(tokens):
77
+ if token.type != "blockquote_open":
78
+ continue
79
+ if i + 2 >= len(tokens):
80
+ continue
81
+ para, inline = tokens[i + 1], tokens[i + 2]
82
+ if para.type != "paragraph_open" or inline.type != "inline":
83
+ continue
84
+ match = _MARKER.match(inline.content)
85
+ if not match:
86
+ continue
87
+
88
+ kind = match.group(1).lower()
89
+ # drop the marker from the first text node, and the line break after it
90
+ children = inline.children or []
91
+ if children and children[0].type == "text":
92
+ children[0].content = _MARKER.sub("", children[0].content, count=1)
93
+ if not children[0].content:
94
+ children.pop(0)
95
+ if children and children[0].type in ("softbreak", "hardbreak"):
96
+ children.pop(0)
97
+ inline.content = inline.content[match.end() :].lstrip("\n")
98
+
99
+ token.meta = {**(token.meta or {}), "alert": kind}
100
+ for j in range(i + 1, len(tokens)):
101
+ if tokens[j].type == "blockquote_close" and tokens[j].level == token.level:
102
+ tokens[j].meta = {**(tokens[j].meta or {}), "alert": kind}
103
+ break
104
+
105
+ # an alert that had only the marker leaves an empty paragraph behind
106
+ if not inline.content.strip() and not children:
107
+ del tokens[i + 1 : i + 4]
108
+
109
+
110
+ def _blockquote_open(self: Any, tokens: list[Any], idx: int, options: Any, env: Any) -> str:
111
+ kind = (tokens[idx].meta or {}).get("alert")
112
+ if not kind:
113
+ return self.renderToken(tokens, idx, options, env)
114
+ return _open_html(kind, _title(kind, env))
115
+
116
+
117
+ def _blockquote_close(self: Any, tokens: list[Any], idx: int, options: Any, env: Any) -> str:
118
+ if (tokens[idx].meta or {}).get("alert"):
119
+ return "</div></div>"
120
+ return self.renderToken(tokens, idx, options, env)
121
+
122
+
123
+ def install(md: MarkdownIt) -> None:
124
+ for name in (*KINDS, *_ALIAS):
125
+ canonical = _ALIAS.get(name, name)
126
+ container_plugin(
127
+ md,
128
+ name,
129
+ marker=":",
130
+ validate=lambda params, markup, _n=name: params.strip().split(" ", 1)[0] == _n,
131
+ render=_make_container_render(name, canonical),
132
+ )
133
+
134
+ md.core.ruler.after("block", "github_alerts", _alerts_rule)
135
+ md.add_render_rule("blockquote_open", _blockquote_open)
136
+ md.add_render_rule("blockquote_close", _blockquote_close)