Skip to content
Open
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
7 changes: 7 additions & 0 deletions features/par-set-text.feature
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,10 @@ Feature: Replace paragraph text
When I set the paragraph text
Then the paragraph has the text I set
And the paragraph formatting is preserved


Scenario: Set text of a paragraph having a comment
Given a paragraph having a comment
When I set the paragraph text
Then the paragraph has the text I set
And the comment is still anchored to the paragraph
21 changes: 21 additions & 0 deletions features/steps/paragraph.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

from docx import Document
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.oxml.ns import qn
from docx.text.parfmt import ParagraphFormat

from helpers import saved_docx_path, test_docx, test_text
Expand All @@ -25,6 +26,12 @@ def given_a_document_containing_three_paragraphs(context: Context):
context.document = document


@given("a paragraph having a comment")
def given_a_paragraph_having_a_comment(context: Context):
document = context.document = Document(test_docx("comments-rich-para"))
context.paragraph = document.paragraphs[2]


@given("a paragraph having {align_type} alignment")
def given_a_paragraph_align_type_alignment(context: Context, align_type: str):
paragraph_idx = {
Expand Down Expand Up @@ -237,6 +244,20 @@ def then_the_paragraph_has_the_style_I_set(context: Context):
assert paragraph.style == expected_style


@then("the comment is still anchored to the paragraph")
def then_the_comment_is_still_anchored_to_the_paragraph(context: Context):
def comment_0_markers(element: Any) -> list[str]:
xpath = ".//w:commentRangeStart | .//w:commentRangeEnd | .//w:commentReference"
return [m.tag.split("}")[1] for m in element.xpath(xpath) if m.get(qn("w:id")) == "0"]

expected = ["commentRangeStart", "commentRangeEnd", "commentReference"]
# -- in this paragraph, in order, and nowhere else in the document --
actual = comment_0_markers(context.paragraph._p)
assert actual == expected, f"expected: {expected}, got: {actual}"
actual = comment_0_markers(context.document.element.body)
assert actual == expected, f"expected: {expected}, got: {actual}"


@then("the paragraph has the text I set")
def then_the_paragraph_has_the_text_I_set(context: Context):
actual = context.paragraph.text
Expand Down
27 changes: 27 additions & 0 deletions src/docx/text/paragraph.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from typing import TYPE_CHECKING, Iterator, List, cast

from docx.enum.style import WD_STYLE_TYPE
from docx.oxml.ns import qn
from docx.oxml.text.run import CT_R
from docx.shared import StoryChild
from docx.styles.style import ParagraphStyle
Expand Down Expand Up @@ -159,13 +160,39 @@ def text(self) -> str:
the text is mapped to a ``<w:tab/>`` element and each ``\\n`` or ``\\r``
character is mapped to a line break. Paragraph-level formatting, such as style,
is preserved. All run-level formatting, such as bold or italic, is removed.

Comment anchors in the paragraph are kept. Each ``<w:commentRangeStart>`` is
placed before the new run, and each ``<w:commentRangeEnd>`` and comment-reference
run after it, so a comment anchored to part of the paragraph then covers all of
the new text, not its original span. A comment range that starts or ends in
another paragraph keeps its marker there. Footnote references and tracked-change
markup (``<w:ins>``, ``<w:del>``) in the paragraph are still removed.
"""
return self._p.text

@text.setter
def text(self, text: str | None):
# -- comment-range markers and the comment-reference run are paragraph content, so
# -- `.clear()` would remove them and leave the comment anchored to nothing. Hold on
# -- to the ones in this paragraph, including those inside a hyperlink, which is
# -- removed too.
comment_markers = self._p.xpath(
"(. | ./w:hyperlink)/*[self::w:commentRangeStart or self::w:commentRangeEnd"
" or self::w:r[w:commentReference]]"
)
self.clear()
self.add_run(text)
new_r = self._p.r_lst[0]
# -- put each one back, range-starts before the new run and range-ends and reference
# -- runs after it, both in document order. Only markers that were in this paragraph
# -- come back, so a range spanning paragraphs is neither duplicated nor cut short.
last = new_r
for marker in comment_markers:
if marker.tag == qn("w:commentRangeStart"):
new_r.addprevious(marker)
else:
last.addnext(marker)
last = marker

def _insert_paragraph_before(self):
"""Return a newly created paragraph, inserted directly before this paragraph."""
Expand Down
70 changes: 70 additions & 0 deletions tests/text/test_paragraph.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,76 @@ def it_can_replace_the_text_it_contains(self, text_set_fixture):
paragraph.text = text
assert paragraph.text == expected_text

def it_reattaches_comment_markers_when_text_is_assigned(self, fake_parent: t.ProvidesStoryPart):
p = cast(
CT_P,
element(
'w:p/(w:commentRangeStart{w:id=42},w:r/w:t"old"'
",w:commentRangeEnd{w:id=42}"
",w:r/(w:rPr/w:rStyle{w:val=CommentReference},w:commentReference{w:id=42}))"
),
)
paragraph = Paragraph(p, fake_parent)

paragraph.text = "new"

assert paragraph.text == "new"
assert p.xml == xml(
'w:p/(w:commentRangeStart{w:id=42},w:r/w:t"new"'
",w:commentRangeEnd{w:id=42}"
",w:r/(w:rPr/w:rStyle{w:val=CommentReference},w:commentReference{w:id=42}))"
)

@pytest.mark.parametrize(
("p_cxml", "expected_cxml"),
[
# -- range starts here and ends in a later paragraph, only the start comes back --
(
'w:p/(w:r/w:t"foo ",w:commentRangeStart{w:id=1},w:r/w:t"bar")',
'w:p/(w:commentRangeStart{w:id=1},w:r/w:t"new")',
),
# -- range starts in an earlier paragraph and ends here --
(
'w:p/(w:r/w:t"foo",w:commentRangeEnd{w:id=1},w:r/w:commentReference{w:id=1}'
',w:r/w:t" bar")',
'w:p/(w:r/w:t"new",w:commentRangeEnd{w:id=1},w:r/w:commentReference{w:id=1})',
),
# -- two comments on different words, both now cover the new run --
(
'w:p/(w:commentRangeStart{w:id=1},w:r/w:t"foo",w:commentRangeEnd{w:id=1}'
',w:r/w:commentReference{w:id=1},w:r/w:t" ",w:commentRangeStart{w:id=2}'
',w:r/w:t"bar",w:commentRangeEnd{w:id=2},w:r/w:commentReference{w:id=2})',
'w:p/(w:commentRangeStart{w:id=1},w:commentRangeStart{w:id=2},w:r/w:t"new"'
",w:commentRangeEnd{w:id=1},w:r/w:commentReference{w:id=1}"
",w:commentRangeEnd{w:id=2},w:r/w:commentReference{w:id=2})",
),
# -- comment anchored inside a hyperlink, which is removed --
(
'w:p/(w:r/w:t"see ",w:hyperlink{w:anchor=_Toc1}/(w:commentRangeStart{w:id=3}'
',w:r/w:t"here",w:commentRangeEnd{w:id=3},w:r/w:commentReference{w:id=3}))',
'w:p/(w:commentRangeStart{w:id=3},w:r/w:t"new",w:commentRangeEnd{w:id=3}'
",w:r/w:commentReference{w:id=3})",
),
# -- paragraph properties stay first --
(
'w:p/(w:pPr,w:commentRangeStart{w:id=5},w:r/w:t"foo",w:commentRangeEnd{w:id=5}'
",w:r/w:commentReference{w:id=5})",
'w:p/(w:pPr,w:commentRangeStart{w:id=5},w:r/w:t"new",w:commentRangeEnd{w:id=5}'
",w:r/w:commentReference{w:id=5})",
),
],
)
def it_keeps_only_the_comment_markers_it_contains_when_text_is_assigned(
self, p_cxml: str, expected_cxml: str, fake_parent: t.ProvidesStoryPart
):
p = cast(CT_P, element(p_cxml))
paragraph = Paragraph(p, fake_parent)

paragraph.text = "new"

assert paragraph.text == "new"
assert p.xml == xml(expected_cxml)

def it_knows_its_alignment_value(self, alignment_get_fixture):
paragraph, expected_value = alignment_get_fixture
assert paragraph.alignment == expected_value
Expand Down