From 4484a3609933603c352413a51860de38a97b4c1b Mon Sep 17 00:00:00 2001 From: Reinder Vos de Wael Date: Fri, 22 Nov 2024 14:06:51 -0500 Subject: [PATCH] fix: Only first run replaced when find/replace is used with a style --- pyproject.toml | 2 +- src/cmi_docx/run.py | 4 +++- tests/test_document.py | 9 ++++++--- 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index c1c5694..027f258 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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 "] license = "LGPL-2.1" diff --git a/src/cmi_docx/run.py b/src/cmi_docx/run.py index 0464576..b2249f4 100644 --- a/src/cmi_docx/run.py +++ b/src/cmi_docx/run.py @@ -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 diff --git a/tests/test_document.py b/tests/test_document.py index 2dadc1e..306374b 100644 --- a/tests/test_document.py +++ b/tests/test_document.py @@ -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"