Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Fix finding runs when the needle ends on the last character #38

Merged
merged 1 commit into from
Dec 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading