docx_edit.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. #!/usr/bin/env python3
  2. # MIT License. Part of the Hermes docx skill.
  3. """Edit an existing .docx in place (or to a new file).
  4. Subcommands:
  5. replace find-and-replace text, preserving run formatting
  6. set-cell set the text of a table cell
  7. insert insert a paragraph before a given body paragraph index
  8. delete delete a body paragraph by index
  9. style apply a paragraph style to a body paragraph by index
  10. normalize merge adjacent runs with identical formatting
  11. toc insert a Table of Contents field at a body paragraph index
  12. page-numbers add "Page X of Y" (PAGE/NUMPAGES fields) to the footer
  13. Examples:
  14. docx_edit.py replace in.docx --find old --replace new -o out.docx
  15. docx_edit.py set-cell in.docx --table 0 --row 1 --col 2 --text "42"
  16. docx_edit.py insert in.docx --index 3 --text "New para" --style Normal
  17. docx_edit.py delete in.docx --index 3
  18. docx_edit.py style in.docx --index 0 --style "Heading 1"
  19. docx_edit.py normalize in.docx -o out.docx
  20. docx_edit.py toc in.docx --index 1 -o out.docx
  21. docx_edit.py page-numbers in.docx -o out.docx
  22. Field results (TOC entries, page numbers) are computed by Word or
  23. LibreOffice when the document is opened, not by python-docx; until then
  24. the fields show placeholder text.
  25. """
  26. from __future__ import annotations
  27. import argparse
  28. import json
  29. import sys
  30. from docx import Document
  31. from docx_common import iter_all_paragraphs, replace_in_paragraph
  32. W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
  33. def _q(tag: str) -> str:
  34. return f"{{{W}}}{tag}"
  35. def cmd_replace(doc, args) -> dict:
  36. n = 0
  37. for para in iter_all_paragraphs(doc):
  38. n += replace_in_paragraph(para, args.find, args.replace)
  39. return {"replacements": n}
  40. def cmd_set_cell(doc, args) -> dict:
  41. cell = doc.tables[args.table].cell(args.row, args.col)
  42. cell.text = args.text
  43. return {"table": args.table, "row": args.row, "col": args.col}
  44. def cmd_insert(doc, args) -> dict:
  45. paras = doc.paragraphs
  46. if args.index < len(paras):
  47. anchor = paras[args.index]
  48. new_para = anchor.insert_paragraph_before(args.text, style=args.style)
  49. else:
  50. new_para = doc.add_paragraph(args.text, style=args.style)
  51. return {"inserted_at": args.index, "text": new_para.text}
  52. def cmd_delete(doc, args) -> dict:
  53. para = doc.paragraphs[args.index]
  54. el = para._element
  55. el.getparent().remove(el)
  56. return {"deleted_index": args.index}
  57. def cmd_style(doc, args) -> dict:
  58. doc.paragraphs[args.index].style = doc.styles[args.style]
  59. return {"index": args.index, "style": args.style}
  60. def _run_format_key(r_el) -> str:
  61. """Canonical string for a run's w:rPr (None when absent)."""
  62. from lxml import etree
  63. rpr = r_el.find(_q("rPr"))
  64. return "" if rpr is None else etree.tostring(rpr).decode("utf-8")
  65. def cmd_normalize(doc) -> dict:
  66. """Merge adjacent sibling runs with identical formatting."""
  67. merged = 0
  68. for para in iter_all_paragraphs(doc):
  69. prev = None
  70. for r_el in list(para._p):
  71. if r_el.tag != _q("r"):
  72. prev = None
  73. continue
  74. # only merge plain-text runs (no breaks, tabs, drawings...)
  75. kids = {c.tag for c in r_el} - {_q("rPr"), _q("t")}
  76. if kids:
  77. prev = None
  78. continue
  79. if (prev is not None
  80. and _run_format_key(prev) == _run_format_key(r_el)):
  81. pt = prev.find(_q("t"))
  82. ct = r_el.find(_q("t"))
  83. if pt is None:
  84. pt = prev.makeelement(_q("t"), {})
  85. prev.append(pt)
  86. pt.text = (pt.text or "") + ((ct.text or "")
  87. if ct is not None else "")
  88. pt.set("{http://www.w3.org/XML/1998/namespace}space",
  89. "preserve")
  90. r_el.getparent().remove(r_el)
  91. merged += 1
  92. else:
  93. prev = r_el
  94. return {"runs_merged": merged}
  95. def _add_field(para, instr: str, placeholder: str) -> None:
  96. """Append a complex field (begin/instrText/separate/result/end)."""
  97. p = para._p
  98. for ftype, extra in (("begin", None), (None, instr),
  99. ("separate", None), (None, placeholder),
  100. ("end", None)):
  101. r = p.makeelement(_q("r"), {})
  102. p.append(r)
  103. if ftype is not None:
  104. fld = r.makeelement(_q("fldChar"), {_q("fldCharType"): ftype})
  105. r.append(fld)
  106. elif extra is instr:
  107. it = r.makeelement(_q("instrText"), {})
  108. it.set("{http://www.w3.org/XML/1998/namespace}space", "preserve")
  109. it.text = instr
  110. r.append(it)
  111. else:
  112. t = r.makeelement(_q("t"), {})
  113. t.text = extra
  114. r.append(t)
  115. def cmd_toc(doc, args) -> dict:
  116. paras = doc.paragraphs
  117. if args.index < len(paras):
  118. para = paras[args.index].insert_paragraph_before("")
  119. else:
  120. para = doc.add_paragraph("")
  121. _add_field(para, r' TOC \o "1-3" \h \z \u ',
  122. "Table of contents - open in Word/LibreOffice and update "
  123. "fields to populate.")
  124. return {"toc_inserted_at": args.index}
  125. def cmd_page_numbers(doc, args) -> dict:
  126. footer = doc.sections[0].footer
  127. para = footer.paragraphs[0] if footer.paragraphs \
  128. else footer.add_paragraph()
  129. para.add_run("Page ")
  130. _add_field(para, " PAGE ", "1")
  131. para.add_run(" of ")
  132. _add_field(para, " NUMPAGES ", "1")
  133. return {"footer_fields": ["PAGE", "NUMPAGES"]}
  134. def main() -> int:
  135. ap = argparse.ArgumentParser(description="Edit a .docx file.")
  136. sub = ap.add_subparsers(dest="cmd", required=True)
  137. def common(p):
  138. p.add_argument("path", help="input .docx")
  139. p.add_argument("-o", "--output",
  140. help="output path (default: overwrite input)")
  141. p = sub.add_parser("replace", help="find-and-replace text")
  142. common(p)
  143. p.add_argument("--find", required=True)
  144. p.add_argument("--replace", required=True)
  145. p.add_argument("--body-only", action="store_true",
  146. help="skip headers/footers")
  147. p = sub.add_parser("set-cell", help="set table cell text")
  148. common(p)
  149. p.add_argument("--table", type=int, required=True, help="table index")
  150. p.add_argument("--row", type=int, required=True)
  151. p.add_argument("--col", type=int, required=True)
  152. p.add_argument("--text", required=True)
  153. p = sub.add_parser("insert", help="insert paragraph at body index")
  154. common(p)
  155. p.add_argument("--index", type=int, required=True)
  156. p.add_argument("--text", required=True)
  157. p.add_argument("--style", default=None)
  158. p = sub.add_parser("delete", help="delete body paragraph by index")
  159. common(p)
  160. p.add_argument("--index", type=int, required=True)
  161. p = sub.add_parser("style", help="apply style to body paragraph")
  162. common(p)
  163. p.add_argument("--index", type=int, required=True)
  164. p.add_argument("--style", required=True)
  165. p = sub.add_parser("normalize",
  166. help="merge adjacent runs with identical formatting")
  167. common(p)
  168. p = sub.add_parser("toc", help="insert a TOC field (Word computes it)")
  169. common(p)
  170. p.add_argument("--index", type=int, default=0,
  171. help="body paragraph index to insert before (default 0)")
  172. p = sub.add_parser("page-numbers",
  173. help="add PAGE/NUMPAGES fields to the footer")
  174. common(p)
  175. args = ap.parse_args()
  176. doc = Document(args.path)
  177. if args.cmd == "replace":
  178. if args.body_only:
  179. n = 0
  180. for para in iter_all_paragraphs(doc, include_headers_footers=False):
  181. n += replace_in_paragraph(para, args.find, args.replace)
  182. result = {"replacements": n}
  183. else:
  184. result = cmd_replace(doc, args)
  185. elif args.cmd == "set-cell":
  186. result = cmd_set_cell(doc, args)
  187. elif args.cmd == "insert":
  188. result = cmd_insert(doc, args)
  189. elif args.cmd == "delete":
  190. result = cmd_delete(doc, args)
  191. elif args.cmd == "normalize":
  192. result = cmd_normalize(doc)
  193. elif args.cmd == "toc":
  194. result = cmd_toc(doc, args)
  195. elif args.cmd == "page-numbers":
  196. result = cmd_page_numbers(doc, args)
  197. else:
  198. result = cmd_style(doc, args)
  199. out = args.output or args.path
  200. doc.save(out)
  201. result.update({"ok": True, "output": out})
  202. print(json.dumps(result, ensure_ascii=False))
  203. return 0
  204. if __name__ == "__main__":
  205. sys.exit(main())