diff --git a/clang/lib/Format/BreakableToken.cpp b/clang/lib/Format/BreakableToken.cpp index db7361bf5f2ff..94bd9823e1f5a 100644 --- a/clang/lib/Format/BreakableToken.cpp +++ b/clang/lib/Format/BreakableToken.cpp @@ -785,7 +785,16 @@ BreakableLineCommentSection::BreakableLineCommentSection( Lines[i].substr(IndentPrefix.size(), FirstCharByteSize), Encoding) != 1) return false; - if (FirstCommentChar == '#') + // In C-like comments, add a space before #. For example this is useful + // to preserve the relative indentation when commenting out code with + // #includes. + // + // In languages using # as the comment leader such as proto, don't + // add a space to support patterns like: + // ######### + // # section + // ######### + if (FirstCommentChar == '#' && !TokenText.startswith("#")) return false; return FirstCommentChar == '\\' || isPunctuation(FirstCommentChar) || isHorizontalWhitespace(FirstCommentChar); diff --git a/clang/unittests/Format/FormatTestTextProto.cpp b/clang/unittests/Format/FormatTestTextProto.cpp index 44b67d275bcc3..10a43c1519d6d 100644 --- a/clang/unittests/Format/FormatTestTextProto.cpp +++ b/clang/unittests/Format/FormatTestTextProto.cpp @@ -408,6 +408,23 @@ TEST_F(FormatTestTextProto, UnderstandsHashComments) { "dd: 100\n" "#### another quadriple-hash comment\n", Style)); + + // Ensure we support a common pattern for naming sections. + EXPECT_EQ("##############\n" + "# section name\n" + "##############", + format("##############\n" + "# section name\n" + "##############", + Style)); + + EXPECT_EQ("///////////////\n" + "// section name\n" + "///////////////", + format("///////////////\n" + "// section name\n" + "///////////////", + Style)); } TEST_F(FormatTestTextProto, FormatsExtensions) {