|
| 1 | +package cc.unitmesh.cpp.provider |
| 2 | + |
| 3 | +import cc.unitmesh.devti.context.builder.CodeModifier |
| 4 | +import com.intellij.lang.Language |
| 5 | +import com.intellij.openapi.command.WriteCommandAction |
| 6 | +import com.intellij.openapi.project.Project |
| 7 | +import com.intellij.openapi.vfs.VirtualFile |
| 8 | +import com.intellij.psi.PsiManager |
| 9 | +import com.jetbrains.cidr.execution.debugger.OCDebuggerTypesHelper |
| 10 | +import com.jetbrains.cidr.lang.OCLanguage |
| 11 | +import com.jetbrains.cidr.lang.parser.OCElementType |
| 12 | +import com.jetbrains.cidr.lang.psi.OCFile |
| 13 | +import com.jetbrains.cidr.lang.util.OCElementFactory |
| 14 | + |
| 15 | +class CppCodeModifier : CodeModifier { |
| 16 | + override fun isApplicable(language: Language): Boolean = language is OCLanguage |
| 17 | + |
| 18 | + override fun insertTestCode(sourceFile: VirtualFile, project: Project, code: String): Boolean { |
| 19 | + val isExit = sourceFile as? OCFile |
| 20 | + if (isExit == null) { |
| 21 | + insertClass(sourceFile, project, code) |
| 22 | + return true |
| 23 | + } |
| 24 | + |
| 25 | + insertMethod(sourceFile, project, code) |
| 26 | + return true |
| 27 | + } |
| 28 | + |
| 29 | + override fun insertMethod(sourceFile: VirtualFile, project: Project, code: String): Boolean { |
| 30 | + val file = sourceFile as OCFile |
| 31 | + val psiElement = file.lastChild |
| 32 | + |
| 33 | + val codeElement = OCElementFactory.expressionOrStatementsCodeFragment(code, project, file, true, false) |
| 34 | + |
| 35 | + com.intellij.openapi.application.runReadAction { |
| 36 | + psiElement?.parent?.addAfter(codeElement, psiElement) |
| 37 | + } |
| 38 | + |
| 39 | + return true |
| 40 | + } |
| 41 | + |
| 42 | + override fun insertClass(sourceFile: VirtualFile, project: Project, code: String): Boolean { |
| 43 | + WriteCommandAction.runWriteCommandAction(project) { |
| 44 | + val psiFile = PsiManager.getInstance(project).findFile(sourceFile) as OCFile |
| 45 | + val document = psiFile.viewProvider.document!! |
| 46 | + document.insertString(document.textLength, code) |
| 47 | + } |
| 48 | + |
| 49 | + return true |
| 50 | + } |
| 51 | +} |
0 commit comments