Installation

Install as Agent Plugin Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install markdown-to-word-mermaid@skills-hub

Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled). Plugin markdown-to-word-mermaid v1.0.0 follows the Agent Plugins spec.

Install with the gh extension
gh skills-hub install markdown-to-word-mermaid

Don't have the extension? Run gh extension install samueltauil/skills-hub first.

Download and extract to your repository:

.github/skills/markdown-to-word-mermaid/

Extract the ZIP to .github/skills/ in your repo. The folder name must match markdown-to-word-mermaid for Copilot to auto-discover it.

Skill Files (6)

SKILL.md 8.1 KB
---
name: markdown-to-word-mermaid
description: 'Export Markdown containing Mermaid code fences to Word (.docx) with embedded SVG diagrams and PNG fallbacks. Use when diagram sharpness, Office-compatible labels, or page-aware placement matters. Not for Word-to-Markdown conversion, editable Office shapes, or general slide creation.'
license: MIT
argument-hint: 'Markdown input file and optional DOCX output path'
user-invocable: true
---

# Markdown to Word with Mermaid

Export technical documents without manually replacing Mermaid fences with screenshots. The bundled converter renders each diagram locally, embeds the SVG through Office OOXML relationships, and retains a 3x PNG fallback. Word is not required to generate the file; an SVG-capable Word version is needed to inspect vector rendering.

## When to use

- A design document, runbook, or report contains Mermaid code fences and must be delivered as DOCX.
- Diagram labels must remain sharp when zoomed or printed.
- A tall diagram needs page-aware placement rather than being split across pages.

For general Markdown-to-DOCX conversion with existing PNG images, a general converter such as `md-to-docx` may be simpler. This skill focuses on rendering and packaging Mermaid diagrams. SVG embedding does not create editable Word shapes, connectors, or text boxes.

## Requirements and setup

- Python 3.10+ and the packages in [scripts/requirements.txt](scripts/requirements.txt).
- Node.js compatible with the chosen Mermaid CLI release, plus `@mermaid-js/mermaid-cli`.
- A local browser usable by Puppeteer and an installed font covering the document's characters.
- Default font: Noto Sans JP. Use `--font-family` to select another installed family.

Resolve paths relative to this skill's installation directory, not an assumed repository name. The examples below run from the skill directory. Use the user's selected Python environment (`python`, `python3`, or its absolute path).

Before installing dependencies, confirm the environment and obtain permission if required. Reuse an existing Mermaid CLI when available. Otherwise install it into a user-approved local tools directory, not globally:

```sh
python -m pip install -r scripts/requirements.txt
npm install --prefix ./run/mermaid-cli @mermaid-js/mermaid-cli
```

The local executable is `./run/mermaid-cli/node_modules/.bin/mmdc` on POSIX and `./run/mermaid-cli/node_modules/.bin/mmdc.cmd` on Windows. Keep installed dependencies out of the submitted skill package. Lock the selected dependency versions in the consuming project for reproducible installations.

On Windows the converter detects standard Chrome and Edge paths. For another browser location, set `MERMAID_BROWSER_PATH` to its absolute executable path:

```powershell
$env:MERMAID_BROWSER_PATH = "C:\Program Files\Google\Chrome\Application\chrome.exe"
```

On POSIX, use `export MERMAID_BROWSER_PATH=/absolute/path/to/browser`, or use Puppeteer's installed browser. Do not disable the browser sandbox just to make a conversion pass.

## Workflow

1. Confirm the input Markdown file, output destination, and font. If no destination is provided, use the input path with a `.docx` extension.
2. Check that the output does not exist. Never delete or overwrite an existing document; ask for a different destination.
3. Run [scripts/markdown_to_word.py](scripts/markdown_to_word.py). Preserve the user's diagram source and meaning. Do not silently repair invalid Mermaid.
4. Check the generated package and, when Word is available, inspect the document visually. Report package checks and visual checks separately.

With `mmdc` on PATH:

```sh
python scripts/markdown_to_word.py input.md --output output.docx
```

Using a workspace-local CLI on Windows:

```powershell
python scripts/markdown_to_word.py input.md --output output.docx --mermaid-cli ./run/mermaid-cli/node_modules/.bin/mmdc.cmd
```

Selecting an installed font:

```sh
python scripts/markdown_to_word.py input.md --output output.docx --font-family "Noto Sans JP" --timeout 120
```

For a reproducible example, convert [assets/example.md](assets/example.md) to a new output path. It includes English and Japanese labels, multiple diagrams, and a tall diagram.

## Conversion behavior

- Headings, paragraphs, emphasis, lists (preserving ordered list start numbers and separate list boundaries), blockquotes, tables, and code blocks become Word content.
- Each Mermaid fence renders to SVG and a 3x PNG with a per-command timeout (default: 120 seconds). Office SVG extensions reference the SVG; the normal image reference retains the PNG fallback, and drawing metadata (`title` and `descr`) includes the section heading or Mermaid `accTitle`/`accDescr` plus the diagram type.
- Output DOCX files are staged and SVG-injected inside a temporary directory before moving to the destination path so failed runs never leave partial files behind.
- The selected font is applied to Word paragraph styles and Mermaid's font configuration. Code runs use Consolas. Fonts are not embedded; unavailable fonts may be substituted.
- `htmlLabels: false` is set globally and for flowcharts to avoid HTML `foreignObject` labels that Office may not display. Check actual SVG output for unsupported constructs.
- Diagrams are centered, keep their aspect ratio, and use a non-splitting paragraph. Diagrams occupying at least 70% of the page body height start on a new page. Oversized diagrams are scaled to the page body height. Large diagrams generate a readability warning.
- A simple single-line frontmatter `title` becomes the document title; other frontmatter fields are removed from the body. This is not a full YAML metadata parser.
- Ordinary Markdown image links remain alt text and a source path or URL; they are not embedded. Raw HTML is reduced to text, not executed.

## Stop conditions and limitations

- Missing input, wrong extensions, an existing output, missing CLI, invalid Mermaid, rendering failure, or unusable SVG dimensions stop the conversion with an error.
- The converter does not call an external rendering service or a separate AI API. Dependency installation and browser execution are not an offline sandbox. Review untrusted diagram content, including external resources, before rendering it.
- Diagrams are not semantically editable Office objects. Word rendering, font substitution, and final pagination depend on the viewer and must be checked there.
- A successfully created DOCX is not proof that every diagram label is readable. Split large diagrams in the source only with the user's approval.

## Verification

Run the test suite from the skill directory:

```sh
python -m unittest discover -s tests -v
```

The ordinary suite mocks Mermaid rendering. To run the real-renderer test as well, set `MERMAID_CLI` to the CLI executable's absolute path, then run the command again. On Windows PowerShell:

```powershell
$env:MERMAID_CLI = (Join-Path $env:APPDATA "npm\mmdc.cmd")
python -m unittest discover -s tests -v
```

That test renders the bundled sample and checks the resulting DOCX's SVG references, PNG fallbacks, labels, and drawing dimensions. It does not automate Word visual inspection.

Before reporting completion:

- Count Mermaid fences and verify the same number of SVG parts and SVG image references in the DOCX.
- Confirm PNG fallback references exist and no label `foreignObject` remains in the sample's SVGs.
- In Word, inspect node names, branch labels, font, diagram placement, and page boundaries; check zoomed or printed output when sharpness matters.
- If Word or the actual renderer was unavailable, state which checks were not performed.

For contribution scope, evaluation cases, and a draft submission description, see [references/publication.md](references/publication.md). That file is maintainer guidance, not permission to publish.
## Gotchas

