Support nested keep-chomping block scalars when appending to block list
diff --git a/pkgs/yaml_edit/lib/src/list_mutations.dart b/pkgs/yaml_edit/lib/src/list_mutations.dart index 2595d96..6210dfc 100644 --- a/pkgs/yaml_edit/lib/src/list_mutations.dart +++ b/pkgs/yaml_edit/lib/src/list_mutations.dart
@@ -161,9 +161,24 @@ if (nextNewLineIndex == -1) { formattedValue = getLineEnding(yaml) + formattedValue; } else { - if (lastNode is YamlScalar && - (lastNode.style == ScalarStyle.LITERAL || - lastNode.style == ScalarStyle.FOLDED)) { + var deepestNode = lastNode; + while (true) { + if (deepestNode is YamlList && + deepestNode.style == CollectionStyle.BLOCK && + deepestNode.isNotEmpty) { + deepestNode = deepestNode.nodes.last; + } else if (deepestNode is YamlMap && + deepestNode.style == CollectionStyle.BLOCK && + deepestNode.isNotEmpty) { + deepestNode = deepestNode.nodes.values.last; + } else { + break; + } + } + + if (deepestNode is YamlScalar && + (deepestNode.style == ScalarStyle.LITERAL || + deepestNode.style == ScalarStyle.FOLDED)) { while (nextNewLineIndex + 1 < yaml.length) { final nextLineEnd = yaml.indexOf('\n', nextNewLineIndex + 1); final lineSlice = nextLineEnd == -1
diff --git a/pkgs/yaml_edit/test/append_test.dart b/pkgs/yaml_edit/test/append_test.dart index fb43c47..f32eb56 100644 --- a/pkgs/yaml_edit/test/append_test.dart +++ b/pkgs/yaml_edit/test/append_test.dart
@@ -261,6 +261,39 @@ expect(doc.parseAt(['list', 1]).value, equals('next')); }); + test('preserves multiple trailing newlines of nested |+ when appending', + () { + final doc = YamlEditor('list:\n - map_key: |+\n hello\n\n\n'); + doc.appendToList(['list'], 'next'); + final result = doc.toString(); + expect(result, + equals('list:\n - map_key: |+\n hello\n\n\n - next\n')); + expect(doc.parseAt(['list', 0, 'map_key']).value, equals('hello\n\n\n')); + expect(doc.parseAt(['list', 1]).value, equals('next')); + }); + + test( + 'preserves multiple trailing newlines of nested list |+ when appending', + () { + final doc = YamlEditor('list:\n - - |+\n hello\n\n\n'); + doc.appendToList(['list'], 'next'); + final result = doc.toString(); + expect(result, equals('list:\n - - |+\n hello\n\n\n - next\n')); + expect(doc.parseAt(['list', 0, 0]).value, equals('hello\n\n\n')); + expect(doc.parseAt(['list', 1]).value, equals('next')); + }); + + test('preserves multiple trailing newlines of nested >+ when appending', + () { + final doc = YamlEditor('list:\n - map_key: >+\n hello\n\n\n'); + doc.appendToList(['list'], 'next'); + final result = doc.toString(); + expect(result, + equals('list:\n - map_key: >+\n hello\n\n\n - next\n')); + expect(doc.parseAt(['list', 0, 'map_key']).value, equals('hello\n\n\n')); + expect(doc.parseAt(['list', 1]).value, equals('next')); + }); + test('appends to list ending with single-line scalar without newlines', () { final doc = YamlEditor('list:\n - item'); doc.appendToList(['list'], 'item2');