Skip to content

Commit 52a5a31

Browse files
committed
Fix indentation when there is a leading new line
1 parent 2380374 commit 52a5a31

File tree

1 file changed

+17
-1
lines changed

1 file changed

+17
-1
lines changed

Sources/SwiftSyntax/Syntax.swift

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -355,7 +355,23 @@ public extension SyntaxProtocol {
355355
/// Returns a new syntax node with its leading trivia replaced
356356
/// by the provided trivia.
357357
func withLeadingTrivia(_ leadingTrivia: Trivia) -> Self {
358-
return Self(Syntax(data.withLeadingTrivia(leadingTrivia)))!
358+
var leadingTrivia: [TriviaPiece] = leadingTrivia.pieces
359+
360+
// If there is 3 or more, then we see if the first two is a newline and a space
361+
// If so, we need to replace add the correct amount of space after each newline
362+
// comming after to have the right indentation of the code.
363+
if leadingTrivia.count > 2,
364+
case .newlines = leadingTrivia[0],
365+
case .spaces(let spaces) = leadingTrivia[1] {
366+
367+
for i in (2..<leadingTrivia.count).reversed() {
368+
if case .newlines = leadingTrivia[i] {
369+
leadingTrivia.insert(.spaces(spaces), at: i + 1)
370+
}
371+
}
372+
}
373+
374+
return Self(Syntax(data.withLeadingTrivia(Trivia(pieces: leadingTrivia))))!
359375
}
360376

361377
/// Returns a new syntax node with its trailing trivia replaced

0 commit comments

Comments
 (0)