- `mmdc.cmd` needs Windows command handling; pass its path with `--mermaid-cli` rather than rewriting the script.
- A missing font can affect both PNG rendering and SVG display. Use a family installed on the rendering and viewing machines.
- Keep the SVG and PNG paired. Replacing SVG with a screenshot defeats the vector-preserving workflow.
- Package validation, renderer tests, agent-selection evaluation, and human visual acceptance are different checks.
assets/
example.md 1.2 KB
---
title: Mermaid delivery sample
---

This synthetic example contains no project or customer data.

## Approval flow

The document owner submits a draft. A reviewer either approves it or requests changes.

```mermaid
flowchart LR
    Draft[Draft] --> Review{Approved?}
    Review -->|Yes| Publish[Publish]
    Review -->|No| Revise[Revise]
    Revise --> Draft
```

## Japanese labels

```mermaid
flowchart LR
    Input[入力] --> Check{確認済み?}
    Check -->|はい| Output[出力]
    Check -->|いいえ| Return[差戻し]
```

## Tall diagram

This diagram exercises scaling and the explicit page-break rule.

```mermaid
flowchart TD
    Receive[Receive request] --> Validate[Validate input]
    Validate --> Read[Read Markdown]
    Read --> Parse[Parse blocks]
    Parse --> Render[Render SVG]
    Render --> Fallback[Render PNG fallback]
    Fallback --> Package[Package document]
    Package --> Inspect[Inspect package]
    Inspect --> Preview[Preview in Word]
    Preview --> Deliver[Deliver document]
```

## Ordinary content

| Item | Expected result |
| ---- | --------------- |
| SVG  | SVG retained    |
| PNG  | PNG retained    |
| Text | Both languages  |

- Keep the Markdown source.
- Check the document in Word.

> Vector output is not an editable Office flowchart.
references/
publication.md 2.3 KB
# Scope and evaluation notes

## Scope vs. general Markdown converters

This skill converts Markdown documents containing Mermaid code fences into Word (`.docx`) documents. It renders diagrams locally with Mermaid CLI, embeds vector SVG through Office OOXML relationships (`asvg:svgBlip`), retains 3x PNG fallbacks, and keeps tall diagrams together with page-aware placement.

A general converter such as `md-to-docx` handles Markdown body content and pre-rendered PNG images. Use `markdown-to-word-mermaid` when the input contains Mermaid source fences that must be rendered into vector SVGs with Office-compatible text labels (`htmlLabels: false`) and page-aware sizing. Embedding an SVG does not make individual diagram nodes, connectors, or labels editable as native Word shapes.

## Evaluation cases

| Input / request | Expected behavior |
| --- | --- |
| Export a design document with Mermaid flowcharts to Word | Select this skill and embed both vector SVG and PNG fallback in the DOCX |
| Export a runbook containing a tall Mermaid diagram to Word | Keep the diagram together on a page, starting on a new page and scaling when needed |
| Convert a plain Markdown document that only links to existing PNG images | Prefer a general Markdown-to-DOCX converter if Mermaid rendering is not needed |
| Edit individual Mermaid shapes and connectors directly inside Word | Explain that embedded SVGs are not editable Office shapes and suggest an editable-diagram workflow |
| Mermaid CLI or a compatible local browser is unavailable | Report the missing prerequisite and stop before rendering or installing packages without approval |

## Verification checklist

- Confirm that sample fixtures and generated outputs contain no confidential paths, credentials, or non-synthetic data.
- Run the unit test suite (`python -m unittest discover -s tests -v`) to verify SVG relationship injection, PNG fallback retention, custom font propagation, ordered list numbering, diagram alt text, timeout handling, and atomic output staging.
- When `MERMAID_CLI` is configured, run the real-renderer test against `assets/example.md` and confirm that no `foreignObject` label elements remain in the embedded SVGs.
- Perform visual inspection in Word separately from automated package tests, checking label sharpness, connectors, font appearance, and pagination.
scripts/
markdown_to_word.py 25.9 KB
from __future__ import annotations

import argparse
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
import zipfile
from pathlib import Path
from typing import Any

from docx import Document
from docx.enum.style import WD_STYLE_TYPE
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
from docx.shared import Emu, Pt
from lxml import etree
from markdown_it import MarkdownIt


SVG_NAMESPACE = "http://schemas.microsoft.com/office/drawing/2016/SVG/main"
SVG_EXTENSION_URI = "{96DAC541-7B7A-43D3-8B79-37D633B846F1}"
IMAGE_RELATIONSHIP = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image"
RELATIONSHIPS_NAMESPACE = "http://schemas.openxmlformats.org/package/2006/relationships"
CONTENT_TYPES_NAMESPACE = "http://schemas.openxmlformats.org/package/2006/content-types"
WORD_NAMESPACE = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
DRAWING_NAMESPACE = "http://schemas.openxmlformats.org/drawingml/2006/main"
WORD_DRAWING_NAMESPACE = "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"
RELATIONSHIP_ATTRIBUTE = "{http://schemas.openxmlformats.org/officeDocument/2006/relationships}embed"
SVG_CONFIG = {
    "theme": "default",
    "htmlLabels": False,
    "themeVariables": {"fontFamily": "Noto Sans JP, sans-serif"},
    "flowchart": {"htmlLabels": False},
}
PNG_FALLBACK = (
    b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01"
    b"\x08\x06\x00\x00\x00\x1f\x15\xc4\x89\x00\x00\x00\x0bIDAT"
    b"x\x9cc\x00\x02\x00\x00\x05\x00\x01\xa5\xf6E\x8c\x00\x00\x00\x00IEND\xaeB`\x82"
)


def _resolve_cli(cli_name: str) -> str:
    resolved = shutil.which(cli_name)
    if resolved:
        return resolved
    candidate = Path(cli_name)
    if candidate.is_file():
        return str(candidate.resolve())
    raise FileNotFoundError(
        f"Mermaid CLI '{cli_name}' was not found. Install @mermaid-js/mermaid-cli or pass --mermaid-cli."
    )


def _command_prefix(cli: str) -> list[str]:
    cli_path = Path(cli)
    if os.name != "nt" or cli_path.suffix.lower() not in {".cmd", ".bat"}:
        return [cli]
    node = shutil.which("node")
    if node is None:
        raise FileNotFoundError("Node.js is required to invoke Mermaid CLI without a shell on Windows.")
    for directory in cli_path.resolve().parents:
        candidates = (
            directory / "@mermaid-js/mermaid-cli/src/cli.js",
            directory / "node_modules/@mermaid-js/mermaid-cli/src/cli.js",
        )
        entry_point = next((candidate for candidate in candidates if candidate.is_file()), None)
        if entry_point is not None:
            return [node, str(entry_point)]
    raise FileNotFoundError(
        "Could not locate the Mermaid CLI JavaScript entry point beside the Windows command shim."
    )


def _puppeteer_config(directory: Path) -> list[str]:
    browser = os.environ.get("MERMAID_BROWSER_PATH")
    candidates = [Path(browser)] if browser else []
    if os.name == "nt":
        candidates.extend(
            [
                Path(os.environ.get("PROGRAMFILES", "C:/Program Files"))
                / "Google/Chrome/Application/chrome.exe",
                Path(os.environ.get("PROGRAMFILES(X86)", "C:/Program Files (x86)"))
                / "Microsoft/Edge/Application/msedge.exe",
            ]
        )
    browser_path = next((path.resolve() for path in candidates if path.is_file()), None)
    if browser_path is None:
        return []
    config_path = directory / "puppeteer-config.json"
    config_path.write_text(json.dumps({"executablePath": str(browser_path)}), encoding="utf-8")
    return ["-p", str(config_path)]


