#!/usr/bin/env python3 """Преобразование Markdown в документ DOCX.""" from __future__ import annotations import argparse import re from pathlib import Path from docx import Document from docx.shared import Pt, RGBColor FENCE = re.compile(r"^\s*(```|~~~)") HEADING = re.compile(r"^(#{1,6})\s+(.*)$") BULLET = re.compile(r"^(\s*)[-*+]\s+(.*)$") NUMBERED = re.compile(r"^(\s*)\d+[.)]\s+(.*)$") INLINE = re.compile(r"(\*\*.+?\*\*|__.+?__|\*[^*\n]+?\*|_[^_\n]+?_|`[^`\n]+`|\[[^\]]+\]\([^)]+\))") def add_inline(paragraph, text: str) -> None: position = 0 for match in INLINE.finditer(text): if match.start() > position: paragraph.add_run(text[position:match.start()]) token = match.group(0) if token.startswith(("**", "__")): run = paragraph.add_run(token[2:-2]) run.bold = True elif token.startswith("`"): run = paragraph.add_run(token[1:-1]) run.font.name = "Courier New" run.font.size = Pt(9) elif token.startswith("["): label, url = re.match(r"\[([^\]]+)\]\(([^)]+)\)", token).groups() run = paragraph.add_run(label) run.underline = True run.font.color.rgb = RGBColor(0x0F, 0x76, 0x6E) if url != label: extra = paragraph.add_run(f" ({url})") extra.font.size = Pt(8) extra.font.color.rgb = RGBColor(0x55, 0x55, 0x55) else: run = paragraph.add_run(token[1:-1]) run.italic = True position = match.end() if position < len(text): paragraph.add_run(text[position:]) def add_table(document, rows: list[list[str]]) -> None: if not rows: return width = max(len(row) for row in rows) table = document.add_table(rows=len(rows), cols=width) table.style = "Table Grid" for row_index, row in enumerate(rows): for column_index in range(width): cell = table.cell(row_index, column_index) value = row[column_index] if column_index < len(row) else "" cell.text = value if row_index == 0: for paragraph in cell.paragraphs: for run in paragraph.runs: run.bold = True def convert(source: Path, target: Path, title: str | None) -> None: text = source.read_text(encoding="utf-8") document = Document() if title: document.core_properties.title = title heading = document.add_heading(title, level=0) heading.alignment = 1 lines = text.splitlines() index = 0 paragraph_buffer: list[str] = [] def flush() -> None: if paragraph_buffer: add_inline(document.add_paragraph(), " ".join(part.strip() for part in paragraph_buffer)) paragraph_buffer.clear() while index < len(lines): line = lines[index] stripped = line.strip() if FENCE.match(line): flush() index += 1 code_lines = [] while index < len(lines) and not FENCE.match(lines[index]): code_lines.append(lines[index]) index += 1 paragraph = document.add_paragraph(style="No Spacing") run = paragraph.add_run("\n".join(code_lines)) run.font.name = "Courier New" run.font.size = Pt(9) index += 1 continue if not stripped: flush() index += 1 continue heading = HEADING.match(line) if heading: flush() level = min(len(heading.group(1)), 9) document.add_heading(heading.group(2).strip(), level=level) index += 1 continue bullet = BULLET.match(line) if bullet: flush() depth = len(bullet.group(1)) // 2 paragraph = document.add_paragraph(style="List Bullet") paragraph.paragraph_format.left_indent = Pt(18 * depth) add_inline(paragraph, bullet.group(2)) index += 1 continue numbered = NUMBERED.match(line) if numbered: flush() depth = len(numbered.group(1)) // 2 paragraph = document.add_paragraph(style="List Number") paragraph.paragraph_format.left_indent = Pt(18 * depth) add_inline(paragraph, numbered.group(2)) index += 1 continue if stripped.startswith(">"): flush() quote_lines = [] while index < len(lines) and lines[index].strip().startswith(">"): quote_lines.append(lines[index].strip()[1:].strip()) index += 1 paragraph = document.add_paragraph(style="Quote") add_inline(paragraph, " ".join(quote_lines)) continue if stripped.startswith("|") and stripped.endswith("|"): flush() table_rows = [] while index < len(lines): candidate = lines[index].strip() if not (candidate.startswith("|") and candidate.endswith("|")): break cells = [cell.strip() for cell in candidate.strip("|").split("|")] if all(re.fullmatch(r":?-{3,}:?", cell) for cell in cells): index += 1 continue table_rows.append(cells) index += 1 add_table(document, table_rows) continue paragraph_buffer.append(line) index += 1 flush() document.save(target) def main() -> int: parser = argparse.ArgumentParser(description="Собрать DOCX из Markdown") parser.add_argument("--path", type=Path, required=True, help="Файл или папка") parser.add_argument("--glob", default="*.md", help="Маска файлов") parser.add_argument("--output", type=Path, help="Имя DOCX для одного файла") parser.add_argument("--output-dir", type=Path, default=Path("docx-out"), help="Папка для документов") parser.add_argument("--title", help="Заголовок документа") parser.add_argument("--force", action="store_true", help="Перезаписать DOCX") args = parser.parse_args() root = args.path.expanduser().resolve() if not root.exists(): parser.error(f"Путь не найден: {root}") if args.output and not root.is_file(): parser.error("--output можно использовать только с одним файлом") out_dir = args.output_dir.expanduser().resolve() files = [root] if root.is_file() else sorted(path for path in root.rglob(args.glob) if path.is_file()) written = 0 for source in files: if args.output and root.is_file(): target = args.output.expanduser() else: relative = source.relative_to(root) if root.is_dir() else Path(source.name) target = out_dir / relative.with_suffix(".docx") if target.resolve() == source.resolve(): print(f"Пропуск, выходной путь совпадает с входным: {source}") continue if target.exists() and not args.force: print(f"Пропуск, файл уже есть: {target}") continue target.parent.mkdir(parents=True, exist_ok=True) convert(source, target, args.title) written += 1 print(f"Сохранено: {target}") print(f"Документов собрано: {written}") return 0 if __name__ == "__main__": raise SystemExit(main())