Skip to content

Commit

Permalink
[header] Support header comments so line breaks properly with pretty …
Browse files Browse the repository at this point in the history
…print

License headers will be comments at start of html.  Pretty print today does not line break
when it writes it thus it is not properly pretty printed.  This patch looks for usage of
pretty print and fact that 'accum' is empty to ensure the proper line break.
  • Loading branch information
hazendaz committed Nov 25, 2021
1 parent 46b0b95 commit a850726
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
15 changes: 13 additions & 2 deletions src/main/java/org/jsoup/nodes/Comment.java
Expand Up @@ -37,12 +37,23 @@ public Comment setData(String data) {
}

void outerHtmlHead(Appendable accum, int depth, Document.OutputSettings out) throws IOException {
if (out.prettyPrint() && ((siblingIndex() == 0 && parentNode instanceof Element && ((Element) parentNode).tag().formatAsBlock()) || (out.outline() )))
if (out.prettyPrint() && ((siblingIndex() == 0 && parentNode instanceof Element && ((Element) parentNode).tag().formatAsBlock()) || (out.outline() ))) {
indent(accum, depth, out);
accum
}

// Handle Header License Comment Properly under Pretty Print
if (out.prettyPrint() && accum.toString().isEmpty()) {
accum
.append("<!--")
.append(getData())
.append("-->")
.append("\n");
} else {
accum
.append("<!--")
.append(getData())
.append("-->");
}
}

void outerHtmlTail(Appendable accum, int depth, Document.OutputSettings out) {}
Expand Down
3 changes: 2 additions & 1 deletion src/test/java/org/jsoup/nodes/CommentTest.java
Expand Up @@ -21,7 +21,8 @@ public void getData() {

@Test
public void testToString() {
assertEquals("<!-- This is one heck of a comment! -->", comment.toString());
// Tests under toString are pretty printed with first being simulated license header (no content), respect new line
assertEquals("<!-- This is one heck of a comment! -->\n", comment.toString());

Document doc = Jsoup.parse("<div><!-- comment--></div>");
assertEquals("<div>\n <!-- comment-->\n</div>", doc.body().html());
Expand Down

0 comments on commit a850726

Please sign in to comment.