PsiElement (PsiElement replacement, PsiElement elementToReplace) { if (replacement instanceof PsiExpressionStatement && !(replacement.getLastChild() instanceof PsiJavaToken) && !(replacement.getLastChild() instanceof PsiComment) ) { // replacement is expression (and pattern should be so) // assert ... replacement = ((PsiExpressionStatement)replacement).getExpression(); } else if (replacement instanceof PsiDeclarationStatement && ((PsiDeclarationStatement)replacement).getDeclaredElements().length == 1 && (elementToReplace instanceof PsiVariable || elementToReplace instanceof PsiClass)) { return ((PsiDeclarationStatement)replacement).getDeclaredElements()[0]; } else if (replacement instanceof PsiBlockStatement && elementToReplace instanceof PsiCodeBlock) { return ((PsiBlockStatement)replacement).getCodeBlock(); } return replacement; }