2 * Copyright 2000-2009 JetBrains s.r.o.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package com
.intellij
.codeInsight
.editorActions
.smartEnter
;
18 import com
.intellij
.openapi
.editor
.Document
;
19 import com
.intellij
.openapi
.editor
.Editor
;
20 import com
.intellij
.psi
.*;
21 import com
.intellij
.psi
.util
.PsiTreeUtil
;
22 import com
.intellij
.util
.IncorrectOperationException
;
23 import org
.jetbrains
.annotations
.Nullable
;
26 * Created by IntelliJ IDEA.
30 * To change this template use Options | File Templates.
32 public class MissingForBodyFixer
implements Fixer
{
33 public void apply(Editor editor
, JavaSmartEnterProcessor processor
, PsiElement psiElement
) throws IncorrectOperationException
{
34 PsiForStatement forStatement
= getForStatementParent(psiElement
);
35 if (forStatement
== null) return;
37 final Document doc
= editor
.getDocument();
39 PsiElement body
= forStatement
.getBody();
40 if (body
instanceof PsiBlockStatement
) return;
41 if (body
!= null && startLine(doc
, body
) == startLine(doc
, forStatement
)) return;
43 PsiElement eltToInsertAfter
= forStatement
.getRParenth();
45 if (eltToInsertAfter
== null) {
46 eltToInsertAfter
= forStatement
;
49 doc
.insertString(eltToInsertAfter
.getTextRange().getEndOffset(), text
);
53 private static PsiForStatement
getForStatementParent(PsiElement psiElement
) {
54 PsiForStatement statement
= PsiTreeUtil
.getParentOfType(psiElement
, PsiForStatement
.class);
55 if (statement
== null) return null;
57 PsiStatement init
= statement
.getInitialization();
58 PsiStatement update
= statement
.getUpdate();
59 PsiExpression check
= statement
.getCondition();
61 return isValidChild(init
, psiElement
) || isValidChild(update
, psiElement
) || isValidChild(check
, psiElement
) ? statement
: null;
64 private static boolean isValidChild(PsiElement ancestor
, PsiElement psiElement
) {
65 if (ancestor
!= null) {
66 if (PsiTreeUtil
.isAncestor(ancestor
, psiElement
, false)) {
67 if (PsiTreeUtil
.hasErrorElements(ancestor
)) return false;
75 private static int startLine(Document doc
, PsiElement psiElement
) {
76 return doc
.getLineNumber(psiElement
.getTextRange().getStartOffset());