Which code deletes the editor selection when you type a character?

已回答

I've implemented a TypedHandlerDelegate in Kotlin like

internal class TypedHandler : TypedHandlerDelegate() {

override fun beforeCharTyped(c: Char, project: Project, editor: Editor, file: PsiFile, fileType: FileType): Result {

and it's working fine for cases where there is no selection (i.e. `editor.caretModel.primaryCaret.hasSelection()` returns false).

I noticed that, when there is a selection and I type a character, then 

PsiDocumentManager.getInstance(project).getDocument(file)!!.text

and 

file.viewProvider.findElementAt(primaryCaret.offset - 1).text

return different values when called in my `beforeCharTyped` method. I've read that the PSI and the document may not agree. Up until now, it hasn't been an issue, but my plugin depends on these two values being the same.

While I would love to learn more about the mechanism behind the difference between the two, I think in this scenario, I hope too resolve my problem by overriding whatever action is removing the selected text. It doesn't seem to have anything to do with the `TypedHandlerDelegate` because I overrode that. Which code is causing the editor to remove the selected text when a character is typed? Is there another delegate I can create to override the behavior of deleting the selected text when a character is typed?

0

 

There are many places where the text is deleted. Editor Actions that delete a character/word/ling, will delete the selection, including backspace and delete character actions.

Your expectation for TypedHandleDelegate needs to be adjusted for how it really works and the complexity of working with editors and Psi at the same time.

The methods are called before the character is typed, then after the character is typed, with whatever changes that occurred in between.

The Psi of the file is not yet adjusted when the charTyped method is called. Rapid typing can cause the the PSI to not update for several keystrokes, so it is not always off by 1 character. 

In my plugin, in the beforeCharTyped method, I stash whatever information will be helpful in determining the offset changes in the Psi vs document text, and use them to adjust operations in charTyped(). It is implemented as a collection of classes to help deal with all the differences in handling various PSI elements and house keeping to cleanup after the handler. The complexity is dictated by how complex are the  manipulations and what information needs to be extracted from the outdated PSI.

It is a PITA to debug and maintain.

0

请先登录再写评论。