PsiElement (PsiElement scope) { assert scope.isValid(); PsiElement lastScope = scope; while (true) { final PsiCodeBlock lastCodeBlock = PsiTreeUtil.getParentOfType(lastScope, PsiCodeBlock.class, true); if (lastCodeBlock == null) { break; } lastScope = lastCodeBlock; } if (lastScope == scope) { PsiFile file = scope.getContainingFile(); if (file instanceof PsiCodeFragment) { return file; } } return lastScope; }