Insert line break before elvis when converting if to elvis

This ensures correct indentation
This commit is contained in:
Dmitry Jemerov
2017-12-21 17:09:25 +01:00
parent 6208c69c72
commit 3178dee759
3 changed files with 22 additions and 3 deletions
@@ -18,6 +18,8 @@ package org.jetbrains.kotlin.idea.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
@@ -70,7 +72,12 @@ class FoldInitializerAndIfToElvisIntention : SelfTargetingRangeIntention<KtIfExp
val commentSaver = CommentSaver(childRangeBefore)
val childRangeAfter = childRangeBefore.withoutLastStatement()
val elvis = factory.createExpressionByPattern("$0 ?: $1", initializer, ifNullExpr) as KtBinaryExpression
val pattern = if (element.then?.hasComments() == true)
"$0\n?: $1"
else
"$0 ?: $1"
val elvis = factory.createExpressionByPattern(pattern, initializer, ifNullExpr) as KtBinaryExpression
if (typeReference != null) {
elvis.left!!.replace(factory.createExpressionByPattern("$0 as? $1", initializer, typeReference))
}
@@ -86,6 +93,16 @@ class FoldInitializerAndIfToElvisIntention : SelfTargetingRangeIntention<KtIfExp
editor?.caretModel?.moveToOffset(newElvis.right!!.textOffset)
}
private fun PsiElement.hasComments(): Boolean {
var result = false
accept(object : KtTreeVisitorVoid() {
override fun visitComment(comment: PsiComment?) {
result = true
}
})
return result
}
private data class Data(
val initializer: KtExpression,
val declaration: KtVariableDeclaration,
@@ -1,5 +1,6 @@
fun foo(p: List<String?>): Int {
val v = p[0] ?: // return -1 if null
val v = p[0]
?: // return -1 if null
<caret>return -1
return v.length
}
@@ -1,5 +1,6 @@
fun foo(p: List<String?>): Int {
val v = p[0] ?: // v is null
val v = p[0]
?: // v is null
// we should do something with it
return -1 // let's return -1
// end of if