Skip to content

The agent that grows with you

feat: extend clean-room office skills toward full parity

Tekniumfad88cf1308e
diff --git a/skills/productivity/docx/SKILL.md b/skills/productivity/docx/SKILL.md
index ee18be6b796..78b2f4da435 100644
--- a/skills/productivity/docx/SKILL.md
+++ b/skills/productivity/docx/SKILL.md
@@ -1,13 +1,13 @@
---
name: docx
-description: Create, read, edit, and template Word .docx files.
-version: 1.0.0
+description: Create, read, edit, template, and review Word .docx files.
+version: 1.1.0
author: Nous Research
license: MIT
platforms: [linux, macos, windows]
metadata:
hermes:
- tags: [word, docx, documents, office, templates]
+ tags: [word, docx, documents, office, templates, revisions, comments]
category: productivity
related_skills: [pdf, xlsx, powerpoint]
---
@@ -15,24 +15,31 @@ metadata:
# Docx Skill
Create, read, edit, and template Microsoft Word `.docx` files with
-python-docx via four small CLIs. It handles text, styles, lists, tables,
-images, headers/footers, and `{{token}}` templating. It does not render
-documents to PDF, edit legacy `.doc` binaries, or accept/reject tracked
-changes (it only detects them — see Pitfalls).
+python-docx via small CLIs. It handles text, styles, lists, tables,
+images, headers/footers, `{{token}}` templating, tracked changes
+(list/accept/reject), comments (list/add/delete), TOC and page-number
+fields, and package health checks. It does not render documents itself
+(PDF needs LibreOffice — see Converting to PDF) or edit legacy `.doc`.
## When to Use
- The user asks to generate a Word document (report, letter, contract).
- You need the text, outline, styles, or embedded images of a `.docx`.
- You must change an existing `.docx`: replace text, edit table cells,
- insert/delete paragraphs, apply styles.
+ insert/delete paragraphs, apply styles, merge fragmented runs.
- You have a `.docx` template with `{{placeholders}}` to fill from data.
-- Not for: `.doc` (legacy), `.odt`, PDF conversion, or WYSIWYG layout work.
+- The document has tracked changes to review, accept, or reject.
+- You need to read reviewers' comments, or add/delete comments.
+- A `.docx` won't open or behaves oddly and you need corruption triage.
+- The document needs a table of contents or "Page X of Y" footers.
+- Not for: `.doc` (legacy), `.odt`, or WYSIWYG layout work.
## Prerequisites
- Python 3.10+ with `python-docx` installed:
- `pip install python-docx` (import name is `docx`).
+ `pip install python-docx` (import name is `docx`; lxml comes with it).
+- Comments `add` uses the native API on python-docx >= 1.2 and an XML
+ fallback on older versions — both are automatic.
- For image blocks: the image files must exist locally (PNG/JPEG).
## How to Run
@@ -45,6 +52,9 @@ python scripts/docx_create.py spec.json out.docx
python scripts/docx_read.py out.docx --text
python scripts/docx_edit.py replace out.docx --find old --replace new
python scripts/docx_template.py tpl.docx values.json filled.docx
+python scripts/docx_revisions.py list out.docx
+python scripts/docx_comments.py list out.docx
+python scripts/docx_validate.py out.docx
```
## Quick Reference
@@ -62,20 +72,31 @@ python scripts/docx_template.py tpl.docx values.json filled.docx
| Insert paragraph before index N | `docx_edit.py insert f.docx --index N --text X --style Normal` |
| Delete paragraph N | `docx_edit.py delete f.docx --index N` |
| Apply style to paragraph N | `docx_edit.py style f.docx --index N --style "Heading 1"` |
+| Merge equal-format adjacent runs | `docx_edit.py normalize f.docx -o out.docx` |
+| Insert TOC field before para N | `docx_edit.py toc f.docx --index N -o out.docx` |
+| "Page X of Y" footer fields | `docx_edit.py page-numbers f.docx` |
| Fill `{{tokens}}` | `docx_template.py tpl.docx values.json out.docx --strict` |
+| List revisions (id/author/date/text) | `docx_revisions.py list f.docx` |
+| Accept / reject all revisions | `docx_revisions.py accept-all f.docx -o out.docx` (or `reject-all`) |
+| Accept / reject one revision | `docx_revisions.py accept f.docx --id 3 -o out.docx` |
+| List comments (+anchored text) | `docx_comments.py list f.docx` |
+| Add comment anchored to text | `docx_comments.py add f.docx --target "phrase" --text "note" --author You` |
+| Delete comment by id | `docx_comments.py delete f.docx --id 0` |
+| Health-check the package | `docx_validate.py f.docx` (exit 1 on errors) |
## Procedure
1. **Create.** Write a JSON spec with `write_file`, then run
`scripts/docx_create.py`. The spec supports: `page` (size + margins in
- mm), `header`/`footer` strings, `styles` (custom paragraph styles with
+ mm), `header`/`footer` strings, `footer_page_numbers` (adds a
+ "Page X of Y" field footer), `styles` (custom paragraph styles with
font, size, bold/italic, hex `color`), and `blocks` — `heading`
(level 1-9), `paragraph` (either `text` or a `runs` list where each run
may set `bold`/`italic`/`underline`), `bullet_list`, `numbered_list`,
`table` (`header` row rendered bold, `rows`, optional built-in table
`style` such as `Table Grid`), `image` (`path`, optional `width_mm`),
- and `page_break`. The full spec format is documented at the top of
- `scripts/docx_create.py` — read it with `read_file` when composing.
+ `toc` (Table of Contents field), and `page_break`. The full spec
+ format is documented at the top of `scripts/docx_create.py`.
2. **Read.** Use `scripts/docx_read.py` with exactly one mode flag.
`--text` returns body paragraphs, all table cell text, and
header/footer text as JSON. `--structure` returns the heading outline
@@ -85,34 +106,72 @@ python scripts/docx_template.py tpl.docx values.json filled.docx
(nested included), headers and footers, and preserves run formatting;
add `--body-only` to skip headers/footers. Pass `-o out.docx` to keep
the original; omit it to edit in place. Paragraph indices for
- `insert`/`delete`/`style` refer to `--structure`/`--text` body order.
-4. **Template.** Put `{{name}}`-style tokens in the document (letters,
- digits, `_`, `.`, `-`; optional inner spaces like `{{ name }}` are
- accepted). Run `scripts/docx_template.py` with a JSON object of
- values. Use `--strict` to fail when tokens remain unfilled; the JSON
- output lists `filled` counts and `unfilled_tokens` either way.
-5. **Verify** (always): re-read the output with `--text` or
- `--structure` and confirm the expected content is present.
+ `insert`/`delete`/`style`/`toc` refer to `--structure`/`--text` body
+ order. Run `normalize` first on documents that came out of heavy Word
+ editing — it merges adjacent runs with identical formatting so later
+ find-replace matches reliably.
+4. **Review revisions.** `docx_revisions.py list` reports every `w:ins`
+ and `w:del` (id, author, date, affected text) anywhere in body,
+ tables, headers, or footers. `accept-all` / `reject-all` resolve them
+ in bulk; `accept`/`reject --id N` handles a single revision. Accept
+ keeps insertions and drops deleted text; reject does the reverse.
+5. **Comments.** `docx_comments.py list` returns each comment's id,
+ author, date, body text, and the document text it is anchored to.
+ `add --target "some phrase"` anchors a new comment to the first
+ occurrence of that phrase (runs are split as needed; formatting is
+ preserved). `delete --id N` removes the comment and its markers
+ without touching document text.
+6. **Template.** Put `{{name}}`-style tokens in the document. Run
+ `scripts/docx_template.py` with a JSON object of values. Use
+ `--strict` to fail when tokens remain unfilled; the JSON output lists
+ `filled` counts and `unfilled_tokens` either way.
+7. **Verify** (always): re-read the output with `--text` or
+ `--structure`, and run `docx_validate.py` on anything you produced
+ via revision/comment surgery.
+
+## Converting to PDF
+
+No script needed. When LibreOffice is installed, convert headlessly:
+
+```bash
+soffice --headless --convert-to pdf --outdir outdir/ file.docx
+```
+
+Check availability first (`command -v soffice || command -v
+libreoffice`). If neither exists, tell the user PDF conversion is
+unavailable in this environment rather than improvising — python-docx
+cannot render PDFs, and layout fidelity requires a real renderer.
## Pitfalls
-- **Tokens split across runs.** Word often fragments `{{name}}` into
- several runs. The replace helpers handle this by collapsing the runs;
- the replacement inherits the formatting of the run where the match
- starts. Mid-token formatting changes are therefore flattened.
-- **Tracked changes.** `--revisions` only *detects* insertions,
- deletions, format changes, and comments. Text extraction returns the
- as-is body (insertions included, deletions omitted, i.e. roughly the
- accepted view), but this skill cannot accept/reject revisions or read
- comment text. Say so to the user rather than guessing.
+- **Tokens split across runs.** Word often fragments text into several
+ runs. The replace helpers collapse matched runs (replacement inherits
+ the first run's formatting); running `docx_edit.py normalize` first
+ reduces fragmentation for all later edits.
+- **Revision coverage.** `docx_revisions.py` resolves run-level
+ insertions and deletions (the overwhelming majority). Paragraph-mark
+ and table-row revisions, format-change records, and moves are detected
+ by `--revisions` but not auto-resolved — see
+ `references/revisions-and-comments.md` and hand those to Word.
+- **Comment threading.** Replies and "resolved" status live in
+ `commentsExtended.xml`, which this skill ignores; comments it adds are
+ plain top-level comments.
+- **Field results are computed by Word.** `toc`, `page-numbers`, and the
+ `toc`/`footer_page_numbers` spec options write *field codes*.
+ Word/LibreOffice populates the actual entries and numbers when the
+ file is opened (Word may prompt to update fields); python-docx never
+ computes them, so placeholder text shows until then.
+- **Validation is a health check, not schema validation.**
+ `docx_validate.py` verifies the zip, required parts, relationship
+ targets, image magic bytes, and referenced styles. It is NOT XSD
+ validation — a file can pass and still contain XML Word dislikes.
- **Style names must exist.** Applying a style that isn't defined in the
document raises `KeyError`. Built-ins like `Heading 1`, `List Bullet`,
`List Number`, `Table Grid` exist in the default template; custom
styles must be declared in the create spec first.
- **Numbered lists restart.** `List Number` relies on Word's default
numbering; separate lists in one document may continue numbering
- instead of restarting. Acceptable for simple docs; warn users needing
- precise multi-list numbering.
+ instead of restarting. Warn users needing precise multi-list numbering.
- **Cell writes replace formatting.** `set-cell` uses `cell.text = ...`,
which resets runs in that cell to plain formatting.
- **Encoding.** All JSON specs/values files are read as UTF-8 explicitly;
@@ -126,8 +185,12 @@ python scripts/docx_template.py tpl.docx values.json filled.docx
- After create/edit/template, run `docx_read.py out.docx --text` and
check the expected strings appear (and old strings are gone).
+- After accept/reject, `docx_revisions.py list` should return `[]` (or
+ only the ids you intentionally left); after comment surgery,
+ `docx_comments.py list` should reflect the change and `--text` output
+ must be unchanged.
+- `docx_validate.py out.docx` exits 0 with `"ok": true` on a healthy
+ package — run it after any revision/comment/field manipulation.
- For templates run with `--strict`, or check `unfilled_tokens == []`.
- Structure checks: `--structure` should show the expected heading
outline and table shapes; `--styles` confirms custom styles applied.
-- A valid `.docx` opens with `Document(path)` without exception — the
- read script exiting 0 is itself a sanity check.
diff --git a/skills/productivity/docx/references/revisions-and-comments.md b/skills/productivity/docx/references/revisions-and-comments.md
new file mode 100644
index 00000000000..022db1ac3c0
--- /dev/null
+++ b/skills/productivity/docx/references/revisions-and-comments.md
@@ -0,0 +1,88 @@
+# Revisions and Comments — XML details
+
+Deep reference for `docx_revisions.py` and `docx_comments.py`. Read this
+when you need to reason about the raw WordprocessingML, extend the
+scripts, or debug an unusual document. Everyday use only needs SKILL.md.
+
+## Tracked changes (w:ins / w:del)
+
+Word records run-level tracked changes as wrapper elements inside a
+paragraph (`w:p`), in the `w` namespace
+`http://schemas.openxmlformats.org/wordprocessingml/2006/main`:
+
+```xml
+<w:p>
+ <w:r><w:t>Base </w:t></w:r>
+ <w:ins w:id="1" w:author="Editor" w:date="2026-01-02T03:04:05Z">
+ <w:r><w:t>inserted text</w:t></w:r>
+ </w:ins>
+ <w:del w:id="2" w:author="Editor" w:date="2026-01-02T03:04:05Z">
+ <w:r><w:delText>deleted text</w:delText></w:r>
+ </w:del>
+</w:p>
+```
+
+Key facts the script relies on:
+
+- Deleted text lives in `w:delText`, not `w:t` — that is why plain text
+ extraction naturally shows the "accepted" view (insertions visible,
+ deletions hidden).
+- Resolution semantics:
+ - accept `w:ins` → unwrap (move child runs up, drop the wrapper)
+ - reject `w:ins` → remove the wrapper and its contents
+ - accept `w:del` → remove the wrapper and its contents
+ - reject `w:del` → rename each `w:delText` to `w:t`, then unwrap
+- Revisions can appear anywhere block content is allowed: body, table
+ cells (nested tables too), headers, footers, text boxes. The script
+ iterates the body root plus every header/footer part root with
+ `root.iter(W+"ins", W+"del")`, which finds them at any depth.
+- `w:id` values are unique per revision *element*, but one logical edit
+ session may produce several elements. `accept`/`reject --id` acts on
+ exactly the element(s) carrying that id.
+
+Not handled by the script (detected by `docx_read.py --revisions` but
+left alone): paragraph-mark revisions (`w:rPr/w:ins` on `w:pPr`), table
+row insertions/deletions (`w:trPr/w:ins`), format-change records
+(`w:rPrChange`, `w:pPrChange`), and moves (`w:moveFrom`/`w:moveTo`).
+Moves are rare from typical editors; if present, treat the file with
+Word itself rather than guessing.
+
+## Comments
+
+Three cooperating pieces:
+
+1. **`word/comments.xml`** — one `w:comment` element per comment,
+ carrying `w:id`, `w:author`, `w:initials`, `w:date`, and body
+ paragraphs. Related from document.xml via the relationship type
+ `.../comments` and content type
+ `application/vnd...wordprocessingml.comments+xml` (also needs a
+ `[Content_Types].xml` override — python-docx's part machinery adds it
+ when the part is registered).
+2. **Range markers in the story** — `w:commentRangeStart w:id="N"`
+ before the anchored runs, `w:commentRangeEnd w:id="N"` after them.
+3. **The reference run** — a `w:r` containing `w:commentReference
+ w:id="N"`, placed right after the range end; it ties the balloon to
+ the location.
+
+`docx_comments.py` behavior:
+
+- **list / delete** always work at the XML level, so they handle files
+ from any producer. `anchored_text` is reconstructed by walking each
+ part root in document order and collecting `w:t` text between the
+ start and end markers for each id.
+- **add** first isolates the target text into whole runs. If the match
+ starts or ends mid-run, the run is split at the boundary (the split
+ copies `w:rPr`, so formatting is preserved). Then:
+ - python-docx >= 1.2: the native `document.add_comment(runs, ...)`
+ API is used (it creates the comments part, markers, and reference
+ run itself).
+ - older versions or `--xml`: the script builds `word/comments.xml`,
+ registers the part + relationship through the opc layer, and
+ inserts the markers/reference manually.
+- Deleting a comment removes the `w:comment` element and all three
+ marker kinds for that id; the anchored document text is untouched.
+
+Modern Word also writes `commentsExtended.xml` (threading/resolved
+state). The scripts neither read nor produce it: replies and "resolved"
+flags are invisible here, and comments added by this skill are plain
+top-level comments.
diff --git a/skills/productivity/docx/scripts/docx_comments.py b/skills/productivity/docx/scripts/docx_comments.py
new file mode 100644
index 00000000000..958b337b5e8
--- /dev/null
+++ b/skills/productivity/docx/scripts/docx_comments.py
@@ -0,0 +1,289 @@
+#!/usr/bin/env python3
+# MIT License. Part of the Hermes docx skill.
+"""List, add, and delete comments in a .docx.
+
+Subcommands:
+ list JSON per comment: id, author, initials, date, text, anchored_text
+ add add a comment anchored to the first occurrence of --target
+ delete remove a comment (and its range markers) by --id
+
+Examples:
+ docx_comments.py list report.docx
+ docx_comments.py add report.docx --target "Q3 revenue" \
+ --text "Needs a source" --author "Reviewer" -o out.docx
+ docx_comments.py delete report.docx --id 0 -o out.docx
+
+Uses the native python-docx comments API (>= 1.2) when available; falls
+back to building word/comments.xml and the range markers directly for
+older versions (or when --xml is passed). Listing and deletion always
+work at the XML level so they handle documents from any producer.
+"""
+from __future__ import annotations
+
+import argparse
+import datetime as _dt
+import json
+import sys
+from copy import deepcopy
+
+from docx import Document
+from docx.opc.constants import RELATIONSHIP_TYPE as RT
+from lxml import etree
+
+from docx_common import iter_part_roots
+
+W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
+COMMENTS_CT = ("application/vnd.openxmlformats-officedocument"
+ ".wordprocessingml.comments+xml")
+
+
+def q(tag: str) -> str:
+ return f"{{{W}}}{tag}"
+
+
+# ---------------------------------------------------------------- reading
+
+def _comments_root(doc):
+ """Return the XML root of the comments part, or None."""
+ for rel in doc.part.rels.values():
+ if rel.reltype == RT.COMMENTS:
+ part = rel.target_part
+ el = getattr(part, "_element", None)
+ if el is not None:
+ return el
+ return etree.fromstring(part.blob)
+ return None
+
+
+def _anchored_texts(doc) -> dict:
+ """Map comment id -> document text between its range markers."""
+ anchored: dict[str, list[str]] = {}
+ for root in iter_part_roots(doc):
+ active: set[str] = set()
+ for el in root.iter():
+ if el.tag == q("commentRangeStart"):
+ cid = el.get(q("id"))
+ active.add(cid)
+ anchored.setdefault(cid, [])
+ elif el.tag == q("commentRangeEnd"):
+ active.discard(el.get(q("id")))
+ elif el.tag == q("t") and active:
+ for cid in active:
+ anchored[cid].append(el.text or "")
+ return {cid: "".join(parts) for cid, parts in anchored.items()}
+
+
+def list_comments(doc) -> list:
+ root = _comments_root(doc)
+ if root is None:
+ return []
+ anchored = _anchored_texts(doc)
+ out = []
+ for c in root.iter(q("comment")):
+ cid = c.get(q("id"))
+ text = "\n".join(
+ "".join(t.text or "" for t in p.iter(q("t")))
+ for p in c.iter(q("p")))
+ out.append({"id": cid, "author": c.get(q("author")),
+ "initials": c.get(q("initials")),
+ "date": c.get(q("date")), "text": text,
+ "anchored_text": anchored.get(cid, "")})
+ return out
+
+
+# ---------------------------------------------------------------- anchoring
+
+def _split_run(para, run_el, offset: int):
+ """Split a run element at text offset; return the new right-hand run."""
+ text = "".join(t.text or "" for t in run_el.iter(q("t")))
+ right = deepcopy(run_el)
+ run_el.addnext(right)
+ for el, s in ((run_el, text[:offset]), (right, text[offset:])):
+ for t in list(el.iter(q("t"))):
+ el.remove(t)
+ t = etree.SubElement(el, q("t"))
+ t.text = s
+ t.set("{http://www.w3.org/XML/1998/namespace}space", "preserve")
+ return right
+
+
+def find_anchor_runs(doc, target: str):
+ """Isolate `target`'s first occurrence into whole runs; return them."""
+ from docx_common import iter_all_paragraphs
+ for para in iter_all_paragraphs(doc):
+ full = para.text
+ start = full.find(target)
+ if start < 0:
+ continue
+ end = start + len(target)
+ pos = 0
+ covered = []
+ for run_el in para._p.iter(q("r")):
+ rtext = "".join(t.text or "" for t in run_el.iter(q("t")))
+ r_start, r_end = pos, pos + len(rtext)
+ pos = r_end
+ if r_end <= start or r_start >= end:
+ continue
+ if r_start < start: # split off the left part
+ run_el = _split_run(para, run_el, start - r_start)
+ r_start = start
+ if r_end > end: # split off the right part
+ _split_run(para, run_el, end - r_start)
+ covered.append(run_el)
+ return para, covered
+ return None, []
+
+
+# ---------------------------------------------------------------- adding
+
+def _next_id(doc) -> int:
+ root = _comments_root(doc)
+ if root is None:
+ return 0
+ ids = [int(c.get(q("id"), "0")) for c in root.iter(q("comment"))
+ if c.get(q("id"), "").isdigit()]
+ return max(ids) + 1 if ids else 0
+
+
+def add_comment_native(doc, runs, text, author, initials):
+ from docx.text.run import Run
+ run_objs = [Run(r, None) for r in runs]
+ comment = doc.add_comment(run_objs, text=text, author=author,
+ initials=initials or "")
+ return str(comment.comment_id)
+
+
+def add_comment_xml(doc, runs, text, author, initials) -> str:
+ cid = str(_next_id(doc))
+ root = _comments_root(doc)
+ if root is None:
+ root = etree.fromstring(
+ f'<w:comments xmlns:w="{W}"/>'.encode("utf-8"))
+ from docx.opc.packuri import PackURI
+ from docx.opc.part import Part
+ blob = etree.tostring(root, xml_declaration=True,
+ encoding="UTF-8", standalone=True)
+ part = Part(PackURI("/word/comments.xml"), COMMENTS_CT, blob,
+ doc.part.package)
+ doc.part.relate_to(part, RT.COMMENTS)
+ # keep a live element on the part so edits reach save()
+ part._element = root
+ part.blob_ = None
+
+ def _blob(self=part):
+ return etree.tostring(self._element, xml_declaration=True,
+ encoding="UTF-8", standalone=True)
+ part.__class__ = type("CommentsXmlPart", (Part,),
+ {"blob": property(lambda self: _blob(self))})
+ now = _dt.datetime.now(_dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+ comment = etree.SubElement(root, q("comment"))
+ comment.set(q("id"), cid)
+ comment.set(q("author"), author)
+ if initials:
+ comment.set(q("initials"), initials)
+ comment.set(q("date"), now)
+ p = etree.SubElement(comment, q("p"))
+ r = etree.SubElement(p, q("r"))
+ t = etree.SubElement(r, q("t"))
+ t.text = text
+ # range markers around the anchor runs + reference run after them
+ first, last = runs[0], runs[-1]
+ start = first.makeelement(q("commentRangeStart"), {q("id"): cid})
+ first.addprevious(start)
+ end = last.makeelement(q("commentRangeEnd"), {q("id"): cid})
+ last.addnext(end)
+ ref_run = last.makeelement(q("r"), {})
+ ref = etree.SubElement(ref_run, q("commentReference"))
+ ref.set(q("id"), cid)
+ end.addnext(ref_run)
+ return cid
+
+
+# ---------------------------------------------------------------- deleting
+
+def delete_comment(doc, cid: str) -> bool:
+ root = _comments_root(doc)
+ found = False
+ if root is not None:
+ for c in list(root.iter(q("comment"))):
+ if c.get(q("id")) == cid:
+ c.getparent().remove(c)
+ found = True
+ for part_root in iter_part_roots(doc):
+ for tag in ("commentRangeStart", "commentRangeEnd",
+ "commentReference"):
+ for el in list(part_root.iter(q(tag))):
+ if el.get(q("id")) == cid:
+ parent = el.getparent()
+ # remove the wrapping run for reference marks
+ if tag == "commentReference" and parent.tag == q("r"):
+ parent.getparent().remove(parent)
+ else:
+ parent.remove(el)
+ found = True
+ return found
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser(
+ description="List, add, or delete comments in a .docx.")
+ sub = ap.add_subparsers(dest="cmd", required=True)
+
+ p = sub.add_parser("list", help="list comments as JSON")
+ p.add_argument("path", help="input .docx")
+
+ p = sub.add_parser("add", help="add a comment anchored to text")
+ p.add_argument("path", help="input .docx")
+ p.add_argument("-o", "--output", help="output path (default: in place)")
+ p.add_argument("--target", required=True,
+ help="anchor: first occurrence of this text")
+ p.add_argument("--text", required=True, help="comment body")
+ p.add_argument("--author", default="Hermes")
+ p.add_argument("--initials", default="")
+ p.add_argument("--xml", action="store_true",
+ help="force the XML fallback (skip native API)")
+
+ p = sub.add_parser("delete", help="delete a comment by id")
+ p.add_argument("path", help="input .docx")
+ p.add_argument("-o", "--output", help="output path (default: in place)")
+ p.add_argument("--id", required=True, help="comment id")
+
+ args = ap.parse_args()
+ doc = Document(args.path)
+
+ if args.cmd == "list":
+ print(json.dumps({"ok": True, "comments": list_comments(doc)},
+ ensure_ascii=False))
+ return 0
+
+ if args.cmd == "add":
+ para, runs = find_anchor_runs(doc, args.target)
+ if not runs:
+ print(json.dumps({"ok": False,
+ "error": f"target not found: {args.target}"}))
+ return 1
+ native = hasattr(doc, "add_comment") and not args.xml
+ if native:
+ cid = add_comment_native(doc, runs, args.text, args.author,
+ args.initials)
+ else:
+ cid = add_comment_xml(doc, runs, args.text, args.author,
+ args.initials)
+ result = {"ok": True, "comment_id": cid,
+ "native_api": native, "anchored_to": args.target}
+ else: # delete
+ if not delete_comment(doc, args.id):
+ print(json.dumps({"ok": False,
+ "error": f"no comment with id {args.id}"}))
+ return 1
+ result = {"ok": True, "deleted_id": args.id}
+
+ out = args.output or args.path
+ doc.save(out)
+ result["output"] = out
+ print(json.dumps(result, ensure_ascii=False))
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/skills/productivity/docx/scripts/docx_common.py b/skills/productivity/docx/scripts/docx_common.py
index 560f0327969..2745153a374 100644
--- a/skills/productivity/docx/scripts/docx_common.py
+++ b/skills/productivity/docx/scripts/docx_common.py
@@ -34,6 +34,21 @@ def _iter_table(table):
yield from _iter_table(nested)
+def iter_part_roots(doc):
+ """Yield the XML root of the body plus every header/footer part."""
+ yield doc.element.body
+ seen = set()
+ for section in doc.sections:
+ for part in (
+ section.header, section.footer,
+ section.first_page_header, section.first_page_footer,
+ section.even_page_header, section.even_page_footer,
+ ):
+ if part is not None and id(part._element) not in seen:
+ seen.add(id(part._element))
+ yield part._element
+
+
def replace_in_paragraph(para, old: str, new: str) -> int:
"""Replace `old` with `new` in a paragraph, preserving run formatting.
diff --git a/skills/productivity/docx/scripts/docx_create.py b/skills/productivity/docx/scripts/docx_create.py
index 00ce80c2047..ea507b941c1 100644
--- a/skills/productivity/docx/scripts/docx_create.py
+++ b/skills/productivity/docx/scripts/docx_create.py
@@ -26,9 +26,15 @@ Spec (JSON object):
"rows": [["1", "2"]], "style": "Light Grid Accent 1",
"header_bold": true},
{"type": "image", "path": "pic.png", "width_mm": 60},
- {"type": "page_break"}
+ {"type": "page_break"},
+ {"type": "toc"}
]
}
+
+Extras: `"footer_page_numbers": true` at the top level adds a
+"Page X of Y" footer built from PAGE/NUMPAGES fields, and a `toc` block
+inserts a Table of Contents field. Field results are computed by
+Word/LibreOffice when the file is opened, not by python-docx.
"""
from __future__ import annotations
@@ -122,6 +128,12 @@ def add_block(doc, block: dict) -> None:
doc.add_picture(block["path"], width=width)
elif btype == "page_break":
doc.add_paragraph().add_run().add_break(WD_BREAK.PAGE)
+ elif btype == "toc":
+ from docx_edit import _add_field
+ para = doc.add_paragraph()
+ _add_field(para, r' TOC \o "1-3" \h \z \u ',
+ "Table of contents - open in Word/LibreOffice and "
+ "update fields to populate.")
else:
raise ValueError(f"unknown block type: {btype}")
@@ -148,6 +160,13 @@ def main() -> int:
doc.sections[0].footer.paragraphs[0].text = spec["footer"]
for block in spec.get("blocks", []):
add_block(doc, block)
+ if spec.get("footer_page_numbers"):
+ from docx_edit import _add_field
+ para = doc.sections[0].footer.paragraphs[0]
+ para.add_run("Page ")
+ _add_field(para, " PAGE ", "1")
+ para.add_run(" of ")
+ _add_field(para, " NUMPAGES ", "1")
doc.save(args.output)
print(json.dumps({"ok": True, "output": args.output,
"blocks": len(spec.get("blocks", []))}))
diff --git a/skills/productivity/docx/scripts/docx_edit.py b/skills/productivity/docx/scripts/docx_edit.py
index 90d70ade4aa..7b7804aa5c3 100644
--- a/skills/productivity/docx/scripts/docx_edit.py
+++ b/skills/productivity/docx/scripts/docx_edit.py
@@ -8,6 +8,9 @@ Subcommands:
insert insert a paragraph before a given body paragraph index
delete delete a body paragraph by index
style apply a paragraph style to a body paragraph by index
+ normalize merge adjacent runs with identical formatting
+ toc insert a Table of Contents field at a body paragraph index
+ page-numbers add "Page X of Y" (PAGE/NUMPAGES fields) to the footer
Examples:
docx_edit.py replace in.docx --find old --replace new -o out.docx
@@ -15,6 +18,13 @@ Examples:
docx_edit.py insert in.docx --index 3 --text "New para" --style Normal
docx_edit.py delete in.docx --index 3
docx_edit.py style in.docx --index 0 --style "Heading 1"
+ docx_edit.py normalize in.docx -o out.docx
+ docx_edit.py toc in.docx --index 1 -o out.docx
+ docx_edit.py page-numbers in.docx -o out.docx
+
+Field results (TOC entries, page numbers) are computed by Word or
+LibreOffice when the document is opened, not by python-docx; until then
+the fields show placeholder text.
"""
from __future__ import annotations
@@ -26,6 +36,12 @@ from docx import Document
from docx_common import iter_all_paragraphs, replace_in_paragraph
+W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
+
+
+def _q(tag: str) -> str:
+ return f"{{{W}}}{tag}"
+
def cmd_replace(doc, args) -> dict:
n = 0
@@ -62,6 +78,90 @@ def cmd_style(doc, args) -> dict:
return {"index": args.index, "style": args.style}
+def _run_format_key(r_el) -> str:
+ """Canonical string for a run's w:rPr (None when absent)."""
+ from lxml import etree
+ rpr = r_el.find(_q("rPr"))
+ return "" if rpr is None else etree.tostring(rpr).decode("utf-8")
+
+
+def cmd_normalize(doc) -> dict:
+ """Merge adjacent sibling runs with identical formatting."""
+ merged = 0
+ for para in iter_all_paragraphs(doc):
+ prev = None
+ for r_el in list(para._p):
+ if r_el.tag != _q("r"):
+ prev = None
+ continue
+ # only merge plain-text runs (no breaks, tabs, drawings...)
+ kids = {c.tag for c in r_el} - {_q("rPr"), _q("t")}
+ if kids:
+ prev = None
+ continue
+ if (prev is not None
+ and _run_format_key(prev) == _run_format_key(r_el)):
+ pt = prev.find(_q("t"))
+ ct = r_el.find(_q("t"))
+ if pt is None:
+ pt = prev.makeelement(_q("t"), {})
+ prev.append(pt)
+ pt.text = (pt.text or "") + ((ct.text or "")
+ if ct is not None else "")
+ pt.set("{http://www.w3.org/XML/1998/namespace}space",
+ "preserve")
+ r_el.getparent().remove(r_el)
+ merged += 1
+ else:
+ prev = r_el
+ return {"runs_merged": merged}
+
+
+def _add_field(para, instr: str, placeholder: str) -> None:
+ """Append a complex field (begin/instrText/separate/result/end)."""
+ p = para._p
+ for ftype, extra in (("begin", None), (None, instr),
+ ("separate", None), (None, placeholder),
+ ("end", None)):
+ r = p.makeelement(_q("r"), {})
+ p.append(r)
+ if ftype is not None:
+ fld = r.makeelement(_q("fldChar"), {_q("fldCharType"): ftype})
+ r.append(fld)
+ elif extra is instr:
+ it = r.makeelement(_q("instrText"), {})
+ it.set("{http://www.w3.org/XML/1998/namespace}space", "preserve")
+ it.text = instr
+ r.append(it)
+ else:
+ t = r.makeelement(_q("t"), {})
+ t.text = extra
+ r.append(t)
+
+
+def cmd_toc(doc, args) -> dict:
+ paras = doc.paragraphs
+ if args.index < len(paras):
+ para = paras[args.index].insert_paragraph_before("")
+ else:
+ para = doc.add_paragraph("")
+ _add_field(para, r' TOC \o "1-3" \h \z \u ',
+ "Table of contents - open in Word/LibreOffice and update "
+ "fields to populate.")
+ return {"toc_inserted_at": args.index}
+
+
+def cmd_page_numbers(doc, args) -> dict:
+ footer = doc.sections[0].footer
+ para = footer.paragraphs[0] if footer.paragraphs \
+ else footer.add_paragraph()
+ para.add_run("Page ")
+ _add_field(para, " PAGE ", "1")
+ para.add_run(" of ")
+ _add_field(para, " NUMPAGES ", "1")
+ return {"footer_fields": ["PAGE", "NUMPAGES"]}
+
+
def main() -> int:
ap = argparse.ArgumentParser(description="Edit a .docx file.")
sub = ap.add_subparsers(dest="cmd", required=True)
@@ -100,6 +200,19 @@ def main() -> int:
p.add_argument("--index", type=int, required=True)
p.add_argument("--style", required=True)
+ p = sub.add_parser("normalize",
+ help="merge adjacent runs with identical formatting")
+ common(p)
+
+ p = sub.add_parser("toc", help="insert a TOC field (Word computes it)")
+ common(p)
+ p.add_argument("--index", type=int, default=0,
+ help="body paragraph index to insert before (default 0)")
+
+ p = sub.add_parser("page-numbers",
+ help="add PAGE/NUMPAGES fields to the footer")
+ common(p)
+
args = ap.parse_args()
doc = Document(args.path)
@@ -117,6 +230,12 @@ def main() -> int:
result = cmd_insert(doc, args)
elif args.cmd == "delete":
result = cmd_delete(doc, args)
+ elif args.cmd == "normalize":
+ result = cmd_normalize(doc)
+ elif args.cmd == "toc":
+ result = cmd_toc(doc, args)
+ elif args.cmd == "page-numbers":
+ result = cmd_page_numbers(doc, args)
else:
result = cmd_style(doc, args)
diff --git a/skills/productivity/docx/scripts/docx_revisions.py b/skills/productivity/docx/scripts/docx_revisions.py
new file mode 100644
index 00000000000..70aff305692
--- /dev/null
+++ b/skills/productivity/docx/scripts/docx_revisions.py
@@ -0,0 +1,147 @@
+#!/usr/bin/env python3
+# MIT License. Part of the Hermes docx skill.
+"""Inspect and resolve tracked changes (w:ins / w:del) in a .docx.
+
+Subcommands:
+ list JSON list of revisions: id, author, date, type, text
+ accept-all accept every insertion and deletion
+ reject-all reject every insertion and deletion
+ accept accept one revision by --id
+ reject reject one revision by --id
+
+Examples:
+ docx_revisions.py list report.docx
+ docx_revisions.py accept-all report.docx -o accepted.docx
+ docx_revisions.py reject report.docx --id 3 -o out.docx
+
+Semantics (direct XML manipulation, python-docx oxml layer):
+ accept w:ins -> unwrap (keep inserted runs) reject w:ins -> remove
+ accept w:del -> remove reject w:del -> restore
+ (restore = w:delText tags renamed to w:t, wrapper unwrapped)
+
+Covers run-level insertions/deletions anywhere in body, tables (nested
+included), headers and footers. Row/paragraph-mark revisions and format
+changes (w:rPrChange etc.) are reported by docx_read.py --revisions but
+not resolved here.
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+
+from docx import Document
+
+from docx_common import iter_part_roots
+
+W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
+
+
+def q(tag: str) -> str:
+ return f"{{{W}}}{tag}"
+
+
+INS, DEL = q("ins"), q("del")
+
+
+def _iter_revision_elements(doc):
+ """Yield every w:ins / w:del element across body, headers, footers."""
+ for root in iter_part_roots(doc):
+ for el in root.iter(INS, DEL):
+ yield el
+
+
+def _rev_text(el) -> str:
+ tag = q("delText") if el.tag == DEL else q("t")
+ return "".join(t.text or "" for t in el.iter(tag))
+
+
+def _rev_record(el) -> dict:
+ return {
+ "id": el.get(q("id")),
+ "author": el.get(q("author")),
+ "date": el.get(q("date")),
+ "type": "insertion" if el.tag == INS else "deletion",
+ "text": _rev_text(el),
+ }
+
+
+def _unwrap(el) -> None:
+ """Replace `el` with its children, keeping document order."""
+ parent = el.getparent()
+ idx = list(parent).index(el)
+ for child in list(el):
+ parent.insert(idx, child)
+ idx += 1
+ parent.remove(el)
+
+
+def _apply(el, accept: bool) -> None:
+ if el.getparent() is None: # already detached via an outer wrapper
+ return
+ if el.tag == INS:
+ if accept:
+ _unwrap(el)
+ else:
+ el.getparent().remove(el)
+ else: # w:del
+ if accept:
+ el.getparent().remove(el)
+ else:
+ for dt in list(el.iter(q("delText"))):
+ dt.tag = q("t")
+ _unwrap(el)
+
+
+def resolve(doc, accept: bool, rev_id: str | None = None) -> int:
+ targets = [el for el in _iter_revision_elements(doc)
+ if rev_id is None or el.get(q("id")) == rev_id]
+ for el in targets:
+ _apply(el, accept)
+ return len(targets)
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser(
+ description="List, accept, or reject tracked changes in a .docx.")
+ sub = ap.add_subparsers(dest="cmd", required=True)
+
+ def common(p, out=True):
+ p.add_argument("path", help="input .docx")
+ if out:
+ p.add_argument("-o", "--output",
+ help="output path (default: overwrite input)")
+
+ common(sub.add_parser("list", help="list revisions as JSON"), out=False)
+ common(sub.add_parser("accept-all", help="accept every revision"))
+ common(sub.add_parser("reject-all", help="reject every revision"))
+ for name in ("accept", "reject"):
+ p = sub.add_parser(name, help=f"{name} one revision by id")
+ common(p)
+ p.add_argument("--id", required=True, help="revision id (w:id)")
+
+ args = ap.parse_args()
+ doc = Document(args.path)
+
+ if args.cmd == "list":
+ revs = [_rev_record(el) for el in _iter_revision_elements(doc)]
+ print(json.dumps({"ok": True, "revisions": revs}, ensure_ascii=False))
+ return 0
+
+ accept = args.cmd in ("accept-all", "accept")
+ rev_id = getattr(args, "id", None)
+ n = resolve(doc, accept, rev_id)
+ if rev_id is not None and n == 0:
+ print(json.dumps({"ok": False,
+ "error": f"no revision with id {rev_id}"}))
+ return 1
+ out = args.output or args.path
+ doc.save(out)
+ print(json.dumps({"ok": True, "output": out, "resolved": n,
+ "action": "accept" if accept else "reject"},
+ ensure_ascii=False))
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/skills/productivity/docx/scripts/docx_validate.py b/skills/productivity/docx/scripts/docx_validate.py
new file mode 100644
index 00000000000..91350a44754
--- /dev/null
+++ b/skills/productivity/docx/scripts/docx_validate.py
@@ -0,0 +1,156 @@
+#!/usr/bin/env python3
+# MIT License. Part of the Hermes docx skill.
+"""Health-check a .docx package and report issues as JSON.
+
+Usage: docx_validate.py file.docx
+
+Checks (health-check tier, NOT full XSD schema validation):
+ - the file is a readable zip and python-docx can open it
+ - required package parts exist ([Content_Types].xml, document.xml)
+ - every relationship in every .rels file resolves to a part in the
+ package (dangling image/hyperlink/etc. rels are reported; external
+ targets such as hyperlinks are skipped)
+ - r:embed / r:id references in document.xml resolve to relationships
+ - embedded images are non-empty and start with known magic bytes
+ (PNG/JPEG/GIF/BMP/TIFF/EMF/WMF/SVG); no PIL required
+ - paragraph and run style ids referenced by the document exist in
+ styles.xml
+
+Output: {"ok": bool, "issues": [{"severity": "error"|"warning", ...}]}
+Exit code 1 when any error-severity issue is found (warnings exit 0).
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import posixpath
+import sys
+import zipfile
+
+from lxml import etree
+
+W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
+R = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
+PR = "http://schemas.openxmlformats.org/package/2006/relationships"
+
+IMAGE_MAGIC = (
+ b"\x89PNG\r\n\x1a\n", b"\xff\xd8\xff", b"GIF87a", b"GIF89a",
+ b"BM", b"II*\x00", b"MM\x00*",
+ b"\x01\x00\x00\x00", # EMF
+ b"\xd7\xcd\xc6\x9a", b"\x01\x00\x09\x00", # WMF variants
+ b"<?xml", b"<svg",
+)
+
+
+def _issue(issues, severity, code, detail):
+ issues.append({"severity": severity, "code": code, "detail": detail})
+
+
+def _rel_target(base_part: str, target: str) -> str:
+ base_dir = posixpath.dirname(base_part)
+ return posixpath.normpath(posixpath.join(base_dir, target)).lstrip("/")
+
+
+def validate(path: str) -> dict:
+ issues: list[dict] = []
+
+ try:
+ zf = zipfile.ZipFile(path)
+ except (OSError, zipfile.BadZipFile) as exc:
+ _issue(issues, "error", "not-a-zip", str(exc))
+ return {"ok": False, "issues": issues}
+
+ names = set(zf.namelist())
+ bad = zf.testzip()
+ if bad is not None:
+ _issue(issues, "error", "corrupt-member", f"CRC check failed: {bad}")
+
+ for required in ("[Content_Types].xml", "word/document.xml"):
+ if required not in names:
+ _issue(issues, "error", "missing-part",
+ f"required part absent: {required}")
+ if issues and any(i["severity"] == "error" for i in issues):
+ return {"ok": False, "issues": issues}
+
+ # --- relationships resolve ------------------------------------------
+ rel_ids_by_source: dict[str, dict] = {}
+ for rels_name in [n for n in names if n.endswith(".rels")]:
+ try:
+ root = etree.fromstring(zf.read(rels_name))
+ except etree.XMLSyntaxError as exc:
+ _issue(issues, "error", "bad-rels-xml", f"{rels_name}: {exc}")
+ continue
+ source_part = posixpath.normpath(
+ posixpath.join(posixpath.dirname(rels_name), ".."))
+ source_part = "" if source_part == "." else source_part
+ ids = {}
+ for rel in root.iter(f"{{{PR}}}Relationship"):
+ rid, target = rel.get("Id"), rel.get("Target", "")
+ mode = rel.get("TargetMode", "Internal")
+ ids[rid] = target
+ if mode == "External":
+ continue
+ resolved = _rel_target(source_part + "/x" if source_part
+ else "x", target)
+ if resolved not in names:
+ _issue(issues, "error", "dangling-rel",
+ f"{rels_name}: {rid} -> {target} (missing part)")
+ rel_ids_by_source[source_part or "_package"] = ids
+
+ # --- r:id / r:embed references in document.xml -----------------------
+ doc_root = etree.fromstring(zf.read("word/document.xml"))
+ doc_rels = rel_ids_by_source.get("word", {})
+ for el in doc_root.iter():
+ for attr in (f"{{{R}}}id", f"{{{R}}}embed", f"{{{R}}}link"):
+ rid = el.get(attr)
+ if rid and rid not in doc_rels:
+ _issue(issues, "error", "unresolved-reference",
+ f"document.xml references {rid} with no relationship")
+
+ # --- embedded images decode ------------------------------------------
+ for name in [n for n in names if n.startswith("word/media/")]:
+ data = zf.read(name)
+ if not data:
+ _issue(issues, "error", "empty-image", name)
+ elif not any(data.startswith(m) for m in IMAGE_MAGIC):
+ _issue(issues, "warning", "unknown-image-format",
+ f"{name}: unrecognized magic bytes")
+
+ # --- styles referenced exist ------------------------------------------
+ defined = set()
+ if "word/styles.xml" in names:
+ styles_root = etree.fromstring(zf.read("word/styles.xml"))
+ defined = {s.get(f"{{{W}}}styleId")
+ for s in styles_root.iter(f"{{{W}}}style")}
+ for tag, attr in ((f"{{{W}}}pStyle", f"{{{W}}}val"),
+ (f"{{{W}}}rStyle", f"{{{W}}}val"),
+ (f"{{{W}}}tblStyle", f"{{{W}}}val")):
+ for el in doc_root.iter(tag):
+ sid = el.get(attr)
+ if sid and sid not in defined:
+ _issue(issues, "error", "missing-style",
+ f"style id referenced but not defined: {sid}")
+
+ # --- python-docx can open it ------------------------------------------
+ try:
+ from docx import Document
+ Document(path)
+ except Exception as exc: # noqa: BLE001 - triage tool, report anything
+ _issue(issues, "error", "python-docx-open-failed", str(exc))
+
+ ok = not any(i["severity"] == "error" for i in issues)
+ return {"ok": ok, "issues": issues}
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser(
+ description="Health-check a .docx (not XSD schema validation).")
+ ap.add_argument("path", help="the .docx file to check")
+ args = ap.parse_args()
+ report = validate(args.path)
+ print(json.dumps(report, ensure_ascii=False))
+ return 0 if report["ok"] else 1
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/skills/productivity/docx/tests/test_docx_skill.py b/skills/productivity/docx/tests/test_docx_skill.py
index cace05dec32..cb5c6aea82a 100644
--- a/skills/productivity/docx/tests/test_docx_skill.py
+++ b/skills/productivity/docx/tests/test_docx_skill.py
@@ -232,3 +232,294 @@ class TestTemplate:
assert proc.returncode == 1
payload = json.loads(proc.stdout.decode("utf-8"))
assert payload["unfilled_tokens"] == ["gone"]
+
+
+# --------------------------------------------------------------- new parity
+
+W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
+
+
+def q(tag: str) -> str:
+ return f"{{{W}}}{tag}"
+
+
+def run_raw(script: str, *args: str):
+ env = dict(os.environ, LC_ALL="C", PYTHONIOENCODING="utf-8")
+ return subprocess.run(
+ [sys.executable, str(SCRIPTS / script), *map(str, args)],
+ capture_output=True, env=env)
+
+
+def _add_ins(para, rev_id: int, text: str, author="Editor"):
+ from lxml import etree
+ ins = etree.SubElement(para._p, q("ins"))
+ ins.set(q("id"), str(rev_id))
+ ins.set(q("author"), author)
+ ins.set(q("date"), "2026-01-02T03:04:05Z")
+ r = etree.SubElement(ins, q("r"))
+ t = etree.SubElement(r, q("t"))
+ t.text = text
+ t.set("{http://www.w3.org/XML/1998/namespace}space", "preserve")
+
+
+def _add_del(para, rev_id: int, text: str, author="Editor"):
+ from lxml import etree
+ dele = etree.SubElement(para._p, q("del"))
+ dele.set(q("id"), str(rev_id))
+ dele.set(q("author"), author)
+ dele.set(q("date"), "2026-01-02T03:04:05Z")
+ r = etree.SubElement(dele, q("r"))
+ t = etree.SubElement(r, q("delText"))
+ t.text = text
+ t.set("{http://www.w3.org/XML/1998/namespace}space", "preserve")
+
+
+def tracked(tmp_path: Path) -> Path:
+ """Doc with a tracked insertion + deletion in body AND in a table."""
+ doc = Document()
+ p = doc.add_paragraph("Base ")
+ _add_ins(p, 1, "ADDED")
+ _add_del(p, 2, "REMOVED")
+ table = doc.add_table(rows=1, cols=1)
+ cp = table.cell(0, 0).paragraphs[0]
+ cp.add_run("Cell ")
+ _add_ins(cp, 3, "CELLADD")
+ _add_del(cp, 4, "CELLGONE")
+ path = tmp_path / "tracked.docx"
+ doc.save(str(path))
+ return path
+
+
+class TestRevisions:
+ def test_list(self, tracked: Path):
+ res = run("docx_revisions.py", "list", tracked)
+ revs = {r["id"]: r for r in res["revisions"]}
+ assert len(revs) == 4
+ assert revs["1"] == {"id": "1", "author": "Editor",
+ "date": "2026-01-02T03:04:05Z",
+ "type": "insertion", "text": "ADDED"}
+ assert revs["2"]["type"] == "deletion"
+ assert revs["2"]["text"] == "REMOVED"
+ assert revs["3"]["text"] == "CELLADD" # inside table
+ assert revs["4"]["type"] == "deletion"
+
+ def test_accept_all(self, tracked: Path, tmp_path: Path):
+ out = tmp_path / "acc.docx"
+ res = run("docx_revisions.py", "accept-all", tracked, "-o", out)
+ assert res["resolved"] == 4
+ doc = Document(str(out))
+ assert doc.paragraphs[0].text == "Base ADDED"
+ assert doc.tables[0].cell(0, 0).text == "Cell CELLADD"
+ assert run("docx_revisions.py", "list", out)["revisions"] == []
+
+ def test_reject_all(self, tracked: Path, tmp_path: Path):
+ out = tmp_path / "rej.docx"
+ run("docx_revisions.py", "reject-all", tracked, "-o", out)
+ doc = Document(str(out))
+ assert doc.paragraphs[0].text == "Base REMOVED"
+ assert doc.tables[0].cell(0, 0).text == "Cell CELLGONE"
+
+ def test_accept_single_by_id(self, tracked: Path, tmp_path: Path):
+ out = tmp_path / "one.docx"
+ res = run("docx_revisions.py", "accept", tracked, "--id", "1",
+ "-o", out)
+ assert res["resolved"] == 1
+ doc = Document(str(out))
+ assert doc.paragraphs[0].text == "Base ADDED" # del 2 unresolved
+ remaining = run("docx_revisions.py", "list", out)["revisions"]
+ assert sorted(r["id"] for r in remaining) == ["2", "3", "4"]
+
+ def test_reject_single_by_id(self, tracked: Path, tmp_path: Path):
+ out = tmp_path / "rone.docx"
+ run("docx_revisions.py", "reject", tracked, "--id", "2", "-o", out)
+ doc = Document(str(out))
+ assert doc.paragraphs[0].text == "Base REMOVED" # ins 1 unresolved
+
+ def test_unknown_id_fails(self, tracked: Path, tmp_path: Path):
+ proc = run_raw("docx_revisions.py", "accept", tracked, "--id",
+ "999", "-o", tmp_path / "x.docx")
+ assert proc.returncode == 1
+
+
+class TestComments:
+ @pytest.fixture()
+ def base(self, tmp_path: Path) -> Path:
+ doc = Document()
+ doc.add_paragraph("The quarterly revenue rose sharply.")
+ doc.add_paragraph("Second paragraph.")
+ path = tmp_path / "base.docx"
+ doc.save(str(path))
+ return path
+
+ def test_add_list_delete(self, base: Path, tmp_path: Path):
+ out = tmp_path / "com.docx"
+ res = run("docx_comments.py", "add", base, "--target",
+ "quarterly revenue", "--text", "Needs a source",
+ "--author", "Reviewer", "--initials", "R", "-o", out)
+ assert res["ok"] is True
+ cid = res["comment_id"]
+
+ listed = run("docx_comments.py", "list", out)["comments"]
+ assert len(listed) == 1
+ c = listed[0]
+ assert c["id"] == cid
+ assert c["author"] == "Reviewer"
+ assert c["text"] == "Needs a source"
+ assert c["anchored_text"] == "quarterly revenue"
+ assert c["date"]
+
+ # document text unchanged by anchoring
+ text = run("docx_read.py", out, "--text")
+ assert "The quarterly revenue rose sharply." in text["body"]
+
+ out2 = tmp_path / "nocom.docx"
+ run("docx_comments.py", "delete", out, "--id", cid, "-o", out2)
+ assert run("docx_comments.py", "list", out2)["comments"] == []
+ text2 = run("docx_read.py", out2, "--text")
+ assert "The quarterly revenue rose sharply." in text2["body"]
+
+ def test_xml_fallback_path(self, base: Path, tmp_path: Path):
+ out = tmp_path / "xmlcom.docx"
+ res = run("docx_comments.py", "add", base, "--target",
+ "Second paragraph", "--text", "fallback note",
+ "--author", "Bot", "--xml", "-o", out)
+ assert res["native_api"] is False
+ listed = run("docx_comments.py", "list", out)["comments"]
+ assert listed[0]["text"] == "fallback note"
+ assert listed[0]["anchored_text"] == "Second paragraph"
+ # file still opens cleanly
+ assert Document(str(out)).paragraphs[1].text == "Second paragraph."
+
+ def test_missing_target_fails(self, base: Path, tmp_path: Path):
+ proc = run_raw("docx_comments.py", "add", base, "--target",
+ "not present", "--text", "x", "-o",
+ tmp_path / "y.docx")
+ assert proc.returncode == 1
+
+
+class TestValidate:
+ def test_healthy_file_passes(self, created: Path):
+ res = run("docx_validate.py", created)
+ assert res["ok"] is True
+ assert all(i["severity"] != "error" for i in res["issues"])
+
+ def test_not_a_zip(self, tmp_path: Path):
+ bad = tmp_path / "bad.docx"
+ bad.write_bytes(b"this is not a zip file")
+ proc = run_raw("docx_validate.py", bad)
+ assert proc.returncode == 1
+ rep = json.loads(proc.stdout.decode("utf-8"))
+ assert rep["issues"][0]["code"] == "not-a-zip"
+
+ def test_dangling_rel_and_empty_image(self, created: Path,
+ tmp_path: Path):
+ import shutil
+ import zipfile
+ broken = tmp_path / "broken.docx"
+ shutil.copy(created, broken)
+ # rebuild the zip: drop the image part, zero out nothing else
+ src = zipfile.ZipFile(str(created))
+ with zipfile.ZipFile(str(broken), "w") as dst:
+ for item in src.infolist():
+ if item.filename.startswith("word/media/"):
+ dst.writestr(item.filename, b"") # empty image
+ else:
+ dst.writestr(item, src.read(item.filename))
+ proc = run_raw("docx_validate.py", broken)
+ assert proc.returncode == 1
+ rep = json.loads(proc.stdout.decode("utf-8"))
+ codes = {i["code"] for i in rep["issues"]}
+ assert "empty-image" in codes
+
+ def test_missing_style(self, tmp_path: Path):
+ import zipfile
+ doc = Document()
+ doc.add_paragraph("styled", style="Heading 1")
+ path = tmp_path / "styles.docx"
+ doc.save(str(path))
+ # rewrite document.xml to reference a style id that doesn't exist
+ src = zipfile.ZipFile(str(path))
+ broken = tmp_path / "badstyle.docx"
+ with zipfile.ZipFile(str(broken), "w") as dst:
+ for item in src.infolist():
+ data = src.read(item.filename)
+ if item.filename == "word/document.xml":
+ data = data.replace(b'w:val="Heading1"',
+ b'w:val="GhostStyle"')
+ dst.writestr(item, data)
+ proc = run_raw("docx_validate.py", broken)
+ assert proc.returncode == 1
+ rep = json.loads(proc.stdout.decode("utf-8"))
+ assert any(i["code"] == "missing-style" and "GhostStyle"
+ in i["detail"] for i in rep["issues"])
+
+
+class TestNormalize:
+ def test_merges_split_runs(self, tmp_path: Path):
+ doc = Document()
+ p = doc.add_paragraph()
+ p.add_run("Hel") # identical (no) formatting, split
+ p.add_run("lo wo")
+ p.add_run("rld")
+ b = p.add_run("BOLD1")
+ b.bold = True
+ b2 = p.add_run("BOLD2")
+ b2.bold = True
+ i = p.add_run("ital")
+ i.italic = True
+ path = tmp_path / "split.docx"
+ doc.save(str(path))
+
+ out = tmp_path / "norm.docx"
+ res = run("docx_edit.py", "normalize", path, "-o", out)
+ assert res["runs_merged"] == 3 # 2 plain merges + 1 bold merge
+
+ doc2 = Document(str(out))
+ para = doc2.paragraphs[0]
+ assert para.text == "Hello worldBOLD1BOLD2ital"
+ assert [r.text for r in para.runs] == \
+ ["Hello world", "BOLD1BOLD2", "ital"]
+ assert para.runs[1].bold is True
+ assert para.runs[2].italic is True
+
+
+class TestFields:
+ def test_toc_and_page_numbers_via_edit(self, created: Path,
+ tmp_path: Path):
+ out = tmp_path / "fields.docx"
+ run("docx_edit.py", "toc", created, "--index", "0", "-o", out)
+ run("docx_edit.py", "page-numbers", out)
+
+ import zipfile
+ doc_xml = zipfile.ZipFile(str(out)).read(
+ "word/document.xml").decode("utf-8")
+ assert "TOC \\o" in doc_xml
+ assert "fldChar" in doc_xml
+ footer_names = [n for n in zipfile.ZipFile(str(out)).namelist()
+ if n.startswith("word/footer")]
+ footers = "".join(zipfile.ZipFile(str(out)).read(n).decode("utf-8")
+ for n in footer_names)
+ assert "PAGE" in footers and "NUMPAGES" in footers
+ # still a valid document
+ assert run("docx_validate.py", out)["ok"] is True
+
+ def test_toc_and_footer_in_create_spec(self, tmp_path: Path):
+ spec = {
+ "footer_page_numbers": True,
+ "blocks": [
+ {"type": "toc"},
+ {"type": "heading", "text": "Chapter", "level": 1},
+ ],
+ }
+ spec_path = tmp_path / "fspec.json"
+ spec_path.write_text(json.dumps(spec), encoding="utf-8")
+ out = tmp_path / "fcreate.docx"
+ run("docx_create.py", spec_path, out)
+
+ import zipfile
+ z = zipfile.ZipFile(str(out))
+ assert "TOC \\o" in z.read("word/document.xml").decode("utf-8")
+ footers = "".join(z.read(n).decode("utf-8") for n in z.namelist()
+ if n.startswith("word/footer"))
+ assert "NUMPAGES" in footers
diff --git a/skills/productivity/pdf/SKILL.md b/skills/productivity/pdf/SKILL.md
index 02e57497e4e..4c6cf343aeb 100644
--- a/skills/productivity/pdf/SKILL.md
+++ b/skills/productivity/pdf/SKILL.md
@@ -14,13 +14,15 @@ metadata:
# PDF Skill
-Create PDFs from structured specs, extract text/tables/metadata, merge/split/rotate/watermark pages, fill AcroForm form fields, and encrypt/decrypt — using pypdf, reportlab, and pdfplumber. Scanned (image-only) PDFs contain no text layer: OCR is explicitly out of scope here — when a page is image-only, stop and use the `ocr-and-documents` skill instead of pretending to extract text.
+Create PDFs from structured specs, build and fill AcroForm forms (with layout linting and visual overlays), extract text/tables/metadata, merge/split/rotate/watermark/stamp pages, export page images, manage metadata and attachments, and encrypt/decrypt — using pypdf, reportlab, and pdfplumber. Scanned (image-only) PDFs contain no text layer: OCR is explicitly out of scope here — when a page is image-only, stop and use the `ocr-and-documents` skill instead of pretending to extract text.
## When to Use
- Generate a report, invoice, or multi-page document as PDF.
+- Build a fillable AcroForm (text/checkbox/radio/dropdown) from a JSON spec, linting the layout first.
- Pull text, tables (JSON/CSV), metadata, or form-field values out of a PDF.
-- Merge, split, rotate, extract page subsets, watermark, bookmark, or compress PDFs.
+- Merge, split, rotate, extract page subsets, watermark, stamp text/images at coordinates, bookmark, or compress PDFs.
+- Export pages as PNGs for visual review or for OCR hand-off; set/clear document metadata; add/extract file attachments.
- Fill or flatten AcroForm forms; encrypt or decrypt with passwords.
- NOT for scanned/image-only PDFs (use `ocr-and-documents`) and NOT for pixel-perfect HTML-to-PDF rendering (use a headless browser).
@@ -28,6 +30,7 @@ Create PDFs from structured specs, extract text/tables/metadata, merge/split/rot
- Python 3.10+ with `pypdf`, `reportlab`, `pdfplumber`:
`python3 -m pip install pypdf reportlab pdfplumber`
+- Optional, for page rasterization (`pdf_page_image.py`, overlay rendering): `python3 -m pip install pypdfium2`, or poppler's `pdftoppm` on PATH. Scripts fall back pypdfium2 → pdftoppm and report `{"rendered": false, "missing": [...]}` (exit 0) when neither exists.
- Each helper script checks imports lazily and prints an install hint if a dependency is missing.
## How to Run
@@ -36,6 +39,9 @@ All helpers live in `scripts/` and are argparse CLIs — run them with the `term
```bash
python3 scripts/pdf_create.py spec.json -o out.pdf # build PDF from JSON spec
+python3 scripts/pdf_make_form.py formspec.json -o form.pdf # build fillable AcroForm from JSON spec
+python3 scripts/pdf_form_layout.py formspec.json # lint form layout BEFORE building
+python3 scripts/pdf_form_layout.py formspec.json --render-overlay boxes.png [--pdf form.pdf]
python3 scripts/pdf_read.py doc.pdf --text # per-page text (JSON)
python3 scripts/pdf_read.py doc.pdf --tables --csv-dir t/ # tables to JSON + CSV files
python3 scripts/pdf_read.py doc.pdf --meta # metadata, page sizes, encrypted/scanned flags
@@ -46,6 +52,13 @@ python3 scripts/pdf_fill_form.py form.pdf --fields-json values.json -o filled.pd
python3 scripts/pdf_secure.py doc.pdf --encrypt -o enc.pdf --user-password your-password
python3 scripts/pdf_secure.py enc.pdf --decrypt -o dec.pdf --password your-password
python3 scripts/pdf_watermark.py doc.pdf --stamp mark.pdf -o stamped.pdf [--under]
+python3 scripts/pdf_stamp.py doc.pdf -o out.pdf --text "DRAFT" --x 150 --y 400 \
+ --font-size 60 --rotation 45 --opacity 0.3 --color "#cc0000" [--pages 1-3]
+python3 scripts/pdf_stamp.py doc.pdf -o out.pdf --image sig.png --x 400 --y 60 --width 120
+python3 scripts/pdf_page_image.py doc.pdf --pages 1-3 --dpi 150 --out-dir imgs/
+python3 scripts/pdf_meta.py doc.pdf --set-meta --title "T" --author "A" -o out.pdf
+python3 scripts/pdf_meta.py doc.pdf --attach data.csv -o out.pdf
+python3 scripts/pdf_meta.py doc.pdf --list-attachments | --extract-attachments dir/
```
## Quick Reference
@@ -53,6 +66,8 @@ python3 scripts/pdf_watermark.py doc.pdf --stamp mark.pdf -o stamped.pdf [--unde
| Task | Tool | Command / API |
|---|---|---|
| Create doc (headings, tables, images) | reportlab platypus | `pdf_create.py spec.json -o out.pdf` |
+| Build fillable form | reportlab acroForm | `pdf_make_form.py formspec.json -o form.pdf` |
+| Lint form layout / overlay image | pure python + PIL | `pdf_form_layout.py formspec.json [--render-overlay o.png]` |
| Per-page text | pdfplumber | `pdf_read.py f.pdf --text` |
| Tables → JSON/CSV | pdfplumber | `pdf_read.py f.pdf --tables` |
| Metadata / sizes / encrypted / scanned | pypdf + pdfplumber | `pdf_read.py f.pdf --meta` |
@@ -60,18 +75,23 @@ python3 scripts/pdf_watermark.py doc.pdf --stamp mark.pdf -o stamped.pdf [--unde
| Split / extract / rotate | pypdf | `pdf_split.py f.pdf --pages 2-5 --rotate 90` |
| List / fill / flatten form | pypdf | `pdf_read.py --fields`, `pdf_fill_form.py` |
| Encrypt / decrypt (AES-256) | pypdf | `pdf_secure.py --encrypt/--decrypt` |
-| Watermark / stamp | pypdf | `pdf_watermark.py f.pdf --stamp w.pdf` |
+| Watermark / stamp PDF page | pypdf | `pdf_watermark.py f.pdf --stamp w.pdf` |
+| Stamp text/image at coordinates | reportlab + pypdf | `pdf_stamp.py f.pdf --text "Sign here" --x 400 --y 60` |
+| Pages → PNG (review / OCR hand-off) | pypdfium2 or pdftoppm | `pdf_page_image.py f.pdf --pages 1-3 --out-dir imgs/` |
+| Set/clear metadata, attachments | pypdf | `pdf_meta.py --set-meta / --attach / --extract-attachments` |
| Compress content streams | pypdf | `pdf_split.py f.pdf --pages 1-N --compress` |
## Procedure
-1. **Inspect first.** Run `pdf_read.py file.pdf --meta`. Check `encrypted` (if true, decrypt first with `pdf_secure.py --decrypt`) and `likely_scanned_pages`. If pages are image-only, hand off to the `ocr-and-documents` skill — do not report empty text as "no content".
+1. **Inspect first.** Run `pdf_read.py file.pdf --meta`. Check `encrypted` (if true, decrypt first with `pdf_secure.py --decrypt`) and `likely_scanned_pages`. If pages are image-only, export them with `pdf_page_image.py --pages <scanned> --dpi 300 --out-dir imgs/` and hand the PNGs to the `ocr-and-documents` skill — do not report empty text as "no content".
2. **Create.** Write a JSON spec with `write_file` (elements: `heading`, `paragraph`, `table`, `image`, `pagebreak`; optional `title`/`author` metadata; page numbers are added automatically), then run `pdf_create.py`. Verify visually with `vision_analyze` on a rendered page image if layout matters.
3. **Extract.** `--text` gives a JSON list of per-page strings; `--tables` gives row arrays per page and can also emit CSV files. Read results with `read_file`; never eyeball a binary PDF directly.
-4. **Manipulate.** `pdf_merge.py` concatenates and can add one bookmark per source file; `pdf_split.py` handles page ranges (1-based, e.g. `1-3,5,9-`), rotation in 90° steps, and `--compress`. Watermark by preparing a single-page stamp PDF (e.g. via `pdf_create.py`) and overlaying it with `pdf_watermark.py`.
-5. **Forms.** List fields (`--fields`) to learn exact names and types, write a UTF-8 JSON of `{"FieldName": "value"}` with `write_file` (checkboxes accept `true`/`false`; radio/choice values must match the field's export options), then `pdf_fill_form.py`. Re-read with `--fields` to confirm values landed.
-6. **Secure.** Encrypt with distinct user/owner passwords and AES-256. To remove a password you know, `--decrypt` writes an unencrypted copy.
-7. **Verify** (see below) before reporting success.
+4. **Manipulate.** `pdf_merge.py` concatenates and can add one bookmark per source file; `pdf_split.py` handles page ranges (1-based, e.g. `1-3,5,9-`), rotation in 90° steps, and `--compress`. Watermark by preparing a single-page stamp PDF (e.g. via `pdf_create.py`) and overlaying it with `pdf_watermark.py`; for one-liner stamps ("sign here", diagonal DRAFT, corner labels) use `pdf_stamp.py` with text or an image at explicit coordinates.
+5. **Build forms.** Write one form-spec JSON (fields with `label_box`/`entry_box` in PDF points — see `references/forms.md`), lint it with `pdf_form_layout.py` and fix every reported problem, optionally review the `--render-overlay` PNG with `vision_analyze`, then build with `pdf_make_form.py` and confirm with `pdf_read.py --fields`.
+6. **Fill forms.** List fields (`--fields`) to learn exact names and types, write a UTF-8 JSON of `{"FieldName": "value"}` with `write_file` (checkboxes accept `true`/`false`; radio/choice values must match the field's export options), then `pdf_fill_form.py`. Re-read with `--fields` to confirm values landed.
+7. **Metadata & attachments.** `pdf_meta.py --set-meta` writes Title/Author/Subject/Keywords (DocInfo); `--clear-meta` drops them; `--attach`/`--list-attachments`/`--extract-attachments` round-trip embedded files.
+8. **Secure.** Encrypt with distinct user/owner passwords and AES-256. To remove a password you know, `--decrypt` writes an unencrypted copy.
+9. **Verify** (see below) before reporting success.
## Pitfalls
@@ -83,12 +103,20 @@ python3 scripts/pdf_watermark.py doc.pdf --stamp mark.pdf -o stamped.pdf [--unde
- **Permission flags don't enforce**: owner-password permission bits (no-print, no-copy) are polite requests that viewers may honor; any library (including pypdf) can read and strip them. Only the user password actually gates content via encryption. Never present permission flags as security.
- **Table extraction is heuristic**: pdfplumber detects tables from ruling lines/word alignment; borderless or merged-cell tables may need `table_settings` tuning or manual cleanup.
- **Page indexing**: helper CLIs take 1-based pages; pypdf APIs are 0-based. The scripts convert — don't double-convert.
+- **Rotated stamp text extraction**: pdfplumber's line grouping scrambles rotated glyphs (a 45° "DRAFT" extracts as stray letters); verify rotated stamps with `pypdf`'s `extract_text()` or a rendered image instead.
+- **Radio groups**: reportlab needs ≥2 `radio()` widgets per group, fills need the slashed export value (`"/red"`), and flatten fidelity is worst for radios — see `references/forms.md`.
+- **Metadata scope**: `pdf_meta.py` writes the classic DocInfo dictionary only; embedded XMP metadata (if any) is left untouched and may show different values in some viewers.
+- **PDF/A is out of scope**: pypdf/reportlab cannot produce or validate conformant PDF/A. If archival conformance is required, run Ghostscript via the `terminal` tool (e.g. `gs -dPDFA=2 -dPDFACompatibilityPolicy=1 -sColorConversionStrategy=UseDeviceIndependentColor -sDEVICE=pdfwrite -o out.pdf in.pdf` with a suitable ICC profile) and validate with veraPDF — both are external installs, and the result still needs validation, not assumption.
- Rotation must be a multiple of 90; encrypted inputs must be decrypted before any other operation.
## Verification
- After create/merge/split: `pdf_read.py out.pdf --meta` — confirm `page_count`, and per-page `rotation` when you rotated.
- After extraction: check the JSON is non-empty and spot-check a known string or cell.
+- Form design loop: `pdf_form_layout.py spec.json` must exit 0; then `--render-overlay boxes.png --pdf form.pdf` and review the PNG with `vision_analyze` (red = entry boxes with field names, blue = label boxes) asking about overlaps, misalignment, and labels detached from their fields. Iterate spec → lint → overlay until clean.
+- After building a form: `pdf_read.py form.pdf --fields` lists every spec field with the right type and options.
- After form fill: `pdf_read.py filled.pdf --fields` and compare values (exact match, including non-ASCII).
+- After stamping: re-extract text (pypdf for rotated stamps) or render the page with `pdf_page_image.py` and inspect with `vision_analyze`.
+- After metadata/attachment edits: `pdf_read.py --meta` / `pdf_meta.py --list-attachments`, and re-extract an attachment to byte-compare.
- After encrypt: `--meta` shows `"encrypted": true` and opening without a password fails; after decrypt, text extraction matches the original.
- For anything visual (watermarks, flattened forms), render and inspect with `vision_analyze`.
diff --git a/skills/productivity/pdf/references/forms.md b/skills/productivity/pdf/references/forms.md
new file mode 100644
index 00000000000..155c15c7390
--- /dev/null
+++ b/skills/productivity/pdf/references/forms.md
@@ -0,0 +1,99 @@
+# Building Fillable Forms: spec format and workflow
+
+The same JSON spec drives both `pdf_form_layout.py` (design lint) and
+`pdf_make_form.py` (AcroForm build). Coordinates are PDF points, origin
+at the bottom-left of the page (1 pt = 1/72 inch; A4 is 595.27 x 841.89,
+letter is 612 x 792).
+
+## Spec shape
+
+```json
+{
+ "title": "Example Intake Form",
+ "author": "example-author",
+ "page_size": "A4",
+ "page_count": 1,
+ "fields": [
+ {"name": "surname", "type": "text", "page": 1,
+ "label": "Surname", "label_box": [72, 700, 150, 714],
+ "entry_box": [160, 696, 400, 716],
+ "value": "", "tooltip": "Family name"},
+
+ {"name": "agree", "type": "checkbox", "page": 1,
+ "label": "I agree", "label_box": [72, 660, 150, 674],
+ "entry_box": [160, 658, 176, 674], "checked": false},
+
+ {"name": "color", "type": "radio", "page": 1,
+ "label": "Color", "label_box": [72, 620, 150, 634],
+ "entry_box": [160, 616, 400, 636],
+ "options": ["red", "blue"], "value": "blue"},
+
+ {"name": "size", "type": "dropdown", "page": 1,
+ "label": "Size", "label_box": [72, 580, 150, 594],
+ "entry_box": [160, 576, 300, 596],
+ "options": ["small", "large"], "value": "small"}
+ ]
+}
+```
+
+- `page_size`: `"A4"`, `"letter"`, or `[width, height]` in points.
+- `page_count`: optional; extended automatically to the highest field page.
+- Boxes are `[x0, y0, x1, y1]` with `x0 < x1`, `y0 < y1`.
+- `label` is drawn as static text near `label_box`; omit it (and
+ `label_box`) for unlabeled fields.
+- `radio`: the buttons are laid out left-to-right inside `entry_box`,
+ one slot per option, each with a small static caption. `value`
+ pre-selects an option by its export name.
+- `dropdown` maps to an AcroForm choice (combo) field.
+
+## Field types → what pdf_read.py --fields reports
+
+| Spec type | /FT | value format after fill |
+|---|---|---|
+| text | /Tx (`text`) | the string |
+| checkbox | /Btn (`button`) | `/Yes` or `/Off` |
+| radio | /Btn (`button`) | `/<export>`, e.g. `/red` |
+| dropdown | /Ch (`choice`) | the option string |
+
+When filling with `pdf_fill_form.py`, checkboxes accept `true`/`false`;
+radio values need the leading slash (`"/red"`); dropdown values are the
+plain option string.
+
+## Layout lint rules (pdf_form_layout.py)
+
+Per field, on its declared page:
+
+- boxes must be well-formed and inside the page bounds;
+- entry boxes must be at least 8x8 pt (12 pt tall for text/dropdown);
+- no two entry boxes on the same page may overlap (the second and later
+ fields of an overlapping cluster are flagged);
+- a label must sit within 150 pt of its entry box and must not overlap it.
+
+Exit code 0 = clean, 1 = at least one problem; the JSON report lists
+per-field `problems`. Lint the spec BEFORE building — fixing numbers in
+JSON is cheaper than debugging a rendered PDF.
+
+## Visual review loop
+
+```bash
+python3 scripts/pdf_form_layout.py spec.json --render-overlay overlay.png [--pdf built.pdf]
+```
+
+Red rectangles = entry boxes (with field names), blue = label boxes.
+Without `--pdf` the overlay is drawn on a blank page (PIL-only, always
+works); with `--pdf` the real page is rasterized underneath
+(needs pypdfium2 or pdftoppm — otherwise the report says
+`"rendered": false` with install hints). Feed the PNG to `vision_analyze`
+and ask specifically about collisions, alignment, and stray labels.
+
+## Radio-group quirks (reportlab + pypdf)
+
+- reportlab requires at least two `radio()` calls per group; a
+ single-option radio group produces a broken field.
+- Pre-selecting is done at build time via `"value"`; changing selection
+ later via `pdf_fill_form.py` needs the slashed export name (`"/red"`).
+- Some viewers render reportlab radio appearances inconsistently after a
+ pypdf fill; verify with `--fields` (data truth) plus a rendered page
+ image (visual truth) rather than either alone.
+- Flattening radio groups is the least reliable flatten case — check the
+ output image before shipping.
diff --git a/skills/productivity/pdf/scripts/_raster.py b/skills/productivity/pdf/scripts/_raster.py
new file mode 100644
index 00000000000..d9ccbc91538
--- /dev/null
+++ b/skills/productivity/pdf/scripts/_raster.py
@@ -0,0 +1,76 @@
+"""Shared page rasterizer with a fallback chain: pypdfium2 -> pdftoppm.
+
+Returns PIL Images so callers can annotate/save. Not a CLI.
+"""
+from __future__ import annotations
+
+import shutil
+import subprocess
+import tempfile
+from pathlib import Path
+
+
+def available_backends() -> list[str]:
+ """Names of usable rasterizer backends, in preference order."""
+ backends = []
+ try:
+ import pypdfium2 # noqa: F401
+ backends.append("pypdfium2")
+ except ImportError:
+ pass
+ if shutil.which("pdftoppm"):
+ backends.append("pdftoppm")
+ return backends
+
+
+def missing_hints() -> list[str]:
+ """Install hints for when no backend is available."""
+ return [
+ "python3 -m pip install pypdfium2",
+ "poppler-utils (provides pdftoppm), e.g. apt-get install poppler-utils",
+ ]
+
+
+def rasterize_page(pdf_path: str, page: int, dpi: int = 150, password: str | None = None):
+ """Render one 1-based page to a PIL Image, or None if no backend works.
+
+ Raises ValueError for an out-of-range page when a backend is present.
+ """
+ for backend in available_backends():
+ if backend == "pypdfium2":
+ return _via_pdfium(pdf_path, page, dpi, password)
+ if backend == "pdftoppm":
+ img = _via_pdftoppm(pdf_path, page, dpi, password)
+ if img is not None:
+ return img
+ return None
+
+
+def _via_pdfium(pdf_path: str, page: int, dpi: int, password: str | None):
+ import pypdfium2 as pdfium
+ doc = pdfium.PdfDocument(pdf_path, password=password)
+ try:
+ if not 1 <= page <= len(doc):
+ raise ValueError(f"page {page} out of range 1-{len(doc)}")
+ bitmap = doc[page - 1].render(scale=dpi / 72.0)
+ return bitmap.to_pil().convert("RGB")
+ finally:
+ doc.close()
+
+
+def _via_pdftoppm(pdf_path: str, page: int, dpi: int, password: str | None):
+ from PIL import Image
+ with tempfile.TemporaryDirectory() as tmp:
+ prefix = str(Path(tmp) / "page")
+ cmd = ["pdftoppm", "-png", "-r", str(dpi), "-f", str(page), "-l", str(page)]
+ if password:
+ cmd += ["-upw", password]
+ cmd += [pdf_path, prefix]
+ proc = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8")
+ if proc.returncode != 0:
+ raise ValueError(f"pdftoppm failed: {proc.stderr.strip()}")
+ produced = sorted(Path(tmp).glob("page*.png"))
+ if not produced:
+ raise ValueError(f"page {page} out of range (pdftoppm produced no image)")
+ with Image.open(produced[0]) as img:
+ return img.convert("RGB")
diff --git a/skills/productivity/pdf/scripts/pdf_form_layout.py b/skills/productivity/pdf/scripts/pdf_form_layout.py
new file mode 100644
index 00000000000..ed5e5a88b0c
--- /dev/null
+++ b/skills/productivity/pdf/scripts/pdf_form_layout.py
@@ -0,0 +1,168 @@
+#!/usr/bin/env python3
+"""Validate a form-spec layout BEFORE building the PDF, with optional
+visual overlay rendering for review with a vision model.
+
+Input is the same JSON spec pdf_make_form.py consumes: each field has
+"page", "label_box" and "entry_box" as [x0, y0, x1, y1] in PDF points
+(origin bottom-left). Checks per field:
+ - boxes lie within the page bounds
+ - boxes are well-formed (x0 < x1, y0 < y1)
+ - entry boxes meet minimum sizes (default 8x8 pt; 12 pt height for text)
+ - no two entry boxes on the same page overlap
+ - the label sits near its entry box (default within 150 pt gap)
+
+Prints a JSON report {"ok": bool, "fields": [...], "errors": N};
+exit 0 when clean, 1 when any check fails.
+
+--render-overlay OUT.png rasterizes --overlay-page (default 1) of an
+existing PDF (--pdf; a blank page of spec size if omitted) and draws
+label boxes (blue) and entry boxes (red) with field names, for
+review with `vision_analyze`. If no rasterizer (pypdfium2/pdftoppm) is
+available the overlay is skipped with {"rendered": false, "missing": [...]}
+and validation exit status is unchanged.
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+
+MIN_W = 8.0
+MIN_H = 8.0
+MIN_TEXT_H = 12.0
+MAX_LABEL_GAP = 150.0
+
+
+def _boxes_overlap(a, b) -> bool:
+ return not (a[2] <= b[0] or b[2] <= a[0] or a[3] <= b[1] or b[3] <= a[1])
+
+
+def _box_gap(a, b) -> float:
+ dx = max(b[0] - a[2], a[0] - b[2], 0.0)
+ dy = max(b[1] - a[3], a[1] - b[3], 0.0)
+ return (dx ** 2 + dy ** 2) ** 0.5
+
+
+def _page_size(spec: dict) -> tuple[float, float]:
+ sizes = {"a4": (595.27, 841.89), "letter": (612.0, 792.0)}
+ ps = spec.get("page_size", "A4")
+ if isinstance(ps, (list, tuple)) and len(ps) == 2:
+ return float(ps[0]), float(ps[1])
+ return sizes.get(str(ps).lower(), sizes["a4"])
+
+
+def _check_box(box, width, height, min_w, min_h, kind) -> list[str]:
+ problems = []
+ if box is None:
+ return [f"{kind}_box missing"]
+ x0, y0, x1, y1 = (float(v) for v in box)
+ if x0 >= x1 or y0 >= y1:
+ problems.append(f"{kind}_box malformed (need x0<x1 and y0<y1): {box}")
+ return problems
+ if x0 < 0 or y0 < 0 or x1 > width or y1 > height:
+ problems.append(f"{kind}_box outside page bounds {width}x{height}: {box}")
+ if x1 - x0 < min_w or y1 - y0 < min_h:
+ problems.append(f"{kind}_box below minimum size {min_w}x{min_h}: {box}")
+ return problems
+
+
+def validate(spec: dict) -> dict:
+ width, height = _page_size(spec)
+ fields = spec.get("fields", [])
+ report = []
+ entry_boxes: dict[int, list[tuple[str, list[float]]]] = {}
+ for f in fields:
+ name = f.get("name", "?")
+ page = int(f.get("page", 1))
+ problems = []
+ min_h = MIN_TEXT_H if f.get("type", "text") in ("text", "dropdown") else MIN_H
+ entry = f.get("entry_box")
+ problems += _check_box(entry, width, height, MIN_W, min_h, "entry")
+ label = f.get("label_box")
+ if f.get("label"):
+ problems += _check_box(label, width, height, 4, 4, "label")
+ if entry and label and len(problems) == 0:
+ gap = _box_gap([float(v) for v in label], [float(v) for v in entry])
+ if gap > MAX_LABEL_GAP:
+ problems.append(f"label is {gap:.0f}pt from its entry box (max {MAX_LABEL_GAP:.0f})")
+ if _boxes_overlap([float(v) for v in label], [float(v) for v in entry]):
+ problems.append("label_box overlaps its own entry_box")
+ if entry and not any("malformed" in p or "missing" in p for p in problems):
+ ebox = [float(v) for v in entry]
+ for other_name, other_box in entry_boxes.get(page, []):
+ if _boxes_overlap(ebox, other_box):
+ problems.append(f"entry_box overlaps field {other_name!r}")
+ entry_boxes.setdefault(page, []).append((name, ebox))
+ report.append({"name": name, "page": page, "ok": not problems, "problems": problems})
+ errors = sum(1 for r in report if not r["ok"])
+ return {"ok": errors == 0, "page_size": [width, height],
+ "field_count": len(report), "errors": errors, "fields": report}
+
+
+def render_overlay(spec: dict, pdf_path: str | None, page: int, out_png: str,
+ dpi: int = 100) -> dict:
+ sys.path.insert(0, str(__import__("pathlib").Path(__file__).resolve().parent))
+ import _raster
+ if not _raster.available_backends() and pdf_path:
+ return {"rendered": False, "missing": _raster.missing_hints()}
+ from PIL import Image, ImageDraw
+ width, height = _page_size(spec)
+ if pdf_path:
+ img = _raster.rasterize_page(pdf_path, page, dpi=dpi)
+ if img is None:
+ return {"rendered": False, "missing": _raster.missing_hints()}
+ scale = img.width / width
+ else:
+ scale = dpi / 72.0
+ img = Image.new("RGB", (int(width * scale), int(height * scale)), "white")
+ draw = ImageDraw.Draw(img)
+
+ def to_px(box):
+ x0, y0, x1, y1 = (float(v) for v in box)
+ return [x0 * scale, img.height - y1 * scale, x1 * scale, img.height - y0 * scale]
+
+ for f in spec.get("fields", []):
+ if int(f.get("page", 1)) != page:
+ continue
+ if f.get("entry_box"):
+ px = to_px(f["entry_box"])
+ draw.rectangle(px, outline=(220, 30, 30), width=2)
+ draw.text((px[0] + 2, px[1] + 2), str(f.get("name", "?")), fill=(220, 30, 30))
+ if f.get("label_box"):
+ draw.rectangle(to_px(f["label_box"]), outline=(30, 60, 220), width=2)
+ img.save(out_png)
+ return {"rendered": True, "overlay": out_png, "page": page,
+ "legend": {"entry_box": "red", "label_box": "blue"}}
+
+
+def main() -> int:
+ for stream in (sys.stdout, sys.stderr):
+ try:
+ stream.reconfigure(encoding="utf-8")
+ except Exception:
+ pass
+ parser = argparse.ArgumentParser(
+ description="Validate form-spec layout (boxes, overlaps, label pairing); "
+ "optionally render an annotated overlay image.")
+ parser.add_argument("spec", help="Form spec JSON (same format as pdf_make_form.py)")
+ parser.add_argument("--pdf", help="Existing PDF to rasterize under the overlay "
+ "(blank page if omitted)")
+ parser.add_argument("--render-overlay", metavar="OUT_PNG",
+ help="Write an annotated PNG for visual review")
+ parser.add_argument("--overlay-page", type=int, default=1, help="1-based page (default 1)")
+ parser.add_argument("--dpi", type=int, default=100, help="Overlay render DPI (default 100)")
+ args = parser.parse_args()
+
+ with open(args.spec, encoding="utf-8") as fh:
+ spec = json.load(fh)
+ result = validate(spec)
+ if args.render_overlay:
+ result["overlay"] = render_overlay(spec, args.pdf, args.overlay_page,
+ args.render_overlay, args.dpi)
+ json.dump(result, sys.stdout, ensure_ascii=False, indent=2)
+ print()
+ return 0 if result["ok"] else 1
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/skills/productivity/pdf/scripts/pdf_make_form.py b/skills/productivity/pdf/scripts/pdf_make_form.py
new file mode 100644
index 00000000000..7ee6a551262
--- /dev/null
+++ b/skills/productivity/pdf/scripts/pdf_make_form.py
@@ -0,0 +1,145 @@
+#!/usr/bin/env python3
+"""Create a fillable AcroForm PDF from a JSON spec (reportlab canvas.acroForm).
+
+Spec format (UTF-8 JSON; coordinates in PDF points, origin bottom-left):
+{
+ "title": "Example Intake Form",
+ "page_size": "A4", // or "letter" or [width, height]
+ "page_count": 1,
+ "fields": [
+ {"name": "surname", "type": "text", "page": 1,
+ "label": "Surname", "label_box": [72, 700, 150, 714],
+ "entry_box": [160, 696, 400, 716], "value": "", "tooltip": "Family name"},
+ {"name": "agree", "type": "checkbox", "page": 1,
+ "label": "I agree", "label_box": [72, 660, 150, 674],
+ "entry_box": [160, 658, 176, 674], "checked": false},
+ {"name": "color", "type": "radio", "page": 1,
+ "label": "Color", "label_box": [72, 620, 150, 634],
+ "entry_box": [160, 616, 400, 636], "options": ["red", "blue"],
+ "value": "red"},
+ {"name": "size", "type": "dropdown", "page": 1,
+ "label": "Size", "label_box": [72, 580, 150, 594],
+ "entry_box": [160, 576, 300, 596], "options": ["small", "large"],
+ "value": "small"}
+ ]
+}
+The same spec (label_box/entry_box/page) is what pdf_form_layout.py validates,
+so lint the layout first, then build.
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+
+
+def _reconfigure_stdio() -> None:
+ for stream in (sys.stdout, sys.stderr):
+ try:
+ stream.reconfigure(encoding="utf-8")
+ except Exception:
+ pass
+
+
+def _page_size(spec: dict):
+ from reportlab.lib.pagesizes import A4, letter
+ ps = spec.get("page_size", "A4")
+ if isinstance(ps, (list, tuple)) and len(ps) == 2:
+ return float(ps[0]), float(ps[1])
+ return letter if str(ps).lower() == "letter" else A4
+
+
+def build_form(spec: dict, out_path: str) -> int:
+ try:
+ from reportlab.lib import colors
+ from reportlab.pdfgen import canvas
+ except ImportError:
+ print("Missing dependency: install with 'python3 -m pip install reportlab'", file=sys.stderr)
+ return 2
+
+ width, height = _page_size(spec)
+ page_count = int(spec.get("page_count", 1))
+ fields = spec.get("fields", [])
+ by_page: dict[int, list[dict]] = {}
+ for f in fields:
+ by_page.setdefault(int(f.get("page", 1)), []).append(f)
+ page_count = max([page_count, *by_page.keys()]) if by_page else page_count
+
+ c = canvas.Canvas(out_path, pagesize=(width, height))
+ if spec.get("title"):
+ c.setTitle(str(spec["title"]))
+ if spec.get("author"):
+ c.setAuthor(str(spec["author"]))
+ form = c.acroForm
+ created = []
+
+ for pageno in range(1, page_count + 1):
+ for f in by_page.get(pageno, []):
+ name = f["name"]
+ ftype = f.get("type", "text")
+ ex0, ey0, ex1, ey1 = (float(v) for v in f["entry_box"])
+ ew, eh = ex1 - ex0, ey1 - ey0
+ if f.get("label"):
+ lx, ly = (float(f["label_box"][0]), float(f["label_box"][1])) \
+ if f.get("label_box") else (ex0 - 90, ey0 + 4)
+ c.setFont("Helvetica", float(f.get("label_size", 10)))
+ c.setFillColor(colors.black)
+ c.drawString(lx, ly + 2, str(f["label"]))
+ tooltip = f.get("tooltip", "")
+ if ftype == "text":
+ form.textfield(name=name, x=ex0, y=ey0, width=ew, height=eh,
+ value=str(f.get("value", "")), tooltip=tooltip,
+ borderWidth=0.5, forceBorder=True)
+ elif ftype == "checkbox":
+ size = min(ew, eh)
+ form.checkbox(name=name, x=ex0, y=ey0, size=size,
+ checked=bool(f.get("checked", False)),
+ buttonStyle="check", tooltip=tooltip,
+ borderWidth=0.5, forceBorder=True)
+ elif ftype == "radio":
+ options = f.get("options", [])
+ if not options:
+ print(f"Warning: radio {name!r} has no options, skipped", file=sys.stderr)
+ continue
+ size = min(eh, ew / max(len(options), 1) * 0.5, 16)
+ slot = ew / len(options)
+ sel = f.get("value")
+ c.setFont("Helvetica", 8)
+ for i, opt in enumerate(options):
+ ox = ex0 + i * slot
+ form.radio(name=name, value=str(opt), x=ox, y=ey0, size=size,
+ selected=(str(opt) == str(sel)), buttonStyle="circle",
+ borderWidth=0.5, forceBorder=True)
+ c.drawString(ox + size + 2, ey0 + size / 3, str(opt))
+ elif ftype == "dropdown":
+ options = [str(o) for o in f.get("options", [])]
+ value = str(f.get("value", options[0] if options else ""))
+ form.choice(name=name, x=ex0, y=ey0, width=ew, height=eh,
+ options=options, value=value, tooltip=tooltip,
+ borderWidth=0.5, forceBorder=True)
+ else:
+ print(f"Warning: unknown field type {ftype!r} for {name!r}, skipped",
+ file=sys.stderr)
+ continue
+ created.append({"name": name, "type": ftype, "page": pageno})
+ c.showPage()
+ c.save()
+ print(json.dumps({"output": out_path, "pages": page_count, "fields": created},
+ ensure_ascii=False))
+ return 0
+
+
+def main() -> int:
+ _reconfigure_stdio()
+ parser = argparse.ArgumentParser(
+ description="Create a fillable AcroForm PDF from a JSON spec (reportlab).")
+ parser.add_argument("spec", help="Path to UTF-8 JSON form spec")
+ parser.add_argument("-o", "--output", required=True, help="Output PDF path")
+ args = parser.parse_args()
+ with open(args.spec, encoding="utf-8") as fh:
+ spec = json.load(fh)
+ return build_form(spec, args.output)
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/skills/productivity/pdf/scripts/pdf_meta.py b/skills/productivity/pdf/scripts/pdf_meta.py
new file mode 100644
index 00000000000..005a142f5d7
--- /dev/null
+++ b/skills/productivity/pdf/scripts/pdf_meta.py
@@ -0,0 +1,115 @@
+#!/usr/bin/env python3
+"""Document metadata and file attachments for PDFs (pypdf).
+
+Modes (one required):
+ --set-meta set metadata keys given via --title/--author/...
+ --clear-meta drop all document info metadata
+ --attach FILE embed a file attachment
+ --list-attachments list embedded attachment names
+ --extract-attachments DIR write all attachments into DIR
+
+Metadata note: values are stored in the classic DocInfo dictionary
+(Title/Author/Subject/Keywords). XMP metadata, if present, is not
+rewritten and may disagree in sophisticated viewers.
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import sys
+from pathlib import Path
+
+
+def main() -> int:
+ for stream in (sys.stdout, sys.stderr):
+ try:
+ stream.reconfigure(encoding="utf-8")
+ except Exception:
+ pass
+ parser = argparse.ArgumentParser(description="Set/clear PDF metadata; manage attachments.")
+ parser.add_argument("pdf", help="Input PDF path")
+ mode = parser.add_mutually_exclusive_group(required=True)
+ mode.add_argument("--set-meta", action="store_true", help="Set metadata fields")
+ mode.add_argument("--clear-meta", action="store_true", help="Remove all DocInfo metadata")
+ mode.add_argument("--attach", metavar="FILE", help="Embed FILE as an attachment")
+ mode.add_argument("--list-attachments", action="store_true", help="List attachment names")
+ mode.add_argument("--extract-attachments", metavar="DIR", help="Extract attachments into DIR")
+ parser.add_argument("-o", "--output", help="Output PDF (required for write modes)")
+ parser.add_argument("--title")
+ parser.add_argument("--author")
+ parser.add_argument("--subject")
+ parser.add_argument("--keywords")
+ parser.add_argument("--password", help="Password if the input is encrypted")
+ args = parser.parse_args()
+
+ try:
+ from pypdf import PdfReader, PdfWriter
+ except ImportError:
+ print("Missing dependency: install with 'python3 -m pip install pypdf'", file=sys.stderr)
+ return 2
+
+ reader = PdfReader(args.pdf)
+ if reader.is_encrypted:
+ if args.password is None or not reader.decrypt(args.password):
+ print("Error: input is encrypted; pass --password", file=sys.stderr)
+ return 3
+
+ if args.list_attachments:
+ names = list(reader.attachments.keys())
+ json.dump({"attachment_count": len(names), "attachments": names}, sys.stdout,
+ ensure_ascii=False, indent=2)
+ print()
+ return 0
+
+ if args.extract_attachments:
+ out_dir = Path(args.extract_attachments)
+ out_dir.mkdir(parents=True, exist_ok=True)
+ written = []
+ for name, contents in reader.attachments.items():
+ data = contents[0] if isinstance(contents, list) else contents
+ safe = os.path.basename(name) or "attachment.bin"
+ target = out_dir / safe
+ with open(target, "wb") as fh:
+ fh.write(bytes(data))
+ written.append(str(target))
+ json.dump({"extracted": written}, sys.stdout, ensure_ascii=False, indent=2)
+ print()
+ return 0
+
+ if not args.output:
+ print("Error: -o/--output is required for write modes", file=sys.stderr)
+ return 4
+
+ writer = PdfWriter()
+ writer.append(reader)
+
+ if args.set_meta:
+ meta = {}
+ for key, value in ((f"/{k.capitalize()}", getattr(args, k))
+ for k in ("title", "author", "subject", "keywords")):
+ if value is not None:
+ meta[key] = value
+ if not meta:
+ print("Error: --set-meta needs at least one of --title/--author/--subject/--keywords",
+ file=sys.stderr)
+ return 4
+ writer.add_metadata(meta)
+ result = {"output": args.output, "set": {k.lstrip("/"): v for k, v in meta.items()}}
+ elif args.clear_meta:
+ writer.metadata = None
+ result = {"output": args.output, "cleared": True}
+ else: # --attach
+ attach_path = Path(args.attach)
+ with open(attach_path, "rb") as fh:
+ writer.add_attachment(attach_path.name, fh.read())
+ result = {"output": args.output, "attached": attach_path.name}
+
+ with open(args.output, "wb") as fh:
+ writer.write(fh)
+ print(json.dumps(result, ensure_ascii=False))
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/skills/productivity/pdf/scripts/pdf_page_image.py b/skills/productivity/pdf/scripts/pdf_page_image.py
new file mode 100644
index 00000000000..bb25584820e
--- /dev/null
+++ b/skills/productivity/pdf/scripts/pdf_page_image.py
@@ -0,0 +1,99 @@
+#!/usr/bin/env python3
+"""Export PDF pages as PNG images at a chosen DPI.
+
+Rasterizer fallback chain: pypdfium2 (pip) -> pdftoppm (poppler-utils).
+When neither is available, exits 0 with {"rendered": false, "missing": [...]}
+so callers can branch instead of crashing.
+
+Typical uses: visual verification with a vision model, and exporting
+image-only (scanned) pages for hand-off to the ocr-and-documents skill.
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+from pathlib import Path
+
+
+def parse_pages(spec: str, page_count: int) -> list[int]:
+ """'1-3,5,9-' (1-based, inclusive) -> sorted page list."""
+ pages: set[int] = set()
+ for part in spec.split(","):
+ part = part.strip()
+ if not part:
+ continue
+ if "-" in part:
+ start_s, _, end_s = part.partition("-")
+ start = int(start_s) if start_s else 1
+ end = int(end_s) if end_s else page_count
+ pages.update(range(start, end + 1))
+ else:
+ pages.add(int(part))
+ bad = [p for p in pages if not 1 <= p <= page_count]
+ if bad:
+ raise ValueError(f"pages out of range 1-{page_count}: {sorted(bad)}")
+ return sorted(pages)
+
+
+def main() -> int:
+ for stream in (sys.stdout, sys.stderr):
+ try:
+ stream.reconfigure(encoding="utf-8")
+ except Exception:
+ pass
+ parser = argparse.ArgumentParser(description="Export PDF pages as PNG images.")
+ parser.add_argument("pdf", help="Input PDF path")
+ parser.add_argument("--pages", default="1-", help="1-based ranges, e.g. '1-3,5' (default: all)")
+ parser.add_argument("--dpi", type=int, default=150, help="Render DPI (default 150)")
+ parser.add_argument("--out-dir", required=True, help="Directory for PNG files")
+ parser.add_argument("--prefix", default="page", help="Output filename prefix (default 'page')")
+ parser.add_argument("--password", help="Password for encrypted PDFs")
+ args = parser.parse_args()
+
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
+ import _raster
+
+ if not _raster.available_backends():
+ json.dump({"rendered": False, "missing": _raster.missing_hints()}, sys.stdout)
+ print()
+ return 0
+
+ try:
+ from pypdf import PdfReader
+ except ImportError:
+ print("Missing dependency: install with 'python3 -m pip install pypdf'", file=sys.stderr)
+ return 2
+ reader = PdfReader(args.pdf)
+ if reader.is_encrypted:
+ if args.password is None or not reader.decrypt(args.password):
+ print("File is encrypted; pass --password.", file=sys.stderr)
+ return 3
+ page_count = len(reader.pages)
+
+ try:
+ pages = parse_pages(args.pages, page_count)
+ except ValueError as exc:
+ print(f"Error: {exc}", file=sys.stderr)
+ return 4
+
+ out_dir = Path(args.out_dir)
+ out_dir.mkdir(parents=True, exist_ok=True)
+ files = []
+ for pageno in pages:
+ img = _raster.rasterize_page(args.pdf, pageno, dpi=args.dpi, password=args.password)
+ if img is None:
+ json.dump({"rendered": False, "missing": _raster.missing_hints()}, sys.stdout)
+ print()
+ return 0
+ out_path = out_dir / f"{args.prefix}{pageno:03d}.png"
+ img.save(out_path)
+ files.append(str(out_path))
+ json.dump({"rendered": True, "dpi": args.dpi, "page_count": page_count,
+ "files": files}, sys.stdout, ensure_ascii=False, indent=2)
+ print()
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/skills/productivity/pdf/scripts/pdf_stamp.py b/skills/productivity/pdf/scripts/pdf_stamp.py
new file mode 100644
index 00000000000..f346f60a9f1
--- /dev/null
+++ b/skills/productivity/pdf/scripts/pdf_stamp.py
@@ -0,0 +1,143 @@
+#!/usr/bin/env python3
+"""Stamp text or an image at coordinates onto selected PDF pages.
+
+Builds an in-memory single-page overlay with reportlab, then merges it
+onto each selected page with pypdf. Coordinates are PDF points, origin
+bottom-left. Covers 'sign here' arrows, diagonal DRAFT banners, and
+page-corner labels.
+
+Examples:
+ pdf_stamp.py in.pdf -o out.pdf --text "DRAFT" --x 200 --y 400 \
+ --font-size 60 --rotation 45 --opacity 0.3 --color "#cc0000"
+ pdf_stamp.py in.pdf -o out.pdf --image sig.png --x 400 --y 60 \
+ --width 120 --pages 3
+"""
+from __future__ import annotations
+
+import argparse
+import io
+import json
+import sys
+
+
+def parse_pages(spec: str, page_count: int) -> list[int]:
+ pages: set[int] = set()
+ for part in spec.split(","):
+ part = part.strip()
+ if not part:
+ continue
+ if "-" in part:
+ start_s, _, end_s = part.partition("-")
+ start = int(start_s) if start_s else 1
+ end = int(end_s) if end_s else page_count
+ pages.update(range(start, end + 1))
+ else:
+ pages.add(int(part))
+ bad = [p for p in pages if not 1 <= p <= page_count]
+ if bad:
+ raise ValueError(f"pages out of range 1-{page_count}: {sorted(bad)}")
+ return sorted(pages)
+
+
+def build_overlay(args, page_width: float, page_height: float) -> bytes:
+ from reportlab.lib.colors import HexColor
+ from reportlab.pdfgen import canvas
+ buf = io.BytesIO()
+ c = canvas.Canvas(buf, pagesize=(page_width, page_height))
+ c.saveState()
+ try:
+ c.setFillAlpha(float(args.opacity))
+ c.setStrokeAlpha(float(args.opacity))
+ except Exception:
+ pass # very old reportlab: no alpha support
+ c.translate(float(args.x), float(args.y))
+ if args.rotation:
+ c.rotate(float(args.rotation))
+ if args.text:
+ c.setFont(args.font, float(args.font_size))
+ c.setFillColor(HexColor(args.color))
+ c.drawString(0, 0, args.text)
+ else:
+ kwargs = {}
+ if args.width:
+ kwargs["width"] = float(args.width)
+ if args.height:
+ kwargs["height"] = float(args.height)
+ if "width" in kwargs and "height" not in kwargs:
+ from PIL import Image as PILImage
+ with PILImage.open(args.image) as im:
+ kwargs["height"] = kwargs["width"] * im.height / im.width
+ c.drawImage(args.image, 0, 0, mask="auto", **kwargs)
+ c.restoreState()
+ c.save()
+ return buf.getvalue()
+
+
+def main() -> int:
+ for stream in (sys.stdout, sys.stderr):
+ try:
+ stream.reconfigure(encoding="utf-8")
+ except Exception:
+ pass
+ parser = argparse.ArgumentParser(description="Stamp text or an image onto PDF pages.")
+ parser.add_argument("pdf", help="Input PDF path")
+ parser.add_argument("-o", "--output", required=True, help="Output PDF path")
+ what = parser.add_mutually_exclusive_group(required=True)
+ what.add_argument("--text", help="Text to stamp")
+ what.add_argument("--image", help="Image file to stamp (PNG/JPEG)")
+ parser.add_argument("--x", type=float, required=True, help="X in points (origin bottom-left)")
+ parser.add_argument("--y", type=float, required=True, help="Y in points")
+ parser.add_argument("--pages", default="1-", help="1-based ranges, e.g. '1-3,5' (default: all)")
+ parser.add_argument("--font", default="Helvetica", help="Font name (default Helvetica)")
+ parser.add_argument("--font-size", type=float, default=24, help="Font size in points")
+ parser.add_argument("--color", default="#000000", help="Text color as #RRGGBB")
+ parser.add_argument("--rotation", type=float, default=0, help="Degrees counterclockwise")
+ parser.add_argument("--opacity", type=float, default=1.0, help="0.0-1.0 (default 1.0)")
+ parser.add_argument("--width", type=float, help="Image width in points")
+ parser.add_argument("--height", type=float, help="Image height in points")
+ parser.add_argument("--under", action="store_true",
+ help="Place the stamp under existing content instead of over it")
+ parser.add_argument("--password", help="Password if the input is encrypted")
+ args = parser.parse_args()
+
+ try:
+ from pypdf import PdfReader, PdfWriter
+ except ImportError:
+ print("Missing dependency: install with 'python3 -m pip install pypdf reportlab'",
+ file=sys.stderr)
+ return 2
+
+ reader = PdfReader(args.pdf)
+ if reader.is_encrypted:
+ if args.password is None or not reader.decrypt(args.password):
+ print("Error: input is encrypted; pass --password", file=sys.stderr)
+ return 3
+ try:
+ pages = set(parse_pages(args.pages, len(reader.pages)))
+ except ValueError as exc:
+ print(f"Error: {exc}", file=sys.stderr)
+ return 4
+
+ writer = PdfWriter()
+ overlay_cache: dict[tuple[float, float], object] = {}
+ for idx, page in enumerate(reader.pages, start=1):
+ if idx in pages:
+ size = (float(page.mediabox.width), float(page.mediabox.height))
+ if size not in overlay_cache:
+ overlay_pdf = PdfReader(io.BytesIO(build_overlay(args, *size)))
+ overlay_cache[size] = overlay_pdf.pages[0]
+ stamp = overlay_cache[size]
+ if args.under:
+ page.merge_page(stamp, over=False)
+ else:
+ page.merge_page(stamp)
+ writer.add_page(page)
+ with open(args.output, "wb") as fh:
+ writer.write(fh)
+ print(json.dumps({"output": args.output, "stamped_pages": sorted(pages),
+ "kind": "text" if args.text else "image"}, ensure_ascii=False))
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/skills/productivity/pdf/tests/test_pdf_skill.py b/skills/productivity/pdf/tests/test_pdf_skill.py
index 69b91f2779d..2b3da9ea5fd 100644
--- a/skills/productivity/pdf/tests/test_pdf_skill.py
+++ b/skills/productivity/pdf/tests/test_pdf_skill.py
@@ -171,3 +171,244 @@ def test_compress(report_pdf: Path, workdir: Path):
run("pdf_split.py", str(report_pdf), "--pages", "1-2", "--compress", "-o", str(out))
data = json.loads(run("pdf_read.py", str(out), "--text").stdout)
assert "UNIQUEMARK42" in data["pages"][0]
+
+
+# ---------------------------------------------------------------- form creation
+
+FORM_SPEC = {
+ "title": "Example Intake Form",
+ "page_size": "A4",
+ "fields": [
+ {"name": "surname", "type": "text", "page": 1, "label": "Surname",
+ "label_box": [72, 700, 150, 714], "entry_box": [160, 696, 400, 716]},
+ {"name": "agree", "type": "checkbox", "page": 1, "label": "I agree",
+ "label_box": [72, 660, 150, 674], "entry_box": [160, 658, 176, 674]},
+ {"name": "color", "type": "radio", "page": 1, "label": "Color",
+ "label_box": [72, 620, 150, 634], "entry_box": [160, 616, 400, 636],
+ "options": ["red", "blue"], "value": "blue"},
+ {"name": "size", "type": "dropdown", "page": 1, "label": "Size",
+ "label_box": [72, 580, 150, 594], "entry_box": [160, 576, 300, 596],
+ "options": ["small", "large"], "value": "small"},
+ ],
+}
+
+
[email protected](scope="module")
+def built_form(workdir: Path) -> Path:
+ spec_path = workdir / "formspec.json"
+ spec_path.write_text(json.dumps(FORM_SPEC), encoding="utf-8")
+ out = workdir / "built_form.pdf"
+ result = json.loads(run("pdf_make_form.py", str(spec_path), "-o", str(out)).stdout)
+ assert len(result["fields"]) == 4
+ return out
+
+
+def test_make_form_lists_all_fields(built_form: Path):
+ data = json.loads(run("pdf_read.py", str(built_form), "--fields").stdout)
+ fields = data["fields"]
+ assert set(fields) == {"surname", "agree", "color", "size"}
+ assert fields["surname"]["type"] == "text"
+ assert fields["agree"]["options"] == ["/Off", "/Yes"]
+ assert fields["color"]["value"] == "/blue" # pre-selected radio
+ assert set(fields["size"]["options"]) == {"small", "large"}
+ # label text is drawn on the page, not just stored in the widget
+ text = json.loads(run("pdf_read.py", str(built_form), "--text").stdout)
+ assert "Surname" in text["pages"][0] and "Size" in text["pages"][0]
+
+
+def test_make_form_fill_roundtrip(built_form: Path, workdir: Path):
+ values = {"surname": "Smith", "agree": True, "color": "/red", "size": "large"}
+ vals = workdir / "builtvals.json"
+ vals.write_text(json.dumps(values), encoding="utf-8")
+ filled = workdir / "built_filled.pdf"
+ run("pdf_fill_form.py", str(built_form), "--fields-json", str(vals), "-o", str(filled))
+ fields = json.loads(run("pdf_read.py", str(filled), "--fields").stdout)["fields"]
+ assert fields["surname"]["value"] == "Smith"
+ assert fields["agree"]["value"] == "/Yes"
+ assert fields["color"]["value"] == "/red"
+ assert fields["size"]["value"] == "large"
+
+
+# ------------------------------------------------------------- layout validation
+
+def test_form_layout_valid_spec(workdir: Path):
+ spec_path = workdir / "layout_ok.json"
+ spec_path.write_text(json.dumps(FORM_SPEC), encoding="utf-8")
+ report = json.loads(run("pdf_form_layout.py", str(spec_path)).stdout)
+ assert report["ok"] is True
+ assert report["errors"] == 0
+ assert all(f["ok"] for f in report["fields"])
+
+
+def test_form_layout_detects_problems(workdir: Path):
+ bad = {
+ "page_size": "A4",
+ "fields": [
+ # out of bounds (x1 beyond A4 width)
+ {"name": "wide", "type": "text", "page": 1, "label": "Wide",
+ "label_box": [10, 700, 60, 714], "entry_box": [70, 696, 900, 716]},
+ # two overlapping entry boxes
+ {"name": "one", "type": "text", "page": 1, "label": "One",
+ "label_box": [10, 600, 60, 614], "entry_box": [70, 596, 300, 616]},
+ {"name": "two", "type": "text", "page": 1, "label": "Two",
+ "label_box": [10, 560, 60, 574], "entry_box": [200, 600, 400, 620]},
+ # label far away from its entry
+ {"name": "lost", "type": "text", "page": 1, "label": "Lost",
+ "label_box": [10, 100, 60, 114], "entry_box": [400, 500, 500, 520]},
+ # too small
+ {"name": "tiny", "type": "text", "page": 1,
+ "entry_box": [10, 50, 14, 54]},
+ ],
+ }
+ spec_path = workdir / "layout_bad.json"
+ spec_path.write_text(json.dumps(bad), encoding="utf-8")
+ proc = run("pdf_form_layout.py", str(spec_path), expect=1)
+ report = json.loads(proc.stdout)
+ assert report["ok"] is False
+ by_name = {f["name"]: f for f in report["fields"]}
+ assert any("bounds" in p for p in by_name["wide"]["problems"])
+ assert any("overlaps field" in p for p in by_name["two"]["problems"])
+ assert any("from its entry" in p for p in by_name["lost"]["problems"])
+ assert any("minimum size" in p for p in by_name["tiny"]["problems"])
+ assert by_name["one"]["ok"] # first of the overlapping pair reports clean
+
+
+# ------------------------------------------------- rasterization (overlay, pages)
+
+def _raster_available() -> bool:
+ import shutil
+ try:
+ import pypdfium2 # noqa: F401
+ return True
+ except ImportError:
+ return shutil.which("pdftoppm") is not None
+
+
+def test_form_layout_overlay(built_form: Path, workdir: Path):
+ spec_path = workdir / "formspec.json"
+ out_png = workdir / "overlay.png"
+ report = json.loads(run("pdf_form_layout.py", str(spec_path), "--pdf", str(built_form),
+ "--render-overlay", str(out_png)).stdout)
+ overlay = report["overlay"]
+ if _raster_available():
+ assert overlay["rendered"] is True
+ assert out_png.exists() and out_png.stat().st_size > 1000
+ from PIL import Image
+ with Image.open(out_png) as img:
+ assert img.width > 100 and img.height > 100
+ else:
+ assert overlay["rendered"] is False
+ assert overlay["missing"] # install hints present
+
+
+def test_form_layout_overlay_blank_page(workdir: Path):
+ # No --pdf: overlay is drawn on a blank page, PIL-only, always renders.
+ spec_path = workdir / "formspec.json"
+ out_png = workdir / "overlay_blank.png"
+ report = json.loads(run("pdf_form_layout.py", str(spec_path),
+ "--render-overlay", str(out_png)).stdout)
+ assert report["overlay"]["rendered"] is True
+ assert out_png.exists()
+
+
+def test_page_image_export(report_pdf: Path, workdir: Path):
+ out_dir = workdir / "pageimgs"
+ result = json.loads(run("pdf_page_image.py", str(report_pdf), "--pages", "1-2",
+ "--dpi", "72", "--out-dir", str(out_dir)).stdout)
+ if _raster_available():
+ assert result["rendered"] is True
+ assert len(result["files"]) == 2
+ from PIL import Image
+ with Image.open(result["files"][0]) as img:
+ # A4 at 72 dpi is ~595x842 px
+ assert 500 < img.width < 700
+ else:
+ assert result["rendered"] is False
+ assert result["missing"]
+
+
+def test_page_image_bad_range(report_pdf: Path, workdir: Path):
+ if not _raster_available():
+ pytest.skip("no rasterizer available")
+ run("pdf_page_image.py", str(report_pdf), "--pages", "9",
+ "--out-dir", str(workdir / "nope"), expect=4)
+
+
+# --------------------------------------------------------------------- stamping
+
+def test_stamp_text(report_pdf: Path, workdir: Path):
+ out = workdir / "stamp_text.pdf"
+ run("pdf_stamp.py", str(report_pdf), "-o", str(out),
+ "--text", "STAMPMARK77", "--x", "150", "--y", "500",
+ "--font-size", "30", "--color", "#cc0000", "--pages", "1")
+ data = json.loads(run("pdf_read.py", str(out), "--text").stdout)
+ assert "STAMPMARK77" in data["pages"][0]
+ assert "STAMPMARK77" not in data["pages"][1] # only page 1 stamped
+
+
+def test_stamp_text_rotated_opacity(report_pdf: Path, workdir: Path):
+ out = workdir / "stamp_rot.pdf"
+ run("pdf_stamp.py", str(report_pdf), "-o", str(out),
+ "--text", "DRAFT", "--x", "150", "--y", "400", "--font-size", "60",
+ "--rotation", "45", "--opacity", "0.3")
+ # Rotated glyphs confuse pdfplumber's line grouping; verify via pypdf.
+ from pypdf import PdfReader
+ text = PdfReader(str(out)).pages[0].extract_text()
+ assert "DRAFT" in text
+
+
+def test_stamp_image(report_pdf: Path, sample_image: Path, workdir: Path):
+ out = workdir / "stamp_img.pdf"
+ run("pdf_stamp.py", str(report_pdf), "-o", str(out),
+ "--image", str(sample_image), "--x", "400", "--y", "60",
+ "--width", "100", "--pages", "2")
+ from pypdf import PdfReader
+ before = PdfReader(str(report_pdf))
+ after = PdfReader(str(out))
+
+ def image_xobjects(page):
+ res = page.get("/Resources", {})
+ xo = res.get("/XObject")
+ if xo is None:
+ return 0
+ return sum(1 for k in xo if xo[k].get("/Subtype") == "/Image")
+
+ assert image_xobjects(after.pages[1]) > image_xobjects(before.pages[1])
+ assert image_xobjects(after.pages[0]) == image_xobjects(before.pages[0])
+
+
+# --------------------------------------------------------- metadata + attachments
+
+def test_meta_set_and_clear(report_pdf: Path, workdir: Path):
+ out = workdir / "meta_set.pdf"
+ run("pdf_meta.py", str(report_pdf), "--set-meta", "-o", str(out),
+ "--title", "Retitled Example", "--author", "example-author",
+ "--subject", "Testing", "--keywords", "alpha, beta")
+ meta = json.loads(run("pdf_read.py", str(out), "--meta").stdout)["metadata"]
+ assert meta["Title"] == "Retitled Example"
+ assert meta["Author"] == "example-author"
+ assert meta["Subject"] == "Testing"
+ assert meta["Keywords"] == "alpha, beta"
+
+ cleared = workdir / "meta_clear.pdf"
+ run("pdf_meta.py", str(out), "--clear-meta", "-o", str(cleared))
+ meta = json.loads(run("pdf_read.py", str(cleared), "--meta").stdout)["metadata"]
+ assert "Title" not in meta or meta.get("Title") in ("", None)
+
+
+def test_attachments_roundtrip(report_pdf: Path, workdir: Path):
+ payload = workdir / "payload.txt"
+ payload.write_text("attachment payload UNIQUEATTACH99\n", encoding="utf-8")
+ with_att = workdir / "with_att.pdf"
+ run("pdf_meta.py", str(report_pdf), "--attach", str(payload), "-o", str(with_att))
+
+ listing = json.loads(run("pdf_meta.py", str(with_att), "--list-attachments").stdout)
+ assert listing["attachment_count"] == 1
+ assert listing["attachments"] == ["payload.txt"]
+
+ ext_dir = workdir / "extracted"
+ result = json.loads(run("pdf_meta.py", str(with_att),
+ "--extract-attachments", str(ext_dir)).stdout)
+ assert len(result["extracted"]) == 1
+ extracted = Path(result["extracted"][0])
+ assert "UNIQUEATTACH99" in extracted.read_text(encoding="utf-8")
diff --git a/skills/productivity/powerpoint/SKILL.md b/skills/productivity/powerpoint/SKILL.md
index 02f284ca148..0fa88debd6d 100644
--- a/skills/productivity/powerpoint/SKILL.md
+++ b/skills/productivity/powerpoint/SKILL.md
@@ -1,7 +1,7 @@
---
name: powerpoint
description: Create, read, edit .pptx decks with python-pptx.
-version: 1.0.0
+version: 1.1.0
author: Nous Research
license: MIT
platforms: [linux, macos, windows]
@@ -15,17 +15,18 @@ metadata:
# Powerpoint Skill
Create, inspect, and edit PowerPoint (.pptx) presentations using the
-python-pptx library. Four helper scripts cover deck creation from a JSON
-spec, structured read-back, in-place edits, and template-driven brand
-decks — all offline, no PowerPoint installation required.
+python-pptx library. Five helper scripts cover deck creation from a JSON
+spec, structured read-back, in-place edits, template-driven brand decks,
+and slide rendering — all offline, no PowerPoint installation required.
## When to Use
- The user asks to build a slide deck, report presentation, or pitch deck.
- You need to extract text, notes, tables, chart data, or images from a
.pptx someone shared.
-- You need to update an existing deck: replace text, refresh chart data,
- swap a logo, remove or reorder slides.
+- You need to update an existing deck: replace text, refresh or patch
+ chart data, swap a logo, duplicate/remove/reorder slides, set
+ backgrounds, footers, hyperlinks, or speaker notes.
- You must produce an on-brand deck from a company .pptx template.
- Do NOT use this for .ppt (legacy binary) files — convert them first with
`soffice --convert-to pptx old.ppt` if LibreOffice is available.
@@ -33,13 +34,14 @@ decks — all offline, no PowerPoint installation required.
## Prerequisites
- Python 3.10+ with `python-pptx` installed
- (`pip install python-pptx`). Pillow is optional (only if you need to
- probe image dimensions yourself).
-- Optional: LibreOffice (`soffice`) for rendering slides to images for
- visual verification. Degrade gracefully if absent — all create/read/edit
- operations work without it.
+ (`pip install python-pptx`).
+- Optional: LibreOffice (`soffice`) plus poppler (`pdftoppm` or
+ `pdftocairo`) for rendering slides to PNGs and for PDF export.
+ `pptx_render.py` detects both with `shutil.which` and degrades
+ gracefully (reports `{"rendered": false, "missing": [...]}`, exit 0)
+ when absent — all create/read/edit operations work without them.
- Check availability via `terminal`:
- `python3 -c "import pptx; print(pptx.__version__)"` and `which soffice`.
+ `python3 -c "import pptx; print(pptx.__version__)"` and `which soffice pdftoppm`.
## How to Run
@@ -53,8 +55,10 @@ python3 scripts/pptx_read.py deck.pptx --notes # speaker notes
python3 scripts/pptx_read.py deck.pptx --images ./img # export pictures
python3 scripts/pptx_edit.py deck.pptx --replace-text "Old Corp" "New Corp"
python3 scripts/pptx_edit.py deck.pptx --chart-data update.json
+python3 scripts/pptx_edit.py deck.pptx --duplicate-slide 2
python3 scripts/pptx_edit.py deck.pptx --remove-slide 3 --move-slide 2 0
python3 scripts/pptx_from_template.py brand.pptx out.pptx --values vals.json
+python3 scripts/pptx_render.py deck.pptx --outdir ./render # slide PNGs
```
Author JSON specs with `write_file`; inspect script output and generated
@@ -69,11 +73,20 @@ JSON with `read_file`.
| Outline as JSON | `pptx_read.py deck.pptx --outline` |
| Export images | `pptx_read.py deck.pptx --images DIR` |
| Replace text | `pptx_edit.py deck.pptx --replace-text OLD NEW` |
-| Update chart | `pptx_edit.py deck.pptx --chart-data spec.json` |
+| Replace chart data | `pptx_edit.py deck.pptx --chart-data spec.json` |
+| Patch one series | same flag, spec with `"ops"` (see below) |
| Swap picture | `pptx_edit.py deck.pptx --swap-image N NAME new.png` |
+| Duplicate slide | `pptx_edit.py deck.pptx --duplicate-slide N` |
| Remove slide | `pptx_edit.py deck.pptx --remove-slide N` |
| Reorder slide | `pptx_edit.py deck.pptx --move-slide FROM TO` |
+| Slide background | `pptx_edit.py deck.pptx --set-background N RRGGBB` |
+| Hyperlink runs | `pptx_edit.py deck.pptx --hyperlink N TEXT URL` |
+| Slide number on | `pptx_edit.py deck.pptx --enable-slide-number N` |
+| Footer text | `pptx_edit.py deck.pptx --set-footer N TEXT` |
+| Set notes | `pptx_edit.py deck.pptx --set-notes N TEXT` |
+| Append notes | `pptx_edit.py deck.pptx --append-notes N TEXT` |
| Fill template | `pptx_from_template.py tpl.pptx out.pptx --values v.json` |
+| Render slide PNGs | `pptx_render.py deck.pptx --outdir DIR` |
## Procedure
@@ -83,11 +96,14 @@ Write a JSON spec (see `pptx_create.py --help` for the full format), then
run `pptx_create.py`. Per slide you can set: `layout` (title,
title_content, section, two_content, title_only, blank), `title`,
`subtitle`, `bullets` (strings, or dicts with `level` 0-4, `size` pt,
-`bold`, `italic`, `font`, `color` hex), `images` (path + left/top/width/
-height in inches), `tables` (`rows` as list-of-lists), `shapes`
-(rectangle, rounded_rectangle, oval, diamond, right_arrow, chevron, with
-`fill` hex + optional `text`), `charts` (bar, bar_h, line, pie with
-`categories` + `series`), and `notes` (speaker notes).
+`bold`, `italic`, `font`, `color` hex, `link` URL for a hyperlink),
+`background` (solid hex), `footer` (text; enables the layout's footer
+placeholder), `slide_number` (true; enables the layout's slide-number
+placeholder), `images` (path + left/top/width/height in inches), `tables`
+(`rows` as list-of-lists), `shapes` (rectangle, rounded_rectangle, oval,
+diamond, right_arrow, chevron, with `fill` hex + optional `text`),
+`charts` (bar, bar_h, line, pie with `categories` + `series`), and
+`notes` (speaker notes).
### 2. Read a deck
@@ -101,12 +117,27 @@ Use `--images DIR` to dump embedded pictures to files, then
`pptx_edit.py` combines operations in one pass; use `--output` to keep the
original. Text replacement scans slide shapes, table cells, and notes.
-Chart update uses `chart.replace_data()` with a JSON spec naming the
-slide/chart index and new categories/series. Image swap retargets the
-picture's relationship id so position and size are preserved. Slide
-removal drops the relationship and the `<p:sldId>` entry; reorder moves
-the `<p:sldId>` element within `<p:sldIdLst>` (python-pptx has no public
-API for either — the script does the XML-level work).
+Image swap retargets the picture's relationship id so position and size
+are preserved. Slide removal drops the relationship and the `<p:sldId>`
+entry; reorder moves the `<p:sldId>` element within `<p:sldIdLst>`
+(python-pptx has no public API for either — the script does the XML-level
+work). `--duplicate-slide N` appends an independent deep copy of slide N:
+shape XML plus image/media/hyperlink relationships are cloned and rIds
+remapped, so editing the copy never touches the original. Chart slides
+are refused (see Pitfalls). `--set-notes`/`--append-notes` edit speaker
+notes; `--set-background`, `--hyperlink`, `--enable-slide-number`, and
+`--set-footer` handle deck polish.
+
+Chart updates take a JSON spec via `--chart-data`. Full replace:
+`{"slide": 0, "chart": 0, "categories": [...], "series": {...}}`. For
+surgical edits, pass `"ops"` instead — a list of
+`{"op": "update_series", "name": ..., "values": [...]}`,
+`add_series`, `remove_series`, `rename_category` (`from`/`to` or
+`index`), and `set_title`. python-pptx can only swap a chart's entire
+dataset (`replace_data`), so ops are implemented as read-existing →
+modify → replace; the per-part UX is a wrapper, and any chart data not
+expressible as categories + numeric series will be normalized by the
+round-trip.
### 4. Build from a template
@@ -117,36 +148,56 @@ so they inherit the master's fonts and colors. Tip: to start from a
template with zero slides, delete existing ones afterward with
`pptx_edit.py --remove-slide`.
-### 5. Visual verification (optional)
+### 5. Visual verification
-If `soffice` exists, render slides to PNG and inspect with
-`vision_analyze`:
+`pptx_render.py deck.pptx --outdir ./render` converts the deck to PDF
+with `soffice --headless` and splits it into one PNG per slide with
+`pdftoppm` (or `pdftocairo`). Output JSON lists the PNG paths — review
+each with `vision_analyze`. When either tool is missing the script exits
+0 with `{"rendered": false, "missing": [...]}` and guidance; fall back to
+the JSON outline from `pptx_read.py`, which verifies content and
+structure, just not visuals.
+
+## Converting to PDF
+
+If LibreOffice is installed, export the finished deck to PDF directly:
```bash
-soffice --headless --convert-to png --outdir ./render deck.pptx # slide 1
-soffice --headless --convert-to pdf --outdir ./render deck.pptx # all slides
+soffice --headless --convert-to pdf --outdir ./out deck.pptx
```
-PNG export renders only the first slide; convert to PDF for all slides
-(then `pdftoppm -png render/deck.pdf render/slide` if poppler is
-available). When `soffice` is absent, rely on the JSON outline from
-`pptx_read.py` — it verifies content and structure, just not visuals.
+The output lands at `./out/deck.pdf`. Fonts not installed on the host are
+substituted, so render-verify (Procedure step 5) before shipping the PDF.
+There is no offline pure-Python .pptx→PDF path; if `soffice` is absent,
+say so rather than approximating.
## Pitfalls
-- **Run splitting**: PowerPoint fragments paragraph text into multiple
- runs at spell-check and formatting boundaries. `--replace-text`
- preserves formatting exactly when a match lies within one run; when the
- match spans runs, the paragraph is rewritten with only the first run's
- formatting. Verify important slides after replacement.
+- **Run splitting**: PowerPoint fragments paragraph text into runs at
+ spell-check and edit boundaries. `--replace-text` first merges adjacent
+ runs whose formatting is identical, so matches split across such runs
+ are replaced with formatting fully preserved. Only when a match spans
+ *genuinely differently-formatted* runs is the paragraph rewritten with
+ the first run's formatting — verify those slides after replacement.
+- **Chart slides cannot be duplicated**: each chart relationship embeds a
+ separate XLSX workbook part; cloning that graph reliably is not
+ supported, so `--duplicate-slide` refuses chart slides cleanly instead
+ of corrupting the deck. Rebuild the chart on a new slide instead.
+ External-hyperlink and image/media rels are carried over; layout and
+ notes rels are recreated fresh.
+- **Chart ops are a wrapper**: python-pptx replaces the whole dataset;
+ `"ops"` round-trips existing plot data through `replace_data`, and
+ changing chart *type* is not possible.
- **Reordering is XML-level**: python-pptx has no supported reorder API.
- `--move-slide` manipulates `<p:sldIdLst>` directly; it is safe for
- ordinary decks but re-read the deck afterward to confirm.
-- **Copying slides between decks is unsupported** — layouts, images, and
- relationships would need deep cloning. Rebuild the slide in the target
- deck instead.
-- Chart edits replace the whole data set; you cannot patch a single cell.
- Adding/removing series works, but changing chart *type* does not.
+ `--move-slide` manipulates `<p:sldIdLst>` directly; safe for ordinary
+ decks but re-read the deck afterward to confirm.
+- **Copying slides between decks is unsupported** — duplication works
+ only within one deck, where layouts and masters are shared.
+- Footer/slide-number enablement copies the placeholder from the slide's
+ layout; on layouts without those placeholders, `--set-footer` fails
+ with a clear message (add a textbox instead).
+- Hyperlinks apply to whole runs; `--hyperlink` links every run
+ containing the given text on that slide.
- The default python-pptx template is 4:3; the create script sets 16:9
unless the spec says otherwise. Custom templates keep their own size.
- Layout indexes vary by template. For brand templates, list layout names
@@ -161,7 +212,9 @@ available). When `soffice` is absent, rely on the JSON outline from
1. After any create/edit, run `pptx_read.py OUT.pptx --outline` and check
slide count, texts, tables, notes, and chart values match intent.
2. `--images DIR` then file-size check confirms pictures embedded.
-3. For high-stakes decks, render via `soffice` (see Procedure step 5) and
- review each slide image with `vision_analyze`.
+3. Render every slide with `pptx_render.py deck.pptx --outdir ./render`
+ and review each PNG with `vision_analyze` — this catches overlapping
+ shapes, truncated text, and color problems the outline cannot. If the
+ render tools are missing, the script says so; rely on the outline.
4. The bundled test suite is the full contract:
`python3 -m pytest tests/ -q` (requires python-pptx + pytest).
diff --git a/skills/productivity/powerpoint/scripts/pptx_create.py b/skills/productivity/powerpoint/scripts/pptx_create.py
index 05d1b524ecd..71d18765a87 100644
--- a/skills/productivity/powerpoint/scripts/pptx_create.py
+++ b/skills/productivity/powerpoint/scripts/pptx_create.py
@@ -10,7 +10,11 @@ Spec format (all positions/sizes in inches, colors as RRGGBB hex):
"bullets": ["Top item",
{"text": "Sub item", "level": 1, "bold": true,
"size": 18, "color": "CC0000", "font": "Arial",
- "italic": false}],
+ "italic": false,
+ "link": "https://example.com/agenda"}],
+ "background": "1F2937", // solid slide background (hex)
+ "footer": "Confidential", // footer placeholder text
+ "slide_number": true, // enable slide-number placeholder
"notes": "Speaker notes for this slide"},
{"layout": "blank", "title": "Widgets",
"images": [{"path": "logo.png", "left": 1, "top": 1, "width": 3}],
@@ -30,6 +34,7 @@ Chart types: bar, bar_h, line, pie Shape types: rectangle,
rounded_rectangle, oval, diamond, right_arrow, chevron
"""
import argparse
+import copy
import json
import sys
@@ -66,6 +71,8 @@ def style_run(run, spec):
font.name = spec["font"]
if spec.get("color"):
font.color.rgb = RGBColor.from_string(spec["color"])
+ if spec.get("link"):
+ run.hyperlink.address = spec["link"]
def add_bullets(text_frame, bullets):
@@ -80,10 +87,34 @@ def add_bullets(text_frame, bullets):
style_run(run, item)
+def copy_layout_placeholder(slide, ph_idx):
+ """Copy a layout placeholder (footer=11, slide number=12) onto the
+ slide so it actually renders; returns the shape or None if the layout
+ does not provide it."""
+ for ph in slide.slide_layout.placeholders:
+ if ph.placeholder_format.idx == ph_idx:
+ slide.shapes._spTree.append(copy.deepcopy(ph._element))
+ for shape in slide.placeholders:
+ if shape.placeholder_format.idx == ph_idx:
+ return shape
+ return None
+
+
def build_slide(prs, spec):
layout_idx = LAYOUTS.get(spec.get("layout", "title_content"), 1)
slide = prs.slides.add_slide(prs.slide_layouts[layout_idx])
+ if spec.get("background"):
+ fill = slide.background.fill
+ fill.solid()
+ fill.fore_color.rgb = RGBColor.from_string(spec["background"])
+ if spec.get("slide_number"):
+ copy_layout_placeholder(slide, 12)
+ if spec.get("footer"):
+ shape = copy_layout_placeholder(slide, 11)
+ if shape is not None:
+ shape.text_frame.text = spec["footer"]
+
if spec.get("title") is not None and slide.shapes.title is not None:
slide.shapes.title.text = spec["title"]
if spec.get("subtitle") is not None:
diff --git a/skills/productivity/powerpoint/scripts/pptx_edit.py b/skills/productivity/powerpoint/scripts/pptx_edit.py
index 6e8f30fb8d3..9acaacd461a 100644
--- a/skills/productivity/powerpoint/scripts/pptx_edit.py
+++ b/skills/productivity/powerpoint/scripts/pptx_edit.py
@@ -3,28 +3,83 @@
Operations (repeatable / combinable):
--replace-text OLD NEW Replace text everywhere (slides, tables, notes).
- Run-level replace preserves formatting when the
- match sits inside a single run; if PowerPoint has
- split the match across runs, the whole paragraph
- is rewritten using the first run's font.
- --chart-data SPEC.json Replace data of a chart. Spec:
+ Adjacent runs with identical formatting are
+ merged first, so matches PowerPoint split across
+ identically-formatted runs keep their formatting.
+ Only a match spanning genuinely different
+ formats falls back to a paragraph rewrite with
+ the first run's font (documented caveat).
+ --chart-data SPEC.json Update a chart. Full replace spec:
{"slide": 0, "chart": 0,
"categories": ["Q1", "Q2"],
"series": {"North": [1, 2], "South": [3, 4]}}
+ Or surgical ops (existing data is read, modified,
+ and written back via replace_data):
+ {"slide": 0, "chart": 0, "ops": [
+ {"op": "update_series", "name": "North",
+ "values": [5, 6]},
+ {"op": "add_series", "name": "East",
+ "values": [1, 2]},
+ {"op": "remove_series", "name": "South"},
+ {"op": "rename_category", "from": "Q1",
+ "to": "Q1 FY26"},
+ {"op": "set_title", "title": "New title"}]}
--swap-image SLIDE SHAPE_NAME NEW_IMAGE
Replace a picture's bits, keeping position/size.
--remove-slide N Delete slide at index N (0-based).
- --move-slide FROM TO Reorder: move slide FROM to position TO
- (0-based; XML-level _sldIdLst manipulation).
+ --move-slide FROM TO Reorder: move slide FROM to position TO.
+ --duplicate-slide N Append an independent deep copy of slide N
+ (text, images, tables, shapes, notes). Refuses
+ slides containing charts (a chart embeds an XLSX
+ workbook part that cannot be cloned reliably).
+ --set-background N HEX Solid background color for slide N.
+ --hyperlink N TEXT URL Make runs containing TEXT on slide N links.
+ --enable-slide-number N Copy the layout's slide-number placeholder in.
+ --set-footer N TEXT Enable the layout's footer placeholder with TEXT.
+ --set-notes N TEXT Replace slide N's speaker notes.
+ --append-notes N TEXT Append a paragraph to slide N's speaker notes.
"""
import argparse
import copy
import json
import sys
+from lxml import etree
from pptx import Presentation
from pptx.chart.data import CategoryChartData
+from pptx.dml.color import RGBColor
from pptx.enum.shapes import MSO_SHAPE_TYPE
+from pptx.oxml.ns import qn
+
+R_EMBED = "{http://schemas.openxmlformats.org/officeDocument/2006/relationships}"
+
+
+def _run_format_key(r):
+ """Canonical string for a run's <a:rPr>; None when absent."""
+ rPr = r.find(qn("a:rPr"))
+ if rPr is None:
+ return None
+ return etree.tostring(rPr)
+
+
+def normalize_runs(para):
+ """Merge adjacent runs whose formatting is byte-identical.
+
+ PowerPoint splits paragraph text into runs at spell-check and edit
+ boundaries even when formatting never changes; merging them back makes
+ cross-run text replacement lossless for the common case.
+ """
+ runs = list(para.runs)
+ i = 0
+ while i + 1 < len(runs):
+ a, b = runs[i], runs[i + 1]
+ if (_run_format_key(a._r) == _run_format_key(b._r)
+ and a._r.getnext() is b._r):
+ a.text = a.text + b.text
+ b._r.getparent().remove(b._r)
+ runs.pop(i + 1)
+ else:
+ i += 1
def replace_in_text_frame(text_frame, old, new):
@@ -33,6 +88,10 @@ def replace_in_text_frame(text_frame, old, new):
joined = "".join(run.text for run in para.runs)
if old not in joined:
continue
+ if not any(old in run.text for run in para.runs):
+ # Match spans runs: merge identically-formatted neighbours
+ # first, which resolves pure spell-check splits losslessly.
+ normalize_runs(para)
if any(old in run.text for run in para.runs):
# Run-level replace: preserves each run's formatting exactly.
for run in para.runs:
@@ -40,8 +99,9 @@ def replace_in_text_frame(text_frame, old, new):
count += run.text.count(old)
run.text = run.text.replace(old, new)
else:
- # Match split across runs -> rewrite paragraph text,
- # keeping only the first run's formatting (documented caveat).
+ # Match spans genuinely differently-formatted runs -> rewrite
+ # paragraph, keeping only the first run's formatting (caveat).
+ joined = "".join(run.text for run in para.runs)
count += joined.count(old)
first = para.runs[0]
first.text = joined.replace(old, new)
@@ -70,7 +130,26 @@ def replace_text(prs, old, new):
return total
+def _read_chart_data(chart):
+ """Current categories and ordered (name, values) pairs of a chart."""
+ categories = [str(c) for c in chart.plots[0].categories]
+ series = []
+ for plot in chart.plots:
+ for s in plot.series:
+ try:
+ name = s.name
+ except (AttributeError, KeyError):
+ name = ""
+ series.append([name, list(s.values)])
+ return categories, series
+
+
def update_chart(prs, spec_path):
+ """Full replace ("categories"+"series") or surgical "ops".
+
+ python-pptx can only swap a chart's entire dataset (replace_data), so
+ surgical ops are implemented as read-existing -> modify -> replace.
+ """
with open(spec_path, encoding="utf-8") as fh:
spec = json.load(fh)
slide = prs.slides[spec.get("slide", 0)]
@@ -78,6 +157,50 @@ def update_chart(prs, spec_path):
if not charts:
raise SystemExit(f"no chart on slide {spec.get('slide', 0)}")
chart = charts[spec.get("chart", 0)]
+
+ if "ops" in spec:
+ categories, series = _read_chart_data(chart)
+ dirty = False
+ for op in spec["ops"]:
+ kind = op["op"]
+ if kind == "update_series":
+ match = [s for s in series if s[0] == op["name"]]
+ if not match:
+ raise SystemExit(f"no series named {op['name']!r}")
+ match[0][1] = op["values"]
+ dirty = True
+ elif kind == "add_series":
+ series.append([op["name"], op["values"]])
+ dirty = True
+ elif kind == "remove_series":
+ before = len(series)
+ series = [s for s in series if s[0] != op["name"]]
+ if len(series) == before:
+ raise SystemExit(f"no series named {op['name']!r}")
+ dirty = True
+ elif kind == "rename_category":
+ if "index" in op:
+ idx = int(op["index"])
+ else:
+ if op["from"] not in categories:
+ raise SystemExit(
+ f"no category named {op['from']!r}")
+ idx = categories.index(op["from"])
+ categories[idx] = op["to"]
+ dirty = True
+ elif kind == "set_title":
+ chart.has_title = True
+ chart.chart_title.text_frame.text = op["title"]
+ else:
+ raise SystemExit(f"unknown chart op {kind!r}")
+ if dirty:
+ data = CategoryChartData()
+ data.categories = categories
+ for name, values in series:
+ data.add_series(name, values)
+ chart.replace_data(data)
+ return
+
data = CategoryChartData()
data.categories = spec["categories"]
for name, values in spec["series"].items():
@@ -92,7 +215,7 @@ def swap_image(prs, slide_idx, shape_name, new_path):
and shape.name == shape_name):
image_part, rid = slide.part.get_or_add_image_part(new_path)
blip = shape._element.blipFill.blip
- blip.set("{http://schemas.openxmlformats.org/officeDocument/2006/relationships}embed", rid)
+ blip.set(R_EMBED + "embed", rid)
return True
raise SystemExit(f"no picture named {shape_name!r} on slide {slide_idx}")
@@ -100,7 +223,7 @@ def swap_image(prs, slide_idx, shape_name, new_path):
def remove_slide(prs, index):
sldIdLst = prs.slides._sldIdLst
slide_id = list(sldIdLst)[int(index)]
- rid = slide_id.get("{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id")
+ rid = slide_id.get(R_EMBED + "id")
prs.part.drop_rel(rid)
sldIdLst.remove(slide_id)
@@ -114,12 +237,132 @@ def move_slide(prs, src, dst):
sldIdLst.insert(int(dst), element)
+def duplicate_slide(prs, index):
+ """Append an independent deep copy of slide `index`.
+
+ Copies the shape tree XML and re-creates image/media relationships on
+ the new slide part, remapping rIds. Charts are refused: each chart
+ relationship embeds a separate XLSX workbook part, and cloning that
+ graph reliably is not supported — better to refuse than corrupt.
+ """
+ source = prs.slides[int(index)]
+ if any(sh.has_chart for sh in source.shapes):
+ raise SystemExit(
+ f"slide {index} contains a chart; duplication of chart slides "
+ "is not supported (chart XML embeds a workbook part that "
+ "cannot be cloned safely). Rebuild the chart on a new slide "
+ "with pptx_create.py / pptx_from_template.py instead.")
+
+ dest = prs.slides.add_slide(source.slide_layout)
+ # drop the placeholders add_slide seeded from the layout
+ for shape in list(dest.shapes):
+ shape._element.getparent().remove(shape._element)
+
+ for shape in source.shapes:
+ dest.shapes._spTree.append(copy.deepcopy(shape._element))
+
+ # re-create the source slide's part relationships on the copy
+ rid_map = {}
+ for rel in list(source.part.rels.values()):
+ if rel.reltype.endswith(("/slideLayout", "/notesSlide")):
+ continue
+ if rel.is_external:
+ new_rid = dest.part.rels.get_or_add_ext_rel(
+ rel.reltype, rel.target_ref)
+ else:
+ new_rid = dest.part.relate_to(rel.target_part, rel.reltype)
+ rid_map[rel.rId] = new_rid
+
+ for el in dest.shapes._spTree.iter():
+ for attr, val in el.attrib.items():
+ if attr.startswith(R_EMBED) and val in rid_map:
+ el.set(attr, rid_map[val])
+
+ if source.has_notes_slide:
+ dest.notes_slide.notes_text_frame.text = (
+ source.notes_slide.notes_text_frame.text)
+ return len(prs.slides._sldIdLst) - 1
+
+
+def set_background(slide, hex_color):
+ fill = slide.background.fill
+ fill.solid()
+ fill.fore_color.rgb = RGBColor.from_string(hex_color)
+
+
+def add_hyperlink(prs, slide_idx, text, url):
+ """Turn every run containing `text` on the slide into a hyperlink.
+
+ The link applies to the whole run (python-pptx links whole runs).
+ """
+ slide = prs.slides[int(slide_idx)]
+ hits = 0
+ for shape in slide.shapes:
+ if not shape.has_text_frame:
+ continue
+ for para in shape.text_frame.paragraphs:
+ for run in para.runs:
+ if text in run.text:
+ run.hyperlink.address = url
+ hits += 1
+ if not hits:
+ raise SystemExit(f"no run containing {text!r} on slide {slide_idx}")
+ return hits
+
+
+def _copy_layout_placeholder(slide, ph_idx):
+ """Copy the layout placeholder with idx `ph_idx` onto the slide.
+
+ Slide-number (idx 12) and footer (idx 11) placeholders exist on the
+ layout but are not inherited by a slide until the slide carries its
+ own copy — this enables them. Returns the new shape, or None when the
+ layout does not provide that placeholder.
+ """
+ for ph in slide.slide_layout.placeholders:
+ if ph.placeholder_format.idx == ph_idx:
+ el = copy.deepcopy(ph._element)
+ slide.shapes._spTree.append(el)
+ for shape in slide.placeholders:
+ if shape.placeholder_format.idx == ph_idx:
+ return shape
+ return None
+ return None
+
+
+def enable_slide_number(slide):
+ if any(ph.placeholder_format.idx == 12 for ph in slide.placeholders):
+ return True
+ return _copy_layout_placeholder(slide, 12) is not None
+
+
+def set_footer(slide, text):
+ shape = next((ph for ph in slide.placeholders
+ if ph.placeholder_format.idx == 11), None)
+ if shape is None:
+ shape = _copy_layout_placeholder(slide, 11)
+ if shape is None:
+ raise SystemExit("layout provides no footer placeholder; add a "
+ "textbox instead")
+ shape.text_frame.text = text
+ return True
+
+
+def set_notes(slide, text, append=False):
+ tf = slide.notes_slide.notes_text_frame
+ if append and tf.text:
+ para = tf.add_paragraph()
+ para.text = text
+ else:
+ tf.text = text
+
+
def main(argv=None):
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
parser = argparse.ArgumentParser(
- description="Edit a .pptx: replace text, update chart data, "
- "swap images, remove or reorder slides.",
+ description="Edit a .pptx: replace text, update chart data, swap "
+ "images, duplicate/remove/reorder slides, backgrounds, "
+ "hyperlinks, footers, slide numbers, speaker notes.",
epilog=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("pptx", help="path to the .pptx file")
parser.add_argument("--output", help="save to this path instead of "
@@ -132,6 +375,15 @@ def main(argv=None):
parser.add_argument("--remove-slide", type=int, metavar="N")
parser.add_argument("--move-slide", nargs=2, type=int,
metavar=("FROM", "TO"))
+ parser.add_argument("--duplicate-slide", type=int, metavar="N")
+ parser.add_argument("--set-background", nargs=2,
+ metavar=("SLIDE", "HEX"))
+ parser.add_argument("--hyperlink", nargs=3,
+ metavar=("SLIDE", "TEXT", "URL"))
+ parser.add_argument("--enable-slide-number", type=int, metavar="N")
+ parser.add_argument("--set-footer", nargs=2, metavar=("SLIDE", "TEXT"))
+ parser.add_argument("--set-notes", nargs=2, metavar=("SLIDE", "TEXT"))
+ parser.add_argument("--append-notes", nargs=2, metavar=("SLIDE", "TEXT"))
args = parser.parse_args(argv)
prs = Presentation(args.pptx)
@@ -145,6 +397,27 @@ def main(argv=None):
if args.swap_image:
swap_image(prs, *args.swap_image)
report["image_swapped"] = True
+ if args.duplicate_slide is not None:
+ report["duplicated_to"] = duplicate_slide(prs, args.duplicate_slide)
+ if args.set_background:
+ set_background(prs.slides[int(args.set_background[0])],
+ args.set_background[1])
+ report["background_set"] = True
+ if args.hyperlink:
+ report["hyperlinked_runs"] = add_hyperlink(prs, *args.hyperlink)
+ if args.enable_slide_number is not None:
+ report["slide_number_enabled"] = enable_slide_number(
+ prs.slides[args.enable_slide_number])
+ if args.set_footer:
+ set_footer(prs.slides[int(args.set_footer[0])], args.set_footer[1])
+ report["footer_set"] = True
+ if args.set_notes:
+ set_notes(prs.slides[int(args.set_notes[0])], args.set_notes[1])
+ report["notes_set"] = True
+ if args.append_notes:
+ set_notes(prs.slides[int(args.append_notes[0])],
+ args.append_notes[1], append=True)
+ report["notes_appended"] = True
if args.remove_slide is not None:
remove_slide(prs, args.remove_slide)
report["slide_removed"] = args.remove_slide
diff --git a/skills/productivity/powerpoint/scripts/pptx_render.py b/skills/productivity/powerpoint/scripts/pptx_render.py
new file mode 100644
index 00000000000..7d54aa02bc5
--- /dev/null
+++ b/skills/productivity/powerpoint/scripts/pptx_render.py
@@ -0,0 +1,93 @@
+#!/usr/bin/env python3
+"""Render every slide of a .pptx to per-slide PNG images.
+
+Pipeline: LibreOffice (soffice --headless --convert-to pdf) turns the deck
+into a PDF, then poppler (pdftoppm, or pdftocairo as an alternate) splits
+the PDF into one PNG per slide.
+
+Output is JSON. When both tools are present:
+ {"rendered": true, "files": ["render/slide-1.png", ...]}
+When either tool is missing the script still exits 0 and reports:
+ {"rendered": false, "missing": ["soffice"], "guidance": "..."}
+so callers can degrade gracefully (fall back to pptx_read.py --outline).
+"""
+import argparse
+import glob
+import json
+import os
+import shutil
+import subprocess
+import sys
+import tempfile
+
+
+def find_tools():
+ """Return (soffice, splitter, missing) using shutil.which."""
+ soffice = shutil.which("soffice")
+ splitter = shutil.which("pdftoppm") or shutil.which("pdftocairo")
+ missing = []
+ if not soffice:
+ missing.append("soffice")
+ if not splitter:
+ missing.append("pdftoppm (or pdftocairo)")
+ return soffice, splitter, missing
+
+
+def render(pptx_path, out_dir, prefix, dpi):
+ soffice, splitter, missing = find_tools()
+ if missing:
+ return {
+ "rendered": False, "missing": missing,
+ "guidance": "Install LibreOffice (soffice) and poppler-utils "
+ "(pdftoppm/pdftocairo) to render slides. Without "
+ "them, verify decks with pptx_read.py --outline "
+ "instead.",
+ }
+
+ os.makedirs(out_dir, exist_ok=True)
+ with tempfile.TemporaryDirectory() as tmp:
+ proc = subprocess.run(
+ [soffice, "--headless", "--convert-to", "pdf",
+ "--outdir", tmp, pptx_path],
+ capture_output=True, text=True, encoding="utf-8",
+ errors="replace", timeout=300)
+ pdfs = glob.glob(os.path.join(tmp, "*.pdf"))
+ if proc.returncode != 0 or not pdfs:
+ raise SystemExit(f"soffice PDF conversion failed: {proc.stderr}")
+ pdf = pdfs[0]
+ out_prefix = os.path.join(out_dir, prefix)
+ proc = subprocess.run(
+ [splitter, "-png", "-r", str(dpi), pdf, out_prefix],
+ capture_output=True, text=True, encoding="utf-8",
+ errors="replace", timeout=300)
+ if proc.returncode != 0:
+ raise SystemExit(f"{os.path.basename(splitter)} failed: "
+ f"{proc.stderr}")
+
+ files = sorted(glob.glob(out_prefix + "*.png"))
+ return {"rendered": True, "files": files}
+
+
+def main(argv=None):
+ if hasattr(sys.stdout, "reconfigure"):
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
+ parser = argparse.ArgumentParser(
+ description="Render each slide of a .pptx to a PNG via "
+ "soffice + pdftoppm/pdftocairo.",
+ epilog=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("pptx", help="path to the .pptx file")
+ parser.add_argument("--outdir", default="render",
+ help="directory for PNGs (default: ./render)")
+ parser.add_argument("--prefix", default="slide",
+ help="PNG filename prefix (default: slide)")
+ parser.add_argument("--dpi", type=int, default=100,
+ help="render resolution (default: 100)")
+ args = parser.parse_args(argv)
+
+ result = render(args.pptx, args.outdir, args.prefix, args.dpi)
+ print(json.dumps(result, indent=2))
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/skills/productivity/powerpoint/tests/test_powerpoint_skill.py b/skills/productivity/powerpoint/tests/test_powerpoint_skill.py
index d8b17dd53c9..a5ccdfa6382 100644
--- a/skills/productivity/powerpoint/tests/test_powerpoint_skill.py
+++ b/skills/productivity/powerpoint/tests/test_powerpoint_skill.py
@@ -255,3 +255,221 @@ def test_help_flags():
[sys.executable, os.path.join(SCRIPTS, script), "--help"],
capture_output=True, text=True, encoding="utf-8")
assert proc.returncode == 0 and "usage" in proc.stdout.lower()
+
+
+# ---------------------------------------------------------------------------
+# parity features: render, run-merge replace, chart ops, duplication,
+# polish (background/hyperlink/slide-number/footer), notes editing
+# ---------------------------------------------------------------------------
+
+def run_raw(script, *args):
+ env = dict(os.environ, LC_ALL="C", PYTHONIOENCODING="utf-8")
+ return subprocess.run(
+ [sys.executable, os.path.join(SCRIPTS, script), *args],
+ capture_output=True, text=True, encoding="utf-8", env=env)
+
+
+def test_render_all_slides(workdir):
+ import shutil
+ spec_path = workdir / "render_spec.json"
+ write_json(spec_path, {"slides": [
+ {"layout": "title", "title": "One"},
+ {"layout": "title_content", "title": "Two", "bullets": ["b"]},
+ {"layout": "blank"}]})
+ deck3 = workdir / "render_me.pptx"
+ run("pptx_create.py", str(spec_path), str(deck3))
+ out_dir = workdir / "render_out"
+ result = run("pptx_render.py", str(deck3), "--outdir", str(out_dir))
+ have_tools = shutil.which("soffice") and (
+ shutil.which("pdftoppm") or shutil.which("pdftocairo"))
+ if have_tools:
+ assert result["rendered"] is True
+ assert len(result["files"]) == 3
+ for png in result["files"]:
+ with open(png, "rb") as fh:
+ assert fh.read(8) == b"\x89PNG\r\n\x1a\n"
+ else:
+ assert result["rendered"] is False
+ assert result["missing"]
+ assert "guidance" in result
+
+
+def test_replace_across_identically_formatted_runs(workdir):
+ """A match split mid-word into equal-format runs keeps formatting."""
+ import copy as cp
+ from pptx import Presentation
+ from pptx.dml.color import RGBColor
+ from pptx.util import Inches, Pt
+
+ prs = Presentation()
+ slide = prs.slides.add_slide(prs.slide_layouts[6])
+ box = slide.shapes.add_textbox(Inches(1), Inches(1),
+ Inches(6), Inches(1))
+ para = box.text_frame.paragraphs[0]
+ run_obj = para.add_run()
+ run_obj.text = "Say TotalWord now"
+ run_obj.font.bold = True
+ run_obj.font.size = Pt(20)
+ run_obj.font.color.rgb = RGBColor.from_string("CC0000")
+ # simulate PowerPoint's spell-check split: same rPr, seam mid-match
+ second = cp.deepcopy(run_obj._r)
+ run_obj._r.addnext(second)
+ run_obj.text = "Say Total"
+ para.runs[1].text = "Word now"
+ path = workdir / "split_runs.pptx"
+ prs.save(str(path))
+
+ edited = workdir / "split_runs_edited.pptx"
+ result = run("pptx_edit.py", str(path), "--output", str(edited),
+ "--replace-text", "TotalWord", "MergedWord")
+ assert result["replacements"] == 1
+
+ prs2 = Presentation(str(edited))
+ para2 = prs2.slides[0].shapes[0].text_frame.paragraphs[0]
+ assert "".join(r.text for r in para2.runs) == "Say MergedWord now"
+ for r in para2.runs:
+ assert r.font.bold is True
+ assert r.font.size == Pt(20)
+ assert str(r.font.color.rgb) == "CC0000"
+
+
+def test_chart_surgical_ops(deck, workdir):
+ from pptx import Presentation
+ spec = workdir / "chart_ops.json"
+ write_json(spec, {"slide": 3, "chart": 0, "ops": [
+ {"op": "update_series", "name": "North", "values": [99, 88]},
+ {"op": "add_series", "name": "East", "values": [1, 2]},
+ {"op": "remove_series", "name": "South"},
+ {"op": "rename_category", "from": "Q1", "to": "Q1 FY26"},
+ {"op": "set_title", "title": "Updated Sales"}]})
+ edited = workdir / "chart_ops.pptx"
+ run("pptx_edit.py", deck, "--output", str(edited),
+ "--chart-data", str(spec))
+ outline = run("pptx_read.py", str(edited))
+ bar = outline["slides"][3]["charts"][0]
+ assert bar["categories"] == ["Q1 FY26", "Q2"]
+ names = [s["name"] for s in bar["series"]]
+ assert "South" not in names and "East" in names
+ north = next(s for s in bar["series"] if s["name"] == "North")
+ assert north["values"] == [99.0, 88.0]
+ east = next(s for s in bar["series"] if s["name"] == "East")
+ assert east["values"] == [1.0, 2.0]
+ chart = next(s.chart for s in Presentation(str(edited)).slides[3].shapes
+ if s.has_chart)
+ assert chart.chart_title.text_frame.text == "Updated Sales"
+
+
+def test_chart_op_unknown_series_fails(deck, workdir):
+ spec = workdir / "chart_bad.json"
+ write_json(spec, {"slide": 3, "chart": 0, "ops": [
+ {"op": "update_series", "name": "Nowhere", "values": [1, 2]}]})
+ proc = run_raw("pptx_edit.py", deck, "--output",
+ str(workdir / "never.pptx"), "--chart-data", str(spec))
+ assert proc.returncode != 0
+ assert "Nowhere" in proc.stderr
+
+
+def test_duplicate_image_slide_is_independent(deck, workdir):
+ import base64
+ dup = workdir / "dup.pptx"
+ result = run("pptx_edit.py", deck, "--output", str(dup),
+ "--duplicate-slide", "2")
+ assert result["duplicated_to"] == 4
+ outline = run("pptx_read.py", str(dup)) # re-opens cleanly
+ assert outline["slide_count"] == 5
+ s4 = outline["slides"][4]
+ assert len(s4["images"]) == 1
+ assert s4["tables"][0][0] == ["Region", "Sales"]
+ assert "Callout" in s4["texts"]
+
+ # independence: swap the image on the COPY, original stays red
+ blue = base64.b64decode(
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGNg"
+ "YPj/HwADAgH/p5UronAAAAAASUVORK5CYII=")
+ blue_path = workdir / "blue2.png"
+ blue_path.write_bytes(blue)
+ from pptx import Presentation
+ from pptx.enum.shapes import MSO_SHAPE_TYPE
+ prs = Presentation(str(dup))
+ name = next(s.name for s in prs.slides[4].shapes
+ if s.shape_type == MSO_SHAPE_TYPE.PICTURE)
+ run("pptx_edit.py", str(dup), "--swap-image", "4", name,
+ str(blue_path))
+ prs = Presentation(str(dup))
+ orig = next(s for s in prs.slides[2].shapes
+ if s.shape_type == MSO_SHAPE_TYPE.PICTURE)
+ copy_pic = next(s for s in prs.slides[4].shapes
+ if s.shape_type == MSO_SHAPE_TYPE.PICTURE)
+ assert copy_pic.image.blob == blue
+ assert orig.image.blob != blue
+
+
+def test_duplicate_chart_slide_refused(deck, workdir):
+ proc = run_raw("pptx_edit.py", deck, "--output",
+ str(workdir / "never2.pptx"), "--duplicate-slide", "3")
+ assert proc.returncode != 0
+ assert "chart" in proc.stderr.lower()
+
+
+def test_create_polish_features(workdir):
+ from pptx import Presentation
+ spec_path = workdir / "polish.json"
+ write_json(spec_path, {"slides": [
+ {"layout": "title_content", "title": "Polished",
+ "background": "112233", "footer": "Confidential draft",
+ "slide_number": True,
+ "bullets": [{"text": "Visit example",
+ "link": "https://example.com/info"}]}]})
+ out = workdir / "polish.pptx"
+ run("pptx_create.py", str(spec_path), str(out))
+ prs = Presentation(str(out))
+ slide = prs.slides[0]
+ assert str(slide.background.fill.fore_color.rgb) == "112233"
+ ph_idx = [ph.placeholder_format.idx for ph in slide.placeholders]
+ assert 12 in ph_idx # slide number enabled
+ footer = next(ph for ph in slide.placeholders
+ if ph.placeholder_format.idx == 11)
+ assert footer.text_frame.text == "Confidential draft"
+ link_runs = [r for sh in slide.shapes if sh.has_text_frame
+ for p in sh.text_frame.paragraphs for r in p.runs
+ if r.hyperlink.address]
+ assert link_runs[0].hyperlink.address == "https://example.com/info"
+
+
+def test_edit_polish_features(deck, workdir):
+ from pptx import Presentation
+ edited = workdir / "polish_edit.pptx"
+ result = run("pptx_edit.py", deck, "--output", str(edited),
+ "--set-background", "0", "004400",
+ "--hyperlink", "1", "Overview", "https://example.com/x",
+ "--enable-slide-number", "1",
+ "--set-footer", "1", "Footer via edit")
+ assert result["background_set"] and result["footer_set"]
+ assert result["hyperlinked_runs"] == 1
+ assert result["slide_number_enabled"] is True
+ prs = Presentation(str(edited))
+ assert str(prs.slides[0].background.fill.fore_color.rgb) == "004400"
+ s1 = prs.slides[1]
+ assert any(ph.placeholder_format.idx == 12 for ph in s1.placeholders)
+ footer = next(ph for ph in s1.placeholders
+ if ph.placeholder_format.idx == 11)
+ assert footer.text_frame.text == "Footer via edit"
+ links = [r.hyperlink.address for sh in s1.shapes if sh.has_text_frame
+ for p in sh.text_frame.paragraphs for r in p.runs
+ if r.hyperlink.address]
+ assert links == ["https://example.com/x"]
+
+
+def test_set_and_append_notes(deck, workdir):
+ edited = workdir / "notes_edit.pptx"
+ result = run("pptx_edit.py", deck, "--output", str(edited),
+ "--set-notes", "0", "Fresh notes")
+ assert result["notes_set"]
+ run("pptx_edit.py", str(edited), "--append-notes", "0", "Second line")
+ notes = run("pptx_read.py", str(edited), "--notes")
+ assert notes["notes"][0] == "Fresh notes\nSecond line"
+
+
+def test_render_help_flag():
+ proc = run_raw("pptx_render.py", "--help")
+ assert proc.returncode == 0 and "usage" in proc.stdout.lower()
diff --git a/skills/productivity/xlsx/SKILL.md b/skills/productivity/xlsx/SKILL.md
index 4ef8ebb23bf..f9e3544dca3 100644
--- a/skills/productivity/xlsx/SKILL.md
+++ b/skills/productivity/xlsx/SKILL.md
@@ -1,7 +1,7 @@
---
name: xlsx
description: Create, read, edit Excel .xlsx workbooks and CSVs.
-version: 1.0.0
+version: 1.1.0
author: Nous Research
license: MIT
platforms: [linux, macos, windows]
@@ -23,11 +23,15 @@ scripts are argparse CLIs that print JSON and use explicit UTF-8 I/O.
- Creating .xlsx reports: multiple sheets, number formats, styling,
merged cells, freeze panes, autofilter, conditional formatting,
- charts, data-validation dropdowns.
+ charts, data-validation dropdowns, native Excel tables, defined
+ names, hyperlinks, cell notes, sheet protection.
- Reading a workbook: sheet inventory, dumping data as JSON or CSV,
- listing formulas vs cached values.
+ listing formulas vs cached values, notes, defined names, tables.
- Editing existing files: set cells, append rows, insert/delete
- rows/columns, copy/rename sheets.
+ rows/columns (reference-aware via `xlsx_restructure.py`),
+ copy/rename sheets, tables, names, notes, protection.
+- Recalculating formulas headlessly via LibreOffice
+ (`xlsx_recalc.py`).
- CSV interop with type inference and non-UTF-8 encodings.
- Not for the legacy .xls binary format (use LibreOffice to convert
first: `soffice --headless --convert-to xlsx old.xls`).
@@ -50,6 +54,8 @@ python scripts/xlsx_read.py report.xlsx --sheets # inventory
python scripts/xlsx_read.py report.xlsx --json --sheet Data
python scripts/xlsx_read.py report.xlsx --formulas
python scripts/xlsx_edit.py report.xlsx --sheet Data --set B2=42 --recalc
+python scripts/xlsx_restructure.py report.xlsx --sheet Data --insert-rows 3:2
+python scripts/xlsx_recalc.py report.xlsx
python scripts/csv_to_xlsx.py data.csv out.xlsx --encoding utf-8
python scripts/xlsx_to_csv.py report.xlsx out.csv --sheet Data
```
@@ -68,7 +74,17 @@ Author the JSON spec with `write_file`, inspect script JSON output with
| List formulas + cached values | `xlsx_read.py f.xlsx --formulas` |
| Set a cell / formula | `xlsx_edit.py f.xlsx --set "A1==SUM(B:B)"` |
| Append a row | `xlsx_edit.py f.xlsx --append '[1,"x",true]'` |
-| Insert 2 rows before row 3 | `xlsx_edit.py f.xlsx --insert-rows 3:2` |
+| Insert 2 rows, refs NOT shifted | `xlsx_edit.py f.xlsx --insert-rows 3:2` |
+| Insert 2 rows, refs shifted | `xlsx_restructure.py f.xlsx --insert-rows 3:2` |
+| Delete a column, refs shifted | `xlsx_restructure.py f.xlsx --delete-cols B` |
+| Create a native table | `xlsx_edit.py f.xlsx --add-table Sales:A1:C9` |
+| Append inside a table | `--table-append 'Sales=["West",5]'` |
+| List tables | `xlsx_edit.py f.xlsx --list-tables` |
+| Defined names | `--define-name "Rates='Data'!$B$2:$B$9"` / `--delete-name Rates` / `xlsx_read.py f.xlsx --names` |
+| Hyperlink | `--hyperlink "A1=https://example.com|Docs"` |
+| Cell note | `--note "B2=Check this|Reviewer"`; read via `xlsx_read.py f.xlsx --notes` |
+| Protect sheet (see Pitfalls) | `--protect your-password --unlock B2:B9` |
+| Recalculate via LibreOffice | `xlsx_recalc.py f.xlsx` |
| Copy / rename sheet | `--copy-sheet Src:New --rename-sheet Old:New` |
| Force recalc on open | `xlsx_edit.py f.xlsx --recalc` |
| CSV -> styled xlsx | `csv_to_xlsx.py in.csv out.xlsx` |
@@ -81,8 +97,11 @@ Author the JSON spec with `write_file`, inspect script JSON output with
`rows` (scalars or styled cell objects), sparse `cells` overrides,
`column_widths`, `row_heights`, `merges`, `freeze_panes`,
`autofilter`, `conditional_formats` (cell_is rules and color
- scales), `charts` (bar/line/pie from cell ranges), and
- `validations` (list dropdowns). Typed values: JSON numbers/bools
+ scales), `charts` (bar/line/pie from cell ranges),
+ `validations` (list dropdowns), `tables` (native Excel tables with
+ a style name), and `protection`. Workbook-level `defined_names`
+ maps names to refs. Cell objects also take `hyperlink` and `note`.
+ Typed values: JSON numbers/bools
pass through; dates use `{"value": "2026-01-31", "type": "date"}`.
Number formats are Excel format strings: currency `"$#,##0.00"`,
percent `"0.0%"`, date `"yyyy-mm-dd"`.
@@ -92,32 +111,62 @@ Author the JSON spec with `write_file`, inspect script JSON output with
the workbook's `fullCalcOnLoad` flag so Excel/LibreOffice recompute
everything on open. openpyxl itself NEVER evaluates formulas.
3. **Read**: `--sheets` for inventory (names, dimensions, merged
- ranges, chart count), `--json`/`--csv` for data, `--formulas` to
- pair each formula string with its cached result. Cached results
+ ranges, chart count, tables, protection, defined names),
+ `--json`/`--csv` for data, `--formulas` to
+ pair each formula string with its cached result, `--notes` for
+ cell comments, `--names` for defined names. Cached results
exist only if the file was last saved by a real spreadsheet app;
files fresh from openpyxl return `null` there. To materialize
- results headlessly: `soffice --headless --convert-to xlsx file.xlsx`
- then reload with `--data-only`.
+ results headlessly run `xlsx_recalc.py file.xlsx` (uses
+ LibreOffice; prints `{"recalculated": false, ...}` and exits 0
+ when `soffice` is absent), then reload with `--data-only`.
4. **Edit**: `xlsx_edit.py` applies renames/copies first, then
structural row/column changes, then `--set`/`--append`. It edits in
place unless `--out` is given — copy the file first if you need the
original.
-5. **CSV interop**: `csv_to_xlsx.py` infers int/float/bool/ISO-date
+5. **Restructure**: for insert/delete on sheets that have formulas,
+ merges, tables, or filters, use `xlsx_restructure.py` instead of
+ `xlsx_edit.py`. It rewrites formula references on ALL sheets
+ (absolute `$` refs, ranges, cross-sheet refs), shifts merges,
+ autofilter, freeze panes, validation and conditional-format
+ ranges, table refs, defined names, and row/column dimensions, then
+ prints a JSON report including a `not_shifted` list. Rules and
+ limits: `references/restructuring.md`.
+6. **CSV interop**: `csv_to_xlsx.py` infers int/float/bool/ISO-date
per cell and styles the header row; `xlsx_to_csv.py` writes ISO
dates and blank strings for empty cells. Both default to UTF-8 and
accept `--encoding` (e.g. `utf-8-sig` for Excel-friendly BOM,
`cp1252` for legacy Windows exports).
+## Converting to PDF
+
+LibreOffice converts headlessly (also works for CSV export of a single
+sheet):
+
+```bash
+soffice --headless --convert-to pdf report.xlsx --outdir out/
+soffice --headless --convert-to csv report.xlsx --outdir out/ # 1st sheet only
+```
+
+Only the first sheet lands in a CSV; for other sheets use
+`xlsx_to_csv.py --sheet NAME`. If `soffice` is missing, install
+LibreOffice or hand the file to the user unconverted.
+
## Pitfalls
- **openpyxl does not calculate.** Formula results are available only
via `load_workbook(path, data_only=True)` and only when the file was
previously saved by Excel/LibreOffice. Otherwise you get `None`.
-- **Insert/delete does not shift references.** `insert_rows`,
- `delete_cols`, etc. move cell values but do NOT update merged-cell
- ranges, formula references, chart anchors, or conditional-format
- ranges. After structural edits on sheets with merges or formulas,
- re-check them with `--sheets` and `--formulas` and fix manually.
+- **`xlsx_edit.py` insert/delete does not shift references** (raw
+ openpyxl behavior). Use `xlsx_restructure.py`, which does — but even
+ it cannot move chart anchors, images, or conditional-format RULE
+ formulas; read its JSON report's `not_shifted` list and
+ `references/restructuring.md`.
+- **Sheet protection is NOT security.** `--protect` sets the standard
+ xlsx sheet-protection hash: it signals "don't edit this" to
+ well-behaved apps and nothing more. Anyone can strip it by editing
+ the zip's XML or unchecking it in LibreOffice. Never rely on it for
+ confidentiality or integrity; it does not encrypt anything.
- **`data_only=True` then save** silently discards all formulas
(cached values replace them). Never save a workbook loaded that way
unless that is the goal.
@@ -140,5 +189,8 @@ Author the JSON spec with `write_file`, inspect script JSON output with
- Dump data with `--json` and compare against the source values.
- After edits: re-dump the touched range; if formulas were written,
confirm `--formulas` lists them and that `--recalc` was applied.
+- After `xlsx_restructure.py`: read its JSON report, then re-run
+ `--formulas` and `--sheets` to confirm references and ranges landed
+ where expected.
- For a full visual check, open in LibreOffice:
`soffice --headless --convert-to pdf out.xlsx` and inspect the PDF.
diff --git a/skills/productivity/xlsx/references/restructuring.md b/skills/productivity/xlsx/references/restructuring.md
new file mode 100644
index 00000000000..66f0bef1771
--- /dev/null
+++ b/skills/productivity/xlsx/references/restructuring.md
@@ -0,0 +1,71 @@
+# Reference-aware restructuring (xlsx_restructure.py)
+
+`scripts/xlsx_restructure.py` performs one row/column insert or delete
+and rewrites everything that references the moved cells. This document
+gives the exact rewrite rules and honest limits.
+
+## What gets rewritten
+
+| Artifact | Scope | Behavior |
+|---|---|---|
+| Formula references | ALL sheets | A1 refs into the edited sheet are shifted; refs into a fully deleted region become `#REF!` |
+| Merged-cell ranges | edited sheet | shifted; expanded when they span the insertion point; dropped (reported `to: null`) when fully deleted |
+| Autofilter ref | edited sheet | shifted/expanded like a range |
+| Freeze panes | edited sheet | anchor cell shifted (never below row/col of the pane's own minimum) |
+| Data validations | edited sheet | each range in the sqref shifted; deleted ranges removed |
+| Conditional formats | edited sheet | applied range (sqref) shifted |
+| Native tables | edited sheet | table `ref` shifted/expanded |
+| Defined names | workbook scope | `attr_text` refs into the edited sheet rewritten |
+| Row heights / column widths | edited sheet | dimension keys re-indexed |
+
+## Reference grammar handled
+
+- Relative and absolute coordinates in any mix: `B2`, `$B2`, `B$2`,
+ `$B$2` — the `$` flags are preserved through the shift.
+- Ranges `B2:D9`, including partial-absolute endpoints.
+- Cross-sheet refs: `Data!B2`, `'My Sheet'!$A$1:$C$9` (quoted names may
+ contain doubled quotes `''`). Only refs whose sheet qualifier matches
+ the edited sheet are touched; unqualified refs are interpreted
+ relative to the formula's own sheet.
+- String literals inside formulas (`"See B2"`) are never rewritten.
+- Function names that look like cells (`LOG10(...)`) are not touched
+ (a reference is never followed by `(`).
+- Whole-row/column refs (`B:B`, `2:2`) pass through unchanged — Excel
+ semantics keep them valid across inserts within the span.
+
+## Shift semantics
+
+Insert of N at index i: every coordinate >= i moves +N; range endpoints
+move independently, so a range spanning i grows by N.
+
+Delete of N at index i: coordinates before i are unchanged; coordinates
+past the deleted block move -N; a single cell inside the block becomes
+`#REF!`; a RANGE partially covering the block is clamped (Excel does the
+same); a range entirely inside the block becomes `#REF!` (formulas) or
+is removed (merges/validations).
+
+## What it CANNOT shift (honest limits)
+
+- **Chart anchors and plotted ranges** — openpyxl chart objects are not
+ reliably round-tripped; anchors stay where they were. Re-create
+ charts after restructuring if their data moved.
+- **Images / drawings** — same reason.
+- **Conditional-format RULE formulas** — the applied range (sqref) is
+ shifted, but formulas inside `cell_is`/`expression` rules (e.g.
+ `$B1>100`) are left as-is. Review them if they reference moved cells.
+- **Sheet-local defined names** and names using R1C1 or union/
+ intersection operators are rewritten only if they parse as plain A1
+ refs; anything else passes through untouched.
+- **Structured table references** in formulas (`Table1[Sales]`) don't
+ need shifting (they follow the table), and are left alone.
+
+Every run prints a JSON report listing exactly which formulas, merges,
+tables, names, and ranges were changed, plus a fixed `not_shifted` list
+of the above limits — inspect it after any structural edit.
+
+## One op per invocation
+
+The CLI takes exactly one of `--insert-rows/--delete-rows/
+--insert-cols/--delete-cols` (as `IDX[:N]`; columns accept letters).
+For multiple operations run it repeatedly — ordering compound shifts in
+one pass is where spreadsheet tools historically corrupt references.
diff --git a/skills/productivity/xlsx/scripts/xlsx_create.py b/skills/productivity/xlsx/scripts/xlsx_create.py
index c8e9e02d3be..14b351cfd99 100644
--- a/skills/productivity/xlsx/scripts/xlsx_create.py
+++ b/skills/productivity/xlsx/scripts/xlsx_create.py
@@ -4,6 +4,7 @@
Spec (JSON object):
{
"full_calc_on_load": true, # force recalculation on open (optional)
+ "defined_names": {"Rates": "'Data'!$B$2:$B$4"}, # workbook scope
"sheets": [
{
"name": "Data",
@@ -25,7 +26,13 @@ Spec (JSON object):
],
"validations": [
{"range": "D2:D9", "type": "list", "formula1": "\"Yes,No,Maybe\""}
- ]
+ ],
+ "tables": [
+ {"name": "Sales", "range": "A1:C4",
+ "style": "TableStyleMedium9"} # native Excel table
+ ],
+ "protection": {"password": "your-password", # NOT security --
+ "unlock": ["B2:B9"]} # see SKILL.md Pitfalls
}
]
}
@@ -34,6 +41,8 @@ Cell object keys (all optional except value/formula):
value scalar; JSON true/false -> bool, numbers stay numeric
type "date" or "datetime" -> value parsed from ISO string
formula e.g. "=SUM(A2:A9)" (leading '=' optional)
+ hyperlink URL; value becomes the display text
+ note cell note text (or {"text": ..., "author": ...})
format Excel number format, e.g. "$#,##0.00", "0.0%", "yyyy-mm-dd"
bold, italic booleans
font_size points
@@ -59,10 +68,14 @@ from datetime import date, datetime
from openpyxl import Workbook
from openpyxl.chart import BarChart, LineChart, PieChart, Reference
+from openpyxl.comments import Comment
from openpyxl.formatting.rule import CellIsRule, ColorScaleRule
-from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
+from openpyxl.styles import (Alignment, Border, Font, PatternFill,
+ Protection, Side)
from openpyxl.utils import column_index_from_string, range_boundaries
+from openpyxl.workbook.defined_name import DefinedName
from openpyxl.worksheet.datavalidation import DataValidation
+from openpyxl.worksheet.table import Table, TableStyleInfo
def parse_typed(value, type_hint=None):
@@ -81,6 +94,18 @@ def apply_cell(ws, coord, spec):
cell.value = f if f.startswith("=") else "=" + f
elif "value" in spec:
cell.value = parse_typed(spec["value"], spec.get("type"))
+ if "hyperlink" in spec:
+ cell.hyperlink = spec["hyperlink"]
+ if cell.value is None:
+ cell.value = spec["hyperlink"]
+ cell.style = "Hyperlink"
+ if "note" in spec:
+ note = spec["note"]
+ if isinstance(note, dict):
+ cell.comment = Comment(note.get("text", ""),
+ note.get("author", "xlsx-skill"))
+ else:
+ cell.comment = Comment(str(note), "xlsx-skill")
if "format" in spec:
cell.number_format = spec["format"]
font_kw = {}
@@ -181,6 +206,22 @@ def build_sheet(ws, spec):
allow_blank=dv_spec.get("allow_blank", True))
dv.add(dv_spec["range"])
ws.add_data_validation(dv)
+ for t_spec in spec.get("tables", []):
+ table = Table(displayName=t_spec["name"], ref=t_spec["range"])
+ table.tableStyleInfo = TableStyleInfo(
+ name=t_spec.get("style", "TableStyleMedium9"),
+ showRowStripes=t_spec.get("row_stripes", True),
+ showColumnStripes=t_spec.get("column_stripes", False))
+ ws.add_table(table)
+ prot = spec.get("protection")
+ if prot:
+ for rng in prot.get("unlock", []):
+ for row in ws[rng]:
+ for cell in row:
+ cell.protection = Protection(locked=False)
+ if prot.get("password"):
+ ws.protection.password = prot["password"]
+ ws.protection.sheet = True
def main(argv=None):
@@ -200,6 +241,8 @@ def main(argv=None):
for sheet_spec in spec.get("sheets", []):
ws = wb.create_sheet(sheet_spec.get("name", "Sheet1"))
build_sheet(ws, sheet_spec)
+ for name, ref in spec.get("defined_names", {}).items():
+ wb.defined_names[name] = DefinedName(name, attr_text=ref)
if spec.get("full_calc_on_load"):
wb.calculation.fullCalcOnLoad = True
wb.save(args.output)
diff --git a/skills/productivity/xlsx/scripts/xlsx_edit.py b/skills/productivity/xlsx/scripts/xlsx_edit.py
index 731d6534ca5..83b7892a7f9 100644
--- a/skills/productivity/xlsx/scripts/xlsx_edit.py
+++ b/skills/productivity/xlsx/scripts/xlsx_edit.py
@@ -11,12 +11,27 @@ Operations (repeatable where noted, applied in the order listed below):
--set CELL=VALUE repeatable; type-inferred (int, float, bool,
ISO date, else string). '=...' sets a formula.
--append ROWJSON repeatable; JSON array appended as a row
+ --add-table NAME:RANGE[:STYLE] create a native Excel table (ListObject)
+ --table-append NAME=ROWJSON append a row inside a table, auto-extending
+ the table's range (repeatable)
+ --list-tables print tables on the target sheet and exit
+ --define-name NAME=REF workbook-scope defined name, e.g.
+ "Rates='Data'!$B$2:$B$9" (repeatable)
+ --delete-name NAME remove a defined name (repeatable)
+ --hyperlink CELL=URL[|TEXT] set a hyperlink (optional display text)
+ --note CELL=TEXT[|AUTHOR] set a cell note/comment (repeatable)
+ --clear-note CELL remove a cell note (repeatable)
+ --protect [PASSWORD] enable sheet protection; combine with
+ --unlock RANGE to leave ranges editable.
+ NOT security: trivially strippable (see
+ SKILL.md Pitfalls).
--recalc set fullCalcOnLoad so Excel/LibreOffice
recomputes all formulas on next open
WARNING: openpyxl does NOT shift merged-cell ranges, chart anchors, or
formula references when rows/columns are inserted or deleted. Verify any
-sheet containing merges or formulas after structural edits.
+sheet containing merges or formulas after structural edits — or use
+xlsx_restructure.py, which rewrites references for you.
Usage:
xlsx_edit.py book.xlsx --sheet Data --set B2=42 --set C2=2026-01-01 \
@@ -32,6 +47,11 @@ import sys
from datetime import date, datetime
from openpyxl import load_workbook
+from openpyxl.comments import Comment
+from openpyxl.styles import Protection
+from openpyxl.utils import get_column_letter, range_boundaries
+from openpyxl.workbook.defined_name import DefinedName
+from openpyxl.worksheet.table import Table, TableStyleInfo
def infer(text):
@@ -60,10 +80,33 @@ def parse_idx(arg):
return int(arg), 1
+def add_table(ws, spec):
+ parts = spec.split(":")
+ if len(parts) < 3:
+ raise ValueError("--add-table needs NAME:RANGE like Sales:A1:C9")
+ name = parts[0]
+ rng = ":".join(parts[1:3])
+ style = parts[3] if len(parts) > 3 else "TableStyleMedium9"
+ table = Table(displayName=name, ref=rng)
+ table.tableStyleInfo = TableStyleInfo(name=style, showRowStripes=True)
+ ws.add_table(table)
+
+
+def table_append(ws, name, row_values):
+ table = ws.tables[name]
+ min_col, min_row, max_col, max_row = range_boundaries(table.ref)
+ new_row = max_row + 1
+ for offset, value in enumerate(row_values):
+ ws.cell(row=new_row, column=min_col + offset, value=value)
+ table.ref = (f"{get_column_letter(min_col)}{min_row}:"
+ f"{get_column_letter(max_col)}{new_row}")
+
+
def main(argv=None):
ap = argparse.ArgumentParser(
description="Edit an existing .xlsx workbook.",
- epilog="openpyxl does not shift merges/formula refs on insert/delete.")
+ epilog="Plain insert/delete does not shift merges/formula refs — "
+ "use xlsx_restructure.py for reference-aware moves.")
ap.add_argument("file", help="path to .xlsx file")
ap.add_argument("--sheet", help="target sheet (default: active)")
ap.add_argument("--out", help="output path (default: edit in place)")
@@ -81,6 +124,27 @@ def main(argv=None):
metavar="IDX[:N]")
ap.add_argument("--set", action="append", default=[], metavar="CELL=VALUE")
ap.add_argument("--append", action="append", default=[], metavar="ROWJSON")
+ ap.add_argument("--add-table", action="append", default=[],
+ metavar="NAME:RANGE[:STYLE]")
+ ap.add_argument("--table-append", action="append", default=[],
+ metavar="NAME=ROWJSON")
+ ap.add_argument("--list-tables", action="store_true",
+ help="print tables on the target sheet and exit")
+ ap.add_argument("--define-name", action="append", default=[],
+ metavar="NAME=REF")
+ ap.add_argument("--delete-name", action="append", default=[],
+ metavar="NAME")
+ ap.add_argument("--hyperlink", action="append", default=[],
+ metavar="CELL=URL[|TEXT]")
+ ap.add_argument("--note", action="append", default=[],
+ metavar="CELL=TEXT[|AUTHOR]")
+ ap.add_argument("--clear-note", action="append", default=[],
+ metavar="CELL")
+ ap.add_argument("--protect", nargs="?", const="", metavar="PASSWORD",
+ help="protect the target sheet (integrity signal only, "
+ "NOT security)")
+ ap.add_argument("--unlock", action="append", default=[], metavar="RANGE",
+ help="cell range left editable under --protect")
ap.add_argument("--recalc", action="store_true",
help="force full recalculation when the file is opened")
args = ap.parse_args(argv)
@@ -100,6 +164,16 @@ def main(argv=None):
ws = wb[args.sheet] if args.sheet else wb.active
+ if args.list_tables:
+ print(json.dumps({"ok": True, "sheet": ws.title,
+ "tables": {t.displayName: {
+ "ref": t.ref,
+ "style": t.tableStyleInfo.name
+ if t.tableStyleInfo else None}
+ for t in ws.tables.values()}},
+ ensure_ascii=False))
+ return 0
+
for arg in args.insert_rows:
idx, n = parse_idx(arg)
ws.insert_rows(idx, n)
@@ -125,6 +199,51 @@ def main(argv=None):
ws.append(json.loads(row_json))
changes.append(f"append row {ws.max_row}")
+ for spec in args.add_table:
+ add_table(ws, spec)
+ changes.append(f"add_table {spec.split(':')[0]}")
+ for spec in args.table_append:
+ name, row_json = spec.split("=", 1)
+ table_append(ws, name, json.loads(row_json))
+ changes.append(f"table_append {name} -> {ws.tables[name].ref}")
+
+ for spec in args.define_name:
+ name, ref = spec.split("=", 1)
+ wb.defined_names[name] = DefinedName(name, attr_text=ref)
+ changes.append(f"define_name {name}")
+ for name in args.delete_name:
+ del wb.defined_names[name]
+ changes.append(f"delete_name {name}")
+
+ for spec in args.hyperlink:
+ coord, rest = spec.split("=", 1)
+ url, _, text = rest.partition("|")
+ cell = ws[coord]
+ cell.hyperlink = url
+ cell.value = text or (cell.value if cell.value is not None else url)
+ cell.style = "Hyperlink"
+ changes.append(f"hyperlink {coord}")
+ for spec in args.note:
+ coord, rest = spec.split("=", 1)
+ text, _, author = rest.partition("|")
+ ws[coord].comment = Comment(text, author or "xlsx-skill")
+ changes.append(f"note {coord}")
+ for coord in args.clear_note:
+ ws[coord].comment = None
+ changes.append(f"clear_note {coord}")
+
+ if args.protect is not None:
+ for rng in args.unlock:
+ for row in ws[rng]:
+ for cell in row:
+ cell.protection = Protection(locked=False)
+ if args.protect:
+ ws.protection.password = args.protect
+ ws.protection.sheet = True
+ changes.append(f"protect {ws.title}"
+ + (f" (unlocked {len(args.unlock)} ranges)"
+ if args.unlock else ""))
+
if args.recalc:
wb.calculation.fullCalcOnLoad = True
changes.append("fullCalcOnLoad")
diff --git a/skills/productivity/xlsx/scripts/xlsx_read.py b/skills/productivity/xlsx/scripts/xlsx_read.py
index 1b92f4db6f6..6b753c1ef87 100644
--- a/skills/productivity/xlsx/scripts/xlsx_read.py
+++ b/skills/productivity/xlsx/scripts/xlsx_read.py
@@ -6,6 +6,8 @@ Modes (pick one):
--json dump one sheet's rows as a JSON array of arrays
--csv dump one sheet as CSV to stdout or --out
--formulas JSON list of formula cells {"cell", "formula", "cached"}
+ --notes JSON list of cell notes/comments across sheets
+ --names JSON map of workbook defined names
Options:
--sheet NAME sheet to dump (default: active sheet)
@@ -20,6 +22,8 @@ Usage:
xlsx_read.py book.xlsx --json --sheet Data
xlsx_read.py book.xlsx --csv --sheet Data --out data.csv
xlsx_read.py book.xlsx --formulas
+ xlsx_read.py book.xlsx --notes
+ xlsx_read.py book.xlsx --names
"""
from __future__ import annotations
@@ -54,8 +58,30 @@ def cmd_sheets(wb):
"charts": len(getattr(ws, "_charts", [])),
"freeze_panes": ws.freeze_panes,
"autofilter": ws.auto_filter.ref,
+ "tables": {t.displayName: t.ref for t in ws.tables.values()},
+ "protected": bool(ws.protection.sheet),
})
- print(json.dumps({"sheets": info}, ensure_ascii=False, indent=2))
+ names = {name: dn.attr_text for name, dn in wb.defined_names.items()}
+ print(json.dumps({"sheets": info, "defined_names": names},
+ ensure_ascii=False, indent=2))
+
+
+def cmd_notes(wb, sheet):
+ out = []
+ sheets = [sheet] if sheet else wb.sheetnames
+ for name in sheets:
+ for row in wb[name].iter_rows():
+ for cell in row:
+ if cell.comment is not None:
+ out.append({"sheet": name, "cell": cell.coordinate,
+ "text": cell.comment.text,
+ "author": cell.comment.author})
+ print(json.dumps({"notes": out}, ensure_ascii=False, indent=2))
+
+
+def cmd_names(wb):
+ names = {name: dn.attr_text for name, dn in wb.defined_names.items()}
+ print(json.dumps({"defined_names": names}, ensure_ascii=False, indent=2))
def cmd_formulas(path, sheet):
@@ -85,6 +111,8 @@ def main(argv=None):
mode.add_argument("--json", action="store_true")
mode.add_argument("--csv", action="store_true")
mode.add_argument("--formulas", action="store_true")
+ mode.add_argument("--notes", action="store_true")
+ mode.add_argument("--names", action="store_true")
ap.add_argument("--sheet", help="sheet name (default: active)")
ap.add_argument("--data-only", action="store_true",
help="return cached formula results (see module docstring)")
@@ -100,6 +128,12 @@ def main(argv=None):
if args.sheets:
cmd_sheets(wb)
return 0
+ if args.notes:
+ cmd_notes(wb, args.sheet)
+ return 0
+ if args.names:
+ cmd_names(wb)
+ return 0
ws = wb[args.sheet] if args.sheet else wb.active
rows = sheet_rows(ws)
diff --git a/skills/productivity/xlsx/scripts/xlsx_recalc.py b/skills/productivity/xlsx/scripts/xlsx_recalc.py
new file mode 100644
index 00000000000..e63300d9f51
--- /dev/null
+++ b/skills/productivity/xlsx/scripts/xlsx_recalc.py
@@ -0,0 +1,111 @@
+#!/usr/bin/env python3
+"""Recalculate a workbook's formulas headlessly with LibreOffice.
+
+openpyxl never computes formulas. This script shells out to `soffice`
+(LibreOffice) to open the workbook, recalculate, and re-save it, so
+cached formula results become available to `xlsx_read.py --data-only`
+and `--formulas`.
+
+Behavior:
+ * soffice on PATH: converts the file to .xlsx in a temp dir (which
+ recalculates all formulas) and replaces the original (or writes
+ --out). Prints {"recalculated": true, ...} and exits 0.
+ * soffice absent: prints {"recalculated": false, "reason": ...} with
+ installation guidance and STILL exits 0 — callers can branch on the
+ JSON instead of the exit code.
+
+Note: LibreOffice recalculates .xlsx on load per its default
+calculation settings; conversion re-saves with fresh cached values.
+
+Usage:
+ xlsx_recalc.py book.xlsx
+ xlsx_recalc.py book.xlsx --out recalced.xlsx
+ xlsx_recalc.py book.xlsx --timeout 120
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import shutil
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+
+
+def count_cached(path):
+ """Number of formula cells with a cached value present."""
+ from openpyxl import load_workbook
+ wb_f = load_workbook(path, data_only=False)
+ wb_v = load_workbook(path, data_only=True)
+ formulas = cached = 0
+ for name in wb_f.sheetnames:
+ ws_f, ws_v = wb_f[name], wb_v[name]
+ for row in ws_f.iter_rows():
+ for cell in row:
+ if isinstance(cell.value, str) and cell.value.startswith("="):
+ formulas += 1
+ if ws_v[cell.coordinate].value is not None:
+ cached += 1
+ return formulas, cached
+
+
+def main(argv=None):
+ ap = argparse.ArgumentParser(
+ description="Recalculate .xlsx formulas headlessly via LibreOffice.")
+ ap.add_argument("file", help="path to .xlsx file")
+ ap.add_argument("--out", help="output path (default: replace input)")
+ ap.add_argument("--timeout", type=int, default=180,
+ help="seconds to wait for soffice (default 180)")
+ args = ap.parse_args(argv)
+
+ src = Path(args.file).resolve()
+ if not src.exists():
+ print(json.dumps({"ok": False, "error": f"no such file: {src}"}),
+ file=sys.stderr)
+ return 1
+
+ soffice = shutil.which("soffice")
+ if not soffice:
+ print(json.dumps({
+ "ok": True, "recalculated": False,
+ "reason": "LibreOffice (soffice) not found on PATH",
+ "guidance": "Install LibreOffice (e.g. `apt install "
+ "libreoffice-calc` or `brew install --cask "
+ "libreoffice`), or open the file in Excel/"
+ "LibreOffice once and re-save it.",
+ }, ensure_ascii=False))
+ return 0
+
+ with tempfile.TemporaryDirectory() as tmp:
+ proc = subprocess.run(
+ [soffice, "--headless", "--calc", "--convert-to", "xlsx:Calc "
+ "MS Excel 2007 XML", "--outdir", tmp, str(src)],
+ capture_output=True, text=True, encoding="utf-8",
+ timeout=args.timeout,
+ env={"HOME": tmp, "PATH": Path(soffice).parent.as_posix()
+ + ":/usr/bin:/bin"})
+ produced = Path(tmp) / (src.stem + ".xlsx")
+ if proc.returncode != 0 or not produced.exists():
+ print(json.dumps({"ok": False,
+ "error": "soffice conversion failed",
+ "stderr": proc.stderr.strip()[-500:]}),
+ file=sys.stderr)
+ return 1
+ formulas, cached = count_cached(produced)
+ dest = Path(args.out).resolve() if args.out else src
+ shutil.copyfile(produced, dest)
+
+ print(json.dumps({
+ "ok": True, "recalculated": True, "output": str(dest),
+ "formula_cells": formulas, "with_cached_values": cached,
+ }, ensure_ascii=False))
+ return 0
+
+
+if __name__ == "__main__":
+ try:
+ sys.exit(main())
+ except Exception as exc: # noqa: BLE001
+ print(json.dumps({"ok": False, "error": str(exc)}), file=sys.stderr)
+ sys.exit(1)
diff --git a/skills/productivity/xlsx/scripts/xlsx_restructure.py b/skills/productivity/xlsx/scripts/xlsx_restructure.py
new file mode 100644
index 00000000000..d58a640498a
--- /dev/null
+++ b/skills/productivity/xlsx/scripts/xlsx_restructure.py
@@ -0,0 +1,337 @@
+#!/usr/bin/env python3
+"""Reference-aware row/column insert and delete for .xlsx workbooks.
+
+Unlike plain openpyxl insert_rows/delete_cols (and xlsx_edit.py's thin
+wrappers), this script also rewrites everything that points at the moved
+cells:
+
+ * formula references in ALL sheets, including absolute refs ($B$2),
+ ranges (B2:B9), and cross-sheet refs ('My Sheet'!A1 / Data!$B$8).
+ References into a deleted region become #REF!.
+ * merged-cell ranges (shifted; expanded when they span the insertion
+ point; removed when fully deleted)
+ * autofilter range, freeze panes, data-validation ranges,
+ conditional-formatting applied ranges (sqref)
+ * native table (ListObject) refs on the edited sheet
+ * workbook-scope defined names that point at the edited sheet
+ * row heights / column widths
+
+It prints a JSON report of every rewrite it made and lists what it
+could NOT shift (chart anchors, images, conditional-format RULE
+formulas). Full rules and limits: references/restructuring.md.
+
+One structural operation per invocation:
+
+Usage:
+ xlsx_restructure.py book.xlsx --sheet Data --insert-rows 3:2
+ xlsx_restructure.py book.xlsx --sheet Data --delete-rows 5
+ xlsx_restructure.py book.xlsx --sheet Data --insert-cols B:1 --out new.xlsx
+ xlsx_restructure.py book.xlsx --sheet Data --delete-cols 4:2
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import re
+import sys
+
+from openpyxl import load_workbook
+from openpyxl.formatting.formatting import ConditionalFormattingList
+from openpyxl.utils import (column_index_from_string, get_column_letter,
+ range_boundaries)
+
+# A1-style reference, optionally sheet-qualified, optionally a range.
+# Guards: not preceded by a word char/$/. (avoids ABC123 identifiers) and
+# not followed by a word char or "(" (avoids function names like LOG10().
+REF_RE = re.compile(
+ r"(?<![\w$.:])"
+ r"(?P<sheet>(?:'(?:[^']|'')+'|[A-Za-z_][A-Za-z0-9_.]*)!)?"
+ r"(?P<start>\$?[A-Za-z]{1,3}\$?[0-9]{1,7})"
+ r"(?::(?P<end>\$?[A-Za-z]{1,3}\$?[0-9]{1,7}))?"
+ r"(?![\w(])")
+STRING_RE = re.compile(r'"(?:[^"]|"")*"')
+COORD_RE = re.compile(r"^(\$?)([A-Za-z]{1,3})(\$?)([0-9]+)$")
+
+
+def shift_point(v, idx, n, delete):
+ """New 1-based index for a single row/col, or None if deleted."""
+ if delete:
+ if v < idx:
+ return v
+ if v >= idx + n:
+ return v - n
+ return None
+ return v + n if v >= idx else v
+
+
+def shift_span(a, b, idx, n, delete):
+ """New (start, end) for an inclusive span, or None if fully deleted."""
+ if delete:
+ na = a if a < idx else (a - n if a >= idx + n else idx)
+ nb = b if b < idx else (b - n if b >= idx + n else idx - 1)
+ return None if na > nb else (na, nb)
+ return (a + n if a >= idx else a, b + n if b >= idx else b)
+
+
+def shift_range(rng, axis, idx, n, delete):
+ """Shift an A1 range string (no sheet prefix). None = fully deleted."""
+ min_col, min_row, max_col, max_row = range_boundaries(rng)
+ if axis == "rows":
+ span = shift_span(min_row, max_row, idx, n, delete)
+ if span is None:
+ return None
+ min_row, max_row = span
+ else:
+ span = shift_span(min_col, max_col, idx, n, delete)
+ if span is None:
+ return None
+ min_col, max_col = span
+ start = f"{get_column_letter(min_col)}{min_row}"
+ end = f"{get_column_letter(max_col)}{max_row}"
+ return start if start == end and ":" not in rng else f"{start}:{end}"
+
+
+class RefRewriter:
+ """Rewrite A1 references in formula-like text for one shift op."""
+
+ def __init__(self, target_sheet, axis, idx, n, delete):
+ self.target = target_sheet.lower()
+ self.axis, self.idx, self.n, self.delete = axis, idx, n, delete
+
+ def _shift_coord(self, coord):
+ m = COORD_RE.match(coord)
+ col_abs, col, row_abs, row = m.groups()
+ ci, ri = column_index_from_string(col.upper()), int(row)
+ if self.axis == "rows":
+ ri = shift_point(ri, self.idx, self.n, self.delete)
+ if ri is None:
+ return None
+ else:
+ ci = shift_point(ci, self.idx, self.n, self.delete)
+ if ci is None:
+ return None
+ return f"{col_abs}{get_column_letter(ci)}{row_abs}{ri}"
+
+ def _shift_pair(self, start, end):
+ """Shift a range preserving $ flags; None = collapsed to #REF!."""
+ new_start = self._shift_coord(start)
+ new_end = self._shift_coord(end)
+ if new_start is None or new_end is None:
+ # spans may survive partial deletion: clamp via span math
+ s, e = COORD_RE.match(start), COORD_RE.match(end)
+ if self.axis == "rows":
+ span = shift_span(int(s.group(4)), int(e.group(4)),
+ self.idx, self.n, self.delete)
+ if span is None:
+ return None
+ new_start = f"{s.group(1)}{s.group(2)}{s.group(3)}{span[0]}"
+ new_end = f"{e.group(1)}{e.group(2)}{e.group(3)}{span[1]}"
+ else:
+ span = shift_span(column_index_from_string(s.group(2).upper()),
+ column_index_from_string(e.group(2).upper()),
+ self.idx, self.n, self.delete)
+ if span is None:
+ return None
+ new_start = (f"{s.group(1)}{get_column_letter(span[0])}"
+ f"{s.group(3)}{s.group(4)}")
+ new_end = (f"{e.group(1)}{get_column_letter(span[1])}"
+ f"{e.group(3)}{e.group(4)}")
+ return new_start, new_end
+
+ def _sub(self, match, home_sheet):
+ prefix = match.group("sheet") or ""
+ if prefix:
+ name = prefix[:-1]
+ if name.startswith("'"):
+ name = name[1:-1].replace("''", "'")
+ ref_sheet = name
+ else:
+ ref_sheet = home_sheet
+ if ref_sheet.lower() != self.target:
+ return match.group(0)
+ start, end = match.group("start"), match.group("end")
+ if end is None:
+ new = self._shift_coord(start)
+ return prefix + ("#REF!" if new is None else new)
+ pair = self._shift_pair(start, end)
+ return (prefix + "#REF!" if pair is None
+ else f"{prefix}{pair[0]}:{pair[1]}")
+
+ def rewrite(self, text, home_sheet):
+ """Rewrite refs outside quoted string literals. Returns new text."""
+ out, pos = [], 0
+ for lit in STRING_RE.finditer(text):
+ out.append(REF_RE.sub(lambda m: self._sub(m, home_sheet),
+ text[pos:lit.start()]))
+ out.append(lit.group(0))
+ pos = lit.end()
+ out.append(REF_RE.sub(lambda m: self._sub(m, home_sheet), text[pos:]))
+ return "".join(out)
+
+
+def shift_dimensions(dims, idx, n, delete, is_row):
+ """Rebuild a row/column dimensions map with shifted keys."""
+ items = list(dims.items())
+ saved = {}
+ for key, dim in items:
+ pos = key if is_row else column_index_from_string(key)
+ new = shift_point(pos, idx, n, delete)
+ if new is not None and new != pos:
+ saved[new if is_row else get_column_letter(new)] = dim
+ del dims[key]
+ for key, dim in saved.items():
+ if is_row:
+ dim.index = key
+ else:
+ dim.index = column_index_from_string(key)
+ dims[key] = dim
+ return len(saved)
+
+
+def main(argv=None):
+ ap = argparse.ArgumentParser(
+ description="Insert/delete rows or columns AND rewrite formula "
+ "references, merges, filters, validations, tables, and "
+ "defined names to match.",
+ epilog="Cannot shift: chart anchors, images, conditional-format "
+ "rule formulas. See references/restructuring.md.")
+ ap.add_argument("file", help="path to .xlsx file")
+ ap.add_argument("--sheet", help="target sheet (default: active)")
+ ap.add_argument("--out", help="output path (default: edit in place)")
+ op = ap.add_mutually_exclusive_group(required=True)
+ op.add_argument("--insert-rows", metavar="IDX[:N]")
+ op.add_argument("--delete-rows", metavar="IDX[:N]")
+ op.add_argument("--insert-cols", metavar="COL[:N]",
+ help="COL is a letter (B) or 1-based number")
+ op.add_argument("--delete-cols", metavar="COL[:N]")
+ args = ap.parse_args(argv)
+
+ raw = (args.insert_rows or args.delete_rows
+ or args.insert_cols or args.delete_cols)
+ idx_s, _, n_s = raw.partition(":")
+ n = int(n_s) if n_s else 1
+ axis = "rows" if (args.insert_rows or args.delete_rows) else "cols"
+ delete = bool(args.delete_rows or args.delete_cols)
+ if axis == "cols" and idx_s.isalpha():
+ idx = column_index_from_string(idx_s.upper())
+ else:
+ idx = int(idx_s)
+
+ wb = load_workbook(args.file)
+ ws = wb[args.sheet] if args.sheet else wb.active
+ rewriter = RefRewriter(ws.title, axis, idx, n, delete)
+ report = {"ok": True, "sheet": ws.title, "axis": axis,
+ "op": "delete" if delete else "insert", "index": idx, "count": n,
+ "formulas": [], "merges": [], "tables": {}, "defined_names": {},
+ "validations": [], "conditional_formats": [],
+ "not_shifted": ["chart anchors", "images",
+ "conditional-format rule formulas"]}
+
+ # 1. capture merge ranges (openpyxl does not move them), then unmerge
+ old_merges = [str(r) for r in list(ws.merged_cells.ranges)]
+ for rng in old_merges:
+ ws.unmerge_cells(rng)
+
+ # 2. structural move of cell values/styles/comments
+ getattr(ws, f"{report['op']}_{axis}")(idx, n)
+
+ # 3. formulas everywhere
+ for sheet in wb.worksheets:
+ for row in sheet.iter_rows():
+ for cell in row:
+ if isinstance(cell.value, str) and cell.value.startswith("="):
+ new = rewriter.rewrite(cell.value, sheet.title)
+ if new != cell.value:
+ report["formulas"].append(
+ {"sheet": sheet.title, "cell": cell.coordinate,
+ "from": cell.value, "to": new})
+ cell.value = new
+
+ # 4. merges back, shifted
+ for rng in old_merges:
+ new = shift_range(rng, axis, idx, n, delete)
+ if new is None:
+ report["merges"].append({"from": rng, "to": None})
+ else:
+ ws.merge_cells(new)
+ if new != rng:
+ report["merges"].append({"from": rng, "to": new})
+
+ # 5. autofilter + freeze panes
+ if ws.auto_filter.ref:
+ new = shift_range(ws.auto_filter.ref, axis, idx, n, delete)
+ if new != ws.auto_filter.ref:
+ report["autofilter"] = {"from": ws.auto_filter.ref, "to": new}
+ ws.auto_filter.ref = new
+ if ws.freeze_panes:
+ m = COORD_RE.match(ws.freeze_panes)
+ ci = column_index_from_string(m.group(2).upper())
+ ri = int(m.group(4))
+ if axis == "rows":
+ ri = shift_point(ri, idx, n, delete) or max(idx, 2)
+ else:
+ ci = shift_point(ci, idx, n, delete) or max(idx, 2)
+ new = f"{get_column_letter(ci)}{ri}"
+ if new != ws.freeze_panes:
+ report["freeze_panes"] = {"from": ws.freeze_panes, "to": new}
+ ws.freeze_panes = new
+
+ # 6. data validations + conditional formatting applied ranges
+ for dv in ws.data_validations.dataValidation:
+ old = str(dv.sqref)
+ parts = [shift_range(p, axis, idx, n, delete) for p in old.split()]
+ parts = [p for p in parts if p]
+ if parts and " ".join(parts) != old:
+ dv.sqref = " ".join(parts)
+ report["validations"].append({"from": old, "to": str(dv.sqref)})
+ new_cf = ConditionalFormattingList()
+ for cf in ws.conditional_formatting:
+ old = str(cf.sqref)
+ parts = [shift_range(p, axis, idx, n, delete) for p in old.split()]
+ parts = [p for p in parts if p]
+ if not parts:
+ report["conditional_formats"].append({"from": old, "to": None})
+ continue
+ new = " ".join(parts)
+ for rule in cf.rules:
+ new_cf.add(new, rule)
+ if new != old:
+ report["conditional_formats"].append({"from": old, "to": new})
+ ws.conditional_formatting = new_cf
+
+ # 7. native tables on the edited sheet
+ for table in ws.tables.values():
+ new = shift_range(table.ref, axis, idx, n, delete)
+ if new and new != table.ref:
+ report["tables"][table.displayName] = {"from": table.ref,
+ "to": new}
+ table.ref = new
+
+ # 8. workbook-scope defined names
+ for name, dn in wb.defined_names.items():
+ if dn.attr_text and "!" in dn.attr_text:
+ new = rewriter.rewrite(dn.attr_text, ws.title)
+ if new != dn.attr_text:
+ report["defined_names"][name] = {"from": dn.attr_text,
+ "to": new}
+ dn.attr_text = new
+
+ # 9. row heights / column widths
+ if axis == "rows":
+ shift_dimensions(ws.row_dimensions, idx, n, delete, is_row=True)
+ else:
+ shift_dimensions(ws.column_dimensions, idx, n, delete, is_row=False)
+
+ out = args.out or args.file
+ wb.save(out)
+ report["output"] = out
+ print(json.dumps(report, ensure_ascii=False, indent=2))
+ return 0
+
+
+if __name__ == "__main__":
+ try:
+ sys.exit(main())
+ except Exception as exc: # noqa: BLE001
+ print(json.dumps({"ok": False, "error": str(exc)}), file=sys.stderr)
+ sys.exit(1)
diff --git a/skills/productivity/xlsx/tests/test_xlsx_skill.py b/skills/productivity/xlsx/tests/test_xlsx_skill.py
index c1fccbbced2..dd56f2fa172 100644
--- a/skills/productivity/xlsx/tests/test_xlsx_skill.py
+++ b/skills/productivity/xlsx/tests/test_xlsx_skill.py
@@ -8,6 +8,7 @@ from __future__ import annotations
import csv
import json
import os
+import shutil
import subprocess
import sys
from datetime import date
@@ -242,10 +243,300 @@ def test_edit_existing(workbook, tmp_path):
def test_help_and_errors():
for script in ["xlsx_create.py", "xlsx_read.py", "xlsx_edit.py",
- "csv_to_xlsx.py", "xlsx_to_csv.py"]:
+ "csv_to_xlsx.py", "xlsx_to_csv.py",
+ "xlsx_restructure.py", "xlsx_recalc.py"]:
proc = run(script, "--help")
assert "usage" in proc.stdout.lower()
bad = run("xlsx_read.py", "/nonexistent.xlsx", "--sheets",
expect_ok=False)
assert bad.returncode != 0
assert json.loads(bad.stderr)["ok"] is False
+
+
+# ---------------------------------------------------------------------------
+# Reference-aware restructuring (xlsx_restructure.py)
+# ---------------------------------------------------------------------------
+
+RESTRUCTURE_SPEC = {
+ "defined_names": {"SalesRange": "'Data'!$B$2:$B$4"},
+ "sheets": [
+ {
+ "name": "Data",
+ "rows": [
+ ["Region", "Sales", "Weight"],
+ ["North", 100, 0.5],
+ ["South", 200, 0.3],
+ ["East", 300, 0.2],
+ [None, None, None],
+ ["Total", None, None],
+ ],
+ "cells": {
+ "B6": {"formula": "SUM(B2:B4)"},
+ "C6": {"formula": "$B$2*C2"},
+ "D6": {"formula": "LOG10(B4)"},
+ "E6": {"formula": "SUM(B:B)"},
+ "F6": {"formula": '"row B2: "&B2'},
+ },
+ "merges": ["E2:E4", "A7:B7"],
+ "freeze_panes": "A2",
+ "autofilter": "A1:C4",
+ "conditional_formats": [
+ {"range": "B2:B4", "type": "cell_is",
+ "operator": "greaterThan", "formula": ["150"],
+ "fill": "C6EFCE"},
+ ],
+ "validations": [
+ {"range": "C2:C4", "type": "list",
+ "formula1": '"0.2,0.3,0.5"'},
+ ],
+ "tables": [
+ {"name": "SalesTbl", "range": "A1:C4"},
+ ],
+ },
+ {
+ "name": "Summary",
+ "rows": [["Grand total"]],
+ "cells": {
+ "B1": {"formula": "SUM(Data!B2:B4)"},
+ "B2": {"formula": "'Data'!$B$3"},
+ "B3": {"formula": "SUM(A1:A1)"},
+ },
+ },
+ ],
+}
+
+
+def restructure_book(tmp_path):
+ spec_path = tmp_path / "rspec.json"
+ spec_path.write_text(json.dumps(RESTRUCTURE_SPEC), encoding="utf-8")
+ out = tmp_path / "restructure.xlsx"
+ run("xlsx_create.py", spec_path, out)
+ return out
+
+
+def test_restructure_insert_rows_shifts_everything(restructure_book):
+ # merge A6:C6 gets pushed down; A1:A1 merge is before the insert point
+ proc = run("xlsx_restructure.py", restructure_book,
+ "--sheet", "Data", "--insert-rows", "3:2")
+ report = json.loads(proc.stdout)
+ assert report["ok"] and report["op"] == "insert"
+
+ wb = load_workbook(restructure_book)
+ data, summary = wb["Data"], wb["Summary"]
+ # values physically moved
+ assert data["A2"].value == "North"
+ assert data["A5"].value == "South" # was row 3
+ assert data["A8"].value == "Total" # was row 6
+ # same-sheet formulas rewritten (range expanded across insert point)
+ assert data["B8"].value == "=SUM(B2:B6)"
+ # absolute ref before insert point unchanged; relative arm shifted
+ assert data["C8"].value == "=$B$2*C2"
+ # function names, whole-column refs, string literals untouched
+ assert data["D8"].value == "=LOG10(B6)"
+ assert data["E8"].value == "=SUM(B:B)"
+ assert data["F8"].value == '="row B2: "&B2'
+ # cross-sheet formulas on the OTHER sheet rewritten
+ assert summary["B1"].value == "=SUM(Data!B2:B6)"
+ assert summary["B2"].value == "='Data'!$B$5"
+ # Summary-local refs not confused with Data refs
+ assert summary["B3"].value == "=SUM(A1:A1)"
+ # merges: E2:E4 spans the insert point -> expanded; A7:B7 -> shifted
+ merged = [str(r) for r in data.merged_cells.ranges]
+ assert "E2:E6" in merged and "A9:B9" in merged
+ # autofilter expanded, freeze panes intact
+ assert data.auto_filter.ref == "A1:C6"
+ assert data.freeze_panes == "A2"
+ # validation + conditional format ranges shifted
+ dv = data.data_validations.dataValidation[0]
+ assert str(dv.sqref) == "C2:C6"
+ cf = list(data.conditional_formatting)[0]
+ assert str(cf.sqref) == "B2:B6"
+ # native table expanded
+ assert data.tables["SalesTbl"].ref == "A1:C6"
+ # defined name rewritten
+ assert wb.defined_names["SalesRange"].attr_text == "'Data'!$B$2:$B$6"
+ # report is honest about limits
+ assert "chart anchors" in report["not_shifted"]
+ assert any(f["cell"] == "B1" and f["sheet"] == "Summary"
+ for f in report["formulas"])
+
+
+def test_restructure_delete_rows_and_ref_errors(restructure_book):
+ run("xlsx_restructure.py", restructure_book,
+ "--sheet", "Data", "--delete-rows", "3")
+ wb = load_workbook(restructure_book)
+ data, summary = wb["Data"], wb["Summary"]
+ assert data["A3"].value == "East" # South deleted
+ assert data["B5"].value == "=SUM(B2:B3)" # range clamped
+ # single-cell ref into the deleted row becomes #REF!
+ assert summary["B2"].value == "='Data'!#REF!"
+ assert summary["B1"].value == "=SUM(Data!B2:B3)"
+ assert data.tables["SalesTbl"].ref == "A1:C3"
+
+
+def test_restructure_insert_cols(restructure_book):
+ proc = run("xlsx_restructure.py", restructure_book,
+ "--sheet", "Data", "--insert-cols", "B:1")
+ report = json.loads(proc.stdout)
+ assert report["axis"] == "cols" and report["index"] == 2
+ wb = load_workbook(restructure_book)
+ data, summary = wb["Data"], wb["Summary"]
+ assert data["C2"].value == 100 # Sales moved B->C
+ assert data["C6"].value == "=SUM(C2:C4)"
+ assert data["D6"].value == "=$C$2*D2"
+ assert summary["B1"].value == "=SUM(Data!C2:C4)"
+ assert wb.defined_names["SalesRange"].attr_text == "'Data'!$C$2:$C$4"
+ merged = [str(r) for r in data.merged_cells.ranges]
+ assert "F2:F4" in merged # merge shifted right
+ assert "A7:C7" in merged # merge expanded across col B
+
+
+# ---------------------------------------------------------------------------
+# Tables, defined names, hyperlinks, notes, protection (edit + read paths)
+# ---------------------------------------------------------------------------
+
+def test_tables_create_append_list(tmp_path):
+ spec = {"sheets": [{"name": "T",
+ "rows": [["Item", "Qty"], ["a", 1], ["b", 2]],
+ "tables": [{"name": "Stock", "range": "A1:B3",
+ "style": "TableStyleLight1"}]}]}
+ spec_path = tmp_path / "tspec.json"
+ spec_path.write_text(json.dumps(spec), encoding="utf-8")
+ book = tmp_path / "tables.xlsx"
+ run("xlsx_create.py", spec_path, book)
+
+ wb = load_workbook(book)
+ tbl = wb["T"].tables["Stock"]
+ assert tbl.ref == "A1:B3"
+ assert tbl.tableStyleInfo.name == "TableStyleLight1"
+
+ # --add-table + --table-append auto-extends the range
+ run("xlsx_edit.py", book, "--sheet", "T",
+ "--add-table", "Extra:D1:E2",
+ "--table-append", 'Stock=["c", 3]')
+ wb = load_workbook(book)
+ ws = wb["T"]
+ assert ws.tables["Stock"].ref == "A1:B4"
+ assert ws["A4"].value == "c" and ws["B4"].value == 3
+ assert ws.tables["Extra"].ref == "D1:E2"
+
+ listing = json.loads(
+ run("xlsx_edit.py", book, "--sheet", "T", "--list-tables").stdout)
+ assert listing["tables"]["Stock"]["ref"] == "A1:B4"
+ assert set(listing["tables"]) == {"Stock", "Extra"}
+ # tables also appear in the read inventory
+ inv = json.loads(run("xlsx_read.py", book, "--sheets").stdout)
+ assert inv["sheets"][0]["tables"]["Stock"] == "A1:B4"
+
+
+def test_names_hyperlinks_notes(tmp_path):
+ spec = {
+ "defined_names": {"Rate": "'D'!$B$1"},
+ "sheets": [{"name": "D", "cells": {
+ "A1": {"value": "docs",
+ "hyperlink": "https://example.com/docs"},
+ "B1": {"value": 0.07, "note": "quarterly rate"},
+ "C1": {"value": 1, "note": {"text": "check", "author": "QA"}},
+ }}],
+ }
+ spec_path = tmp_path / "nspec.json"
+ spec_path.write_text(json.dumps(spec), encoding="utf-8")
+ book = tmp_path / "names.xlsx"
+ run("xlsx_create.py", spec_path, book)
+
+ wb = load_workbook(book)
+ ws = wb["D"]
+ assert ws["A1"].hyperlink.target == "https://example.com/docs"
+ assert ws["B1"].comment.text == "quarterly rate"
+ assert ws["C1"].comment.author == "QA"
+ assert wb.defined_names["Rate"].attr_text == "'D'!$B$1"
+
+ # edit path: add/delete names, hyperlink, note, clear note
+ run("xlsx_edit.py", book, "--sheet", "D",
+ "--define-name", "Extra='D'!$C$1",
+ "--delete-name", "Rate",
+ "--hyperlink", "D1=https://example.com/more|More",
+ "--note", "D1=see more|Reviewer",
+ "--clear-note", "B1")
+ wb = load_workbook(book)
+ ws = wb["D"]
+ assert "Rate" not in wb.defined_names
+ assert wb.defined_names["Extra"].attr_text == "'D'!$C$1"
+ assert ws["D1"].hyperlink.target == "https://example.com/more"
+ assert ws["D1"].value == "More"
+ assert ws["D1"].comment.author == "Reviewer"
+ assert ws["B1"].comment is None
+
+ # read path: --notes and --names JSON output
+ notes = json.loads(run("xlsx_read.py", book, "--notes").stdout)["notes"]
+ coords = {(n["cell"], n["author"]) for n in notes}
+ assert ("D1", "Reviewer") in coords and ("C1", "QA") in coords
+ names = json.loads(run("xlsx_read.py", book, "--names").stdout)
+ assert names["defined_names"] == {"Extra": "'D'!$C$1"}
+
+
+def test_sheet_protection(tmp_path):
+ spec = {"sheets": [{"name": "P", "rows": [["locked", "open"]],
+ "protection": {"password": "your-password",
+ "unlock": ["B1:B1"]}}]}
+ spec_path = tmp_path / "pspec.json"
+ spec_path.write_text(json.dumps(spec), encoding="utf-8")
+ book = tmp_path / "prot.xlsx"
+ run("xlsx_create.py", spec_path, book)
+
+ wb = load_workbook(book)
+ ws = wb["P"]
+ assert ws.protection.sheet is True
+ assert ws.protection.password # hash stored
+ assert ws["B1"].protection.locked is False
+ assert ws["A1"].protection.locked is not False
+ inv = json.loads(run("xlsx_read.py", book, "--sheets").stdout)
+ assert inv["sheets"][0]["protected"] is True
+
+ # edit path on a fresh unprotected sheet
+ plain = tmp_path / "plain.xlsx"
+ spec_path.write_text(json.dumps(
+ {"sheets": [{"name": "P", "rows": [["a", "b"]]}]}), encoding="utf-8")
+ run("xlsx_create.py", spec_path, plain)
+ run("xlsx_edit.py", plain, "--sheet", "P",
+ "--protect", "your-password", "--unlock", "B1:B1")
+ ws = load_workbook(plain)["P"]
+ assert ws.protection.sheet is True and ws["B1"].protection.locked is False
+
+
+# ---------------------------------------------------------------------------
+# Headless recalculation (xlsx_recalc.py) — branches on soffice presence
+# ---------------------------------------------------------------------------
+
+def test_recalc_reports_json_both_ways(tmp_path):
+ spec = {"sheets": [{"name": "R", "rows": [[2], [3]],
+ "cells": {"A3": {"formula": "SUM(A1:A2)"}}}]}
+ spec_path = tmp_path / "cspec.json"
+ spec_path.write_text(json.dumps(spec), encoding="utf-8")
+ book = tmp_path / "calc.xlsx"
+ run("xlsx_create.py", spec_path, book)
+
+ # absent-soffice branch is always testable by hiding PATH
+ env = dict(os.environ, LC_ALL="C", LANG="C", PATH=str(tmp_path))
+ proc = subprocess.run(
+ [sys.executable, str(SCRIPTS / "xlsx_recalc.py"), str(book)],
+ capture_output=True, text=True, env=env, encoding="utf-8")
+ assert proc.returncode == 0
+ absent = json.loads(proc.stdout)
+ assert absent["recalculated"] is False and "soffice" in absent["reason"]
+ assert "guidance" in absent
+
+ if not shutil.which("soffice"):
+ pytest.skip("LibreOffice not installed; absent branch covered above")
+
+ out = tmp_path / "calced.xlsx"
+ proc = run("xlsx_recalc.py", book, "--out", out, "--timeout", "300")
+ result = json.loads(proc.stdout)
+ assert result["recalculated"] is True
+ assert result["formula_cells"] == 1
+ assert result["with_cached_values"] == 1
+ # cached value now visible to --formulas
+ formulas = json.loads(run("xlsx_read.py", out, "--formulas").stdout)
+ entry = formulas["formulas"][0]
+ assert entry["formula"] == "=SUM(A1:A2)" and entry["cached"] == 5