Fix closing brace indentation with --trimwhitespace nonblank-lines (#2477)

Co-authored-by: calda <1811727+calda@users.noreply.github.com>
This commit is contained in:
Copilot
2026-03-25 15:21:21 +11:00
committed by Cal Stephens
parent d798a8a5e3
commit d8245dbba7
2 changed files with 34 additions and 0 deletions
+10
View File
@@ -3301,6 +3301,16 @@ extension Formatter {
guard let lastNewlineIndex = lastIndex(of: .linebreak, in: Range(range.range)) else { break }
removeToken(at: lastNewlineIndex)
// If the removed linebreak was at the end of a blank line that had trailing
// whitespace (i.e. the preceding token is a space and the one before that is
// a linebreak), also remove the trailing whitespace so it doesn't end up
// incorrectly concatenated with the indent of the following token.
if token(at: lastNewlineIndex - 1)?.isSpace == true,
token(at: lastNewlineIndex - 2)?.isLinebreak == true
{
removeToken(at: lastNewlineIndex - 1)
}
}
}
@@ -208,4 +208,28 @@ final class BlankLinesAtEndOfScopeTests: XCTestCase {
"""
testFormatting(for: input, output, rule: .blankLinesAtEndOfScope, options: .init(typeBlankLines: .insert), exclude: [.blankLinesAtStartOfScope])
}
func testBlankLinesAtEndOfScopeRemovedWithTrailingWhitespace() {
// Blank line before closing brace that has trailing whitespace should be
// removed correctly without leaving the whitespace on the closing brace's line
let input = """
func foo() {
if let bar = bar {
bar()
}
\("")
}
"""
let output = """
func foo() {
if let bar = bar {
bar()
}
}
"""
let options = FormatOptions(truncateBlankLines: false)
testFormatting(for: input, output, rule: .blankLinesAtEndOfScope, options: options)
}
}