@@ -513,16 +513,37 @@ private Cursor addNewKeyValue(
513513 pos = afterLastProperty ();
514514 }
515515
516+ boolean afterFinalComment = isAfterFinalComment (pos );
517+
516518 // Add a newline whitespace token if necessary
517519 pos = prepareNewLine (pos );
518520
521+ if (afterFinalComment ) {
522+ // Keep a trailing comment free rather than attaching it to the new key.
523+ pos .addEol (eolType );
524+ }
525+
519526 // Add tokens for key, separator and value
520527 pos .add (new PropertiesParser .Token (PropertiesParser .Type .KEY , rawKey , key ));
521528 pos .add (new PropertiesParser .Token (PropertiesParser .Type .SEPARATOR , "=" ));
522529 pos .add (new PropertiesParser .Token (PropertiesParser .Type .VALUE , rawValue , value ));
523530 return pos ;
524531 }
525532
533+ // Returns true only at the end of the token list when the last token is a comment,
534+ // optionally followed by one EOL. An existing blank line after the comment returns false.
535+ // Uses a copy so the insertion cursor is not moved.
536+ private boolean isAfterFinalComment (Cursor pos ) {
537+ if (!pos .atEnd ()) {
538+ return false ;
539+ }
540+ Cursor previous = pos .copy ().prev ();
541+ if (previous .isEol ()) {
542+ previous .prev ();
543+ }
544+ return previous .isType (PropertiesParser .Type .COMMENT );
545+ }
546+
526547 // Prepare the list for adding a new line at the given position. It will make sure the cursor
527548 // is at a valid insertion point and that any required EOLs are added.
528549 private Cursor prepareNewLine (Cursor pos ) {
0 commit comments