improve formatting of comment created with the "Replace with block comment" intention
[fedora-idea.git] / plugins / IntentionPowerPak / src / com / siyeh / ipp / comment / MoveCommentToSeparateLineIntention.java
blobb0e846377acea3e5785efbd5dc3d64ae40115ec6
1 /*
2 * Copyright 2003-2005 Dave Griffith
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.siyeh.ipp.comment;
18 import com.intellij.psi.*;
19 import com.intellij.psi.codeStyle.CodeStyleManager;
20 import com.intellij.util.IncorrectOperationException;
21 import com.siyeh.ipp.base.Intention;
22 import com.siyeh.ipp.base.PsiElementPredicate;
23 import com.siyeh.ipp.psiutils.TreeUtil;
24 import org.jetbrains.annotations.NotNull;
26 public class MoveCommentToSeparateLineIntention extends Intention {
28 @NotNull
29 protected PsiElementPredicate getElementPredicate() {
30 return new CommentOnLineWithSourcePredicate();
33 public void processIntention(@NotNull PsiElement element)
34 throws IncorrectOperationException {
35 final PsiComment selectedComment = (PsiComment)element;
36 PsiElement elementToCheck = selectedComment;
37 final PsiWhiteSpace whiteSpace;
38 while (true) {
39 elementToCheck = TreeUtil.getPrevLeaf(elementToCheck);
40 if (elementToCheck == null) {
41 return;
43 if (isLineBreakWhiteSpace(elementToCheck)) {
44 whiteSpace = (PsiWhiteSpace)elementToCheck;
45 break;
48 final PsiElement copyWhiteSpace = whiteSpace.copy();
49 final PsiElement parent = whiteSpace.getParent();
50 assert parent != null;
51 final PsiManager manager = selectedComment.getManager();
52 final PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
53 final String commentText = selectedComment.getText();
54 final PsiComment newComment =
55 factory.createCommentFromText(commentText, parent);
56 final PsiElement insertedComment = parent
57 .addBefore(newComment, whiteSpace);
58 parent.addBefore(copyWhiteSpace, insertedComment);
60 selectedComment.delete();
61 final CodeStyleManager codeStyleManager = manager.getCodeStyleManager();
62 codeStyleManager.reformat(insertedComment);
65 private static boolean isLineBreakWhiteSpace(PsiElement element) {
66 if (!(element instanceof PsiWhiteSpace)) {
67 return false;
69 final String text = element.getText();
70 return containsLineBreak(text);
73 private static boolean containsLineBreak(String text) {
74 return text.indexOf((int)'\n') >= 0 || text.indexOf((int)'\r') >= 0;