Demonstrate correct way of registering typed handlers

This commit is contained in:
Dmitry Jemerov 2020-01-03 18:15:24 +01:00
parent 0807d3c364
commit 6b2882911f
3 changed files with 13 additions and 24 deletions

View File

@ -14,20 +14,6 @@ import org.jetbrains.annotations.NotNull;
* @see com.intellij.openapi.actionSystem.AnAction
*/
public class EditorHandlerIllustration extends AnAction {
/**
* This block of static code does not pertain to this class.
* It registers the custom MyTypedHandler, a TypedActionHandler
* that handles actions activated by typing in the editor.
* This registration code just needs to appear in a class (like AnAction class)
* that gets instantiated as part of IntelliJ startup.
*/
static {
final EditorActionManager actionManager = EditorActionManager.getInstance();
final TypedAction typedAction = actionManager.getTypedAction();
typedAction.setupHandler(new MyTypedHandler());
}
/**
* Clones a new caret at a higher Logical Position line number.
* @param e Event related to this action

View File

@ -2,31 +2,30 @@
package org.intellij.sdk.editor;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.codeInsight.editorActions.TypedHandlerDelegate;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.editor.actionSystem.TypedActionHandler;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiFile;
import org.jetbrains.annotations.NotNull;
/**
* This is a custom TypedActionHandler that handles actions activated
* This is a custom TypedHandlerDelegate that handles actions activated
* keystrokes in the editor.
* The execute method inserts a fixed string at Offset 0 of the document.
* Document changes are made in the context of a write action.
* MyTypedHandler is registered by static code in the EditorHandlerIllustration class.
*
* @see com.intellij.openapi.editor.actionSystem.TypedActionHandler
*/
class MyTypedHandler implements TypedActionHandler {
class MyTypedHandler extends TypedHandlerDelegate {
@NotNull
@Override
public void execute(@NotNull Editor editor, char c, @NotNull DataContext dataContext) {
public Result charTyped(char c, @NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) {
// Get the document and project
final Document document = editor.getDocument();
final Project project = editor.getProject();
// Construct the runnable to substitute the string at offset 0 in the document
Runnable runnable = () -> document.insertString(0, "editor_basics\n");
// Make the document change in the context of a write action.
WriteCommandAction.runWriteCommandAction(project, runnable);
return Result.STOP;
}
}

View File

@ -61,4 +61,8 @@
</action>
</actions>
<extensions defaultExtensionNs="com.intellij">
<typedHandler implementation="org.intellij.sdk.editor.MyTypedHandler"/>
</extensions>
</idea-plugin>