def _run_command(command: list[str], *, timeout: float = 120.0) -> None:
    try:
        result = subprocess.run(
            command,
            capture_output=True,
            text=True,
            encoding="utf-8",
            errors="replace",
            timeout=timeout,
        )
    except subprocess.TimeoutExpired as error:
        raise RuntimeError(f"Mermaid rendering timed out after {timeout:g}s.") from error
    if result.returncode:
        details = result.stderr.strip() or result.stdout.strip()
        raise RuntimeError(f"Mermaid rendering failed (exit {result.returncode}): {details}")


def _render_mermaid(
    code: str, diagram_number: int, temp_root: Path, cli: str,
    font_family: str = "Noto Sans JP",
    *,
    timeout: float = 120.0,
) -> tuple[Path, Path, float, float]:
    diagram_dir = temp_root / f"diagram-{diagram_number}"
    diagram_dir.mkdir()
    source_path = diagram_dir / "diagram.mmd"
    config_path = diagram_dir / "mermaid-config.json"
    svg_path = diagram_dir / "diagram.svg"
    png_path = diagram_dir / "diagram.png"
    source_path.write_text(code.rstrip() + "\n", encoding="utf-8")
    config = {**SVG_CONFIG, "themeVariables": {"fontFamily": f"{font_family}, sans-serif"}}
    config_path.write_text(json.dumps(config, ensure_ascii=False), encoding="utf-8")

    command_prefix = _command_prefix(cli)
    common = ["-i", str(source_path), "-c", str(config_path), *_puppeteer_config(diagram_dir)]
    _run_command([*command_prefix, *common, "-o", str(svg_path), "-e", "svg"], timeout=timeout)
    _run_command([*command_prefix, *common, "-o", str(png_path), "-e", "png", "-s", "3"], timeout=timeout)

    if not svg_path.is_file() or not png_path.is_file():
        raise RuntimeError("Mermaid CLI completed without producing both SVG and PNG outputs.")
    width, height = _validate_svg(svg_path)
    return svg_path, png_path, width, height


def _svg_length(value: str | None) -> float | None:
    if not value:
        return None
    match = re.fullmatch(r"\s*([0-9]*\.?[0-9]+)(?:px)?\s*", value)
    return float(match.group(1)) if match else None


def _validate_svg(svg_path: Path) -> tuple[float, float]:
    parser = etree.XMLParser(resolve_entities=False, no_network=True, recover=False)
    try:
        root = etree.parse(str(svg_path), parser).getroot()
    except etree.XMLSyntaxError as error:
        raise RuntimeError(f"Mermaid CLI produced invalid SVG: {error}") from error

    if etree.QName(root).localname != "svg":
        raise RuntimeError("Mermaid CLI output does not have an SVG root element.")

    view_box = root.get("viewBox")
    if view_box:
        values = [float(value) for value in re.split(r"[ ,]+", view_box.strip())]
        if len(values) == 4 and values[2] > 0 and values[3] > 0:
            return values[2], values[3]

    width = _svg_length(root.get("width"))
    height = _svg_length(root.get("height"))
    if width and height:
        return width, height
    raise RuntimeError("Mermaid SVG has no usable viewBox or width/height dimensions.")


def _add_inline_content(paragraph: Any, tokens: list[Any], *, header: bool = False) -> None:
    emphasis: list[str] = []
    link_stack: list[str] = []
    for token in tokens:
        if token.type in {"strong_open", "em_open", "s_open"}:
            emphasis.append(token.type.removesuffix("_open"))
        elif token.type in {"strong_close", "em_close", "s_close"}:
            if emphasis:
                emphasis.pop()
        elif token.type == "link_open":
            link_stack.append(token.attrGet("href") or "")
        elif token.type == "link_close":
            href = link_stack.pop() if link_stack else ""
            if href:
                paragraph.add_run(f" ({href})")
        elif token.type in {"text", "code_inline", "html_inline"}:
            text = token.content
            if token.type == "html_inline":
                text = re.sub(r"<[^>]*>", "", text)
            run = paragraph.add_run(text)
            run.bold = header or "strong" in emphasis
            run.italic = "em" in emphasis
            run.font.strike = "s" in emphasis
            if token.type == "code_inline":
                run.font.name = "Consolas"
                run.font.size = Pt(9)
        elif token.type in {"softbreak", "hardbreak"}:
            paragraph.add_run().add_break()
        elif token.type == "image":
            paragraph.add_run(token.content or "[image]")
            source = token.attrGet("src")
            if source:
                paragraph.add_run(f" ({source})")


def _new_paragraph(document: Any, list_stack: list[dict[str, Any]], quote_depth: int) -> Any:
    if quote_depth:
        return document.add_paragraph(style="Quote")
    if list_stack:
        depth = min(len(list_stack), 3)
        suffix = f" {depth}" if depth > 1 else ""
        current_list = list_stack[-1]
        if current_list.get("item_continuation", False):
            return document.add_paragraph(style=f"List Continue{suffix}")
        current_list["item_continuation"] = True
        if current_list["ordered"]:
            paragraph = document.add_paragraph(style=f"List Continue{suffix}")
            run = paragraph.add_run(f"{current_list['next_number']}. ")
            run.bold = False
            current_list["next_number"] += 1
            return paragraph
        return document.add_paragraph(style=f"List Bullet{suffix}")
    return document.add_paragraph()


def _diagram_description(code: str, diagram_number: int, current_heading: str | None) -> tuple[str, str]:
    acc_title = re.search(r"(?m)^\s*accTitle\s*:\s*(.+?)\s*$", code)
    acc_descr = re.search(r"(?m)^\s*accDescr\s*:\s*(.+?)\s*$", code)
    first_statement = next(
        (
            line.strip()
            for line in code.splitlines()
            if line.strip() and not line.strip().startswith("%%")
        ),
        "diagram",
    )
    diagram_kind = first_statement.split()[0]
    title = (
        acc_title.group(1)
        if acc_title
        else f"{current_heading} — Mermaid diagram {diagram_number}"
        if current_heading
        else f"Mermaid diagram {diagram_number}"
    )
    if acc_descr:
        description = f"{title}: {acc_descr.group(1)} ({diagram_kind}; vector SVG)."
    else:
        description = f"{title} ({diagram_kind}; vector SVG)."
    return title, description


def _add_code_block(document: Any, content: str) -> None:
    paragraph = document.add_paragraph(style="No Spacing")
    paragraph.paragraph_format.keep_together = True
    run = paragraph.add_run(content.rstrip("\n"))
    run.font.name = "Consolas"
    run.font.size = Pt(9)


def _add_diagram(
    document: Any,
    svg_path: Path,
    png_path: Path,
    diagram_number: int,
    svg_width: float,
    svg_height: float,
    *,
    code: str = "",
    current_heading: str | None = None,
) -> None:
    section = document.sections[-1]
    available_width = section.page_width - section.left_margin - section.right_margin
    available_height = section.page_height - section.top_margin - section.bottom_margin
    width = float(available_width)
    height = width * svg_height / svg_width
    if height >= available_height * 0.70:
        scale = min(1.0, float(available_height) / height)
        width *= scale
        height *= scale
    if height >= available_height * 0.70:
        print(
            f"Warning: Mermaid diagram {diagram_number} uses most of a page; verify label readability in Word.",
            file=sys.stderr,
        )

    paragraph = document.add_paragraph()
    paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
    paragraph.paragraph_format.keep_together = True
    if height >= available_height * 0.70:
        paragraph.paragraph_format.page_break_before = True
    run = paragraph.add_run()
    picture = run.add_picture(str(png_path), width=Emu(round(width)), height=Emu(round(height)))
    title, description = _diagram_description(code, diagram_number, current_heading)
    picture._inline.docPr.set("name", f"mermaid-svg-{diagram_number}")
    picture._inline.docPr.set("title", title)
    picture._inline.docPr.set("descr", description)


