diff --git a/Sources/Rules.swift b/Sources/Rules.swift index 070134580..e1fb9400c 100644 --- a/Sources/Rules.swift +++ b/Sources/Rules.swift @@ -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) } diff --git a/Tests/RulesTests+Indentation.swift b/Tests/RulesTests+Indentation.swift index 088becfb9..4f7525293 100644 --- a/Tests/RulesTests+Indentation.swift +++ b/Tests/RulesTests+Indentation.swift @@ -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() {