Skip to content

Commit

Permalink
fix: Only first run replaced when find/replace is used with a style
Browse files Browse the repository at this point in the history
  • Loading branch information
ReinderVosDeWael committed Nov 22, 2024
1 parent 0bc20bf commit 4484a36
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 5 deletions.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "cmi_docx"
version = "0.3.3"
version = "0.3.4"
description = ".docx utilities"
authors = ["Reinder Vos de Wael <[email protected]>"]
license = "LGPL-2.1"
Expand Down
4 changes: 3 additions & 1 deletion src/cmi_docx/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,10 @@ def _replace_with_style(self, replace: str, style: styles.RunStyle) -> None:
start = self.character_indices[0]
end = self.character_indices[1]

pre, post = self.runs[0].text[:start], self.runs[0].text[end:]
pre, post = self.runs[0].text[:start], self.runs[-1].text[end:]
self.runs[0].text = pre
for index in range(1, len(self.runs)):
self.runs[index].text = ""

new_run = self.paragraph._element._new_r()
new_run.text = replace
Expand Down
9 changes: 6 additions & 3 deletions tests/test_document.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,12 +93,15 @@ def test_replace(runs: list[str], needle: str, replace: str, expected: str) -> N
def test_replace_with_style() -> None:
"""Test replacing text in a document with style."""
doc = docx.Document()
doc.add_paragraph("Hello, world!")
paragraph = doc.add_paragraph("")
paragraph.add_run("{{")
paragraph.add_run("Hello, World!")
paragraph.add_run("}}")
extend_document = document.ExtendDocument(doc)

extend_document.replace("Hello", "Goodbye", styles.RunStyle(bold=True))
extend_document.replace("{{Hello", "Goodbye", styles.RunStyle(bold=True))

assert doc.paragraphs[0].text == "Goodbye, world!"
assert doc.paragraphs[0].text == "Goodbye, World!}}"
assert not doc.paragraphs[0].runs[0].bold
assert doc.paragraphs[0].runs[1].bold
assert doc.paragraphs[0].runs[1].text == "Goodbye"
Expand Down

0 comments on commit 4484a36

Please sign in to comment.