Skip to content

Instantly share code, notes, and snippets.

@dkandalov
Last active January 29, 2022 16:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dkandalov/5024580 to your computer and use it in GitHub Desktop.
Save dkandalov/5024580 to your computer and use it in GitHub Desktop.
Evaluate selection as Groovy
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.codehaus.groovy.control.CompilationFailedException
import static liveplugin.PluginUtil.*
// This is micro-plugin for IntelliJ to evaluate selected text as Groovy expression
// (Note that this code can only be executed within this plugin https://github.com/dkandalov/live-plugin)
// You can try it on the following code. Should produce 14.
/*
def ints = [1, 2, 3]
ints.sum{ it * it }
*/
registerAction("EvalSelectionAsGroovy", "alt shift E", "ToolsMenu", "Eval as Groovy") { event ->
def editor = currentEditorIn(event.project)
if (editor == null) return
def text = editor.selectionModel.selectedText
if (text == null) return
try {
def result = Eval.me(text)
appendToSelectionIn(editor, result.toString(), event.project)
} catch (Exception e) {
showInConsole(e, "EvalSelectionAsGroovy", event.project)
}
}
show("Registered 'Eval Selection as Groovy' action<br/>Use Alt+Shift+E to run it")
static appendToSelectionIn(Editor editor, String text, Project project) {
runDocumentWriteAction(project) {
editor.with {
def lineNumber = document.getLineNumber(selectionModel.selectionEnd)
def lineEndOffset = document.getLineEndOffset(lineNumber)
document.insertString(lineEndOffset, " // -> ${text}")
}
}
}
@D00mch
Copy link

D00mch commented Jan 20, 2022

line 24, I guess it should be result.toString() instead of 'asString(result)'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment