from __future__ import annotations
import html
import shutil
import subprocess
import sys
import tempfile
import time
import zipfile
from dataclasses import dataclass
from pathlib import Path
from xml.sax.saxutils import escape, quoteattr
from markdown_it import MarkdownIt
from markdown_it.token import Token
from .markdown_compat import cjk_strong_plugin
from .docx_inline import source_style_name
WP_NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
DOCX_EXPORT_ENGINES = {
"pandoc": "Pandoc(推荐,保真度较高)",
"python-docx": "python-docx(纯 Python)",
"builtin": "内置基础导出",
}
class DocxExportError(RuntimeError):
pass
def resolve_pandoc_executable() -> Path | None:
"""Locate the bundled Pandoc first, with PATH as a development fallback."""
roots: list[Path] = []
bundled_root = getattr(sys, "_MEIPASS", None)
if bundled_root:
roots.append(Path(bundled_root))
roots.append(Path(__file__).resolve().parent.parent)
executable_name = "pandoc.exe" if sys.platform == "win32" else "pandoc"
for root in roots:
candidate = root / "vendor" / "pandoc" / executable_name
if candidate.is_file():
return candidate
path_executable = shutil.which("pandoc")
return Path(path_executable) if path_executable else None
def export_markdown_to_docx(
source: str,
output_path: Path,
engine: str = "builtin",
source_path: Path | None = None,
style_rules: dict | None = None,
document_font_family: str = "",
document_font_size: float = 16,
preset: str = "default",
page_settings: object = None,
cancel: object = None,
progress: object = None,
) -> Path:
from .docx_style import apply_docx_styles
from .export_jobs import check_cancelled
from .file_versions import atomic_write
if output_path.suffix.lower() != ".docx":
output_path = output_path.with_suffix(".docx")
check_cancelled(cancel)
if progress:
progress("正在转换 Word 内容…")
with tempfile.TemporaryDirectory(prefix="mdhelper-export-") as directory:
target = Path(directory) / "document.docx"
if engine == "pandoc":
result = export_markdown_to_docx_pandoc(source, target, source_path=source_path, cancel=cancel, semantic_styles=True)
elif engine == "python-docx":
result = export_markdown_to_docx_python_docx(source, target)
else:
result = export_markdown_to_docx_builtin(source, target)
check_cancelled(cancel)
if progress:
progress("正在应用字体、段落和页面设置…")
apply_docx_styles(result, style_rules, font_family=document_font_family,
font_size_px=document_font_size, preset=preset)
if page_settings is not None:
from .export_settings import apply_docx_page_settings
apply_docx_page_settings(result, page_settings)
check_cancelled(cancel)
data = result.read_bytes()
check_cancelled(cancel)
atomic_write(output_path, data)
return output_path
def export_markdown_to_docx_builtin(source: str, output_path: Path) -> Path:
if output_path.suffix.lower() != ".docx":
output_path = output_path.with_suffix(".docx")
blocks = _markdown_blocks(source)
links, source_styles = {}, set()
for block in blocks:
groups = [block.runs] if isinstance(block, ParagraphBlock) else [runs for row in block.rows for runs in row]
for runs in groups:
for _, style in runs:
name = source_style_name(style.get('semantic_order', ()))
if name: source_styles.add(name)
if style.get('href'):
style['link_id'] = links.setdefault(style['href'], f'rIdLink{len(links) + 1}')
document_xml = _document_xml(blocks)
has_lists = any(isinstance(b, ParagraphBlock) and b.list_kind for b in blocks)
output_path.parent.mkdir(parents=True, exist_ok=True)
with zipfile.ZipFile(output_path, "w", compression=zipfile.ZIP_DEFLATED) as package:
content_types = CONTENT_TYPES_XML
if has_lists:
content_types = content_types.replace('', '')
package.writestr('word/numbering.xml', _numbering_xml(blocks))
package.writestr("[Content_Types].xml", content_types)
package.writestr("_rels/.rels", PACKAGE_RELS_XML)
package.writestr("word/document.xml", document_xml)
markers = ''.join(f'' for name in sorted(source_styles))
package.writestr("word/styles.xml", STYLES_XML.replace('', markers + ''))
package.writestr("word/settings.xml", SETTINGS_XML)
relations = ''.join(f'' for href, identifier in links.items())
if has_lists: relations += ''
package.writestr("word/_rels/document.xml.rels", DOCUMENT_RELS_XML.replace('', relations + ''))
return output_path
def export_markdown_to_docx_pandoc(source: str, output_path: Path, source_path: Path | None = None, cancel: object = None, semantic_styles: bool = False) -> Path:
output_path = output_path.resolve()
if output_path.suffix.lower() != ".docx":
output_path = output_path.with_suffix(".docx")
output_path.parent.mkdir(parents=True, exist_ok=True)
pandoc_path = resolve_pandoc_executable()
if pandoc_path is None:
raise DocxExportError("未找到程序内置的 Pandoc,当前 MDHelper 安装包可能不完整,请重新获取完整版本。")
# Export the current editor text, including unsaved edits. Retain the source
# directory only for resolving linked images and other local resources.
with tempfile.NamedTemporaryFile("w", suffix=".md", encoding="utf-8", delete=False) as handle:
handle.write(source)
temporary_path = Path(handle.name)
input_path = temporary_path
resource_directory = source_path.resolve().parent if source_path is not None else input_path.parent
command = [str(pandoc_path), str(input_path), "-o", str(output_path), "--standalone"]
if semantic_styles:
command.append('--lua-filter=' + str(Path(__file__).with_name('resources') / 'word_inline_styles.lua'))
run_options: dict[str, object] = {}
if sys.platform == "win32":
run_options["creationflags"] = subprocess.CREATE_NO_WINDOW
try:
from .export_jobs import check_cancelled
process = subprocess.Popen(
command,
cwd=str(resource_directory),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
encoding="utf-8", errors="replace",
**run_options,
)
started = time.monotonic()
try:
while True:
check_cancelled(cancel)
if time.monotonic() - started > 120:
raise subprocess.TimeoutExpired(command, 120)
try:
stdout, stderr = process.communicate(timeout=0.1)
break
except subprocess.TimeoutExpired:
continue
finally:
if process.poll() is None:
process.kill()
process.communicate()
except FileNotFoundError as exc:
raise DocxExportError("程序内置的 Pandoc 无法启动,当前 MDHelper 安装包可能不完整。") from exc
except subprocess.TimeoutExpired as exc:
raise DocxExportError("pandoc 导出超时。") from exc
finally:
if temporary_path is not None:
try:
temporary_path.unlink(missing_ok=True)
except OSError:
pass
if process.returncode != 0:
detail = (stderr or stdout or "pandoc 返回错误。").strip()
raise DocxExportError(detail)
return output_path
def export_markdown_to_docx_python_docx(source: str, output_path: Path) -> Path:
if output_path.suffix.lower() != ".docx":
output_path = output_path.with_suffix(".docx")
try:
from docx import Document
from docx.oxml.ns import qn
from docx.shared import Pt
from docx.enum.style import WD_STYLE_TYPE
except ImportError as exc:
raise DocxExportError("未找到 python-docx,请先安装 python-docx。") from exc
document = Document()
normal = document.styles["Normal"]
normal.font.name = "Microsoft YaHei"
normal.font.size = Pt(11)
normal.element.rPr.rFonts.set(qn("w:eastAsia"), "Microsoft YaHei")
document.styles.add_style("MDHelper Code Char", WD_STYLE_TYPE.CHARACTER)
blocks = _markdown_blocks(source)
from docx.oxml import parse_xml
for numbering in parse_xml(_numbering_xml(blocks)):
document.part.numbering_part.element.append(numbering)
for block in blocks:
if isinstance(block, TableBlock):
_add_python_docx_table(document, block)
continue
_add_python_docx_paragraph(document, block)
output_path.parent.mkdir(parents=True, exist_ok=True)
document.save(str(output_path))
return output_path
def _markdown_blocks(source: str) -> list[ParagraphBlock | TableBlock]:
markdown = MarkdownIt("commonmark", {"html": True}).enable(["table", "strikethrough"]).use(cjk_strong_plugin)
return _DocxBuilder(markdown.parse(source)).build()
def _add_python_docx_paragraph(document: object, block: ParagraphBlock) -> None:
style = f"Heading {block.style.removeprefix('Heading')}" if block.style.startswith("Heading") else None
if block.list_kind == "bullet":
style = "List Bullet"
elif block.list_kind == "number":
style = "List Number"
elif block.style == "Code":
from docx.enum.style import WD_STYLE_TYPE
if "MDHelper Code" not in document.styles:
document.styles.add_style("MDHelper Code", WD_STYLE_TYPE.PARAGRAPH)
style = "MDHelper Code"
elif block.quote_depth:
style = "Quote"
paragraph = document.add_paragraph(style=style)
if block.list_kind:
from docx.oxml import parse_xml
paragraph._p.get_or_add_pPr().append(parse_xml(f''))
if block.quote_depth:
paragraph.paragraph_format.left_indent = _docx_inches(0.35)
for text, run_style in block.runs:
parts = text.split("\n")
for part_index, part in enumerate(parts):
if part_index:
paragraph.add_run().add_break()
_add_python_docx_run(paragraph, part, run_style)
def _add_python_docx_run(paragraph, text, style):
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
from docx.opc.constants import RELATIONSHIP_TYPE as RT
run = paragraph.add_run(text)
if style.get('bold'): run.bold = True
if style.get('italic'): run.italic = True
if style.get('strike'): run.font.strike = True
if style.get('code'):
run.style = 'MDHelper Code Char'
run.font.name = 'Consolas'
marker = source_style_name(style.get('semantic_order', ()))
if marker:
from docx.enum.style import WD_STYLE_TYPE
styles = paragraph.part.document.styles
if marker not in styles: styles.add_style(marker, WD_STYLE_TYPE.CHARACTER)
run.style = marker
if style.get('href'):
link = OxmlElement('w:hyperlink')
link.set(qn('r:id'), paragraph.part.relate_to(style['href'], RT.HYPERLINK, is_external=True))
run._r.addprevious(link)
link.append(run._r)
def _add_python_docx_table(document: object, block: TableBlock) -> None:
if not block.rows:
return
column_count = max(len(row) for row in block.rows)
table = document.add_table(rows=len(block.rows), cols=column_count)
table.style = "Table Grid"
for row_index, row in enumerate(block.rows):
for col_index in range(column_count):
cell = table.cell(row_index, col_index)
runs = row[col_index] if col_index < len(row) else [("", {})]
paragraph = cell.paragraphs[0]
for text, run_style in runs:
_add_python_docx_run(paragraph, text, run_style)
def _docx_pt(value: int) -> object:
from docx.shared import Pt
return Pt(value)
def _docx_inches(value: float) -> object:
from docx.shared import Inches
return Inches(value)
@dataclass
class ParagraphBlock:
runs: list[tuple[str, dict[str, object]]]
style: str = "Normal"
list_kind: str = ""
quote_depth: int = 0
list_level: int = 0
list_id: int = 0
list_start: int = 1
@dataclass
class TableBlock:
rows: list[list[list[tuple[str, dict[str, bool]]]]]
class _DocxBuilder:
def __init__(self, tokens: list[Token]) -> None:
self.tokens = tokens
self.blocks: list[ParagraphBlock | TableBlock] = []
self.index = 0
self.list_stack: list[str] = []
self.list_ids: list[int] = []
self.list_starts: list[int] = []
self.list_sequence = 1000
self.quote_depth = 0
def build(self) -> list[ParagraphBlock | TableBlock]:
while self.index < len(self.tokens):
token = self.tokens[self.index]
if token.type == "heading_open":
level = min(max(int(token.tag[1:]), 1), 6) if token.tag.startswith("h") else 1
self._add_next_inline(f"Heading{level}")
continue
if token.type == "paragraph_open":
style = "Quote" if self.quote_depth else "Normal"
self._add_next_inline(style, list_kind=self.list_stack[-1] if self.list_stack else "")
continue
if token.type in {"fence", "code_block"}:
for line in token.content.rstrip("\n").splitlines() or [""]:
self.blocks.append(ParagraphBlock([(line, {"code": True})], style="Code"))
elif token.type == "blockquote_open":
self.quote_depth += 1
elif token.type == "blockquote_close":
self.quote_depth = max(0, self.quote_depth - 1)
elif token.type in ('bullet_list_open', 'ordered_list_open'):
self.list_stack.append('bullet' if token.type == 'bullet_list_open' else 'number')
self.list_sequence += 1
self.list_ids.append(self.list_sequence)
self.list_starts.append(int(token.attrGet('start') or 1))
elif token.type in {"bullet_list_close", "ordered_list_close"} and self.list_stack:
self.list_stack.pop()
self.list_ids.pop()
self.list_starts.pop()
elif token.type == "table_open":
self.blocks.append(self._collect_table())
continue
elif token.type == "hr":
self.blocks.append(ParagraphBlock([("_" * 30, {})]))
self.index += 1
return self.blocks
def _add_next_inline(self, style: str, list_kind: str = "") -> None:
inline = self.tokens[self.index + 1] if self.index + 1 < len(self.tokens) else None
runs = _inline_runs(inline.children if inline is not None else None)
self.blocks.append(ParagraphBlock(runs, style=style, list_kind=list_kind, quote_depth=self.quote_depth,
list_level=min(8, max(0, len(self.list_stack) - 1)), list_id=self.list_ids[-1] if self.list_ids else 0,
list_start=self.list_starts[-1] if self.list_starts else 1))
self.index += 3
def _collect_table(self) -> TableBlock:
rows: list[list[list[tuple[str, dict[str, bool]]]]] = []
current_row: list[list[tuple[str, dict[str, bool]]]] | None = None
while self.index < len(self.tokens):
token = self.tokens[self.index]
if token.type == "tr_open":
current_row = []
elif token.type == "tr_close" and current_row is not None:
rows.append(current_row)
current_row = None
elif token.type in {"th_open", "td_open"} and current_row is not None:
inline = self.tokens[self.index + 1] if self.index + 1 < len(self.tokens) else None
cell_runs = _inline_runs(inline.children if inline is not None else None)
current_row.append(cell_runs)
elif token.type == "table_close":
self.index += 1
break
self.index += 1
return TableBlock(rows)
def _inline_runs(children: list[Token] | None) -> list[tuple[str, dict[str, object]]]:
if not children:
return [("", {})]
runs: list[tuple[str, dict[str, object]]] = []
style_stack: list[str] = []
links = []
for child in children:
if child.type == "strong_open":
style_stack.append("bold")
elif child.type == "strong_close":
_pop_style(style_stack, "bold")
elif child.type == "em_open":
style_stack.append("italic")
elif child.type == "em_close":
_pop_style(style_stack, "italic")
elif child.type == 's_open': style_stack.append('strike')
elif child.type == 's_close': _pop_style(style_stack, 'strike')
elif child.type == 'link_open':
links.append(child.attrGet('href') or '')
style_stack.append('link')
elif child.type == 'link_close':
if links: links.pop()
_pop_style(style_stack, 'link')
elif child.type in {"text", "html_inline", 'code_inline'}:
text = html.unescape(child.content) if child.type == "html_inline" else child.content
style = {key: True for key in style_stack}
if child.type == 'code_inline': style['code'] = True
keys = {'bold': 'strong', 'italic': 'emphasis', 'strike': 'strike', 'link': 'link'}
style['semantic_order'] = tuple(dict.fromkeys([keys[key] for key in style_stack] + (['inline_code'] if style.get('code') else [])))
if links: style['href'] = links[-1]
runs.append((text, style))
elif child.type in {"softbreak", "hardbreak"}:
runs.append(("\n", {}))
elif child.children:
runs.extend(_inline_runs(child.children))
return runs or [("", {})]
def _pop_style(style_stack: list[str], value: str) -> None:
for index in range(len(style_stack) - 1, -1, -1):
if style_stack[index] == value:
del style_stack[index]
return
def _document_xml(blocks: list[ParagraphBlock | TableBlock]) -> str:
body = "\n".join(_block_xml(block) for block in blocks)
return f"""
{body}
"""
def _block_xml(block: ParagraphBlock | TableBlock) -> str:
if isinstance(block, TableBlock):
return _table_xml(block)
return _paragraph_xml(block)
def _paragraph_xml(block: ParagraphBlock) -> str:
props = [f''] if block.style != "Normal" else []
if block.list_kind:
props = ['']
props.append(f'')
if block.quote_depth:
props.append('')
ppr = f"{''.join(props)}" if props else ""
return f"{ppr}{''.join(_run_xml(text, style) for text, style in block.runs)}"
def _run_xml(text: str, style: dict[str, object]) -> str:
if text == "\n":
return ""
props = []
if style.get("bold"):
props.append("")
if style.get("italic"):
props.append("")
if style.get('strike'): props.append('')
marker = source_style_name(style.get('semantic_order', ()))
if marker:
props.append(f'')
elif style.get("code"):
props.append('')
rpr = f"{''.join(props)}" if props else ""
preserve = ' xml:space="preserve"' if text[:1].isspace() or text[-1:].isspace() else ""
run = f"{rpr}{escape(text)}"
if style.get('link_id'): run = f'{run}'
return run
def _numbering_xml(blocks):
"""Use real numbering for both basic engines, including starts and nesting."""
definitions = {b.list_id: b for b in blocks if isinstance(b, ParagraphBlock) and b.list_kind}
abstracts, instances = [], []
for identifier, block in definitions.items():
levels = []
for level in range(9):
fmt, text = ('decimal', f'%{level + 1}.') if block.list_kind == 'number' else ('bullet', '•')
levels.append(f'')
abstracts.append(f'{"".join(levels)}')
instances.append(f'')
return f'{"".join(abstracts + instances)}'
def _table_xml(block: TableBlock) -> str:
rows = []
for row in block.rows:
cells = []
for cell in row:
cells.append(f"{_paragraph_xml(ParagraphBlock(cell))}")
rows.append(f"{''.join(cells)}")
return (
''
''
''
''
''
''
''
f"{''.join(rows)}"
)
CONTENT_TYPES_XML = """
"""
PACKAGE_RELS_XML = """
"""
DOCUMENT_RELS_XML = """
"""
SETTINGS_XML = f"""
"""
STYLES_XML = f"""
"""