Last active
January 29, 2022 16:37
-
-
Save dkandalov/5024580 to your computer and use it in GitHub Desktop.
Evaluate selection as Groovy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
line 24, I guess it should be
result.toString()
instead of 'asString(result)'