IDE: Extract Method
[IU]
This example extracts a range of statements into a new method,

```kotlin
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.refactoring.extractMethod.ExtractMethodHandler
import com.intellij.refactoring.extractMethod.ExtractMethodProcessor

// Configuration - modify these for your use case
val filePath = "/path/to/your/File.java" // TODO: Set your file path
val startLine = 10 // TODO: 1-based start line of selection
val endLine = 12   // TODO: 1-based end line of selection
val newMethodName = "extractedMethod"  // TODO: Set the new method name
val dryRun = true


val (psiFile, document) = readAction {
    val virtualFile = findFile(filePath) ?: return@readAction null to null
    val psi = PsiManager.getInstance(project).findFile(virtualFile)
    val doc = FileDocumentManager.getInstance().getDocument(virtualFile)
    psi to doc
}

if (psiFile == null || document == null) {
    println("File not found or no document: $filePath")
    return
}

val editor = withContext(Dispatchers.EDT) {
    EditorFactory.getInstance().createEditor(document, project)
}
try {
    val startOffset = document.getLineStartOffset(startLine - 1)
    val endOffset = document.getLineEndOffset(endLine - 1)

    val statements = readAction {
        PsiTreeUtil.collectElements(psiFile) { element ->
            element is PsiStatement &&
                element.textRange.startOffset >= startOffset &&
                element.textRange.endOffset <= endOffset
        }.filterIsInstance<PsiStatement>().toTypedArray()
    }

    if (statements.isEmpty()) {
        println("No statements found in the specified line range.")
        return
    }

    val processor = ExtractMethodProcessor(
        project,
        editor,
        statements,
        null,
        "Extract Method",
        newMethodName,
        null
    )
    processor.setShowErrorDialogs(false)
    val prepared = readAction { processor.prepare() }
    if (!prepared) {
        println("Extract method preparation failed.")
        return
    }
    processor.setMethodName(newMethodName)
    readAction {
        processor.prepareVariablesAndName()
        processor.prepareNullability()
    }

    if (dryRun) {
        println("Extract method prepared for $filePath ($startLine-$endLine).")
        println("Set dryRun=false to apply changes.")
        return
    }

    writeIntentReadAction { ExtractMethodHandler.extractMethod(project, processor) }

    println("Extracted method: $newMethodName")
} finally {
    withContext(Dispatchers.EDT) {
        EditorFactory.getInstance().releaseEditor(editor)
    }
}
```

# See also

- [Code Action](mcp-steroid://lsp/code-action) - Quick fixes and refactorings
- [Rename](mcp-steroid://lsp/rename) - Rename symbol across project
- [IntelliJ API Power User Guide](mcp-steroid://prompt/skill) - Core API patterns
