Skip to content

Commit bd98242

Browse files
committed
Fix indentation when there is a leading new line
1 parent 410c9e0 commit bd98242

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
@@ -327,7 +327,23 @@ public extension SyntaxProtocol {
327327
/// Returns a new syntax node with its leading trivia replaced
328328
/// by the provided trivia.
329329
func withLeadingTrivia(_ leadingTrivia: Trivia) -> Self {
330-
return Self(Syntax(data.withLeadingTrivia(leadingTrivia)))!
330+
var leadingTrivia: [TriviaPiece] = leadingTrivia.pieces
331+
332+
// If there is 3 or more, then we see if the first two is a newline and a space
333+
// If so, we need to replace add the correct amount of space after each newline
334+
// comming after to have the right indentation of the code.
335+
if leadingTrivia.count > 2,
336+
case .newlines = leadingTrivia[0],
337+
case .spaces(let spaces) = leadingTrivia[1] {
338+
339+
for i in (2..<leadingTrivia.count).reversed() {
340+
if case .newlines = leadingTrivia[i] {
341+
leadingTrivia.insert(.spaces(spaces), at: i + 1)
342+
}
343+
}
344+
}
345+
346+
return Self(Syntax(data.withLeadingTrivia(Trivia(pieces: leadingTrivia))))!
331347
}
332348

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

0 commit comments

Comments
 (0)