Take maxwidth into account when unwrapping braces

This commit is contained in:
Nick Lockwood
2020-07-30 01:38:56 +01:00
parent e4241a2acc
commit 60796c2e89
2 changed files with 17 additions and 2 deletions
+16 -1
View File
@@ -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(" ")])
}
}
+1 -1
View File
@@ -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)
}