mddoco 2.3.0__tar.gz → 2.5.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 (47) hide show
  1. {mddoco-2.3.0/src/mddoco.egg-info → mddoco-2.5.0}/PKG-INFO +54 -10
  2. {mddoco-2.3.0 → mddoco-2.5.0}/README.md +52 -9
  3. {mddoco-2.3.0 → mddoco-2.5.0}/pyproject.toml +2 -1
  4. mddoco-2.5.0/src/mddoco/__init__.py +1 -0
  5. {mddoco-2.3.0 → mddoco-2.5.0}/src/mddoco/cli.py +28 -11
  6. {mddoco-2.3.0 → mddoco-2.5.0}/src/mddoco/converter.py +8 -4
  7. mddoco-2.5.0/src/mddoco/docx.py +296 -0
  8. {mddoco-2.3.0 → mddoco-2.5.0}/src/mddoco/renderer.py +7 -0
  9. mddoco-2.5.0/src/mddoco/themes/site-professional-wide.html +14 -0
  10. {mddoco-2.3.0 → mddoco-2.5.0/src/mddoco.egg-info}/PKG-INFO +54 -10
  11. {mddoco-2.3.0 → mddoco-2.5.0}/src/mddoco.egg-info/SOURCES.txt +4 -0
  12. {mddoco-2.3.0 → mddoco-2.5.0}/src/mddoco.egg-info/requires.txt +1 -0
  13. mddoco-2.5.0/tests/test_docx.py +152 -0
  14. mddoco-2.5.0/tests/test_jinja_formats.py +146 -0
  15. {mddoco-2.3.0 → mddoco-2.5.0}/tests/test_preprocessor.py +1 -1
  16. {mddoco-2.3.0 → mddoco-2.5.0}/tests/test_themes.py +7 -1
  17. mddoco-2.3.0/src/mddoco/__init__.py +0 -1
  18. {mddoco-2.3.0 → mddoco-2.5.0}/LICENSE +0 -0
  19. {mddoco-2.3.0 → mddoco-2.5.0}/setup.cfg +0 -0
  20. {mddoco-2.3.0 → mddoco-2.5.0}/src/mddoco/d2.py +0 -0
  21. {mddoco-2.3.0 → mddoco-2.5.0}/src/mddoco/graph.py +0 -0
  22. {mddoco-2.3.0 → mddoco-2.5.0}/src/mddoco/mermaid.py +0 -0
  23. {mddoco-2.3.0 → mddoco-2.5.0}/src/mddoco/pdf.py +0 -0
  24. {mddoco-2.3.0 → mddoco-2.5.0}/src/mddoco/preprocessor.py +0 -0
  25. {mddoco-2.3.0 → mddoco-2.5.0}/src/mddoco/scanner.py +0 -0
  26. {mddoco-2.3.0 → mddoco-2.5.0}/src/mddoco/themes/_site_base.html +0 -0
  27. {mddoco-2.3.0 → mddoco-2.5.0}/src/mddoco/themes/academic-wide.html +0 -0
  28. {mddoco-2.3.0 → mddoco-2.5.0}/src/mddoco/themes/academic.html +0 -0
  29. {mddoco-2.3.0 → mddoco-2.5.0}/src/mddoco/themes/dark-wide.html +0 -0
  30. {mddoco-2.3.0 → mddoco-2.5.0}/src/mddoco/themes/dark.html +0 -0
  31. {mddoco-2.3.0 → mddoco-2.5.0}/src/mddoco/themes/default-wide.html +0 -0
  32. {mddoco-2.3.0 → mddoco-2.5.0}/src/mddoco/themes/default.html +0 -0
  33. {mddoco-2.3.0 → mddoco-2.5.0}/src/mddoco/themes/paged-professional.html +0 -0
  34. {mddoco-2.3.0 → mddoco-2.5.0}/src/mddoco/themes/professional-wide.html +0 -0
  35. {mddoco-2.3.0 → mddoco-2.5.0}/src/mddoco/themes/professional.html +0 -0
  36. {mddoco-2.3.0 → mddoco-2.5.0}/src/mddoco/themes/site-dark.html +0 -0
  37. {mddoco-2.3.0 → mddoco-2.5.0}/src/mddoco/themes/site-professional.html +0 -0
  38. {mddoco-2.3.0 → mddoco-2.5.0}/src/mddoco/themes/site-terminal.html +0 -0
  39. {mddoco-2.3.0 → mddoco-2.5.0}/src/mddoco/themes/site.html +0 -0
  40. {mddoco-2.3.0 → mddoco-2.5.0}/src/mddoco/themes/vanilla.html +0 -0
  41. {mddoco-2.3.0 → mddoco-2.5.0}/src/mddoco/toc.py +0 -0
  42. {mddoco-2.3.0 → mddoco-2.5.0}/src/mddoco/writer.py +0 -0
  43. {mddoco-2.3.0 → mddoco-2.5.0}/src/mddoco.egg-info/dependency_links.txt +0 -0
  44. {mddoco-2.3.0 → mddoco-2.5.0}/src/mddoco.egg-info/entry_points.txt +0 -0
  45. {mddoco-2.3.0 → mddoco-2.5.0}/src/mddoco.egg-info/top_level.txt +0 -0
  46. {mddoco-2.3.0 → mddoco-2.5.0}/tests/test_d2.py +0 -0
  47. {mddoco-2.3.0 → mddoco-2.5.0}/tests/test_toc.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mddoco
