Metadata-Version: 2.5
Name: markdown2word
Version: 0.1.0
Summary: Markdown + YAML front matter + a Word/ODT template -> styled document
Project-URL: Source, https://git.sophia.minesparis.psl.eu/rjolivet/md2doc
Author: Raphaël Jolivet
License: MIT
License-File: LICENSE
Keywords: docx,markdown,odt,opendocument,pandoc,template
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: Console
Classifier: Intended Audience :: End Users/Desktop
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Text Processing :: Markup
Requires-Python: >=3.9
Requires-Dist: docxcompose>=1.4
Requires-Dist: docxtpl>=0.18
Requires-Dist: lxml>=4.9
Requires-Dist: python-docx>=1.1
Requires-Dist: pyyaml>=6.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == 'dev'
Description-Content-Type: text/markdown

# md2doc — Markdown + a Word/ODT template → a styled document

`md2doc` turns a Markdown file with a YAML header into a real `.docx` or `.odt`,
built on your own template. It is meant for the common split: you write in plain
text, your colleagues review in Word or LibreOffice.

```
Report.md  +  template.docx  ──►  Report.docx  (──► Report.pdf)
Report.md  +  template.odt   ──►  Report.odt   (──► Report.pdf)
```

## Why

Markdown is quick to write, diffs cleanly and stays readable in a git
repository. Word is what reviewers, managers and clients actually open, comment
on and print. `md2doc` keeps the source in Markdown while producing a document
that is 100 % native: real styles, real headings, real tables, a real cover page
— not a text dump pasted into a blank file.

The output format is the template's own: give a `.docx` template and you get a
`.docx`, give an `.odt` template and you get an `.odt`. Use `.odt` when the
template comes from LibreOffice and must keep features that a
Word round-trip would flatten (frames, columns, a designed table of contents,
an existing back cover).

## Requirements