def _render_table(document: Any, tokens: list[Any], start: int) -> int:
    rows: list[tuple[list[Any], bool]] = []
    current_cells: list[Any] | None = None
    in_header = False
    index = start + 1
    while index < len(tokens) and tokens[index].type != "table_close":
        token = tokens[index]
        if token.type == "thead_open":
            in_header = True
        elif token.type == "tbody_open":
            in_header = False
        elif token.type == "tr_open":
            current_cells = []
        elif token.type == "inline" and current_cells is not None:
            current_cells.append(token)
        elif token.type == "tr_close" and current_cells is not None:
            rows.append((current_cells, in_header))
            current_cells = None
        index += 1

    column_count = max((len(cells) for cells, _ in rows), default=0)
    if column_count:
        table = document.add_table(rows=len(rows), cols=column_count)
        try:
            table.style = "Table Grid"
        except KeyError:
            pass
        for row_index, (cells, is_header) in enumerate(rows):
            for column_index, inline_token in enumerate(cells):
                cell = table.cell(row_index, column_index)
                _add_inline_content(cell.paragraphs[0], inline_token.children or [], header=is_header)
    return index + 1


def _convert_blocks(
    document: Any, markdown_text: str, temp_root: Path, cli_name: str,
    font_family: str = "Noto Sans JP",
    *,
    timeout: float = 120.0,
) -> int:
    parser = MarkdownIt("commonmark").enable("table")
    tokens = parser.parse(markdown_text)
    list_stack: list[dict[str, Any]] = []
    quote_depth = 0
    current_paragraph = None
    in_heading = False
    current_heading: str | None = None
    diagram_number = 0
    cli: str | None = None
    index = 0

    while index < len(tokens):
        token = tokens[index]
        token_type = token.type

        if token_type == "table_open":
            index = _render_table(document, tokens, index)
            current_paragraph = None
            continue
        if token_type in {"bullet_list_open", "ordered_list_open"}:
            start_attr = token.attrGet("start") if token_type == "ordered_list_open" else None
            start_number = int(start_attr) if start_attr and str(start_attr).isdigit() else 1
            list_stack.append(
                {
                    "ordered": token_type == "ordered_list_open",
                    "next_number": start_number,
                    "item_continuation": False,
                }
            )
        elif token_type == "list_item_open":
            if list_stack:
                list_stack[-1]["item_continuation"] = False
        elif token_type == "list_item_close":
            if list_stack:
                list_stack[-1]["item_continuation"] = False
        elif token_type in {"bullet_list_close", "ordered_list_close"}:
            if list_stack:
                list_stack.pop()
        elif token_type == "blockquote_open":
            quote_depth += 1
        elif token_type == "blockquote_close":
            quote_depth = max(0, quote_depth - 1)
        elif token_type == "paragraph_open":
            current_paragraph = _new_paragraph(document, list_stack, quote_depth)
        elif token_type == "heading_open":
            level = int(token.tag[1])
            current_paragraph = document.add_paragraph(style=f"Heading {level}")
            current_paragraph.paragraph_format.keep_with_next = True
            in_heading = True
        elif token_type == "inline":
            if current_paragraph is None:
                current_paragraph = _new_paragraph(document, list_stack, quote_depth)
            _add_inline_content(current_paragraph, token.children or [])
            if in_heading and token.content.strip():
                current_heading = token.content.strip()
        elif token_type == "paragraph_close":
            current_paragraph = None
        elif token_type == "heading_close":
            current_paragraph = None
            in_heading = False
        elif token_type == "fence":
            if token.info.strip().split(maxsplit=1)[0:1] == ["mermaid"]:
                diagram_number += 1
                if cli is None:
                    cli = _resolve_cli(cli_name)
                svg_path, png_path, svg_width, svg_height = _render_mermaid(
                    token.content, diagram_number, temp_root, cli, font_family, timeout=timeout
                )
                _add_diagram(
                    document,
                    svg_path,
                    png_path,
                    diagram_number,
                    svg_width,
                    svg_height,
                    code=token.content,
                    current_heading=current_heading,
                )
            else:
                _add_code_block(document, token.content)
            current_paragraph = None
        elif token_type == "code_block":
            _add_code_block(document, token.content)
            current_paragraph = None
        elif token_type == "html_block":
            plain_text = re.sub(r"<[^>]*>", "", token.content).strip()
            if plain_text:
                document.add_paragraph(plain_text)
            current_paragraph = None
        elif token_type == "hr":
            document.add_paragraph()
            current_paragraph = None
        index += 1

    return diagram_number


def _svg_relationship_id(rels_root: Any) -> str:
    numbers = [
        int(match.group(1))
        for relationship in rels_root.findall(f"{{{RELATIONSHIPS_NAMESPACE}}}Relationship")
        if (match := re.fullmatch(r"rId([0-9]+)", relationship.get("Id", "")))
    ]
    return f"rId{max(numbers, default=0) + 1}"


def _inject_svg_parts(
    docx_path: Path, svg_paths: list[Path], *, temp_root: Path | None = None
) -> None:
    if not svg_paths:
        return

    ns = {
        "a": DRAWING_NAMESPACE,
        "asvg": SVG_NAMESPACE,
        "wp": WORD_DRAWING_NAMESPACE,
    }
    temporary_docx = (
        temp_root / "injected-output.docx"
        if temp_root is not None
        else docx_path.with_name(f"{docx_path.stem}.tmp{docx_path.suffix}")
    )
    with zipfile.ZipFile(docx_path, "r") as source, zipfile.ZipFile(
        temporary_docx, "w", compression=zipfile.ZIP_DEFLATED
    ) as target:
        document_xml = etree.fromstring(source.read("word/document.xml"))
        relationships_xml = etree.fromstring(source.read("word/_rels/document.xml.rels"))
        content_types_xml = etree.fromstring(source.read("[Content_Types].xml"))
        svg_default = content_types_xml.find(f"{{{CONTENT_TYPES_NAMESPACE}}}Default[@Extension='svg']")
        if svg_default is None:
            svg_default = etree.SubElement(content_types_xml, f"{{{CONTENT_TYPES_NAMESPACE}}}Default")
            svg_default.set("Extension", "svg")
            svg_default.set("ContentType", "image/svg+xml")

        replacements = {
            "word/document.xml": None,
            "word/_rels/document.xml.rels": None,
            "[Content_Types].xml": None,
        }
        for number, svg_path in enumerate(svg_paths, start=1):
            marker = f"mermaid-svg-{number}"
            inline = document_xml.xpath(
                f".//wp:inline[wp:docPr[@name='{marker}']]", namespaces=ns
            )
            if len(inline) != 1:
                raise RuntimeError(f"Could not locate the Word drawing for Mermaid diagram {number}.")
            blip = inline[0].find(".//a:blip", namespaces=ns)
            if blip is None:
                raise RuntimeError(f"Word drawing for Mermaid diagram {number} has no image reference.")

            relationship_id = _svg_relationship_id(relationships_xml)
            relationship = etree.SubElement(
                relationships_xml, f"{{{RELATIONSHIPS_NAMESPACE}}}Relationship"
            )
            relationship.set("Id", relationship_id)
            relationship.set("Type", IMAGE_RELATIONSHIP)
            relationship.set("Target", f"media/mermaid-{number}.svg")

            extension_list = blip.find("a:extLst", namespaces=ns)
            if extension_list is None:
                extension_list = etree.SubElement(blip, f"{{{DRAWING_NAMESPACE}}}extLst")
            extension = etree.SubElement(extension_list, f"{{{DRAWING_NAMESPACE}}}ext")
            extension.set("uri", SVG_EXTENSION_URI)
            svg_blip = etree.SubElement(extension, f"{{{SVG_NAMESPACE}}}svgBlip")
            svg_blip.set(RELATIONSHIP_ATTRIBUTE, relationship_id)
            replacements[f"word/media/mermaid-{number}.svg"] = svg_path.read_bytes()

        replacements["word/document.xml"] = etree.tostring(
            document_xml, xml_declaration=True, encoding="UTF-8", standalone=True
        )
        replacements["word/_rels/document.xml.rels"] = etree.tostring(
            relationships_xml, xml_declaration=True, encoding="UTF-8", standalone=True
        )
        replacements["[Content_Types].xml"] = etree.tostring(
            content_types_xml, xml_declaration=True, encoding="UTF-8", standalone=True
        )

        for item in source.infolist():
            if item.filename not in replacements:
                target.writestr(item, source.read(item.filename))
        for name, data in replacements.items():
            if data is not None:
                target.writestr(name, data)
    temporary_docx.replace(docx_path)


