Skip to content

Commit

Permalink
Merge pull request #113 from EdgeCaseBerg/utility-collapse-ws-#73
Browse files Browse the repository at this point in the history
Utility.trim collapse whitespace for adjacent text nodes #73
  • Loading branch information
ashawley authored May 24, 2018
2 parents 8a00d5f + 361d02e commit 390bd11
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
11 changes: 9 additions & 2 deletions shared/src/main/scala/scala/xml/Utility.scala
Original file line number Diff line number Diff line change
Expand Up @@ -46,17 +46,24 @@ object Utility extends AnyRef with parsing.TokenTests {
*/
def trim(x: Node): Node = x match {
case Elem(pre, lab, md, scp, child@_*) =>
val children = child flatMap trimProper
val children = combineAdjacentTextNodes(child:_*) flatMap trimProper
Elem(pre, lab, md, scp, children.isEmpty, children: _*)
}

private def combineAdjacentTextNodes(children: Node*): Seq[Node] = {
children.foldRight(Seq.empty[Node]) {
case (Text(left), Text(right) +: accMinusLast) => Text(left + right) +: accMinusLast
case (n, acc) => n +: acc
}
}

/**
* trim a child of an element. `Attribute` values and `Atom` nodes that
* are not `Text` nodes are unaffected.
*/
def trimProper(x: Node): Seq[Node] = x match {
case Elem(pre, lab, md, scp, child@_*) =>
val children = child flatMap trimProper
val children = combineAdjacentTextNodes(child:_*) flatMap trimProper
Elem(pre, lab, md, scp, children.isEmpty, children: _*)
case Text(s) =>
new TextBuffer().append(s).toText
Expand Down
23 changes: 23 additions & 0 deletions shared/src/test/scala/scala/xml/UtilityTest.scala
Original file line number Diff line number Diff line change
Expand Up @@ -194,4 +194,27 @@ class UtilityTest {
).toMap.withDefault {
key: Char => key.toString
}

def issue73StartsWithAndEndsWithWSInFirst: Unit = {
val x = <div>{Text(" My name is ")}{Text("Harry")}</div>
assertEquals(<div>My name is Harry</div>, Utility.trim(x))
}

@Test
def issue73EndsWithWSInLast: Unit = {
val x = <div>{Text("My name is ")}{Text("Harry ")}</div>
assertEquals(<div>My name is Harry</div>, Utility.trim(x))
}

@Test
def issue73HasWSInMiddle: Unit = {
val x = <div>{Text("My name is")}{Text(" ")}{Text("Harry")}</div>
assertEquals(<div>My name is Harry</div>, Utility.trim(x))
}

@Test
def issue73HasWSEverywhere: Unit = {
val x = <div>{Text(" My name ")}{Text(" is ")}{Text(" Harry ")}</div>
assertEquals(<div>My name is Harry</div>, Utility.trim(x))
}
}

0 comments on commit 390bd11

Please sign in to comment.