mddoco 2.2.2__tar.gz → 2.3.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 (43) hide show
  1. {mddoco-2.2.2/src/mddoco.egg-info → mddoco-2.3.0}/PKG-INFO +59 -8
  2. {mddoco-2.2.2 → mddoco-2.3.0}/README.md +58 -7
  3. {mddoco-2.2.2 → mddoco-2.3.0}/pyproject.toml +1 -1
  4. mddoco-2.3.0/src/mddoco/__init__.py +1 -0
  5. {mddoco-2.2.2 → mddoco-2.3.0}/src/mddoco/converter.py +2 -0
  6. mddoco-2.3.0/src/mddoco/d2.py +83 -0
  7. {mddoco-2.2.2 → mddoco-2.3.0}/src/mddoco/themes/_site_base.html +2 -1
  8. {mddoco-2.2.2 → mddoco-2.3.0}/src/mddoco/themes/academic.html +3 -2
  9. {mddoco-2.2.2 → mddoco-2.3.0}/src/mddoco/themes/dark.html +3 -2
  10. {mddoco-2.2.2 → mddoco-2.3.0}/src/mddoco/themes/default.html +3 -2
  11. {mddoco-2.2.2 → mddoco-2.3.0}/src/mddoco/themes/paged-professional.html +2 -1
  12. {mddoco-2.2.2 → mddoco-2.3.0}/src/mddoco/themes/professional.html +2 -1
  13. {mddoco-2.2.2 → mddoco-2.3.0/src/mddoco.egg-info}/PKG-INFO +59 -8
  14. {mddoco-2.2.2 → mddoco-2.3.0}/src/mddoco.egg-info/SOURCES.txt +2 -0
  15. mddoco-2.3.0/tests/test_d2.py +113 -0
  16. {mddoco-2.2.2 → mddoco-2.3.0}/tests/test_preprocessor.py +1 -1
  17. mddoco-2.2.2/src/mddoco/__init__.py +0 -1
  18. {mddoco-2.2.2 → mddoco-2.3.0}/LICENSE +0 -0
  19. {mddoco-2.2.2 → mddoco-2.3.0}/setup.cfg +0 -0
  20. {mddoco-2.2.2 → mddoco-2.3.0}/src/mddoco/cli.py +0 -0
  21. {mddoco-2.2.2 → mddoco-2.3.0}/src/mddoco/graph.py +0 -0
  22. {mddoco-2.2.2 → mddoco-2.3.0}/src/mddoco/mermaid.py +0 -0
  23. {mddoco-2.2.2 → mddoco-2.3.0}/src/mddoco/pdf.py +0 -0
  24. {mddoco-2.2.2 → mddoco-2.3.0}/src/mddoco/preprocessor.py +0 -0
  25. {mddoco-2.2.2 → mddoco-2.3.0}/src/mddoco/renderer.py +0 -0
  26. {mddoco-2.2.2 → mddoco-2.3.0}/src/mddoco/scanner.py +0 -0
  27. {mddoco-2.2.2 → mddoco-2.3.0}/src/mddoco/themes/academic-wide.html +0 -0
  28. {mddoco-2.2.2 → mddoco-2.3.0}/src/mddoco/themes/dark-wide.html +0 -0
  29. {mddoco-2.2.2 → mddoco-2.3.0}/src/mddoco/themes/default-wide.html +0 -0
  30. {mddoco-2.2.2 → mddoco-2.3.0}/src/mddoco/themes/professional-wide.html +0 -0
  31. {mddoco-2.2.2 → mddoco-2.3.0}/src/mddoco/themes/site-dark.html +0 -0
  32. {mddoco-2.2.2 → mddoco-2.3.0}/src/mddoco/themes/site-professional.html +0 -0
  33. {mddoco-2.2.2 → mddoco-2.3.0}/src/mddoco/themes/site-terminal.html +0 -0
  34. {mddoco-2.2.2 → mddoco-2.3.0}/src/mddoco/themes/site.html +0 -0
  35. {mddoco-2.2.2 → mddoco-2.3.0}/src/mddoco/themes/vanilla.html +0 -0
  36. {mddoco-2.2.2 → mddoco-2.3.0}/src/mddoco/toc.py +0 -0
  37. {mddoco-2.2.2 → mddoco-2.3.0}/src/mddoco/writer.py +0 -0
  38. {mddoco-2.2.2 → mddoco-2.3.0}/src/mddoco.egg-info/dependency_links.txt +0 -0
  39. {mddoco-2.2.2 → mddoco-2.3.0}/src/mddoco.egg-info/entry_points.txt +0 -0
  40. {mddoco-2.2.2 → mddoco-2.3.0}/src/mddoco.egg-info/requires.txt +0 -0
  41. {mddoco-2.2.2 → mddoco-2.3.0}/src/mddoco.egg-info/top_level.txt +0 -0
  42. {mddoco-2.2.2 → mddoco-2.3.0}/tests/test_themes.py +0 -0
  43. {mddoco-2.2.2 → mddoco-2.3.0}/tests/test_toc.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mddoco
3
- Version: 2.2.2
3
+ Version: 2.3.0
4
4
  Summary: Markdown to HTML/PDF document converter
5
5
  Author-email: Phil Massyn <phil.massyn@icloud.com>
6
6
  Project-URL: Homepage, https://github.com/massyn/mddoco
@@ -22,12 +22,14 @@ Dynamic: license-file
22
22
 
23
23
  # mddoco
24
24
 
