Skip to content

Commit 1a8e232

Browse files
author
Steve Canny
committed
para: add Paragraph.text setter
1 parent 97b2e62 commit 1a8e232

3 files changed

Lines changed: 27 additions & 3 deletions

File tree

docx/text.py

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -121,14 +121,27 @@ def style(self, style):
121121
@property
122122
def text(self):
123123
"""
124-
A string formed by concatenating the text of each run in the
125-
paragraph.
124+
String formed by concatenating the text of each run in the paragraph.
125+
Tabs and line breaks in the XML are mapped to ``\\t`` and ``\\n``
126+
characters respectively.
127+
128+
Assigning text to this property causes all existing paragraph content
129+
to be replaced with a single run containing the assigned text.
130+
A ``\\t`` character in the text is mapped to a ``<w:tab/>`` element
131+
and each ``\\n`` or ``\\r`` character is mapped to a line break.
132+
Paragraph-level formatting, such as style, is preserved. All
133+
run-level formatting, such as bold or italic, is removed.
126134
"""
127135
text = ''
128136
for run in self.runs:
129137
text += run.text
130138
return text
131139

140+
@text.setter
141+
def text(self, text):
142+
self.clear()
143+
self.add_run(text)
144+
132145

133146
class Run(object):
134147
"""

features/par-set-text.feature

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ Feature: Replace paragraph text
44
I need a writable text property on paragraph
55

66

7-
@wip
87
Scenario: Set paragraph text
98
Given a paragraph with content and formatting
109
When I set the paragraph text

tests/test_text.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,11 @@ def it_knows_the_text_it_contains(self, text_get_fixture):
6565
paragraph, expected_text = text_get_fixture
6666
assert paragraph.text == expected_text
6767

68+
def it_can_replace_the_text_it_contains(self, text_set_fixture):
69+
paragraph, text, expected_text = text_set_fixture
70+
paragraph.text = text
71+
assert paragraph.text == expected_text
72+
6873
def it_can_insert_a_paragraph_before_itself(self, insert_before_fixture):
6974
paragraph, text, style, body, expected_xml = insert_before_fixture
7075
new_paragraph = paragraph.insert_paragraph_before(text, style)
@@ -153,6 +158,13 @@ def text_get_fixture(self):
153158
paragraph = Paragraph(p)
154159
return paragraph, 'foo de bar'
155160

161+
@pytest.fixture
162+
def text_set_fixture(self):
163+
p = a_p().with_nsdecls().element
164+
paragraph = Paragraph(p)
165+
paragraph.add_run('barfoo')
166+
return paragraph, 'foo\tbar\rbaz\n', 'foo\tbar\nbaz\n'
167+
156168
# fixture components ---------------------------------------------
157169

158170
@pytest.fixture

0 commit comments

Comments
 (0)