mddoco 2.3.0__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.3.0/src/mddoco.egg-info → mddoco-2.4.0}/PKG-INFO +53 -10
  2. {mddoco-2.3.0 → mddoco-2.4.0}/README.md +51 -9
  3. {mddoco-2.3.0 → mddoco-2.4.0}/pyproject.toml +2 -1
  4. mddoco-2.4.0/src/mddoco/__init__.py +1 -0
  5. {mddoco-2.3.0 → mddoco-2.4.0}/src/mddoco/cli.py +28 -11
  6. {mddoco-2.3.0 → mddoco-2.4.0}/src/mddoco/converter.py +8 -4
  7. mddoco-2.4.0/src/mddoco/docx.py +296 -0
  8. {mddoco-2.3.0 → mddoco-2.4.0}/src/mddoco/renderer.py +7 -0
  9. {mddoco-2.3.0 → mddoco-2.4.0/src/mddoco.egg-info}/PKG-INFO +53 -10
  10. {mddoco-2.3.0 → mddoco-2.4.0}/src/mddoco.egg-info/SOURCES.txt +3 -0
  11. {mddoco-2.3.0 → mddoco-2.4.0}/src/mddoco.egg-info/requires.txt +1 -0
  12. mddoco-2.4.0/tests/test_docx.py +152 -0
  13. mddoco-2.4.0/tests/test_jinja_formats.py +146 -0
  14. {mddoco-2.3.0 → mddoco-2.4.0}/tests/test_preprocessor.py +1 -1
  15. mddoco-2.3.0/src/mddoco/__init__.py +0 -1
  16. {mddoco-2.3.0 → mddoco-2.4.0}/LICENSE +0 -0
  17. {mddoco-2.3.0 → mddoco-2.4.0}/setup.cfg +0 -0
  18. {mddoco-2.3.0 → mddoco-2.4.0}/src/mddoco/d2.py +0 -0
  19. {mddoco-2.3.0 → mddoco-2.4.0}/src/mddoco/graph.py +0 -0
  20. {mddoco-2.3.0 → mddoco-2.4.0}/src/mddoco/mermaid.py +0 -0
  21. {mddoco-2.3.0 → mddoco-2.4.0}/src/mddoco/pdf.py +0 -0
  22. {mddoco-2.3.0 → mddoco-2.4.0}/src/mddoco/preprocessor.py +0 -0
  23. {mddoco-2.3.0 → mddoco-2.4.0}/src/mddoco/scanner.py +0 -0
  24. {mddoco-2.3.0 → mddoco-2.4.0}/src/mddoco/themes/_site_base.html +0 -0
  25. {mddoco-2.3.0 → mddoco-2.4.0}/src/mddoco/themes/academic-wide.html +0 -0
  26. {mddoco-2.3.0 → mddoco-2.4.0}/src/mddoco/themes/academic.html +0 -0
  27. {mddoco-2.3.0 → mddoco-2.4.0}/src/mddoco/themes/dark-wide.html +0 -0
  28. {mddoco-2.3.0 → mddoco-2.4.0}/src/mddoco/themes/dark.html +0 -0
  29. {mddoco-2.3.0 → mddoco-2.4.0}/src/mddoco/themes/default-wide.html +0 -0
  30. {mddoco-2.3.0 → mddoco-2.4.0}/src/mddoco/themes/default.html +0 -0
  31. {mddoco-2.3.0 → mddoco-2.4.0}/src/mddoco/themes/paged-professional.html +0 -0
  32. {mddoco-2.3.0 → mddoco-2.4.0}/src/mddoco/themes/professional-wide.html +0 -0
  33. {mddoco-2.3.0 → mddoco-2.4.0}/src/mddoco/themes/professional.html +0 -0
  34. {mddoco-2.3.0 → mddoco-2.4.0}/src/mddoco/themes/site-dark.html +0 -0
  35. {mddoco-2.3.0 → mddoco-2.4.0}/src/mddoco/themes/site-professional.html +0 -0
  36. {mddoco-2.3.0 → mddoco-2.4.0}/src/mddoco/themes/site-terminal.html +0 -0
  37. {mddoco-2.3.0 → mddoco-2.4.0}/src/mddoco/themes/site.html +0 -0
  38. {mddoco-2.3.0 → mddoco-2.4.0}/src/mddoco/themes/vanilla.html +0 -0
  39. {mddoco-2.3.0 → mddoco-2.4.0}/src/mddoco/toc.py +0 -0
  40. {mddoco-2.3.0 → mddoco-2.4.0}/src/mddoco/writer.py +0 -0
  41. {mddoco-2.3.0 → mddoco-2.4.0}/src/mddoco.egg-info/dependency_links.txt +0 -0
  42. {mddoco-2.3.0 → mddoco-2.4.0}/src/mddoco.egg-info/entry_points.txt +0 -0
  43. {mddoco-2.3.0 → mddoco-2.4.0}/src/mddoco.egg-info/top_level.txt +0 -0
  44. {mddoco-2.3.0 → mddoco-2.4.0}/tests/test_d2.py +0 -0
  45. {mddoco-2.3.0 → mddoco-2.4.0}/tests/test_themes.py +0 -0
  46. {mddoco-2.3.0 → 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.3.0
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,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
 
@@ -315,7 +327,7 @@ graph TD
315
327
  ```
316
328
  ````
317
329
 
318
- 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.
319
331
 
320
332
  ### D2 diagrams
321
333
 
@@ -329,7 +341,7 @@ server -> db: query
329
341
  ```
330
342
  ````
331
343
 
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.
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.
333
345
 
334
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.
335
347
  - A diagram that fails to compile stops the build with D2's error message, the same as an invalid `graph` block.
@@ -358,3 +370,34 @@ d2 --version
358
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.
359
371
 
360
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,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
 
@@ -293,7 +304,7 @@ graph TD
293
304
  ```
294
305
  ````
295
306
 
296
- 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.
297
308
 
298
309
  ### D2 diagrams
299
310
 
@@ -307,7 +318,7 @@ server -> db: query
307
318
  ```
308
319
  ````
309
320
 
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.
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.
311
322
 
312
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.
313
324
  - A diagram that fails to compile stops the build with D2's error message, the same as an invalid `graph` block.
@@ -336,3 +347,34 @@ d2 --version
336
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.
337
348
 
338
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.3.0"
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,
@@ -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)
@@ -35,6 +35,13 @@ def theme_supports_pdf(theme: str) -> bool:
35
35
 
