#!/usr/bin/env python3 """Turn a KB Markdown file into a Word, OpenDocument, PDF or HTML file in a house style, through pandoc. The style is a file the user never has to open: convert.py convert FILE.md [--to docx|odt|pdf|html] [--style NAME] [--out PATH] [--out-dir DIR] [--toc] [--number-sections] [--keep-links] [--force] convert.py new-style NAME [--from FILE.docx|.dotx] [--body-font F] [--heading-font F] [--size PT] [--heading-color RRGGBB] [--paper a4|letter] [--margin-cm CM] [--force] convert.py edit-style NAME [same options as new-style, without --from] convert.py check-style NAME # which styles pandoc uses are missing from NAME.docx convert.py styles # list templates/styles/ convert.py doctor # pandoc, LibreOffice, PDF route Styles live in templates/styles/: NAME.docx (the Word reference document, required), NAME.odt and NAME.css (optional, for odt and html). pandoc takes fonts, sizes, colours, spacing, page size, margins, header and footer from the reference document and ignores its text. Before conversion the Markdown is cleaned for a reader outside the KB: the frontmatter becomes title/author/date/lang metadata, the first `# H1` becomes the title when the frontmatter has none, HTML comments are dropped, [[Wikilinks]] become plain text, and links to KB paths become their label (they would be dead in a Word file; --keep-links keeps them). Code blocks are never touched. PDF and ODT go through the Word style: pandoc writes the .docx and LibreOffice converts it, so all formats look the same. Without LibreOffice, PDF falls back to a pandoc PDF engine (style not applied, said so) and ODT to pandoc's own. Exit 0 = written, 1 = refused (output exists, unknown style, bad input), 2 = usage, 3 = a required program is missing or failed. Python 3.8+, standard library only; needs pandoc, optionally LibreOffice. """ import argparse import json import re import shutil import subprocess import sys import tempfile import zipfile from datetime import date from pathlib import Path STYLES_DIR = Path("templates") / "styles" DEFAULT_OUT_DIR = Path("outputs") / "documents" FORMATS = ("docx", "odt", "pdf", "html") PDF_ENGINES = ("typst", "weasyprint", "wkhtmltopdf", "xelatex", "lualatex", "pdflatex") SOFFICE_TIMEOUT = 180 # The paragraph/character/table styles pandoc's docx writer uses. A reference # document without one of them gets pandoc's own definition for it. PANDOC_STYLES = [ "Normal", "Body Text", "First Paragraph", "Compact", "Title", "Subtitle", "Author", "Date", "Abstract", "heading 1", "heading 2", "heading 3", "heading 4", "heading 5", "heading 6", "Block Text", "Source Code", "Verbatim Char", "Hyperlink", "Footnote Text", "Footnote Reference", "Caption", "Table Caption", "Image Caption", "Table", "TOC Heading", ] KEY_STYLES = {"Normal", "Body Text", "Title", "heading 1", "heading 2", "heading 3", "Table"} # Child order inside and (ECMA-376). Word rejects a file # whose children are out of order, so inserts respect it. RPR_ORDER = ("rStyle rFonts b bCs i iCs caps smallCaps strike dstrike outline shadow emboss " "imprint noProof snapToGrid vanish webHidden color spacing w kern position sz szCs " "highlight u effect bdr shd fitText vertAlign rtl cs em lang eastAsianLayout " "specVanish oMath").split() SECTPR_ORDER = ("headerReference footerReference footnotePr endnotePr type pgSz pgMar paperSrc " "pgBorders lnNumType pgNumType cols formProt vAlign noEndnote titlePg " "textDirection bidi rtlGutter docGrid printerSettings sectPrChange").split() PAPER = {"a4": (11906, 16838), "letter": (12240, 15840)} HEADING_STYLE_IDS = ["Title", "Subtitle"] + ["Heading%d" % i for i in range(1, 10)] DOCX_CT = "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml" DOTX_CT = "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml" class Refused(Exception): """Exit 1 with a message.""" class Missing(Exception): """Exit 3 with a message.""" # --------------------------------------------------------------------------- tools def pandoc_version(): exe = shutil.which("pandoc") if not exe: return None try: out = subprocess.run([exe, "--version"], capture_output=True, timeout=30, encoding="utf-8", errors="replace").stdout except (OSError, subprocess.SubprocessError): return None m = re.search(r"pandoc(?:\.exe)?\s+(\d+(?:\.\d+)*)", out) return tuple(int(x) for x in m.group(1).split(".")) if m else (0,) def soffice(): for name in ("soffice", "libreoffice"): exe = shutil.which(name) if exe: return exe for p in ("/Applications/LibreOffice.app/Contents/MacOS/soffice", r"C:\Program Files\LibreOffice\program\soffice.exe", r"C:\Program Files (x86)\LibreOffice\program\soffice.exe"): if Path(p).exists(): return p return None def need_pandoc(): v = pandoc_version() if v is None: raise Missing("pandoc not found. Install it from https://pandoc.org/installing.html " "(Fedora: dnf install pandoc; Debian/Ubuntu: apt install pandoc; " "macOS: brew install pandoc; Windows: winget install JohnMacFarlane.Pandoc).") return v def run(cmd, timeout=300): try: p = subprocess.run(cmd, capture_output=True, timeout=timeout, encoding="utf-8", errors="replace") except subprocess.TimeoutExpired: raise Missing("%s timed out after %ds" % (Path(cmd[0]).name, timeout)) except OSError as e: raise Missing("could not run %s: %s" % (cmd[0], e)) if p.returncode != 0: raise Missing("%s failed (exit %d):\n%s" % (Path(cmd[0]).name, p.returncode, (p.stderr or p.stdout).strip())) return p def soffice_convert(exe, src, fmt, workdir): """Convert src with LibreOffice into workdir; return the new file's path. A private profile keeps it from colliding with a LibreOffice the user has open.""" profile = (Path(workdir) / "lo-profile").resolve().as_uri() outdir = Path(workdir) / ("lo-out-" + fmt) outdir.mkdir(exist_ok=True) run([exe, "-env:UserInstallation=" + profile, "--headless", "--norestore", "--convert-to", fmt, "--outdir", str(outdir), str(src)], timeout=SOFFICE_TIMEOUT) out = outdir / (Path(src).stem + "." + fmt) if not out.exists(): raise Missing("LibreOffice did not produce %s (is another conversion stuck?)" % out.name) return out # --------------------------------------------------------------------------- Markdown def split_frontmatter(text): if not text.startswith("---\n"): return {}, text end = text.find("\n---", 4) if end < 0: return {}, text meta = {} for line in text[4:end].split("\n"): m = re.match(r"^([A-Za-z_][\w-]*):\s*(.*?)\s*$", line) if m: v = m.group(2) if len(v) >= 2 and v[0] == v[-1] and v[0] in "\"'": v = v[1:-1] meta[m.group(1)] = v rest = text[end + 4:] return meta, rest[1:] if rest.startswith("\n") else rest def split_fences(body): """Yield (is_code, chunk). Fenced code blocks are passed through untouched.""" out, buf, fence = [], [], None for line in body.split("\n"): m = re.match(r"^\s{0,3}(`{3,}|~{3,})", line) if fence is None and m: if buf: out.append((False, "\n".join(buf))) buf, fence = [line], m.group(1) elif fence is not None and re.match(r"^\s{0,3}" + re.escape(fence[0]) + "{%d,}\\s*$" % len(fence), line): buf.append(line) out.append((True, "\n".join(buf))) buf, fence = [], None else: buf.append(line) if buf: out.append((fence is not None, "\n".join(buf))) return out def is_external(target): return bool(re.match(r"^(?:[a-z][a-z0-9+.-]*:|#)", target, re.I)) def wikilink_text(m): target, label = m.group(1), m.group(2) return label or target.rstrip("/").split("/")[-1].replace(".md", "") def clean_prose(text, keep_links): text = re.sub(r"\n?", "", text, flags=re.S) # Rule C pairs a wikilink with a Markdown link to the same page: keep one label. def pair(m): label = wikilink_text(m) return "[%s](%s)" % (label, m.group(3)) if keep_links else label text = re.sub(r"\[\[([^\]|\n]+)(?:\|([^\]\n]+))?\]\]\s*\(\[[^\]\n]*\]\(([^)\s]+)\)\)", pair, text) text = re.sub(r"\[\[([^\]|\n]+)(?:\|([^\]\n]+))?\]\]", wikilink_text, text) if not keep_links: def local(m): return m.group(0) if is_external(m.group(2)) else m.group(1) text = re.sub(r"(?]*>", "", author).strip() when = fm.get("date") or fm.get("created") or "" if when: meta["date"] = when if fm.get("lang"): meta["lang"] = fm["lang"] parts = [chunk if code else clean_prose(chunk, keep_links) for code, chunk in split_fences(body)] return meta, "\n".join(parts).strip("\n") + "\n" # --------------------------------------------------------------------------- docx XML def children(inner): """Direct children of an element's inner XML as (name, start, end).""" out, pos = [], 0 tag = re.compile(r"]*?(/?)>") while True: m = tag.search(inner, pos) if not m: return out if m.group(2) == "/": end = m.end() else: close = inner.find("" % m.group(1), m.end()) end = len(inner) if close < 0 else close + len(m.group(1)) + 6 out.append((m.group(1), m.start(), end)) pos = end def set_child(inner, name, element, order): """Replace every child with element, placed in schema order.""" for n, s, e in reversed(children(inner)): if n == name: inner = inner[:s] + inner[e:] rank = order.index(name) kids = children(inner) for n, s, _ in kids: if n in order and order.index(n) > rank: return inner[:s] + element + inner[s:] known = [e for n, _, e in kids if n in order] at = known[-1] if known else len(inner) return inner[:at] + element + inner[at:] def edit_block(xml, open_re, tag, fn): """Apply fn to the inner XML of the first matched by open_re.""" m = re.search(open_re, xml, re.S) if not m: return xml, False if m.group(0).endswith("/>"): new = "%s" % (tag, fn(""), tag) return xml[:m.start()] + new + xml[m.end():], True close = xml.find("" % tag, m.end()) return xml[:m.end()] + fn(xml[m.end():close]) + xml[close:], True def style_span(xml, style_id): m = re.search(r']*w:styleId="%s"[^>]*>' % re.escape(style_id), xml) if not m: return None return m.start(), xml.find("", m.end()) + len("") def edit_style_rpr(xml, style_id, edits): span = style_span(xml, style_id) if not span: return xml, False block = xml[span[0]:span[1]] if not re.search(r"", block): block = block[:-len("")] + "" def apply(inner): for name, element in edits: inner = set_child(inner, name, element, RPR_ORDER) return inner block, _ = edit_block(block, r"", "rPr", apply) return xml[:span[0]] + block + xml[span[1]:], True def fonts_el(font): f = xml_attr(font) return '' % (f, f, f, f) def xml_attr(s): return s.replace("&", "&").replace('"', """).replace("<", "<") def patch_styles(xml, opts, notes): rpr_edits = [] if opts.body_font: rpr_edits.append(("rFonts", fonts_el(opts.body_font))) if opts.size: half = str(int(round(opts.size * 2))) rpr_edits += [("sz", '' % half), ("szCs", '' % half)] if rpr_edits: def apply(inner): for name, element in rpr_edits: inner = set_child(inner, name, element, RPR_ORDER) return inner m = re.search(r"(.*?)", xml, re.S) if m: seg, _ = edit_block(m.group(1) if "", r"", "rPr", apply) xml = xml[:m.start(1)] + seg + xml[m.end(1):] else: notes.append("no document defaults found; body font/size set on Normal only") # A template may pin its own font or size on Normal; the request wins there too. xml, _ = edit_style_rpr(xml, "Normal", rpr_edits) heading_edits = [] if opts.heading_font: heading_edits.append(("rFonts", fonts_el(opts.heading_font))) if opts.heading_color: heading_edits.append(("color", '' % opts.heading_color)) if heading_edits: found = [] for sid in HEADING_STYLE_IDS: xml, ok = edit_style_rpr(xml, sid, heading_edits) if ok: found.append(sid) if not found: notes.append("no Title or Heading styles found; heading settings not applied") return xml def patch_theme(xml, opts): for which, font in (("major", opts.heading_font), ("minor", opts.body_font)): if font: xml = re.sub(r'(\s*]*?(/?)>", xml)) if not sects: at = xml.rfind("") if at < 0: return xml xml = xml[:at] + "" + xml[at:] sects = list(re.finditer(r"]*?(/?)>", xml)) m = sects[-1] if m.group(1) == "/": xml = xml[:m.start()] + "" + "" + xml[m.end():] m = list(re.finditer(r"]*?(/?)>", xml))[-1] close = xml.find("", m.end()) inner = xml[m.end():close] if opts.paper: w, h = PAPER[opts.paper] inner = set_child(inner, "pgSz", '' % (w, h), SECTPR_ORDER) if opts.margin_cm is not None: t = int(round(opts.margin_cm * 567)) inner = set_child(inner, "pgMar", '' % (t, t, t, t), SECTPR_ORDER) return xml[:m.end()] + inner + xml[close:] def rewrite_zip(path, edits): """edits: {member name: function(str) -> str}. Rewrites the zip in place.""" tmp = Path(str(path) + ".tmp") with zipfile.ZipFile(path) as zin, zipfile.ZipFile(tmp, "w", zipfile.ZIP_DEFLATED) as zout: for info in zin.infolist(): data = zin.read(info.filename) if info.filename in edits: data = edits[info.filename](data.decode("utf-8")).encode("utf-8") zout.writestr(info, data) tmp.replace(path) def style_settings_given(opts): return any(v is not None for v in (opts.body_font, opts.heading_font, opts.size, opts.heading_color, opts.paper, opts.margin_cm)) def apply_settings(path, opts): notes = [] with zipfile.ZipFile(path) as z: names = set(z.namelist()) if "word/styles.xml" not in names or "word/document.xml" not in names: raise Refused("%s is not a Word document (no word/styles.xml)" % path) edits = {"word/styles.xml": lambda x: patch_styles(x, opts, notes)} if opts.paper or opts.margin_cm is not None: edits["word/document.xml"] = lambda x: patch_document(x, opts) if "word/theme/theme1.xml" in names and (opts.body_font or opts.heading_font): edits["word/theme/theme1.xml"] = lambda x: patch_theme(x, opts) rewrite_zip(path, edits) return notes def style_names(path): with zipfile.ZipFile(path) as z: xml = z.read("word/styles.xml").decode("utf-8") return {n.lower() for n in re.findall(r'= (2, 19) else "--self-contained"] if css.exists(): cmd += ["--css", str(css)] else: notes.append("no %s.css: html uses pandoc's default look" % name) p = run(cmd) elif fmt == "odt": ref_odt = sdir / (name + ".odt") if ref_odt.exists(): p = run(base + ["-t", "odt", "-o", str(produced), "--reference-doc", str(ref_odt)]) elif lo and ref_docx: p = docx_to(tmpd / (src.stem + ".docx")) produced = soffice_convert(lo, tmpd / (src.stem + ".docx"), "odt", tmpd) via = "pandoc + LibreOffice" else: p = run(base + ["-t", "odt", "-o", str(produced)]) notes.append("odt uses pandoc's default look (no %s.odt%s)" % (name, "" if lo else ", no LibreOffice")) else: # pdf if lo: p = docx_to(tmpd / (src.stem + ".docx")) produced = soffice_convert(lo, tmpd / (src.stem + ".docx"), "pdf", tmpd) via = "pandoc + LibreOffice" else: engine = next((e for e in PDF_ENGINES if shutil.which(e)), None) if not engine: raise Missing("PDF needs LibreOffice (keeps the Word style) or a pandoc PDF " "engine (%s); none found" % ", ".join(PDF_ENGINES)) p = run(base + ["-o", str(produced), "--pdf-engine=" + engine]) via = "pandoc --pdf-engine=" + engine notes.append("no LibreOffice: the PDF does not follow the Word style") out.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(produced, out) for line in (p.stderr or "").splitlines(): if line.strip(): notes.append("pandoc: " + line.strip()) print("written: %s" % rel(out, root)) print("format: %s via %s, style: %s" % (fmt, via, name if ref_docx else "pandoc default")) if meta.get("title"): print("title: %s" % meta["title"]) for n in notes: print("note: " + n) return 0 def rel(path, root): try: return Path(path).resolve().relative_to(Path(root).resolve()).as_posix() except ValueError: return str(path) # --------------------------------------------------------------------------- CLI def hex_color(v): v = v.lstrip("#").upper() if not re.match(r"^[0-9A-F]{6}$", v): raise argparse.ArgumentTypeError("colour must be six hex digits, e.g. 1F3864") return v def style_options(p): p.add_argument("--body-font") p.add_argument("--heading-font") p.add_argument("--size", type=float, help="body text size in points") p.add_argument("--heading-color", type=hex_color, help="RRGGBB") p.add_argument("--paper", choices=sorted(PAPER)) p.add_argument("--margin-cm", type=float) def main(argv=None): for stream in (sys.stdout, sys.stderr): if hasattr(stream, "reconfigure"): stream.reconfigure(encoding="utf-8", errors="replace") ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) ap.add_argument("--root", default=".") sub = ap.add_subparsers(dest="cmd") sub.required = True c = sub.add_parser("convert") c.add_argument("file") c.add_argument("--to", choices=FORMATS, default="docx") c.add_argument("--style", default="house") c.add_argument("--style-required", action="store_true", help="refuse instead of falling back to pandoc's default when the style is missing") c.add_argument("--out") c.add_argument("--out-dir") c.add_argument("--toc", action="store_true") c.add_argument("--number-sections", action="store_true") c.add_argument("--keep-links", action="store_true") c.add_argument("--force", action="store_true") c.set_defaults(fn=cmd_convert) n = sub.add_parser("new-style") n.add_argument("name") n.add_argument("--from", dest="from_file") n.add_argument("--force", action="store_true") style_options(n) n.set_defaults(fn=cmd_new_style) e = sub.add_parser("edit-style") e.add_argument("name") style_options(e) e.set_defaults(fn=cmd_edit_style) k = sub.add_parser("check-style") k.add_argument("name") k.set_defaults(fn=cmd_check_style) sub.add_parser("styles").set_defaults(fn=cmd_styles) sub.add_parser("doctor").set_defaults(fn=cmd_doctor) args = ap.parse_args(argv) args.root = str(Path(args.root).resolve()) try: return args.fn(args) except Refused as e: print("refused: %s" % e, file=sys.stderr) return 1 except Missing as e: print("error: %s" % e, file=sys.stderr) return 3 except zipfile.BadZipFile as e: print("refused: not a valid Office file (%s)" % e, file=sys.stderr) return 1 if __name__ == "__main__": sys.exit(main())