Skip to content

Commit

Permalink
feat: Improve code insertion in AutoDevInsertCodeAction
Browse files Browse the repository at this point in the history
- Replace `textToPaste` with `newText` to better represent the variable's purpose.
- Modify the logic to handle both selected text and no selection cases, ensuring the correct insertion point is used.
- Update the insertion and PSI file handling to work with the new `newText` variable.
- Ensure that the document is committed and reformatted correctly after insertion.
  • Loading branch information
phodal committed Mar 2, 2024
1 parent 1100f9b commit a1a63bb
Showing 1 changed file with 17 additions and 7 deletions.
Expand Up @@ -15,16 +15,26 @@ class AutoDevInsertCodeAction : DumbAwareAction() {
val project = e.project ?: return
val editor = e.getData(PlatformDataKeys.EDITOR) ?: return
val selectionModel = if (editor.selectionModel.hasSelection()) editor.selectionModel else null
val textToPaste = selectionModel?.selectedText ?: editor.document.text.trimEnd()
val newText = selectionModel?.selectedText ?: editor.document.text.trimEnd()

val textEditor = FileEditorManager.getInstance(project).selectedTextEditor ?: return
WriteCommandAction.writeCommandAction(project).compute<Any, RuntimeException> {
val offset: Int = textEditor.caretModel.offset
textEditor.document.insertString(offset, textToPaste)
val currentSelection = textEditor.selectionModel

val psiFile = PsiDocumentManager.getInstance(project).getPsiFile(textEditor.document) ?: return@compute
PsiDocumentManager.getInstance(project).commitDocument(textEditor.document)
CodeStyleManager.getInstance(project).reformatText(psiFile, offset, offset + textToPaste.length)
WriteCommandAction.writeCommandAction(project).compute<Any, RuntimeException> {
val offset: Int
val document = textEditor.document

if (currentSelection.hasSelection()) {
offset = currentSelection.selectionStart
document.replaceString(currentSelection.selectionStart, currentSelection.selectionEnd, newText)
} else {
offset = textEditor.caretModel.offset
document.insertString(offset, newText)
}

val psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document) ?: return@compute
PsiDocumentManager.getInstance(project).commitDocument(document)
CodeStyleManager.getInstance(project).reformatText(psiFile, offset, offset + newText.length)
}
}

Expand Down

0 comments on commit a1a63bb

Please sign in to comment.