- OKF export: a bare [[X]] becomes a bundle-root link when it resolves
(path, file name or title; `&`, spaces and brackets percent-encoded)
instead of degrading to plain text.
- N2 "degraded, not empty": retrieve reports DEGRADED for unread pages,
graph or exact search ("no candidates among what could be read");
lint reports Crux quotes and secret scans it could not do, and no
longer skips an unreadable file as binary in the secrets scan.
AGENTS.md rule; test_silent_reads guards new swallowed reads
(`# ok-silent: <reason>` for the deliberate ones).
- N17: case- and accent-insensitive fold in retrieve's tldr and scope
matching; lint check 20 flags page names that collide after folding.
- N7: one publish filter in both exporters drops HTML comments outside
code (unclosed to the end of the page), `--drop-section NAME` leaves out
sections, and a page whose frontmatter never closes is refused (exit 1).
- Test that an interrupted routine stays due until --mark.
- Docs: lint, retrieve and exporter skills, both manuals; goldens updated.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
746 lines
29 KiB
Python
746 lines
29 KiB
Python
#!/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 <w:rPr> and <w:sectPr> (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): # ok-silent: callers report pandoc as unavailable
|
|
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"(?<!!)\[([^\]\n]+)\]\(([^)\s]+)(?:\s+\"[^\"]*\")?\)", local, text)
|
|
return text
|
|
|
|
|
|
def prepare(text, keep_links):
|
|
"""Return (metadata for pandoc, cleaned Markdown body)."""
|
|
fm, body = split_frontmatter(text.lstrip("\ufeff").replace("\r\n", "\n"))
|
|
meta = {}
|
|
title = fm.get("title", "").strip()
|
|
if not title:
|
|
m = re.search(r"^# +(.+?)\s*#*\s*$", body, re.M)
|
|
if m and not body[:m.start()].strip().strip("-").strip():
|
|
title = m.group(1).strip()
|
|
body = body[:m.start()] + body[m.end():].lstrip("\n")
|
|
if title:
|
|
meta["title"] = re.sub(r"\[\[([^\]|]+)(?:\|([^\]]+))?\]\]", wikilink_text, title)
|
|
for key in ("subtitle",):
|
|
if fm.get(key):
|
|
meta[key] = fm[key]
|
|
author = fm.get("author", "").strip()
|
|
if author:
|
|
meta["author"] = re.sub(r"\s*<[^>]*>", "", 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 <w:*> children of an element's inner XML as (name, start, end)."""
|
|
out, pos = [], 0
|
|
tag = re.compile(r"<w:([A-Za-z]+)\b[^>]*?(/?)>")
|
|
while True:
|
|
m = tag.search(inner, pos)
|
|
if not m:
|
|
return out
|
|
if m.group(2) == "/":
|
|
end = m.end()
|
|
else:
|
|
close = inner.find("</w:%s>" % 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 <w:name> 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 <w:tag> matched by open_re."""
|
|
m = re.search(open_re, xml, re.S)
|
|
if not m:
|
|
return xml, False
|
|
if m.group(0).endswith("/>"):
|
|
new = "<w:%s>%s</w:%s>" % (tag, fn(""), tag)
|
|
return xml[:m.start()] + new + xml[m.end():], True
|
|
close = xml.find("</w:%s>" % 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:style\b[^>]*w:styleId="%s"[^>]*>' % re.escape(style_id), xml)
|
|
if not m:
|
|
return None
|
|
return m.start(), xml.find("</w:style>", m.end()) + len("</w:style>")
|
|
|
|
|
|
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"<w:rPr\s*/?>", block):
|
|
block = block[:-len("</w:style>")] + "<w:rPr></w:rPr></w:style>"
|
|
|
|
def apply(inner):
|
|
for name, element in edits:
|
|
inner = set_child(inner, name, element, RPR_ORDER)
|
|
return inner
|
|
block, _ = edit_block(block, r"<w:rPr\s*/?>", "rPr", apply)
|
|
return xml[:span[0]] + block + xml[span[1]:], True
|
|
|
|
|
|
def fonts_el(font):
|
|
f = xml_attr(font)
|
|
return '<w:rFonts w:ascii="%s" w:hAnsi="%s" w:eastAsia="%s" w:cs="%s"/>' % (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", '<w:sz w:val="%s"/>' % half), ("szCs", '<w:szCs w:val="%s"/>' % 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"<w:rPrDefault>(.*?)</w:rPrDefault>", xml, re.S)
|
|
if m:
|
|
seg, _ = edit_block(m.group(1) if "<w:rPr" in m.group(1) else "<w:rPr></w:rPr>",
|
|
r"<w:rPr\s*/?>", "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", '<w:color w:val="%s"/>' % 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'(<a:%sFont>\s*<a:latin typeface=")[^"]*(")' % which,
|
|
lambda m: m.group(1) + xml_attr(font) + m.group(2), xml)
|
|
return xml
|
|
|
|
|
|
def patch_document(xml, opts):
|
|
sects = list(re.finditer(r"<w:sectPr\b[^>]*?(/?)>", xml))
|
|
if not sects:
|
|
at = xml.rfind("</w:body>")
|
|
if at < 0:
|
|
return xml
|
|
xml = xml[:at] + "<w:sectPr></w:sectPr>" + xml[at:]
|
|
sects = list(re.finditer(r"<w:sectPr\b[^>]*?(/?)>", xml))
|
|
m = sects[-1]
|
|
if m.group(1) == "/":
|
|
xml = xml[:m.start()] + "<w:sectPr>" + "</w:sectPr>" + xml[m.end():]
|
|
m = list(re.finditer(r"<w:sectPr\b[^>]*?(/?)>", xml))[-1]
|
|
close = xml.find("</w:sectPr>", m.end())
|
|
inner = xml[m.end():close]
|
|
if opts.paper:
|
|
w, h = PAPER[opts.paper]
|
|
inner = set_child(inner, "pgSz", '<w:pgSz w:w="%d" w:h="%d"/>' % (w, h), SECTPR_ORDER)
|
|
if opts.margin_cm is not None:
|
|
t = int(round(opts.margin_cm * 567))
|
|
inner = set_child(inner, "pgMar", '<w:pgMar w:top="%d" w:right="%d" w:bottom="%d" w:left="%d" '
|
|
'w:header="709" w:footer="709" w:gutter="0"/>' % (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'<w:name w:val="([^"]*)"', xml)}
|
|
|
|
|
|
# --------------------------------------------------------------------------- commands
|
|
|
|
def styles_dir(root):
|
|
return Path(root) / STYLES_DIR
|
|
|
|
|
|
def valid_name(name):
|
|
if not re.match(r"^[a-z0-9][a-z0-9-]{0,60}$", name):
|
|
raise Refused("style name %r: use lower-case letters, digits and hyphens" % name)
|
|
return name
|
|
|
|
|
|
def cmd_styles(args):
|
|
d = styles_dir(args.root)
|
|
found = {}
|
|
for p in sorted(d.glob("*")) if d.is_dir() else []:
|
|
if p.suffix.lower() in (".docx", ".odt", ".css"):
|
|
found.setdefault(p.stem, []).append(p.suffix[1:].lower())
|
|
if not found:
|
|
print("no styles in %s" % STYLES_DIR.as_posix())
|
|
return 0
|
|
for name, kinds in found.items():
|
|
flag = "" if "docx" in kinds else " (no .docx: docx and pdf use pandoc's default)"
|
|
print("%-20s %s%s" % (name, ", ".join(kinds), flag))
|
|
return 0
|
|
|
|
|
|
def cmd_doctor(args):
|
|
v = pandoc_version()
|
|
lo = soffice()
|
|
engines = [e for e in PDF_ENGINES if shutil.which(e)]
|
|
print("pandoc: %s" % (".".join(map(str, v)) if v else "MISSING (required)"))
|
|
print("libreoffice: %s" % (lo or "missing (PDF and ODT will not follow the Word style)"))
|
|
if lo:
|
|
print("pdf: via LibreOffice from the styled .docx")
|
|
elif engines:
|
|
print("pdf: via pandoc --pdf-engine=%s (Word style not applied)" % engines[0])
|
|
else:
|
|
print("pdf: unavailable (install LibreOffice)")
|
|
print("styles: %s" % (", ".join(sorted(p.stem for p in styles_dir(args.root).glob("*.docx")))
|
|
if styles_dir(args.root).is_dir() else "none") or "none")
|
|
return 0 if v else 3
|
|
|
|
|
|
def cmd_new_style(args):
|
|
name = valid_name(args.name)
|
|
d = styles_dir(args.root)
|
|
dest = d / (name + ".docx")
|
|
if dest.exists() and not args.force:
|
|
raise Refused("%s exists; use edit-style to change it, or --force to replace it"
|
|
% dest.relative_to(args.root).as_posix())
|
|
d.mkdir(parents=True, exist_ok=True)
|
|
if args.from_file:
|
|
src = Path(args.from_file)
|
|
if not src.is_file():
|
|
raise Refused("no such file: %s" % src)
|
|
ext = src.suffix.lower()
|
|
if ext in (".docm", ".dotm"):
|
|
raise Refused("%s holds macros; save it as .docx or .dotx (no macros) first" % src.name)
|
|
if ext not in (".docx", ".dotx"):
|
|
raise Refused("a style is made from a .docx or .dotx file, not %s" % ext)
|
|
shutil.copyfile(src, dest)
|
|
if ext == ".dotx":
|
|
rewrite_zip(dest, {"[Content_Types].xml": lambda x: x.replace(DOTX_CT, DOCX_CT)})
|
|
else:
|
|
need_pandoc()
|
|
with open(dest, "wb") as f:
|
|
p = subprocess.run(["pandoc", "--print-default-data-file", "reference.docx"],
|
|
stdout=f, stderr=subprocess.PIPE, timeout=60)
|
|
if p.returncode != 0:
|
|
dest.unlink()
|
|
raise Missing("pandoc could not print its reference.docx: %s"
|
|
% p.stderr.decode("utf-8", "replace").strip())
|
|
notes = apply_settings(dest, args) if style_settings_given(args) else []
|
|
print("written: %s" % dest.relative_to(args.root).as_posix())
|
|
for n in notes:
|
|
print("note: " + n)
|
|
if args.from_file:
|
|
report_missing(dest)
|
|
return 0
|
|
|
|
|
|
def cmd_edit_style(args):
|
|
name = valid_name(args.name)
|
|
dest = styles_dir(args.root) / (name + ".docx")
|
|
if not dest.exists():
|
|
raise Refused("no style %s; create it with new-style" % name)
|
|
if not style_settings_given(args):
|
|
raise Refused("nothing to change: give --body-font, --heading-font, --size, "
|
|
"--heading-color, --paper or --margin-cm")
|
|
notes = apply_settings(dest, args)
|
|
print("updated: %s" % dest.relative_to(args.root).as_posix())
|
|
for n in notes:
|
|
print("note: " + n)
|
|
return 0
|
|
|
|
|
|
def report_missing(path):
|
|
have = style_names(path)
|
|
missing = [s for s in PANDOC_STYLES if s.lower() not in have]
|
|
key = [s for s in missing if s in KEY_STYLES]
|
|
if not missing:
|
|
print("check: every style pandoc uses is defined")
|
|
else:
|
|
print("check: %d of %d styles pandoc uses are not defined; pandoc adds its own for them:"
|
|
% (len(missing), len(PANDOC_STYLES)))
|
|
print(" " + ", ".join(missing))
|
|
if key:
|
|
print(" important: " + ", ".join(key))
|
|
return missing
|
|
|
|
|
|
def cmd_check_style(args):
|
|
path = styles_dir(args.root) / (valid_name(args.name) + ".docx")
|
|
if not path.exists():
|
|
raise Refused("no style %s" % args.name)
|
|
report_missing(path)
|
|
return 0
|
|
|
|
|
|
def default_output(root, src, fmt, out_dir):
|
|
root = Path(root).resolve()
|
|
src = Path(src).resolve()
|
|
if out_dir:
|
|
d = Path(out_dir)
|
|
d = d if d.is_absolute() else root / d
|
|
else:
|
|
try:
|
|
rel = src.relative_to(root)
|
|
d = src.parent if rel.parts[:1] == ("outputs",) else root / DEFAULT_OUT_DIR
|
|
except ValueError:
|
|
d = root / DEFAULT_OUT_DIR
|
|
return d / (src.stem + "." + fmt)
|
|
|
|
|
|
def cmd_convert(args):
|
|
version = need_pandoc()
|
|
root = Path(args.root).resolve()
|
|
src = Path(args.file)
|
|
if not src.is_absolute():
|
|
src = (Path.cwd() / src).resolve()
|
|
if not src.is_file():
|
|
raise Refused("no such file: %s" % args.file)
|
|
fmt = args.to
|
|
out = Path(args.out) if args.out else default_output(root, src, fmt, args.out_dir)
|
|
if not out.is_absolute():
|
|
out = root / out
|
|
if out.suffix.lower() != "." + fmt:
|
|
raise Refused("--out %s does not end in .%s" % (out.name, fmt))
|
|
if out.exists() and not args.force:
|
|
raise Refused("exists: %s (--force replaces it, --out writes elsewhere)" % rel(out, root))
|
|
name = valid_name(args.style)
|
|
sdir = styles_dir(root)
|
|
ref_docx = sdir / (name + ".docx")
|
|
notes = []
|
|
if not ref_docx.exists():
|
|
if args.style_required:
|
|
raise Refused("no style %s in %s" % (name, STYLES_DIR.as_posix()))
|
|
notes.append("no style %s: used pandoc's default look" % name)
|
|
ref_docx = None
|
|
|
|
meta, body = prepare(src.read_text(encoding="utf-8-sig"), args.keep_links)
|
|
lo = soffice()
|
|
with tempfile.TemporaryDirectory(prefix="ckb-convert-") as tmp:
|
|
tmpd = Path(tmp)
|
|
md = tmpd / (src.stem + ".md")
|
|
md.write_text(body, encoding="utf-8")
|
|
metaf = tmpd / "meta.json"
|
|
metaf.write_text(json.dumps(meta, ensure_ascii=False), encoding="utf-8")
|
|
base = ["pandoc", str(md), "-f", "markdown-yaml_metadata_block+autolink_bare_uris",
|
|
"--metadata-file", str(metaf),
|
|
"--resource-path", "%s%s%s" % (src.parent, ";" if sys.platform == "win32" else ":", root)]
|
|
if "title" not in meta:
|
|
base += ["--metadata", "pagetitle=" + src.stem]
|
|
if args.toc:
|
|
base.append("--toc")
|
|
if args.number_sections:
|
|
base.append("--number-sections")
|
|
|
|
def docx_to(path):
|
|
cmd = base + ["-t", "docx", "-o", str(path)]
|
|
if ref_docx:
|
|
cmd += ["--reference-doc", str(ref_docx)]
|
|
return run(cmd)
|
|
|
|
via = "pandoc"
|
|
produced = tmpd / ("out." + fmt)
|
|
if fmt == "docx":
|
|
p = docx_to(produced)
|
|
elif fmt == "html":
|
|
css = sdir / (name + ".css")
|
|
cmd = base + ["-t", "html5", "--standalone", "-o", str(produced),
|
|
"--embed-resources" if version >= (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())
|