Skip to content

Commit

Permalink
Don't insert trailing commas over the max width
Browse files Browse the repository at this point in the history
  • Loading branch information
nreid260 committed Jun 4, 2024
1 parent 9a916b7 commit 388118a
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -107,15 +107,24 @@ object RedundantElementManager {
})

val result = StringBuilder(code)
val suggestionElements = trailingCommaSuggestor.getTrailingCommaSuggestions()

for (element in suggestionElements.sortedByDescending(PsiElement::endOffset)) {
result.insert(element.endOffset, ',')
}
trailingCommaSuggestor.getTrailingCommaSuggestions()
.asSequence()
.sortedByDescending(PsiElement::endOffset)
.filter {
// https://github.com/facebook/ktfmt/issues/472
it.endColumnZero() < options.maxWidth
}
.forEach { result.insert(it.endOffset, ',') }

return result.toString()
}

private fun PsiElement.endColumnZero(): Int {
val document = this.containingFile.viewProvider.document!!
val zeroLineNumber = document.getLineNumber(this.endOffset)
return this.endOffset - document.getLineStartOffset(zeroLineNumber)
}

private fun PsiElement?.containsNewline(): Boolean {
if (this !is PsiWhiteSpace) return false
return this.text.contains('\n')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1832,6 +1832,30 @@ class GoogleStyleFormatterKtTest {
assertThatFormatting(code).withOptions(Formatter.GOOGLE_FORMAT).isEqualTo(expected)
}

@Test
fun `trailing commas are not inserted over the max width`() =
assertFormatted(
"""
|//////////////////
|fun foo() {
| bar(
| someArg,
| justBeforeMax,
| )
| bar(
| someArg,
| exactlyAtMaaax
| )
| bar(
| someArg,
| justAfterMaaaax
| )
|}
|"""
.trimMargin(),
formattingOptions = Formatter.GOOGLE_FORMAT,
deduceMaxWidth = true)

companion object {
/** Triple quotes, useful to use within triple-quoted strings. */
private const val TQ = "\"\"\""
Expand Down

0 comments on commit 388118a

Please sign in to comment.