Skip to content

Commit 889d7e7

Browse files
Add check in AnchorIndentationFormattingRule to skip anchor for else-if on separate lines
Co-authored-by: CyrusNajmabadi <4564579+CyrusNajmabadi@users.noreply.github.com>
1 parent f74ab56 commit 889d7e7

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/AnchorIndentationFormattingRule.cs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
// See the LICENSE file in the project root for more information.
44

55
using System.Collections.Generic;
6+
using System.Linq;
7+
using Microsoft.CodeAnalysis.CSharp.Extensions;
68
using Microsoft.CodeAnalysis.CSharp.Syntax;
79
using Microsoft.CodeAnalysis.Formatting.Rules;
810

@@ -49,6 +51,24 @@ public override void AddAnchorIndentationOperations(List<AnchorIndentationOperat
4951
switch (node)
5052
{
5153
case StatementSyntax statement:
54+
// Don't add anchor indentation for if statements that are on a separate line from their else keyword.
55+
// The if statement should be indented like any other embedded statement in that case.
56+
if (statement is IfStatementSyntax ifStatement && ifStatement.Parent is ElseClauseSyntax elseClause)
57+
{
58+
var elseKeyword = elseClause.ElseKeyword;
59+
var ifKeyword = ifStatement.IfKeyword;
60+
61+
// Check if there's a newline between the else and if tokens
62+
var hasNewLine = elseKeyword.TrailingTrivia.Any(SyntaxKind.EndOfLineTrivia) ||
63+
ifKeyword.LeadingTrivia.Any(SyntaxKind.EndOfLineTrivia);
64+
65+
if (hasNewLine)
66+
{
67+
// Skip adding anchor operation - let the indent operation from IndentBlockFormattingRule apply
68+
return;
69+
}
70+
}
71+
5272
AddAnchorIndentationOperation(list, statement);
5373
return;
5474
case UsingDirectiveSyntax usingNode:

0 commit comments

Comments
 (0)