Do you want to write an idea plug-in? Learn about these APIs!

Time:2020-11-10

preface

After watching the idea plug-in development easy tutorial, can’t wait to start the whole plug-in? I planned one, two, three, but I didn’t know where to start. Now I’d like to share some common APIs I’ve compiled.

The official account: Liu Zhihang, which records the skills, development and source notes in work study, and occasionally shares some insights in life. Welcome to guide!

Anaction action

  1. Create action integrationAnActionAnd realize itactionPerformedMethod. You can get theAnActionEventThe code is as follows:
public class JsonFormatAction extends AnAction {

    @Override
    public void actionPerformed(AnActionEvent event) {

        //Gets the current project object
        Project project = event.getData(PlatformDataKeys.PROJECT);
        //Get the currently edited file, and then get psiclass and psifield objects
        PsiFile psiFile = event.getData(CommonDataKeys.PSI_FILE);
        Editor editor = event.getData(CommonDataKeys.EDITOR);
        //Get Java class or interface
        PsiClass psiClass = getTargetClass(editor, psiFile);
        //Create and call dialogwrapper
        DialogWrapper dialog = new JsonFormat(project, psiFile, editor, psiClass);
        dialog.show();
    }
  1. Other ways
//Get project. Internal call GetData( CommonDataKeys.PROJECT ) = getDataContext().getData( CommonDataKeys.PROJECT )
Project project = e.getProject();
//Get data context
DataContext dataContext = e.getDataContext();
//Context can also get other information and input the fields defined for platformdatakeys
Project project1 = dataContext.getData(PlatformDataKeys.PROJECT);
Editor editor = dataContext.getData(PlatformDataKeys.EDITOR);
PsiFile psiFile = dataContext.getData(PlatformDataKeys.PSI_FILE);
PsiElement psiElement = dataContext.getData(PlatformDataKeys.PSI_ELEMENT);
//Virtual file
VirtualFile virtualFile = dataContext.getData(PlatformDataKeys.VIRTUAL_FILE);

Get psiclass

Psiclass is a Java class or interface

@Nullable
protected PsiClass getTargetClass(Editor editor, PsiFile file) {
    int offset = editor.getCaretModel().getOffset();
    PsiElement element = file.findElementAt(offset);
    if (element == null) {
        return null;
    } else {
        PsiClass target = PsiTreeUtil.getParentOfType(element, PsiClass.class);
        return target instanceof SyntheticElement ? null : target;
    }
}

Psixxx operation

Psiclass operation API

The source code is annotated and clear, only a part of it is recorded here

//Get full class name
String qualifiedName = aClass.getQualifiedName();
//Get all fields
PsiField[] fields = aClass.getFields();

Psifield operation

//Get field name
String name = psiField.getName()

Psielement operation

Psiclass and psifield both implement psielement

//Delete
element.delete()
//Add elements, add methods and fields to a class, or call addbefore and addafter
add(PsiElement element)

Psitype operation

Psitype supports common basic types, but not when creating objects. You need to create them yourself

PsiElementFactory psiElementFactory = JavaPsiFacade.getElementFactory(project);
//String type
PsiType stringPsiType = psiElementFactory.createTypeFromText("java.lang.String", null)
// list
PsiType listPsiType = psiElementFactory.createTypeFromText("java.util.List<String>", null);
//Custom list
PsiType typeFromText = psiElementFactory.createTypeFromText("java.util.List<" + className + ">", null);

Other APIs

XML file operation

Reference address:https://jetbrains.org/intelli…

In order to Mapper.xml For example, declare the interface, inherit domelement, and define an XML model with @ attribute, @ subtag, @ subtagslist annotations. Note that the @ subtagslist method should use the plural form.

public interface Mapper extends DomElement {

    /**
     * namespace
     *
     * @return
     */
    @Attribute("namespace")
    GenericAttributeValue<String> getNamespace();

    /**
     *
     *Add, delete, modify and query the corresponding node
     *
     * @return
     */
    @SubTagsList({"select", "insert", "update", "delete"})
    List<Statement> getStatements();
​
    @SubTagList("select")
    List<Select> getSelects();

    @SubTagList("insert")
    List<Insert> getInserts();

    @SubTagList("update")
    List<Update> getUpdates();

    @SubTagList("delete")
    List<Delete> getDeletes();

}

search for file

For example, if you want to search all XML files in the project, the mapper interface is used to define it Mapper.xml You can use domservice to search all the Mapper.xml :

//All the element mappers of the current project are filled in with type and scope globalsearchscope respectively
List<DomFileElement<Mapper>> fileElements = DomService.getInstance().getFileElements(Mapper.class, project, GlobalSearchScope.allScope(project));

write file

Need to callWriteCommandActionWrite asynchronously

WriteCommandAction.runWriteCommandAction(project, () -> {
    doGenerate(psiClass, jsonObject);
});

notice

After the operation is successful, notify the user in the lower right corner of the idea and use the notificationgroup class.

//Static properties
private static final NotificationGroup NOTIFICATION_GROUP = new NotificationGroup("Java2Json.NotificationGroup", NotificationDisplayType.BALLOON, true);

public void actionPerformed(@NotNull AnActionEvent e) {
    // call in method
    Notification success = NOTIFICATION_GROUP.createNotification(message, NotificationType.INFORMATION);
    Notifications.Bus.notify(success, project);

}

It can also be defined as a tool class, as follows

/**
 *
 *Message notification tool class
 *
 * @author liuzhihang
 * @date 2020/2/28 18:52
 */
public class NotificationUtils {

    private static NotificationGroup notificationGroup = new NotificationGroup("ApiDoc.NotificationGroup", NotificationDisplayType.BALLOON, true);

    public static void warnNotify(String message, Project project) {
        Notifications.Bus.notify(notificationGroup.createNotification(message, NotificationType.WARNING), project);
    }

    public static void infoNotify(String message, Project project) {
        Notifications.Bus.notify(notificationGroup.createNotification(message, NotificationType.INFORMATION), project);
    }

    public static void errorNotify(String message, Project project) {
        Notifications.Bus.notify(notificationGroup.createNotification(message, NotificationType.ERROR), project);
    }

}

summary

These are the most commonly used ones. You can also find official documents. The official documents are relatively comprehensive now, and the address is in the relevant materials. You can also use clone toolkit as the plug-in source code. There are some comments in the source code. In other excellent plug-ins, there can also be relevant use methods.

Related information