def _extract_frontmatter(markdown_text: str) -> tuple[str | None, str]:
    lines = markdown_text.splitlines()
    if not lines or lines[0].strip() != "---":
        return None, markdown_text
    closing_index = next(
        (index for index in range(1, len(lines)) if lines[index].strip() in {"---", "..."}),
        None,
    )
    if closing_index is None:
        return None, markdown_text

    metadata_lines = lines[1:closing_index]
    first_metadata_line = next((line.strip() for line in metadata_lines if line.strip()), "")
    if not re.match(r"^[A-Za-z_][A-Za-z0-9_-]*\s*:", first_metadata_line):
        return None, markdown_text

    frontmatter = "\n".join(metadata_lines)
    title_match = re.search(r"(?m)^title:\s*(.*?)\s*$", frontmatter)
    title = title_match.group(1).strip("\"'") if title_match else None
    body = "\n".join(lines[closing_index + 1 :])
    if body:
        body += "\n"
    return title or None, body


def convert_markdown(
    input_path: Path, output_path: Path, cli_name: str,
    *, font_family: str = "Noto Sans JP", timeout: float = 120.0,
) -> None:
    input_path = input_path.resolve()
    output_path = output_path.resolve()
    if input_path == output_path:
        raise ValueError("Input Markdown and output DOCX paths must be different.")
    if input_path.suffix.lower() not in {".md", ".markdown"}:
        raise ValueError("Input file must use the .md or .markdown extension.")
    if output_path.suffix.lower() != ".docx":
        raise ValueError("Output file must use the .docx extension.")
    if output_path.exists():
        raise FileExistsError(f"Output file already exists; refusing to overwrite it: {output_path}")
    font_family = font_family.strip()
    if not font_family:
        raise ValueError("Font family must not be empty.")
    if timeout <= 0:
        raise ValueError("Timeout must be greater than zero.")

    title, markdown_text = _extract_frontmatter(input_path.read_text(encoding="utf-8-sig"))
    document = Document()
    for style in document.styles:
        if style.type == WD_STYLE_TYPE.PARAGRAPH:
            style.font.name = font_family
            style.element.get_or_add_rPr().rFonts.set(qn("w:eastAsia"), font_family)
    document.core_properties.title = title or input_path.stem
    first_heading = re.search(r"(?m)^#\s+(.+?)\s*$", markdown_text)
    if title and (first_heading is None or first_heading.group(1) != title):
        document.add_heading(title, level=0)
    output_path.parent.mkdir(parents=True, exist_ok=True)

    with tempfile.TemporaryDirectory(
        prefix=".markdown-to-word-mermaid-", dir=output_path.parent
    ) as temporary_directory:
        temp_root = Path(temporary_directory)
        staged_docx = temp_root / "staged-output.docx"
        diagram_count = _convert_blocks(
            document, markdown_text, temp_root, cli_name, font_family, timeout=timeout
        )
        document.save(staged_docx)
        svg_paths = [temp_root / f"diagram-{number}" / "diagram.svg" for number in range(1, diagram_count + 1)]
        _inject_svg_parts(staged_docx, svg_paths, temp_root=temp_root)
        _publish_docx_exclusively(staged_docx, output_path)


def _publish_docx_exclusively(staged_docx: Path, output_path: Path) -> None:
    try:
        os.link(staged_docx, output_path)
    except FileExistsError as error:
        raise FileExistsError(
            f"Output file already exists; refusing to overwrite it: {output_path}"
        ) from error
    except OSError as error:
        if os.name != "nt":
            raise OSError(
                f"Cannot publish DOCX atomically because hard links are unavailable: {output_path}"
            ) from error
        try:
            os.rename(staged_docx, output_path)
        except FileExistsError as conflict:
            raise FileExistsError(
                f"Output file already exists; refusing to overwrite it: {output_path}"
            ) from conflict
    else:
        staged_docx.unlink(missing_ok=True)


def main() -> int:
    parser = argparse.ArgumentParser(
        description="Convert Markdown to DOCX and embed Mermaid diagrams as SVG vectors."
    )
    parser.add_argument("input", type=Path, help="Input Markdown file")
    parser.add_argument("--output", type=Path, help="Output DOCX path")
    parser.add_argument("--mermaid-cli", default="mmdc", help="Mermaid CLI executable (default: mmdc)")
    parser.add_argument("--font-family", default="Noto Sans JP", help="Installed font for text and diagrams (default: Noto Sans JP)")
    parser.add_argument("--timeout", type=float, default=120.0, help="Per-command Mermaid CLI timeout in seconds (default: 120)")
    args = parser.parse_args()
    output_path = args.output or args.input.with_suffix(".docx")

    try:
        convert_markdown(
            args.input,
            output_path,
            args.mermaid_cli,
            font_family=args.font_family,
            timeout=args.timeout,
        )
    except (FileNotFoundError, OSError, RuntimeError, ValueError) as error:
        print(f"Error: {error}", file=sys.stderr)
        return 1
    print(output_path.resolve())
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
requirements.txt 0.1 KB
markdown-it-py>=3.0.0,<5.0.0
python-docx>=1.1.2,<2.0.0
lxml>=5.0.0,<7.0.0
tests/
test_markdown_to_word.py 25.5 KB
from __future__ import annotations

import os
import re
import tempfile
import unittest
from pathlib import Path
import sys
import struct
import zlib
import json
import subprocess
from unittest.mock import patch
from zipfile import ZipFile

from lxml import etree

sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts"))

import markdown_to_word
from markdown_to_word import convert_markdown


PNG_DATA = (
    b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01"
    b"\x08\x06\x00\x00\x00\x1f\x15\xc4\x89\x00\x00\x00\x0bIDAT"
    b"x\x9cc\x00\x02\x00\x00\x05\x00\x01\xa5\xf6E\x8c\x00\x00\x00\x00IEND\xaeB`\x82"
)


