Search code examples
intellij-idea

Is it possible to invoke an Intellij IDE script externally i.e. via the command-line?


I am trying to write a script using the Intellij IDE scripting console, and invoke it externally using the command-line launcher e.g. idea for Intellij IDEA.

It looks like support was added in 2021.1 (see YouTrack ticket], but it might have been removed since(?).

I've tried to invoke the script using the following command but nothing happens; script does not seem to be executed, and no errors are logged.

# following command in YouTrack ticket referenced above
idea ideScript /path/to/script

These are the contents of the script, this works when run in the IDE.

# ide_script.kts
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.ActionCallback

val project = ProjectManager.getInstance().defaultProject
val actionManager: ActionManager = ActionManager.getInstance()
val action: AnAction = actionManager.getAction("NextTab")
val actionResult: ActionCallback = actionManager.tryToExecute(action, null, null, null, true)

Messages.showInfoMessage(project, actionResult.error ?: "Action success", "Action Result")

Ideally I'd also like to (if possible) parameterize the script e.g. pass in the action name.


Solution

  • I got it to work by wrapping the contents of the script in the following snippet:

    IDE.application.invokeLater {
      // execute IDE action here
    }
    

    Then invoking the IDE script as you normally would idea ideScript /path/to/script.

    I also created a shell script that handles accepts the action name as an argument; the full code is in the following GitHub gist for anyone that is interested.