Skip to content

Commit 752314e

Browse files
author
Steve Canny
committed
text: add xml:space="preserve" on <w:t>
when added text has leading or trailing space
1 parent 6b65381 commit 752314e

File tree

4 files changed

+15
-11
lines changed

4 files changed

+15
-11
lines changed

docx/oxml/shared.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
'w': ('http://schemas.openxmlformats.org/wordprocessingml/2006/main'),
2020
'wp': ('http://schemas.openxmlformats.org/drawingml/2006/wordprocessing'
2121
'Drawing'),
22+
'xml': ('http://www.w3.org/XML/1998/namespace')
2223
}
2324

2425
# configure XML parser

docx/oxml/text.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,8 @@ def add_t(self, text):
206206
Return a newly added CT_T (<w:t>) element containing *text*.
207207
"""
208208
t = CT_Text.new(text)
209+
if len(text.strip()) < len(text):
210+
t.set(qn('xml:space'), 'preserve')
209211
self.append(t)
210212
return t
211213

tests/oxml/unitdata/text.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,10 @@ class CT_TextBuilder(BaseBuilder):
4949
__nspfxs__ = ('w',)
5050
__attrs__ = ()
5151

52+
def with_space(self, value):
53+
self._set_xmlattr('xml:space', str(value))
54+
return self
55+
5256

5357
def a_b():
5458
return CT_OnOffBuilder('w:b')

tests/test_text.py

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -30,10 +30,7 @@ def it_has_a_sequence_of_the_runs_it_contains(self, runs_fixture):
3030

3131
def it_can_add_a_run_to_itself(self, add_run_fixture):
3232
paragraph, text, expected_xml = add_run_fixture
33-
if text is None:
34-
run = paragraph.add_run()
35-
else:
36-
run = paragraph.add_run(text)
33+
run = paragraph.add_run(text)
3734
assert paragraph._p.xml == expected_xml
3835
assert isinstance(run, Run)
3936
assert run._r is paragraph._p.r_lst[0]
@@ -180,13 +177,13 @@ def add_break_fixture(self, request, run):
180177
expected_xml = an_r().with_nsdecls().with_child(br_bldr).xml()
181178
return run, break_type, expected_xml
182179

183-
@pytest.fixture
184-
def add_text_fixture(self, run, Text_):
185-
text_str = 'foobar'
186-
expected_xml = (
187-
an_r().with_nsdecls().with_child(
188-
a_t().with_text(text_str))
189-
).xml()
180+
@pytest.fixture(params=['foobar', ' foo bar', 'bar foo '])
181+
def add_text_fixture(self, request, run, Text_):
182+
text_str = request.param
183+
t_bldr = a_t().with_text(text_str)
184+
if text_str.startswith(' ') or text_str.endswith(' '):
185+
t_bldr.with_space('preserve')
186+
expected_xml = an_r().with_nsdecls().with_child(t_bldr).xml()
190187
return run, text_str, expected_xml, Text_
191188

192189
@pytest.fixture(params=[True, False, None])

0 commit comments

Comments
 (0)