3
- Version: 2.3.0
3
+ Version: 2.5.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,13 +16,14 @@ 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 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)
@@ -40,9 +41,9 @@ Or for development:
40
41
  pip install -e .
41
42
  ```
42
43
 
43
- > **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.
44
45
  > The `playwright` Python package is installed automatically, but the Chromium
45
- > 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
46
47
  > Chromium for you (~150 MB, one time). To do it ahead of time, or if the
47
48
  > automatic download fails, run it yourself:
48
49
  >
@@ -54,6 +55,10 @@ pip install -e .
54
55
  > [D2 diagrams](#d2-diagrams).** It is a separate program, not a Python
55
56
  > package, so `pip` does not install it. See [Installing the D2 CLI](#installing-the-d2-cli).
56
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
+
57
62
  ## Usage
58
63
 
59
64
  ```
@@ -67,10 +72,10 @@ mddoco [OPTIONS] INPUT_PATH
67
72
  | Option | Short | Default | Description |
68
73
  |---|---|---|---|
69
74
  | `--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) |
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) |
71
76
  | `--title TEXT` | `-t` | _(none)_ | Document title shown at the top of the page |
72
- | `--theme NAME` | | `default` | Theme to use for rendering |
73
- | `--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) |
74
79
  | `--toc-depth N` | | `3` | Maximum heading depth included in the TOC (1–6) |
75
80
 
76
81
  ### Examples
@@ -93,9 +98,16 @@ With a title, TOC, and custom output directory:
93
98
  mddoco ./docs --title "My Project" --toc --output ./out
94
99
  ```
95
100
 
101
+ As a PDF or a Word document:
102
+
103
+ ```bash
104
+ mddoco ./docs --format pdf
105
+ mddoco ./docs --format docx
106
+ ```
107
+
96
108
  ## Output
97
109
 
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.
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.
99
111
 
100
112
  ## Examples
101
113
 
@@ -205,6 +217,7 @@ Themes are Jinja2 HTML files with embedded CSS. Pass a theme name with `--theme
205
217
  | `paged-professional` | Corporate style with Paged.js pagination for print-ready PDFs |
206
218
  | `site` | Website layout: side nav with one page per H1, minimalist styling (HTML only) |
207
219
  | `site-professional` | Same as `site` with a navy sidebar and card layout (HTML only) |
220
+ | `site-professional-wide` | Same as `site-professional` with the content card stretched to almost full width (HTML only) |
208
221
  | `site-dark` | Same as `site` on a dark background (HTML only) |
209
222
  | `site-terminal` | Same as `site` as a green-phosphor terminal, just for fun (HTML only) |
210
223
 
