Index: clang/lib/Format/UnwrappedLineParser.cpp =================================================================== --- clang/lib/Format/UnwrappedLineParser.cpp +++ clang/lib/Format/UnwrappedLineParser.cpp @@ -2587,10 +2587,13 @@ FormatTok->setFinalizedType(TT_ElseLBrace); ElseLeftBrace = FormatTok; CompoundStatementIndenter Indenter(this, Style, Line->Level); - if (parseBlock(/*MustBeDeclaration=*/false, /*AddLevels=*/1u, - /*MunchSemi=*/true, - KeepElseBraces) == IfStmtKind::IfOnly) { - Kind = IfStmtKind::IfElseIf; + const IfStmtKind ElseBlockKind = + parseBlock(/*MustBeDeclaration=*/false, /*AddLevels=*/1u, + /*MunchSemi=*/true, KeepElseBraces); + if ((ElseBlockKind == IfStmtKind::IfOnly || + ElseBlockKind == IfStmtKind::IfElseIf) && + FormatTok->is(tok::kw_else)) { + KeepElseBraces = true; } addUnwrappedLine(); } else if (FormatTok->is(tok::kw_if)) { Index: clang/unittests/Format/FormatTest.cpp =================================================================== --- clang/unittests/Format/FormatTest.cpp +++ clang/unittests/Format/FormatTest.cpp @@ -25349,6 +25349,30 @@ "}", Style); + verifyFormat("if (a)\n" + " if (b)\n" + " c;\n" + " else {\n" + " if (d)\n" + " e;\n" + " }\n" + "else\n" + " f;", + Style); + + verifyFormat("if (a)\n" + " if (b)\n" + " c;\n" + " else {\n" + " if (d)\n" + " e;\n" + " else if (f)\n" + " g;\n" + " }\n" + "else\n" + " h;", + Style); + verifyFormat("if (a)\n" " b;\n" "else if (c)\n"