3 * Copyright 2000-2009 JetBrains s.r.o.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
17 package com
.intellij
.codeInsight
.generation
.surroundWith
;
19 import com
.intellij
.codeInsight
.CodeInsightBundle
;
20 import com
.intellij
.codeInsight
.CodeInsightUtilBase
;
21 import com
.intellij
.openapi
.editor
.Editor
;
22 import com
.intellij
.openapi
.project
.Project
;
23 import com
.intellij
.openapi
.util
.TextRange
;
24 import com
.intellij
.psi
.*;
25 import com
.intellij
.psi
.codeStyle
.CodeStyleManager
;
26 import com
.intellij
.util
.IncorrectOperationException
;
28 class JavaWithNotInstanceofSurrounder
extends JavaExpressionSurrounder
{
29 public boolean isApplicable(PsiExpression expr
) {
30 PsiType type
= expr
.getType();
31 if (type
== null) return false;
32 return !(type
instanceof PsiPrimitiveType
);
35 public TextRange
surroundExpression(Project project
, Editor editor
, PsiExpression expr
) throws IncorrectOperationException
{
36 PsiManager manager
= expr
.getManager();
37 PsiElementFactory factory
= JavaPsiFacade
.getInstance(manager
.getProject()).getElementFactory();
38 CodeStyleManager codeStyleManager
= CodeStyleManager
.getInstance(project
);
40 PsiPrefixExpression prefixExpr
= (PsiPrefixExpression
)factory
.createExpressionFromText("!(a instanceof Type)", null);
41 prefixExpr
= (PsiPrefixExpression
)codeStyleManager
.reformat(prefixExpr
);
42 PsiParenthesizedExpression parenthExpr
= (PsiParenthesizedExpression
)prefixExpr
.getOperand();
43 PsiInstanceOfExpression instanceofExpr
= (PsiInstanceOfExpression
)parenthExpr
.getExpression();
44 instanceofExpr
.getOperand().replace(expr
);
45 prefixExpr
= (PsiPrefixExpression
)expr
.replace(prefixExpr
);
46 parenthExpr
= (PsiParenthesizedExpression
)prefixExpr
.getOperand();
47 instanceofExpr
= (PsiInstanceOfExpression
)parenthExpr
.getExpression();
48 instanceofExpr
= CodeInsightUtilBase
.forcePsiPostprocessAndRestoreElement(instanceofExpr
);
49 TextRange range
= instanceofExpr
.getCheckType().getTextRange();
50 editor
.getDocument().deleteString(range
.getStartOffset(), range
.getEndOffset());
51 return new TextRange(range
.getStartOffset(), range
.getStartOffset());
54 public String
getTemplateDescription() {
55 return CodeInsightBundle
.message("surround.with.not.instanceof.template");