Skip to content

Instantly share code, notes, and snippets.

@kontext-e
Last active December 5, 2019 12:33
Show Gist options
  • Save kontext-e/f68c6a1b90dd862afb5d to your computer and use it in GitHub Desktop.
Save kontext-e/f68c6a1b90dd862afb5d to your computer and use it in GitHub Desktop.
Plugin for IntelliJ LivePlugin; adds a new intention for generating call parameters based on the parameters of the called method
// Usage:
// Install LivePlugin http://plugins.jetbrains.com/plugin/7282
// Install this plugin into LivePlugin and run it
// In source code, create a method or constructor call and place the cursor into the empty braces
// Open the intentions drop down menu and select the "Create variables for method call parameters"
import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.Document
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiCallExpression
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethodCallExpression
import com.intellij.psi.PsiField
import com.intellij.psi.PsiNewExpression
import com.intellij.psi.PsiParameter
import com.intellij.psi.PsiExpressionList
import com.intellij.util.IncorrectOperationException
import org.jetbrains.annotations.NotNull
import static liveplugin.PluginUtil.registerIntention
import static liveplugin.PluginUtil.show
registerIntention("ParameterMagic", new ParameterMagicIntentionAction("Create variables for method call parameters"))
if (!isIdeStartup) show("Reloaded ParameterNameGenerator plugin")
class ParameterMagicIntentionAction extends PsiElementBaseIntentionAction {
private final String text
ParameterMagicIntentionAction(String text) {
this.text = text
}
@Override void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement psiElement) throws IncorrectOperationException {
PsiCallExpression call = findParent(PsiCallExpression, psiElement)
if(call == null) {
return;
}
Document doc = editor.getDocument()
PsiParameter[] params = call.resolveMethod().getParameterList().getParameters()
String prefix = ""
def offset = editor.getCaretModel().getOffset()
for(PsiParameter p : params) {
doc.insertString(offset, prefix+p.getName())
offset += p.getName().length() + prefix.length()
prefix = ", "
}
}
@Override boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiElement psiElement) {
return findParent(PsiCallExpression, psiElement) != null
}
@Override String getFamilyName() {
"ParameterMagic"
}
@Override String getText() {
text
}
private <T> T findParent(Class<T> aClass, PsiElement element) {
if (element == null) null
else if (PsiClass.isAssignableFrom(element.class)) null
else if (aClass.isAssignableFrom(element.class)) element
else findParent(aClass, element.parent)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment