Skip to content

Commit 7400e1d

Browse files
committed
Fix indentation when there is a leading new line
1 parent 950dba9 commit 7400e1d

File tree

3 files changed

+250
-228
lines changed

3 files changed

+250
-228
lines changed

Sources/SwiftSyntax/Syntax.swift

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -323,7 +323,23 @@ public extension SyntaxProtocol {
323323
/// Returns a new syntax node with its leading trivia replaced
324324
/// by the provided trivia.
325325
func withLeadingTrivia(_ leadingTrivia: Trivia) -> Self {
326-
return Self(Syntax(data.withLeadingTrivia(leadingTrivia)))!
326+
var leadingTrivia: [TriviaPiece] = leadingTrivia.pieces
327+
328+
// If there is 3 or more, then we see if the first two is a newline and a space
329+
// If so, we need to replace add the correct amount of space after each newline
330+
// comming after to have the right indentation of the code.
331+
if leadingTrivia.count > 2,
332+
case .newlines = leadingTrivia[0],
333+
case .spaces(let spaces) = leadingTrivia[1] {
334+
335+
for i in (2..<leadingTrivia.count).reversed() {
336+
if case .newlines = leadingTrivia[i] {
337+
leadingTrivia.insert(.spaces(spaces), at: i + 1)
338+
}
339+
}
340+
}
341+
342+
return Self(Syntax(data.withLeadingTrivia(Trivia(pieces: leadingTrivia))))!
327343
}
328344

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

0 commit comments

Comments
 (0)