zcode-app-cli 3.3.5-1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. package/LICENSE +24 -0
  2. package/README.md +642 -0
  3. package/bin/zcode.js +848 -0
  4. package/config.example.json +110 -0
  5. package/package.json +81 -0
  6. package/vendor/.node-bundle-meta.json +6 -0
  7. package/vendor/extraction.json +11 -0
  8. package/vendor/node_modules/@zcode/tui/dist/index.js +161875 -0
  9. package/vendor/node_modules/@zcode/tui/package.json +14 -0
  10. package/vendor/packages/android-emulator-plugin/.mcp.json +19 -0
  11. package/vendor/packages/android-emulator-plugin/.zcode-plugin/plugin.json +63 -0
  12. package/vendor/packages/android-emulator-plugin/README.md +134 -0
  13. package/vendor/packages/android-emulator-plugin/commands/android-dev.md +11 -0
  14. package/vendor/packages/android-emulator-plugin/dist/lib/path.d.ts +4 -0
  15. package/vendor/packages/android-emulator-plugin/dist/lib/path.js +17 -0
  16. package/vendor/packages/android-emulator-plugin/dist/lib/result.d.ts +5 -0
  17. package/vendor/packages/android-emulator-plugin/dist/lib/result.js +22 -0
  18. package/vendor/packages/android-emulator-plugin/dist/lib/run.d.ts +18 -0
  19. package/vendor/packages/android-emulator-plugin/dist/lib/run.js +99 -0
  20. package/vendor/packages/android-emulator-plugin/dist/mcp/server.d.ts +3 -0
  21. package/vendor/packages/android-emulator-plugin/dist/mcp/server.js +47607 -0
  22. package/vendor/packages/android-emulator-plugin/dist/providers/app.d.ts +39 -0
  23. package/vendor/packages/android-emulator-plugin/dist/providers/app.js +50 -0
  24. package/vendor/packages/android-emulator-plugin/dist/providers/avd.d.ts +37 -0
  25. package/vendor/packages/android-emulator-plugin/dist/providers/avd.js +185 -0
  26. package/vendor/packages/android-emulator-plugin/dist/providers/build.d.ts +68 -0
  27. package/vendor/packages/android-emulator-plugin/dist/providers/build.js +131 -0
  28. package/vendor/packages/android-emulator-plugin/dist/providers/config.d.ts +7 -0
  29. package/vendor/packages/android-emulator-plugin/dist/providers/config.js +29 -0
  30. package/vendor/packages/android-emulator-plugin/dist/providers/device.d.ts +20 -0
  31. package/vendor/packages/android-emulator-plugin/dist/providers/device.js +91 -0
  32. package/vendor/packages/android-emulator-plugin/dist/providers/logs.d.ts +15 -0
  33. package/vendor/packages/android-emulator-plugin/dist/providers/logs.js +31 -0
  34. package/vendor/packages/android-emulator-plugin/dist/providers/preflight.d.ts +15 -0
  35. package/vendor/packages/android-emulator-plugin/dist/providers/preflight.js +123 -0
  36. package/vendor/packages/android-emulator-plugin/dist/providers/project-template.d.ts +13 -0
  37. package/vendor/packages/android-emulator-plugin/dist/providers/project-template.js +211 -0
  38. package/vendor/packages/android-emulator-plugin/dist/providers/project.d.ts +33 -0
  39. package/vendor/packages/android-emulator-plugin/dist/providers/project.js +195 -0
  40. package/vendor/packages/android-emulator-plugin/dist/providers/screenshot.d.ts +14 -0
  41. package/vendor/packages/android-emulator-plugin/dist/providers/screenshot.js +73 -0
  42. package/vendor/packages/android-emulator-plugin/dist/providers/sdk.d.ts +14 -0
  43. package/vendor/packages/android-emulator-plugin/dist/providers/sdk.js +185 -0
  44. package/vendor/packages/android-emulator-plugin/dist/providers/ui.d.ts +92 -0
  45. package/vendor/packages/android-emulator-plugin/dist/providers/ui.js +146 -0
  46. package/vendor/packages/android-emulator-plugin/hooks/hooks.json +3 -0
  47. package/vendor/packages/android-emulator-plugin/package.json +35 -0
  48. package/vendor/packages/android-emulator-plugin/skills/android-dev/INSTALL_ENVIRONMENT.md +357 -0
  49. package/vendor/packages/android-emulator-plugin/skills/android-dev/SKILL.md +73 -0
  50. package/vendor/packages/android-emulator-plugin/templates/compose-app/README.md +5 -0
  51. package/vendor/packages/document-skills-plugin/.zcode-plugin/plugin.json +8 -0
  52. package/vendor/packages/document-skills-plugin/package.json +8 -0
  53. package/vendor/packages/document-skills-plugin/skills/docx/LICENSE.txt +13 -0
  54. package/vendor/packages/document-skills-plugin/skills/docx/SKILL.md +201 -0
  55. package/vendor/packages/document-skills-plugin/skills/docx/references/chart-templates.md +386 -0
  56. package/vendor/packages/document-skills-plugin/skills/docx/references/common-rules.md +419 -0
  57. package/vendor/packages/document-skills-plugin/skills/docx/references/decorations.md +537 -0
  58. package/vendor/packages/document-skills-plugin/skills/docx/references/design-system.md +1797 -0
  59. package/vendor/packages/document-skills-plugin/skills/docx/references/docx-js-advanced.md +257 -0
  60. package/vendor/packages/document-skills-plugin/skills/docx/references/docx-js-core.md +332 -0
  61. package/vendor/packages/document-skills-plugin/skills/docx/references/faq.md +323 -0
  62. package/vendor/packages/document-skills-plugin/skills/docx/references/math-formulas.md +276 -0
  63. package/vendor/packages/document-skills-plugin/skills/docx/references/ooxml.md +222 -0
  64. package/vendor/packages/document-skills-plugin/skills/docx/references/toc.md +264 -0
  65. package/vendor/packages/document-skills-plugin/skills/docx/routes/comment.md +88 -0
  66. package/vendor/packages/document-skills-plugin/skills/docx/routes/create.md +207 -0
  67. package/vendor/packages/document-skills-plugin/skills/docx/routes/edit.md +115 -0
  68. package/vendor/packages/document-skills-plugin/skills/docx/routes/format.md +120 -0
  69. package/vendor/packages/document-skills-plugin/skills/docx/routes/read.md +114 -0
  70. package/vendor/packages/document-skills-plugin/skills/docx/scenes/academic.md +783 -0
  71. package/vendor/packages/document-skills-plugin/skills/docx/scenes/contract.md +463 -0
  72. package/vendor/packages/document-skills-plugin/skills/docx/scenes/copywriting.md +139 -0
  73. package/vendor/packages/document-skills-plugin/skills/docx/scenes/exam.md +698 -0
  74. package/vendor/packages/document-skills-plugin/skills/docx/scenes/official-doc.md +411 -0
  75. package/vendor/packages/document-skills-plugin/skills/docx/scenes/report.md +340 -0
  76. package/vendor/packages/document-skills-plugin/skills/docx/scenes/resume.md +534 -0
  77. package/vendor/packages/document-skills-plugin/skills/docx/scripts/__init__.py +1 -0
  78. package/vendor/packages/document-skills-plugin/skills/docx/scripts/add_toc_placeholders.py +749 -0
  79. package/vendor/packages/document-skills-plugin/skills/docx/scripts/document.py +1333 -0
  80. package/vendor/packages/document-skills-plugin/skills/docx/scripts/postcheck.py +807 -0
  81. package/vendor/packages/document-skills-plugin/skills/docx/scripts/templates/comments.xml +3 -0
  82. package/vendor/packages/document-skills-plugin/skills/docx/scripts/templates/commentsExtended.xml +3 -0
  83. package/vendor/packages/document-skills-plugin/skills/docx/scripts/templates/commentsExtensible.xml +3 -0
  84. package/vendor/packages/document-skills-plugin/skills/docx/scripts/templates/commentsIds.xml +3 -0
  85. package/vendor/packages/document-skills-plugin/skills/docx/scripts/templates/people.xml +3 -0
  86. package/vendor/packages/document-skills-plugin/skills/docx/scripts/utilities.py +374 -0
  87. package/vendor/packages/document-skills-plugin/skills/docx/setup.sh +177 -0
  88. package/vendor/packages/document-skills-plugin/skills/pdf/LICENSE.txt +13 -0
  89. package/vendor/packages/document-skills-plugin/skills/pdf/SKILL.md +919 -0
  90. package/vendor/packages/document-skills-plugin/skills/pdf/briefs/academic.md +1058 -0
  91. package/vendor/packages/document-skills-plugin/skills/pdf/briefs/creative.md +770 -0
  92. package/vendor/packages/document-skills-plugin/skills/pdf/briefs/poster.md +702 -0
  93. package/vendor/packages/document-skills-plugin/skills/pdf/briefs/process-advanced.md +284 -0
  94. package/vendor/packages/document-skills-plugin/skills/pdf/briefs/process.md +319 -0
  95. package/vendor/packages/document-skills-plugin/skills/pdf/briefs/report.md +1659 -0
  96. package/vendor/packages/document-skills-plugin/skills/pdf/configs/components.md +153 -0
  97. package/vendor/packages/document-skills-plugin/skills/pdf/configs/fonts.md +93 -0
  98. package/vendor/packages/document-skills-plugin/skills/pdf/configs/visual_framework.md +263 -0
  99. package/vendor/packages/document-skills-plugin/skills/pdf/references/resume-academic.tex +130 -0
  100. package/vendor/packages/document-skills-plugin/skills/pdf/references/resume-altacv.tex +190 -0
  101. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/cover_validate.js +367 -0
  102. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/design_engine.py +2816 -0
  103. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/html2pdf-next.js +754 -0
  104. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/html2poster.js +256 -0
  105. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/pdf.py +2959 -0
  106. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/pdf_qa.py +901 -0
  107. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/poster_validate.py +1337 -0
  108. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/setup.sh +269 -0
  109. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/toc_validate.py +2075 -0
  110. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/charts.md +320 -0
  111. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/cover-backgrounds.md +384 -0
  112. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/cover.md +1442 -0
  113. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/fill-engine.md +527 -0
  114. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/geometry.md +142 -0
  115. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/overflow.md +630 -0
  116. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/pagination.md +367 -0
  117. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/palette.md +217 -0
  118. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/typography.md +20 -0
  119. package/vendor/packages/ios-simulator-plugin/.mcp.json +15 -0
  120. package/vendor/packages/ios-simulator-plugin/.zcode-plugin/plugin.json +34 -0
  121. package/vendor/packages/ios-simulator-plugin/README.md +111 -0
  122. package/vendor/packages/ios-simulator-plugin/commands/ios-dev.md +11 -0
  123. package/vendor/packages/ios-simulator-plugin/dist/lib/path.d.ts +4 -0
  124. package/vendor/packages/ios-simulator-plugin/dist/lib/path.js +18 -0
  125. package/vendor/packages/ios-simulator-plugin/dist/lib/result.d.ts +5 -0
  126. package/vendor/packages/ios-simulator-plugin/dist/lib/result.js +20 -0
  127. package/vendor/packages/ios-simulator-plugin/dist/lib/run.d.ts +17 -0
  128. package/vendor/packages/ios-simulator-plugin/dist/lib/run.js +83 -0
  129. package/vendor/packages/ios-simulator-plugin/dist/mcp/server.d.ts +3 -0
  130. package/vendor/packages/ios-simulator-plugin/dist/mcp/server.js +46833 -0
  131. package/vendor/packages/ios-simulator-plugin/dist/providers/build.d.ts +112 -0
  132. package/vendor/packages/ios-simulator-plugin/dist/providers/build.js +99 -0
  133. package/vendor/packages/ios-simulator-plugin/dist/providers/logs.d.ts +21 -0
  134. package/vendor/packages/ios-simulator-plugin/dist/providers/logs.js +26 -0
  135. package/vendor/packages/ios-simulator-plugin/dist/providers/preflight.d.ts +12 -0
  136. package/vendor/packages/ios-simulator-plugin/dist/providers/preflight.js +62 -0
  137. package/vendor/packages/ios-simulator-plugin/dist/providers/project.d.ts +35 -0
  138. package/vendor/packages/ios-simulator-plugin/dist/providers/project.js +288 -0
  139. package/vendor/packages/ios-simulator-plugin/dist/providers/screenshot.d.ts +22 -0
  140. package/vendor/packages/ios-simulator-plugin/dist/providers/screenshot.js +30 -0
  141. package/vendor/packages/ios-simulator-plugin/dist/providers/sim.d.ts +60 -0
  142. package/vendor/packages/ios-simulator-plugin/dist/providers/sim.js +116 -0
  143. package/vendor/packages/ios-simulator-plugin/dist/providers/ui.d.ts +57 -0
  144. package/vendor/packages/ios-simulator-plugin/dist/providers/ui.js +67 -0
  145. package/vendor/packages/ios-simulator-plugin/hooks/hooks.json +3 -0
  146. package/vendor/packages/ios-simulator-plugin/package.json +35 -0
  147. package/vendor/packages/ios-simulator-plugin/skills/ios-dev/SKILL.md +45 -0
  148. package/vendor/packages/ios-simulator-plugin/templates/swiftui-app/README.md +5 -0
  149. package/vendor/packages/restore-legacy-sessions-plugin/.zcode-plugin/plugin.json +9 -0
  150. package/vendor/packages/restore-legacy-sessions-plugin/README.md +35 -0
  151. package/vendor/packages/restore-legacy-sessions-plugin/commands/restore-legacy-sessions.md +11 -0
  152. package/vendor/packages/restore-legacy-sessions-plugin/package.json +8 -0
  153. package/vendor/packages/restore-legacy-sessions-plugin/skills/restore-legacy-sessions/SKILL.md +92 -0
  154. package/vendor/packages/restore-legacy-sessions-plugin/skills/restore-legacy-sessions/scripts/restore-conversation.mjs +648 -0
  155. package/vendor/packages/restore-legacy-sessions-plugin/skills/restore-legacy-sessions/scripts/scan-legacy-sessions.mjs +422 -0
  156. package/vendor/packages/skill-creator-plugin/.zcode-plugin/plugin.json +8 -0
  157. package/vendor/packages/skill-creator-plugin/package.json +8 -0
  158. package/vendor/packages/skill-creator-plugin/skills/skill-creator/SKILL.md +159 -0
  159. package/vendor/packages/zcode-guide-plugin/.zcode-plugin/plugin.json +8 -0
  160. package/vendor/packages/zcode-guide-plugin/README.md +22 -0
  161. package/vendor/packages/zcode-guide-plugin/package.json +8 -0
  162. package/vendor/packages/zcode-guide-plugin/skills/diagnosing-commands/SKILL.md +66 -0
  163. package/vendor/packages/zcode-guide-plugin/skills/diagnosing-hooks/SKILL.md +66 -0
  164. package/vendor/packages/zcode-guide-plugin/skills/diagnosing-mcp/SKILL.md +97 -0
  165. package/vendor/packages/zcode-guide-plugin/skills/diagnosing-plugins/SKILL.md +59 -0
  166. package/vendor/packages/zcode-guide-plugin/skills/diagnosing-skills/SKILL.md +61 -0
  167. package/vendor/packages/zcode-guide-plugin/skills/zcode-configuration-guide/SKILL.md +99 -0
  168. package/vendor/zcode.cjs +2926 -0
  169. package/zcode-runtime.lock.json +8 -0
