Skip to content

Commit 390bd11

Browse files
authored
Merge pull request #113 from EdgeCaseBerg/utility-collapse-ws-#73
Utility.trim collapse whitespace for adjacent text nodes #73
2 parents 8a00d5f + 361d02e commit 390bd11

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed

shared/src/main/scala/scala/xml/Utility.scala

+9-2
Original file line numberDiff line numberDiff line change
@@ -46,17 +46,24 @@ object Utility extends AnyRef with parsing.TokenTests {
4646
*/
4747
def trim(x: Node): Node = x match {
4848
case Elem(pre, lab, md, scp, child@_*) =>
49-
val children = child flatMap trimProper
49+
val children = combineAdjacentTextNodes(child:_*) flatMap trimProper
5050
Elem(pre, lab, md, scp, children.isEmpty, children: _*)
5151
}
5252

53+
private def combineAdjacentTextNodes(children: Node*): Seq[Node] = {
54+
children.foldRight(Seq.empty[Node]) {
55+
case (Text(left), Text(right) +: accMinusLast) => Text(left + right) +: accMinusLast
56+
case (n, acc) => n +: acc
57+
}
58+
}
59+
5360
/**
5461
* trim a child of an element. `Attribute` values and `Atom` nodes that
5562
* are not `Text` nodes are unaffected.
5663
*/
5764
def trimProper(x: Node): Seq[Node] = x match {
5865
case Elem(pre, lab, md, scp, child@_*) =>
59-
val children = child flatMap trimProper
66+
val children = combineAdjacentTextNodes(child:_*) flatMap trimProper
6067
Elem(pre, lab, md, scp, children.isEmpty, children: _*)
6168
case Text(s) =>
6269
new TextBuffer().append(s).toText

shared/src/test/scala/scala/xml/UtilityTest.scala

+23
Original file line numberDiff line numberDiff line change
@@ -194,4 +194,27 @@ class UtilityTest {
194194
).toMap.withDefault {
195195
key: Char => key.toString
196196
}
197+
198+
def issue73StartsWithAndEndsWithWSInFirst: Unit = {
199+
val x = <div>{Text(" My name is ")}{Text("Harry")}</div>
200+
assertEquals(<div>My name is Harry</div>, Utility.trim(x))
201+
}
202+
203+
@Test
204+
def issue73EndsWithWSInLast: Unit = {
205+
val x = <div>{Text("My name is ")}{Text("Harry ")}</div>
206+
assertEquals(<div>My name is Harry</div>, Utility.trim(x))
207+
}
208+
209+
@Test
210+
def issue73HasWSInMiddle: Unit = {
211+
val x = <div>{Text("My name is")}{Text(" ")}{Text("Harry")}</div>
212+
assertEquals(<div>My name is Harry</div>, Utility.trim(x))
213+
}
214+
215+
@Test
216+
def issue73HasWSEverywhere: Unit = {
217+
val x = <div>{Text(" My name ")}{Text(" is ")}{Text(" Harry ")}</div>
218+
assertEquals(<div>My name is Harry</div>, Utility.trim(x))
219+
}
197220
}

0 commit comments

Comments
 (0)