After inserting PsiElement, there is no automatic line break (kts)


class BuildGradleKtsTest : BasePlatformTestCase() {

    override fun getTestDataPath(): String {
        return "src/test/testData/project"
    }

    fun testAddAliyunMirrorImage() {
        val ktFile = myFixture.configureByText(
            "build.gradle.kts",
            """
                allprojects {
                    repositories {
                        google()
                        mavenCentral()
                    }
                }
            """.trimIndent(),
        ) as KtFile


        val ktCalls = PsiTreeUtil.findChildrenOfType(ktFile, KtCallExpression::class.java)
        val findRepo = ktCalls.find { it.calleeExpression?.text == "repositories" }
        assertNotNull(findRepo != null)
        findRepo ?: return


        val factory = MyKotlinPsiElementFactory(project)
        val ktFunLit = findRepo.lambdaArguments.firstOrNull()?.getLambdaExpression()?.functionLiteral
        assert(ktFunLit != null)
        if (ktFunLit != null) {
            val block = ktFunLit.bodyExpression ?: return
            val ele = aliyunGradleMirrorImages.map(factory::createCallExpression)
            val last = block.statements.lastOrNull() ?: return

            WriteCommandAction.runWriteCommandAction(project) {
//                ele.forEach(block::add)
                ele.forEach {
                    block.addAfter(it, last)
                }
            }
            println(ktFile.text)
        }

    }

}

this is psi tree

After insertion, if it’s successful but doesn’t automatically wrap, is there an API that can automatically handle this situation?

Is the content you created still valid syntax? If it is, then try to apply formatting.

Otherwise, you need to insert linebreak PSI elements, too.