Search code examples
gradleintellij-ideapluginswindowaction

Intellij plugin development print in console window


I am new to Intellij Idea plugin development. So I am developing a simple plugin to print a string value in a tool window(similar to console window)! There are less examples when I searched the web! I have a slight understanding about the Intellij action system but is unable to figure out how to register the necessary action in the plugin.xml to print the string in a tool window!

Following is my code

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;

    public class A extends AnAction {

        @Override
        public void actionPerformed(AnActionEvent e) {
           String x="Hello how are you?";
        }
    }

How can I print String x in a tool window?


Solution

  • Console windows can't just exist on their own, they have to be tied to a tool window. Here's a quick example.

    First create a ToolWindow for your plugin in XML:

    <extensions defaultExtensionNs="com.intellij">
      <!-- Add your extensions here -->
      <toolWindow id="MyPlugin" 
                  anchor="bottom"
                  icon="iconfile.png"
                  factoryClass="com.intellij.execution.dashboard.RunDashboardToolWindowFactory"></toolWindow>
    </extensions>
    

    Then in your action, you can grab a handle to that tool window and lazily create a console view, then add your text there:

      ToolWindow toolWindow = ToolWindowManager.getInstance(e.getProject()).getToolWindow("MyPlugin");
      ConsoleView consoleView = TextConsoleBuilderFactory.getInstance().createBuilder(e.getProject()).getConsole();
      Content content = toolWindow.getContentManager().getFactory().createContent(consoleView.getComponent(), "MyPlugin Output", false);
      toolWindow.getContentManager().addContent(content);
      consoleView.print("Hello from MyPlugin!", ConsoleViewContentType.NORMAL_OUTPUT);
    

    A couple of notes:

    1. Your new tool window may not be visible by default so you may need to activate it from the View -> Tool Windows menu.

    2. We used RunDashboardToolWindowFactory to create our new tool window, so it will take on the layout of a run window. You can use any implementation of ToolWindowFactory (including your own custom class) in its place.

    enter image description here