Fixed Convert to foreach intention loosing comments

This commit is contained in:
Valentin Kipyatkov
2015-05-23 15:20:57 +03:00
parent 0f36458d2e
commit 333445d93e
9 changed files with 149 additions and 16 deletions
@@ -17,11 +17,14 @@
package org.jetbrains.kotlin.idea.intentions
import com.intellij.openapi.editor.Editor
import org.jetbrains.kotlin.lexer.JetTokens
import org.jetbrains.kotlin.psi.JetBlockExpression
import org.jetbrains.kotlin.psi.JetForExpression
import org.jetbrains.kotlin.psi.JetPsiFactory
import org.jetbrains.kotlin.psi.createExpressionByPattern
import org.jetbrains.kotlin.psi.psiUtil.contentRange
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.getText
public class ConvertToForEachFunctionCallIntention : JetSelfTargetingIntention<JetForExpression>(javaClass(), "Replace with a forEach function call") {
override fun isApplicableTo(element: JetForExpression, caretOffset: Int): Boolean {
@@ -35,7 +38,15 @@ public class ConvertToForEachFunctionCallIntention : JetSelfTargetingIntention<J
val loopParameter = element.getLoopParameter()!!
val functionBodyText = when (body) {
is JetBlockExpression -> body.getStatements().map { it.getText() }.joinToString("\n")
is JetBlockExpression -> {
val content = body.contentRange()
val text = content.getText()
if (content.last?.getNode()?.getElementType() == JetTokens.EOL_COMMENT)
text + "\n"
else
text
}
else -> body.getText()
}
@@ -143,8 +143,8 @@ public class InvertIfConditionIntention : JetSelfTargetingIntention<JetIfExpress
if (thenBranch is JetBlockExpression) {
val range = thenBranch.contentRange()
if (range != null) {
parent.addRangeAfter(range.first, range.second, ifExpression)
if (!range.isEmpty) {
parent.addRangeAfter(range.first, range.last, ifExpression)
parent.addAfter(factory.createNewLine(), ifExpression)
}
}
@@ -155,14 +155,6 @@ public class InvertIfConditionIntention : JetSelfTargetingIntention<JetIfExpress
return ifExpression
}
private fun JetBlockExpression.contentRange(): Pair<PsiElement, PsiElement>? {
val first = getLBrace()?.siblings(withItself = false)?.firstOrNull { it !is PsiWhiteSpace } ?: return null
val rBrace = getRBrace()
if (first == rBrace) return null
val last = rBrace!!.siblings(forward = false, withItself = false).first { it !is PsiWhiteSpace }
return Pair(first, last)
}
private fun exitStatementExecutedAfter(expression: JetExpression): JetExpression? {
val parent = expression.getParent()
if (parent is JetBlockExpression) {