@@ -165,6 +165,7 @@ public Yaml.Mapping visitMapping(Yaml.Mapping mapping, ExecutionContext ctx) {
165165 List <Yaml .Mapping .Entry > entries = new ArrayList <>();
166166 String firstDeletedPrefix = null ;
167167 boolean previousWasDeleted = false ;
168+ String trailingInlineComment = null ;
168169 for (Yaml .Mapping .Entry entry : m .getEntries ()) {
169170 if (ToBeRemoved .hasMarker (entry .getValue ()) ||
170171 ToBeRemoved .hasMarker (entry ) ||
@@ -173,6 +174,10 @@ public Yaml.Mapping visitMapping(Yaml.Mapping mapping, ExecutionContext ctx) {
173174 if (entries .isEmpty () && firstDeletedPrefix == null ) {
174175 firstDeletedPrefix = entry .getPrefix ();
175176 }
177+ // Capture inline comment from the first deleted entry after kept entries
178+ if (trailingInlineComment == null && !entries .isEmpty ()) {
179+ trailingInlineComment = extractInlineComment (entry .getPrefix ());
180+ }
176181 changed = true ;
177182 previousWasDeleted = true ;
178183 } else {
@@ -183,6 +188,19 @@ public Yaml.Mapping visitMapping(Yaml.Mapping mapping, ExecutionContext ctx) {
183188 }
184189 entries .add (entry );
185190 previousWasDeleted = false ;
191+ trailingInlineComment = null ;
192+ }
193+ }
194+
195+ // Preserve inline comment from deleted trailing entries on the last kept entry
196+ if (trailingInlineComment != null && !entries .isEmpty ()) {
197+ int lastIndex = entries .size () - 1 ;
198+ Yaml .Mapping .Entry lastKept = entries .get (lastIndex );
199+ if (lastKept .getValue () instanceof Yaml .Scalar &&
200+ ((Yaml .Scalar ) lastKept .getValue ()).getStyle () == Yaml .Scalar .Style .PLAIN ) {
201+ Yaml .Scalar scalar = (Yaml .Scalar ) lastKept .getValue ();
202+ entries .set (lastIndex , lastKept .withValue (
203+ scalar .withValue (scalar .getValue () + trailingInlineComment )));
186204 }
187205 }
188206
@@ -242,6 +260,16 @@ private static boolean containsNewline(@Nullable String str) {
242260 return str != null && str .indexOf ('\n' ) >= 0 ;
243261 }
244262
263+ /**
264+ * Extract an inline comment from a prefix string. Inline comments appear before the
265+ * first newline in the prefix (e.g. {@code " # comment\n "} → {@code " # comment"}).
266+ */
267+ private static @ Nullable String extractInlineComment (String prefix ) {
268+ int newlineIndex = prefix .indexOf ('\n' );
269+ String beforeNewline = newlineIndex >= 0 ? prefix .substring (0 , newlineIndex ) : prefix ;
270+ return beforeNewline .contains ("#" ) ? beforeNewline : null ;
271+ }
272+
245273 private static boolean endsWithBlockScalar (Yaml .Mapping .Entry entry ) {
246274 return endsWithBlockScalar (entry .getValue ());
247275 }
0 commit comments