25
- A CLI tool that converts markdown files to a single HTML (or future PDF) document.
25
+ A CLI tool that converts markdown files to a single HTML or PDF document.
26
26
 
27
27
  [![Publish to PyPI](https://github.com/massyn/mddoco/actions/workflows/ci.yml/badge.svg)](https://github.com/massyn/mddoco/actions/workflows/ci.yml)
28
28
  ![PyPI Version](https://img.shields.io/pypi/v/mddoco) ![PyPI Downloads](https://img.shields.io/pypi/dd/mddoco)
29
29
  ## Installation
30
30
 
31
+ mddoco needs Python 3.10 or newer.
32
+
31
33
  ```bash
32
34
  pip install mddoco
33
35
  ```
@@ -48,6 +50,10 @@ pip install -e .
48
50
  > playwright install chromium
49
51
  > ```
50
52
 
53
+ > **The `d2` command-line tool is required only if your documents contain
54
+ > [D2 diagrams](#d2-diagrams).** It is a separate program, not a Python
55
+ > package, so `pip` does not install it. See [Installing the D2 CLI](#installing-the-d2-cli).
56
+
51
57
  ## Usage
52
58
 
53
59
  ```
@@ -60,8 +66,8 @@ mddoco [OPTIONS] INPUT_PATH
60
66
 
61
67
  | Option | Short | Default | Description |
62
68
  |---|---|---|---|
63
- | `--output PATH` | `-o` | `.` | Directory to write the output file |
64
- | `--format [html\|pdf]` | `-f` | `html` | Output format |
69
+ | `--output PATH` | `-o` | `.` | Output directory, or an explicit file path if it has an extension (`-o out/report.html`) |
70
+ | `--format [html\|pdf]` | `-f` | `html` | Output format (PDF needs Playwright; the `site-*` themes are HTML only) |
65
71
  | `--title TEXT` | `-t` | _(none)_ | Document title shown at the top of the page |
66
72
  | `--theme NAME` | | `default` | Theme to use for rendering |
67
73
  | `--toc / --no-toc` | | off | Generate a table of contents |
@@ -89,11 +95,11 @@ mddoco ./docs --title "My Project" --toc --output ./out
89
95
 
90
96
  ## Output
91
97
 
92
- All matched markdown files are combined into a single HTML document in the output directory. The filename is derived from the input folder or file name.
98
+ All matched markdown files are combined into a single document in the output directory, as HTML (the default) or PDF (`--format pdf`). The filename is derived from the input folder or file name, with the `.html` or `.pdf` extension. If `--output` ends in an extension, it is used as the exact output file path instead.
93
99
 
94
100
  ## Examples
95
101
 
96
- The [`examples/`](examples/) directory contains five runnable input folders, each
102
+ The [`examples/`](examples/) directory contains six runnable input folders, each
97
103
  covering a different feature:
98
104
 
99
105
  | Folder | Demonstrates |
@@ -103,6 +109,7 @@ covering a different feature:
103
109
  | [`examples/03_themed_report`](examples/03_themed_report) | Themes and a table of contents |
104
110
  | [`examples/04_jinja_data`](examples/04_jinja_data) | Jinja2 templates with JSON and CSV data files |
105
111
  | [`examples/05_security_findings`](examples/05_security_findings) | CSV data grouped in a Jinja2 template and fed into a `graph` chart |
112
+ | [`examples/06_d2_diagrams`](examples/06_d2_diagrams) | D2 diagrams (requires the `d2` CLI) |
106
113
 
107
114
  ```bash
108
115
  mddoco examples/03_themed_report --theme professional --title "Q3 Platform Review" --toc --output ./out
@@ -205,7 +212,9 @@ All themes support:
205
212
 
206
213
  - Optional document title
207
214
  - Optional table of contents (the `site-*` themes use their side nav instead)
208
- - [Mermaid.js](https://mermaid.js.org) diagram support (loaded only when diagrams are present)
215
+ - Syntax highlighting for code blocks ([highlight.js](https://highlightjs.org), loaded from a CDN only when code blocks are present)
216
+ - [Mermaid.js](https://mermaid.js.org) diagram support (loaded from a CDN only when diagrams are present)
217
+ - [D2](https://d2lang.com) diagrams, rendered to inline SVG at build time (needs the `d2` CLI, only when diagrams are present)
209
218
  - Graph diagram blocks
210
219
 
211
220
  ### Site themes
@@ -249,7 +258,7 @@ Use ` ```graph ` fenced blocks with a JSON payload. The only required field is `
249
258
  ```
250
259
  ````
251
260
 
252
- Series are inferred from the data keys (everything except `x`). Each series defaults to a line chart in blue.
261
+ Series are inferred from the data keys (everything except `x`). Each series defaults to a line chart, coloured from a built-in palette.
253
262
 
254
263
  **Full schema:**
255
264
 
@@ -307,3 +316,45 @@ graph TD
307
316
  ````
308
317
 
309
318
  mddoco detects mermaid blocks automatically and loads the Mermaid.js CDN only when needed.
319
+
320
+ ### D2 diagrams
321
+
322
+ [D2](https://d2lang.com) diagrams use the same fenced-block syntax:
323
+
324
+ ````markdown
325
+ ```d2
326
+ direction: right
327
+ client -> server: request
328
+ server -> db: query
329
+ ```
330
+ ````
331
+
332
+ Unlike Mermaid, D2 diagrams are rendered while mddoco builds the document, by the `d2` command-line tool, and embedded as inline SVG. The output has no extra scripts, works offline, and prints to PDF without waiting for anything to load.
333
+
334
+ - The `d2` CLI must be installed and on your `PATH` (see below). It is only needed when a document contains a `d2` block; otherwise mddoco never looks for it.
335
+ - A diagram that fails to compile stops the build with D2's error message, the same as an invalid `graph` block.
336
+ - A diagram that takes longer than 30 seconds to compile stops the build with a timeout error.
337
+
338
+ #### Installing the D2 CLI
339
+
340
+ `d2` is a standalone program from the [D2 project](https://d2lang.com), not a Python package. Install it with one of the following, then check that it is on your `PATH`:
341
+
342
+ ```bash
343
+ d2 --version
344
+ ```
345
+
346
+ | Platform | Command |
347
+ |---|---|
348
+ | macOS (Homebrew) | `brew install d2` |
349
+ | Linux and macOS (install script) | `curl -fsSL https://d2lang.com/install.sh \| sh -s --` |
350
+ | Windows (Scoop) | `scoop install main/d2` |
351
+ | Windows (Chocolatey) | `choco install d2` |
352
+ | Windows (installer) | Download the `.msi` from the [releases page](https://github.com/d2lang/d2/releases); it adds `d2` to your `PATH` |
353
+ | Any platform with Go | `go install github.com/d2lang/d2@latest` |
354
+
355
+ - **Install script:** run it with `--dry-run` first (`curl -fsSL https://d2lang.com/install.sh | sh -s -- --dry-run`) to see what it will do. It uses a package manager when it finds one, and otherwise installs under `/usr/local`, or `~/.local` if `/usr/local` needs `sudo`. If it tells you to adjust `PATH`, do that.
356
+ - **Standalone download:** archives for each platform are on the [releases page](https://github.com/d2lang/d2/releases). Extract one and run `make install`, or `make install PREFIX=$HOME/.local` to install without `sudo`.
357
+ - **Other options and details:** see the [D2 install guide](https://d2lang.com/tour/install).
358
+ - **CI:** install `d2` in the workflow before building documents that contain D2 diagrams, for example by downloading a pinned release archive as this repository's own [workflow](.github/workflows/ci.yml) does.
359
+
360
+ If `d2` is missing, mddoco stops with an error pointing to the install guide, and only when it finds a `d2` block.
@@ -1,11 +1,13 @@
1
1
  # mddoco
2
2
 
3
- A CLI tool that converts markdown files to a single HTML (or future PDF) document.
3
+ A CLI tool that converts markdown files to a single HTML or PDF document.
4
4
 
5
5
  [![Publish to PyPI](https://github.com/massyn/mddoco/actions/workflows/ci.yml/badge.svg)](https://github.com/massyn/mddoco/actions/workflows/ci.yml)
6
6
  ![PyPI Version](https://img.shields.io/pypi/v/mddoco) ![PyPI Downloads](https://img.shields.io/pypi/dd/mddoco)
7
7
  ## Installation
8
8
 
9
+ mddoco needs Python 3.10 or newer.
10
+
9
11
  ```bash
10
12
  pip install mddoco
11
13
  ```
@@ -26,6 +28,10 @@ pip install -e .
26
28
  > playwright install chromium
27
29
  > ```
28
30
 
31
+ > **The `d2` command-line tool is required only if your documents contain
32
+ > [D2 diagrams](#d2-diagrams).** It is a separate program, not a Python
33
+ > package, so `pip` does not install it. See [Installing the D2 CLI](#installing-the-d2-cli).
34
+
29
35
  ## Usage
30
36
 
31
37
  ```
@@ -38,8 +44,8 @@ mddoco [OPTIONS] INPUT_PATH
38
44
 
39
45
  | Option | Short | Default | Description |
40
46
  |---|---|---|---|
41
- | `--output PATH` | `-o` | `.` | Directory to write the output file |
42
- | `--format [html\|pdf]` | `-f` | `html` | Output format |
47
+ | `--output PATH` | `-o` | `.` | Output directory, or an explicit file path if it has an extension (`-o out/report.html`) |
48
+ | `--format [html\|pdf]` | `-f` | `html` | Output format (PDF needs Playwright; the `site-*` themes are HTML only) |
43
49
  | `--title TEXT` | `-t` | _(none)_ | Document title shown at the top of the page |
44
50
  | `--theme NAME` | | `default` | Theme to use for rendering |
45
51
  | `--toc / --no-toc` | | off | Generate a table of contents |
@@ -67,11 +73,11 @@ mddoco ./docs --title "My Project" --toc --output ./out
67
73
 
68
74
  ## Output
69
75
 
70
- All matched markdown files are combined into a single HTML document in the output directory. The filename is derived from the input folder or file name.
76
+ All matched markdown files are combined into a single document in the output directory, as HTML (the default) or PDF (`--format pdf`). The filename is derived from the input folder or file name, with the `.html` or `.pdf` extension. If `--output` ends in an extension, it is used as the exact output file path instead.
71
77
 
72
78
  ## Examples
73
79
 
74
- The [`examples/`](examples/) directory contains five runnable input folders, each
80
+ The [`examples/`](examples/) directory contains six runnable input folders, each
75
81
  covering a different feature:
76
82
 
77
83
  | Folder | Demonstrates |
@@ -81,6 +87,7 @@ covering a different feature:
81
87
  | [`examples/03_themed_report`](examples/03_themed_report) | Themes and a table of contents |
82
88
  | [`examples/04_jinja_data`](examples/04_jinja_data) | Jinja2 templates with JSON and CSV data files |
83
89
  | [`examples/05_security_findings`](examples/05_security_findings) | CSV data grouped in a Jinja2 template and fed into a `graph` chart |
90
+ | [`examples/06_d2_diagrams`](examples/06_d2_diagrams) | D2 diagrams (requires the `d2` CLI) |
84
91
 
85
92
  ```bash
86
93
  mddoco examples/03_themed_report --theme professional --title "Q3 Platform Review" --toc --output ./out
@@ -183,7 +190,9 @@ All themes support:
183
190
 
184
191
  - Optional document title
185
192
  - Optional table of contents (the `site-*` themes use their side nav instead)
186
- - [Mermaid.js](https://mermaid.js.org) diagram support (loaded only when diagrams are present)
193
+ - Syntax highlighting for code blocks ([highlight.js](https://highlightjs.org), loaded from a CDN only when code blocks are present)
194
+ - [Mermaid.js](https://mermaid.js.org) diagram support (loaded from a CDN only when diagrams are present)
195
+ - [D2](https://d2lang.com) diagrams, rendered to inline SVG at build time (needs the `d2` CLI, only when diagrams are present)
187
196
  - Graph diagram blocks
188
197
 
189
198
  ### Site themes
@@ -227,7 +236,7 @@ Use ` ```graph ` fenced blocks with a JSON payload. The only required field is `
227
236
  ```
228
237
  ````
229
238
 
230
- Series are inferred from the data keys (everything except `x`). Each series defaults to a line chart in blue.
239
+ Series are inferred from the data keys (everything except `x`). Each series defaults to a line chart, coloured from a built-in palette.
231
240
 
232
241
  **Full schema:**
233
242
 
@@ -285,3 +294,45 @@ graph TD
285
294
  ````
286
295
 
287
296
  mddoco detects mermaid blocks automatically and loads the Mermaid.js CDN only when needed.
297
+
298
+ ### D2 diagrams
299
+
300
+ [D2](https://d2lang.com) diagrams use the same fenced-block syntax:
301
+
302
+ ````markdown
303
+ ```d2
304
+ direction: right
305
+ client -> server: request
306
+ server -> db: query
307
+ ```
308
+ ````
309
+
310
+ Unlike Mermaid, D2 diagrams are rendered while mddoco builds the document, by the `d2` command-line tool, and embedded as inline SVG. The output has no extra scripts, works offline, and prints to PDF without waiting for anything to load.
311
+
312
+ - The `d2` CLI must be installed and on your `PATH` (see below). It is only needed when a document contains a `d2` block; otherwise mddoco never looks for it.
313
+ - A diagram that fails to compile stops the build with D2's error message, the same as an invalid `graph` block.
314
+ - A diagram that takes longer than 30 seconds to compile stops the build with a timeout error.
315
+
316
+ #### Installing the D2 CLI
317
+
318
+ `d2` is a standalone program from the [D2 project](https://d2lang.com), not a Python package. Install it with one of the following, then check that it is on your `PATH`:
319
+
320
+ ```bash
321
+ d2 --version
322
+ ```
323
+
324
+ | Platform | Command |
325
+ |---|---|
326
+ | macOS (Homebrew) | `brew install d2` |
327
+ | Linux and macOS (install script) | `curl -fsSL https://d2lang.com/install.sh \| sh -s --` |
328
+ | Windows (Scoop) | `scoop install main/d2` |
329
+ | Windows (Chocolatey) | `choco install d2` |
330
+ | Windows (installer) | Download the `.msi` from the [releases page](https://github.com/d2lang/d2/releases); it adds `d2` to your `PATH` |
331
+ | Any platform with Go | `go install github.com/d2lang/d2@latest` |
332
+
333
+ - **Install script:** run it with `--dry-run` first (`curl -fsSL https://d2lang.com/install.sh | sh -s -- --dry-run`) to see what it will do. It uses a package manager when it finds one, and otherwise installs under `/usr/local`, or `~/.local` if `/usr/local` needs `sudo`. If it tells you to adjust `PATH`, do that.
334
+ - **Standalone download:** archives for each platform are on the [releases page](https://github.com/d2lang/d2/releases). Extract one and run `make install`, or `make install PREFIX=$HOME/.local` to install without `sudo`.
335
+ - **Other options and details:** see the [D2 install guide](https://d2lang.com/tour/install).
336
+ - **CI:** install `d2` in the workflow before building documents that contain D2 diagrams, for example by downloading a pinned release archive as this repository's own [workflow](.github/workflows/ci.yml) does.
337
+
338
+ If `d2` is missing, mddoco stops with an error pointing to the install guide, and only when it finds a `d2` block.
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "mddoco"
7
- version = "2.2.2"
7
+ version = "2.3.0"
8
8
  description = "Markdown to HTML/PDF document converter"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -0,0 +1 @@
1
+ __version__ = "2.3.0"
@@ -2,6 +2,7 @@ from pathlib import Path
2
2
 
3
3
  import markdown
4
4
 
5
+ from mddoco.d2 import process_d2
5
6
  from mddoco.graph import process_graph
6
7
  from mddoco.mermaid import process_mermaid
7
8
  from mddoco.preprocessor import render_j2
@@ -36,6 +37,7 @@ def convert_file(
36
37
  html = md.convert(text)
37
38
  html, _ = process_mermaid(html)
38
39
  html, _ = process_graph(html)
40
+ html, _ = process_d2(html)
39
41
 
40
42
  toc_entries = flatten_tokens(md.toc_tokens) if toc else []
41
43
  return html, toc_entries
@@ -0,0 +1,83 @@
1
+ import logging
2
+ import re
3
+ import shutil
4
+ import subprocess
5
+ from html import unescape
6
+
7
+ log = logging.getLogger(__name__)
8
+
9
+ _D2_BLOCK = re.compile(
10
+ r'<pre><code class="language-d2">(.*?)</code></pre>',
11
+ re.DOTALL,
12
+ )
13
+
14
+ _OUTER_SVG = re.compile(r'(?P<tag><svg\b[^>]*)\sviewBox="(?P<dims>[^"]+)"')
15
+
16
+ _INSTALL_HINT = (
17
+ "D2 diagrams require the 'd2' command-line tool, which was not found on "
18
+ "PATH. Install it from https://d2lang.com/tour/install"
19
+ )
20
+
21
+ _TIMEOUT_SECONDS = 30
22
+
23
+
24
+ def _render_d2(source: str) -> str:
25
+ """Compile D2 source with the d2 CLI and return an inline SVG element."""
26
+ d2 = shutil.which("d2")
27
+ if d2 is None:
28
+ raise RuntimeError(_INSTALL_HINT)
29
+
30
+ try:
31
+ result = subprocess.run(
32
+ [d2, "-", "-"],
33
+ input=unescape(source),
34
+ capture_output=True,
35
+ text=True,
36
+ encoding="utf-8",
37
+ timeout=_TIMEOUT_SECONDS,
38
+ )
39
+ except subprocess.TimeoutExpired as exc:
40
+ raise RuntimeError(f"d2 timed out after {_TIMEOUT_SECONDS}s") from exc
41
+
42
+ if result.returncode != 0:
43
+ detail = result.stderr.strip() or f"exit code {result.returncode}"
44
+ raise RuntimeError(f"d2 failed: {detail}")
45
+
46
+ start = result.stdout.find("<svg") # skip the XML declaration
47
+ svg = result.stdout[max(start, 0) :]
48
+ svg = _OUTER_SVG.sub(_with_natural_size, svg, count=1)
49
+ return f'<div class="d2">{svg}</div>'
50
+
51
+
52
+ def _with_natural_size(m: re.Match) -> str:
53
+ """Give the outer <svg> its viewBox size so it is not stretched to fit."""
54
+ dims = m.group("dims")
55
+ width, height = (round(float(v)) for v in dims.split()[2:])
56
+ return f'{m.group("tag")} viewBox="{dims}" width="{width}" height="{height}"'
57
+
58
+
59
+ def process_d2(html: str) -> tuple[str, bool]:
60
+ """Replace fenced d2 blocks with SVG diagrams rendered by the d2 CLI.
61
+
62
+ Raises on any render failure — errors are logged before raising so the
63
+ caller sees the problem on the console.
64
+ Returns (processed_html, found).
65
+ """
66
+ found = bool(_D2_BLOCK.search(html))
67
+ errors: list[Exception] = []
68
+
69
+ def replace(m: re.Match) -> str:
70
+ try:
71
+ return _render_d2(m.group(1))
72
+ except Exception as exc:
73
+ errors.append(exc)
74
+ return ""
75
+
76
+ processed = _D2_BLOCK.sub(replace, html)
77
+
78
+ for exc in errors:
79
+ log.error("D2 error: %s", exc)
80
+ if errors:
81
+ raise errors[0]
82
+
83
+ return processed, found
@@ -171,7 +171,8 @@
171
171
  }
172
172
  blockquote p { margin: 0.3em 0; }
173
173
 
174
- .mermaid { text-align: center; margin: 1.5em 0; }
174
+ .mermaid, .d2 { text-align: center; margin: 1.5em 0; }
175
+ .d2 svg { max-width: 100%; height: auto; }
175
176
 
176
177
  /* ── Previous / next ──────────────────────────────────────── */
177
178
  .site-pager {
@@ -140,11 +140,12 @@
140
140
  .toc-block a { color: #111; font-size: 0.9em; text-decoration: none; }
141
141
  .toc-block a:hover { text-decoration: underline; }
142
142
 
143
- /* Mermaid diagrams */
144
- .mermaid {
143
+ /* Mermaid and D2 diagrams */
144
+ .mermaid, .d2 {
145
145
  text-align: center;
146
146
  margin: 1.5em 0;
147
147
  }
148
+ .d2 svg { max-width: 100%; height: auto; }
148
149
 
149
150
  @media print {
150
151
  body { padding: 0; font-size: 12pt; }
@@ -141,11 +141,12 @@
141
141
  .toc-block > ul > li > a { font-weight: 700; }
142
142
  .toc-block a { color: var(--accent); font-size: 0.9em; }
143
143
 
144
- /* Mermaid diagrams */
145
- .mermaid {
144
+ /* Mermaid and D2 diagrams */
145
+ .mermaid, .d2 {
146
146
  text-align: center;
147
147
  margin: 1.5em 0;
148
148
  }
149
+ .d2 svg { max-width: 100%; height: auto; }
149
150
  /* body raises specificity above highlight.js's own pre code.hljs rule, which loads later */
150
151
  body pre code.hljs { background: transparent; padding: 0; }
151
152
  /* Print: no trailing space after the content, which would spill
@@ -122,11 +122,12 @@
122
122
  .toc-block > ul > li > a { font-weight: 700; }
123
123
  .toc-block a { color: #0366d6; font-size: 0.9em; }
124
124
 
125
- /* Mermaid diagrams */
126
- .mermaid {
125
+ /* Mermaid and D2 diagrams */
126
+ .mermaid, .d2 {
127
127
  text-align: center;
128
128
  margin: 1.5em 0;
129
129
  }
130
+ .d2 svg { max-width: 100%; height: auto; }
130
131
  /* body raises specificity above highlight.js's own pre code.hljs rule, which loads later */
131
132
  body pre code.hljs { background: transparent; padding: 0; }
132
133
  /* Print: no trailing space after the content, which would spill
@@ -212,7 +212,8 @@
212
212
  .toc-block a:hover { color: var(--accent); }
213
213
 
214
214
  /* ── Mermaid ────────────────────────────────────────────────── */
215
- .mermaid { text-align: center; margin: 1.5em 0; }
215
+ .mermaid, .d2 { text-align: center; margin: 1.5em 0; }
216
+ .d2 svg { max-width: 100%; height: auto; }
216
217
  /* body raises specificity above highlight.js's own pre code.hljs rule, which loads later */
217
218
  body pre code.hljs { background: transparent; padding: 0; }
218
219
  </style>
@@ -177,7 +177,8 @@
177
177
  .toc-block a:hover { color: var(--accent); }
178
178
 
179
179
  /* ── Mermaid ───────────────────────────────────────────────── */
180
- .mermaid { text-align: center; margin: 1.5em 0; }
180
+ .mermaid, .d2 { text-align: center; margin: 1.5em 0; }
181
+ .d2 svg { max-width: 100%; height: auto; }
181
182
  /* body raises specificity above highlight.js's own pre code.hljs rule, which loads later */
182
183
  body pre code.hljs { background: transparent; padding: 0; }
183
184
  /* Print: no trailing space after the content, which would spill
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mddoco
3
- Version: 2.2.2
3
+ Version: 2.3.0
4
4
  Summary: Markdown to HTML/PDF document converter
5
5
  Author-email: Phil Massyn <phil.massyn@icloud.com>
6
6
  Project-URL: Homepage, https://github.com/massyn/mddoco
@@ -22,12 +22,14 @@ Dynamic: license-file
22
22
 
23
23
  # mddoco
24
24
 
25
- A CLI tool that converts markdown files to a single HTML (or future PDF) document.
25
+ A CLI tool that converts markdown files to a single HTML or PDF document.
26
26
 
27
27
  [![Publish to PyPI](https://github.com/massyn/mddoco/actions/workflows/ci.yml/badge.svg)](https://github.com/massyn/mddoco/actions/workflows/ci.yml)
28
28
  ![PyPI Version](https://img.shields.io/pypi/v/mddoco) ![PyPI Downloads](https://img.shields.io/pypi/dd/mddoco)
29
29
  ## Installation
30
30
 
31
+ mddoco needs Python 3.10 or newer.
32
+
31
33
  ```bash
32
34
  pip install mddoco
33
35
  ```
@@ -48,6 +50,10 @@ pip install -e .
48
50
  > playwright install chromium
49
51
  > ```
50
52
 
53
+ > **The `d2` command-line tool is required only if your documents contain
54
+ > [D2 diagrams](#d2-diagrams).** It is a separate program, not a Python
55
+ > package, so `pip` does not install it. See [Installing the D2 CLI](#installing-the-d2-cli).
56
+
51
57
  ## Usage
52
58
 
53
59
  ```
@@ -60,8 +66,8 @@ mddoco [OPTIONS] INPUT_PATH
60
66
 
61
67
  | Option | Short | Default | Description |
62
68
  |---|---|---|---|
63
- | `--output PATH` | `-o` | `.` | Directory to write the output file |
64
- | `--format [html\|pdf]` | `-f` | `html` | Output format |
69
+ | `--output PATH` | `-o` | `.` | Output directory, or an explicit file path if it has an extension (`-o out/report.html`) |
70
+ | `--format [html\|pdf]` | `-f` | `html` | Output format (PDF needs Playwright; the `site-*` themes are HTML only) |
65
71
  | `--title TEXT` | `-t` | _(none)_ | Document title shown at the top of the page |
66
72
  | `--theme NAME` | | `default` | Theme to use for rendering |
67
73
  | `--toc / --no-toc` | | off | Generate a table of contents |
@@ -89,11 +95,11 @@ mddoco ./docs --title "My Project" --toc --output ./out
89
95
 
90
96
  ## Output
91
97
 
92
- All matched markdown files are combined into a single HTML document in the output directory. The filename is derived from the input folder or file name.
98
+ All matched markdown files are combined into a single document in the output directory, as HTML (the default) or PDF (`--format pdf`). The filename is derived from the input folder or file name, with the `.html` or `.pdf` extension. If `--output` ends in an extension, it is used as the exact output file path instead.
93
99
 
94
100
  ## Examples
95
101
 
96
- The [`examples/`](examples/) directory contains five runnable input folders, each
102
+ The [`examples/`](examples/) directory contains six runnable input folders, each
97
103
  covering a different feature:
98
104
 
99
105
  | Folder | Demonstrates |
@@ -103,6 +109,7 @@ covering a different feature:
103
109
  | [`examples/03_themed_report`](examples/03_themed_report) | Themes and a table of contents |
104
110
  | [`examples/04_jinja_data`](examples/04_jinja_data) | Jinja2 templates with JSON and CSV data files |
105
111
  | [`examples/05_security_findings`](examples/05_security_findings) | CSV data grouped in a Jinja2 template and fed into a `graph` chart |
112
+ | [`examples/06_d2_diagrams`](examples/06_d2_diagrams) | D2 diagrams (requires the `d2` CLI) |
106
113
 
107
114
  ```bash
108
115
  mddoco examples/03_themed_report --theme professional --title "Q3 Platform Review" --toc --output ./out
@@ -205,7 +212,9 @@ All themes support:
205
212
 
206
213
  - Optional document title
207
214
  - Optional table of contents (the `site-*` themes use their side nav instead)
208
- - [Mermaid.js](https://mermaid.js.org) diagram support (loaded only when diagrams are present)
215
+ - Syntax highlighting for code blocks ([highlight.js](https://highlightjs.org), loaded from a CDN only when code blocks are present)
216
+ - [Mermaid.js](https://mermaid.js.org) diagram support (loaded from a CDN only when diagrams are present)
217
+ - [D2](https://d2lang.com) diagrams, rendered to inline SVG at build time (needs the `d2` CLI, only when diagrams are present)
209
218
  - Graph diagram blocks
210
219
 
211
220
  ### Site themes
@@ -249,7 +258,7 @@ Use ` ```graph ` fenced blocks with a JSON payload. The only required field is `
249
258
  ```
250
259
  ````
251
260
 
252
- Series are inferred from the data keys (everything except `x`). Each series defaults to a line chart in blue.
261
+ Series are inferred from the data keys (everything except `x`). Each series defaults to a line chart, coloured from a built-in palette.
253
262
 
254
263
  **Full schema:**
255
264
 
@@ -307,3 +316,45 @@ graph TD
307
316
  ````
308
317
 
309
318
  mddoco detects mermaid blocks automatically and loads the Mermaid.js CDN only when needed.
319
+
320
+ ### D2 diagrams
321
+
322
+ [D2](https://d2lang.com) diagrams use the same fenced-block syntax:
323
+
324
+ ````markdown
325
+ ```d2
326
+ direction: right
327
+ client -> server: request
328
+ server -> db: query
329
+ ```
330
+ ````
331
+
332
+ Unlike Mermaid, D2 diagrams are rendered while mddoco builds the document, by the `d2` command-line tool, and embedded as inline SVG. The output has no extra scripts, works offline, and prints to PDF without waiting for anything to load.
333
+
334
+ - The `d2` CLI must be installed and on your `PATH` (see below). It is only needed when a document contains a `d2` block; otherwise mddoco never looks for it.
335
+ - A diagram that fails to compile stops the build with D2's error message, the same as an invalid `graph` block.
336
+ - A diagram that takes longer than 30 seconds to compile stops the build with a timeout error.
337
+
338
+ #### Installing the D2 CLI
339
+
340
+ `d2` is a standalone program from the [D2 project](https://d2lang.com), not a Python package. Install it with one of the following, then check that it is on your `PATH`:
341
+
342
+ ```bash
343
+ d2 --version
344
+ ```
345
+
346
+ | Platform | Command |
347
+ |---|---|
348
+ | macOS (Homebrew) | `brew install d2` |
349
+ | Linux and macOS (install script) | `curl -fsSL https://d2lang.com/install.sh \| sh -s --` |
350
+ | Windows (Scoop) | `scoop install main/d2` |
351
+ | Windows (Chocolatey) | `choco install d2` |
352
+ | Windows (installer) | Download the `.msi` from the [releases page](https://github.com/d2lang/d2/releases); it adds `d2` to your `PATH` |
353
+ | Any platform with Go | `go install github.com/d2lang/d2@latest` |
354
+
355
+ - **Install script:** run it with `--dry-run` first (`curl -fsSL https://d2lang.com/install.sh | sh -s -- --dry-run`) to see what it will do. It uses a package manager when it finds one, and otherwise installs under `/usr/local`, or `~/.local` if `/usr/local` needs `sudo`. If it tells you to adjust `PATH`, do that.
356
+ - **Standalone download:** archives for each platform are on the [releases page](https://github.com/d2lang/d2/releases). Extract one and run `make install`, or `make install PREFIX=$HOME/.local` to install without `sudo`.
357
+ - **Other options and details:** see the [D2 install guide](https://d2lang.com/tour/install).
358
+ - **CI:** install `d2` in the workflow before building documents that contain D2 diagrams, for example by downloading a pinned release archive as this repository's own [workflow](.github/workflows/ci.yml) does.
359
+
360
+ If `d2` is missing, mddoco stops with an error pointing to the install guide, and only when it finds a `d2` block.
@@ -4,6 +4,7 @@ pyproject.toml
4
4
  src/mddoco/__init__.py
5
5
  src/mddoco/cli.py
6
6
  src/mddoco/converter.py
7
+ src/mddoco/d2.py
7
8
  src/mddoco/graph.py
8
9
  src/mddoco/mermaid.py
9
10
  src/mddoco/pdf.py
@@ -33,6 +34,7 @@ src/mddoco/themes/site-professional.html
33
34
  src/mddoco/themes/site-terminal.html
34
35
  src/mddoco/themes/site.html
35
36
  src/mddoco/themes/vanilla.html
37
+ tests/test_d2.py
36
38
  tests/test_preprocessor.py
37
39
  tests/test_themes.py
38
40
  tests/test_toc.py
@@ -0,0 +1,113 @@
1
+ import shutil
2
+ import subprocess
3
+
4
+ import pytest
5
+
6
+ from mddoco import d2
7
+ from mddoco.d2 import process_d2
8
+
9
+
10
+ def _block(source: str) -> str:
11
+ return f'<pre><code class="language-d2">{source}</code></pre>'
12
+
13
+
14
+ def _fake_run(stdout="", stderr="", returncode=0, calls=None):
15
+ def run(cmd, **kwargs):
16
+ if calls is not None:
17
+ calls.append((cmd, kwargs))
18
+ return subprocess.CompletedProcess(cmd, returncode, stdout, stderr)
19
+
20
+ return run
21
+
22
+
23
+ @pytest.fixture
24
+ def fake_d2(monkeypatch):
25
+ monkeypatch.setattr(d2.shutil, "which", lambda name: "/usr/bin/d2")
26
+
27
+
28
+ def test_no_d2_blocks_leaves_html_untouched_and_needs_no_binary(monkeypatch):
29
+ monkeypatch.setattr(d2.shutil, "which", lambda name: None)
30
+ html = "<p>hello</p><pre><code>plain</code></pre>"
31
+ assert process_d2(html) == (html, False)
32
+
33
+
34
+ def test_block_replaced_with_inline_svg(fake_d2, monkeypatch):
35
+ svg = '<?xml version="1.0"?><svg viewBox="0 0 1 1"></svg>'
36
+ monkeypatch.setattr(d2.subprocess, "run", _fake_run(stdout=svg))
37
+ html, found = process_d2(f"<p>a</p>{_block('x -> y')}<p>b</p>")
38
+ assert found
39
+ assert html == (
40
+ '<p>a</p><div class="d2">'
41
+ '<svg viewBox="0 0 1 1" width="1" height="1"></svg></div><p>b</p>'
42
+ )
43
+
44
+
45
+ def test_outer_svg_gets_its_natural_size(fake_d2, monkeypatch):
46
+ svg = '<svg xmlns="x" viewBox="0 0 255.4 455"><svg width="1"></svg></svg>'
47
+ monkeypatch.setattr(d2.subprocess, "run", _fake_run(stdout=svg))
48
+ html, _ = process_d2(_block("x"))
49
+ assert '<svg xmlns="x" viewBox="0 0 255.4 455" width="255" height="455">' in html
50
+
51
+
52
+ def test_source_is_unescaped_and_sent_on_stdin(fake_d2, monkeypatch):
53
+ calls = []
54
+ monkeypatch.setattr(
55
+ d2.subprocess, "run", _fake_run(stdout="<svg></svg>", calls=calls)
56
+ )
57
+ process_d2(_block("x -&gt; y: &quot;hi&quot; &amp; bye"))
58
+ cmd, kwargs = calls[0]
59
+ assert cmd == ["/usr/bin/d2", "-", "-"]
60
+ assert kwargs["input"] == 'x -> y: "hi" & bye'
61
+
62
+
63
+ def test_multiple_blocks_each_rendered(fake_d2, monkeypatch):
64
+ calls = []
65
+ monkeypatch.setattr(
66
+ d2.subprocess, "run", _fake_run(stdout="<svg></svg>", calls=calls)
67
+ )
68
+ html, _ = process_d2(_block("a -> b") + _block("c -> d"))
69
+ assert html.count('<div class="d2">') == 2
70
+ assert len(calls) == 2
71
+
72
+
73
+ def test_compile_failure_raises_with_d2_message(fake_d2, monkeypatch):
74
+ monkeypatch.setattr(
75
+ d2.subprocess,
76
+ "run",
77
+ _fake_run(stderr="err: maps must be terminated", returncode=1),
78
+ )
79
+ html = _block("a -> {")
80
+ with pytest.raises(RuntimeError, match="maps must be terminated"):
81
+ process_d2(html)
82
+
83
+
84
+ def test_timeout_raises(fake_d2, monkeypatch):
85
+ def run(cmd, **kwargs):
86
+ raise subprocess.TimeoutExpired(cmd, kwargs["timeout"])
87
+
88
+ monkeypatch.setattr(d2.subprocess, "run", run)
89
+ html = _block("a -> b")
90
+ with pytest.raises(RuntimeError, match="timed out"):
91
+ process_d2(html)
92
+
93
+
94
+ def test_missing_binary_gives_install_hint(monkeypatch):
95
+ monkeypatch.setattr(d2.shutil, "which", lambda name: None)
96
+ html = _block("a -> b")
97
+ with pytest.raises(RuntimeError, match="d2lang.com/tour/install"):
98
+ process_d2(html)
99
+
100
+
101
+ @pytest.mark.skipif(shutil.which("d2") is None, reason="d2 CLI not installed")
102
+ def test_real_d2_renders_svg():
103
+ html, found = process_d2(_block("a -&gt; b: hello"))
104
+ assert found
105
+ assert html.startswith('<div class="d2"><svg')
106
+ assert "<?xml" not in html
107
+
108
+
109
+ @pytest.mark.skipif(shutil.which("d2") is None, reason="d2 CLI not installed")
110
+ def test_real_d2_rejects_invalid_source():
111
+ html = _block("a -&gt; {")
112
+ with pytest.raises(RuntimeError, match="d2 failed"):
113
+ process_d2(html)
@@ -14,7 +14,7 @@ from mddoco.preprocessor import (
14
14
 
15
15
 
16
16
  def test_version():
17
- assert mddoco.__version__ == "2.2.2"
17
+ assert mddoco.__version__ == "2.3.0"
18
18
 
19
19
 
20
20
  # --- _parse_csv_line ---
@@ -1 +0,0 @@
1
- __version__ = "2.2.2"
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes