document.py 52 KB

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