From dbcf796e90b7ec8180222739d47efdf458a3306a Mon Sep 17 00:00:00 2001 From: Kirill Rakhman Date: Wed, 10 May 2017 10:49:08 +0200 Subject: [PATCH] Add Smart Enter processor for object expessions (#1079) Fixes #KT-17807 --- .../editor/fixers/KotlinClassBodyFixer.kt | 18 ++++++++--- .../codeInsight/smartEnter/SmartEnterTest.kt | 32 +++++++++++++++++++ 2 files changed, 45 insertions(+), 5 deletions(-) diff --git a/idea/src/org/jetbrains/kotlin/idea/editor/fixers/KotlinClassBodyFixer.kt b/idea/src/org/jetbrains/kotlin/idea/editor/fixers/KotlinClassBodyFixer.kt index 03f8f3e3480..5b56dec68c6 100644 --- a/idea/src/org/jetbrains/kotlin/idea/editor/fixers/KotlinClassBodyFixer.kt +++ b/idea/src/org/jetbrains/kotlin/idea/editor/fixers/KotlinClassBodyFixer.kt @@ -22,18 +22,26 @@ import com.intellij.psi.PsiElement import org.jetbrains.kotlin.idea.editor.KotlinSmartEnterHandler import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.psiUtil.endOffset +import org.jetbrains.kotlin.psi.psiUtil.getPrevSiblingIgnoringWhitespaceAndComments class KotlinClassBodyFixer : SmartEnterProcessorWithFixers.Fixer() { override fun apply(editor: Editor, processor: KotlinSmartEnterHandler, psiElement: PsiElement) { if (psiElement !is KtClassOrObject) return - if (psiElement.getBody() != null) return - val doc = editor.document - val endOffset = psiElement.range.end + val body = psiElement.getBody() + if (!body?.text.isNullOrBlank()) return - editor.caretModel.moveToOffset(psiElement.endOffset - 1) + var endOffset = psiElement.range.end + + if (body != null) { + body.getPrevSiblingIgnoringWhitespaceAndComments()?.let { + endOffset = it.endOffset + } + } + + editor.caretModel.moveToOffset(endOffset - 1) // Insert '\n' to force a multiline body, otherwise there will be an empty body on one line and a caret on the next one. - doc.insertString(endOffset, "{\n}") + editor.document.insertString(endOffset, "{\n}") } } \ No newline at end of file diff --git a/idea/tests/org/jetbrains/kotlin/idea/codeInsight/smartEnter/SmartEnterTest.kt b/idea/tests/org/jetbrains/kotlin/idea/codeInsight/smartEnter/SmartEnterTest.kt index d26a729e017..33a04a0777d 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/codeInsight/smartEnter/SmartEnterTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/codeInsight/smartEnter/SmartEnterTest.kt @@ -1380,6 +1380,38 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { """ ) + fun testObjectExpressionBody1() = doFileTest( + """ + interface I + val a = object : I + """ + , + """ + interface I + val a = object : I { + + } + """ + ) + + fun testObjectExpressionBody2() = doFileTest( + """ + interface I + val a = object : I + + val b = "" + """ + , + """ + interface I + val a = object : I { + + } + + val b = "" + """ + ) + fun doFunTest(before: String, after: String) { fun String.withFunContext(): String { val bodyText = "//----\n${this.trimIndent()}\n//----"