官方文档
https://www.jetbrains.org/intellij/sdk/docs/tutorials/editor_basics/editor_events.html
Github
https://github.com/kungyutucheng/my_gradle_plugin
运行环境
macOS 10.14.5
IntelliJ idea 2019.2.4
效果
Demo
MyTypedHandler
package com.kungyu.editor.component;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.actionSystem.TypedActionHandler;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NotNull;
/**
* @author wengyongcheng
* @since 2020/3/10 2:36 下午
*/
public class MyTypedHandler implements TypedActionHandler {
@Override
public void execute(@NotNull Editor editor, char charTyped, @NotNull DataContext dataContext) {
final Document document = editor.getDocument();
final Project project = editor.getProject();
Runnable runnable = () -> document.insertString(0,"test");
WriteCommandAction.runWriteCommandAction(project,runnable);
}
}
EditorHandlerIllustration
package com.kungyu.editor.component;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.actionSystem.EditorActionHandler;
import com.intellij.openapi.editor.actionSystem.EditorActionManager;
import com.intellij.openapi.editor.actionSystem.TypedAction;
import com.intellij.openapi.editor.actionSystem.TypedActionHandler;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NotNull;
/**
* @author wengyongcheng
* @since 2020/3/10 2:32 下午
*/
public class EditorHandlerIllustration extends AnAction {
static {
final EditorActionManager editorActionManager = EditorActionManager.getInstance();
final TypedAction typedAction = editorActionManager.getTypedAction();
typedAction.setupHandler(new MyTypedHandler());
}
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
final Editor editor = e.getRequiredData(CommonDataKeys.EDITOR);
EditorActionHandler editorActionHandler = EditorActionManager.getInstance().getActionHandler(IdeActions.ACTION_EDITOR_CLONE_CARET_BELOW);
editorActionHandler.execute(editor, editor.getCaretModel().getPrimaryCaret(), e.getDataContext());
}
@Override
public void update(@NotNull AnActionEvent e) {
final Editor editor = e.getRequiredData(CommonDataKeys.EDITOR);
final Project project = e.getProject();
boolean menuAllowed = false;
if (editor != null && project != null) {
menuAllowed = !editor.getCaretModel().getAllCarets().isEmpty();
}
e.getPresentation().setEnabledAndVisible(menuAllowed);
}
}
注册Action
<action id="com.kungyu.editor.component.EditorHandlerIllustration" class="com.kungyu.editor.component.EditorHandlerIllustration"
text="EditorHandlerIllustration" description="EditorHandlerIllustration">
<add-to-group group-id="EditorPopupMenu" anchor="after" relative-to-action="com.kungyu.editor.component.EditorAreaIllustration"/>
</action>