Skip to content

Commit

Permalink
fix: Fix finding runs when the needle ends on the last character
Browse files Browse the repository at this point in the history
  • Loading branch information
ReinderVosDeWael committed Dec 19, 2024
1 parent dc811f3 commit c38c232
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 2 deletions.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "cmi-docx"
version = "0.3.6"
version = "0.3.7"
description = "Additional tooling for Python-docx."
readme = "README.md"
requires-python = ">=3.10"
Expand Down
5 changes: 4 additions & 1 deletion src/cmi_docx/paragraph.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,13 @@ def find_in_runs(self, needle: str) -> list[run.FindRun]:
run_finds: list[run.FindRun] = []
run_lengths = [len(run.text) for run in self.paragraph.runs]
cumulative_run_lengths = list(itertools.accumulate(run_lengths))

for occurence in self.find_in_paragraph(needle).character_indices:
start_run = bisect.bisect_right(cumulative_run_lengths, occurence[0])
end_run = bisect.bisect_right(
cumulative_run_lengths[:-1], occurence[1], lo=start_run
cumulative_run_lengths[:-1],
occurence[1] - 1, # -1 as the range does not include the last character
lo=start_run,
)

start_index = (
Expand Down
13 changes: 13 additions & 0 deletions tests/test_paragraph.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,19 @@ def test_find_in_single_run(sample_paragraph: docx_paragraph.Paragraph) -> None:
assert actual[1].character_indices == expected[1].character_indices


def test_find_in_single_run_complete() -> None:
"""Tests finding an exact match of a run."""
document = docx.Document()
para = document.add_paragraph("This is a sample paragraph.")
para.add_run("full-run")
para.add_run("another")
extend_paragraph = paragraph.ExtendParagraph(para)

actual = extend_paragraph.find_in_runs("full-run")

assert len(actual[0].runs) == 1


def test_replace_single_run(sample_paragraph: docx_paragraph.Paragraph) -> None:
"""Test replacing text in a paragraph."""
extend_paragraph = paragraph.ExtendParagraph(sample_paragraph)
Expand Down

0 comments on commit c38c232

Please sign in to comment.