def png_data() -> bytes:
    def chunk(kind: bytes, data: bytes) -> bytes:
        payload = kind + data
        return struct.pack(">I", len(data)) + payload + struct.pack(">I", zlib.crc32(payload))

    return (
        b"\x89PNG\r\n\x1a\n"
        + chunk(b"IHDR", struct.pack(">2I5B", 1, 1, 8, 6, 0, 0, 0))
        + chunk(b"IDAT", zlib.compress(b"\x00\x00\x00\x00\x00"))
        + chunk(b"IEND", b"")
    )


class MarkdownToWordTests(unittest.TestCase):
    def test_thematic_breaks_do_not_strip_document_content(self) -> None:
        markdown = (
            "---\n# Design\n\n```mermaid\nflowchart LR\nA --> B\n```\n\n"
            "---\nRemaining text\n"
        )

        title, body = markdown_to_word._extract_frontmatter(markdown)

        self.assertIsNone(title)
        self.assertEqual(body, markdown)

    def test_custom_font_and_multiple_svg_relationships(self) -> None:
        with tempfile.TemporaryDirectory() as temporary_directory:
            root = Path(temporary_directory)
            source = root / "input.md"
            output = root / "output.docx"
            source.write_text(
                "# Workflow\n\n```mermaid\nflowchart LR\nA --> B\n```\n\n"
                "```mermaid\nsequenceDiagram\nAlice->>Bob: Review\n```\n",
                encoding="utf-8",
            )
            commands: list[list[str]] = []

            def fake_command(command: list[str], **_: object) -> None:
                commands.append(command)
                config_path = Path(command[command.index("-c") + 1])
                config = json.loads(config_path.read_text(encoding="utf-8"))
                self.assertEqual(config["themeVariables"]["fontFamily"], "Aptos, sans-serif")
                self.assertFalse(config["htmlLabels"])
                self.assertFalse(config["flowchart"]["htmlLabels"])
                output_path = Path(command[command.index("-o") + 1])
                if output_path.suffix == ".svg":
                    output_path.write_text(
                        '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 100">'
                        '<text font-family="Aptos">Review</text></svg>',
                        encoding="utf-8",
                    )
                else:
                    self.assertEqual(command[command.index("-s") + 1], "3")
                    output_path.write_bytes(png_data())

            with patch("markdown_to_word._resolve_cli", return_value="mmdc"), patch(
                "markdown_to_word._run_command", side_effect=fake_command
            ):
                convert_markdown(source, output, "mmdc", font_family="Aptos")

            self.assertEqual(len(commands), 4)
            with ZipFile(output) as docx:
                document_xml = etree.fromstring(docx.read("word/document.xml"))
                relationships = etree.fromstring(docx.read("word/_rels/document.xml.rels"))
                styles = etree.fromstring(docx.read("word/styles.xml"))
                for number in (1, 2):
                    self.assertIn(f"word/media/mermaid-{number}.svg", docx.namelist())
                svg_ids = document_xml.xpath(
                    ".//asvg:svgBlip/@r:embed",
                    namespaces={
                        "asvg": "http://schemas.microsoft.com/office/drawing/2016/SVG/main",
                        "r": "http://schemas.openxmlformats.org/officeDocument/2006/relationships",
                    },
                )
                self.assertEqual(len(set(svg_ids)), 2)
                targets = [
                    relationships.xpath(
                        f"string(.//*[local-name()='Relationship' and @Id='{relationship_id}']/@Target)"
                    )
                    for relationship_id in svg_ids
                ]
                self.assertEqual(targets, ["media/mermaid-1.svg", "media/mermaid-2.svg"])
                self.assertTrue(styles.xpath(
                    ".//w:style[@w:styleId='Normal']/w:rPr/w:rFonts[@w:ascii='Aptos' and @w:eastAsia='Aptos']",
                    namespaces={"w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main"},
                ))

    def test_rejects_empty_font_before_rendering(self) -> None:
        with tempfile.TemporaryDirectory() as temporary_directory:
            root = Path(temporary_directory)
            source = root / "input.md"
            source.write_text("# Input\n", encoding="utf-8")
            with patch("markdown_to_word._render_mermaid") as renderer:
                with self.assertRaises(ValueError):
                    convert_markdown(source, root / "output.docx", "mmdc", font_family=" ")
            renderer.assert_not_called()
            self.assertFalse((root / "output.docx").exists())

    def test_rendering_failure_does_not_create_document(self) -> None:
        with tempfile.TemporaryDirectory() as temporary_directory:
            root = Path(temporary_directory)
            source = root / "input.md"
            output = root / "output.docx"
            source.write_text("```mermaid\ninvalid diagram\n```\n", encoding="utf-8")
            with patch("markdown_to_word._resolve_cli", return_value="mmdc"), patch(
                "markdown_to_word._run_command", side_effect=RuntimeError("Mermaid rendering failed")
            ):
                with self.assertRaisesRegex(RuntimeError, "Mermaid rendering failed"):
                    convert_markdown(source, output, "mmdc")
            self.assertFalse(output.exists())

    def test_embeds_svg_vectors_with_png_fallback_and_page_layout(self) -> None:
        with tempfile.TemporaryDirectory() as temporary_directory:
            root = Path(temporary_directory)
            source = root / "input.md"
            output = root / "output.docx"
            browser = root / "chrome.exe"
            browser.touch()
            source.write_text(
                "---\ntitle: Sample Document\nstatus: draft\n---\n\n"
                "# Design\n\nA table follows.\n\n| Item | Value |\n| --- | --- |\n| One | Two |\n\n"
                "```mermaid\ngraph TD\n  A[Start] --> B[End]\n```\n",
                encoding="utf-8",
            )

            def fake_renderer(command: list[str], **_: object) -> object:
                input_path = Path(command[command.index("-i") + 1])
                output_path = Path(command[command.index("-o") + 1])
                puppeteer_config = Path(command[command.index("-p") + 1])
                self.assertEqual(json.loads(puppeteer_config.read_text(encoding="utf-8"))["executablePath"], str(browser))
                if output_path.suffix == ".svg":
                    config_path = Path(command[command.index("-c") + 1])
                    config = config_path.read_text(encoding="utf-8")
                    self.assertIn("Noto Sans JP", config)
                    self.assertFalse(json.loads(config)["htmlLabels"])
                    self.assertIn("graph TD", input_path.read_text(encoding="utf-8"))
                    output_path.write_text(
                        '<svg xmlns="http://www.w3.org/2000/svg" width="400px" height="500px" '
                        'viewBox="0 0 400 500"><text>図</text></svg>',
                        encoding="utf-8",
                    )
                else:
                    output_path.write_bytes(png_data())

                class Result:
                    returncode = 0
                    stdout = ""
                    stderr = ""

                return Result()

            with patch.dict("os.environ", {"MERMAID_BROWSER_PATH": str(browser)}), patch(
                "markdown_to_word.shutil.which", return_value="mmdc"
            ), patch(
                "markdown_to_word.subprocess.run", side_effect=fake_renderer
            ):
                convert_markdown(source, output, "mmdc")

            with ZipFile(output) as docx:
                names = docx.namelist()
                self.assertIn("word/media/mermaid-1.svg", names)
                self.assertIn("word/media/image1.png", names)
                document_xml = etree.fromstring(docx.read("word/document.xml"))
                relationships_xml = etree.fromstring(docx.read("word/_rels/document.xml.rels"))
                content_types = etree.fromstring(docx.read("[Content_Types].xml"))
                core_properties = etree.fromstring(docx.read("docProps/core.xml"))

            svg_blips = document_xml.xpath(
                ".//asvg:svgBlip",
                namespaces={"asvg": "http://schemas.microsoft.com/office/drawing/2016/SVG/main"},
            )
            self.assertEqual(len(svg_blips), 1)
            svg_relationship_id = svg_blips[0].get(
                "{http://schemas.openxmlformats.org/officeDocument/2006/relationships}embed"
            )
            relationships = relationships_xml.xpath(
                f".//*[local-name()='Relationship' and @Id='{svg_relationship_id}']"
            )
            self.assertEqual(relationships[0].get("Target"), "media/mermaid-1.svg")
            self.assertTrue(
                content_types.xpath(
                    ".//*[local-name()='Default' and @Extension='svg' and @ContentType='image/svg+xml']"
                )
            )
            drawings = document_xml.xpath(".//*[local-name()='docPr' and @name='mermaid-svg-1']")
            self.assertEqual(len(drawings), 1)
            self.assertEqual(
                core_properties.xpath("string(.//*[local-name()='title'])"),
                "Sample Document",
            )
            document_text = "".join(document_xml.xpath(".//*[local-name()='t']/text()"))
            self.assertIn("Sample Document", document_text)
            page_breaks = document_xml.xpath(".//*[local-name()='pageBreakBefore']")
            self.assertEqual(len(page_breaks), 1)

    def test_fails_if_mermaid_cli_is_missing(self) -> None:
        with tempfile.TemporaryDirectory() as temporary_directory:
            root = Path(temporary_directory)
            source = root / "input.md"
            source.write_text("```mermaid\ngraph TD\n  A --> B\n```\n", encoding="utf-8")
            with patch("markdown_to_word.shutil.which", return_value=None):
                with self.assertRaises(FileNotFoundError):
                    convert_markdown(source, root / "output.docx", "mmdc")
                plain_source = root / "plain.md"
                plain_source.write_text("# No diagram\n\nPlain text.\n", encoding="utf-8")
                plain_output = root / "plain.docx"
                convert_markdown(plain_source, plain_output, "mmdc")
                self.assertTrue(plain_output.is_file())

    def test_existing_output_is_preserved_without_rendering(self) -> None:
        with tempfile.TemporaryDirectory() as temporary_directory:
            directory = Path(temporary_directory)
            input_path = directory / "input.md"
            output_path = directory / "input.docx"
            original_output = b"existing document"
            input_path.write_text("# Input\n", encoding="utf-8")
            output_path.write_bytes(original_output)

            with (
                patch.object(markdown_to_word, "Document") as document,
                patch.object(markdown_to_word, "_convert_blocks") as render,
                self.assertRaisesRegex(FileExistsError, "refusing to overwrite"),
            ):
                convert_markdown(input_path, output_path, "mmdc")

            document.assert_not_called()
            render.assert_not_called()
            self.assertEqual(output_path.read_bytes(), original_output)

    def test_injection_failure_does_not_leave_output_or_adjacent_temp_file(self) -> None:
        with tempfile.TemporaryDirectory() as temporary_directory:
            root = Path(temporary_directory)
            source = root / "input.md"
            output = root / "output.docx"
            adjacent_tmp = root / "output.tmp.docx"
            adjacent_tmp.write_bytes(b"preexisting adjacent file")
            source.write_text("```mermaid\nflowchart LR\nA --> B\n```\n", encoding="utf-8")

            def fake_command(command: list[str], **_: object) -> None:
                output_path = Path(command[command.index("-o") + 1])
                if output_path.suffix == ".svg":
                    output_path.write_text(
                        '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 100"><text>Node</text></svg>',
                        encoding="utf-8",
                    )
                else:
                    output_path.write_bytes(png_data())

            with (
                patch("markdown_to_word._resolve_cli", return_value="mmdc"),
                patch("markdown_to_word._run_command", side_effect=fake_command),
                patch("markdown_to_word._inject_svg_parts", side_effect=RuntimeError("SVG injection failed")),
                self.assertRaisesRegex(RuntimeError, "SVG injection failed"),
            ):
                convert_markdown(source, output, "mmdc")

            self.assertFalse(output.exists())
            self.assertEqual(adjacent_tmp.read_bytes(), b"preexisting adjacent file")

    def test_preserves_ordered_list_start_and_separate_list_boundaries(self) -> None:
        with tempfile.TemporaryDirectory() as temporary_directory:
            root = Path(temporary_directory)
            source = root / "lists.md"
            output = root / "lists.docx"
            source.write_text(
                "# Lists\n\n"
                "5. Fifth item\n"
                "6. Sixth item\n\n"
                "Intervening paragraph.\n\n"
                "1. Restarted first\n"
                "2. Restarted second\n",
                encoding="utf-8",
            )
            convert_markdown(source, output, "mmdc")
            with ZipFile(output) as docx:
                document_xml = etree.fromstring(docx.read("word/document.xml"))
            paragraphs = [
                "".join(paragraph.xpath(".//*[local-name()='t']/text()"))
                for paragraph in document_xml.xpath(".//*[local-name()='p']")
            ]
            self.assertIn("5. Fifth item", paragraphs)
            self.assertIn("6. Sixth item", paragraphs)
            self.assertIn("1. Restarted first", paragraphs)
            self.assertIn("2. Restarted second", paragraphs)

    def test_populates_contextual_diagram_alt_text_and_enforces_timeout(self) -> None:
        with tempfile.TemporaryDirectory() as temporary_directory:
            root = Path(temporary_directory)
            source = root / "alt.md"
            output = root / "alt.docx"
            source.write_text(
                "## Approval Flow\n\n"
                "```mermaid\n"
                "flowchart LR\n"
                "  accTitle: Release Gate\n"
                "  accDescr: Validates package before release\n"
                "  A --> B\n"
                "```\n",
                encoding="utf-8",
            )

            def fake_command(command: list[str], **_: object) -> None:
                output_path = Path(command[command.index("-o") + 1])
                if output_path.suffix == ".svg":
                    output_path.write_text(
                        '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 100"><text>Gate</text></svg>',
                        encoding="utf-8",
                    )
                else:
                    output_path.write_bytes(png_data())

            with (
                patch("markdown_to_word._resolve_cli", return_value="mmdc"),
                patch("markdown_to_word._run_command", side_effect=fake_command),
            ):
                convert_markdown(source, output, "mmdc")

            with ZipFile(output) as docx:
                document_xml = etree.fromstring(docx.read("word/document.xml"))
            doc_pr = document_xml.xpath(".//*[local-name()='docPr' and @name='mermaid-svg-1']")[0]
            self.assertEqual(doc_pr.get("title"), "Release Gate")
            self.assertIn("Validates package before release", doc_pr.get("descr", ""))
            self.assertIn("flowchart", doc_pr.get("descr", ""))

            with patch(
                "markdown_to_word.subprocess.run",
                side_effect=subprocess.TimeoutExpired(cmd=["mmdc"], timeout=5.0),
            ):
                with self.assertRaisesRegex(RuntimeError, "timed out after 5s"):
                    markdown_to_word._run_command(["mmdc"], timeout=5.0)

    @unittest.skipUnless(os.name == "nt", "Windows command-shim coverage")
    def test_windows_mermaid_cli_avoids_shell_for_ampersand_paths(self) -> None:
        with tempfile.TemporaryDirectory() as temporary_directory:
            root = Path(temporary_directory) / "R&D"
            shim = root / "node_modules" / ".bin" / "mmdc.cmd"
            entry_point = root / "node_modules" / "@mermaid-js" / "mermaid-cli" / "src" / "cli.js"
            node = root / "node.exe"
            shim.parent.mkdir(parents=True)
            entry_point.parent.mkdir(parents=True)
            shim.touch()
            entry_point.touch()
            node.touch()
            commands: list[tuple[list[str], dict[str, object]]] = []

            def fake_run(command: list[str], **kwargs: object) -> object:
                commands.append((command, kwargs))
                output_path = Path(command[command.index("-o") + 1])
                if output_path.suffix == ".svg":
                    output_path.write_text(
                        '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 50"/>',
                        encoding="utf-8",
                    )
                else:
                    output_path.write_bytes(png_data())

                class Result:
                    returncode = 0
                    stdout = ""
                    stderr = ""

                return Result()

            with patch(
                "markdown_to_word.shutil.which",
                side_effect=lambda name: str(node) if name == "node" else None,
            ), patch("markdown_to_word.subprocess.run", side_effect=fake_run):
                markdown_to_word._render_mermaid("flowchart LR\nA --> B", 1, root, str(shim))

            self.assertEqual(len(commands), 2)
            for command, kwargs in commands:
                self.assertEqual(command[:2], [str(node), str(entry_point)])
                self.assertNotIn("cmd.exe", command[0].lower())
                self.assertFalse(kwargs.get("shell", False))
                self.assertIn("R&D", command[command.index("-o") + 1])

    def test_hard_link_failure_never_exposes_a_partial_destination(self) -> None:
        with tempfile.TemporaryDirectory() as temporary_directory:
            root = Path(temporary_directory)
            staged = root / "staged.docx"
            output = root / "output.docx"
            staged.write_bytes(b"complete document")

            with patch("markdown_to_word.os.link", side_effect=OSError("hard links unavailable")):
                if os.name == "nt":
                    markdown_to_word._publish_docx_exclusively(staged, output)
                    self.assertEqual(output.read_bytes(), b"complete document")
                    self.assertFalse(staged.exists())
                    second_staged = root / "second-staged.docx"
                    second_staged.write_bytes(b"replacement document")
                    with patch(
                        "markdown_to_word.os.link",
                        side_effect=OSError("hard links unavailable"),
                    ), self.assertRaisesRegex(FileExistsError, "refusing to overwrite"):
                        markdown_to_word._publish_docx_exclusively(second_staged, output)
                    self.assertEqual(output.read_bytes(), b"complete document")
                else:
                    with self.assertRaisesRegex(OSError, "Cannot publish DOCX atomically"):
                        markdown_to_word._publish_docx_exclusively(staged, output)
                    self.assertFalse(output.exists())
                    self.assertEqual(staged.read_bytes(), b"complete document")

    def test_preserves_multi_paragraph_list_items_and_atomic_publication(self) -> None:
        with tempfile.TemporaryDirectory() as temporary_directory:
            root = Path(temporary_directory)
            source = root / "continuation-lists.md"
            output = root / "continuation-lists.docx"
            source.write_text(
                "# Multi-Paragraph Lists\n\n"
                "1. Ordered first paragraph\n\n"
                "   Ordered continuation paragraph\n\n"
                "2. Ordered second item\n\n"
                "- Bullet first paragraph\n\n"
                "  Bullet continuation paragraph\n",
                encoding="utf-8",
            )
            convert_markdown(source, output, "mmdc")
            with ZipFile(output) as docx:
                document_xml = etree.fromstring(docx.read("word/document.xml"))
            entries = [
                (
                    paragraph.xpath("string(./*[local-name()='pPr']/*[local-name()='pStyle']/@*[local-name()='val'])"),
                    "".join(paragraph.xpath(".//*[local-name()='t']/text()")),
                )
                for paragraph in document_xml.xpath(".//*[local-name()='p']")
            ]
            self.assertIn(("ListContinue", "1. Ordered first paragraph"), entries)
            self.assertIn(("ListContinue", "Ordered continuation paragraph"), entries)
            self.assertIn(("ListContinue", "2. Ordered second item"), entries)
            self.assertNotIn(("ListContinue", "3. Ordered second item"), entries)
            self.assertIn(("ListBullet", "Bullet first paragraph"), entries)
            self.assertIn(("ListContinue", "Bullet continuation paragraph"), entries)

            staged = root / "staged.docx"
            staged.write_bytes(b"new content")
            conflict_target = root / "conflict.docx"
            conflict_target.write_bytes(b"existing content")
            with self.assertRaisesRegex(FileExistsError, "refusing to overwrite"):
                markdown_to_word._publish_docx_exclusively(staged, conflict_target)
            self.assertEqual(conflict_target.read_bytes(), b"existing content")