@@ -315,7 +328,7 @@ graph TD
315
328
  ```
316
329
  ````
317
330
 
318
- mddoco detects mermaid blocks automatically and loads the Mermaid.js CDN only when needed.
331
+ 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.
319
332
 
320
333
  ### D2 diagrams
321
334
 
@@ -329,7 +342,7 @@ server -> db: query
329
342
  ```
330
343
  ````
331
344
 
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.
345
+ 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.
333
346
 
334
347
  - 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
348
  - A diagram that fails to compile stops the build with D2's error message, the same as an invalid `graph` block.
@@ -358,3 +371,34 @@ d2 --version
358
371
  - **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
372
 
360
373
  If `d2` is missing, mddoco stops with an error pointing to the install guide, and only when it finds a `d2` block.
374
+
375
+ ## Word output
376
+
377
+ `--format docx` writes a Word document:
378
+
379
+ ```bash
380
+ mddoco docs/ --format docx --title "Security Findings" -o out/
381
+ ```
382
+
383
+ 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.
384
+
385
+ - **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.
386
+ - **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.
387
+ - **No table of contents.** Insert one in Word, or in Google Docs with Insert > Table of contents. `--toc` is ignored with a warning.
388
+ - **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.
389
+ - **Code blocks** keep their syntax colours.
390
+
391
+ ### Google Docs
392
+
393
+ 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.
394
+
395
+ ### Installing Pandoc
396
+
397
+ | Platform | Command |
398
+ |---|---|
399
+ | macOS (Homebrew) | `brew install pandoc` |
400
+ | Debian and Ubuntu | `sudo apt-get install pandoc` |
401
+ | Windows (Chocolatey) | `choco install pandoc` |
402
+ | Any platform | Download an installer from [pandoc.org/installing.html](https://pandoc.org/installing.html) |
403
+
404
+ Check it with `pandoc --version`. If `pandoc` is missing, mddoco stops with an error pointing to the install page.
@@ -1,6 +1,6 @@
1
1
  # mddoco
2
2
 
3
- A CLI tool that converts markdown files to a single HTML or 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)
@@ -18,9 +18,9 @@ Or for development:
18
18
  pip install -e .
19
19
  ```
20
20
 
21
- > **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.
22
22
  > The `playwright` Python package is installed automatically, but the Chromium
23
- > 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
24
24
  > Chromium for you (~150 MB, one time). To do it ahead of time, or if the
25
25
  > automatic download fails, run it yourself:
26
26
  >
@@ -32,6 +32,10 @@ pip install -e .
32
32
  > [D2 diagrams](#d2-diagrams).** It is a separate program, not a Python
33
33
  > package, so `pip` does not install it. See [Installing the D2 CLI](#installing-the-d2-cli).
34
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
+
35
39
  ## Usage
36
40
 
37
41
  ```
@@ -45,10 +49,10 @@ mddoco [OPTIONS] INPUT_PATH
45
49
  | Option | Short | Default | Description |
46
50
  |---|---|---|---|
47
51
  | `--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) |
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) |
49
53
  | `--title TEXT` | `-t` | _(none)_ | Document title shown at the top of the page |
50
- | `--theme NAME` | | `default` | Theme to use for rendering |
51
- | `--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) |
52
56
  | `--toc-depth N` | | `3` | Maximum heading depth included in the TOC (1–6) |
53
57
 
54
58
  ### Examples
@@ -71,9 +75,16 @@ With a title, TOC, and custom output directory:
71
75
  mddoco ./docs --title "My Project" --toc --output ./out
72
76
  ```
73
77
 
78
+ As a PDF or a Word document:
79
+
80
+ ```bash
81
+ mddoco ./docs --format pdf
82
+ mddoco ./docs --format docx
83
+ ```
84
+
74
85
  ## Output
75
86
 
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.
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.
77
88
 
78
89
  ## Examples
79
90
 
@@ -183,6 +194,7 @@ Themes are Jinja2 HTML files with embedded CSS. Pass a theme name with `--theme
183
194
  | `paged-professional` | Corporate style with Paged.js pagination for print-ready PDFs |
184
195
  | `site` | Website layout: side nav with one page per H1, minimalist styling (HTML only) |
