Skip to content

Commit e6c490e

Browse files
authoredJun 25, 2018
Merge pull request #233 from hosamaly/issue-231
Fix #231: Minimize empty elements with lengthy attributes
2 parents 488f069 + baf1b5b commit e6c490e

File tree

2 files changed

+32
-6
lines changed

2 files changed

+32
-6
lines changed
 

‎jvm/src/test/scala/scala/xml/XMLTest.scala

+16
Original file line numberDiff line numberDiff line change
@@ -749,4 +749,20 @@ class XMLTestJVM {
749749
assertEquals("<node>\n <leaf/>\n</node>", pp.format(x))
750750
}
751751

752+
@UnitTest
753+
def issue231: Unit = {
754+
val pp = new xml.PrettyPrinter(4, 2, minimizeEmpty = true)
755+
val x = <a b="c"/>
756+
val formatted = pp.format(x)
757+
assertEquals(x, XML.loadString(formatted))
758+
assertTrue(formatted.trim.lines.length >= 2)
759+
}
760+
761+
@UnitTest
762+
def issue231_withoutAttributes: Unit = {
763+
val pp = new xml.PrettyPrinter(4, 2, minimizeEmpty = true)
764+
val x = <abcdefg/>
765+
val formatted = pp.format(x)
766+
assertEquals(x, XML.loadString(formatted))
767+
}
752768
}

‎shared/src/main/scala/scala/xml/PrettyPrinter.scala

+16-6
Original file line numberDiff line numberDiff line change
@@ -160,8 +160,16 @@ class PrettyPrinter(width: Int, step: Int, minimizeEmpty: Boolean) {
160160
if (childrenAreLeaves(node) && fits(test)) {
161161
makeBox(ind, test)
162162
} else {
163-
val (stg, len2) = startTag(node, pscope)
164-
val etg = endTag(node)
163+
val ((stg, len2), etg) =
164+
if (node.child.isEmpty && minimizeEmpty) {
165+
// force the tag to be self-closing
166+
val firstAttribute = test.indexOf(' ')
167+
val firstBreak = if (firstAttribute != -1) firstAttribute else test.lastIndexOf('/')
168+
((test, firstBreak), "")
169+
} else {
170+
(startTag(node, pscope), endTag(node))
171+
}
172+
165173
if (stg.length < width - cur) { // start tag fits
166174
makeBox(ind, stg)
167175
makeBreak()
@@ -180,10 +188,12 @@ class PrettyPrinter(width: Int, step: Int, minimizeEmpty: Boolean) {
180188
makeBreak()
181189
}
182190
}*/
183-
makeBox(ind, stg.substring(len2, stg.length))
184-
makeBreak()
185-
traverse(node.child.iterator, node.scope, ind + step)
186-
makeBox(cur, etg)
191+
makeBox(ind, stg.substring(len2, stg.length).trim)
192+
if (etg.nonEmpty) {
193+
makeBreak()
194+
traverse(node.child.iterator, node.scope, ind + step)
195+
makeBox(cur, etg)
196+
}
187197
makeBreak()
188198
} else { // give up
189199
makeBox(ind, test)

0 commit comments

Comments
 (0)
Please sign in to comment.