markdown2word 0.1.0__py3-none-any.whl
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.
- markdown2word-0.1.0.dist-info/METADATA +246 -0
- markdown2word-0.1.0.dist-info/RECORD +13 -0
- markdown2word-0.1.0.dist-info/WHEEL +4 -0
- markdown2word-0.1.0.dist-info/entry_points.txt +2 -0
- markdown2word-0.1.0.dist-info/licenses/LICENSE +21 -0
- md2doc/__init__.py +10 -0
- md2doc/assets/reference.odt +0 -0
- md2doc/assets/template.docx +0 -0
- md2doc/cli.py +119 -0
- md2doc/docx.py +126 -0
- md2doc/frontmatter.py +72 -0
- md2doc/odt.py +690 -0
- md2doc/pandoc.py +66 -0
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: markdown2word
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Markdown + YAML front matter + a Word/ODT template -> styled document
|
|
5
|
+
Project-URL: Source, https://git.sophia.minesparis.psl.eu/rjolivet/md2doc
|
|
6
|
+
Author: Raphaël Jolivet
|
|
7
|
+
License: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Keywords: docx,markdown,odt,opendocument,pandoc,template
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Environment :: Console
|
|
12
|
+
Classifier: Intended Audience :: End Users/Desktop
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Topic :: Text Processing :: Markup
|
|
16
|
+
Requires-Python: >=3.9
|
|
17
|
+
Requires-Dist: docxcompose>=1.4
|
|
18
|
+
Requires-Dist: docxtpl>=0.18
|
|
19
|
+
Requires-Dist: lxml>=4.9
|
|
20
|
+
Requires-Dist: python-docx>=1.1
|
|
21
|
+
Requires-Dist: pyyaml>=6.0
|
|
22
|
+
Provides-Extra: dev
|
|
23
|
+
Requires-Dist: pytest>=7.0; extra == 'dev'
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
# md2doc — Markdown + a Word/ODT template → a styled document
|
|
27
|
+
|
|
28
|
+
`md2doc` turns a Markdown file with a YAML header into a real `.docx` or `.odt`,
|
|
29
|
+
built on your own template. It is meant for the common split: you write in plain
|
|
30
|
+
text, your colleagues review in Word or LibreOffice.
|
|
31
|
+
|
|
32
|
+
```
|
|
33
|
+
Report.md + template.docx ──► Report.docx (──► Report.pdf)
|
|
34
|
+
Report.md + template.odt ──► Report.odt (──► Report.pdf)
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## Why
|
|
38
|
+
|
|
39
|
+
Markdown is quick to write, diffs cleanly and stays readable in a git
|
|
40
|
+
repository. Word is what reviewers, managers and clients actually open, comment
|
|
41
|
+
on and print. `md2doc` keeps the source in Markdown while producing a document
|
|
42
|
+
that is 100 % native: real styles, real headings, real tables, a real cover page
|
|
43
|
+
— not a text dump pasted into a blank file.
|
|
44
|
+
|
|
45
|
+
The output format is the template's own: give a `.docx` template and you get a
|
|
46
|
+
`.docx`, give an `.odt` template and you get an `.odt`. Use `.odt` when the
|
|
47
|
+
template comes from LibreOffice and must keep features that a
|
|
48
|
+
Word round-trip would flatten (frames, columns, a designed table of contents,
|
|
49
|
+
an existing back cover).
|
|
50
|
+
|
|
51
|
+
## Requirements
|
|
52
|
+
|
|
53
|
+
- [pandoc](https://pandoc.org) 3.x — the conversion engine.
|
|
54
|
+
- Python 3.9+ with the packages in `requirements.txt`.
|
|
55
|
+
- LibreOffice (`soffice`) — only for the optional `--pdf` export, and always for
|
|
56
|
+
the ODT table-of-contents pass.
|
|
57
|
+
|
|
58
|
+
## Install
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
pip install markdown2word # installs the `md2doc` command
|
|
62
|
+
# or, from a clone:
|
|
63
|
+
uv venv .venv && uv pip install --python .venv/bin/python -r requirements.txt
|
|
64
|
+
PYTHONPATH=src .venv/bin/python -m md2doc.cli --help
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
`scripts/make_assets.py` regenerates the bundled default template
|
|
68
|
+
(`src/md2doc/assets/template.docx`) from pandoc's own reference document. You
|
|
69
|
+
only need it if you want to rebuild the stock template.
|
|
70
|
+
|
|
71
|
+
## The Markdown file
|
|
72
|
+
|
|
73
|
+
The file starts with a YAML front matter between `---` lines:
|
|
74
|
+
|
|
75
|
+
```yaml
|
|
76
|
+
---
|
|
77
|
+
title: Rapport d'exemple
|
|
78
|
+
tagline: OPEN-PV : outil paramétré
|
|
79
|
+
subtitle: PU 10 : comparaison des bases
|
|
80
|
+
author:
|
|
81
|
+
- Camille Dupont
|
|
82
|
+
- Raphaël Jolivet
|
|
83
|
+
date: Juillet 2026
|
|
84
|
+
year: 2026 # optional; read from `date` otherwise
|
|
85
|
+
contract: 2025AC000028
|
|
86
|
+
lang: fr-FR
|
|
87
|
+
toc: true # insert a table of contents
|
|
88
|
+
---
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
Recognised keys (all become `{{ placeholders }}` in the template):
|
|
92
|
+
|
|
93
|
+
| Key | Role |
|
|
94
|
+
|------------|-------------------------------------------------------------------|
|
|
95
|
+
| `title` | document title |
|
|
96
|
+
| `tagline` | programme / collection tagline |
|
|
97
|
+
| `subtitle` | document subtitle |
|
|
98
|
+
| `author` | one name or a list; joined with commas |
|
|
99
|
+
| `date` | date (defaults to today) |
|
|
100
|
+
| `year` | year; taken from a 4-digit number found in `date` otherwise |
|
|
101
|
+
| `contract` | contract number |
|
|
102
|
+
| `lang` | document language (e.g. `fr-FR`); drives the spell checker |
|
|
103
|
+
| `toc` | `true` builds the table of contents (same as `--toc`) |
|
|
104
|
+
|
|
105
|
+
Any other scalar key is exposed to the template too. The keys above are
|
|
106
|
+
*consumed*: they are removed from what is handed to pandoc, so they do not leak
|
|
107
|
+
into the body.
|
|
108
|
+
|
|
109
|
+
For ODT, `lang` sets the language on the default paragraph/character styles and
|
|
110
|
+
writes `<dc:language>` in the document metadata, which is what LibreOffice's
|
|
111
|
+
spell checker reads.
|
|
112
|
+
|
|
113
|
+
The body is ordinary pandoc Markdown: headings, lists (bullet and numbered),
|
|
114
|
+
**bold**, *italic*, `inline code`, fenced code blocks, block quotes, tables,
|
|
115
|
+
images (``), footnotes (`[^1]`) and links. Each one maps
|
|
116
|
+
to a native style, so reviewers can restyle the whole document at once.
|
|
117
|
+
|
|
118
|
+
## The template — what it does
|
|
119
|
+
|
|
120
|
+
A template is a normal `.docx` or `.odt` with two jobs:
|
|
121
|
+
|
|
122
|
+
1. **Styles** — pandoc uses it as its style reference: paragraph and character
|
|
123
|
+
styles, page size, margins, headers and footers. The template is meant to be
|
|
124
|
+
**self-sufficient**: it should carry every style the body needs, so no
|
|
125
|
+
separate style file is required.
|
|
126
|
+
2. **Front matter and back matter** — for DOCX its body is rendered with
|
|
127
|
+
[docxtpl](https://docxtpl.readthedocs.io) from the front matter (cover,
|
|
128
|
+
résumé, abstract…). For ODT the body is read as-is and the Markdown body is
|
|
129
|
+
spliced where a `{{ body }}` marker sits, and an optional `--back` document
|
|
130
|
+
where `{{ back }}` sits.
|
|
131
|
+
|
|
132
|
+
Put any `{{ placeholder }}` you like in the front matter: `{{ title }}`,
|
|
133
|
+
`{{ subtitle }}`, `{{ authors }}`, `{{ date }}`, plus any extra front-matter
|
|
134
|
+
key. Two placeholders are special:
|
|
135
|
+
|
|
136
|
+
| Placeholder | DOCX | ODT |
|
|
137
|
+
|-------------|----------------------------------------|--------------------------------------------|
|
|
138
|
+
| `{{ toc }}` | a live Word TOC field | a table of contents rebuilt by md2doc |
|
|
139
|
+
| `{{ pages }}` | a live `NUMPAGES` field | a live `text:page-count` field |
|
|
140
|
+
|
|
141
|
+
An existing ADEME-styled `text:table-of-content` element is also filled (its
|
|
142
|
+
cached entries are replaced), so an ODT template that already contains a
|
|
143
|
+
sommaire keeps its exact look.
|
|
144
|
+
|
|
145
|
+
### Custom styles and table theme
|
|
146
|
+
|
|
147
|
+
For ODT templates an optional styles file makes everything explicit and keepable
|
|
148
|
+
next to the template (pass it with `--styles`):
|
|
149
|
+
|
|
150
|
+
```xml
|
|
151
|
+
<md2doc-styles xmlns:style="…" xmlns:fo="…">
|
|
152
|
+
<!-- redirect a pandoc style to one the template already has -->
|
|
153
|
+
<md2doc-rename from="Heading_20_1" to="Titre_20_1"/>
|
|
154
|
+
|
|
155
|
+
<!-- add or override a named style -->
|
|
156
|
+
<style:style style:name="Text_20_body" style:family="paragraph"
|
|
157
|
+
style:parent-style-name="Normal"/>
|
|
158
|
+
|
|
159
|
+
<!-- promote a paragraph style to a TOC heading -->
|
|
160
|
+
<md2doc-toc-heading style="titre_20_SANS_20_NUMEROTATION" level="1"/>
|
|
161
|
+
|
|
162
|
+
<!-- borders and header fill for pandoc's automatic table cells -->
|
|
163
|
+
<md2doc-table border="#810F3F" header-bg="#810F3F" header-fg="#FFFFFF"/>
|
|
164
|
+
</md2doc-styles>
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
All elements are optional. `<md2doc-rename>` is preferred over an alias style
|
|
168
|
+
when the template's own style drives chapter numbering: an alias with the same
|
|
169
|
+
outline level makes LibreOffice drop it.
|
|
170
|
+
|
|
171
|
+
### Customising it
|
|
172
|
+
|
|
173
|
+
Open the template in Word or LibreOffice and edit it like any document:
|
|
174
|
+
|
|
175
|
+
- restyle `Normal`, `Title`, `Heading 1`, `Caption`, … — the body follows;
|
|
176
|
+
- change the page size, margins, header and footer;
|
|
177
|
+
- edit the front matter, keeping or moving the `{{ ... }}` fields.
|
|
178
|
+
|
|
179
|
+
Save it back and re-run `md2doc`. Nothing else to configure.
|
|
180
|
+
|
|
181
|
+
## Command-line reference
|
|
182
|
+
|
|
183
|
+
```
|
|
184
|
+
md2doc INPUT.md [-o OUT] [-t TEMPLATE] [--styles STYLES.xml]
|
|
185
|
+
[--back BACK] [--no-cover] [--toc] [--toc-depth N]
|
|
186
|
+
[--pdf] [--keep]
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
| Option | Effect |
|
|
190
|
+
|--------------------|---------------------------------------------------------------|
|
|
191
|
+
| `-o`, `--output` | output file (default: next to the input, with the template's extension) |
|
|
192
|
+
| `-t`, `--template` | template (`.docx` or `.odt`; default: bundled `template.docx`) |
|
|
193
|
+
| `--styles` | explicit custom styles + table theme (ODT) |
|
|
194
|
+
| `--back` | document appended after the body (ODT: spliced at `{{ back }}`)|
|
|
195
|
+
| `--no-cover` | styles only; keep pandoc's title block (DOCX only) |
|
|
196
|
+
| `--toc` | build a table of contents |
|
|
197
|
+
| `--toc-depth` | heading levels kept in the TOC (default: 3) |
|
|
198
|
+
| `--pdf` | also export a PDF with LibreOffice |
|
|
199
|
+
| `--keep` | keep the intermediate `build/` files |
|
|
200
|
+
|
|
201
|
+
## Notes and limits
|
|
202
|
+
|
|
203
|
+
- **ODT table of contents** — LibreOffice does not update indexes in
|
|
204
|
+
`--headless` mode. `md2doc` therefore fills the entries itself and runs a
|
|
205
|
+
**two-pass** build: render once to locate each heading in the PDF, then render
|
|
206
|
+
again with the page numbers filled in. `--pdf` is what enables the second pass.
|
|
207
|
+
- **DOCX table of contents** — pandoc inserts a real Word TOC *field*. It is
|
|
208
|
+
empty until the reader updates it; Word does so on open (pandoc sets the
|
|
209
|
+
"update fields" flag). In LibreOffice, use *Tools ▸ Update ▸ Indexes and
|
|
210
|
+
tables* if the PDF shows it blank.
|
|
211
|
+
- **Images** — relative paths in the Markdown resolve against the working
|
|
212
|
+
directory, so run `md2doc` from the project root. Images wider than the
|
|
213
|
+
template's text area are scaled down to fit, keeping their aspect ratio.
|
|
214
|
+
- **ODF style names** — spaces in style names are encoded as `_20_`. Pandoc
|
|
215
|
+
passes `custom-style` values verbatim, so md2doc encodes them before splicing.
|
|
216
|
+
- **Bullets render blank in LibreOffice / OnlyOffice** — pandoc marks its DOCX
|
|
217
|
+
bullets with the Word *Symbol* font (U+F0B7). On a machine without Symbol,
|
|
218
|
+
readers show nothing. `md2doc` rewrites them to a plain `•` automatically.
|
|
219
|
+
- **Complex fixed pages** (multi-column back matter, designed back covers, text
|
|
220
|
+
boxes) are not produced by Markdown. Keep such pages in the template, or pass
|
|
221
|
+
them as a separate `.odt`/`.docx` to `--back`.
|
|
222
|
+
|
|
223
|
+
## Layout
|
|
224
|
+
|
|
225
|
+
```
|
|
226
|
+
md2doc/
|
|
227
|
+
pyproject.toml package metadata (distribution: markdown2word)
|
|
228
|
+
requirements.txt Python dependencies
|
|
229
|
+
scripts/make_assets.py builds the bundled default template
|
|
230
|
+
src/md2doc/
|
|
231
|
+
cli.py argument parsing, format dispatch, two-pass TOC
|
|
232
|
+
frontmatter.py YAML front matter and placeholder context
|
|
233
|
+
pandoc.py pandoc / LibreOffice wrappers
|
|
234
|
+
docx.py DOCX backend
|
|
235
|
+
odt.py ODT backend
|
|
236
|
+
assets/template.docx styles + cover (generated; edit freely)
|
|
237
|
+
assets/reference.odt pandoc's stock ODT styles, merged on demand
|
|
238
|
+
examples/rapport.md sample source
|
|
239
|
+
tests/ unit tests
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
## A worked example
|
|
243
|
+
|
|
244
|
+
The openpv repository shows the ODT path end to end — splitting a delivered
|
|
245
|
+
report into a reusable front/back template and rebuilding it from Markdown —
|
|
246
|
+
under `doc/livrables/pu10/md2doc/`.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
md2doc/__init__.py,sha256=MQD2e6w6z4wp1EPy4bamrbNHL7wyegk5CnmDTs6RzLU,482
|
|
2
|
+
md2doc/cli.py,sha256=x-YjO7addCbq6_WCE_2ajtir_fMiWOPQQgXLXvReyUI,4672
|
|
3
|
+
md2doc/docx.py,sha256=t4xI5Sze8eulPkIr_IhZ0SIrj7WXGB75bh9RC1Biudc,4474
|
|
4
|
+
md2doc/frontmatter.py,sha256=qYJW1HKSyTTop3INR_GqlbGUUwhua94xdho2ShW67ko,2479
|
|
5
|
+
md2doc/odt.py,sha256=93x-d3obz8N1mn7z_ltPyWxdMCI10BRBMj_VrXYvALY,26330
|
|
6
|
+
md2doc/pandoc.py,sha256=iTt6JXIuLo3z8FYRFqgFE4MxCYTlRxDeJcC2Xnw8QSU,2286
|
|
7
|
+
md2doc/assets/reference.odt,sha256=_cL7V9Ze6AgtnGdZPm4Ar4czoO_3jZC-Z2RpRpmjOpY,7158
|
|
8
|
+
md2doc/assets/template.docx,sha256=P5-laba_TGADCmaiIOnPwIPYfgkt9KOLsW6FAK1-Rvw,11024
|
|
9
|
+
markdown2word-0.1.0.dist-info/METADATA,sha256=z8_g-TeT72KocqxEzTxua7bmBnLGgqcBzi_eCogBfzE,11112
|
|
10
|
+
markdown2word-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
11
|
+
markdown2word-0.1.0.dist-info/entry_points.txt,sha256=t9YcdsUap2p__wPs7YRa2XbDl84oXN6ib9v_efUU0j0,43
|
|
12
|
+
markdown2word-0.1.0.dist-info/licenses/LICENSE,sha256=4yiETm1W3XP8LxELDZYtlVSU1qxfPCYniUaiyi9uPHQ,1073
|
|
13
|
+
markdown2word-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Raphaël Jolivet
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
md2doc/__init__.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""md2doc - Markdown (with YAML front matter) + a Word/ODT template -> document.
|
|
2
|
+
|
|
3
|
+
The template is a normal ``.docx`` or ``.odt`` file that plays two roles: its
|
|
4
|
+
styles, page setup and headers style the document, and its body is the front
|
|
5
|
+
matter (cover, résumé, table of contents…) with ``{{ placeholder }}`` fields
|
|
6
|
+
filled from the Markdown front matter. The Markdown body is rendered by pandoc
|
|
7
|
+
and spliced in; an optional back matter file is appended.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
__version__ = "0.1.0"
|
|
Binary file
|
|
Binary file
|
md2doc/cli.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"""Command-line entry point for md2doc."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import re
|
|
6
|
+
import subprocess
|
|
7
|
+
import tempfile
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from . import docx, odt
|
|
11
|
+
from .frontmatter import split_front_matter
|
|
12
|
+
from .pandoc import to_pdf
|
|
13
|
+
|
|
14
|
+
HERE = Path(__file__).resolve().parent
|
|
15
|
+
DEFAULT_TEMPLATE = HERE / "assets" / "template.docx"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _norm(text):
|
|
19
|
+
return re.sub(r"\s+", "", text).lower()
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _pdf_pages(pdf):
|
|
23
|
+
out = subprocess.run(["pdfinfo", str(pdf)], capture_output=True, text=True).stdout
|
|
24
|
+
m = re.search(r"^Pages:\s+(\d+)", out, re.M)
|
|
25
|
+
return int(m.group(1)) if m else 0
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def locate_pages(pdf, headings):
|
|
29
|
+
"""Map each heading anchor to the page of its first occurrence in *pdf*."""
|
|
30
|
+
n = _pdf_pages(pdf)
|
|
31
|
+
pages_text = {}
|
|
32
|
+
for p in range(1, n + 1):
|
|
33
|
+
r = subprocess.run(["pdftotext", "-f", str(p), "-l", str(p), str(pdf), "-"],
|
|
34
|
+
capture_output=True, text=True)
|
|
35
|
+
pages_text[p] = _norm(r.stdout)
|
|
36
|
+
located = {}
|
|
37
|
+
floor = 1
|
|
38
|
+
for h in headings:
|
|
39
|
+
target = _norm(h["text"])
|
|
40
|
+
if not target:
|
|
41
|
+
continue
|
|
42
|
+
for p in range(floor, n + 1):
|
|
43
|
+
if target in pages_text[p]:
|
|
44
|
+
located[h["anchor"]] = p
|
|
45
|
+
floor = p
|
|
46
|
+
break
|
|
47
|
+
return located
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def build(template, meta, body, out, *, toc, toc_depth, back, no_cover, work,
|
|
51
|
+
styles=None):
|
|
52
|
+
if Path(template).suffix.lower() == ".odt":
|
|
53
|
+
if no_cover:
|
|
54
|
+
raise SystemExit("--no-cover is not supported for ODT templates")
|
|
55
|
+
if toc:
|
|
56
|
+
_, headings = odt.build(template, meta, body, out, toc=True,
|
|
57
|
+
toc_depth=toc_depth, back=back, work=work,
|
|
58
|
+
toc_fill=False, styles_path=styles)
|
|
59
|
+
pdf = to_pdf(out)
|
|
60
|
+
pages = locate_pages(pdf, headings)
|
|
61
|
+
out, _ = odt.build(template, meta, body, out, toc=True,
|
|
62
|
+
toc_depth=toc_depth, back=back, work=work,
|
|
63
|
+
toc_pages=pages, styles_path=styles)
|
|
64
|
+
else:
|
|
65
|
+
out, _ = odt.build(template, meta, body, out, toc=False,
|
|
66
|
+
back=back, work=work, styles_path=styles)
|
|
67
|
+
return out
|
|
68
|
+
return docx.build(template, meta, body, out, toc=toc, toc_depth=toc_depth,
|
|
69
|
+
no_cover=no_cover, back=back, work=work)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def main(argv=None):
|
|
73
|
+
parser = argparse.ArgumentParser(
|
|
74
|
+
description=__doc__,
|
|
75
|
+
formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
76
|
+
parser.add_argument("input", type=Path, help="Markdown file with YAML front matter")
|
|
77
|
+
parser.add_argument("-o", "--output", type=Path, help="output document")
|
|
78
|
+
parser.add_argument("-t", "--template", type=Path, default=DEFAULT_TEMPLATE,
|
|
79
|
+
help="template (.docx or .odt): styles + front matter")
|
|
80
|
+
parser.add_argument("--back", type=Path,
|
|
81
|
+
help="document appended after the body (back matter)")
|
|
82
|
+
parser.add_argument("--styles", type=Path,
|
|
83
|
+
help="explicit custom styles for the template "
|
|
84
|
+
"(ODT: named styles + table theme)")
|
|
85
|
+
parser.add_argument("--no-cover", action="store_true",
|
|
86
|
+
help="styles only; keep pandoc's title block (DOCX only)")
|
|
87
|
+
parser.add_argument("--toc", action="store_true", help="build a table of contents")
|
|
88
|
+
parser.add_argument("--toc-depth", type=int, default=3)
|
|
89
|
+
parser.add_argument("--pdf", action="store_true",
|
|
90
|
+
help="also export a PDF via LibreOffice")
|
|
91
|
+
parser.add_argument("--keep", action="store_true", help="keep intermediate files")
|
|
92
|
+
args = parser.parse_args(argv)
|
|
93
|
+
|
|
94
|
+
template = args.template
|
|
95
|
+
if not template.exists():
|
|
96
|
+
raise SystemExit(f"template not found: {template}")
|
|
97
|
+
out = args.output
|
|
98
|
+
if out is None:
|
|
99
|
+
out = args.input.with_suffix(".odt" if template.suffix.lower() == ".odt"
|
|
100
|
+
else ".docx")
|
|
101
|
+
|
|
102
|
+
meta, body = split_front_matter(args.input.read_text(encoding="utf-8"))
|
|
103
|
+
toc = args.toc or bool(meta.get("toc"))
|
|
104
|
+
toc_depth = int(meta.get("toc-depth", args.toc_depth))
|
|
105
|
+
|
|
106
|
+
with tempfile.TemporaryDirectory(prefix="md2doc-") as tmp:
|
|
107
|
+
work = Path("build") if args.keep else Path(tmp)
|
|
108
|
+
work.mkdir(exist_ok=True)
|
|
109
|
+
build(template, meta, body, out, toc=toc, toc_depth=toc_depth,
|
|
110
|
+
back=args.back, no_cover=args.no_cover, work=work,
|
|
111
|
+
styles=args.styles)
|
|
112
|
+
print(f"wrote {out}")
|
|
113
|
+
if args.pdf:
|
|
114
|
+
print(f"wrote {to_pdf(out)}")
|
|
115
|
+
return 0
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
if __name__ == "__main__":
|
|
119
|
+
raise SystemExit(main())
|
md2doc/docx.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"""DOCX backend: Markdown + a .docx template -> .docx.
|
|
2
|
+
|
|
3
|
+
The template supplies the styles (it is also pandoc's style reference) and its
|
|
4
|
+
body is the front matter, rendered with docxtpl. The Markdown body is produced
|
|
5
|
+
by pandoc and appended with docxcompose. ``{{ toc }}`` and ``{{ pages }}``
|
|
6
|
+
become live Word fields (table of contents, page count).
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import re
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from .frontmatter import body_markdown, context
|
|
14
|
+
|
|
15
|
+
W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
|
|
16
|
+
|
|
17
|
+
TOC_SENTINEL = "\ue000MD2DOC_TOC\ue001"
|
|
18
|
+
PAGES_SENTINEL = "\ue000MD2DOC_PAGES\ue001"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _field_runs(instr, cached="1"):
|
|
22
|
+
"""Return the XML of Word runs implementing a simple field."""
|
|
23
|
+
return (
|
|
24
|
+
f'<w:r xmlns:w="{W}"><w:fldChar w:fldCharType="begin"/></w:r>'
|
|
25
|
+
f'<w:r xmlns:w="{W}"><w:instrText xml:space="preserve"> {instr} '
|
|
26
|
+
f'</w:instrText></w:r>'
|
|
27
|
+
f'<w:r xmlns:w="{W}"><w:fldChar w:fldCharType="separate"/></w:r>'
|
|
28
|
+
f'<w:r xmlns:w="{W}"><w:t xml:space="preserve">{cached}</w:t></w:r>'
|
|
29
|
+
f'<w:r xmlns:w="{W}"><w:fldChar w:fldCharType="end"/></w:r>'
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _replace_sentinel(paragraph, sentinel, field_xml):
|
|
34
|
+
"""Replace the run holding *sentinel* by *field_xml* runs, in place."""
|
|
35
|
+
from lxml import etree
|
|
36
|
+
|
|
37
|
+
for run in list(paragraph.runs):
|
|
38
|
+
if sentinel in run.text:
|
|
39
|
+
before, _, after = run.text.partition(sentinel)
|
|
40
|
+
run.text = before
|
|
41
|
+
anchor = run._r
|
|
42
|
+
for frag in etree.fromstring(
|
|
43
|
+
f'<w:wrap xmlns:w="{W}">{field_xml}</w:wrap>').iterchildren():
|
|
44
|
+
anchor.addnext(frag)
|
|
45
|
+
anchor = frag
|
|
46
|
+
if after:
|
|
47
|
+
new = etree.SubElement(paragraph._p, f"{{{W}}}r")
|
|
48
|
+
t = etree.SubElement(new, f"{{{W}}}t")
|
|
49
|
+
t.set("{http://www.w3.org/XML/1998/namespace}space", "preserve")
|
|
50
|
+
t.text = after
|
|
51
|
+
return True
|
|
52
|
+
return False
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _replace_paragraph(paragraph, field_xml):
|
|
56
|
+
"""Replace the whole paragraph content with *field_xml* runs."""
|
|
57
|
+
from lxml import etree
|
|
58
|
+
for child in list(paragraph._p):
|
|
59
|
+
if child.tag != f"{{{W}}}pPr":
|
|
60
|
+
paragraph._p.remove(child)
|
|
61
|
+
for frag in etree.fromstring(
|
|
62
|
+
f'<w:wrap xmlns:w="{W}">{field_xml}</w:wrap>').iterchildren():
|
|
63
|
+
paragraph._p.append(frag)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _set_update_fields(doc):
|
|
67
|
+
from docx.oxml.ns import qn
|
|
68
|
+
from docx.oxml import OxmlElement
|
|
69
|
+
settings = doc.settings.element
|
|
70
|
+
if settings.find(qn("w:updateFields")) is None:
|
|
71
|
+
el = OxmlElement("w:updateFields")
|
|
72
|
+
el.set(qn("w:val"), "true")
|
|
73
|
+
settings.append(el)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _apply_fields(doc, toc, toc_depth):
|
|
77
|
+
"""Replace the TOC / page-count sentinels with real Word fields."""
|
|
78
|
+
for paragraph in doc.paragraphs:
|
|
79
|
+
text = "".join(r.text for r in paragraph.runs).strip()
|
|
80
|
+
if text == TOC_SENTINEL:
|
|
81
|
+
_replace_paragraph(paragraph,
|
|
82
|
+
_field_runs(f'TOC \\o "1-{toc_depth}" \\h \\z \\u',
|
|
83
|
+
"Mettez à jour le champ (F9)."))
|
|
84
|
+
elif PAGES_SENTINEL in "".join(r.text for r in paragraph.runs):
|
|
85
|
+
_replace_sentinel(paragraph, PAGES_SENTINEL,
|
|
86
|
+
_field_runs("NUMPAGES", "1"))
|
|
87
|
+
if toc:
|
|
88
|
+
_set_update_fields(doc)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def build(template, meta, body, out, *, toc=False, toc_depth=3,
|
|
92
|
+
no_cover=False, back=None, work=None):
|
|
93
|
+
from docx import Document
|
|
94
|
+
from docxcompose.composer import Composer
|
|
95
|
+
|
|
96
|
+
from . import pandoc
|
|
97
|
+
|
|
98
|
+
work = Path(work)
|
|
99
|
+
ctx = context(meta)
|
|
100
|
+
ctx["toc"] = TOC_SENTINEL
|
|
101
|
+
ctx["pages"] = PAGES_SENTINEL
|
|
102
|
+
|
|
103
|
+
body_md = work / "body.md"
|
|
104
|
+
body_md.write_text(body_markdown(meta, body), encoding="utf-8")
|
|
105
|
+
body_docx = pandoc.body_to_docx(body_md, work / "body.docx", reference=template)
|
|
106
|
+
pandoc.fix_list_bullets(body_docx)
|
|
107
|
+
|
|
108
|
+
if no_cover:
|
|
109
|
+
doc = Document(body_docx)
|
|
110
|
+
composer = Composer(doc)
|
|
111
|
+
else:
|
|
112
|
+
from docxtpl import DocxTemplate
|
|
113
|
+
cover = work / "cover.docx"
|
|
114
|
+
tpl = DocxTemplate(str(template))
|
|
115
|
+
tpl.render(ctx)
|
|
116
|
+
tpl.save(str(cover))
|
|
117
|
+
doc = Document(cover)
|
|
118
|
+
_apply_fields(doc, toc, toc_depth)
|
|
119
|
+
doc.save(str(cover))
|
|
120
|
+
composer = Composer(doc)
|
|
121
|
+
composer.append(Document(body_docx))
|
|
122
|
+
|
|
123
|
+
if back is not None:
|
|
124
|
+
composer.append(Document(str(back)))
|
|
125
|
+
composer.save(str(out))
|
|
126
|
+
return out
|
md2doc/frontmatter.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""YAML front matter parsing and cover/citation context."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import datetime as dt
|
|
5
|
+
import re
|
|
6
|
+
|
|
7
|
+
import yaml
|
|
8
|
+
|
|
9
|
+
#: Keys consumed by the front matter (cover, citation, TOC); they are removed
|
|
10
|
+
#: from what is forwarded to pandoc, so they do not leak into the body.
|
|
11
|
+
FRONT_KEYS = {
|
|
12
|
+
"title", "tagline", "subtitle", "author", "authors", "date", "year",
|
|
13
|
+
"contract", "lang", "toc", "toc-depth",
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def split_front_matter(text):
|
|
18
|
+
"""Return ``(metadata, body)``; the body drops the leading ``---`` block."""
|
|
19
|
+
if not text.startswith("---"):
|
|
20
|
+
return {}, text
|
|
21
|
+
end = text.find("\n---", 3)
|
|
22
|
+
if end == -1:
|
|
23
|
+
return {}, text
|
|
24
|
+
meta = yaml.safe_load(text[3:end]) or {}
|
|
25
|
+
return meta, text[end + 4:].lstrip("\n")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _fmt_authors(author):
|
|
29
|
+
if isinstance(author, (list, tuple)):
|
|
30
|
+
return ", ".join(str(a) for a in author)
|
|
31
|
+
return str(author) if author else ""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def context(meta):
|
|
35
|
+
"""Normalise front-matter values into the placeholder context.
|
|
36
|
+
|
|
37
|
+
Provides ``title``, ``tagline``, ``subtitle``, ``date``, ``authors``,
|
|
38
|
+
``year`` and ``contract``; missing values become empty strings.
|
|
39
|
+
"""
|
|
40
|
+
date = meta.get("date")
|
|
41
|
+
if date is None:
|
|
42
|
+
date = dt.date.today().isoformat()
|
|
43
|
+
year = meta.get("year")
|
|
44
|
+
if year is None:
|
|
45
|
+
# ``date`` is free text (e.g. "Juillet 2026"); take its year, not its
|
|
46
|
+
# first four characters.
|
|
47
|
+
found = re.search(r"\b(19|20)\d{2}\b", str(date))
|
|
48
|
+
year = found.group(0) if found else str(date)[:4]
|
|
49
|
+
ctx = {k: "" for k in ("title", "tagline", "subtitle", "contract")}
|
|
50
|
+
ctx.update({
|
|
51
|
+
"title": meta.get("title", "") or "",
|
|
52
|
+
"tagline": meta.get("tagline", "") or "",
|
|
53
|
+
"subtitle": meta.get("subtitle", "") or "",
|
|
54
|
+
"contract": meta.get("contract", "") or "",
|
|
55
|
+
"date": str(date),
|
|
56
|
+
"year": str(year),
|
|
57
|
+
"authors": _fmt_authors(meta.get("author")),
|
|
58
|
+
})
|
|
59
|
+
# any extra scalar front-matter key is exposed too
|
|
60
|
+
for key, value in meta.items():
|
|
61
|
+
if key not in ctx and isinstance(value, (str, int, float)):
|
|
62
|
+
ctx[key] = str(value)
|
|
63
|
+
return ctx
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def body_markdown(meta, body):
|
|
67
|
+
"""Re-emit the body, stripping the front-matter keys the template consumes."""
|
|
68
|
+
keys = {k: v for k, v in meta.items() if k.lower() not in FRONT_KEYS}
|
|
69
|
+
if not keys:
|
|
70
|
+
return body
|
|
71
|
+
header = yaml.safe_dump(keys, allow_unicode=True, sort_keys=False)
|
|
72
|
+
return f"---\n{header}---\n\n{body}"
|