Skip to content

Commit

Permalink
Allow for inserting a paragraph with text/style (#7)
Browse files Browse the repository at this point in the history
  • Loading branch information
ReinderVosDeWael authored Apr 2, 2024
1 parent 9d5384a commit 7cd231a
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 7 deletions.
34 changes: 29 additions & 5 deletions src/cmi_docx/document.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,20 +61,44 @@ def replace(self, needle: str, replace: str) -> None:
for run_find in run_finder:
run_find.replace(replace)

def insert_paragraph(
def insert_paragraph_by_text(
self,
paragraph: docx_paragraph.Paragraph,
index: int,
) -> None:
"""Inserts a paragraph at a given index.
text: str,
style: str | None = None,
) -> docx_paragraph.Paragraph:
"""Inserts a paragraph into a document.
Args:
paragraph: The paragraph to insert.
index: The index to insert the paragraph at.
text: The text to insert.
style: The style to apply to the text.
Returns:
The new paragraph.
"""
new_paragraph = self._insert_empty_paragraph(index)
new_paragraph.add_run(text, style=style)
return new_paragraph

def insert_paragraph_by_object(
self,
index: int,
paragraph: docx_paragraph.Paragraph,
) -> docx_paragraph.Paragraph:
"""Inserts a paragraph into a document.
Args:
index: The index to insert the paragraph at.
paragraph: The paragraph to insert.
Returns:
The new paragraph.
"""
new_paragraph = self._insert_empty_paragraph(index)
for paragraph_run in paragraph.runs:
new_paragraph.add_run(paragraph_run.text, paragraph_run.style)
return new_paragraph

def insert_image(
self,
Expand Down
18 changes: 16 additions & 2 deletions tests/test_document.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,15 +46,29 @@ def test_replace() -> None:
assert doc.paragraphs[0].text == "Goodbye, world!"


def test_insert_paragraph() -> None:
def test_insert_paragraph_by_object() -> None:
"""Test inserting a paragraph into a document."""
doc = docx.Document()
doc.add_paragraph("Hello, world!")
doc.add_paragraph("Goodbye, world!")
extend_document = document.ExtendDocument(doc)
new_paragraph = docx.Document().add_paragraph("Maintain, world!")

extend_document.insert_paragraph(new_paragraph, 1)
extend_document.insert_paragraph_by_object(1, new_paragraph)

assert doc.paragraphs[0].text == "Hello, world!"
assert doc.paragraphs[1].text == "Maintain, world!"
assert doc.paragraphs[2].text == "Goodbye, world!"


def test_insert_paragraph_by_text() -> None:
"""Test inserting a paragraph into a document."""
doc = docx.Document()
doc.add_paragraph("Hello, world!")
doc.add_paragraph("Goodbye, world!")
extend_document = document.ExtendDocument(doc)

extend_document.insert_paragraph_by_text(1, "Maintain, world!")

assert doc.paragraphs[0].text == "Hello, world!"
assert doc.paragraphs[1].text == "Maintain, world!"
Expand Down

0 comments on commit 7cd231a

Please sign in to comment.