- [pandoc](https://pandoc.org) 3.x — the conversion engine.
- Python 3.9+ with the packages in `requirements.txt`.
- LibreOffice (`soffice`) — only for the optional `--pdf` export, and always for
  the ODT table-of-contents pass.

## Install

```bash
pip install markdown2word          # installs the `md2doc` command
# or, from a clone:
uv venv .venv && uv pip install --python .venv/bin/python -r requirements.txt
PYTHONPATH=src .venv/bin/python -m md2doc.cli --help
```

`scripts/make_assets.py` regenerates the bundled default template
(`src/md2doc/assets/template.docx`) from pandoc's own reference document. You
only need it if you want to rebuild the stock template.

## The Markdown file

The file starts with a YAML front matter between `---` lines:

```yaml
---
title: Rapport d'exemple
tagline: OPEN-PV : outil paramétré
subtitle: PU 10 : comparaison des bases
author:
  - Camille Dupont
  - Raphaël Jolivet
date: Juillet 2026
year: 2026            # optional; read from `date` otherwise
contract: 2025AC000028
lang: fr-FR
toc: true             # insert a table of contents
---
```

Recognised keys (all become `{{ placeholders }}` in the template):

| Key        | Role                                                              |
|------------|-------------------------------------------------------------------|
| `title`    | document title                                                    |
| `tagline`  | programme / collection tagline                                    |
| `subtitle` | document subtitle                                                 |
| `author`   | one name or a list; joined with commas                             |
| `date`     | date (defaults to today)                                          |
| `year`     | year; taken from a 4-digit number found in `date` otherwise       |
| `contract` | contract number                                                   |
| `lang`     | document language (e.g. `fr-FR`); drives the spell checker        |
| `toc`      | `true` builds the table of contents (same as `--toc`)             |

Any other scalar key is exposed to the template too. The keys above are
*consumed*: they are removed from what is handed to pandoc, so they do not leak
into the body.

For ODT, `lang` sets the language on the default paragraph/character styles and
writes `<dc:language>` in the document metadata, which is what LibreOffice's
spell checker reads.

The body is ordinary pandoc Markdown: headings, lists (bullet and numbered),
**bold**, *italic*, `inline code`, fenced code blocks, block quotes, tables,
images (`![caption](figure.png)`), footnotes (`[^1]`) and links. Each one maps
to a native style, so reviewers can restyle the whole document at once.

## The template — what it does

A template is a normal `.docx` or `.odt` with two jobs:

1. **Styles** — pandoc uses it as its style reference: paragraph and character
   styles, page size, margins, headers and footers. The template is meant to be
   **self-sufficient**: it should carry every style the body needs, so no
   separate style file is required.
2. **Front matter and back matter** — for DOCX its body is rendered with
   [docxtpl](https://docxtpl.readthedocs.io) from the front matter (cover,
   résumé, abstract…). For ODT the body is read as-is and the Markdown body is
   spliced where a `{{ body }}` marker sits, and an optional `--back` document
   where `{{ back }}` sits.

Put any `{{ placeholder }}` you like in the front matter: `{{ title }}`,
`{{ subtitle }}`, `{{ authors }}`, `{{ date }}`, plus any extra front-matter
key. Two placeholders are special:

| Placeholder | DOCX                                   | ODT                                        |
|-------------|----------------------------------------|--------------------------------------------|
| `{{ toc }}` | a live Word TOC field                  | a table of contents rebuilt by md2doc      |
| `{{ pages }}` | a live `NUMPAGES` field              | a live `text:page-count` field             |

An existing ADEME-styled `text:table-of-content` element is also filled (its
cached entries are replaced), so an ODT template that already contains a
sommaire keeps its exact look.

### Custom styles and table theme

For ODT templates an optional styles file makes everything explicit and keepable
next to the template (pass it with `--styles`):

```xml
<md2doc-styles xmlns:style="…" xmlns:fo="…">
  <!-- redirect a pandoc style to one the template already has -->
  <md2doc-rename from="Heading_20_1" to="Titre_20_1"/>

  <!-- add or override a named style -->
  <style:style style:name="Text_20_body" style:family="paragraph"
               style:parent-style-name="Normal"/>

  <!-- promote a paragraph style to a TOC heading -->
  <md2doc-toc-heading style="titre_20_SANS_20_NUMEROTATION" level="1"/>

  <!-- borders and header fill for pandoc's automatic table cells -->
  <md2doc-table border="#810F3F" header-bg="#810F3F" header-fg="#FFFFFF"/>
</md2doc-styles>
```

All elements are optional. `<md2doc-rename>` is preferred over an alias style
when the template's own style drives chapter numbering: an alias with the same
outline level makes LibreOffice drop it.

### Customising it

Open the template in Word or LibreOffice and edit it like any document:

- restyle `Normal`, `Title`, `Heading 1`, `Caption`, … — the body follows;
- change the page size, margins, header and footer;
- edit the front matter, keeping or moving the `{{ ... }}` fields.

Save it back and re-run `md2doc`. Nothing else to configure.

## Command-line reference

```
md2doc INPUT.md [-o OUT] [-t TEMPLATE] [--styles STYLES.xml]
                [--back BACK] [--no-cover] [--toc] [--toc-depth N]
                [--pdf] [--keep]
```

| Option             | Effect                                                        |
|--------------------|---------------------------------------------------------------|
| `-o`, `--output`   | output file (default: next to the input, with the template's extension) |
| `-t`, `--template` | template (`.docx` or `.odt`; default: bundled `template.docx`) |
| `--styles`         | explicit custom styles + table theme (ODT)                    |
| `--back`           | document appended after the body (ODT: spliced at `{{ back }}`)|
| `--no-cover`       | styles only; keep pandoc's title block (DOCX only)            |
| `--toc`            | build a table of contents                                     |
| `--toc-depth`      | heading levels kept in the TOC (default: 3)                   |
| `--pdf`            | also export a PDF with LibreOffice                            |
| `--keep`           | keep the intermediate `build/` files                          |

## Notes and limits

- **ODT table of contents** — LibreOffice does not update indexes in
  `--headless` mode. `md2doc` therefore fills the entries itself and runs a
  **two-pass** build: render once to locate each heading in the PDF, then render
  again with the page numbers filled in. `--pdf` is what enables the second pass.
- **DOCX table of contents** — pandoc inserts a real Word TOC *field*. It is
  empty until the reader updates it; Word does so on open (pandoc sets the
  "update fields" flag). In LibreOffice, use *Tools ▸ Update ▸ Indexes and
  tables* if the PDF shows it blank.
- **Images** — relative paths in the Markdown resolve against the working
  directory, so run `md2doc` from the project root. Images wider than the
  template's text area are scaled down to fit, keeping their aspect ratio.
- **ODF style names** — spaces in style names are encoded as `_20_`. Pandoc
  passes `custom-style` values verbatim, so md2doc encodes them before splicing.
- **Bullets render blank in LibreOffice / OnlyOffice** — pandoc marks its DOCX
  bullets with the Word *Symbol* font (U+F0B7). On a machine without Symbol,
  readers show nothing. `md2doc` rewrites them to a plain `•` automatically.
- **Complex fixed pages** (multi-column back matter, designed back covers, text
  boxes) are not produced by Markdown. Keep such pages in the template, or pass
  them as a separate `.odt`/`.docx` to `--back`.

## Layout

```
md2doc/
  pyproject.toml          package metadata (distribution: markdown2word)
  requirements.txt        Python dependencies
  scripts/make_assets.py  builds the bundled default template
  src/md2doc/
    cli.py                argument parsing, format dispatch, two-pass TOC
    frontmatter.py        YAML front matter and placeholder context
    pandoc.py             pandoc / LibreOffice wrappers
    docx.py               DOCX backend
    odt.py                ODT backend
    assets/template.docx  styles + cover (generated; edit freely)
    assets/reference.odt  pandoc's stock ODT styles, merged on demand
  examples/rapport.md     sample source
  tests/                  unit tests
```

## A worked example

The openpv repository shows the ODT path end to end — splitting a delivered
report into a reusable front/back template and rebuilding it from Markdown —
under `doc/livrables/pu10/md2doc/`.
