mddoco 2.2.2__tar.gz → 2.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. {mddoco-2.2.2/src/mddoco.egg-info → mddoco-2.4.0}/PKG-INFO +107 -13
  2. {mddoco-2.2.2 → mddoco-2.4.0}/README.md +105 -12
  3. {mddoco-2.2.2 → mddoco-2.4.0}/pyproject.toml +2 -1
  4. mddoco-2.4.0/src/mddoco/__init__.py +1 -0
  5. {mddoco-2.2.2 → mddoco-2.4.0}/src/mddoco/cli.py +28 -11
  6. {mddoco-2.2.2 → mddoco-2.4.0}/src/mddoco/converter.py +10 -4
  7. mddoco-2.4.0/src/mddoco/d2.py +83 -0
  8. mddoco-2.4.0/src/mddoco/docx.py +296 -0
  9. {mddoco-2.2.2 → mddoco-2.4.0}/src/mddoco/renderer.py +7 -0
  10. {mddoco-2.2.2 → mddoco-2.4.0}/src/mddoco/themes/_site_base.html +2 -1
  11. {mddoco-2.2.2 → mddoco-2.4.0}/src/mddoco/themes/academic.html +3 -2
  12. {mddoco-2.2.2 → mddoco-2.4.0}/src/mddoco/themes/dark.html +3 -2
  13. {mddoco-2.2.2 → mddoco-2.4.0}/src/mddoco/themes/default.html +3 -2
  14. {mddoco-2.2.2 → mddoco-2.4.0}/src/mddoco/themes/paged-professional.html +2 -1
  15. {mddoco-2.2.2 → mddoco-2.4.0}/src/mddoco/themes/professional.html +2 -1
  16. {mddoco-2.2.2 → mddoco-2.4.0/src/mddoco.egg-info}/PKG-INFO +107 -13
  17. {mddoco-2.2.2 → mddoco-2.4.0}/src/mddoco.egg-info/SOURCES.txt +5 -0
  18. {mddoco-2.2.2 → mddoco-2.4.0}/src/mddoco.egg-info/requires.txt +1 -0
  19. mddoco-2.4.0/tests/test_d2.py +113 -0
  20. mddoco-2.4.0/tests/test_docx.py +152 -0
  21. mddoco-2.4.0/tests/test_jinja_formats.py +146 -0
  22. {mddoco-2.2.2 → mddoco-2.4.0}/tests/test_preprocessor.py +1 -1
  23. mddoco-2.2.2/src/mddoco/__init__.py +0 -1
  24. {mddoco-2.2.2 → mddoco-2.4.0}/LICENSE +0 -0
  25. {mddoco-2.2.2 → mddoco-2.4.0}/setup.cfg +0 -0
  26. {mddoco-2.2.2 → mddoco-2.4.0}/src/mddoco/graph.py +0 -0
  27. {mddoco-2.2.2 → mddoco-2.4.0}/src/mddoco/mermaid.py +0 -0
  28. {mddoco-2.2.2 → mddoco-2.4.0}/src/mddoco/pdf.py +0 -0
  29. {mddoco-2.2.2 → mddoco-2.4.0}/src/mddoco/preprocessor.py +0 -0
  30. {mddoco-2.2.2 → mddoco-2.4.0}/src/mddoco/scanner.py +0 -0
  31. {mddoco-2.2.2 → mddoco-2.4.0}/src/mddoco/themes/academic-wide.html +0 -0
  32. {mddoco-2.2.2 → mddoco-2.4.0}/src/mddoco/themes/dark-wide.html +0 -0
  33. {mddoco-2.2.2 → mddoco-2.4.0}/src/mddoco/themes/default-wide.html +0 -0
  34. {mddoco-2.2.2 → mddoco-2.4.0}/src/mddoco/themes/professional-wide.html +0 -0
  35. {mddoco-2.2.2 → mddoco-2.4.0}/src/mddoco/themes/site-dark.html +0 -0
  36. {mddoco-2.2.2 → mddoco-2.4.0}/src/mddoco/themes/site-professional.html +0 -0
  37. {mddoco-2.2.2 → mddoco-2.4.0}/src/mddoco/themes/site-terminal.html +0 -0
  38. {mddoco-2.2.2 → mddoco-2.4.0}/src/mddoco/themes/site.html +0 -0
  39. {mddoco-2.2.2 → mddoco-2.4.0}/src/mddoco/themes/vanilla.html +0 -0
  40. {mddoco-2.2.2 → mddoco-2.4.0}/src/mddoco/toc.py +0 -0
  41. {mddoco-2.2.2 → mddoco-2.4.0}/src/mddoco/writer.py +0 -0
  42. {mddoco-2.2.2 → mddoco-2.4.0}/src/mddoco.egg-info/dependency_links.txt +0 -0
  43. {mddoco-2.2.2 → mddoco-2.4.0}/src/mddoco.egg-info/entry_points.txt +0 -0
  44. {mddoco-2.2.2 → mddoco-2.4.0}/src/mddoco.egg-info/top_level.txt +0 -0
  45. {mddoco-2.2.2 → mddoco-2.4.0}/tests/test_themes.py +0 -0
  46. {mddoco-2.2.2 → mddoco-2.4.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.4.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
@@ -16,18 +16,21 @@ Requires-Dist: playwright>=1.40
16
16
  Requires-Dist: matplotlib>=3.7
17
17
  Provides-Extra: dev
18
18
  Requires-Dist: pytest>=8.0; extra == "dev"
19
+ Requires-Dist: pypdf>=4.0; extra == "dev"
19
20
  Requires-Dist: black>=24.0; extra == "dev"
20
21
  Requires-Dist: ruff<0.17,>=0.16; extra == "dev"
21
22
  Dynamic: license-file
22
23
 
23
24
  # mddoco
24
25
 
25
- A CLI tool that converts markdown files to a single HTML (or future PDF) document.
26
+ A CLI tool that converts markdown files to a single HTML, PDF or Word document.
26
27
 
27
28
  [![Publish to PyPI](https://github.com/massyn/mddoco/actions/workflows/ci.yml/badge.svg)](https://github.com/massyn/mddoco/actions/workflows/ci.yml)
28
29
  ![PyPI Version](https://img.shields.io/pypi/v/mddoco) ![PyPI Downloads](https://img.shields.io/pypi/dd/mddoco)
29
30
  ## Installation
30
31
 
32
+ mddoco needs Python 3.10 or newer.
33
+
31
34
  ```bash
32
35
  pip install mddoco
33
36
  ```
@@ -38,9 +41,9 @@ Or for development:
38
41
  pip install -e .
39
42
  ```
40
43
 
41
- > **Playwright (Chromium) is required for PDF output only.** HTML output works without it.
44
+ > **Playwright (Chromium) is required for PDF output, and for diagrams in Word output.** HTML output works without it.
42
45
  > The `playwright` Python package is installed automatically, but the Chromium
43
- > browser it drives is not. The first time you render a PDF, mddoco downloads
46
+ > browser it drives is not. The first time you need it, mddoco downloads
44
47
  > Chromium for you (~150 MB, one time). To do it ahead of time, or if the
45
48
  > automatic download fails, run it yourself:
46
49
  >
@@ -48,6 +51,14 @@ pip install -e .
48
51
  > playwright install chromium
49
52
  > ```
50
53
 
54
+ > **The `d2` command-line tool is required only if your documents contain
55
+ > [D2 diagrams](#d2-diagrams).** It is a separate program, not a Python
56
+ > package, so `pip` does not install it. See [Installing the D2 CLI](#installing-the-d2-cli).
57
+
58
+ > **The `pandoc` command-line tool is required only for [Word output](#word-output)
59
+ > (`--format docx`).** It is a separate program, not a Python package. See
60
+ > [Installing Pandoc](#installing-pandoc).
61
+
51
62
  ## Usage
52
63
 
53
64
  ```
@@ -60,11 +71,11 @@ mddoco [OPTIONS] INPUT_PATH
60
71
 
61
72
  | Option | Short | Default | Description |
62
73
  |---|---|---|---|
63
- | `--output PATH` | `-o` | `.` | Directory to write the output file |
64
- | `--format [html\|pdf]` | `-f` | `html` | Output format |
74
+ | `--output PATH` | `-o` | `.` | Output directory, or an explicit file path if it has an extension (`-o out/report.html`) |
75
+ | `--format [html\|pdf\|docx]` | `-f` | `html` | Output format (PDF needs Playwright; Word needs Pandoc, plus Playwright when diagrams are present; the `site-*` themes are HTML only) |
65
76
  | `--title TEXT` | `-t` | _(none)_ | Document title shown at the top of the page |
66
- | `--theme NAME` | | `default` | Theme to use for rendering |
67
- | `--toc / --no-toc` | | off | Generate a table of contents |
77
+ | `--theme NAME` | | `default` | Theme to use for rendering (HTML and PDF only; Word output rejects any theme but `default`) |
78
+ | `--toc / --no-toc` | | off | Generate a table of contents (ignored, with a warning, for Word output) |
68
79
  | `--toc-depth N` | | `3` | Maximum heading depth included in the TOC (1–6) |
69
80
 
70
81
  ### Examples
@@ -87,13 +98,20 @@ With a title, TOC, and custom output directory:
87
98
  mddoco ./docs --title "My Project" --toc --output ./out
88
99
  ```
89
100
 
101
+ As a PDF or a Word document:
102
+
103
+ ```bash
104
+ mddoco ./docs --format pdf
105
+ mddoco ./docs --format docx
106
+ ```
107
+
90
108
  ## Output
91
109
 
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.
110
+ All matched markdown files are combined into a single document in the output directory, as HTML (the default), PDF (`--format pdf`) or Word (`--format docx`). The filename is derived from the input folder or file name, with the `.html`, `.pdf` or `.docx` extension. If `--output` ends in an extension, it is used as the exact output file path instead.
93
111
 
94
112
  ## Examples
95
113
 
96
- The [`examples/`](examples/) directory contains five runnable input folders, each
114
+ The [`examples/`](examples/) directory contains six runnable input folders, each
97
115
  covering a different feature:
98
116
 
99
117
  | Folder | Demonstrates |
@@ -103,6 +121,7 @@ covering a different feature:
103
121
  | [`examples/03_themed_report`](examples/03_themed_report) | Themes and a table of contents |
104
122
  | [`examples/04_jinja_data`](examples/04_jinja_data) | Jinja2 templates with JSON and CSV data files |
105
123
  | [`examples/05_security_findings`](examples/05_security_findings) | CSV data grouped in a Jinja2 template and fed into a `graph` chart |
124
+ | [`examples/06_d2_diagrams`](examples/06_d2_diagrams) | D2 diagrams (requires the `d2` CLI) |
106
125
 
107
126
  ```bash
108
127
  mddoco examples/03_themed_report --theme professional --title "Q3 Platform Review" --toc --output ./out
@@ -205,7 +224,9 @@ All themes support:
205
224
 
206
225
  - Optional document title
207
226
  - 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)
227
+ - Syntax highlighting for code blocks ([highlight.js](https://highlightjs.org), loaded from a CDN only when code blocks are present)
228
+ - [Mermaid.js](https://mermaid.js.org) diagram support (loaded from a CDN only when diagrams are present)
229
+ - [D2](https://d2lang.com) diagrams, rendered to inline SVG at build time (needs the `d2` CLI, only when diagrams are present)
209
230
  - Graph diagram blocks
210
231
 
211
232
  ### Site themes
@@ -249,7 +270,7 @@ Use ` ```graph ` fenced blocks with a JSON payload. The only required field is `
249
270
  ```
250
271
  ````
251
272
 
252
- Series are inferred from the data keys (everything except `x`). Each series defaults to a line chart in blue.
273
+ Series are inferred from the data keys (everything except `x`). Each series defaults to a line chart, coloured from a built-in palette.
253
274
 
254
275
  **Full schema:**
255
276
 
@@ -306,4 +327,77 @@ graph TD
306
327
  ```
307
328
  ````
308
329
 
309
- mddoco detects mermaid blocks automatically and loads the Mermaid.js CDN only when needed.
330
+ mddoco detects mermaid blocks automatically and loads the Mermaid.js CDN only when needed. In Word output, Mermaid diagrams are drawn to PNG images, which needs network access to load Mermaid.js.
331
+
332
+ ### D2 diagrams
333
+
334
+ [D2](https://d2lang.com) diagrams use the same fenced-block syntax:
335
+
336
+ ````markdown
337
+ ```d2
338
+ direction: right
339
+ client -> server: request
340
+ server -> db: query
341
+ ```
342
+ ````
343
+
344
+ 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. In Word output the SVG is converted to a PNG image.
345
+
346
+ - 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.
347
+ - A diagram that fails to compile stops the build with D2's error message, the same as an invalid `graph` block.
348
+ - A diagram that takes longer than 30 seconds to compile stops the build with a timeout error.
349
+
350
+ #### Installing the D2 CLI
351
+
352
+ `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`:
353
+
354
+ ```bash
355
+ d2 --version
356
+ ```
357
+
358
+ | Platform | Command |
359
+ |---|---|
360
+ | macOS (Homebrew) | `brew install d2` |
361
+ | Linux and macOS (install script) | `curl -fsSL https://d2lang.com/install.sh \| sh -s --` |
362
+ | Windows (Scoop) | `scoop install main/d2` |
363
+ | Windows (Chocolatey) | `choco install d2` |
364
+ | Windows (installer) | Download the `.msi` from the [releases page](https://github.com/d2lang/d2/releases); it adds `d2` to your `PATH` |
365
+ | Any platform with Go | `go install github.com/d2lang/d2@latest` |
366
+
367
+ - **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.
368
+ - **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`.
369
+ - **Other options and details:** see the [D2 install guide](https://d2lang.com/tour/install).
370
+ - **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.
371
+
372
+ If `d2` is missing, mddoco stops with an error pointing to the install guide, and only when it finds a `d2` block.
373
+
374
+ ## Word output
375
+
376
+ `--format docx` writes a Word document:
377
+
378
+ ```bash
379
+ mddoco docs/ --format docx --title "Security Findings" -o out/
380
+ ```
381
+
382
+ mddoco renders any Jinja2 templates, draws each `graph`, `d2` and `mermaid` block to a PNG image, and passes the result to [Pandoc](https://pandoc.org). Every table then gets grid borders, cell padding and a bold, shaded header row. The borders are written onto each table, because Google Docs keeps them reliably that way.
383
+
384
+ - **Requirements:** `pandoc` on your `PATH`, and Playwright with Chromium (needed only when the document has `graph`, `d2` or `mermaid` blocks, to draw them as images; installed the same way as for PDF output). `d2` is needed only when a document has a `d2` block.
385
+ - **Mermaid needs network access.** It is drawn in Chromium with the pinned Mermaid.js loaded from a CDN. `graph` and `d2` diagrams are drawn offline.
386
+ - **No table of contents.** Insert one in Word, or in Google Docs with Insert > Table of contents. `--toc` is ignored with a warning.
387
+ - **No themes.** The themes are browser HTML and CSS, so `--theme` with anything other than `default` is an error. The document uses Word's default styles.
388
+ - **Code blocks** keep their syntax colours.
389
+
390
+ ### Google Docs
391
+
392
+ There is no Google Docs file format. To get a Google Doc, upload the `.docx` to Google Drive, then right-click it and choose Open with > Google Docs, or open it and choose File > Save as Google Docs.
393
+
394
+ ### Installing Pandoc
395
+
396
+ | Platform | Command |
397
+ |---|---|
398
+ | macOS (Homebrew) | `brew install pandoc` |
399
+ | Debian and Ubuntu | `sudo apt-get install pandoc` |
400
+ | Windows (Chocolatey) | `choco install pandoc` |
401
+ | Any platform | Download an installer from [pandoc.org/installing.html](https://pandoc.org/installing.html) |
402
+
403
+ Check it with `pandoc --version`. If `pandoc` is missing, mddoco stops with an error pointing to the install page.
@@ -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, PDF or Word 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
  ```
@@ -16,9 +18,9 @@ Or for development:
16
18
  pip install -e .
17
19
  ```
18
20
 
19
- > **Playwright (Chromium) is required for PDF output only.** HTML output works without it.
21
+ > **Playwright (Chromium) is required for PDF output, and for diagrams in Word output.** HTML output works without it.
20
22
  > The `playwright` Python package is installed automatically, but the Chromium
21
- > browser it drives is not. The first time you render a PDF, mddoco downloads
23
+ > browser it drives is not. The first time you need it, mddoco downloads
22
24
  > Chromium for you (~150 MB, one time). To do it ahead of time, or if the
23
25
  > automatic download fails, run it yourself:
24
26
  >
@@ -26,6 +28,14 @@ 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
+
35
+ > **The `pandoc` command-line tool is required only for [Word output](#word-output)
36
+ > (`--format docx`).** It is a separate program, not a Python package. See
37
+ > [Installing Pandoc](#installing-pandoc).
38
+
29
39
  ## Usage
30
40
 
31
41
  ```
@@ -38,11 +48,11 @@ mddoco [OPTIONS] INPUT_PATH
38
48
 
39
49
  | Option | Short | Default | Description |
40
50
  |---|---|---|---|
41
- | `--output PATH` | `-o` | `.` | Directory to write the output file |
42
- | `--format [html\|pdf]` | `-f` | `html` | Output format |
51
+ | `--output PATH` | `-o` | `.` | Output directory, or an explicit file path if it has an extension (`-o out/report.html`) |
52
+ | `--format [html\|pdf\|docx]` | `-f` | `html` | Output format (PDF needs Playwright; Word needs Pandoc, plus Playwright when diagrams are present; the `site-*` themes are HTML only) |
43
53
  | `--title TEXT` | `-t` | _(none)_ | Document title shown at the top of the page |
44
- | `--theme NAME` | | `default` | Theme to use for rendering |
45
- | `--toc / --no-toc` | | off | Generate a table of contents |
54
+ | `--theme NAME` | | `default` | Theme to use for rendering (HTML and PDF only; Word output rejects any theme but `default`) |
55
+ | `--toc / --no-toc` | | off | Generate a table of contents (ignored, with a warning, for Word output) |
46
56
  | `--toc-depth N` | | `3` | Maximum heading depth included in the TOC (1–6) |
47
57
 
48
58
  ### Examples
@@ -65,13 +75,20 @@ With a title, TOC, and custom output directory:
65
75
  mddoco ./docs --title "My Project" --toc --output ./out
66
76
  ```
67
77
 
78
+ As a PDF or a Word document:
79
+
80
+ ```bash
81
+ mddoco ./docs --format pdf
82
+ mddoco ./docs --format docx
83
+ ```
84
+
68
85
  ## Output
69
86
 
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.
87
+ All matched markdown files are combined into a single document in the output directory, as HTML (the default), PDF (`--format pdf`) or Word (`--format docx`). The filename is derived from the input folder or file name, with the `.html`, `.pdf` or `.docx` extension. If `--output` ends in an extension, it is used as the exact output file path instead.
71
88
 
72
89
  ## Examples
73
90
 
74
- The [`examples/`](examples/) directory contains five runnable input folders, each
91
+ The [`examples/`](examples/) directory contains six runnable input folders, each
75
92
  covering a different feature:
76
93
 
77
94
  | Folder | Demonstrates |
@@ -81,6 +98,7 @@ covering a different feature:
81
98
  | [`examples/03_themed_report`](examples/03_themed_report) | Themes and a table of contents |
82
99
  | [`examples/04_jinja_data`](examples/04_jinja_data) | Jinja2 templates with JSON and CSV data files |
83
100
  | [`examples/05_security_findings`](examples/05_security_findings) | CSV data grouped in a Jinja2 template and fed into a `graph` chart |
101
+ | [`examples/06_d2_diagrams`](examples/06_d2_diagrams) | D2 diagrams (requires the `d2` CLI) |
84
102
 
85
103
  ```bash
86
104
  mddoco examples/03_themed_report --theme professional --title "Q3 Platform Review" --toc --output ./out
@@ -183,7 +201,9 @@ All themes support:
183
201
 
184
202
  - Optional document title
185
203
  - 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)
204
+ - Syntax highlighting for code blocks ([highlight.js](https://highlightjs.org), loaded from a CDN only when code blocks are present)
205
+ - [Mermaid.js](https://mermaid.js.org) diagram support (loaded from a CDN only when diagrams are present)
206
+ - [D2](https://d2lang.com) diagrams, rendered to inline SVG at build time (needs the `d2` CLI, only when diagrams are present)
187
207
  - Graph diagram blocks
188
208
 
189
209
  ### Site themes
@@ -227,7 +247,7 @@ Use ` ```graph ` fenced blocks with a JSON payload. The only required field is `
227
247
  ```
228
248
  ````
229
249
 
230
- Series are inferred from the data keys (everything except `x`). Each series defaults to a line chart in blue.
250
+ Series are inferred from the data keys (everything except `x`). Each series defaults to a line chart, coloured from a built-in palette.
231
251
 
232
252
  **Full schema:**
233
253
 
@@ -284,4 +304,77 @@ graph TD
284
304
  ```
285
305
  ````
286
306
 
287
- mddoco detects mermaid blocks automatically and loads the Mermaid.js CDN only when needed.
307
+ mddoco detects mermaid blocks automatically and loads the Mermaid.js CDN only when needed. In Word output, Mermaid diagrams are drawn to PNG images, which needs network access to load Mermaid.js.
308
+
309
+ ### D2 diagrams
310
+
311
+ [D2](https://d2lang.com) diagrams use the same fenced-block syntax:
312
+
313
+ ````markdown
314
+ ```d2
315
+ direction: right
316
+ client -> server: request
317
+ server -> db: query
318
+ ```
319
+ ````
320
+
321
+ 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. In Word output the SVG is converted to a PNG image.
322
+
323
+ - 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.
324
+ - A diagram that fails to compile stops the build with D2's error message, the same as an invalid `graph` block.
325
+ - A diagram that takes longer than 30 seconds to compile stops the build with a timeout error.
326
+
327
+ #### Installing the D2 CLI
328
+
329
+ `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`:
330
+
331
+ ```bash
332
+ d2 --version
333
+ ```
334
+
335
+ | Platform | Command |
336
+ |---|---|
337
+ | macOS (Homebrew) | `brew install d2` |
338
+ | Linux and macOS (install script) | `curl -fsSL https://d2lang.com/install.sh \| sh -s --` |
339
+ | Windows (Scoop) | `scoop install main/d2` |
340
+ | Windows (Chocolatey) | `choco install d2` |
341
+ | Windows (installer) | Download the `.msi` from the [releases page](https://github.com/d2lang/d2/releases); it adds `d2` to your `PATH` |
342
+ | Any platform with Go | `go install github.com/d2lang/d2@latest` |
343
+
344
+ - **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.
345
+ - **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`.
346
+ - **Other options and details:** see the [D2 install guide](https://d2lang.com/tour/install).
347
+ - **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.
348
+
349
+ If `d2` is missing, mddoco stops with an error pointing to the install guide, and only when it finds a `d2` block.
350
+
351
+ ## Word output
352
+
353
+ `--format docx` writes a Word document:
354
+
355
+ ```bash
356
+ mddoco docs/ --format docx --title "Security Findings" -o out/
357
+ ```
358
+
359
+ mddoco renders any Jinja2 templates, draws each `graph`, `d2` and `mermaid` block to a PNG image, and passes the result to [Pandoc](https://pandoc.org). Every table then gets grid borders, cell padding and a bold, shaded header row. The borders are written onto each table, because Google Docs keeps them reliably that way.
360
+
361
+ - **Requirements:** `pandoc` on your `PATH`, and Playwright with Chromium (needed only when the document has `graph`, `d2` or `mermaid` blocks, to draw them as images; installed the same way as for PDF output). `d2` is needed only when a document has a `d2` block.
362
+ - **Mermaid needs network access.** It is drawn in Chromium with the pinned Mermaid.js loaded from a CDN. `graph` and `d2` diagrams are drawn offline.
363
+ - **No table of contents.** Insert one in Word, or in Google Docs with Insert > Table of contents. `--toc` is ignored with a warning.
364
+ - **No themes.** The themes are browser HTML and CSS, so `--theme` with anything other than `default` is an error. The document uses Word's default styles.
365
+ - **Code blocks** keep their syntax colours.
366
+
367
+ ### Google Docs
368
+
369
+ There is no Google Docs file format. To get a Google Doc, upload the `.docx` to Google Drive, then right-click it and choose Open with > Google Docs, or open it and choose File > Save as Google Docs.
370
+
371
+ ### Installing Pandoc
372
+
373
+ | Platform | Command |
374
+ |---|---|
375
+ | macOS (Homebrew) | `brew install pandoc` |
376
+ | Debian and Ubuntu | `sudo apt-get install pandoc` |
377
+ | Windows (Chocolatey) | `choco install pandoc` |
378
+ | Any platform | Download an installer from [pandoc.org/installing.html](https://pandoc.org/installing.html) |
379
+
380
+ Check it with `pandoc --version`. If `pandoc` is missing, mddoco stops with an error pointing to the install page.
@@ -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.4.0"
8
8
  description = "Markdown to HTML/PDF document converter"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -22,6 +22,7 @@ dependencies = [
22
22
  [project.optional-dependencies]
23
23
  dev = [
24
24
  "pytest>=8.0",
25
+ "pypdf>=4.0",
25
26
  "black>=24.0",
26
27
  "ruff>=0.16,<0.17",
27
28
  ]
@@ -0,0 +1 @@
1
+ __version__ = "2.4.0"
@@ -4,6 +4,7 @@ from pathlib import Path
4
4
  import click
5
5
 
6
6
  from mddoco.converter import convert_files
7
+ from mddoco.docx import build_docx
7
8
  from mddoco.pdf import html_to_pdf
8
9
  from mddoco.preprocessor import load_context
9
10
  from mddoco.renderer import check_theme_format, render_html
@@ -29,7 +30,7 @@ from mddoco.writer import write_output
29
30
  "fmt",
30
31
  default="html",
31
32
  show_default=True,
32
- type=click.Choice(["html", "pdf"], case_sensitive=False),
33
+ type=click.Choice(["html", "pdf", "docx"], case_sensitive=False),
33
34
  help="Output format.",
34
35
  )
35
36
  @click.option("--title", "-t", default=None, help="Document title.")
@@ -76,16 +77,6 @@ def main(
76
77
 
77
78
  click.echo(f"Found {len(md_files)} markdown file(s).")
78
79
 
79
- try:
80
- context = load_context(input_path)
81
- raw = convert_files(md_files, toc=toc, toc_depth=toc_depth, context=context)
82
- except Exception as exc:
83
- raise click.ClickException(str(exc)) from exc
84
- sections = [(p, html) for p, html, _ in raw]
85
- toc_html = build_toc([e for _, _, entries in raw for e in entries]) if toc else None
86
- has_mermaid = any('<div class="mermaid">' in html for _, html in sections)
87
- has_code = any("<pre><code" in html for _, html in sections)
88
-
89
80
  # Resolve output directory and filename.
90
81
  # If output_path has a suffix, treat it as an explicit file path.
91
82
  # Otherwise treat it as a directory and derive the filename from the input.
@@ -98,6 +89,32 @@ def main(
98
89
  out_dir = output_path
99
90
  out_filename = f"{stem}.{fmt}"
100
91
 
92
+ if fmt == "docx":
93
+ if toc:
94
+ click.echo(
95
+ "Warning: --toc is ignored for Word output. In Word or Google Docs, "
96
+ "use Insert > Table of contents.",
97
+ err=True,
98
+ )
99
+ dest = out_dir / out_filename
100
+ click.echo("Building Word document...")
101
+ try:
102
+ build_docx(md_files, dest, context=load_context(input_path), title=title)
103
+ except Exception as exc:
104
+ raise click.ClickException(str(exc)) from exc
105
+ click.echo(f"Written to {dest}")
106
+ return
107
+
108
+ try:
109
+ context = load_context(input_path)
110
+ raw = convert_files(md_files, toc=toc, toc_depth=toc_depth, context=context)
111
+ except Exception as exc:
112
+ raise click.ClickException(str(exc)) from exc
113
+ sections = [(p, html) for p, html, _ in raw]
114
+ toc_html = build_toc([e for _, _, entries in raw for e in entries]) if toc else None
115
+ has_mermaid = any('<div class="mermaid">' in html for _, html in sections)
116
+ has_code = any("<pre><code" in html for _, html in sections)
117
+
101
118
  try:
102
119
  content = render_html(
103
120
  sections,
@@ -2,12 +2,20 @@ 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
8
9
  from mddoco.toc import TocEntry, flatten_tokens
9
10
 
10
11
 
12
+ def read_markdown(path: Path, context: dict | None = None) -> str:
13
+ """Return a file's Markdown text, rendering .md.j2 templates with Jinja2."""
14
+ if path.suffix.lower() == ".j2":
15
+ return render_j2(path, context or {})
16
+ return path.read_text(encoding="utf-8")
17
+
18
+
11
19
  def convert_file(
12
20
  path: Path,
13
21
  toc: bool = False,
@@ -20,10 +28,7 @@ def convert_file(
20
28
  then the resulting Markdown is converted as normal.
21
29
  Returns (html_body, toc_entries). toc_entries is empty when toc=False.
22
30
  """
23
- if path.suffix.lower() == ".j2":
24
- text = render_j2(path, context or {})
25
- else:
26
- text = path.read_text(encoding="utf-8")
31
+ text = read_markdown(path, context)
27
32
 
28
33
  extensions = ["tables", "fenced_code", "attr_list"]
29
34
  extension_configs: dict = {}
@@ -36,6 +41,7 @@ def convert_file(
36
41
  html = md.convert(text)
37
42
  html, _ = process_mermaid(html)
38
43
  html, _ = process_graph(html)
44
+ html, _ = process_d2(html)
39
45
 
40
46
  toc_entries = flatten_tokens(md.toc_tokens) if toc else []
41
47
  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