185
196
  | `site-professional` | Same as `site` with a navy sidebar and card layout (HTML only) |
197
+ | `site-professional-wide` | Same as `site-professional` with the content card stretched to almost full width (HTML only) |
186
198
  | `site-dark` | Same as `site` on a dark background (HTML only) |
187
199
  | `site-terminal` | Same as `site` as a green-phosphor terminal, just for fun (HTML only) |
188
200
 
@@ -293,7 +305,7 @@ graph TD
293
305
  ```
294
306
  ````
295
307
 
296
- mddoco detects mermaid blocks automatically and loads the Mermaid.js CDN only when needed.
308
+ 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.
297
309
 
298
310
  ### D2 diagrams
299
311
 
@@ -307,7 +319,7 @@ server -> db: query
307
319
  ```
308
320
  ````
309
321
 
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.
322
+ 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.
311
323
 
312
324
  - 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
325
  - A diagram that fails to compile stops the build with D2's error message, the same as an invalid `graph` block.
@@ -336,3 +348,34 @@ d2 --version
336
348
  - **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
349
 
338
350
  If `d2` is missing, mddoco stops with an error pointing to the install guide, and only when it finds a `d2` block.
351
+
352
+ ## Word output
353
+
354
+ `--format docx` writes a Word document:
355
+
356
+ ```bash
357
+ mddoco docs/ --format docx --title "Security Findings" -o out/
358
+ ```
359
+
360
+ 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.
361
+
362
+ - **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.
363
+ - **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.
364
+ - **No table of contents.** Insert one in Word, or in Google Docs with Insert > Table of contents. `--toc` is ignored with a warning.
365
+ - **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.
366
+ - **Code blocks** keep their syntax colours.
367
+
368
+ ### Google Docs
369
+
370
+ 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.
371
+
372
+ ### Installing Pandoc
373
+
374
+ | Platform | Command |
375
+ |---|---|
376
+ | macOS (Homebrew) | `brew install pandoc` |
377
+ | Debian and Ubuntu | `sudo apt-get install pandoc` |
378
+ | Windows (Chocolatey) | `choco install pandoc` |
379
+ | Any platform | Download an installer from [pandoc.org/installing.html](https://pandoc.org/installing.html) |
380
+
381
+ 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.3.0"
7
+ version = "2.5.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.5.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,
@@ -9,6 +9,13 @@ from mddoco.preprocessor import render_j2
9
9
  from mddoco.toc import TocEntry, flatten_tokens
10
10
 
11
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
+
12
19
  def convert_file(
13
20
  path: Path,
14
21
  toc: bool = False,
@@ -21,10 +28,7 @@ def convert_file(
21
28
  then the resulting Markdown is converted as normal.
22
29
  Returns (html_body, toc_entries). toc_entries is empty when toc=False.
23
30
  """
24
- if path.suffix.lower() == ".j2":
25
- text = render_j2(path, context or {})
26
- else:
27
- text = path.read_text(encoding="utf-8")
31
+ text = read_markdown(path, context)
28
32
 
29
33
  extensions = ["tables", "fenced_code", "attr_list"]
30
34
  extension_configs: dict = {}
@@ -0,0 +1,296 @@
1
+ import logging
2
+ import os
3
+ import re
4
+ import shutil
5
+ import subprocess
6
+ import tempfile
7
+ import zipfile
8
+ from collections.abc import Callable
9
+ from pathlib import Path
10
+
11
+ from mddoco.converter import read_markdown
12
+ from mddoco.d2 import _render_d2
13
+ from mddoco.graph import _SVG_HEADER, _parse_source, graph_it
14
+ from mddoco.pdf import _install_chromium
15
+
16
+ log = logging.getLogger(__name__)
17
+
18
+ _PANDOC_HINT = (
19
+ "Word output requires the 'pandoc' command-line tool, which was not found "
20
+ "on PATH. Install it from https://pandoc.org/installing.html"
21
+ )
22
+
23
+ _PANDOC_TIMEOUT_SECONDS = 120
24
+
25
+ _MERMAID_URL = "https://cdn.jsdelivr.net/npm/mermaid@11.17.2/dist/mermaid.min.js"
26
+ _MERMAID_SRI = "sha384-EOXBFmc3gx5mb+vn0vPvvGqACToJD24hhacX5Yx+8NUUQrHIle/Qi5Bg9o3zKwW2"
27
+ _MERMAID_SCRIPT = (
28
+ f'<script src="{_MERMAID_URL}" integrity="{_MERMAID_SRI}" '
29
+ 'crossorigin="anonymous"></script>'
30
+ )
31
+ _MERMAID_PAGE = f'<body style="margin:0;background:#fff">{_MERMAID_SCRIPT}</body>'
32
+ _SVG_PAGE = '<body style="margin:0;background:#fff;display:inline-block">{}</body>'
33
+ _MERMAID_RENDER_JS = """async (source) => {
34
+ mermaid.initialize({
35
+ startOnLoad: false,
36
+ theme: 'neutral',
37
+ htmlLabels: false,
38
+ flowchart: { htmlLabels: false },
39
+ });
40
+ const { svg } = await mermaid.render('mddoco-diagram', source);
41
+ document.body.innerHTML = svg;
42
+ }"""
43
+
44
+ DIAGRAM_LANGUAGES = ("graph", "d2", "mermaid")
45
+
46
+ _FENCE_OPEN = re.compile(r"^( {0,3})(`{3,}|~{3,})\s*([^\s`]*)[^`]*$")
47
+
48
+ _BORDER = '<w:{0} w:val="single" w:sz="4" w:space="0" w:color="A6A6A6"/>'
49
+ _TABLE_BORDERS = (
50
+ "<w:tblBorders>"
51
+ + "".join(
52
+ _BORDER.format(side)
53
+ for side in ("top", "left", "bottom", "right", "insideH", "insideV")
54
+ )
55
+ + "</w:tblBorders>"
56
+ )
57
+ _TABLE_CELL_MARGINS = (
58
+ '<w:tblCellMar><w:top w:w="60" w:type="dxa"/><w:left w:w="100" w:type="dxa"/>'
59
+ '<w:bottom w:w="60" w:type="dxa"/><w:right w:w="100" w:type="dxa"/></w:tblCellMar>'
60
+ )
61
+ _HEADER_CELL_SHADING = (
62
+ '<w:tcPr><w:shd w:val="clear" w:color="auto" w:fill="E7ECF3"/></w:tcPr>'
63
+ )
64
+
65
+
66
+ def replace_diagram_blocks(text: str, replace: Callable[[str, str], str]) -> str:
67
+ """Swap fenced graph, d2 and mermaid blocks for the text ``replace`` returns.
68
+
69
+ Only top-level fences are considered, so an example of a diagram block
70
+ shown inside a longer fence (or an indented one) is left alone, as is any
71
+ block that is never closed.
72
+ """
73
+ lines = text.split("\n")
74
+ out: list[str] = []
75
+ i = 0
76
+ while i < len(lines):
77
+ match = _FENCE_OPEN.match(lines[i])
78
+ if not match:
79
+ out.append(lines[i])
80
+ i += 1
81
+ continue
82
+
83
+ indent, fence, language = match.groups()
84
+ closing = re.compile(rf"^ {{0,3}}{re.escape(fence[0])}{{{len(fence)},}}\s*$")
85
+ end = i + 1
86
+ while end < len(lines) and not closing.match(lines[end]):
87
+ end += 1
88
+
89
+ closed = end < len(lines)
90
+ if language in DIAGRAM_LANGUAGES and closed and not indent:
91
+ out.append(replace(language, "\n".join(lines[i + 1 : end])))
92
+ else:
93
+ out.extend(lines[i : end + 1])
94
+ i = end + 1
95
+
96
+ return "\n".join(out)
97
+
98
+
99
+ def style_tables(document_xml: str) -> str:
100
+ """Give every table grid borders, cell padding and a shaded, bold header row.
101
+
102
+ Borders are written onto each table, not into a Word style, because Google
103
+ Docs keeps them reliably when they are applied directly.
104
+ """
105
+
106
+ def style_header(match: re.Match) -> str:
107
+ row = match.group(0).replace("<w:tcPr />", _HEADER_CELL_SHADING)
108
+ return re.sub(r"<w:r>(<w:t[ >])", r"<w:r><w:rPr><w:b/></w:rPr>\1", row)
109
+
110
+ def style_table(match: re.Match) -> str:
111
+ table = match.group(0)
112
+ # Order inside tblPr: tblW, tblBorders, tblLayout, tblCellMar, tblLook
113
+ table = re.sub(
114
+ r"(<w:tblLayout [^>]*/>|<w:tblLook )",
115
+ lambda m: _TABLE_BORDERS + m.group(1),
116
+ table,
117
+ count=1,
118
+ )
119
+ table = re.sub(
120
+ r"(<w:tblLook )",
121
+ lambda m: _TABLE_CELL_MARGINS + m.group(1),
122
+ table,
123
+ count=1,
124
+ )
125
+ return re.sub(
126
+ r"<w:tr><w:trPr><w:tblHeader[^>]*/></w:trPr>.*?</w:tr>",
127
+ style_header,
128
+ table,
129
+ count=1,
130
+ flags=re.DOTALL,
131
+ )
132
+
133
+ return re.sub(r"<w:tbl>.*?</w:tbl>", style_table, document_xml, flags=re.DOTALL)
134
+
135
+
136
+ def _style_docx_tables(source: Path, dest: Path) -> None:
137
+ """Copy a .docx, applying style_tables to its document body."""
138
+ with (
139
+ zipfile.ZipFile(source) as zin,
140
+ zipfile.ZipFile(dest, "w", zipfile.ZIP_DEFLATED) as zout,
141
+ ):
142
+ for item in zin.infolist():
143
+ data = zin.read(item.filename)
144
+ if item.filename == "word/document.xml":
145
+ data = style_tables(data.decode("utf-8")).encode("utf-8")
146
+ zout.writestr(item, data)
147
+
148
+
149
+ def _diagram_svg(language: str, source: str) -> str | None:
150
+ """Return inline SVG for a graph or d2 block; None for Mermaid (browser-drawn)."""
151
+ if language == "graph":
152
+ svg = graph_it(_parse_source(source))
153
+ return _SVG_HEADER.sub("", svg, count=1)
154
+ if language == "d2":
155
+ return _render_d2(source)
156
+ return None
157
+
158
+
159
+ def _screenshot_diagrams(
160
+ sync_playwright, jobs: list[tuple[str, str, str]], dest_dir: Path
161
+ ) -> None:
162
+ """Render each (file name, language, svg-or-source) job to a PNG."""
163
+ with sync_playwright() as p:
164
+ browser = p.chromium.launch()
165
+ try:
166
+ for name, language, content in jobs:
167
+ page = browser.new_page(
168
+ viewport={"width": 1000, "height": 800}, device_scale_factor=2
169
+ )
170
+ try:
171
+ if language == "mermaid":
172
+ page.set_content(_MERMAID_PAGE)
173
+ if page.evaluate("typeof window.mermaid") != "object":
174
+ raise RuntimeError(
175
+ "Mermaid.js could not be loaded; Mermaid diagrams "
176
+ "need network access"
177
+ )
178
+ page.evaluate(_MERMAID_RENDER_JS, content)
179
+ else:
180
+ page.set_content(_SVG_PAGE.format(content))
181
+ page.locator("svg").first.screenshot(path=str(dest_dir / name))
182
+ except RuntimeError:
183
+ raise
184
+ except Exception as exc:
185
+ raise RuntimeError(
186
+ f"Could not render {language} diagram: {exc}"
187
+ ) from exc
188
+ finally:
189
+ page.close()
190
+ finally:
191
+ browser.close()
192
+
193
+
194
+ def _render_diagram_images(jobs: list[tuple[str, str, str]], dest_dir: Path) -> None:
195
+ """Turn collected diagram jobs into PNG files in ``dest_dir``."""
196
+ if not jobs:
197
+ return
198
+ try:
199
+ from playwright.sync_api import Error as PlaywrightError
200
+ from playwright.sync_api import sync_playwright
201
+ except ImportError:
202
+ raise RuntimeError(
203
+ "Playwright is required to draw diagrams in Word output. "
204
+ "Run: pip install playwright && playwright install chromium"
205
+ )
206
+
207
+ try:
208
+ _screenshot_diagrams(sync_playwright, jobs, dest_dir)
209
+ except PlaywrightError as exc:
210
+ if "Executable doesn't exist" not in str(exc):
211
+ raise RuntimeError(f"Could not render diagrams: {exc}") from exc
212
+ _install_chromium()
213
+ _screenshot_diagrams(sync_playwright, jobs, dest_dir)
214
+
215
+
216
+ def build_markdown(
217
+ paths: list[Path], context: dict | None
218
+ ) -> tuple[str, list[tuple[str, str, str]]]:
219
+ """Join the files' Markdown, replacing diagram blocks with image links.
220
+
221
+ Returns (markdown, jobs). Each job is (png file name, language, svg or
222
+ source) and is drawn to a PNG by the caller.
223
+ """
224
+ jobs: list[tuple[str, str, str]] = []
225
+
226
+ def replace(language: str, source: str) -> str:
227
+ name = f"diagram-{len(jobs) + 1}.png"
228
+ try:
229
+ content = _diagram_svg(language, source)
230
+ except Exception as exc:
231
+ log.error("%s error: %s", language.capitalize(), exc)
232
+ raise
233
+ jobs.append((name, language, content if content is not None else source))
234
+ return f"![{language} diagram {len(jobs)}]({name})"
235
+
236
+ sections = [
237
+ replace_diagram_blocks(read_markdown(path, context), replace) for path in paths
238
+ ]
239
+ return "\n\n".join(sections), jobs
240
+
241
+
242
+ def build_docx(
243
+ paths: list[Path],
244
+ dest: Path,
245
+ context: dict | None = None,
246
+ title: str | None = None,
247
+ ) -> None:
248
+ """Write the Markdown files to ``dest`` as a Word document using Pandoc.
249
+
250
+ Diagrams (graph, d2, mermaid) are drawn to PNG images first, and every
251
+ table gets borders and a shaded header row.
252
+ """
253
+ pandoc = shutil.which("pandoc")
254
+ if pandoc is None:
255
+ raise RuntimeError(_PANDOC_HINT)
256
+
257
+ with tempfile.TemporaryDirectory(prefix="mddoco-docx-") as tmp:
258
+ work = Path(tmp)
259
+ markdown, jobs = build_markdown(paths, context)
260
+ _render_diagram_images(jobs, work)
261
+
262
+ # Relative image links in the Markdown resolve against each source folder.
263
+ search_path = [str(work)] + [str(p.parent.resolve()) for p in paths]
264
+ raw = work / "pandoc-output.docx"
265
+ cmd = [
266
+ pandoc,
267
+ "--from=gfm",
268
+ "--to=docx",
269
+ f"--output={raw}",
270
+ f"--resource-path={os.pathsep.join(dict.fromkeys(search_path))}",
271
+ ]
272
+ if title:
273
+ cmd.append(f"--metadata=title:{title}")
274
+
275
+ try:
276
+ result = subprocess.run(
277
+ cmd,
278
+ input=markdown,
279
+ capture_output=True,
280
+ text=True,
281
+ encoding="utf-8",
282
+ timeout=_PANDOC_TIMEOUT_SECONDS,
283
+ )
284
+ except subprocess.TimeoutExpired as exc:
285
+ raise RuntimeError(
286
+ f"pandoc timed out after {_PANDOC_TIMEOUT_SECONDS}s"
287
+ ) from exc
288
+
289
+ if result.returncode != 0:
290
+ detail = result.stderr.strip() or f"exit code {result.returncode}"
291
+ raise RuntimeError(f"pandoc failed: {detail}")
292
+ if result.stderr.strip():
293
+ log.warning("pandoc: %s", result.stderr.strip())
294
+
295
+ dest.parent.mkdir(parents=True, exist_ok=True)
296
+ _style_docx_tables(raw, dest)