@@ -0,0 +1,1333 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Library for working with Word documents: comments, tracked changes, and editing.
4
+
5
+ Usage:
6
+ from skills.docx.scripts.document import Document
7
+
8
+ # Initialize
9
+ doc = Document('workspace/unpacked')
10
+ doc = Document('workspace/unpacked', author="John Doe", initials="JD")
11
+
12
+ # Find nodes
13
+ node = doc["word/document.xml"].get_node(tag="w:del", attrs={"w:id": "1"})
14
+ node = doc["word/document.xml"].get_node(tag="w:p", line_number=10)
15
+
16
+ # Add comments
17
+ doc.add_comment(start=node, end=node, text="Comment text")
18
+ doc.reply_to_comment(parent_comment_id=0, text="Reply text")
19
+
20
+ # Suggest tracked changes
21
+ doc["word/document.xml"].suggest_deletion(node) # Delete content
22
+ doc["word/document.xml"].revert_insertion(ins_node) # Reject insertion
23
+ doc["word/document.xml"].revert_deletion(del_node) # Reject deletion
24
+
25
+ # Save
26
+ doc.save()
27
+ """
28
+
29
+ import html
30
+ import random
31
+ import shutil
32
+ import tempfile
33
+ from datetime import datetime, timezone
34
+ from pathlib import Path
35
+
36
+ import zipfile
37
+
38
+ import defusedxml.minidom
39
+ from defusedxml import minidom
40
+
41
+ from .utilities import XMLEditor
42
+
43
+
44
+ # ---------------------------------------------------------------------------
45
+ # Inline pack utility (replaces former ooxml.scripts.pack dependency)
46
+ # ---------------------------------------------------------------------------
47
+
48
+ def _condense_xml(xml_file):
49
+ """Strip unnecessary whitespace from XML, preserving text content."""
50
+ with open(xml_file, "r", encoding="utf-8") as f:
51
+ dom = defusedxml.minidom.parse(f)
52
+ for element in dom.getElementsByTagName("*"):
53
+ if element.tagName.endswith(":t"):
54
+ continue
55
+ for child in list(element.childNodes):
56
+ if (
57
+ child.nodeType == child.TEXT_NODE
58
+ and child.nodeValue
59
+ and child.nodeValue.strip() == ""
60
+ ) or child.nodeType == child.COMMENT_NODE:
61
+ element.removeChild(child)
62
+ with open(xml_file, "wb") as f:
63
+ f.write(dom.toxml(encoding="UTF-8"))
64
+
65
+
66
+ def _pack_document(input_dir, output_file):
67
+ """Pack an unpacked directory back into a .docx file."""
68
+ input_dir = Path(input_dir)
69
+ output_file = Path(output_file)
70
+ with tempfile.TemporaryDirectory() as temp_dir:
71
+ temp_content_dir = Path(temp_dir) / "content"
72
+ shutil.copytree(input_dir, temp_content_dir)
73
+ for pattern in ["*.xml", "*.rels"]:
74
+ for xml_file in temp_content_dir.rglob(pattern):
75
+ _condense_xml(xml_file)
76
+ output_file.parent.mkdir(parents=True, exist_ok=True)
77
+ with zipfile.ZipFile(output_file, "w", zipfile.ZIP_DEFLATED) as zf:
78
+ for f in temp_content_dir.rglob("*"):
79
+ if f.is_file():
80
+ zf.write(f, f.relative_to(temp_content_dir))
81
+
82
+ # Path to template files
83
+ TEMPLATE_DIR = Path(__file__).parent / "templates"
84
+
85
+
86
+ class DocxXMLEditor(XMLEditor):
87
+ """XMLEditor that automatically applies RSID, author, and date to new elements.
88
+
89
+ Automatically adds attributes to elements that support them when inserting new content:
90
+ - w:rsidR, w:rsidRDefault, w:rsidP (for w:p and w:r elements)
91
+ - w:author and w:date (for w:ins, w:del, w:comment elements)
92
+ - w:id (for w:ins and w:del elements)
93
+
94
+ Attributes:
95
+ dom (defusedxml.minidom.Document): The DOM document for direct manipulation
96
+ """
97
+
98
+ def __init__(
99
+ self, xml_path, rsid: str, author: str = "Z.AI", initials: str = "Z"
100
+ ):
101
+ """Initialize with required RSID and optional author.
102
+
103
+ Args:
104
+ xml_path: Path to XML file to edit
105
+ rsid: RSID to automatically apply to new elements
106
+ author: Author name for tracked changes and comments (default: "Z.AI")
107
+ initials: Author initials (default: "C")
108
+ """
109
+ super().__init__(xml_path)
110
+ self.rsid = rsid
111
+ self.author = author
112
+ self.initials = initials
113
+
114
+ def _get_next_change_id(self):
115
+ """Get the next available change ID by checking all tracked change elements."""
116
+ max_id = -1
117
+ for tag in ("w:ins", "w:del"):
118
+ elements = self.dom.getElementsByTagName(tag)
119
+ for elem in elements:
120
+ change_id = elem.getAttribute("w:id")
121
+ if change_id:
122
+ try:
123
+ max_id = max(max_id, int(change_id))
124
+ except ValueError:
125
+ pass
126
+ return max_id + 1
127
+
128
+ def _ensure_w16du_namespace(self):
129
+ """Ensure w16du namespace is declared on the root element."""
130
+ root = self.dom.documentElement
131
+ if not root.hasAttribute("xmlns:w16du"): # type: ignore
132
+ root.setAttribute( # type: ignore
133
+ "xmlns:w16du",
134
+ "http://schemas.microsoft.com/office/word/2023/wordml/word16du",
135
+ )
136
+
137
+ def _ensure_w16cex_namespace(self):
138
+ """Ensure w16cex namespace is declared on the root element."""
139
+ root = self.dom.documentElement
140
+ if not root.hasAttribute("xmlns:w16cex"): # type: ignore
141
+ root.setAttribute( # type: ignore
142
+ "xmlns:w16cex",
143
+ "http://schemas.microsoft.com/office/word/2018/wordml/cex",
144
+ )
145
+
146
+ def _ensure_w14_namespace(self):
147
+ """Ensure w14 namespace is declared on the root element."""
148
+ root = self.dom.documentElement
149
+ if not root.hasAttribute("xmlns:w14"): # type: ignore
150
+ root.setAttribute( # type: ignore
151
+ "xmlns:w14",
152
+ "http://schemas.microsoft.com/office/word/2010/wordml",
153
+ )
154
+
155
+ def _inject_attributes_to_nodes(self, nodes):
156
+ """Inject RSID, author, and date attributes into DOM nodes where applicable.
157
+
158
+ Adds attributes to elements that support them:
159
+ - w:r: gets w:rsidR (or w:rsidDel if inside w:del)
160
+ - w:p: gets w:rsidR, w:rsidRDefault, w:rsidP, w14:paraId, w14:textId
161
+ - w:t: gets xml:space="preserve" if text has leading/trailing whitespace
162
+ - w:ins, w:del: get w:id, w:author, w:date, w16du:dateUtc
163
+ - w:comment: gets w:author, w:date, w:initials
164
+ - w16cex:commentExtensible: gets w16cex:dateUtc
165
+
166
+ Args:
167
+ nodes: List of DOM nodes to process
168
+ """
169
+ from datetime import datetime, timezone
170
+
171
+ timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
172
+
173
+ def is_inside_deletion(elem):
174
+ """Check if element is inside a w:del element."""
175
+ parent = elem.parentNode
176
+ while parent:
177
+ if parent.nodeType == parent.ELEMENT_NODE and parent.tagName == "w:del":
178
+ return True
179
+ parent = parent.parentNode
180
+ return False
181
+
182
+ def add_rsid_to_p(elem):
183
+ if not elem.hasAttribute("w:rsidR"):
184
+ elem.setAttribute("w:rsidR", self.rsid)
185
+ if not elem.hasAttribute("w:rsidRDefault"):
186
+ elem.setAttribute("w:rsidRDefault", self.rsid)
187
+ if not elem.hasAttribute("w:rsidP"):
188
+ elem.setAttribute("w:rsidP", self.rsid)
189
+ # Add w14:paraId and w14:textId if not present
190
+ if not elem.hasAttribute("w14:paraId"):
191
+ self._ensure_w14_namespace()
192
+ elem.setAttribute("w14:paraId", _generate_hex_id())
193
+ if not elem.hasAttribute("w14:textId"):
194
+ self._ensure_w14_namespace()
195
+ elem.setAttribute("w14:textId", _generate_hex_id())
196
+
197
+ def add_rsid_to_r(elem):
198
+ # Use w:rsidDel for <w:r> inside <w:del>, otherwise w:rsidR
199
+ if is_inside_deletion(elem):
200
+ if not elem.hasAttribute("w:rsidDel"):
201
+ elem.setAttribute("w:rsidDel", self.rsid)
202
+ else:
203
+ if not elem.hasAttribute("w:rsidR"):
204
+ elem.setAttribute("w:rsidR", self.rsid)
205
+
206
+ def add_tracked_change_attrs(elem):
207
+ # Auto-assign w:id if not present
208
+ if not elem.hasAttribute("w:id"):
209
+ elem.setAttribute("w:id", str(self._get_next_change_id()))
210
+ if not elem.hasAttribute("w:author"):
211
+ elem.setAttribute("w:author", self.author)
212
+ if not elem.hasAttribute("w:date"):
213
+ elem.setAttribute("w:date", timestamp)
214
+ # Add w16du:dateUtc for tracked changes (same as w:date since we generate UTC timestamps)
215
+ if elem.tagName in ("w:ins", "w:del") and not elem.hasAttribute(
216
+ "w16du:dateUtc"
217
+ ):
218
+ self._ensure_w16du_namespace()
219
+ elem.setAttribute("w16du:dateUtc", timestamp)
220
+
221
+ def add_comment_attrs(elem):
222
+ if not elem.hasAttribute("w:author"):
223
+ elem.setAttribute("w:author", self.author)
224
+ if not elem.hasAttribute("w:date"):
225
+ elem.setAttribute("w:date", timestamp)
226
+ if not elem.hasAttribute("w:initials"):
227
+ elem.setAttribute("w:initials", self.initials)
228
+
229
+ def add_comment_extensible_date(elem):
230
+ # Add w16cex:dateUtc for comment extensible elements
231
+ if not elem.hasAttribute("w16cex:dateUtc"):
232
+ self._ensure_w16cex_namespace()
233
+ elem.setAttribute("w16cex:dateUtc", timestamp)
234
+
235
+ def add_xml_space_to_t(elem):
236
+ # Add xml:space="preserve" to w:t if text has leading/trailing whitespace
237
+ if (
238
+ elem.firstChild
239
+ and elem.firstChild.nodeType == elem.firstChild.TEXT_NODE
240
+ ):
241
+ text = elem.firstChild.data
242
+ if text and (text[0].isspace() or text[-1].isspace()):
243
+ if not elem.hasAttribute("xml:space"):
244
+ elem.setAttribute("xml:space", "preserve")
245
+
246
+ for node in nodes:
247
+ if node.nodeType != node.ELEMENT_NODE:
248
+ continue
249
+
250
+ # Handle the node itself
251
+ if node.tagName == "w:p":
252
+ add_rsid_to_p(node)
253
+ elif node.tagName == "w:r":
254
+ add_rsid_to_r(node)
255
+ elif node.tagName == "w:t":
256
+ add_xml_space_to_t(node)
257
+ elif node.tagName in ("w:ins", "w:del"):
258
+ add_tracked_change_attrs(node)
259
+ elif node.tagName == "w:comment":
260
+ add_comment_attrs(node)
261
+ elif node.tagName == "w16cex:commentExtensible":
262
+ add_comment_extensible_date(node)
263
+
264
+ # Process descendants (getElementsByTagName doesn't return the element itself)
265
+ for elem in node.getElementsByTagName("w:p"):
266
+ add_rsid_to_p(elem)
267
+ for elem in node.getElementsByTagName("w:r"):
268
+ add_rsid_to_r(elem)
269
+ for elem in node.getElementsByTagName("w:t"):
270
+ add_xml_space_to_t(elem)
271
+ for tag in ("w:ins", "w:del"):
272
+ for elem in node.getElementsByTagName(tag):
273
+ add_tracked_change_attrs(elem)
274
+ for elem in node.getElementsByTagName("w:comment"):
275
+ add_comment_attrs(elem)
276
+ for elem in node.getElementsByTagName("w16cex:commentExtensible"):
277
+ add_comment_extensible_date(elem)
278
+
279
+ def replace_node(self, elem, new_content):
280
+ """Replace node with automatic attribute injection."""
281
+ nodes = super().replace_node(elem, new_content)
282
+ self._inject_attributes_to_nodes(nodes)
283
+ return nodes
284
+
285
+ def insert_after(self, elem, xml_content):
286
+ """Insert after with automatic attribute injection."""
287
+ nodes = super().insert_after(elem, xml_content)
288
+ self._inject_attributes_to_nodes(nodes)
289
+ return nodes
290
+
291
+ def insert_before(self, elem, xml_content):
292
+ """Insert before with automatic attribute injection."""
293
+ nodes = super().insert_before(elem, xml_content)
294
+ self._inject_attributes_to_nodes(nodes)
295
+ return nodes
296
+
297
+ def append_to(self, elem, xml_content):
298
+ """Append to with automatic attribute injection."""
299
+ nodes = super().append_to(elem, xml_content)
300
+ self._inject_attributes_to_nodes(nodes)
301
+ return nodes
302
+
303
+ def revert_insertion(self, elem):
304
+ """Reject an insertion by wrapping its content in a deletion.
305
+
306
+ Wraps all runs inside w:ins in w:del, converting w:t to w:delText.
307
+ Can process a single w:ins element or a container element with multiple w:ins.
308
+
309
+ Args:
310
+ elem: Element to process (w:ins, w:p, w:body, etc.)
311
+
312
+ Returns:
313
+ list: List containing the processed element(s)
314
+
315
+ Raises:
316
+ ValueError: If the element contains no w:ins elements
317
+
318
+ Example:
319
+ # Reject a single insertion
320
+ ins = doc["word/document.xml"].get_node(tag="w:ins", attrs={"w:id": "5"})
321
+ doc["word/document.xml"].revert_insertion(ins)
322
+
323
+ # Reject all insertions in a paragraph
324
+ para = doc["word/document.xml"].get_node(tag="w:p", line_number=42)
325
+ doc["word/document.xml"].revert_insertion(para)
326
+ """
327
+ # Collect insertions
328
+ ins_elements = []
329
+ if elem.tagName == "w:ins":
330
+ ins_elements.append(elem)
331
+ else:
332
+ ins_elements.extend(elem.getElementsByTagName("w:ins"))
333
+
334
+ # Validate that there are insertions to reject
335
+ if not ins_elements:
336
+ raise ValueError(
337
+ f"revert_insertion requires w:ins elements. "
338
+ f"The provided element <{elem.tagName}> contains no insertions. "
339
+ )
340
+
341
+ # Process all insertions - wrap all children in w:del
342
+ for ins_elem in ins_elements:
343
+ runs = list(ins_elem.getElementsByTagName("w:r"))
344
+ if not runs:
345
+ continue
346
+
347
+ # Create deletion wrapper
348
+ del_wrapper = self.dom.createElement("w:del")
349
+
350
+ # Process each run
351
+ for run in runs:
352
+ # Convert w:t → w:delText and w:rsidR → w:rsidDel
353
+ if run.hasAttribute("w:rsidR"):
354
+ run.setAttribute("w:rsidDel", run.getAttribute("w:rsidR"))
355
+ run.removeAttribute("w:rsidR")
356
+ elif not run.hasAttribute("w:rsidDel"):
357
+ run.setAttribute("w:rsidDel", self.rsid)
358
+
359
+ for t_elem in list(run.getElementsByTagName("w:t")):
360
+ del_text = self.dom.createElement("w:delText")
361
+ # Copy ALL child nodes (not just firstChild) to handle entities
362
+ while t_elem.firstChild:
363
+ del_text.appendChild(t_elem.firstChild)
364
+ for i in range(t_elem.attributes.length):
365
+ attr = t_elem.attributes.item(i)
366
+ del_text.setAttribute(attr.name, attr.value)
367
+ t_elem.parentNode.replaceChild(del_text, t_elem)
368
+
369
+ # Move all children from ins to del wrapper
370
+ while ins_elem.firstChild:
371
+ del_wrapper.appendChild(ins_elem.firstChild)
372
+
373
+ # Add del wrapper back to ins
374
+ ins_elem.appendChild(del_wrapper)
375
+
376
+ # Inject attributes to the deletion wrapper
377
+ self._inject_attributes_to_nodes([del_wrapper])
378
+
379
+ return [elem]
380
+
381
+ def revert_deletion(self, elem):
382
+ """Reject a deletion by re-inserting the deleted content.
383
+
384
+ Creates w:ins elements after each w:del, copying deleted content and
385
+ converting w:delText back to w:t.
386
+ Can process a single w:del element or a container element with multiple w:del.
387
+
388
+ Args:
389
+ elem: Element to process (w:del, w:p, w:body, etc.)
390
+
391
+ Returns:
392
+ list: If elem is w:del, returns [elem, new_ins]. Otherwise returns [elem].
393
+
394
+ Raises:
395
+ ValueError: If the element contains no w:del elements
396
+
397
+ Example:
398
+ # Reject a single deletion - returns [w:del, w:ins]
399
+ del_elem = doc["word/document.xml"].get_node(tag="w:del", attrs={"w:id": "3"})
400
+ nodes = doc["word/document.xml"].revert_deletion(del_elem)
401
+
402
+ # Reject all deletions in a paragraph - returns [para]
403
+ para = doc["word/document.xml"].get_node(tag="w:p", line_number=42)
404
+ nodes = doc["word/document.xml"].revert_deletion(para)
405
+ """
406
+ # Collect deletions FIRST - before we modify the DOM
407
+ del_elements = []
408
+ is_single_del = elem.tagName == "w:del"
409
+
410
+ if is_single_del:
411
+ del_elements.append(elem)
412
+ else:
413
+ del_elements.extend(elem.getElementsByTagName("w:del"))
414
+
415
+ # Validate that there are deletions to reject
416
+ if not del_elements:
417
+ raise ValueError(
418
+ f"revert_deletion requires w:del elements. "
419
+ f"The provided element <{elem.tagName}> contains no deletions. "
420
+ )
421
+
422
+ # Track created insertion (only relevant if elem is a single w:del)
423
+ created_insertion = None
424
+
425
+ # Process all deletions - create insertions that copy the deleted content
426
+ for del_elem in del_elements:
427
+ # Clone the deleted runs and convert them to insertions
428
+ runs = list(del_elem.getElementsByTagName("w:r"))
429
+ if not runs:
430
+ continue
431
+
432
+ # Create insertion wrapper
433
+ ins_elem = self.dom.createElement("w:ins")
434
+
435
+ for run in runs:
436
+ # Clone the run
437
+ new_run = run.cloneNode(True)
438
+
439
+ # Convert w:delText → w:t
440
+ for del_text in list(new_run.getElementsByTagName("w:delText")):
441
+ t_elem = self.dom.createElement("w:t")
442
+ # Copy ALL child nodes (not just firstChild) to handle entities
443
+ while del_text.firstChild:
444
+ t_elem.appendChild(del_text.firstChild)
445
+ for i in range(del_text.attributes.length):
446
+ attr = del_text.attributes.item(i)
447
+ t_elem.setAttribute(attr.name, attr.value)
448
+ del_text.parentNode.replaceChild(t_elem, del_text)
449
+
450
+ # Update run attributes: w:rsidDel → w:rsidR
451
+ if new_run.hasAttribute("w:rsidDel"):
452
+ new_run.setAttribute("w:rsidR", new_run.getAttribute("w:rsidDel"))
453
+ new_run.removeAttribute("w:rsidDel")
454
+ elif not new_run.hasAttribute("w:rsidR"):
455
+ new_run.setAttribute("w:rsidR", self.rsid)
456
+
457
+ ins_elem.appendChild(new_run)
458
+
459
+ # Insert the new insertion after the deletion
460
+ nodes = self.insert_after(del_elem, ins_elem.toxml())
461
+
462
+ # If processing a single w:del, track the created insertion
463
+ if is_single_del and nodes:
464
+ created_insertion = nodes[0]
465
+
466
+ # Return based on input type
467
+ if is_single_del and created_insertion:
468
+ return [elem, created_insertion]
469
+ else:
470
+ return [elem]
471
+
472
+ @staticmethod
473
+ def suggest_paragraph(xml_content: str) -> str:
474
+ """Transform paragraph XML to add tracked change wrapping for insertion.
475
+
476
+ Wraps runs in <w:ins> and adds <w:ins/> to w:rPr in w:pPr for numbered lists.
477
+
478
+ Args:
479
+ xml_content: XML string containing a <w:p> element
480
+
481
+ Returns:
482
+ str: Transformed XML with tracked change wrapping
483
+ """
484
+ wrapper = f'<root xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">{xml_content}</root>'
485
+ doc = minidom.parseString(wrapper)
486
+ para = doc.getElementsByTagName("w:p")[0]
487
+
488
+ # Ensure w:pPr exists
489
+ pPr_list = para.getElementsByTagName("w:pPr")
490
+ if not pPr_list:
491
+ pPr = doc.createElement("w:pPr")
492
+ para.insertBefore(
493
+ pPr, para.firstChild
494
+ ) if para.firstChild else para.appendChild(pPr)
495
+ else:
496
+ pPr = pPr_list[0]
497
+
498
+ # Ensure w:rPr exists in w:pPr
499
+ rPr_list = pPr.getElementsByTagName("w:rPr")
500
+ if not rPr_list:
501
+ rPr = doc.createElement("w:rPr")
502
+ pPr.appendChild(rPr)
503
+ else:
504
+ rPr = rPr_list[0]
505
+
506
+ # Add <w:ins/> to w:rPr
507
+ ins_marker = doc.createElement("w:ins")
508
+ rPr.insertBefore(
509
+ ins_marker, rPr.firstChild
510
+ ) if rPr.firstChild else rPr.appendChild(ins_marker)
511
+
512
+ # Wrap all non-pPr children in <w:ins>
513
+ ins_wrapper = doc.createElement("w:ins")
514
+ for child in [c for c in para.childNodes if c.nodeName != "w:pPr"]:
515
+ para.removeChild(child)
516
+ ins_wrapper.appendChild(child)
517
+ para.appendChild(ins_wrapper)
518
+
519
+ return para.toxml()
520
+
521
+ def suggest_deletion(self, elem):
522
+ """Mark a w:r or w:p element as deleted with tracked changes (in-place DOM manipulation).
523
+
524
+ For w:r: wraps in <w:del>, converts <w:t> to <w:delText>, preserves w:rPr
525
+ For w:p (regular): wraps content in <w:del>, converts <w:t> to <w:delText>
526
+ For w:p (numbered list): adds <w:del/> to w:rPr in w:pPr, wraps content in <w:del>
527
+
528
+ Args:
529
+ elem: A w:r or w:p DOM element without existing tracked changes
530
+
531
+ Returns:
532
+ Element: The modified element
533
+
534
+ Raises:
535
+ ValueError: If element has existing tracked changes or invalid structure
536
+ """
537
+ if elem.nodeName == "w:r":
538
+ # Check for existing w:delText
539
+ if elem.getElementsByTagName("w:delText"):
540
+ raise ValueError("w:r element already contains w:delText")
541
+
542
+ # Convert w:t → w:delText
543
+ for t_elem in list(elem.getElementsByTagName("w:t")):
544
+ del_text = self.dom.createElement("w:delText")
545
+ # Copy ALL child nodes (not just firstChild) to handle entities
546
+ while t_elem.firstChild:
547
+ del_text.appendChild(t_elem.firstChild)
548
+ # Preserve attributes like xml:space
549
+ for i in range(t_elem.attributes.length):
550
+ attr = t_elem.attributes.item(i)
551
+ del_text.setAttribute(attr.name, attr.value)
552
+ t_elem.parentNode.replaceChild(del_text, t_elem)
553
+
554
+ # Update run attributes: w:rsidR → w:rsidDel
555
+ if elem.hasAttribute("w:rsidR"):
556
+ elem.setAttribute("w:rsidDel", elem.getAttribute("w:rsidR"))
557
+ elem.removeAttribute("w:rsidR")
558
+ elif not elem.hasAttribute("w:rsidDel"):
559
+ elem.setAttribute("w:rsidDel", self.rsid)
560
+
561
+ # Wrap in w:del
562
+ del_wrapper = self.dom.createElement("w:del")
563
+ parent = elem.parentNode
564
+ parent.insertBefore(del_wrapper, elem)
565
+ parent.removeChild(elem)
566
+ del_wrapper.appendChild(elem)
567
+
568
+ # Inject attributes to the deletion wrapper
569
+ self._inject_attributes_to_nodes([del_wrapper])
570
+
571
+ return del_wrapper
572
+
573
+ elif elem.nodeName == "w:p":
574
+ # Check for existing tracked changes
575
+ if elem.getElementsByTagName("w:ins") or elem.getElementsByTagName("w:del"):
576
+ raise ValueError("w:p element already contains tracked changes")
577
+
578
+ # Check if it's a numbered list item
579
+ pPr_list = elem.getElementsByTagName("w:pPr")
580
+ is_numbered = pPr_list and pPr_list[0].getElementsByTagName("w:numPr")
581
+
582
+ if is_numbered:
583
+ # Add <w:del/> to w:rPr in w:pPr
584
+ pPr = pPr_list[0]
585
+ rPr_list = pPr.getElementsByTagName("w:rPr")
586
+
587
+ if not rPr_list:
588
+ rPr = self.dom.createElement("w:rPr")
589
+ pPr.appendChild(rPr)
590
+ else:
591
+ rPr = rPr_list[0]
592
+
593
+ # Add <w:del/> marker
594
+ del_marker = self.dom.createElement("w:del")
595
+ rPr.insertBefore(
596
+ del_marker, rPr.firstChild
597
+ ) if rPr.firstChild else rPr.appendChild(del_marker)
598
+
599
+ # Convert w:t → w:delText in all runs
600
+ for t_elem in list(elem.getElementsByTagName("w:t")):
601
+ del_text = self.dom.createElement("w:delText")
602
+ # Copy ALL child nodes (not just firstChild) to handle entities
603
+ while t_elem.firstChild:
604
+ del_text.appendChild(t_elem.firstChild)
605
+ # Preserve attributes like xml:space
606
+ for i in range(t_elem.attributes.length):
607
+ attr = t_elem.attributes.item(i)
608
+ del_text.setAttribute(attr.name, attr.value)
609
+ t_elem.parentNode.replaceChild(del_text, t_elem)
610
+
611
+ # Update run attributes: w:rsidR → w:rsidDel
612
+ for run in elem.getElementsByTagName("w:r"):
613
+ if run.hasAttribute("w:rsidR"):
614
+ run.setAttribute("w:rsidDel", run.getAttribute("w:rsidR"))
615
+ run.removeAttribute("w:rsidR")
616
+ elif not run.hasAttribute("w:rsidDel"):
617
+ run.setAttribute("w:rsidDel", self.rsid)
618
+
619
+ # Wrap all non-pPr children in <w:del>
620
+ del_wrapper = self.dom.createElement("w:del")
621
+ for child in [c for c in elem.childNodes if c.nodeName != "w:pPr"]:
622
+ elem.removeChild(child)
623
+ del_wrapper.appendChild(child)
624
+ elem.appendChild(del_wrapper)
625
+
626
+ # Inject attributes to the deletion wrapper
627
+ self._inject_attributes_to_nodes([del_wrapper])
628
+
629
+ return elem
630
+
631
+ else:
632
+ raise ValueError(f"Element must be w:r or w:p, got {elem.nodeName}")
633
+
634
+
635
+ def _generate_hex_id() -> str:
636
+ """Generate random 8-character hex ID for para/durable IDs.
637
+
638
+ Values are constrained to be less than 0x7FFFFFFF per OOXML spec:
639
+ - paraId must be < 0x80000000
640
+ - durableId must be < 0x7FFFFFFF
641
+ We use the stricter constraint (0x7FFFFFFF) for both.
642
+ """
643
+ return f"{random.randint(1, 0x7FFFFFFE):08X}"
644
+
645
+
646
+ def _generate_rsid() -> str:
647
+ """Generate random 8-character hex RSID."""
648
+ return "".join(random.choices("0123456789ABCDEF", k=8))
649
+
650
+
651
+ class Document:
652
+ """Manages comments in unpacked Word documents."""
653
+
654
+ def __init__(
655
+ self,
656
+ unpacked_dir,
657
+ rsid=None,
658
+ track_revisions=False,
659
+ author="Z.AI",
660
+ initials="C",
661
+ ):
662
+ """
663
+ Initialize with path to unpacked Word document directory.
664
+ Automatically sets up comment infrastructure (people.xml, RSIDs).
665
+
666
+ Args:
667
+ unpacked_dir: Path to unpacked DOCX directory (must contain word/ subdirectory)
668
+ rsid: Optional RSID to use for all comment elements. If not provided, one will be generated.
669
+ track_revisions: If True, enables track revisions in settings.xml (default: False)
670
+ author: Default author name for comments (default: "Z.AI")
671
+ initials: Default author initials for comments (default: "C")
672
+ """
673
+ self.original_path = Path(unpacked_dir)
674
+
675
+ if not self.original_path.exists() or not self.original_path.is_dir():
676
+ raise ValueError(f"Directory not found: {unpacked_dir}")
677
+
678
+ # Create temporary directory with subdirectories for unpacked content and baseline
679
+ self.temp_dir = tempfile.mkdtemp(prefix="docx_")
680
+ self.unpacked_path = Path(self.temp_dir) / "unpacked"
681
+ shutil.copytree(self.original_path, self.unpacked_path)
682
+
683
+ # Pack original directory into temporary .docx for validation baseline (outside unpacked dir)
684
+ self.original_docx = Path(self.temp_dir) / "original.docx"
685
+ _pack_document(self.original_path, self.original_docx)
686
+
687
+ self.word_path = self.unpacked_path / "word"
688
+
689
+ # Generate RSID if not provided
690
+ self.rsid = rsid if rsid else _generate_rsid()
691
+ print(f"Using RSID: {self.rsid}")
692
+
693
+ # Set default author and initials
694
+ self.author = author
695
+ self.initials = initials
696
+
697
+ # Cache for lazy-loaded editors
698
+ self._editors = {}
699
+
700
+ # Comment file paths
701
+ self.comments_path = self.word_path / "comments.xml"
702
+ self.comments_extended_path = self.word_path / "commentsExtended.xml"
703
+ self.comments_ids_path = self.word_path / "commentsIds.xml"
704
+ self.comments_extensible_path = self.word_path / "commentsExtensible.xml"
705
+
706
+ # Load existing comments and determine next ID (before setup modifies files)
707
+ self.existing_comments = self._load_existing_comments()
708
+ self.next_comment_id = self._get_next_comment_id()
709
+
710
+ # Convenient access to document.xml editor (semi-private)
711
+ self._document = self["word/document.xml"]
712
+
713
+ # Setup tracked changes infrastructure
714
+ self._setup_tracking(track_revisions=track_revisions)
715
+
716
+ # Add author to people.xml
717
+ self._add_author_to_people(author)
718
+
719
+ def __getitem__(self, xml_path: str) -> DocxXMLEditor:
720
+ """
721
+ Get or create a DocxXMLEditor for the specified XML file.
722
+
723
+ Enables lazy-loaded editors with bracket notation:
724
+ node = doc["word/document.xml"].get_node(tag="w:p", line_number=42)
725
+
726
+ Args:
727
+ xml_path: Relative path to XML file (e.g., "word/document.xml", "word/comments.xml")
728
+
729
+ Returns:
730
+ DocxXMLEditor instance for the specified file
731
+
732
+ Raises:
733
+ ValueError: If the file does not exist
734
+
735
+ Example:
736
+ # Get node from document.xml
737
+ node = doc["word/document.xml"].get_node(tag="w:del", attrs={"w:id": "1"})
738
+
739
+ # Get node from comments.xml
740
+ comment = doc["word/comments.xml"].get_node(tag="w:comment", attrs={"w:id": "0"})
741
+ """
742
+ if xml_path not in self._editors:
743
+ file_path = self.unpacked_path / xml_path
744
+ if not file_path.exists():
745
+ raise ValueError(f"XML file not found: {xml_path}")
746
+ # Use DocxXMLEditor with RSID, author, and initials for all editors
747
+ self._editors[xml_path] = DocxXMLEditor(
748
+ file_path, rsid=self.rsid, author=self.author, initials=self.initials
749
+ )
750
+ return self._editors[xml_path]
751
+
752
+ def add_comment(self, start, end, text: str) -> int:
753
+ """
754
+ Add a comment spanning from one element to another.
755
+
756
+ Args:
757
+ start: DOM element for the starting point
758
+ end: DOM element for the ending point
759
+ text: Comment content
760
+
761
+ Returns:
762
+ The comment ID that was created
763
+
764
+ Example:
765
+ start_node = cm.get_document_node(tag="w:del", id="1")
766
+ end_node = cm.get_document_node(tag="w:ins", id="2")
767
+ cm.add_comment(start=start_node, end=end_node, text="Explanation")
768
+ """
769
+ comment_id = self.next_comment_id
770
+ para_id = _generate_hex_id()
771
+ durable_id = _generate_hex_id()
772
+ timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
773
+
774
+ # Add comment ranges to document.xml immediately
775
+ self._document.insert_before(start, self._comment_range_start_xml(comment_id))
776
+
777
+ # If end node is a paragraph, append comment markup inside it
778
+ # Otherwise insert after it (for run-level anchors)
779
+ if end.tagName == "w:p":
780
+ self._document.append_to(end, self._comment_range_end_xml(comment_id))
781
+ else:
782
+ self._document.insert_after(end, self._comment_range_end_xml(comment_id))
783
+
784
+ # Add to comments.xml immediately
785
+ self._add_to_comments_xml(
786
+ comment_id, para_id, text, self.author, self.initials, timestamp
787
+ )
788
+
789
+ # Add to commentsExtended.xml immediately
790
+ self._add_to_comments_extended_xml(para_id, parent_para_id=None)
791
+
792
+ # Add to commentsIds.xml immediately
793
+ self._add_to_comments_ids_xml(para_id, durable_id)
794
+
795
+ # Add to commentsExtensible.xml immediately
796
+ self._add_to_comments_extensible_xml(durable_id)
797
+
798
+ # Update existing_comments so replies work
799
+ self.existing_comments[comment_id] = {"para_id": para_id}
800
+
801
+ self.next_comment_id += 1
802
+ return comment_id
803
+
804
+ def reply_to_comment(
805
+ self,
806
+ parent_comment_id: int,
807
+ text: str,
808
+ ) -> int:
809
+ """
810
+ Add a reply to an existing comment.
811
+
812
+ Args:
813
+ parent_comment_id: The w:id of the parent comment to reply to
814
+ text: Reply text
815
+
816
+ Returns:
817
+ The comment ID that was created for the reply
818
+
819
+ Example:
820
+ cm.reply_to_comment(parent_comment_id=0, text="I agree with this change")
821
+ """
822
+ if parent_comment_id not in self.existing_comments:
823
+ raise ValueError(f"Parent comment with id={parent_comment_id} not found")
824
+
825
+ parent_info = self.existing_comments[parent_comment_id]
826
+ comment_id = self.next_comment_id
827
+ para_id = _generate_hex_id()
828
+ durable_id = _generate_hex_id()
829
+ timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
830
+
831
+ # Add comment ranges to document.xml immediately
832
+ parent_start_elem = self._document.get_node(
833
+ tag="w:commentRangeStart", attrs={"w:id": str(parent_comment_id)}
834
+ )
835
+ parent_ref_elem = self._document.get_node(
836
+ tag="w:commentReference", attrs={"w:id": str(parent_comment_id)}
837
+ )
838
+
839
+ self._document.insert_after(
840
+ parent_start_elem, self._comment_range_start_xml(comment_id)
841
+ )
842
+ parent_ref_run = parent_ref_elem.parentNode
843
+ self._document.insert_after(
844
+ parent_ref_run, f'<w:commentRangeEnd w:id="{comment_id}"/>'
845
+ )
846
+ self._document.insert_after(
847
+ parent_ref_run, self._comment_ref_run_xml(comment_id)
848
+ )
849
+
850
+ # Add to comments.xml immediately
851
+ self._add_to_comments_xml(
852
+ comment_id, para_id, text, self.author, self.initials, timestamp
853
+ )
854
+
855
+ # Add to commentsExtended.xml immediately (with parent)
856
+ self._add_to_comments_extended_xml(
857
+ para_id, parent_para_id=parent_info["para_id"]
858
+ )
859
+
860
+ # Add to commentsIds.xml immediately
861
+ self._add_to_comments_ids_xml(para_id, durable_id)
862
+
863
+ # Add to commentsExtensible.xml immediately
864
+ self._add_to_comments_extensible_xml(durable_id)
865
+
866
+ # Update existing_comments so replies work
867
+ self.existing_comments[comment_id] = {"para_id": para_id}
868
+
869
+ self.next_comment_id += 1
870
+ return comment_id
871
+
872
+ def __del__(self):
873
+ """Clean up temporary directory on deletion."""
874
+ if hasattr(self, "temp_dir") and Path(self.temp_dir).exists():
875
+ shutil.rmtree(self.temp_dir)
876
+
877
+ def validate(self) -> None:
878
+ """
879
+ Validate the document (lightweight check).
880
+
881
+ Currently performs basic structural checks. XSD schema validation and
882
+ redlining validation have been removed. Use save(validate=False) to
883
+ skip validation entirely.
884
+ """
885
+ # Basic structural check: ensure word/document.xml exists
886
+ doc_xml = self.unpacked_path / "word" / "document.xml"
887
+ if not doc_xml.exists():
888
+ raise ValueError("Validation failed: word/document.xml not found")
889
+
890
+ def save(self, destination=None, validate=True) -> None:
891
+ """
892
+ Save all modified XML files to disk and copy to destination directory.
893
+
894
+ This persists all changes made via add_comment() and reply_to_comment().
895
+
896
+ Args:
897
+ destination: Optional path to save to. If None, saves back to original directory.
898
+ validate: If True, validates document before saving (default: True).
899
+ """
900
+ # Only ensure comment relationships and content types if comment files exist
901
+ if self.comments_path.exists():
902
+ self._ensure_comment_relationships()
903
+ self._ensure_comment_content_types()
904
+
905
+ # Save all modified XML files in temp directory
906
+ for editor in self._editors.values():
907
+ editor.save()
908
+
909
+ # Validate by default
910
+ if validate:
911
+ self.validate()
912
+
913
+ # Copy contents from temp directory to destination (or original directory)
914
+ target_path = Path(destination) if destination else self.original_path
915
+ shutil.copytree(self.unpacked_path, target_path, dirs_exist_ok=True)
916
+
917
+ # ==================== Private: Initialization ====================
918
+
919
+ def _get_next_comment_id(self):
920
+ """Get the next available comment ID."""
921
+ if not self.comments_path.exists():
922
+ return 0
923
+
924
+ editor = self["word/comments.xml"]
925
+ max_id = -1
926
+ for comment_elem in editor.dom.getElementsByTagName("w:comment"):
927
+ comment_id = comment_elem.getAttribute("w:id")
928
+ if comment_id:
929
+ try:
930
+ max_id = max(max_id, int(comment_id))
931
+ except ValueError:
932
+ pass
933
+ return max_id + 1
934
+
935
+ def _load_existing_comments(self):
936
+ """Load existing comments from files to enable replies."""
937
+ if not self.comments_path.exists():
938
+ return {}
939
+
940
+ editor = self["word/comments.xml"]
941
+ existing = {}
942
+
943
+ for comment_elem in editor.dom.getElementsByTagName("w:comment"):
944
+ comment_id = comment_elem.getAttribute("w:id")
945
+ if not comment_id:
946
+ continue
947
+
948
+ # Find para_id from the w:p element within the comment
949
+ para_id = None
950
+ for p_elem in comment_elem.getElementsByTagName("w:p"):
951
+ para_id = p_elem.getAttribute("w14:paraId")
952
+ if para_id:
953
+ break
954
+
955
+ if not para_id:
956
+ continue
957
+
958
+ existing[int(comment_id)] = {"para_id": para_id}
959
+
960
+ return existing
961
+
962
+ # ==================== Private: Setup Methods ====================
963
+
964
+ def _setup_tracking(self, track_revisions=False):
965
+ """Set up comment infrastructure in unpacked directory.
966
+
967
+ Args:
968
+ track_revisions: If True, enables track revisions in settings.xml
969
+ """
970
+ # Create or update word/people.xml
971
+ people_file = self.word_path / "people.xml"
972
+ self._update_people_xml(people_file)
973
+
974
+ # Update XML files
975
+ self._add_content_type_for_people(self.unpacked_path / "[Content_Types].xml")
976
+ self._add_relationship_for_people(
977
+ self.word_path / "_rels" / "document.xml.rels"
978
+ )
979
+
980
+ # Always add RSID to settings.xml, optionally enable trackRevisions
981
+ self._update_settings(
982
+ self.word_path / "settings.xml", track_revisions=track_revisions
983
+ )
984
+
985
+ def _update_people_xml(self, path):
986
+ """Create people.xml if it doesn't exist."""
987
+ if not path.exists():
988
+ # Copy from template
989
+ shutil.copy(TEMPLATE_DIR / "people.xml", path)
990
+
991
+ def _add_content_type_for_people(self, path):
992
+ """Add people.xml content type to [Content_Types].xml if not already present."""
993
+ editor = self["[Content_Types].xml"]
994
+
995
+ if self._has_override(editor, "/word/people.xml"):
996
+ return
997
+
998
+ # Add Override element
999
+ root = editor.dom.documentElement
1000
+ override_xml = '<Override PartName="/word/people.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.people+xml"/>'
1001
+ editor.append_to(root, override_xml)
1002
+
1003
+ def _add_relationship_for_people(self, path):
1004
+ """Add people.xml relationship to document.xml.rels if not already present."""
1005
+ editor = self["word/_rels/document.xml.rels"]
1006
+
1007
+ if self._has_relationship(editor, "people.xml"):
1008
+ return
1009
+
1010
+ root = editor.dom.documentElement
1011
+ root_tag = root.tagName # type: ignore
1012
+ prefix = root_tag.split(":")[0] + ":" if ":" in root_tag else ""
1013
+ next_rid = editor.get_next_rid()
1014
+
1015
+ # Create the relationship entry
1016
+ rel_xml = f'<{prefix}Relationship Id="{next_rid}" Type="http://schemas.microsoft.com/office/2011/relationships/people" Target="people.xml"/>'
1017
+ editor.append_to(root, rel_xml)
1018
+
1019
+ def _update_settings(self, path, track_revisions=False, update_fields=True):
1020
+ """Add RSID and optionally enable track revisions and update fields in settings.xml.
1021
+
1022
+ Args:
1023
+ path: Path to settings.xml
1024
+ track_revisions: If True, adds trackRevisions element
1025
+ update_fields: If True, adds updateFields element to auto-update fields on open
1026
+
1027
+ Places elements per OOXML schema order:
1028
+ - trackRevisions: early (before defaultTabStop)
1029
+ - updateFields: early (before defaultTabStop)
1030
+ - rsids: late (after compat)
1031
+ """
1032
+ editor = self["word/settings.xml"]
1033
+ root = editor.get_node(tag="w:settings")
1034
+ prefix = root.tagName.split(":")[0] if ":" in root.tagName else "w"
1035
+
1036
+ # Conditionally add trackRevisions if requested
1037
+ if track_revisions:
1038
+ track_revisions_exists = any(
1039
+ elem.tagName == f"{prefix}:trackRevisions"
1040
+ for elem in editor.dom.getElementsByTagName(f"{prefix}:trackRevisions")
1041
+ )
1042
+
1043
+ if not track_revisions_exists:
1044
+ track_rev_xml = f"<{prefix}:trackRevisions/>"
1045
+ # Try to insert before documentProtection, defaultTabStop, or at start
1046
+ inserted = False
1047
+ for tag in [f"{prefix}:documentProtection", f"{prefix}:defaultTabStop"]:
1048
+ elements = editor.dom.getElementsByTagName(tag)
1049
+ if elements:
1050
+ editor.insert_before(elements[0], track_rev_xml)
1051
+ inserted = True
1052
+ break
1053
+ if not inserted:
1054
+ # Insert as first child of settings
1055
+ if root.firstChild:
1056
+ editor.insert_before(root.firstChild, track_rev_xml)
1057
+ else:
1058
+ editor.append_to(root, track_rev_xml)
1059
+
1060
+ # Conditionally add updateFields if requested
1061
+ if update_fields:
1062
+ update_fields_exists = any(
1063
+ elem.tagName == f"{prefix}:updateFields"
1064
+ for elem in editor.dom.getElementsByTagName(f"{prefix}:updateFields")
1065
+ )
1066
+
1067
+ if not update_fields_exists:
1068
+ update_fields_xml = f'<{prefix}:updateFields {prefix}:val="true"/>'
1069
+ # Try to insert before defaultTabStop, hyphenationZone, or at start
1070
+ inserted = False
1071
+ for tag in [f"{prefix}:defaultTabStop", f"{prefix}:hyphenationZone"]:
1072
+ elements = editor.dom.getElementsByTagName(tag)
1073
+ if elements:
1074
+ editor.insert_before(elements[0], update_fields_xml)
1075
+ inserted = True
1076
+ break
1077
+ if not inserted:
1078
+ # Insert as first child of settings
1079
+ if root.firstChild:
1080
+ editor.insert_before(root.firstChild, update_fields_xml)
1081
+ else:
1082
+ editor.append_to(root, update_fields_xml)
1083
+
1084
+ # Always check if rsids section exists
1085
+ rsids_elements = editor.dom.getElementsByTagName(f"{prefix}:rsids")
1086
+
1087
+ if not rsids_elements:
1088
+ # Add new rsids section
1089
+ rsids_xml = f'''<{prefix}:rsids>
1090
+ <{prefix}:rsidRoot {prefix}:val="{self.rsid}"/>
1091
+ <{prefix}:rsid {prefix}:val="{self.rsid}"/>
1092
+ </{prefix}:rsids>'''
1093
+
1094
+ # Try to insert after compat, before clrSchemeMapping, or before closing tag
1095
+ inserted = False
1096
+ compat_elements = editor.dom.getElementsByTagName(f"{prefix}:compat")
1097
+ if compat_elements:
1098
+ editor.insert_after(compat_elements[0], rsids_xml)
1099
+ inserted = True
1100
+
1101
+ if not inserted:
1102
+ clr_elements = editor.dom.getElementsByTagName(
1103
+ f"{prefix}:clrSchemeMapping"
1104
+ )
1105
+ if clr_elements:
1106
+ editor.insert_before(clr_elements[0], rsids_xml)
1107
+ inserted = True
1108
+
1109
+ if not inserted:
1110
+ editor.append_to(root, rsids_xml)
1111
+ else:
1112
+ # Check if this rsid already exists
1113
+ rsids_elem = rsids_elements[0]
1114
+ rsid_exists = any(
1115
+ elem.getAttribute(f"{prefix}:val") == self.rsid
1116
+ for elem in rsids_elem.getElementsByTagName(f"{prefix}:rsid")
1117
+ )
1118
+
1119
+ if not rsid_exists:
1120
+ rsid_xml = f'<{prefix}:rsid {prefix}:val="{self.rsid}"/>'
1121
+ editor.append_to(rsids_elem, rsid_xml)
1122
+
1123
+ # ==================== Private: XML File Creation ====================
1124
+
1125
+ def _add_to_comments_xml(
1126
+ self, comment_id, para_id, text, author, initials, timestamp
1127
+ ):
1128
+ """Add a single comment to comments.xml."""
1129
+ if not self.comments_path.exists():
1130
+ shutil.copy(TEMPLATE_DIR / "comments.xml", self.comments_path)
1131
+
1132
+ editor = self["word/comments.xml"]
1133
+ root = editor.get_node(tag="w:comments")
1134
+
1135
+ escaped_text = (
1136
+ text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
1137
+ )
1138
+ # Note: w:rsidR, w:rsidRDefault, w:rsidP on w:p, w:rsidR on w:r,
1139
+ # and w:author, w:date, w:initials on w:comment are automatically added by DocxXMLEditor
1140
+ comment_xml = f'''<w:comment w:id="{comment_id}">
1141
+ <w:p w14:paraId="{para_id}" w14:textId="77777777">
1142
+ <w:r><w:rPr><w:rStyle w:val="CommentReference"/></w:rPr><w:annotationRef/></w:r>
1143
+ <w:r><w:rPr><w:color w:val="000000"/><w:sz w:val="20"/><w:szCs w:val="20"/></w:rPr><w:t>{escaped_text}</w:t></w:r>
1144
+ </w:p>
1145
+ </w:comment>'''
1146
+ editor.append_to(root, comment_xml)
1147
+
1148
+ def _add_to_comments_extended_xml(self, para_id, parent_para_id):
1149
+ """Add a single comment to commentsExtended.xml."""
1150
+ if not self.comments_extended_path.exists():
1151
+ shutil.copy(
1152
+ TEMPLATE_DIR / "commentsExtended.xml", self.comments_extended_path
1153
+ )
1154
+
1155
+ editor = self["word/commentsExtended.xml"]
1156
+ root = editor.get_node(tag="w15:commentsEx")
1157
+
1158
+ if parent_para_id:
1159
+ xml = f'<w15:commentEx w15:paraId="{para_id}" w15:paraIdParent="{parent_para_id}" w15:done="0"/>'
1160
+ else:
1161
+ xml = f'<w15:commentEx w15:paraId="{para_id}" w15:done="0"/>'
1162
+ editor.append_to(root, xml)
1163
+
1164
+ def _add_to_comments_ids_xml(self, para_id, durable_id):
1165
+ """Add a single comment to commentsIds.xml."""
1166
+ if not self.comments_ids_path.exists():
1167
+ shutil.copy(TEMPLATE_DIR / "commentsIds.xml", self.comments_ids_path)
1168
+
1169
+ editor = self["word/commentsIds.xml"]
1170
+ root = editor.get_node(tag="w16cid:commentsIds")
1171
+
1172
+ xml = f'<w16cid:commentId w16cid:paraId="{para_id}" w16cid:durableId="{durable_id}"/>'
1173
+ editor.append_to(root, xml)
1174
+
1175
+ def _add_to_comments_extensible_xml(self, durable_id):
1176
+ """Add a single comment to commentsExtensible.xml."""
1177
+ if not self.comments_extensible_path.exists():
1178
+ shutil.copy(
1179
+ TEMPLATE_DIR / "commentsExtensible.xml", self.comments_extensible_path
1180
+ )
1181
+
1182
+ editor = self["word/commentsExtensible.xml"]
1183
+ root = editor.get_node(tag="w16cex:commentsExtensible")
1184
+
1185
+ xml = f'<w16cex:commentExtensible w16cex:durableId="{durable_id}"/>'
1186
+ editor.append_to(root, xml)
1187
+
1188
+ # ==================== Private: XML Fragments ====================
1189
+
1190
+ def _comment_range_start_xml(self, comment_id):
1191
+ """Generate XML for comment range start."""
1192
+ return f'<w:commentRangeStart w:id="{comment_id}"/>'
1193
+
1194
+ def _comment_range_end_xml(self, comment_id):
1195
+ """Generate XML for comment range end with reference run.
1196
+
1197
+ Note: w:rsidR is automatically added by DocxXMLEditor.
1198
+ """
1199
+ return f'''<w:commentRangeEnd w:id="{comment_id}"/>
1200
+ <w:r>
1201
+ <w:rPr><w:rStyle w:val="CommentReference"/></w:rPr>
1202
+ <w:commentReference w:id="{comment_id}"/>
1203
+ </w:r>'''
1204
+
1205
+ def _comment_ref_run_xml(self, comment_id):
1206
+ """Generate XML for comment reference run.
1207
+
1208
+ Note: w:rsidR is automatically added by DocxXMLEditor.
1209
+ """
1210
+ return f'''<w:r>
1211
+ <w:rPr><w:rStyle w:val="CommentReference"/></w:rPr>
1212
+ <w:commentReference w:id="{comment_id}"/>
1213
+ </w:r>'''
1214
+
1215
+ # ==================== Private: Metadata Updates ====================
1216
+
1217
+ def _has_relationship(self, editor, target):
1218
+ """Check if a relationship with given target exists."""
1219
+ for rel_elem in editor.dom.getElementsByTagName("Relationship"):
1220
+ if rel_elem.getAttribute("Target") == target:
1221
+ return True
1222
+ return False
1223
+
1224
+ def _has_override(self, editor, part_name):
1225
+ """Check if an override with given part name exists."""
1226
+ for override_elem in editor.dom.getElementsByTagName("Override"):
1227
+ if override_elem.getAttribute("PartName") == part_name:
1228
+ return True
1229
+ return False
1230
+
1231
+ def _has_author(self, editor, author):
1232
+ """Check if an author already exists in people.xml."""
1233
+ for person_elem in editor.dom.getElementsByTagName("w15:person"):
1234
+ if person_elem.getAttribute("w15:author") == author:
1235
+ return True
1236
+ return False
1237
+
1238
+ def _add_author_to_people(self, author):
1239
+ """Add author to people.xml (called during initialization)."""
1240
+ people_path = self.word_path / "people.xml"
1241
+
1242
+ # people.xml should already exist from _setup_tracking
1243
+ if not people_path.exists():
1244
+ raise ValueError("people.xml should exist after _setup_tracking")
1245
+
1246
+ editor = self["word/people.xml"]
1247
+ root = editor.get_node(tag="w15:people")
1248
+
1249
+ # Check if author already exists
1250
+ if self._has_author(editor, author):
1251
+ return
1252
+
1253
+ # Add author with proper XML escaping to prevent injection
1254
+ escaped_author = html.escape(author, quote=True)
1255
+ person_xml = f'''<w15:person w15:author="{escaped_author}">
1256
+ <w15:presenceInfo w15:providerId="None" w15:userId="{escaped_author}"/>
1257
+ </w15:person>'''
1258
+ editor.append_to(root, person_xml)
1259
+
1260
+ def _ensure_comment_relationships(self):
1261
+ """Ensure word/_rels/document.xml.rels has comment relationships."""
1262
+ editor = self["word/_rels/document.xml.rels"]
1263
+
1264
+ if self._has_relationship(editor, "comments.xml"):
1265
+ return
1266
+
1267
+ root = editor.dom.documentElement
1268
+ root_tag = root.tagName # type: ignore
1269
+ prefix = root_tag.split(":")[0] + ":" if ":" in root_tag else ""
1270
+ next_rid_num = int(editor.get_next_rid()[3:])
1271
+
1272
+ # Add relationship elements
1273
+ rels = [
1274
+ (
1275
+ next_rid_num,
1276
+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments",
1277
+ "comments.xml",
1278
+ ),
1279
+ (
1280
+ next_rid_num + 1,
1281
+ "http://schemas.microsoft.com/office/2011/relationships/commentsExtended",
1282
+ "commentsExtended.xml",
1283
+ ),
1284
+ (
1285
+ next_rid_num + 2,
1286
+ "http://schemas.microsoft.com/office/2016/09/relationships/commentsIds",
1287
+ "commentsIds.xml",
1288
+ ),
1289
+ (
1290
+ next_rid_num + 3,
1291
+ "http://schemas.microsoft.com/office/2018/08/relationships/commentsExtensible",
1292
+ "commentsExtensible.xml",
1293
+ ),
1294
+ ]
1295
+
1296
+ for rel_id, rel_type, target in rels:
1297
+ rel_xml = f'<{prefix}Relationship Id="rId{rel_id}" Type="{rel_type}" Target="{target}"/>'
1298
+ editor.append_to(root, rel_xml)
1299
+
1300
+ def _ensure_comment_content_types(self):
1301
+ """Ensure [Content_Types].xml has comment content types."""
1302
+ editor = self["[Content_Types].xml"]
1303
+
1304
+ if self._has_override(editor, "/word/comments.xml"):
1305
+ return
1306
+
1307
+ root = editor.dom.documentElement
1308
+
1309
+ # Add Override elements
1310
+ overrides = [
1311
+ (
1312
+ "/word/comments.xml",
1313
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml",
1314
+ ),
1315
+ (
1316
+ "/word/commentsExtended.xml",
1317
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.commentsExtended+xml",
1318
+ ),
1319
+ (
1320
+ "/word/commentsIds.xml",
1321
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.commentsIds+xml",
1322
+ ),
1323
+ (
1324
+ "/word/commentsExtensible.xml",
1325
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.commentsExtensible+xml",
1326
+ ),
1327
+ ]
1328
+
1329
+ for part_name, content_type in overrides:
1330
+ override_xml = (
1331
+ f'<Override PartName="{part_name}" ContentType="{content_type}"/>'
1332
+ )
1333
+ editor.append_to(root, override_xml)