How to obtain the PsiMethod-object for the currently selected method?

I just started plugin development, so I've got a rather basic question for most of you I guess :

Is there an easy way of obtaining the PsiMethod-object for the currently selected method in an editor?

I know that I can use the PsiDocumentManager.getInstance(...).getPsiFile(...) in order to obtain the PsiFile for the current editor and then traverse the whole Psi-tree but I wonder if there isn't an easier solution?

A second question: At the moment I am using EditorFactory.getInstance().getEventMulticaster().addCaretListener(...) for listening to caret changes in an editor. Since I am not a singleton-fan , are there alternatives for that approach?

Thanks a lot in advance!
Gerhard

2 comments
Comment actions Permalink

This is what I am using, though I am also new, so it may not be best.

        PsiFile pf = DataKeys.PSI_FILE.getData(dataContext);
        Editor editor = DataKeys.EDITOR.getData(dataContext);
        PsiElement pe = pf.findElementAt(editor.getCaretModel().getOffset());
        PsiMethod method = findMethod(pe);

    private static PsiMethod findMethod(PsiElement element) {
       PsiMethod method = (element instanceof PsiMethod) ? (PsiMethod) element :
             PsiTreeUtil.getParentOfType(element, PsiMethod.class);
       if (method != null && method.getContainingClass() instanceof PsiAnonymousClass) {
          return findMethod(method.getParent());
       }
       return method;
    }

The latter block borrowed from http://www.piraya.nl/products/ideadoc/doc/example/PluginUtil.html part of the http://www.piraya.nl/IDEAPlugins.html tutorial.

0
Comment actions Permalink

Hi David,

thanks a lot, it works perfectly! Just because I am curious: If anyone knows other solutions, it would be nice if they could post them here too.

Cheers,
Gerhard

0

Please sign in to leave a comment.