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
;
27 import org
.jetbrains
.annotations
.NonNls
;
29 class JavaWithForSurrounder
extends JavaStatementsSurrounder
{
30 public String
getTemplateDescription() {
31 return CodeInsightBundle
.message("surround.with.for.template");
34 public TextRange
surroundStatements(Project project
, Editor editor
, PsiElement container
, PsiElement
[] statements
) throws IncorrectOperationException
{
35 PsiManager manager
= PsiManager
.getInstance(project
);
36 PsiElementFactory factory
= JavaPsiFacade
.getInstance(manager
.getProject()).getElementFactory();
37 CodeStyleManager codeStyleManager
= CodeStyleManager
.getInstance(project
);
39 statements
= SurroundWithUtil
.moveDeclarationsOut(container
, statements
, true);
40 if (statements
.length
== 0){
44 @NonNls String text
= "for(a;b;c){\n}";
45 PsiForStatement forStatement
= (PsiForStatement
)factory
.createStatementFromText(text
, null);
46 forStatement
= (PsiForStatement
)codeStyleManager
.reformat(forStatement
);
48 forStatement
= (PsiForStatement
)container
.addAfter(forStatement
, statements
[statements
.length
- 1]);
50 PsiCodeBlock bodyBlock
= ((PsiBlockStatement
)forStatement
.getBody()).getCodeBlock();
51 bodyBlock
.addRange(statements
[0], statements
[statements
.length
- 1]);
52 container
.deleteChildRange(statements
[0], statements
[statements
.length
- 1]);
54 forStatement
= CodeInsightUtilBase
.forcePsiPostprocessAndRestoreElement(forStatement
);
55 TextRange range1
= forStatement
.getInitialization().getTextRange();
56 TextRange range3
= forStatement
.getUpdate().getTextRange();
57 editor
.getDocument().deleteString(range1
.getStartOffset(), range3
.getEndOffset());
58 return new TextRange(range1
.getStartOffset(), range1
.getStartOffset());