Branchwell

Skillfarm / skills · skillfarm.ai / converted / docx / scripts / merge_runs.py

1"""Merge adjacent identically-formatted runs in a DOCX.
2
3Word fragments paragraph text across many <w:r> elements (revision ids,
4spell-check markers, editing history), which makes find-and-replace on
5word/document.xml unreliable — the string you're looking for is split
6across runs. This coalesces adjacent runs whose formatting (<w:rPr>) is
7identical, strips rsid attributes and proofErr markers, and consolidates the
8text elements — <w:t>, and <w:delText> for text inside a tracked deletion.
9
10Rendering is unchanged. The text you search is what Word draws, which is not
11always the bytes in the file: an element without xml:space="preserve" has its
12edge whitespace trimmed before it reaches the page, so `<w:t>Hello </w:t>`
13followed by `<w:t>world</w:t>` reads "Helloworld" and merges to exactly that.
14
15Runs in two different <w:ins>/<w:del> wrappers are never merged: that would
16rewrite tracked-change structure, collapsing separate revisions into one.
17
18Only word/document.xml is processed (not headers, footers, or footnotes).
19
20Usage:
21 python merge_runs.py unpacked/ # after unzip, before editing
22 python merge_runs.py document.docx # rewrite in place
23 python merge_runs.py document.docx -o out.docx
24"""
25
26
27import argparse
28import sys
29import tempfile
30import zipfile
31from pathlib import Path
32
33import defusedxml.minidom
34
35from office.helpers import XML_SPACE, rendered_text, rezip, safe_extract
36
37WORDML_NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
38
39
40def merge_runs(input_dir: str) -> tuple[int, str]:
41 doc_xml = Path(input_dir) / "word" / "document.xml"
42
43 if not doc_xml.exists():
44 return 0, f"Error: {doc_xml} not found"
45
46 try:
47 dom = defusedxml.minidom.parseString(doc_xml.read_text(encoding="utf-8"))
48 root = dom.documentElement
49 run_names = _run_tag_names(root)
50
51 _remove_elements(root, "proofErr")
52
53 runs = _find_runs(root, run_names)
54 _strip_rsid_attrs(runs)
55
56 merge_count = 0
57 for container in {run.parentNode for run in runs}:
58 merge_count += _merge_runs_in(container, run_names)
59
60 doc_xml.write_bytes(dom.toxml(encoding="UTF-8"))
61 return merge_count, f"Merged {merge_count} runs"
62
63 except Exception as e:
64 return 0, f"Error: {e}"
65
66
67
68
69def _is_element(node, tag: str) -> bool:
70 name = node.localName or node.tagName
71 return name == tag or name.endswith(f":{tag}")
72
73
74def _run_tag_names(root) -> set[str]:
75 names = set()
76 for attr in root.attributes.values():
77 if attr.value == WORDML_NS:
78 if attr.name == "xmlns":
79 names.add("r")
80 elif attr.name.startswith("xmlns:"):
81 names.add(attr.name.split(":", 1)[1] + ":r")
82 return names or {"w:r", "r"}
83
84
85def _find_elements(root, tag: str) -> list:
86 results = []
87
88 def traverse(node):
89 if node.nodeType == node.ELEMENT_NODE:
90 if _is_element(node, tag):
91 results.append(node)
92 for child in node.childNodes:
93 traverse(child)
94
95 traverse(root)
96 return results
97
98
99def _find_runs(root, run_names: set[str]) -> list:
100 return [e for e in _find_elements(root, "r") if _is_run(e, run_names)]
101
102
103def _get_child(parent, tag: str):
104 return next(iter(_get_children(parent, tag)), None)
105
106
107def _get_children(parent, tag: str) -> list:
108 return [
109 child
110 for child in parent.childNodes
111 if child.nodeType == child.ELEMENT_NODE and _is_element(child, tag)
112 ]
113
114
115def _is_adjacent(elem1, elem2) -> bool:
116 node = elem1.nextSibling
117 while node:
118 if node == elem2:
119 return True
120 if node.nodeType == node.ELEMENT_NODE:
121 return False
122 if node.nodeType == node.TEXT_NODE and node.data.strip(XML_SPACE):
123 return False
124 node = node.nextSibling
125 return False
126
127
128
129
130def _remove_elements(root, tag: str):
131 for elem in _find_elements(root, tag):
132 if elem.parentNode:
133 elem.parentNode.removeChild(elem)
134
135
136def _strip_rsid_attrs(runs: list):
137 for run in runs:
138 for attr in list(run.attributes.values()):
139 if "rsid" in attr.name.lower():
140 run.removeAttribute(attr.name)
141
142
143
144
145def _merge_runs_in(container, run_names: set[str]) -> int:
146 merge_count = 0
147 run = _first_child_run(container, run_names)
148
149 while run:
150 while True:
151 next_elem = _next_element_sibling(run)
152 if next_elem and _is_run(next_elem, run_names) and _can_merge(run, next_elem):
153 _merge_run_content(run, next_elem)
154 container.removeChild(next_elem)
155 merge_count += 1
156 else:
157 break
158
159 _consolidate_text(run)
160 run = _next_sibling_run(run, run_names)
161
162 return merge_count
163
164
165def _first_child_run(container, run_names: set[str]):
166 for child in container.childNodes:
167 if child.nodeType == child.ELEMENT_NODE and _is_run(child, run_names):
168 return child
169 return None
170
171
172def _next_element_sibling(node):
173 sibling = node.nextSibling
174 while sibling:
175 if sibling.nodeType == sibling.ELEMENT_NODE:
176 return sibling
177 sibling = sibling.nextSibling
178 return None
179
180
181def _next_sibling_run(node, run_names: set[str]):
182 sibling = node.nextSibling
183 while sibling:
184 if sibling.nodeType == sibling.ELEMENT_NODE:
185 if _is_run(sibling, run_names):
186 return sibling
187 sibling = sibling.nextSibling
188 return None
189
190
191def _is_run(node, run_names: set[str]) -> bool:
192 return node.tagName in run_names
193
194
195def _can_merge(run1, run2) -> bool:
196 rpr1 = _get_child(run1, "rPr")
197 rpr2 = _get_child(run2, "rPr")
198
199 if (rpr1 is None) != (rpr2 is None):
200 return False
201 if rpr1 is None:
202 return True
203 return rpr1.toxml() == rpr2.toxml()
204
205
206def _merge_run_content(target, source):
207 for child in list(source.childNodes):
208 if child.nodeType == child.ELEMENT_NODE:
209 name = child.localName or child.tagName
210 if name != "rPr" and not name.endswith(":rPr"):
211 target.appendChild(child)
212
213
214def _element_text(elem) -> str:
215 return "".join(
216 child.data
217 for child in elem.childNodes
218 if child.nodeType in (child.TEXT_NODE, child.CDATA_SECTION_NODE)
219 )
220
221
222def _has_preserve(elem) -> bool:
223 return elem.getAttribute("xml:space") == "preserve"
224
225
226def _rendered_text(elem) -> str:
227 return rendered_text(_element_text(elem), _has_preserve(elem))
228
229
230def _consolidate_text(run):
231 for tag in ("t", "delText"):
232 _consolidate_text_elements(run, tag)
233
234
235def _consolidate_text_elements(run, tag: str):
236 t_elements = _get_children(run, tag)
237
238 for i in range(len(t_elements) - 1, 0, -1):
239 curr, prev = t_elements[i], t_elements[i - 1]
240
241 if _is_adjacent(prev, curr):
242 merged = _rendered_text(prev) + _rendered_text(curr)
243 had_preserve = _has_preserve(prev) or _has_preserve(curr)
244
245 new_text = run.ownerDocument.createTextNode(merged)
246 for node in list(prev.childNodes):
247 if node.nodeType in (node.TEXT_NODE, node.CDATA_SECTION_NODE):
248 prev.removeChild(node)
249 else:
250 run.insertBefore(node, curr)
251 prev.appendChild(new_text)
252 for node in list(curr.childNodes):
253 if node.nodeType not in (node.TEXT_NODE, node.CDATA_SECTION_NODE):
254 run.insertBefore(node, curr)
255
256 if merged != merged.strip(XML_SPACE) or had_preserve:
257 prev.setAttribute("xml:space", "preserve")
258 elif prev.hasAttribute("xml:space"):
259 prev.removeAttribute("xml:space")
260
261 run.removeChild(curr)
262
263
264
265
266def _merge_or_die(path: Path) -> str:
267 _, msg = merge_runs(str(path))
268 if msg.startswith("Error"):
269 print(msg, file=sys.stderr)
270 sys.exit(1)
271 return msg
272
273
274def main() -> None:
275 p = argparse.ArgumentParser(
276 description="Merge adjacent identically-formatted runs in a DOCX (directory or .docx file)."
277 )
278 p.add_argument("input", help="Unpacked DOCX directory OR a .docx/.dotx file")
279 p.add_argument(
280 "-o", "--output",
281 help="Output .docx path (only valid when input is a .docx; default: overwrite input)",
282 )
283 args = p.parse_args()
284
285 src = Path(args.input)
286
287 try:
288 if src.is_dir():
289 if args.output:
290 p.error("--output is only valid for .docx input; directory input is modified in place")
291 print(_merge_or_die(src))
292 elif src.is_file() and src.suffix.lower() in (".docx", ".dotx"):
293 out = Path(args.output) if args.output else src
294 with tempfile.TemporaryDirectory() as tmp:
295 tmp_path = Path(tmp)
296 with zipfile.ZipFile(src) as zf:
297 safe_extract(zf, tmp_path)
298 msg = _merge_or_die(tmp_path)
299 rezip(tmp_path, out)
300 print(f"{msg}; wrote {out}")
301 else:
302 print(f"Error: {src} is neither a directory nor a .docx/.dotx file", file=sys.stderr)
303 sys.exit(1)
304 except (OSError, ValueError, zipfile.BadZipFile) as e:
305 print(f"Error: {e}", file=sys.stderr)
306 sys.exit(1)
307
308
309if __name__ == "__main__":
310 main()