From 60796c2e8925287d37d05c505ac96a021b60cf5a Mon Sep 17 00:00:00 2001 From: Nick Lockwood Date: Wed, 29 Jul 2020 16:11:07 +0100 Subject: [PATCH] Take maxwidth into account when unwrapping braces --- Sources/Rules.swift | 17 ++++++++++++++++- Tests/RulesTests.swift | 2 +- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/Sources/Rules.swift b/Sources/Rules.swift index ecd4e8ee..3d96135b 100644 --- a/Sources/Rules.swift +++ b/Sources/Rules.swift @@ -1399,7 +1399,7 @@ public struct _FormatRules { public let braces = FormatRule( help: "Wrap braces in accordance with selected style (K&R or Allman).", options: ["allman"], - sharedOptions: ["linebreaks"] + sharedOptions: ["linebreaks", "maxwidth", "indent", "tabwidth"] ) { formatter in formatter.forEach(.startOfScope("{")) { i, _ in guard let closingBraceIndex = formatter.endOfScope(at: i), @@ -1442,6 +1442,21 @@ public struct _FormatRules { !formatter.tokens[prevIndex].isComment else { return } + let maxWidth = formatter.options.maxWidth + if maxWidth == 0 { + // Check that brace doesn't have inline content after it + guard formatter.next(.nonSpace, after: i)?.isLinebreak == true else { + return + } + } else { + // Check that unwrapping wouldn't exceed line length + let endOfLine = formatter.endOfLine(at: i) + let length = formatter.lineLength(from: i, upTo: endOfLine) + let prevLineLength = formatter.lineLength(at: prevIndex) + guard prevLineLength + length + 1 <= maxWidth else { + return + } + } formatter.replaceTokens(inRange: prevIndex + 1 ..< i, with: [.space(" ")]) } } diff --git a/Tests/RulesTests.swift b/Tests/RulesTests.swift index e68443b5..bdb9cbd5 100644 --- a/Tests/RulesTests.swift +++ b/Tests/RulesTests.swift @@ -8082,7 +8082,7 @@ class RulesTests: XCTestCase { true } """ - let options = FormatOptions(allmanBraces: true, maxWidth: 20) + let options = FormatOptions(maxWidth: 20) testFormatting(for: input, [output, output2], rules: [FormatRules.wrap], options: options) }