@unittest.skipUnless(os.environ.get("MERMAID_CLI"), "set MERMAID_CLI to run real-renderer coverage")
class RealMermaidRendererTests(unittest.TestCase):
    def test_example_renders_svg_and_png_for_all_diagrams(self) -> None:
        skill_root = Path(__file__).resolve().parents[1]
        source = skill_root / "assets" / "example.md"
        source_text = source.read_text(encoding="utf-8")
        expected_diagrams = len(re.findall(r"(?m)^```mermaid\s*$", source_text))

        with tempfile.TemporaryDirectory() as temporary_directory:
            output = Path(temporary_directory) / "example.docx"
            convert_markdown(source, output, os.environ["MERMAID_CLI"])

            with ZipFile(output) as docx:
                names = docx.namelist()
                svg_names = sorted(
                    name for name in names
                    if re.fullmatch(r"word/media/mermaid-\d+\.svg", name)
                )
                png_names = [
                    name for name in names
                    if re.fullmatch(r"word/media/image\d+\.png", name)
                ]
                document_xml = etree.fromstring(docx.read("word/document.xml"))
                relationships = etree.fromstring(docx.read("word/_rels/document.xml.rels"))
                svg_relationship_ids = document_xml.xpath(
                    ".//asvg:svgBlip/@r:embed",
                    namespaces={
                        "asvg": "http://schemas.microsoft.com/office/drawing/2016/SVG/main",
                        "r": "http://schemas.openxmlformats.org/officeDocument/2006/relationships",
                    },
                )
                relationship_targets = [
                    relationships.xpath(
                        f"string(.//*[local-name()='Relationship' and @Id='{relationship_id}']/@Target)"
                    )
                    for relationship_id in svg_relationship_ids
                ]

                self.assertEqual(len(svg_names), expected_diagrams)
                self.assertEqual(len(png_names), expected_diagrams)
                self.assertEqual(len(svg_relationship_ids), expected_diagrams)
                self.assertEqual(
                    relationship_targets,
                    [f"media/mermaid-{number}.svg" for number in range(1, expected_diagrams + 1)],
                )

                svg_text = []
                for name in svg_names:
                    svg_root = etree.fromstring(docx.read(name))
                    self.assertFalse(svg_root.xpath(".//*[local-name()='foreignObject']"))
                    svg_text.append("".join(svg_root.itertext()))
                joined_svg_text = " ".join(svg_text)
                for label in ("Draft", "Publish", "入力", "差戻し"):
                    self.assertIn(label, joined_svg_text)

                dimensions = document_xml.xpath(
                    ".//wp:extent/@cx | .//wp:extent/@cy",
                    namespaces={"wp": "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"},
                )
                self.assertEqual(len(dimensions), expected_diagrams * 2)
                self.assertTrue(all(int(dimension) > 0 for dimension in dimensions))


if __name__ == "__main__":
    unittest.main()

License (MIT)

View full license text
MIT License

Copyright GitHub, Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.