docx_common.py 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #!/usr/bin/env python3
  2. # MIT License. Shared helpers for the docx skill scripts.
  3. """Shared helpers: paragraph iteration and run-preserving text replacement."""
  4. from __future__ import annotations
  5. def iter_all_paragraphs(doc, include_headers_footers: bool = True):
  6. """Yield every paragraph in body, tables (recursively), headers, footers."""
  7. yield from _iter_container(doc)
  8. if include_headers_footers:
  9. for section in doc.sections:
  10. for part in (
  11. section.header, section.footer,
  12. section.first_page_header, section.first_page_footer,
  13. section.even_page_header, section.even_page_footer,
  14. ):
  15. if part is not None:
  16. yield from _iter_container(part)
  17. def _iter_container(container):
  18. yield from container.paragraphs
  19. for table in container.tables:
  20. yield from _iter_table(table)
  21. def _iter_table(table):
  22. for row in table.rows:
  23. for cell in row.cells:
  24. yield from cell.paragraphs
  25. for nested in cell.tables:
  26. yield from _iter_table(nested)
  27. def iter_part_roots(doc):
  28. """Yield the XML root of the body plus every header/footer part."""
  29. yield doc.element.body
  30. seen = set()
  31. for section in doc.sections:
  32. for part in (
  33. section.header, section.footer,
  34. section.first_page_header, section.first_page_footer,
  35. section.even_page_header, section.even_page_footer,
  36. ):
  37. if part is not None and id(part._element) not in seen:
  38. seen.add(id(part._element))
  39. yield part._element
  40. def replace_in_paragraph(para, old: str, new: str) -> int:
  41. """Replace `old` with `new` in a paragraph, preserving run formatting.
  42. Strategy: first replace occurrences fully contained in a single run
  43. (formatting fully preserved). If the needle spans multiple runs, the
  44. matched runs are collapsed: the replacement inherits the formatting of
  45. the run where the match starts. Returns number of replacements made.
  46. """
  47. if not old or old not in para.text:
  48. return 0
  49. count = 0
  50. # Pass 1: within-run replacements.
  51. for run in para.runs:
  52. if old in run.text:
  53. count += run.text.count(old)
  54. run.text = run.text.replace(old, new)
  55. # Pass 2: cross-run occurrences.
  56. while old in para.text:
  57. runs = para.runs
  58. # Map paragraph text offsets to (run_index, offset_in_run).
  59. full = "".join(r.text for r in runs)
  60. start = full.find(old)
  61. if start < 0:
  62. break
  63. end = start + len(old)
  64. pos = 0
  65. spans = [] # (run_idx, cut_start, cut_end) portions inside the match
  66. for i, r in enumerate(runs):
  67. r_start, r_end = pos, pos + len(r.text)
  68. if r_end > start and r_start < end:
  69. spans.append((i, max(start, r_start) - r_start,
  70. min(end, r_end) - r_start))
  71. pos = r_end
  72. first = True
  73. for i, cs, ce in spans:
  74. t = runs[i].text
  75. if first:
  76. runs[i].text = t[:cs] + new + t[ce:]
  77. first = False
  78. else:
  79. runs[i].text = t[:cs] + t[ce:]
  80. count += 1
  81. return count