diff --git a/rewrite-xml/src/main/java/org/openrewrite/xml/format/LineBreaksVisitor.java b/rewrite-xml/src/main/java/org/openrewrite/xml/format/LineBreaksVisitor.java index 1db7b7f11df..c01d56fd4a8 100644 --- a/rewrite-xml/src/main/java/org/openrewrite/xml/format/LineBreaksVisitor.java +++ b/rewrite-xml/src/main/java/org/openrewrite/xml/format/LineBreaksVisitor.java @@ -18,9 +18,12 @@ import org.jspecify.annotations.Nullable; import org.openrewrite.Tree; import org.openrewrite.xml.XmlIsoVisitor; +import org.openrewrite.xml.tree.Content; import org.openrewrite.xml.tree.Misc; import org.openrewrite.xml.tree.Xml; +import java.util.List; + public class LineBreaksVisitor
extends XmlIsoVisitor
{
@Nullable
private final Tree stopAfter;
@@ -35,10 +38,25 @@ public LineBreaksVisitor(@Nullable Tree stopAfter) {
@Override
public Xml.Comment visitComment(Xml.Comment comment, P p) {
+ if (isTrailingComment(comment)) {
+ return super.visitComment(comment, p);
+ }
return keepMaximumLines(minimumLines(super.visitComment(comment, p),
isFirstMisc(comment) ? 0 : 1), 2);
}
+ private boolean isTrailingComment(Xml.Comment comment) {
+ if (comment.getPrefix().contains("\n")) {
+ return false;
+ }
+ Object parent = getCursor().getParentTreeCursor().getValue();
+ if (!(parent instanceof Xml.Tag)) {
+ return false;
+ }
+ List extends Content> content = ((Xml.Tag) parent).getContent();
+ return content != null && !content.isEmpty() && content.get(0) != comment;
+ }
+
@Override
public Xml.DocTypeDecl visitDocTypeDecl(Xml.DocTypeDecl docTypeDecl, P p) {
return keepMaximumLines(minimumLines(super.visitDocTypeDecl(docTypeDecl, p),
diff --git a/rewrite-xml/src/test/java/org/openrewrite/xml/format/AutoFormatTest.java b/rewrite-xml/src/test/java/org/openrewrite/xml/format/AutoFormatTest.java
index 69f631695b0..f4e940ed860 100644
--- a/rewrite-xml/src/test/java/org/openrewrite/xml/format/AutoFormatTest.java
+++ b/rewrite-xml/src/test/java/org/openrewrite/xml/format/AutoFormatTest.java
@@ -114,4 +114,63 @@ void tagContentIndentation() {
)
);
}
+
+ @Test
+ void trailingCommentStaysOnSameLine() {
+ rewriteRun(
+ xml(
+ """
+
+