Index: clang/lib/Format/TokenAnnotator.h =================================================================== --- clang/lib/Format/TokenAnnotator.h +++ clang/lib/Format/TokenAnnotator.h @@ -31,6 +31,7 @@ LT_PreprocessorDirective, LT_VirtualFunctionDecl, LT_ArrayOfStructInitializer, + LT_CommentAbovePPDirective, }; class AnnotatedLine { Index: clang/lib/Format/TokenAnnotator.cpp =================================================================== --- clang/lib/Format/TokenAnnotator.cpp +++ clang/lib/Format/TokenAnnotator.cpp @@ -2696,15 +2696,18 @@ NextNonCommentLine->First->NewlinesBefore <= 1 && NextNonCommentLine->First->OriginalColumn == Line->First->OriginalColumn) { + const bool PPDirectiveOrImportStmt = + NextNonCommentLine->Type == LT_PreprocessorDirective || + NextNonCommentLine->Type == LT_ImportStatement; + if (PPDirectiveOrImportStmt) + Line->Type = LT_CommentAbovePPDirective; // Align comments for preprocessor lines with the # in column 0 if // preprocessor lines are not indented. Otherwise, align with the next // line. - Line->Level = - (Style.IndentPPDirectives != FormatStyle::PPDIS_BeforeHash && - (NextNonCommentLine->Type == LT_PreprocessorDirective || - NextNonCommentLine->Type == LT_ImportStatement)) - ? 0 - : NextNonCommentLine->Level; + Line->Level = Style.IndentPPDirectives != FormatStyle::PPDIS_BeforeHash && + PPDirectiveOrImportStmt + ? 0 + : NextNonCommentLine->Level; } else { NextNonCommentLine = Line->First->isNot(tok::r_brace) ? Line : nullptr; } Index: clang/lib/Format/UnwrappedLineFormatter.cpp =================================================================== --- clang/lib/Format/UnwrappedLineFormatter.cpp +++ clang/lib/Format/UnwrappedLineFormatter.cpp @@ -60,7 +60,9 @@ // Update the indent level cache size so that we can rely on it // having the right size in adjustToUnmodifiedline. skipLine(Line, /*UnknownIndent=*/true); - if (Line.InPPDirective) { + if (Line.InPPDirective || + (Style.IndentPPDirectives == FormatStyle::PPDIS_BeforeHash && + Line.Type == LT_CommentAbovePPDirective)) { unsigned IndentWidth = (Style.PPIndentWidth >= 0) ? Style.PPIndentWidth : Style.IndentWidth; Indent = Line.Level * IndentWidth + AdditionalIndent; Index: clang/unittests/Format/FormatTest.cpp =================================================================== --- clang/unittests/Format/FormatTest.cpp +++ clang/unittests/Format/FormatTest.cpp @@ -4954,6 +4954,25 @@ " int y = 0;\n" "}\n", style); + verifyFormat("#if 1\n" + " // some comments\n" + " // another\n" + " #define foo 1\n" + "// not a define comment\n" + "void bar() {\n" + " // comment\n" + " int y = 0;\n" + "}", + "#if 1\n" + "// some comments\n" + "// another\n" + "#define foo 1\n" + "// not a define comment\n" + "void bar() {\n" + " // comment\n" + " int y = 0;\n" + "}", + style); } TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) {