diff --git a/src/emitter.cpp b/src/emitter.cpp index 5168cba89..4afb20ef4 100644 --- a/src/emitter.cpp +++ b/src/emitter.cpp @@ -947,8 +947,12 @@ Emitter& Emitter::Write(const _Comment& comment) { PrepareNode(EmitterNodeType::NoType); - if (m_stream.col() > 0) + if (m_stream.col() == 0 && + m_pState->CurGroupNodeType() == EmitterNodeType::BlockMap) { + m_stream << IndentTo(m_pState->CurIndent()); + } else if (m_stream.col() > 0) { m_stream << Indentation(m_pState->GetPreCommentIndent()); + } Utils::WriteComment(m_stream, comment.content.data(), comment.content.size(), m_pState->GetPostCommentIndent()); diff --git a/test/integration/emitter_test.cpp b/test/integration/emitter_test.cpp index f1472d6f3..456b8d14a 100644 --- a/test/integration/emitter_test.cpp +++ b/test/integration/emitter_test.cpp @@ -1822,5 +1822,68 @@ TEST_F(EmitterTest, ShowTrailingZero) { - .nan)"); } +TEST_F(EmitterTest, CommentInsideMapValueIsIndented) { + out << YAML::BeginMap << YAML::Key << "foo" << YAML::BeginMap + << YAML::Comment("Comment") << YAML::Key << "bar" << YAML::Value << true + << YAML::EndMap << YAML::EndMap; + + ExpectEmit( + "foo:\n" + " # Comment\n" + " bar: true"); +} + +TEST_F(EmitterTest, CommentInsideDoubleNestedMapIsIndented) { + out << YAML::BeginMap << YAML::Key << "map1" << YAML::Value << YAML::BeginMap + << YAML::Key << "map2" << YAML::Value << YAML::BeginMap + << YAML::Comment("nested comment") << YAML::Key << "foo" << YAML::Value + << "bar" << YAML::EndMap << YAML::EndMap << YAML::EndMap; + + ExpectEmit( + "map1:\n" + " map2:\n" + " # nested comment\n" + " foo: bar"); +} + +TEST_F(EmitterTest, CommentAtEndOfDoubleNestedMapIsIndented) { + out << YAML::BeginMap << YAML::Key << "map1" << YAML::Value << YAML::BeginMap + << YAML::Key << "map2" << YAML::Value << YAML::BeginMap << YAML::Key + << "foo" << YAML::Value << "bar" << YAML::Newline + << YAML::Comment("nested comment at the end") << YAML::EndMap + << YAML::EndMap << YAML::EndMap; + + ExpectEmit( + "map1:\n" + " map2:\n" + " foo: bar\n" + " # nested comment at the end"); +} + +TEST_F(EmitterTest, CommentAfterNestedMapUsesParentIndentation) { + out << YAML::BeginMap << YAML::Key << "map1" << YAML::Value << YAML::BeginMap + << YAML::Key << "map2" << YAML::Value << YAML::BeginMap << YAML::Key + << "foo" << YAML::Value << "bar" << YAML::EndMap << YAML::Newline + << YAML::Comment("nested comment outside of map2") << YAML::EndMap + << YAML::EndMap; + + ExpectEmit( + "map1:\n" + " map2:\n" + " foo: bar\n" + " # nested comment outside of map2"); +} + +TEST_F(EmitterTest, CommentInsideFlowMapIsUnaffected) { + out << YAML::BeginMap << YAML::Key << "some_map" << YAML::Value << YAML::Flow + << YAML::BeginMap << YAML::Key << "foo" << YAML::Value << "bar" + << YAML::Comment("comment") << YAML::Key << "key2" << YAML::Value + << "value2" << YAML::EndMap << YAML::EndMap; + + ExpectEmit( + "some_map: {foo: bar, # comment\n" + "key2: value2}"); +} + } // namespace } // namespace YAML