May 30, 2019

Today was a major day. I found out a way to create and show multiple annotations. And drum rolls also found out how to remove the created annotations.

Previously, for testing purposes I created a new List<HighlightInfo> inside the actionPerformed method which wasn’t helpful as a new list would be created for a new annotation resulting in the removal of the already created annotations.

I wanted something that would persist its data across the entire lifetime of the currently opened project in the IDE.

Enter projectService and AbstractProjectComponent

Services in IntelliJ are of 3 types, Application, Project and Module. All three have one common feature, state persistence. All services are instantiated exactly once by the platform, and whenever they are required, just call, ProjectManager.getService(project, ServiceClassName.class) to access them. Coming back to the problem of storing a list of annotations,

  1. create a new list in the class:

    public class ServiceClass {
        private final List<HighlightInfo> highlightInfoList = new ArrayList<HighlightInfo>();
    }
    

    and

  2. create a method to add an item to the list

    public void addToList(...) {
        /* create annotations */
        highlightInfo.add(annotation)
    }
    
  3. call the HighlightersUtil.setHighlightersToEditor method and done!

Note about project-service classes: These classes are automatically instantiated once by the platform and only a single Project argument is passed in their constructor. If you want to pass other information, for example, the above class would require extra information such as document and the psiFile required by the setHighlightersToEditor function, that is not possible in a service class. We need AbstractProjectComponent class for this.


Using AbstractProjectComponent multiple custom arguments can be passed to the constructor. These classes that are passed are defined in plugin.xml under

<component>
        <implementation-class>
            ClassName
        <implementation-class>
<component>

The IDE automatically determines the correct classes and passes them in the right order. Cool right?

AbstractProjectComponent along with the above mentioned Service classes can be used to solve the data persistance problem.


And before I forget, here’s how to clear all the annotations. Just pass an empty list to the setHighlightersToEditor method, and it’ll clear all the annotations (Don’t forget to clear your highlightInfoList during this step, else old annotations will prevail when creating the new ones).

HighlightersUtil.setHighlightersToEditor(project, document, 0, psiFile.getTextLength(), new ArrayList<HighlightInfo>(), editorColorScheme, HIGHLIGHT_GROUP_ID)



A day well spent 🌞

Soon.