PsiElement (PsiElement element) { PsiElement e = PsiTreeUtil.getParentOfType(element, PsiVariable.class, PsiExpression.class, PsiMethod.class); if (e instanceof PsiVariable) { // return e; } else if (e instanceof PsiMethod && element.getParent() != e) { e = null; } else if (e instanceof PsiReferenceExpression) { if (e.getParent() instanceof PsiCallExpression) { e = e.getParent(); } else if (e.getParent() instanceof PsiReferenceExpression) { // <caret>System.out case should not return plain class name PsiElement resolve = ((PsiReferenceExpression)e).resolve(); if (resolve instanceof PsiClass) { e = e.getParent(); } } } if (e instanceof PsiNewExpression) { // skip new Runnable() { ... } if (((PsiNewExpression)e).getAnonymousClass() != null) return null; } return e; }