697 lines
32 KiB
Python
697 lines
32 KiB
Python
from __future__ import annotations
|
||
|
||
import html
|
||
import re
|
||
import shutil
|
||
import subprocess
|
||
import sys
|
||
import tempfile
|
||
import time
|
||
import zipfile
|
||
from dataclasses import dataclass, field
|
||
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, LIST_PARAGRAPH_STYLE, QUOTED_LIST_PARAGRAPH_STYLE, SOURCE_PARAGRAPH_STYLES, CONTINUATION, INNER_QUOTE_STYLE, LIST_TARGET
|
||
from .docx_inline import QUOTE_DEPTH, LIST_LEVEL
|
||
|
||
|
||
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('</Types>', '<Override PartName="/word/numbering.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml"/></Types>')
|
||
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'<w:style w:type="character" w:styleId="{name}"><w:name w:val="{name}"/></w:style>' for name in sorted(source_styles))
|
||
markers += ''.join(f'<w:style w:type="paragraph" w:styleId="{name}"><w:name w:val="{name}"/><w:basedOn w:val="ListParagraph"/></w:style>' for name in SOURCE_PARAGRAPH_STYLES)
|
||
package.writestr("word/styles.xml", STYLES_XML.replace('</w:styles>', markers + '</w:styles>'))
|
||
package.writestr("word/settings.xml", SETTINGS_XML)
|
||
relations = ''.join(f'<Relationship Id="{identifier}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target={quoteattr(href)} TargetMode="External"/>' for href, identifier in links.items())
|
||
if has_lists: relations += '<Relationship Id="rIdNumbering" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering" Target="numbering.xml"/>'
|
||
package.writestr("word/_rels/document.xml.rels", DOCUMENT_RELS_XML.replace('</Relationships>', relations + '</Relationships>'))
|
||
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(_pandoc_list_tables(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 _pandoc_list_tables(source: str) -> str:
|
||
"""Disambiguate table-first list items for Pandoc's Markdown reader."""
|
||
markdown = MarkdownIt('commonmark').enable('table')
|
||
lines = source.splitlines(keepends=True)
|
||
items = []
|
||
for token in markdown.parse(source):
|
||
if token.type == 'list_item_open': items.append(token.map[0])
|
||
elif token.type == 'list_item_close': items.pop()
|
||
elif token.type == 'table_open' and items and token.map[0] == items[-1]:
|
||
row = token.map[0]
|
||
match = re.match(r'([ \t]*(?:>[ \t]*)*)([-+*]|\d+[.)])([ \t]+)', lines[row])
|
||
if match:
|
||
prefix, marker, spacing = match.groups()
|
||
indent = prefix + ' ' * (len(marker) + len(spacing))
|
||
lines[row] = match.group() + '\n' + prefix + '\n' + indent + lines[row][match.end():]
|
||
return ''.join(lines)
|
||
|
||
|
||
def _add_python_docx_paragraph(document: object, block: ParagraphBlock) -> None:
|
||
style = f"Heading {block.style.removeprefix('Heading')}" if block.style.startswith("Heading") else None
|
||
special = block.style.startswith('Heading') or block.style == 'Code'
|
||
if block.list_kind == "bullet" and not special:
|
||
style = "List Bullet"
|
||
elif block.list_kind == "number" and not special:
|
||
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 and not special:
|
||
style = "Quote"
|
||
|
||
if block.list_kind and block.loose and not special:
|
||
from docx.enum.style import WD_STYLE_TYPE
|
||
name = QUOTED_LIST_PARAGRAPH_STYLE if block.quote_depth else LIST_PARAGRAPH_STYLE
|
||
if block.inner_quote: name = INNER_QUOTE_STYLE
|
||
if name not in document.styles:
|
||
marker = document.styles.add_style(name, WD_STYLE_TYPE.PARAGRAPH)
|
||
marker.base_style = document.styles[style]
|
||
style = name
|
||
paragraph = document.add_paragraph(style=style)
|
||
if block.continuation: paragraph._p.set(CONTINUATION, '1')
|
||
if block.list_target: paragraph._p.set(LIST_TARGET, block.list_target)
|
||
if block.quote_depth: paragraph._p.set(QUOTE_DEPTH, str(block.quote_depth))
|
||
if block.list_kind:
|
||
from docx.oxml import parse_xml
|
||
paragraph._p.get_or_add_pPr().append(parse_xml(f'<w:numPr xmlns:w="{WP_NS}"><w:ilvl w:val="{block.list_level}"/><w:numId w:val="{block.list_id}"/></w:numPr>'))
|
||
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)
|
||
if block.list_target:
|
||
table._tbl.set(LIST_TARGET, block.list_target)
|
||
table._tbl.set(LIST_LEVEL, str(block.list_level))
|
||
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]
|
||
if col_index < len(block.alignments) and block.alignments[col_index]:
|
||
from docx.enum.text import WD_ALIGN_PARAGRAPH
|
||
paragraph.alignment = {'left':WD_ALIGN_PARAGRAPH.LEFT,'center':WD_ALIGN_PARAGRAPH.CENTER,'right':WD_ALIGN_PARAGRAPH.RIGHT}[block.alignments[col_index]]
|
||
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
|
||
loose: bool = False
|
||
alignment: str = ''
|
||
continuation: bool = False
|
||
inner_quote: bool = False
|
||
list_target: str = ''
|
||
|
||
|
||
@dataclass
|
||
class TableBlock:
|
||
rows: list[list[list[tuple[str, dict[str, bool]]]]]
|
||
alignments: list[str] = field(default_factory=list)
|
||
list_target: str = ''
|
||
list_level: int = 0
|
||
|
||
|
||
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.item_pending: list[bool] = []
|
||
self.item_targets: list[str] = []
|
||
self.list_quote_depths: list[int] = []
|
||
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}", list_kind=self.list_stack[-1] if self.list_stack else "")
|
||
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"}:
|
||
runs = []
|
||
for index, line in enumerate(token.content.rstrip("\n").split('\n')):
|
||
if index: runs.append(('\n', {}))
|
||
runs.append((line, {'code': True}))
|
||
self._append_paragraph(runs, 'Code', self.list_stack[-1] if self.list_stack else '')
|
||
elif token.type == 'list_item_open':
|
||
self.item_pending.append(True)
|
||
self.item_targets.append('list_ordered' if self.list_stack[-1] == 'number' else 'list_bullet')
|
||
elif token.type == 'list_item_close':
|
||
self.item_pending.pop()
|
||
self.item_targets.pop()
|
||
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))
|
||
self.list_quote_depths.append(self.quote_depth)
|
||
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()
|
||
self.list_quote_depths.pop()
|
||
elif token.type == "table_open":
|
||
if self.item_pending and self.item_pending[-1]:
|
||
self._append_paragraph([], 'Normal', self.list_stack[-1])
|
||
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)
|
||
if list_kind and self.item_pending[-1] and inline is not None:
|
||
if re.match(r'^\[[ xX]\]\s', inline.content): self.item_targets[-1] = 'list_task'
|
||
self._append_paragraph(runs, style, list_kind, not self.tokens[self.index].hidden)
|
||
self.index += 3
|
||
|
||
def _append_paragraph(self, runs, style, list_kind, loose=False):
|
||
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, loose=loose,
|
||
continuation=bool(list_kind and self.item_pending and not self.item_pending[-1]),
|
||
list_target=self.item_targets[-1] if list_kind else '',
|
||
inner_quote=bool(self.list_quote_depths and self.quote_depth > self.list_quote_depths[-1])))
|
||
if self.item_pending: self.item_pending[-1] = False
|
||
|
||
def _collect_table(self) -> TableBlock:
|
||
rows: list[list[list[tuple[str, dict[str, bool]]]]] = []
|
||
alignments = []
|
||
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:
|
||
if token.type == 'th_open':
|
||
value = (token.attrGet('style') or '').removeprefix('text-align:').strip()
|
||
alignments.append(value if value in ('left','center','right') else '')
|
||
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, alignments, self.item_targets[-1] if self.item_targets else '', max(0, len(self.list_stack)-1))
|
||
|
||
|
||
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([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"""<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||
<w:document xmlns:w="{WP_NS}" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
|
||
<w:body>
|
||
{body}
|
||
<w:sectPr>
|
||
<w:pgSz w:w="11906" w:h="16838"/>
|
||
<w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720" w:gutter="0"/>
|
||
</w:sectPr>
|
||
</w:body>
|
||
</w:document>
|
||
"""
|
||
|
||
|
||
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'<w:pStyle w:val="{block.style}"/>'] if block.style != "Normal" else []
|
||
if block.list_kind:
|
||
name = (QUOTED_LIST_PARAGRAPH_STYLE if block.quote_depth else LIST_PARAGRAPH_STYLE) if block.loose else 'ListParagraph'
|
||
if block.inner_quote: name = INNER_QUOTE_STYLE
|
||
if not block.style.startswith('Heading') and block.style != 'Code':
|
||
props = [f'<w:pStyle w:val="{name}"/>']
|
||
props.append(f'<w:numPr><w:ilvl w:val="{block.list_level}"/><w:numId w:val="{block.list_id}"/></w:numPr>')
|
||
if block.quote_depth:
|
||
props.append('<w:ind w:left="720"/>')
|
||
if block.alignment: props.append(f'<w:jc w:val="{block.alignment}"/>')
|
||
ppr = f"<w:pPr>{''.join(props)}</w:pPr>" if props else ""
|
||
marker = ' xmlns:mdh="urn:mdhelper:source"' if block.continuation or block.list_target or block.quote_depth else ''
|
||
if block.continuation: marker += ' mdh:continuation="1"'
|
||
if block.list_target: marker += f' mdh:list-target="{block.list_target}"'
|
||
if block.quote_depth: marker += f' mdh:quote-depth="{block.quote_depth}"'
|
||
return f"<w:p{marker}>{ppr}{''.join(_run_xml(text, style) for text, style in block.runs)}</w:p>"
|
||
|
||
|
||
def _run_xml(text: str, style: dict[str, object]) -> str:
|
||
if text == "\n":
|
||
return "<w:r><w:br/></w:r>"
|
||
props = []
|
||
if style.get("bold"):
|
||
props.append("<w:b/>")
|
||
if style.get("italic"):
|
||
props.append("<w:i/>")
|
||
if style.get('strike'): props.append('<w:strike/>')
|
||
marker = source_style_name(style.get('semantic_order', ()))
|
||
if marker:
|
||
props.append(f'<w:rStyle w:val="{marker}"/>')
|
||
elif style.get("code"):
|
||
props.append('<w:rStyle w:val="CodeChar"/>')
|
||
rpr = f"<w:rPr>{''.join(props)}</w:rPr>" if props else ""
|
||
preserve = ' xml:space="preserve"' if text[:1].isspace() or text[-1:].isspace() else ""
|
||
run = f"<w:r>{rpr}<w:t{preserve}>{escape(text)}</w:t></w:r>"
|
||
if style.get('link_id'): run = f'<w:hyperlink r:id="{style["link_id"]}">{run}</w:hyperlink>'
|
||
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'<w:lvl w:ilvl="{level}"><w:start w:val="{block.list_start}"/><w:numFmt w:val="{fmt}"/><w:lvlText w:val="{text}"/><w:lvlJc w:val="left"/></w:lvl>')
|
||
abstracts.append(f'<w:abstractNum w:abstractNumId="{identifier}"><w:multiLevelType w:val="multilevel"/>{"".join(levels)}</w:abstractNum>')
|
||
instances.append(f'<w:num w:numId="{identifier}"><w:abstractNumId w:val="{identifier}"/></w:num>')
|
||
return f'<w:numbering xmlns:w="{WP_NS}">{"".join(abstracts + instances)}</w:numbering>'
|
||
|
||
|
||
def _table_xml(block: TableBlock) -> str:
|
||
marker = f' xmlns:mdh="urn:mdhelper:source" mdh:list-target="{block.list_target}" mdh:list-level="{block.list_level}"' if block.list_target else ''
|
||
rows = []
|
||
for row in block.rows:
|
||
cells = []
|
||
for index, cell in enumerate(row):
|
||
alignment = block.alignments[index] if index < len(block.alignments) else ''
|
||
cells.append(f"<w:tc><w:tcPr><w:tcW w:w=\"0\" w:type=\"auto\"/></w:tcPr>{_paragraph_xml(ParagraphBlock(cell, alignment=alignment))}</w:tc>")
|
||
rows.append(f"<w:tr>{''.join(cells)}</w:tr>")
|
||
return (
|
||
f'<w:tbl{marker}><w:tblPr><w:tblStyle w:val="TableGrid"/><w:tblW w:w="0" w:type="auto"/>'
|
||
'<w:tblBorders><w:top w:val="single" w:sz="4" w:space="0" w:color="D0D7DE"/>'
|
||
'<w:left w:val="single" w:sz="4" w:space="0" w:color="D0D7DE"/>'
|
||
'<w:bottom w:val="single" w:sz="4" w:space="0" w:color="D0D7DE"/>'
|
||
'<w:right w:val="single" w:sz="4" w:space="0" w:color="D0D7DE"/>'
|
||
'<w:insideH w:val="single" w:sz="4" w:space="0" w:color="D0D7DE"/>'
|
||
'<w:insideV w:val="single" w:sz="4" w:space="0" w:color="D0D7DE"/></w:tblBorders></w:tblPr>'
|
||
f"{''.join(rows)}</w:tbl>"
|
||
)
|
||
|
||
|
||
CONTENT_TYPES_XML = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
|
||
<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
|
||
<Default Extension="xml" ContentType="application/xml"/>
|
||
<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>
|
||
<Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/>
|
||
<Override PartName="/word/settings.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml"/>
|
||
</Types>
|
||
"""
|
||
|
||
PACKAGE_RELS_XML = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
|
||
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>
|
||
</Relationships>
|
||
"""
|
||
|
||
DOCUMENT_RELS_XML = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
|
||
<Relationship Id="rIdStyles" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>
|
||
<Relationship Id="rIdSettings" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings" Target="settings.xml"/>
|
||
</Relationships>
|
||
"""
|
||
|
||
SETTINGS_XML = f"""<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||
<w:settings xmlns:w="{WP_NS}">
|
||
<w:defaultTabStop w:val="720"/>
|
||
</w:settings>
|
||
"""
|
||
|
||
STYLES_XML = f"""<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||
<w:styles xmlns:w="{WP_NS}">
|
||
<w:style w:type="paragraph" w:default="1" w:styleId="Normal">
|
||
<w:name w:val="Normal"/>
|
||
<w:qFormat/>
|
||
<w:pPr><w:spacing w:after="120" w:line="276" w:lineRule="auto"/></w:pPr>
|
||
<w:rPr><w:rFonts w:ascii="Microsoft YaHei" w:eastAsia="Microsoft YaHei" w:hAnsi="Microsoft YaHei"/><w:sz w:val="22"/></w:rPr>
|
||
</w:style>
|
||
<w:style w:type="paragraph" w:styleId="Heading1">
|
||
<w:name w:val="heading 1"/><w:basedOn w:val="Normal"/><w:qFormat/>
|
||
<w:pPr><w:spacing w:before="360" w:after="160"/><w:outlineLvl w:val="0"/></w:pPr>
|
||
<w:rPr><w:b/><w:sz w:val="32"/></w:rPr>
|
||
</w:style>
|
||
<w:style w:type="paragraph" w:styleId="Heading2">
|
||
<w:name w:val="heading 2"/><w:basedOn w:val="Normal"/><w:qFormat/>
|
||
<w:pPr><w:spacing w:before="280" w:after="140"/><w:outlineLvl w:val="1"/></w:pPr>
|
||
<w:rPr><w:b/><w:sz w:val="28"/></w:rPr>
|
||
</w:style>
|
||
<w:style w:type="paragraph" w:styleId="Heading3">
|
||
<w:name w:val="heading 3"/><w:basedOn w:val="Normal"/><w:qFormat/>
|
||
<w:pPr><w:spacing w:before="220" w:after="120"/><w:outlineLvl w:val="2"/></w:pPr>
|
||
<w:rPr><w:b/><w:sz w:val="24"/></w:rPr>
|
||
</w:style>
|
||
<w:style w:type="paragraph" w:styleId="Heading4"><w:name w:val="heading 4"/><w:basedOn w:val="Normal"/><w:qFormat/><w:rPr><w:b/></w:rPr></w:style>
|
||
<w:style w:type="paragraph" w:styleId="Heading5"><w:name w:val="heading 5"/><w:basedOn w:val="Normal"/><w:qFormat/><w:rPr><w:b/></w:rPr></w:style>
|
||
<w:style w:type="paragraph" w:styleId="Heading6"><w:name w:val="heading 6"/><w:basedOn w:val="Normal"/><w:qFormat/><w:rPr><w:b/></w:rPr></w:style>
|
||
<w:style w:type="paragraph" w:styleId="Quote">
|
||
<w:name w:val="Quote"/><w:basedOn w:val="Normal"/><w:qFormat/>
|
||
<w:pPr><w:ind w:left="720"/><w:spacing w:before="120" w:after="120"/></w:pPr>
|
||
<w:rPr><w:i/><w:color w:val="57606A"/></w:rPr>
|
||
</w:style>
|
||
<w:style w:type="paragraph" w:styleId="Code">
|
||
<w:name w:val="Code"/><w:basedOn w:val="Normal"/>
|
||
<w:pPr><w:spacing w:before="80" w:after="80"/></w:pPr>
|
||
<w:rPr><w:rFonts w:ascii="Consolas" w:hAnsi="Consolas" w:eastAsia="Microsoft YaHei"/><w:sz w:val="20"/></w:rPr>
|
||
</w:style>
|
||
<w:style w:type="paragraph" w:styleId="ListParagraph"><w:name w:val="List Paragraph"/><w:basedOn w:val="Normal"/></w:style>
|
||
<w:style w:type="character" w:styleId="CodeChar">
|
||
<w:name w:val="Code Char"/>
|
||
<w:rPr><w:rFonts w:ascii="Consolas" w:hAnsi="Consolas" w:eastAsia="Microsoft YaHei"/><w:sz w:val="20"/></w:rPr>
|
||
</w:style>
|
||
<w:style w:type="table" w:default="1" w:styleId="TableGrid">
|
||
<w:name w:val="Table Grid"/>
|
||
</w:style>
|
||
</w:styles>
|
||
"""
|