importpython-markdown 0.0.1__tar.gz → 0.1.1__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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Nicholas H.Tollervey
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
@@ -0,0 +1,74 @@
1
+ Metadata-Version: 2.4
2
+ Name: importpython-markdown
3
+ Version: 0.1.1
4
+ Summary: Runnable Python examples in Markdown, via importpython.org.
5
+ Author-email: "Nicholas H.Tollervey" <ntoll@ntoll.org>
6
+ License: MIT
7
+ Project-URL: Homepage, https://importpython.org/
8
+ Project-URL: Repository, https://codeberg.org/ntoll/importpython
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Documentation
14
+ Classifier: Topic :: Text Processing :: Markup :: Markdown
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: markdown>=3.4
19
+ Requires-Dist: pygments>=2.14
20
+ Dynamic: license-file
21
+
22
+ # importpython-markdown
23
+
24
+ Runnable Python examples in Markdown pages, for MkDocs, Zensical
25
+ and anything else built on Python-Markdown, powered by
26
+ [importpython.org](https://importpython.org/).
27
+
28
+ Wrap a section of ordinary Markdown in `#!` and `!#` gates:
29
+
30
+ #!mpy terminal title="A first example"
31
+
32
+ A caption, rendered as normal Markdown.
33
+
34
+ ```python
35
+ print("Hello, world!")
36
+ ```
37
+
38
+ !#
39
+
40
+ The section becomes a runnable example: the code, a Run button,
41
+ and the program's output beneath - nothing downloaded until a
42
+ reader presses Run. Plain fences are the program; a fence with
43
+ `title="name.py"` is a file delivered beside it; `config` and
44
+ `body` fences carry BFP settings and page markup (escaped for
45
+ you). The `py` and `mpy` types choose Pyodide or MicroPython,
46
+ and `terminal`, `debug`, `send-embedder-url`, `title="..."`,
47
+ `run-label="..."`, `stop-label="..."`, `theme="..."`,
48
+ `terminal-rows="..."`, `terminal-cols="..."`, `class` and `id`
49
+ pass through to the element - each documented at
50
+ [importpython.org](https://importpython.org/docs/writing-markdown/).
51
+
52
+ Install and enable:
53
+
54
+ pip install importpython-markdown
55
+
56
+ ```yaml
57
+ # mkdocs.yml
58
+ markdown_extensions:
59
+ - importpython
60
+ ```
61
+
62
+ ```toml
63
+ # zensical.toml
64
+ [project.markdown_extensions]
65
+ importpython = {}
66
+ ```
67
+
68
+ Pre-release honesty: until BFP's first release, the default
69
+ `script_url` points at the service's test channel, which may
70
+ change; pin your own copy with the `script_url` option if that
71
+ matters to you today.
72
+
73
+ The full documentation lives at
74
+ [importpython.org/docs](https://importpython.org/docs/).
@@ -0,0 +1,53 @@
1
+ # importpython-markdown
2
+
3
+ Runnable Python examples in Markdown pages, for MkDocs, Zensical
4
+ and anything else built on Python-Markdown, powered by
5
+ [importpython.org](https://importpython.org/).
6
+
7
+ Wrap a section of ordinary Markdown in `#!` and `!#` gates:
8
+
9
+ #!mpy terminal title="A first example"
10
+
11
+ A caption, rendered as normal Markdown.
12
+
13
+ ```python
14
+ print("Hello, world!")
15
+ ```
16
+
17
+ !#
18
+
19
+ The section becomes a runnable example: the code, a Run button,
20
+ and the program's output beneath - nothing downloaded until a
21
+ reader presses Run. Plain fences are the program; a fence with
22
+ `title="name.py"` is a file delivered beside it; `config` and
23
+ `body` fences carry BFP settings and page markup (escaped for
24
+ you). The `py` and `mpy` types choose Pyodide or MicroPython,
25
+ and `terminal`, `debug`, `send-embedder-url`, `title="..."`,
26
+ `run-label="..."`, `stop-label="..."`, `theme="..."`,
27
+ `terminal-rows="..."`, `terminal-cols="..."`, `class` and `id`
28
+ pass through to the element - each documented at
29
+ [importpython.org](https://importpython.org/docs/writing-markdown/).
30
+
31
+ Install and enable:
32
+
33
+ pip install importpython-markdown
34
+
35
+ ```yaml
36
+ # mkdocs.yml
37
+ markdown_extensions:
38
+ - importpython
39
+ ```
40
+
41
+ ```toml
42
+ # zensical.toml
43
+ [project.markdown_extensions]
44
+ importpython = {}
45
+ ```
46
+
47
+ Pre-release honesty: until BFP's first release, the default
48
+ `script_url` points at the service's test channel, which may
49
+ change; pin your own copy with the `script_url` option if that
50
+ matters to you today.
51
+
52
+ The full documentation lives at
53
+ [importpython.org/docs](https://importpython.org/docs/).
@@ -0,0 +1,31 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "importpython-markdown"
7
+ version = "0.1.1"
8
+ description = "Runnable Python examples in Markdown, via importpython.org."
9
+ readme = "README.md"
10
+ license = { text = "MIT" }
11
+ authors = [{ name = "Nicholas H.Tollervey", email = "ntoll@ntoll.org" }]
12
+ requires-python = ">=3.10"
13
+ dependencies = ["markdown>=3.4", "pygments>=2.14"]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Intended Audience :: Developers",
17
+ "License :: OSI Approved :: MIT License",
18
+ "Programming Language :: Python :: 3",
19
+ "Topic :: Documentation",
20
+ "Topic :: Text Processing :: Markup :: Markdown",
21
+ ]
22
+
23
+ [project.urls]
24
+ Homepage = "https://importpython.org/"
25
+ Repository = "https://codeberg.org/ntoll/importpython"
26
+
27
+ [project.entry-points."markdown.extensions"]
28
+ importpython = "importpython_markdown:ImportPythonExtension"
29
+
30
+ [tool.setuptools.packages.find]
31
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,474 @@
1
+ """
2
+ Runnable Python examples in Markdown, for any renderer built on
3
+ Python-Markdown, powered by importpython.org.
4
+
5
+ A region between a ``#!`` gate line and a ``!#`` gate line
6
+ becomes one ``<import-python>`` element. Inside the gates,
7
+ ordinary Markdown is rendered as captions, and fenced code
8
+ blocks map onto the element's parts: a plain fence is the
9
+ program, ``title="name"`` on a fence is a file delivered beside
10
+ it, and ``config`` and ``body`` fences carry BFP's settings and
11
+ the frame's page markup. The plugin escapes what needs escaping,
12
+ so a documenter never types an entity, and it validates at build
13
+ time in the element's own vocabulary, so an authoring mistake is
14
+ a loud build failure rather than a silent page.
15
+
16
+ The emitted markup follows the element's contract exactly: each
17
+ part is a bare ``<pre>``, a direct child of the element, in the
18
+ order the author wrote it.
19
+ """
20
+
21
+ import html
22
+ import json
23
+ import re
24
+
25
+ from markdown import Markdown
26
+ from pygments import highlight
27
+ from pygments.formatters import HtmlFormatter
28
+ from pygments.lexers import get_lexer_by_name, get_lexer_for_filename
29
+ from pygments.util import ClassNotFound
30
+ from markdown.extensions import Extension
31
+ from markdown.preprocessors import Preprocessor
32
+
33
+ # The gates. A #! line opens an example and carries its header;
34
+ # a line that is exactly !# closes it. Both are recognised only
35
+ # outside fenced code, so code about the gates can be quoted.
36
+ OPEN_GATE = re.compile(r"^#!(\S+)(?:\s+(.*))?$")
37
+ CLOSE_GATE = re.compile(r"^!#\s*$")
38
+
39
+ # A fence opener or closer: three or more backticks or tildes.
40
+ # The closer must use the same character, at least as many, and
41
+ # carry nothing else - the CommonMark rules this plugin needs.
42
+ FENCE = re.compile(r"^(`{3,}|~{3,})\s*(.*)$")
43
+
44
+ # Attributes on the gate line: bare flags and key="value" pairs.
45
+ ATTRIBUTE = re.compile(r'([\w-]+)(?:="([^"]*)")?')
46
+
47
+ # The element's runtimes, and what the gate may pass through to
48
+ # it. The allow-list is deliberate: a typo in an attribute should
49
+ # fail the build, not be silently ignored in every reader's
50
+ # browser.
51
+ TYPES = ("py", "mpy")
52
+ FLAGS = ("terminal", "debug", "send-embedder-url")
53
+ VALUED = ("title", "run-label", "stop-label", "theme", "class",
54
+ "id", "terminal-rows", "terminal-cols")
55
+
56
+
57
+ class ExampleError(ValueError):
58
+ """
59
+ An authoring mistake in an example, raised so the site build
60
+ fails loudly and names the problem - the documenter's version
61
+ of the element withholding its button.
62
+ """
63
+
64
+ def __init__(self, line, problem):
65
+ super().__init__(f"import-python example, line {line}: {problem}")
66
+
67
+
68
+ def parse_gate(header, line):
69
+ """
70
+ Turn a gate header into the element's attributes, insisting on
71
+ a known runtime first and allow-listed attributes after it, so
72
+ every mistake is caught here rather than shipped.
73
+ """
74
+ match = OPEN_GATE.match(header)
75
+ kind = match.group(1)
76
+ if kind not in TYPES:
77
+ raise ExampleError(
78
+ line, f'unknown type "{kind}"; use one of {", ".join(TYPES)}'
79
+ )
80
+ attributes = {"type": kind}
81
+ rest = match.group(2) or ""
82
+ span = 0
83
+ for found in ATTRIBUTE.finditer(rest):
84
+ if rest[span:found.start()].strip():
85
+ raise ExampleError(
86
+ line, f'cannot parse attributes at "{rest[span:]}"'
87
+ )
88
+ span = found.end()
89
+ name, value = found.group(1), found.group(2)
90
+ if value is None:
91
+ if name not in FLAGS:
92
+ raise ExampleError(
93
+ line,
94
+ f'unknown flag "{name}"; '
95
+ f'flags are {", ".join(FLAGS)}',
96
+ )
97
+ attributes[name] = None
98
+ else:
99
+ if name not in VALUED:
100
+ raise ExampleError(
101
+ line,
102
+ f'unknown attribute "{name}"; '
103
+ f'attributes are {", ".join(VALUED)}',
104
+ )
105
+ attributes[name] = value
106
+ if rest[span:].strip():
107
+ raise ExampleError(
108
+ line, f'cannot parse attributes at "{rest[span:]}"'
109
+ )
110
+ # The terminal's explicit size: each dimension needs the
111
+ # terminal it sizes, and only a positive whole number will do
112
+ # - the same rules the element applies, failing the build
113
+ # here instead of a reader's browser there.
114
+ for name in ("terminal-rows", "terminal-cols"):
115
+ if name in attributes:
116
+ if "terminal" not in attributes:
117
+ raise ExampleError(
118
+ line, f"{name} requires the terminal flag"
119
+ )
120
+ value = attributes[name]
121
+ if not (value.isdigit() and int(value) >= 1):
122
+ raise ExampleError(
123
+ line,
124
+ f'{name} is "{value}"; use a positive whole '
125
+ "number",
126
+ )
127
+ return attributes
128
+
129
+
130
+ def parse_fence_info(info):
131
+ """
132
+ Decide what a fence inside the gates is for. A title makes it
133
+ a file; the reserved words config and body claim their roles;
134
+ anything else - a language name or nothing - is the program.
135
+ The language is kept for the highlighter to use later.
136
+ """
137
+ title = None
138
+ found = re.search(r'title="([^"]*)"', info)
139
+ if found:
140
+ title = found.group(1)
141
+ info = (info[:found.start()] + info[found.end():]).strip()
142
+ language = info.split()[0] if info.split() else None
143
+ if title is not None:
144
+ return {"part": "file", "title": title, "language": language}
145
+ if language in ("config", "body"):
146
+ return {"part": language, "language": None}
147
+ return {"part": "program", "language": language}
148
+
149
+
150
+ def split_example(lines, first_line):
151
+ """
152
+ Walk the region between the gates, separating fenced blocks
153
+ (the element's parts) from the prose between them (the
154
+ captions), preserving the author's order throughout.
155
+ """
156
+ pieces = []
157
+ prose = []
158
+ fence = None
159
+ block = None
160
+ for offset, line in enumerate(lines):
161
+ if fence is None:
162
+ found = FENCE.match(line)
163
+ if found:
164
+ if prose and any(p.strip() for p in prose):
165
+ pieces.append({"part": "prose", "text": prose})
166
+ prose = []
167
+ fence = found.group(1)
168
+ block = parse_fence_info(found.group(2).strip())
169
+ block["text"] = []
170
+ block["line"] = first_line + offset
171
+ continue
172
+ prose.append(line)
173
+ else:
174
+ found = FENCE.match(line)
175
+ closes = (
176
+ found
177
+ and found.group(1)[0] == fence[0]
178
+ and len(found.group(1)) >= len(fence)
179
+ and not found.group(2).strip()
180
+ )
181
+ if closes:
182
+ pieces.append(block)
183
+ fence = None
184
+ block = None
185
+ continue
186
+ block["text"].append(line)
187
+ if fence is not None:
188
+ raise ExampleError(block["line"], "unclosed code fence")
189
+ if prose and any(p.strip() for p in prose):
190
+ pieces.append({"part": "prose", "text": prose})
191
+ return pieces
192
+
193
+
194
+ def validate(pieces, attributes, line):
195
+ """
196
+ The element's own rules, applied at build time: exactly one
197
+ program, no duplicate filenames, at most one config (as valid
198
+ JSON) and one body. The wording follows classify() in
199
+ embed.js, so both layers speak with one voice.
200
+ """
201
+ programs = [p for p in pieces if p["part"] == "program"]
202
+ if not programs:
203
+ raise ExampleError(line, "no program block")
204
+ if len(programs) > 1:
205
+ raise ExampleError(programs[1]["line"], "more than one program block")
206
+ names = set()
207
+ for piece in [p for p in pieces if p["part"] == "file"]:
208
+ if piece["title"] in names:
209
+ raise ExampleError(
210
+ piece["line"],
211
+ f'two blocks name the file "{piece["title"]}"',
212
+ )
213
+ names.add(piece["title"])
214
+ for role in ("config", "body"):
215
+ found = [p for p in pieces if p["part"] == role]
216
+ if len(found) > 1:
217
+ raise ExampleError(
218
+ found[1]["line"], f"more than one {role} block"
219
+ )
220
+ for piece in [p for p in pieces if p["part"] == "config"]:
221
+ try:
222
+ settings = json.loads("\n".join(piece["text"]))
223
+ except json.JSONDecodeError as error:
224
+ raise ExampleError(
225
+ piece["line"],
226
+ f"the config block is not valid JSON: {error}",
227
+ ) from None
228
+ # send-embedder-url writes importpython.py, so while the
229
+ # flag is on the name is reserved - here in the author's
230
+ # own config files too, matching the element's rule.
231
+ if "send-embedder-url" in attributes:
232
+ names = (settings.get("files") or {}).values()
233
+ if any(
234
+ str(name).removeprefix("./") == "importpython.py"
235
+ for name in names
236
+ ):
237
+ raise ExampleError(
238
+ piece["line"],
239
+ "the send-embedder-url flag reserves the "
240
+ 'file "importpython.py"',
241
+ )
242
+ if "send-embedder-url" in attributes:
243
+ for piece in pieces:
244
+ if (
245
+ piece["part"] == "file"
246
+ and piece["title"] == "importpython.py"
247
+ ):
248
+ raise ExampleError(
249
+ piece["line"],
250
+ "the send-embedder-url flag reserves the "
251
+ 'file "importpython.py"',
252
+ )
253
+
254
+
255
+ class ImportPythonPreprocessor(Preprocessor):
256
+ """
257
+ Find every gated region, build its element, and stash the
258
+ result so the surrounding renderer treats it as opaque HTML.
259
+ Fence state is tracked at the top level too, so gates quoted
260
+ inside ordinary code blocks stay code.
261
+ """
262
+
263
+ def __init__(self, md, config):
264
+ super().__init__(md)
265
+ self.config = config
266
+
267
+ def run(self, lines):
268
+ out = []
269
+ example = None
270
+ first = 0
271
+ fence = None
272
+ emitted = False
273
+ for number, line in enumerate(lines, start=1):
274
+ if example is None:
275
+ found = FENCE.match(line)
276
+ if fence is None and OPEN_GATE.match(line):
277
+ example = []
278
+ first = number
279
+ continue
280
+ if found:
281
+ if fence is None:
282
+ fence = found.group(1)
283
+ elif (
284
+ found.group(1)[0] == fence[0]
285
+ and len(found.group(1)) >= len(fence)
286
+ and not found.group(2).strip()
287
+ ):
288
+ fence = None
289
+ out.append(line)
290
+ else:
291
+ if CLOSE_GATE.match(line) and not self.inside_fence(
292
+ example
293
+ ):
294
+ element = self.render(
295
+ lines[first - 1], example, first
296
+ )
297
+ out.append("")
298
+ out.append(self.md.htmlStash.store(element))
299
+ out.append("")
300
+ example = None
301
+ emitted = True
302
+ continue
303
+ example.append(line)
304
+ if example is not None:
305
+ raise ExampleError(first, "unclosed #! gate: no matching !#")
306
+ if emitted and self.config["inject_script"]:
307
+ # As a literal line rather than a stash entry: script
308
+ # opens an HTML block, so Markdown passes it through
309
+ # unwrapped, where a stashed placeholder at document
310
+ # end can be left inside a paragraph.
311
+ out.append("")
312
+ out.append(
313
+ '<script type="module" src="'
314
+ + html.escape(self.config["script_url"])
315
+ + '"></script>'
316
+ )
317
+ out.append("")
318
+ return out
319
+
320
+ def inside_fence(self, lines):
321
+ """
322
+ Whether the region so far ends inside a fenced block, in
323
+ which case a !# line is content rather than the gate.
324
+ """
325
+ fence = None
326
+ for line in lines:
327
+ found = FENCE.match(line)
328
+ if not found:
329
+ continue
330
+ if fence is None:
331
+ fence = found.group(1)
332
+ elif (
333
+ found.group(1)[0] == fence[0]
334
+ and len(found.group(1)) >= len(fence)
335
+ and not found.group(2).strip()
336
+ ):
337
+ fence = None
338
+ return fence is not None
339
+
340
+ def render(self, header, lines, first_line):
341
+ """
342
+ One example: parse, validate, and emit the element with
343
+ its parts and captions in the author's order.
344
+ """
345
+ attributes = parse_gate(header, first_line)
346
+ pieces = split_example(lines, first_line + 1)
347
+ validate(pieces, attributes, first_line)
348
+ parts = ["<import-python"]
349
+ for name, value in attributes.items():
350
+ if value is None:
351
+ parts.append(f" {name}")
352
+ else:
353
+ parts.append(f' {name}="{html.escape(value)}"')
354
+ parts.append(">\n")
355
+ for piece in pieces:
356
+ parts.append(self.render_piece(piece))
357
+ parts.append("</import-python>")
358
+ return "".join(parts)
359
+
360
+ def render_piece(self, piece):
361
+ """
362
+ A caption renders as Markdown through a fresh renderer,
363
+ so the example's own gates cannot nest; a part becomes a
364
+ bare pre, a direct child - the element's contract - with
365
+ its text either highlighted or escaped, and never both by
366
+ hand: Pygments escapes what it colours, and the plain
367
+ path escapes here, so the author never types an entity.
368
+ That is also what makes a body block safe to write as
369
+ plain markup.
370
+ """
371
+ if piece["part"] == "prose":
372
+ inner = Markdown(
373
+ extensions=self.config["inner_extensions"]
374
+ )
375
+ return inner.convert("\n".join(piece["text"])) + "\n"
376
+ text, lit = self.paint("\n".join(piece["text"]), piece)
377
+ if piece["part"] == "file":
378
+ title = html.escape(piece["title"])
379
+ return f'<pre{lit} title="{title}">\n{text}\n</pre>\n'
380
+ if piece["part"] in ("config", "body"):
381
+ role = piece["part"]
382
+ return f'<pre{lit} data-role="{role}">\n{text}\n</pre>\n'
383
+ return f"<pre{lit}>\n{text}\n</pre>\n"
384
+
385
+ def paint(self, code, piece):
386
+ """
387
+ Highlight a part's code as Pygments spans with no wrapper
388
+ of any kind, so the pre stays a bare direct child and its
389
+ textContent stays exactly the code. The class="highlight"
390
+ the coloured path adds is what lets a Material or
391
+ Zensical site's existing Pygments stylesheet colour these
392
+ blocks, palettes and all, with no CSS of ours.
393
+
394
+ The language comes from the fence, or a file's name, with
395
+ json and html assumed for config and body; an unknown or
396
+ absent language falls back to plain escaped text, as the
397
+ wider ecosystem does, because colour is decoration rather
398
+ than contract.
399
+ """
400
+ lexer = None
401
+ if self.config["highlight"]:
402
+ language = piece.get("language")
403
+ if piece["part"] == "config":
404
+ language = "json"
405
+ elif piece["part"] == "body":
406
+ language = "html"
407
+ try:
408
+ if language:
409
+ lexer = get_lexer_by_name(language)
410
+ elif piece["part"] == "file":
411
+ lexer = get_lexer_for_filename(piece["title"])
412
+ except ClassNotFound:
413
+ lexer = None
414
+ if lexer is None:
415
+ return html.escape(code, quote=False), ""
416
+ painted = highlight(
417
+ code, lexer, HtmlFormatter(nowrap=True)
418
+ ).rstrip("\n")
419
+ return painted, ' class="highlight"'
420
+
421
+
422
+ class ImportPythonExtension(Extension):
423
+ """
424
+ The extension: register the preprocessor early, before other
425
+ preprocessors can mistake the gated region for their own.
426
+ """
427
+
428
+ def __init__(self, **kwargs):
429
+ self.config = {
430
+ "script_url": [
431
+ "https://importpython.org/v/test/embed.js",
432
+ "Where embed.js is served from; point this at "
433
+ "your own copy to use one.",
434
+ ],
435
+ "inject_script": [
436
+ True,
437
+ "Append one script tag to any page that carries "
438
+ "an example. Turn off for sites that load "
439
+ "embed.js themselves.",
440
+ ],
441
+ "inner_extensions": [
442
+ [],
443
+ "Markdown extensions applied to the captions "
444
+ "inside an example.",
445
+ ],
446
+ "highlight": [
447
+ True,
448
+ "Colour the code with Pygments spans inside the "
449
+ "bare pre, marked class=\"highlight\" so a "
450
+ "site's existing Pygments stylesheet applies.",
451
+ ],
452
+ }
453
+ super().__init__(**kwargs)
454
+
455
+ def extendMarkdown(self, md):
456
+ # The element must be known as block-level, or the raw
457
+ # HTML postprocessor leaves the stashed element wrapped
458
+ # in a paragraph - and a pre inside a p makes browsers
459
+ # close the paragraph early, structurally breaking the
460
+ # direct-child contract the plugin exists to honour.
461
+ md.block_level_elements.append("import-python")
462
+ md.preprocessors.register(
463
+ ImportPythonPreprocessor(md, self.getConfigs()),
464
+ "import-python",
465
+ 28,
466
+ )
467
+
468
+
469
+ def makeExtension(**kwargs):
470
+ """
471
+ The hook Python-Markdown looks for when the extension is
472
+ named by its module path.
473
+ """
474
+ return ImportPythonExtension(**kwargs)
@@ -0,0 +1,74 @@
1
+ Metadata-Version: 2.4
2
+ Name: importpython-markdown
3
+ Version: 0.1.1
4
+ Summary: Runnable Python examples in Markdown, via importpython.org.
5
+ Author-email: "Nicholas H.Tollervey" <ntoll@ntoll.org>
6
+ License: MIT
7
+ Project-URL: Homepage, https://importpython.org/
8
+ Project-URL: Repository, https://codeberg.org/ntoll/importpython
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Documentation
14
+ Classifier: Topic :: Text Processing :: Markup :: Markdown
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: markdown>=3.4
19
+ Requires-Dist: pygments>=2.14
20
+ Dynamic: license-file
21
+
22
+ # importpython-markdown
23
+
24
+ Runnable Python examples in Markdown pages, for MkDocs, Zensical
25
+ and anything else built on Python-Markdown, powered by
26
+ [importpython.org](https://importpython.org/).
27
+
28
+ Wrap a section of ordinary Markdown in `#!` and `!#` gates:
29
+
30
+ #!mpy terminal title="A first example"
31
+
32
+ A caption, rendered as normal Markdown.
33
+
34
+ ```python
35
+ print("Hello, world!")
36
+ ```
37
+
38
+ !#
39
+
40
+ The section becomes a runnable example: the code, a Run button,
41
+ and the program's output beneath - nothing downloaded until a
42
+ reader presses Run. Plain fences are the program; a fence with
43
+ `title="name.py"` is a file delivered beside it; `config` and
44
+ `body` fences carry BFP settings and page markup (escaped for
45
+ you). The `py` and `mpy` types choose Pyodide or MicroPython,
46
+ and `terminal`, `debug`, `send-embedder-url`, `title="..."`,
47
+ `run-label="..."`, `stop-label="..."`, `theme="..."`,
48
+ `terminal-rows="..."`, `terminal-cols="..."`, `class` and `id`
49
+ pass through to the element - each documented at
50
+ [importpython.org](https://importpython.org/docs/writing-markdown/).
51
+
52
+ Install and enable:
53
+
54
+ pip install importpython-markdown
55
+
56
+ ```yaml
57
+ # mkdocs.yml
58
+ markdown_extensions:
59
+ - importpython
60
+ ```
61
+
62
+ ```toml
63
+ # zensical.toml
64
+ [project.markdown_extensions]
65
+ importpython = {}
66
+ ```
67
+
68
+ Pre-release honesty: until BFP's first release, the default
69
+ `script_url` points at the service's test channel, which may
70
+ change; pin your own copy with the `script_url` option if that
71
+ matters to you today.
72
+
73
+ The full documentation lives at
74
+ [importpython.org/docs](https://importpython.org/docs/).
@@ -0,0 +1,11 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/importpython_markdown/__init__.py
5
+ src/importpython_markdown.egg-info/PKG-INFO
6
+ src/importpython_markdown.egg-info/SOURCES.txt
7
+ src/importpython_markdown.egg-info/dependency_links.txt
8
+ src/importpython_markdown.egg-info/entry_points.txt
9
+ src/importpython_markdown.egg-info/requires.txt
10
+ src/importpython_markdown.egg-info/top_level.txt
11
+ tests/test_extension.py
@@ -0,0 +1,2 @@
1
+ [markdown.extensions]
2
+ importpython = importpython_markdown:ImportPythonExtension
@@ -0,0 +1,2 @@
1
+ markdown>=3.4
2
+ pygments>=2.14
@@ -0,0 +1,345 @@
1
+ """
2
+ Unit tests for importpython-markdown: the gates, the mappings,
3
+ the escaping, the validation, and the script tag - one test per
4
+ rule, so a failure names its rule.
5
+ """
6
+
7
+ import markdown
8
+ import pytest
9
+
10
+ from importpython_markdown import ExampleError
11
+
12
+
13
+ def render(text, **options):
14
+ """
15
+ Render Markdown with the extension configured as a user
16
+ would configure it.
17
+ """
18
+ md = markdown.Markdown(
19
+ extensions=["importpython_markdown"],
20
+ extension_configs={"importpython_markdown": options},
21
+ )
22
+ return md.convert(text)
23
+
24
+
25
+ EXAMPLE = """\
26
+ #!py terminal debug
27
+
28
+ Here is the Foo module.
29
+
30
+ ```title="foo.py"
31
+ def foo():
32
+ return 42
33
+ ```
34
+
35
+ * Some
36
+ * Random
37
+ * Markdown
38
+
39
+ ```
40
+ import foo
41
+
42
+ print(foo.foo())
43
+ ```
44
+ !#
45
+ """
46
+
47
+
48
+ def test_the_worked_example():
49
+ """
50
+ Intent: the example from the design conversation renders as
51
+ one element with a file, two captions, and the program, in
52
+ the author's order, with the flags carried across.
53
+ """
54
+ out = render(EXAMPLE)
55
+ assert '<import-python type="py" terminal debug>' in out
56
+ assert 'title="foo.py"' in out
57
+ assert "foo" in out
58
+ assert "<li>Random</li>" in out
59
+ assert "print(foo.foo())" in out
60
+ assert out.index("Foo module") < out.index('title="foo.py"')
61
+ assert out.index("<li>Some") < out.index("import foo")
62
+ assert out.count("<import-python") == 1
63
+
64
+
65
+ def test_untouched_without_gates():
66
+ """
67
+ Intent: a document with no gates is not our business, and no
68
+ script tag is added to it.
69
+ """
70
+ out = render("# Hello\n\nJust prose.\n")
71
+ assert "import-python" not in out
72
+ assert "embed.js" not in out
73
+
74
+
75
+ def test_gate_inside_a_fence_is_code():
76
+ """
77
+ Intent: documentation about the gates can quote them - a #!
78
+ line inside an ordinary fenced block opens nothing.
79
+ """
80
+ out = render("```\n#!py\n!#\n```\n")
81
+ assert "import-python" not in out
82
+
83
+
84
+ def test_close_gate_inside_inner_fence_is_content():
85
+ """
86
+ Intent: a !# inside a fenced block inside the gates is code
87
+ (somebody's shell snippet), not the closing gate.
88
+ """
89
+ out = render(
90
+ '#!mpy\n```title="notes.sh"\n!#\n```\n\n'
91
+ "```\nprint('hi')\n```\n!#\n"
92
+ )
93
+ assert out.count("<import-python") == 1
94
+ assert ">\n!#\n</pre>" in out
95
+
96
+
97
+ def test_attributes_pass_through_escaped():
98
+ """
99
+ Intent: valued attributes reach the element, HTML-escaped,
100
+ and the accessible-name convention survives the trip.
101
+ """
102
+ out = render(
103
+ '#!mpy title="A & B" run-label="Go"\n\n'
104
+ "```\nprint(1)\n```\n!#\n"
105
+ )
106
+ assert 'title="A &amp; B"' in out
107
+ assert 'run-label="Go"' in out
108
+
109
+
110
+ def test_program_is_escaped():
111
+ """
112
+ Intent: the two characters HTML cares about are escaped for
113
+ the author, so what runs is what was written.
114
+ """
115
+ out = render(
116
+ "#!mpy\n\n```\nprint(1 < 2 & 3)\n```\n!#\n",
117
+ highlight=False,
118
+ )
119
+ assert "print(1 &lt; 2 &amp; 3)" in out
120
+
121
+
122
+ def test_body_is_escaped_for_the_author():
123
+ """
124
+ Intent: a body block is written as plain markup and arrives
125
+ escaped, the two-character chore done by the machine.
126
+ """
127
+ out = render(
128
+ "#!mpy\n\n```body\n<p id=\"out\"></p>\n```\n\n"
129
+ "```\nprint(1)\n```\n!#\n"
130
+ )
131
+ assert 'data-role="body"' in out
132
+ assert "&lt;" in out and "<p id=" not in out
133
+
134
+
135
+ def test_config_maps_and_validates():
136
+ """
137
+ Intent: a config fence becomes the config block, and only
138
+ valid JSON is allowed through.
139
+ """
140
+ out = render(
141
+ '#!py\n\n```config\n{ "packages": ["arrr"] }\n```\n\n'
142
+ "```\nimport arrr\n```\n!#\n"
143
+ )
144
+ assert 'data-role="config"' in out
145
+ with pytest.raises(ExampleError, match="not valid JSON"):
146
+ render("#!py\n\n```config\nnope\n```\n\n```\nx\n```\n!#\n")
147
+
148
+
149
+ def test_unknown_type_fails_the_build():
150
+ """
151
+ Intent: a typo in the runtime is a build failure that names
152
+ the valid choices.
153
+ """
154
+ with pytest.raises(ExampleError, match='unknown type "pyy"'):
155
+ render("#!pyy\n\n```\nx\n```\n!#\n")
156
+
157
+
158
+ def test_unknown_flag_and_attribute_fail_the_build():
159
+ """
160
+ Intent: the allow-list catches typos at build time rather
161
+ than shipping silently ignored attributes.
162
+ """
163
+ with pytest.raises(ExampleError, match='unknown flag "terminl"'):
164
+ render("#!py terminl\n\n```\nx\n```\n!#\n")
165
+ with pytest.raises(ExampleError, match='unknown attribute "titel"'):
166
+ render('#!py titel="x"\n\n```\nx\n```\n!#\n')
167
+
168
+
169
+ def test_the_element_rules_apply_at_build_time():
170
+ """
171
+ Intent: classify()'s structural rules, spoken here in the
172
+ same words: one program, no duplicate filenames, one config.
173
+ """
174
+ with pytest.raises(ExampleError, match="no program block"):
175
+ render("#!py\n\nJust prose.\n!#\n")
176
+ with pytest.raises(ExampleError, match="more than one program"):
177
+ render("#!py\n\n```\na\n```\n\n```\nb\n```\n!#\n")
178
+ with pytest.raises(ExampleError, match='name the file "a.py"'):
179
+ render(
180
+ '#!py\n\n```title="a.py"\nx\n```\n\n'
181
+ '```title="a.py"\ny\n```\n\n```\nz\n```\n!#\n'
182
+ )
183
+
184
+
185
+ def test_unclosed_gate_fails_the_build():
186
+ """
187
+ Intent: a forgotten !# is a named build failure, not a page
188
+ quietly swallowed to its end.
189
+ """
190
+ with pytest.raises(ExampleError, match="unclosed #! gate"):
191
+ render("#!py\n\n```\nx\n```\n")
192
+
193
+
194
+ def test_script_tag_once_for_many_examples():
195
+ """
196
+ Intent: a page with examples gets exactly one script tag,
197
+ however many examples it carries, and its URL is the
198
+ configured one.
199
+ """
200
+ two = EXAMPLE + "\n" + EXAMPLE
201
+ out = render(two, script_url="/v/test/embed.js")
202
+ assert out.count("<import-python") == 2
203
+ assert out.count('src="/v/test/embed.js"') == 1
204
+ assert 'type="module"' in out
205
+
206
+
207
+ def test_script_injection_can_be_turned_off():
208
+ """
209
+ Intent: sites loading embed.js themselves can say so and get
210
+ no second copy.
211
+ """
212
+ out = render(EXAMPLE, inject_script=False)
213
+ assert "embed.js" not in out
214
+
215
+
216
+ def test_highlighting_is_spans_in_a_bare_pre():
217
+ """
218
+ Intent: colour arrives as Pygments spans inside the bare pre
219
+ direct child, marked class="highlight" so a site's existing
220
+ Pygments stylesheet applies - never a wrapper element, which
221
+ would hide the pre from the element.
222
+ """
223
+ out = render("#!mpy\n\n```python\nprint(1)\n```\n!#\n")
224
+ assert '<pre class="highlight">' in out
225
+ assert '<span class="nb">print</span>' in out
226
+ assert "<div" not in out
227
+ assert "<code" not in out
228
+
229
+
230
+ def test_file_language_guessed_from_its_name():
231
+ """
232
+ Intent: a file block with no language on the fence is
233
+ coloured by its filename's extension.
234
+ """
235
+ out = render(
236
+ '#!mpy\n\n```title="a.py"\nx = 1\n```\n\n'
237
+ "```\nimport a\n```\n!#\n"
238
+ )
239
+ assert 'class="highlight" title="a.py"' in out
240
+
241
+
242
+ def test_unknown_language_falls_back_to_plain():
243
+ """
244
+ Intent: colour is decoration, not contract - a language
245
+ Pygments does not know renders plain and escaped, exactly as
246
+ the wider ecosystem behaves.
247
+ """
248
+ out = render("#!mpy\n\n```pyton\nprint(1 < 2)\n```\n!#\n")
249
+ assert "<span" not in out
250
+ assert "1 &lt; 2" in out
251
+
252
+
253
+ def test_config_and_body_get_their_languages():
254
+ """
255
+ Intent: config is coloured as JSON and body as HTML, with the
256
+ body's markup still escaped so its textContent is the markup.
257
+ """
258
+ out = render(
259
+ '#!py\n\n```config\n{ "packages": ["x"] }\n```\n\n'
260
+ '```body\n<p id="o"></p>\n```\n\n```\nz\n```\n!#\n'
261
+ )
262
+ assert out.count("<span") >= 2
263
+ assert "<p id=" not in out
264
+
265
+
266
+ def test_the_element_is_never_paragraph_wrapped():
267
+ """
268
+ Intent: the element and the script tag stand as blocks - a
269
+ pre inside a paragraph would make browsers close the
270
+ paragraph early and break the direct-child contract.
271
+ """
272
+ out = render(EXAMPLE)
273
+ assert "<p><import-python" not in out
274
+ assert "<p><script" not in out
275
+
276
+
277
+ def test_send_embedder_url_flag_passes_through():
278
+ """
279
+ Intent: the flag is allow-listed and reaches the element as
280
+ its attribute, so the page's embed.js can act on it.
281
+ """
282
+ out = render(
283
+ "#!mpy send-embedder-url\n\n```\nimport importpython\n```\n!#\n"
284
+ )
285
+ assert "send-embedder-url" in out.split(">")[0]
286
+
287
+
288
+ def test_send_embedder_url_reserves_the_filename():
289
+ """
290
+ Intent: while the flag is on, importpython.py belongs to the
291
+ service - a titled block or a configured files entry by that
292
+ name is a named build failure, never a silent overwrite.
293
+ """
294
+ with pytest.raises(ExampleError, match="reserves the file"):
295
+ render(
296
+ "#!mpy send-embedder-url\n\n"
297
+ '```title="importpython.py"\nx\n```\n\n'
298
+ "```\nimport importpython\n```\n!#\n"
299
+ )
300
+ with pytest.raises(ExampleError, match="reserves the file"):
301
+ render(
302
+ "#!mpy send-embedder-url\n\n"
303
+ "```config\n"
304
+ '{ "files": { "data:x": "./importpython.py" } }\n'
305
+ "```\n\n```\nimport importpython\n```\n!#\n"
306
+ )
307
+ # Without the flag, the name is the author's to use.
308
+ out = render(
309
+ '#!mpy\n\n```title="importpython.py"\nx = 1\n```\n\n'
310
+ "```\nimport importpython\n```\n!#\n"
311
+ )
312
+ assert 'title="importpython.py"' in out
313
+
314
+
315
+ def test_terminal_size_passes_through():
316
+ """
317
+ Intent: terminal-rows and terminal-cols are allow-listed valued
318
+ attributes that reach the element, sized and named as BFP
319
+ has them.
320
+ """
321
+ out = render(
322
+ '#!mpy terminal terminal-rows="4" terminal-cols="60"\n\n'
323
+ "```\nprint(1)\n```\n!#\n"
324
+ )
325
+ assert 'terminal-rows="4"' in out
326
+ assert 'terminal-cols="60"' in out
327
+
328
+
329
+ def test_terminal_size_is_validated_at_build_time():
330
+ """
331
+ Intent: a dimension without the terminal flag, or a value
332
+ that is not a positive whole number, fails the build with
333
+ the element's own words - never a runtime error in a
334
+ reader's browser.
335
+ """
336
+ with pytest.raises(ExampleError, match="requires the terminal"):
337
+ render('#!mpy terminal-rows="4"\n\n```\nx\n```\n!#\n')
338
+ with pytest.raises(ExampleError, match="positive whole"):
339
+ render(
340
+ '#!mpy terminal terminal-rows="0"\n\n```\nx\n```\n!#\n'
341
+ )
342
+ with pytest.raises(ExampleError, match="positive whole"):
343
+ render(
344
+ '#!mpy terminal terminal-cols="wide"\n\n```\nx\n```\n!#\n'
345
+ )
@@ -1,7 +0,0 @@
1
- Metadata-Version: 2.5
2
- Name: importpython-markdown
3
- Version: 0.0.1
4
- Summary: A markdown plugin to use importpython in docs.
5
- Author-email: "Nicholas H.Tollervey" <ntoll@ntoll.org>
6
- License-Expression: MIT
7
- Requires-Python: >=3.11
@@ -1,16 +0,0 @@
1
- [build-system]
2
- requires = ["hatchling"]
3
- build-backend = "hatchling.build"
4
-
5
- [project]
6
- name = "importpython-markdown"
7
- dynamic = ["version"]
8
- description = "A markdown plugin to use importpython in docs."
9
- requires-python = ">=3.11"
10
- license = "MIT"
11
- authors = [
12
- {name = "Nicholas H.Tollervey", email = "ntoll@ntoll.org"},
13
- ]
14
-
15
- [tool.hatch.version]
16
- path = "src/importpython_markdown/__init__.py"
@@ -1,5 +0,0 @@
1
- """
2
- importpython-markdown
3
- """
4
-
5
- __version__ = "0.0.1"