36
36
  def check_theme_format(theme: str, fmt: str) -> None:
37
37
  """Raise ValueError when the theme is missing or cannot produce ``fmt``."""
38
+ if fmt == "docx":
39
+ if theme != "default":
40
+ raise ValueError(
41
+ "Themes apply to HTML and PDF output only; Word output uses "
42
+ "Word's own styles. Remove --theme, or use --format html or pdf."
43
+ )
44
+ return
38
45
  if fmt == "pdf" and not theme_supports_pdf(theme):
39
46
  raise ValueError(
40
47
  f"Theme '{theme}' is screen-only and cannot produce PDF output. "
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mddoco
3
- Version: 2.3.0
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,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
 
@@ -315,7 +327,7 @@ graph TD
315
327
  ```
316
328
  ````
317
329
 
318
- 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.
319
331
 
320
332
  ### D2 diagrams
321
333
 
@@ -329,7 +341,7 @@ server -> db: query
329
341
  ```
330
342
  ````
331
343
 
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.
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.
333
345
 
334
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.
335
347
  - A diagram that fails to compile stops the build with D2's error message, the same as an invalid `graph` block.
@@ -358,3 +370,34 @@ d2 --version
358
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.
359
371
 
360
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.
@@ -5,6 +5,7 @@ src/mddoco/__init__.py
5
5
  src/mddoco/cli.py
6
6
  src/mddoco/converter.py
7
7
  src/mddoco/d2.py
8
+ src/mddoco/docx.py
8
9
  src/mddoco/graph.py
9
10
  src/mddoco/mermaid.py
10
11
  src/mddoco/pdf.py
@@ -35,6 +36,8 @@ src/mddoco/themes/site-terminal.html
35
36
  src/mddoco/themes/site.html
36
37
  src/mddoco/themes/vanilla.html
37
38
  tests/test_d2.py
39
+ tests/test_docx.py
40
+ tests/test_jinja_formats.py
38
41
  tests/test_preprocessor.py
39
42
  tests/test_themes.py
40
43
  tests/test_toc.py
@@ -6,5 +6,6 @@ matplotlib>=3.7
6
6
 
7
7
  [dev]
8
8
  pytest>=8.0
9
+ pypdf>=4.0
9
10
  black>=24.0
10
11
  ruff<0.17,>=0.16
@@ -0,0 +1,152 @@
1
+ import shutil
2
+ import subprocess
3
+ import zipfile
4
+
5
+ import pytest
6
+
7
+ from mddoco import docx
8
+ from mddoco.docx import build_docx, replace_diagram_blocks, style_tables
9
+ from mddoco.renderer import check_theme_format
10
+
11
+
12
+ def _tag(language, source):
13
+ return f"[{language}:{source.strip()}]"
14
+
15
+
16
+ def test_top_level_diagram_fences_are_replaced():
17
+ text = "intro\n\n```d2\na -> b\n```\n\n~~~mermaid\ngraph TD\n~~~\n\nend"
18
+ out = replace_diagram_blocks(text, _tag)
19
+ assert out == "intro\n\n[d2:a -> b]\n\n[mermaid:graph TD]\n\nend"
20
+
21
+
22
+ def test_other_languages_are_left_alone():
23
+ text = "```python\nprint(1)\n```"
24
+ assert replace_diagram_blocks(text, _tag) == text
25
+
26
+
27
+ def test_nested_indented_and_unclosed_fences_are_left_alone():
28
+ nested = "````markdown\n```d2\na -> b\n```\n````"
29
+ indented = " ```d2\n a -> b\n ```"
30
+ unclosed = "```d2\na -> b"
31
+ for text in (nested, indented, unclosed):
32
+ assert replace_diagram_blocks(text, _tag) == text
33
+
34
+
35
+ def test_diagram_after_nested_example_is_still_replaced():
36
+ text = "````markdown\n```d2\nx\n```\n````\n\n```d2\na -> b\n```"
37
+ out = replace_diagram_blocks(text, _tag)
38
+ assert out.endswith("[d2:a -> b]")
39
+ assert "```d2\nx\n```" in out
40
+
41
+
42
+ _TABLE_WITH_LAYOUT = (
43
+ '<w:tbl><w:tblPr><w:tblStyle w:val="Table" /><w:tblW w:type="pct" w:w="5000" />'
44
+ '<w:tblLayout w:type="fixed" /><w:tblLook w:firstRow="1" w:val="0020" />'
45
+ '</w:tblPr><w:tblGrid /><w:tr><w:trPr><w:tblHeader w:val="on" /></w:trPr>'
46
+ "<w:tc><w:tcPr /><w:p><w:r><w:t>H</w:t></w:r></w:p></w:tc></w:tr>"
47
+ "<w:tr><w:tc><w:tcPr /><w:p><w:r><w:t>x</w:t></w:r></w:p></w:tc></w:tr></w:tbl>"
48
+ )
49
+ _TABLE_WITHOUT_LAYOUT = _TABLE_WITH_LAYOUT.replace('<w:tblLayout w:type="fixed" />', "")
50
+
51
+
52
+ @pytest.mark.parametrize("table", [_TABLE_WITH_LAYOUT, _TABLE_WITHOUT_LAYOUT])
53
+ def test_style_tables_adds_borders_padding_and_header(table):
54
+ out = style_tables(f"<w:body><w:p/>{table}<w:p/></w:body>")
55
+ assert out.count("<w:tblBorders>") == 1
56
+ assert out.count("<w:tblCellMar>") == 1
57
+ assert out.index("<w:tblBorders>") < out.index("<w:tblLook ")
58
+ assert out.index("<w:tblCellMar>") < out.index("<w:tblLook ")
59
+ header, body = out.split("</w:tr>", 1)
60
+ assert "<w:b/>" in header and "w:fill=" in header
61
+ assert "<w:b/>" not in body and "w:fill=" not in body
62
+
63
+
64
+ def test_style_tables_styles_each_table():
65
+ out = style_tables(_TABLE_WITH_LAYOUT + _TABLE_WITHOUT_LAYOUT)
66
+ assert out.count("<w:tblBorders>") == 2
67
+
68
+
69
+ def test_style_tables_without_tables_is_unchanged():
70
+ xml = "<w:body><w:p><w:r><w:t>hi</w:t></w:r></w:p></w:body>"
71
+ assert style_tables(xml) == xml
72
+
73
+
74
+ def test_theme_other_than_default_is_rejected_for_docx():
75
+ with pytest.raises(ValueError, match="Word"):
76
+ check_theme_format("dark", "docx")
77
+
78
+
79
+ def test_default_theme_is_accepted_for_docx():
80
+ check_theme_format("default", "docx")
81
+
82
+
83
+ def test_missing_pandoc_gives_install_hint(tmp_path, monkeypatch):
84
+ md = tmp_path / "a.md"
85
+ md.write_text("# Hi\n")
86
+ monkeypatch.setattr(docx.shutil, "which", lambda name: None)
87
+ with pytest.raises(RuntimeError, match="pandoc.*installing"):
88
+ build_docx([md], tmp_path / "out.docx")
89
+
90
+
91
+ def _fake_pandoc(monkeypatch, run):
92
+ monkeypatch.setattr(docx.shutil, "which", lambda name: "/usr/bin/pandoc")
93
+ monkeypatch.setattr(docx.subprocess, "run", run)
94
+
95
+
96
+ def test_pandoc_failure_is_reported(tmp_path, monkeypatch):
97
+ md = tmp_path / "a.md"
98
+ md.write_text("# Hi\n")
99
+
100
+ def run(cmd, **kwargs):
101
+ return subprocess.CompletedProcess(cmd, 3, "", "boom")
102
+
103
+ _fake_pandoc(monkeypatch, run)
104
+ with pytest.raises(RuntimeError, match="pandoc failed: boom"):
105
+ build_docx([md], tmp_path / "out.docx")
106
+
107
+
108
+ def test_pandoc_timeout_is_reported(tmp_path, monkeypatch):
109
+ md = tmp_path / "a.md"
110
+ md.write_text("# Hi\n")
111
+
112
+ def run(cmd, **kwargs):
113
+ raise subprocess.TimeoutExpired(cmd, kwargs["timeout"])
114
+
115
+ _fake_pandoc(monkeypatch, run)
116
+ with pytest.raises(RuntimeError, match="timed out"):
117
+ build_docx([md], tmp_path / "out.docx")
118
+
119
+
120
+ def test_title_and_gfm_are_passed_to_pandoc(tmp_path, monkeypatch):
121
+ md = tmp_path / "a.md"
122
+ md.write_text("# Hi\n")
123
+ calls = []
124
+
125
+ def run(cmd, **kwargs):
126
+ calls.append((cmd, kwargs))
127
+ out = next(a for a in cmd if a.startswith("--output=")).split("=", 1)[1]
128
+ with zipfile.ZipFile(out, "w") as z:
129
+ z.writestr("word/document.xml", "<w:body/>")
130
+ return subprocess.CompletedProcess(cmd, 0, "", "")
131
+
132
+ _fake_pandoc(monkeypatch, run)
133
+ build_docx([md], tmp_path / "sub" / "out.docx", title="My title")
134
+ cmd, kwargs = calls[0]
135
+ assert "--from=gfm" in cmd
136
+ assert "--metadata=title:My title" in cmd
137
+ assert kwargs["input"].startswith("# Hi")
138
+ assert (tmp_path / "sub" / "out.docx").exists()
139
+
140
+
141
+ @pytest.mark.skipif(shutil.which("pandoc") is None, reason="pandoc not installed")
142
+ def test_real_pandoc_output_has_bordered_tables(tmp_path):
143
+ md = tmp_path / "a.md"
144
+ md.write_text(
145
+ "# Title\n\n| A | B |\n|---|---|\n| 1 | 2 |\n\n```python\nx = 1\n```\n"
146
+ )
147
+ dest = tmp_path / "out.docx"
148
+ build_docx([md], dest)
149
+ with zipfile.ZipFile(dest) as z:
150
+ xml = z.read("word/document.xml").decode("utf-8")
151
+ assert xml.count("<w:tblBorders>") == 1
152
+ assert 'w:val="Heading1"' in xml
@@ -0,0 +1,146 @@
1
+ """Jinja2 templates must render the same content in every output format.
2
+
3
+ tests/jinja_fixtures holds one .md.j2 template that exercises variables,
4
+ filters, conditionals, loops over CSV rows, a macro import, comments, a raw
5
+ block and a graph block fed through ``tojson``, next to a plain .md file.
6
+ Each test runs against HTML, PDF and Word output.
7
+ """
8
+
9
+ import html
10
+ import re
11
+ import shutil
12
+ import zipfile
13
+ from pathlib import Path
14
+
15
+ import pytest
16
+ from click.testing import CliRunner
17
+
18
+ from mddoco.cli import main
19
+
20
+ TESTS = Path(__file__).parent
21
+ FIXTURES = TESTS / "jinja_fixtures"
22
+ BROKEN = TESTS / "jinja_broken"
23
+
24
+ FORMATS = ["html", "pdf", "docx"]
25
+
26
+
27
+ def _require_tools(fmt: str) -> None:
28
+ if fmt in ("pdf", "docx"):
29
+ pytest.importorskip("playwright")
30
+ if fmt == "pdf":
31
+ pytest.importorskip("pypdf")
32
+ if fmt == "docx" and shutil.which("pandoc") is None:
33
+ pytest.skip("pandoc not installed")
34
+
35
+
36
+ def _normalise(text: str) -> str:
37
+ return re.sub(r"\s+", " ", html.unescape(text)).strip()
38
+
39
+
40
+ def _extract_text(fmt: str, path: Path) -> str:
41
+ if fmt == "html":
42
+ body = re.sub(
43
+ r"<(script|style)\b.*?</\1>", " ", path.read_text("utf-8"), flags=re.S
44
+ )
45
+ return _normalise(re.sub(r"<[^>]+>", " ", body))
46
+ if fmt == "pdf":
47
+ from pypdf import PdfReader
48
+
49
+ return _normalise(
50
+ " ".join(page.extract_text() for page in PdfReader(path).pages)
51
+ )
52
+ with zipfile.ZipFile(path) as z:
53
+ xml = z.read("word/document.xml").decode("utf-8")
54
+ return _normalise(
55
+ " ".join(re.findall(r"<w:t(?: [^>]*)?>(.*?)</w:t>", xml, flags=re.S))
56
+ )
57
+
58
+
59
+ @pytest.fixture(scope="module", params=FORMATS)
60
+ def rendered(request, tmp_path_factory):
61
+ fmt = request.param
62
+ _require_tools(fmt)
63
+ out = tmp_path_factory.mktemp(f"jinja-{fmt}")
64
+ result = CliRunner().invoke(main, [str(FIXTURES), "--format", fmt, "-o", str(out)])
65
+ assert result.exit_code == 0, result.output
66
+ path = out / f"{FIXTURES.name}.{fmt}"
67
+ assert path.stat().st_size > 0
68
+ return fmt, path, _extract_text(fmt, path)
69
+
70
+
71
+ def test_variables_filters_and_macros_are_rendered(rendered):
72
+ _, _, text = rendered
73
+ assert "Template Check" in text
74
+ assert "Project: Atlas" in text # macro imported from _macros.j2
75
+ assert "Shouting: ATLAS" in text # upper filter
76
+ assert "Owners: Ada Lovelace and Grace Hopper" in text # join filter
77
+
78
+
79
+ def test_special_characters_survive(rendered):
80
+ _, _, text = rendered
81
+ assert 'Motto: Café & "quoted"' in text
82
+
83
+
84
+ def test_conditionals_pick_the_right_branch(rendered):
85
+ _, _, text = rendered
86
+ assert "STATUS_RELEASED_BRANCH" in text
87
+ assert "STATUS_WRONG_BRANCH" not in text
88
+ assert "ARCHIVED_WRONG_BRANCH" not in text
89
+
90
+
91
+ def test_csv_rows_are_looped_in_order(rendered):
92
+ _, _, text = rendered
93
+ cells = [
94
+ "Zed Zebra Engineer python, go",
95
+ "Amy Ant Lead, Platform rust",
96
+ "Bob Bee Analyst sql, excel, python",
97
+ ]
98
+ positions = [text.find(cell) for cell in cells]
99
+ assert all(pos >= 0 for pos in positions), positions
100
+ assert positions == sorted(positions)
101
+ assert "Headcount: 3" in text
102
+
103
+
104
+ def test_raw_block_is_kept_literally(rendered):
105
+ _, _, text = rendered
106
+ assert "Write {{ literal_variable }} to print a value." in text
107
+
108
+
109
+ def test_no_jinja_syntax_leaks(rendered):
110
+ _, _, text = rendered
111
+ for leaked in ("{% ", "{#", "SENTINEL_TEMPLATE_COMMENT", "m.badge", "project.name"):
112
+ assert leaked not in text
113
+
114
+
115
+ def test_template_and_plain_files_are_combined_in_order(rendered):
116
+ _, _, text = rendered
117
+ assert text.index("Template Check") < text.index("PLAIN_FILE_MARKER")
118
+ assert "_macros" not in text
119
+
120
+
121
+ def test_table_and_chart_exist_in_the_output_format(rendered):
122
+ fmt, path, _ = rendered
123
+ if fmt == "html":
124
+ content = path.read_text("utf-8")
125
+ assert content.count("<table>") == 1
126
+ assert "<svg" in content
127
+ elif fmt == "docx":
128
+ with zipfile.ZipFile(path) as z:
129
+ xml = z.read("word/document.xml").decode("utf-8")
130
+ media = [n for n in z.namelist() if n.startswith("word/media/")]
131
+ assert xml.count("<w:tbl>") == 1
132
+ assert len(media) == 1
133
+ else:
134
+ from pypdf import PdfReader
135
+
136
+ assert len(PdfReader(path).pages) >= 1
137
+
138
+
139
+ @pytest.mark.parametrize("fmt", FORMATS)
140
+ def test_template_syntax_error_fails_the_build(fmt, tmp_path):
141
+ _require_tools(fmt)
142
+ result = CliRunner().invoke(
143
+ main, [str(BROKEN), "--format", fmt, "-o", str(tmp_path)]
144
+ )
145
+ assert result.exit_code != 0
146
+ assert not list(tmp_path.iterdir())
@@ -14,7 +14,7 @@ from mddoco.preprocessor import (
14
14
 
15
15
 
16
16
  def test_version():
17
- assert mddoco.__version__ == "2.3.0"
17
+ assert mddoco.__version__ == "2.4.0"
18
18
 
19
19
 
20
20
  # --- _parse_csv_line ---
@@ -1 +0,0 @@
1
- __version__ = "2.3.0"
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