@Override protected void processIntention(@NotNull PsiElement element, Project project, Editor editor) throws IncorrectOperationException { if (!(element instanceof GrConditionalExpression)) { throw new IncorrectOperationException("Not invoked on a conditional"); } GroovyPsiElementFactory groovyPsiElementFactory = GroovyPsiElementFactory.getInstance(project); GrConditionalExpression condExp = (GrConditionalExpression) element; GrExpression thenBranch = condExp.getThenBranch(); GrExpression elseBranch = condExp.getElseBranch(); Object thenVal = GroovyConstantExpressionEvaluator.evaluate(thenBranch); if (Boolean.TRUE.equals(thenVal) && elseBranch != null) { // aaa ? true : bbb -> aaa || bbb GrExpression conditionExp = condExp.getCondition(); String conditionExpText = getStringToPutIntoOrExpression(conditionExp); String elseExpText = getStringToPutIntoOrExpression(elseBranch); String newExp = conditionExpText + "||" + elseExpText; int caretOffset = conditionExpText.length() + 2; // after "||" GrExpression expressionFromText = groovyPsiElementFactory.createExpressionFromText(newExp, condExp.getContext()); expressionFromText = (GrExpression) condExp.replace(expressionFromText); editor .getCaretModel() .moveToOffset(expressionFromText.getTextOffset() + caretOffset); // just past "||" return; } Object elseVal = GroovyConstantExpressionEvaluator.evaluate(elseBranch); if (Boolean.FALSE.equals(elseVal) && thenBranch != null) { // aaa ? bbb : false -> aaa && bbb GrExpression conditionExp = condExp.getCondition(); String conditionExpText = getStringToPutIntoAndExpression(conditionExp); String thenExpText = getStringToPutIntoAndExpression(thenBranch); String newExp = conditionExpText + "&&" + thenExpText; int caretOffset = conditionExpText.length() + 2; // after "&&" GrExpression expressionFromText = groovyPsiElementFactory.createExpressionFromText(newExp, condExp.getContext()); expressionFromText = (GrExpression) condExp.replace(expressionFromText); editor .getCaretModel() .moveToOffset(expressionFromText.getTextOffset() + caretOffset); // just past "&&" } }
public static int getCaretOffset(@NotNull GrStatement statement) { if (statement instanceof GrVariableDeclaration) { GrVariable[] variables = ((GrVariableDeclaration) statement).getVariables(); if (variables.length > 0) { GrExpression initializer = variables[0].getInitializerGroovy(); if (initializer != null) { return initializer.getTextOffset(); } } } else if (statement instanceof GrAssignmentExpression) { GrExpression value = ((GrAssignmentExpression) statement).getRValue(); if (value != null) { return value.getTextOffset(); } } return statement.getTextOffset(); }