GrExpression (@NotNull PsiFile containingFile, @NotNull GrVariable variable, @NotNull RangeMarker marker, String exprText) { if (exprText == null) return null; if (!variable.isValid()) return null; final PsiElement refVariableElement = containingFile.findElementAt(marker.getStartOffset()); final PsiElement refVariableElementParent = refVariableElement != null ? refVariableElement.getParent() : null; GrExpression expression = refVariableElementParent instanceof GrNewExpression && refVariableElement.getNode().getElementType() == GroovyTokenTypes.kNEW ? (GrNewExpression)refVariableElementParent : refVariableElementParent instanceof GrParenthesizedExpression ? ((GrParenthesizedExpression)refVariableElementParent).getOperand() : PsiTreeUtil.getParentOfType(refVariableElement, GrReferenceExpression.class); if (expression instanceof GrReferenceExpression) { final String referenceName = ((GrReferenceExpression)expression).getReferenceName(); if (((GrReferenceExpression)expression).resolve() == variable || Comparing.strEqual(variable.getName(), referenceName) || Comparing.strEqual(exprText, referenceName)) { return (GrExpression)expression .replace(GroovyPsiElementFactory.getInstance(myProject).createExpressionFromText(exprText, variable)); } } if (expression == null) { expression = PsiTreeUtil.getParentOfType(refVariableElement, GrExpression.class); } while (expression instanceof GrReferenceExpression || expression instanceof GrCall) { final PsiElement parent = expression.getParent(); if (parent instanceof GrMethodCallExpression) { if (parent.getText().equals(exprText)) return (GrExpression)parent; } if (parent instanceof GrExpression) { expression = (GrExpression)parent; if (expression.getText().equals(exprText)) { return expression; } } else if (expression instanceof GrReferenceExpression){ return null; } else { break; } } if (expression != null && expression.isValid() && expression.getText().equals(exprText)) { return expression; } if (refVariableElementParent instanceof GrExpression && refVariableElementParent.getText().equals(exprText)) { return (GrExpression)refVariableElementParent; } return null; }