Skip to content

Commit a1a63bb

Browse files
committed
feat: Improve code insertion in AutoDevInsertCodeAction
- 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.
1 parent 1100f9b commit a1a63bb

File tree

1 file changed

+17
-7
lines changed

1 file changed

+17
-7
lines changed

src/main/kotlin/cc/unitmesh/devti/gui/snippet/AutoDevInsertCodeAction.kt

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,16 +15,26 @@ class AutoDevInsertCodeAction : DumbAwareAction() {
1515
val project = e.project ?: return
1616
val editor = e.getData(PlatformDataKeys.EDITOR) ?: return
1717
val selectionModel = if (editor.selectionModel.hasSelection()) editor.selectionModel else null
18-
val textToPaste = selectionModel?.selectedText ?: editor.document.text.trimEnd()
18+
val newText = selectionModel?.selectedText ?: editor.document.text.trimEnd()
1919

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

25-
val psiFile = PsiDocumentManager.getInstance(project).getPsiFile(textEditor.document) ?: return@compute
26-
PsiDocumentManager.getInstance(project).commitDocument(textEditor.document)
27-
CodeStyleManager.getInstance(project).reformatText(psiFile, offset, offset + textToPaste.length)
23+
WriteCommandAction.writeCommandAction(project).compute<Any, RuntimeException> {
24+
val offset: Int
25+
val document = textEditor.document
26+
27+
if (currentSelection.hasSelection()) {
28+
offset = currentSelection.selectionStart
29+
document.replaceString(currentSelection.selectionStart, currentSelection.selectionEnd, newText)
30+
} else {
31+
offset = textEditor.caretModel.offset
32+
document.insertString(offset, newText)
33+
}
34+
35+
val psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document) ?: return@compute
36+
PsiDocumentManager.getInstance(project).commitDocument(document)
37+
CodeStyleManager.getInstance(project).reformatText(psiFile, offset, offset + newText.length)
2838
}
2939
}
3040

0 commit comments

Comments
 (0)