Skip to content

Commit

Permalink
Fix broken indent inside #ifdef after comment
Browse files Browse the repository at this point in the history
  • Loading branch information
nicklockwood committed Sep 29, 2023
1 parent 8069c6e commit 57321f7
Show file tree
Hide file tree
Showing 2 changed files with 101 additions and 1 deletion.
2 changes: 1 addition & 1 deletion Sources/Rules.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1931,7 +1931,7 @@ public struct _FormatRules {
if let startToken = startToken, [
.startOfScope("#if"), .keyword("#else"), .keyword("#elseif"), .endOfScope("#endif")
].contains(startToken) {
if let index = formatter.index(of: .nonSpaceOrLinebreak, before: lineStart) {
if let index = formatter.index(of: .nonSpaceOrCommentOrLinebreak, before: lineStart) {
lastNonSpaceOrLinebreakIndex = index
lineStart = formatter.startOfLine(at: lastNonSpaceOrLinebreakIndex, excludingIndent: true)
}
Expand Down
100 changes: 100 additions & 0 deletions Tests/RulesTests+Indentation.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2776,6 +2776,106 @@ class IndentTests: RulesTests {
testFormatting(for: input, rule: FormatRules.indent)
}

// indent #if/#else/#elseif/#endif

func testIfDefIndentModes() {
let input = """
struct ContentView: View {
var body: some View {
// swiftformat:options --ifdef indent
Text("Hello, world!")
// Comment above
#if os(macOS)
.padding()
#endif
Text("Hello, world!")
#if os(macOS)
// Comment inside
.padding()
#endif
// swiftformat:options --ifdef no-indent
Text("Hello, world!")
// Comment above
#if os(macOS)
.padding()
#endif
Text("Hello, world!")
#if os(macOS)
// Comment inside
.padding()
#endif
// swiftformat:options --ifdef outdent
Text("Hello, world!")
// Comment above
#if os(macOS)
.padding()
#endif
Text("Hello, world!")
#if os(macOS)
// Comment inside
.padding()
#endif
}
}
"""
let output = """
struct ContentView: View {
var body: some View {
// swiftformat:options --ifdef indent
Text("Hello, world!")
// Comment above
#if os(macOS)
.padding()
#endif
Text("Hello, world!")
#if os(macOS)
// Comment inside
.padding()
#endif
// swiftformat:options --ifdef no-indent
Text("Hello, world!")
// Comment above
#if os(macOS)
.padding()
#endif
Text("Hello, world!")
#if os(macOS)
// Comment inside
.padding()
#endif
// swiftformat:options --ifdef outdent
Text("Hello, world!")
// Comment above
#if os(macOS)
.padding()
#endif
Text("Hello, world!")
#if os(macOS)
// Comment inside
.padding()
#endif
}
}
"""
testFormatting(for: input, output, rule: FormatRules.indent)
}

// indent #if/#else/#elseif/#endif (mode: indent)

func testIfEndifIndenting() {
Expand Down

0 comments on commit 57321f7

Please sign in to comment.