preface


After watching the simple tutorial of IDEA plug-in development, whether the friends can’t wait to start their own plug-in? I planned one, two, three, but I didn’t know where to start. Here I share some of the common apis I’ve compiled.


[liuzhirichard] Record technology, development and source code notes in work and study. From time to time, share what you’ve seen and heard in your life. Welcome to guide!

AnAction operation

  1. Create Action integrationAnActionAnd to achieve itsactionPerformedMethod. This is available in the methodAnActionEventThe code is as follows:
public class JsonFormatAction extends AnAction {

    @Override
    public void actionPerformed(AnActionEvent event) {

        // Get the current project object
        Project project = event.getData(PlatformDataKeys.PROJECT);
        // Get the currently edited file, which can then get the PsiClass, PsiField object
        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 invoke DialogWrapper
        DialogWrapper dialog = new JsonFormat(project, psiFile, editor, psiClass);
        dialog.show();
    }

Copy the code
  1. The other way
GetData (CommonDataKeys.project) = getDataContext().getData(commonDataKeys.project)
Project project = e.getProject();
// Get the data context
DataContext dataContext = e.getDataContext();
// Context can also get other information, taking fields defined by 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);
Copy the code

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; }}Copy the code

Psixxx operation

PsiClass API operation

The source code is annotated and relatively clear, and only a portion of what I used is recorded here

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

PsiField operation

// Get the field name
String name = psiField.getName()
Copy the code

PsiElement operation

Both PsiClass and PsiField implement PsiElement

/ / delete
element.delete()
// Add elements to a class to add methods, fields, etc. You can also call addBefore, addAfter
add(PsiElement element)
Copy the code

PsiType operation

PsiType supports common base types, but not when creating objects. You need to create your own

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

Other apis

XML file manipulation

Reference address: jetbrains.org/intellij/sd…

Use mapper. XML as an example to declare the interface, inherit DomElement, and define an XML model with @attribute, @subtag, and @Subtagslist annotations. Note that the @subtagslist method should be plural.

public interface Mapper extends DomElement {

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

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

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

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

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

}

Copy the code

Search for files

For example, if you want to search all XML files in a project, you can use DomService to search all mapper.xml files:

// All elements of the current project mapper are typed separately and scoped GlobalSearchScope
List<DomFileElement<Mapper>> fileElements = DomService.getInstance().getFileElements(Mapper.class, project, GlobalSearchScope.allScope(project));
Copy the code

Written to the file

You need to call WriteCommandAction for asynchronous writing.

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

notice

NotificationGroup notifies the user in the lower right corner of the IDEA after a successful operation using the NotificationGroup class.

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

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

}
Copy the code

Can also be defined as a utility class, as follows

/** ** Tools for message notification **@author liuzhihang
 * @date2020/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); }}Copy the code

conclusion

Basically commonly used is these, you can also find the official document, the official document is still more comprehensive, the address in the relevant information. You can also Clone Toolkit this plug-in source code, the source code has some comments. There are other good plug-ins that can be used as well.

The relevant data

  • The Toolkit: github.com/liuzhihangs…
  • Copy – as – json: github.com/liuzhihangs…
  • IntelliJ Platform SDK: jetbrains.org/intellij/sd…