Skip to content

Commit 9413d1e

Browse files
authored
Merge pull request #198 from ruby-docx/fix-187-preserve-space
Preserve leading/trailing spaces written to w:t (reported by @Andy9822 in #187)
2 parents 3aef8ef + eadf008 commit 9413d1e

2 files changed

Lines changed: 30 additions & 0 deletions

File tree

‎lib/docx/elements/text.rb‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ def content
1313

1414
def content=(args)
1515
@node.content = args
16+
# Without xml:space="preserve", Word drops leading and trailing spaces.
17+
@node['xml:space'] = 'preserve' if args.to_s.match?(/\A\s|\s\z/)
1618
end
1719

1820
def initialize(node)

‎spec/docx/elements/text_spec.rb‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,5 +23,33 @@
2323

2424
expect(node.content).to eq('world')
2525
end
26+
27+
# Regression tests for #187: without xml:space="preserve", Word drops
28+
# leading and trailing spaces of a w:t.
29+
it 'marks the node xml:space="preserve" when the content has a trailing space' do
30+
text.content = 'Jane '
31+
32+
expect(node.to_xml).to eq('<w:t xml:space="preserve">Jane </w:t>')
33+
end
34+
35+
it 'marks the node xml:space="preserve" when the content has a leading space' do
36+
text.content = ' end'
37+
38+
expect(node.to_xml).to eq('<w:t xml:space="preserve"> end</w:t>')
39+
end
40+
41+
it 'does not add xml:space when the content has no surrounding whitespace' do
42+
text.content = 'Jane'
43+
44+
expect(node.to_xml).to eq('<w:t>Jane</w:t>')
45+
end
46+
47+
it 'keeps an existing xml:space="preserve"' do
48+
node = w_node('<w:t xml:space="preserve"> a </w:t>')
49+
50+
described_class.new(node).content = 'b'
51+
52+
expect(node.to_xml).to eq('<w:t xml:space="preserve">b</w:t>')
53+
end
2654
end
2755
end

0 commit comments

Comments
 (0)