Skip to content

Commit

Permalink
Fix double indentation in Elvis chains
Browse files Browse the repository at this point in the history
  • Loading branch information
nreid260 committed Sep 13, 2023
1 parent 17d80bf commit d7c166f
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 12 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -1207,20 +1207,31 @@ class KotlinInputAstVisitor(
val leftMostExpression = parts.first()
visit(leftMostExpression.left)
for (leftExpression in parts) {
when (leftExpression.operationToken) {
KtTokens.RANGE -> {}
KtTokens.ELVIS -> builder.breakOp(Doc.FillMode.INDEPENDENT, " ", expressionBreakIndent)
else -> builder.space()
}
builder.token(leftExpression.operationReference.text)
val isFirst = leftExpression === leftMostExpression
if (isFirst) {
builder.open(expressionBreakIndent)
}

when (leftExpression.operationToken) {
KtTokens.RANGE -> {}
KtTokens.ELVIS -> builder.space()
else -> builder.breakOp(Doc.FillMode.UNIFIED, " ", ZERO)
KtTokens.RANGE -> {
if (isFirst) {
builder.open(expressionBreakIndent)
}
builder.token(leftExpression.operationReference.text)
}
KtTokens.ELVIS -> {
if (isFirst) {
builder.open(expressionBreakIndent)
}
builder.breakOp(Doc.FillMode.UNIFIED, " ", ZERO)
builder.token(leftExpression.operationReference.text)
builder.space()
}
else -> {
builder.space()
if (isFirst) {
builder.open(expressionBreakIndent)
}
builder.token(leftExpression.operationReference.text)
builder.breakOp(Doc.FillMode.UNIFIED, " ", ZERO)
}
}
visit(leftExpression.right)
}
Expand Down
46 changes: 46 additions & 0 deletions core/src/test/java/com/facebook/ktfmt/format/FormatterTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4379,6 +4379,52 @@ class FormatterTest {
.trimMargin(),
deduceMaxWidth = true)

@Test
fun `chain of Elvis operator`() =
assertFormatted(
"""
|---------------------------
|fun f() {
| return option1()
| ?: option2()
| ?: option3()
| ?: option4()
| ?: option5()
|}
|"""
.trimMargin(),
deduceMaxWidth = true)

@Test
fun `Elvis operator mixed with plus operator breaking on plus`() =
assertFormatted(
"""
|------------------------
|fun f() {
| return option1()
| ?: option2() +
| option3()
| ?: option4() +
| option5()
|}
|"""
.trimMargin(),
deduceMaxWidth = true)

@Test
fun `Elvis operator mixed with plus operator breaking on elvis`() =
assertFormatted(
"""
|---------------------------------
|fun f() {
| return option1()
| ?: option2() + option3()
| ?: option4() + option5()
|}
|"""
.trimMargin(),
deduceMaxWidth = true)

@Test
fun `handle comments in the middle of calling chain`() =
assertFormatted(
Expand Down

0 comments on commit d7c166f

Please sign in to comment.