<orderEntry type="module" module-name="xml" />
<orderEntry type="module" module-name="testFramework" scope="TEST" />
<orderEntry type="library" name="Jaxen" level="project" />
+ <orderEntry type="module" module-name="platform-ultimate" scope="TEST" />
</component>
</module>
return TextRange.from(0, getElement().getTextLength());
}
+ @NotNull
public String getCanonicalText() {
return getElement().getText();
}
return RegExpPropertyImpl.this;
}
+ @NotNull
public String getCanonicalText() {
return getRangeInElement().substring(getElement().getText());
}
return RegExpPyNamedGroupRefImpl.this.resolve();
}
+ @NotNull
public String getCanonicalText() {
return getRangeInElement().substring(getText());
}
jvmarg (value: "-ea")
jvmarg (value: "-Didea.home.path=$home")
pass("idea.test.group")
+ pass("idea.test.patterns")
+ pass("idea.fast.only")
pass("teamcity.tests.recentlyFailedTests.file")
jvmarg (value: "-Didea.platform.prefix=Idea")
jvmarg (value: "-Didea.home.path=$home")
import com.intellij.codeInsight.CodeInsightUtilBase;
import com.intellij.codeInsight.lookup.LookupElement;
-import com.intellij.lang.StdLanguages;
+import com.intellij.lang.LanguageExtension;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.psi.filters.ElementFilter;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.searches.AllClassesSearch;
-import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.Processor;
import gnu.trove.THashSet;
final PsiFile file = context.getFile();
if (file.findElementAt(endOffset - 1) == null) return;
- boolean checkReference = true;
- if (file.getLanguage() == StdLanguages.JAVA) {
- if (PsiTreeUtil.findElementOfClassAtOffset(file, endOffset - 1, PsiImportStatementBase.class, false) != null) {
- checkReference = false;
- } else {
- final OffsetKey key = OffsetKey.create("endOffset", false);
- context.getOffsetMap().addOffset(key, endOffset);
- JavaPsiClassReferenceElement.JAVA_CLASS_INSERT_HANDLER.handleInsert(context, item);
- final int newOffset = context.getOffsetMap().getOffset(key);
- if (newOffset >= 0) {
- endOffset = newOffset;
- } else {
- LOG.error(endOffset + " became invalid: " + context.getOffsetMap() + "; inserting " + qname);
- }
- }
+ final OffsetKey key = OffsetKey.create("endOffset", false);
+ context.getOffsetMap().addOffset(key, endOffset);
+ ClassNameInsertHandler handler = ClassNameInsertHandler.EP_NAME.forLanguage(file.getLanguage());
+ ClassNameInsertHandlerResult checkReference = ClassNameInsertHandlerResult.CHECK_FOR_CORRECT_REFERENCE;
+ if (handler != null) {
+ checkReference = handler.handleInsert(context, item);
+ }
+
+ final int newOffset = context.getOffsetMap().getOffset(key);
+ if (newOffset >= 0) {
+ endOffset = newOffset;
+ }
+ else {
+ LOG.error(endOffset + " became invalid: " + context.getOffsetMap() + "; inserting " + qname);
}
final RangeMarker toDelete = DefaultInsertHandler.insertSpace(endOffset, document);
psiDocumentManager.commitAllDocuments();
PsiReference psiReference = file.findReferenceAt(endOffset - 1);
- boolean insertFqn = true;
- if (checkReference && psiReference != null) {
+
+ boolean insertFqn=checkReference!=ClassNameInsertHandlerResult.REFERENCE_CORRECTED;
+ if (checkReference == ClassNameInsertHandlerResult.CHECK_FOR_CORRECT_REFERENCE && psiReference != null) {
final PsiManager psiManager = file.getManager();
if (psiManager.areElementsEquivalent(psiClass, DefaultInsertHandler.resolveReference(psiReference))) {
insertFqn = false;
}
public void getClasses(final PsiElement context, final CompletionResultSet set, final int offset, final boolean filterByScope) {
- if(context == null || !context.isValid()) return;
+ if (context == null || !context.isValid()) return;
final String packagePrefix = getPackagePrefix(context, offset);
});
}
+
+ public interface ClassNameInsertHandler {
+ LanguageExtension<ClassNameInsertHandler> EP_NAME =
+ new LanguageExtension<ClassNameInsertHandler>("com.intellij.classNameInsertHandler");
+
+ ClassNameInsertHandlerResult handleInsert(InsertionContext context, JavaPsiClassReferenceElement item);
+ }
+
+ public enum ClassNameInsertHandlerResult {
+ INSERT_FQN, REFERENCE_CORRECTED, CHECK_FOR_CORRECT_REFERENCE
+ }
+
}
--- /dev/null
+/*
+ * Copyright 2000-2010 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.intellij.codeInsight.completion;
+
+import com.intellij.lang.StdLanguages;
+import com.intellij.openapi.editor.Editor;
+import com.intellij.psi.PsiFile;
+import com.intellij.psi.PsiImportStatementBase;
+import com.intellij.psi.util.PsiTreeUtil;
+
+/**
+* @author Maxim.Medvedev
+*/
+public class JavaClassNameInsertHandler implements AllClassesGetter.ClassNameInsertHandler {
+ public AllClassesGetter.ClassNameInsertHandlerResult handleInsert(InsertionContext context,
+ JavaPsiClassReferenceElement item) {
+ Editor editor = context.getEditor();
+ PsiFile file = context.getFile();
+ int endOffset = editor.getCaretModel().getOffset();
+ if (file.getLanguage() == StdLanguages.JAVA) {
+ if (PsiTreeUtil.findElementOfClassAtOffset(file, endOffset - 1, PsiImportStatementBase.class, false) != null) {
+ return AllClassesGetter.ClassNameInsertHandlerResult.INSERT_FQN;
+ }
+ else {
+ JavaPsiClassReferenceElement.JAVA_CLASS_INSERT_HANDLER.handleInsert(context, item);
+ }
+ }
+ return AllClassesGetter.ClassNameInsertHandlerResult.CHECK_FOR_CORRECT_REFERENCE;
+ }
+}
*/
package com.intellij.codeInsight.completion;
+import com.intellij.codeInsight.TailType;
import com.intellij.codeInsight.completion.scope.CompletionElement;
import com.intellij.codeInsight.completion.scope.JavaCompletionProcessor;
import com.intellij.codeInsight.lookup.*;
ret.add(tokenizer.nextToken());
}
for (final String s : ret) {
- final LookupItem item = (LookupItem)LookupItemUtil.objectToLookupItem(s);
if (isInline) {
- item.setInsertHandler(new InlineInsertHandler());
+ result.addElement(TailTypeDecorator.withInsertHandler(LookupElementBuilder.create(s), new InlineInsertHandler()));
+ } else {
+ result.addElement(TailTypeDecorator.withTail(LookupElementBuilder.create(s), TailType.SPACE));
}
- result.addElement(item);
}
}
}
}
- private static class InlineInsertHandler implements InsertHandler<LookupItem> {
- public void handleInsert(InsertionContext context, LookupItem item) {
+ private static class InlineInsertHandler implements InsertHandler<LookupElement> {
+ public void handleInsert(InsertionContext context, LookupElement item) {
if (context.getCompletionChar() == Lookup.REPLACE_SELECT_CHAR) {
final Project project = context.getProject();
PsiDocumentManager.getInstance(project).commitAllDocuments();
public boolean analyze(Runnable analyze, final TextRange dirtyScope, final PsiFile file) {
myState.compareAndSet(State.READY, State.VIRGIN);
- if (!myState.compareAndSet(State.VIRGIN, State.BEING_WRITTEN_BY_GHP)) return false;
+ if (!myState.compareAndSet(State.VIRGIN, State.BEING_WRITTEN_BY_GHP)) {
+ return false;
+ }
try {
if (dirtyScope != null) {
}
+ @NotNull
public String getCanonicalText() {
return getText();
}
}
}
- final ASTNode prevElement = FormattingAstUtil.getPrevElement(child);
+ final ASTNode prevElement = FormattingAstUtil.getPrevNonWhiteSpaceNode(child);
if (prevElement != null && prevElement.getElementType() == JavaElementType.MODIFIER_LIST) {
return Indent.getNoneIndent();
}
return role == ChildRole.OPERATION_SIGN || role == ChildRole.COLON;
}
+ @SuppressWarnings({"ConstantConditions"})
private Block createMethodCallExpressionBlock(final ASTNode node, final Wrap blockWrap, final Alignment alignment) {
final ArrayList<ASTNode> nodes = new ArrayList<ASTNode>();
final ArrayList<Block> subBlocks = new ArrayList<Block>();
private Indent calcIndent(final ASTNode child, final int state) {
if (state == AFTER_ELSE && child.getElementType() == ElementType.IF_STATEMENT) {
- if (!mySettings.SPECIAL_ELSE_IF_TREATMENT) {
- return getCodeBlockInternalIndent(1);
+ if (mySettings.SPECIAL_ELSE_IF_TREATMENT) {
+ return Indent.getNoneIndent();
} else {
- return getCodeBlockExternalIndent();
+ return getCodeBlockInternalIndent(1);
}
}
if (isSimpleStatement(child)){
* @return left non-white space sibling of the given node if any; <code>null</code> otherwise
*/
@Nullable
- public static ASTNode getPrevElement(final ASTNode node) {
+ public static ASTNode getPrevNonWhiteSpaceNode(final ASTNode node) {
ASTNode result = node.getTreePrev();
- while (result != null && result.getElementType() == TokenType.WHITE_SPACE) {
+ while (result != null && (result.getElementType() == TokenType.WHITE_SPACE || result.getTextLength() == 0)) {
result = result.getTreePrev();
}
return result;
}
+ /**
+ * Tries to get next non-white space <code>AST</code> node for the given one.
+ *
+ * @param node base node which right non-white space sibling is to be found
+ * @return right non-white space sibling of the given node if any; <code>null</code> otherwise
+ */
+ @Nullable
+ public static ASTNode getNextNonWhiteSpaceNode(final ASTNode node) {
+ ASTNode result = node.getTreeNext();
+ while (result != null && (result.getElementType() == TokenType.WHITE_SPACE || result.getTextLength() == 0)) {
+ result = result.getTreeNext();
+ }
+ return result;
+ }
+
/**
* Allows to answer if given node wraps assignement operation.
*
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.psi.formatter.FormatterUtil;
+import com.intellij.psi.formatter.java.spacing.JavaBraceSpacingProcessor;
import com.intellij.psi.impl.source.SourceTreeToPsiMap;
import com.intellij.psi.impl.source.codeStyle.ImportHelper;
import com.intellij.psi.impl.source.javadoc.PsiDocMethodOrFieldRef;
import java.util.Map;
public class JavaSpacePropertyProcessor extends JavaElementVisitor {
- private static final Logger LOG = Logger.getInstance("#com.intellij.psi.formatter.java.JavaSpacePropertyProcessor");
+ private static final Logger LOG = Logger.getInstance("#com.intellij.psi.formatter.java.JavaSpacePropertyProcessor");
+
+ private final JavaBraceSpacingProcessor myBraceSpacingProcessor;
private PsiElement myParent;
private int myRole1;
private static final ThreadLocal<JavaSpacePropertyProcessor> mySharedProcessorAllocator = new ThreadLocal<JavaSpacePropertyProcessor>();
- private JavaSpacePropertyProcessor() {}
+ private JavaSpacePropertyProcessor() {
+ this(JavaBraceSpacingProcessor.INSTANCE);
+ }
+
+ public JavaSpacePropertyProcessor(JavaBraceSpacingProcessor braceSpacingProcessor) {
+ myBraceSpacingProcessor = braceSpacingProcessor;
+ }
private void doInit(final ASTNode child, final CodeStyleSettings settings) {
init(child);
}
else if (myRole1 == ChildRole.LBRACE) {
if (!(aClass instanceof PsiAnonymousClass)) {
- myResult = Spacing.createSpacing(0, 0, mySettings.BLANK_LINES_AFTER_CLASS_HEADER + 1,
- mySettings.KEEP_LINE_BREAKS, mySettings.KEEP_BLANK_LINES_IN_DECLARATIONS);
+ myResult = myBraceSpacingProcessor.getLBraceSpacing(mySettings, myChild2);
} else {
if (myRole2 == ChildRole.CLASS_INITIALIZER && isTheOnlyClassMember(myChild2)) {
myResult = Spacing.createSpacing(0, 0, 0,
}
else if (myRole1 == ChildRole.CLASS_INITIALIZER) {
if (myRole2 == ChildRole.RBRACE) {
- myResult = Spacing
- .createSpacing(0, Integer.MAX_VALUE, isInsideAnonimusClass() ? 0 : 1, mySettings.KEEP_LINE_BREAKS, mySettings.KEEP_BLANK_LINES_BEFORE_RBRACE);
+ myResult = myBraceSpacingProcessor.getRBraceSpacing(mySettings, myChild1, isInsideAnonimusClass());
}
else {
final int blankLines = getLinesAroundMethod() + 1;
}
@Override public void visitTryStatement(PsiTryStatement statement) {
- if (myRole2 == ChildRole.FINALLY_KEYWORD) {
- processOnNewLineCondition(mySettings.FINALLY_ON_NEW_LINE);
- }
- else if (myRole2 == ChildRole.TRY_BLOCK) {
- myResult = getSpaceBeforeLBrace(mySettings.SPACE_BEFORE_TRY_LBRACE, mySettings.BRACE_STYLE, null,
- mySettings.KEEP_SIMPLE_BLOCKS_IN_ONE_LINE);
+ if (myRole2 == ChildRole.FINALLY_KEYWORD || myRole2 == ChildRole.CATCH_SECTION) {
+ boolean putRightChildOnNewLine = myRole2 == ChildRole.FINALLY_KEYWORD ? mySettings.FINALLY_ON_NEW_LINE : mySettings.CATCH_ON_NEW_LINE;
+ if (putRightChildOnNewLine) {
+ processOnNewLineCondition(mySettings.FINALLY_ON_NEW_LINE);
+ } else {
+ createSpaceProperty(true, false, 0);
+ }
+ return;
}
- else if (myRole2 == ChildRole.FINALLY_BLOCK) {
- myResult = getSpaceBeforeLBrace(mySettings.SPACE_BEFORE_FINALLY_LBRACE, mySettings.BRACE_STYLE, null,
- mySettings.KEEP_SIMPLE_BLOCKS_IN_ONE_LINE);
- }
- else if (myRole2 == ChildRole.CATCH_SECTION) {
- processOnNewLineCondition(mySettings.CATCH_ON_NEW_LINE);
+
+ if (myRole2 == ChildRole.TRY_BLOCK || myRole2 == ChildRole.FINALLY_BLOCK) {
+ boolean useSpaceBeforeLBrace = myRole2 == ChildRole.TRY_BLOCK ? mySettings.SPACE_BEFORE_TRY_LBRACE
+ : mySettings.SPACE_BEFORE_FINALLY_LBRACE;
+ myResult = getSpaceBeforeLBrace(useSpaceBeforeLBrace, mySettings.BRACE_STYLE, null, mySettings.KEEP_SIMPLE_BLOCKS_IN_ONE_LINE);
}
}
--- /dev/null
+/*
+ * Copyright 2000-2010 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.intellij.psi.formatter.java.spacing;
+
+import com.intellij.formatting.Spacing;
+import com.intellij.lang.ASTNode;
+import com.intellij.psi.JavaTokenType;
+import com.intellij.psi.codeStyle.CodeStyleSettings;
+import com.intellij.psi.formatter.java.FormattingAstUtil;
+
+/**
+ * Utility class that encapsulates algorithm of defining {@link Spacing} to use for the target code block containing brace.
+ * <p/>
+ * This class is not singleton but it's thread-safe and provides single-point-of-usage field {@link #INSTANCE}.
+ * <p/>
+ * Thread-safe.
+ *
+ * @author Denis Zhdanov
+ * @since Apr 26, 2010 1:52:52 PM
+ */
+public class JavaBraceSpacingProcessor {
+
+ /** Single-point-of-usage field. */
+ public static final JavaBraceSpacingProcessor INSTANCE = new JavaBraceSpacingProcessor();
+
+ /**
+ * Allows to get {@link Spacing} to use for the given AST node that is assumed to be right sibling of left curly brace and that brace.
+ *
+ * @param settings code formatting settings to use
+ * @param rightNode right sibling of target left curly brace
+ * @return spacing to use for the left curly brace and it's given right sibling
+ */
+ @SuppressWarnings({"MethodMayBeStatic"})
+ public Spacing getLBraceSpacing(CodeStyleSettings settings, ASTNode rightNode) {
+ if (shouldUseFlyingGeeseStyleForLeftBrace(settings, rightNode)) {
+ return getFlyingGeesSpacing(settings);
+ }
+ return Spacing.createSpacing(
+ 0, 0, settings.BLANK_LINES_AFTER_CLASS_HEADER + 1, settings.KEEP_LINE_BREAKS, settings.KEEP_BLANK_LINES_IN_DECLARATIONS
+ );
+ }
+
+ /**
+ * Allows to get {@link Spacing} to use for the given AST node that is assumed to be left sibling of right curly brace and that brace.
+ *
+ * @param settings code formatting settings to use
+ * @param leftNode left sibling of target right curly brace
+ * @return spacing to use for the right curly brace and it's given left sibling
+ */
+ @SuppressWarnings({"MethodMayBeStatic"})
+ public Spacing getRBraceSpacing(CodeStyleSettings settings, ASTNode leftNode, boolean insideAnonymousClass) {
+ if (shouldUseFlyingGeeseStyleForRightBrace(settings, leftNode)) {
+ return getFlyingGeesSpacing(settings);
+ }
+ return Spacing.createSpacing(
+ 0, Integer.MAX_VALUE, insideAnonymousClass ? 0 : 1, settings.KEEP_LINE_BREAKS, settings.KEEP_BLANK_LINES_BEFORE_RBRACE
+ );
+ }
+
+ private static boolean shouldUseFlyingGeeseStyleForLeftBrace(CodeStyleSettings settings, ASTNode rightNode) {
+ if (!settings.USE_FLYING_GEESE_BRACES) {
+ return false;
+ }
+
+ ASTNode rightSibling = FormattingAstUtil.getNextNonWhiteSpaceNode(rightNode);
+ return rightSibling != null && rightSibling.getElementType() == JavaTokenType.RBRACE;
+ }
+
+ private static boolean shouldUseFlyingGeeseStyleForRightBrace(CodeStyleSettings settings, ASTNode leftNode) {
+ if (!settings.USE_FLYING_GEESE_BRACES) {
+ return false;
+ }
+
+ ASTNode leftSibling = FormattingAstUtil.getPrevNonWhiteSpaceNode(leftNode);
+ return leftSibling != null && leftSibling.getElementType() == JavaTokenType.LBRACE;
+ }
+
+ private static Spacing getFlyingGeesSpacing(CodeStyleSettings settings) {
+ return Spacing.createSpacing(settings.FLYING_GEESE_BRACES_GAP, settings.FLYING_GEESE_BRACES_GAP, 0, false, 0);
+ }
+}
if (childType == JavaElementType.ANNOTATION) {
return reservedWrapsProvider.getReservedWrap(JavaElementType.MODIFIER_LIST);
}
- ASTNode prevElement = FormattingAstUtil.getPrevElement(child);
+ ASTNode prevElement = FormattingAstUtil.getPrevNonWhiteSpaceNode(child);
if (prevElement != null && prevElement.getElementType() == JavaElementType.ANNOTATION) {
return reservedWrapsProvider.getReservedWrap(JavaElementType.MODIFIER_LIST);
}
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
+import com.intellij.psi.augment.PsiAugmentProvider;
import com.intellij.psi.filters.ElementFilter;
import com.intellij.psi.impl.light.LightClassReference;
import com.intellij.psi.impl.source.PsiClassReferenceType;
@NotNull
public static PsiMethod[] getConstructors(@NotNull PsiClass aClass) {
final List<PsiMethod> constructorsList = new SmartList<PsiMethod>();
+
final PsiMethod[] methods = aClass.getMethods();
for (final PsiMethod method : methods) {
if (method.isConstructor()) constructorsList.add(method);
}
+
+ final List<PsiMethod> augments = PsiAugmentProvider.collectAugments(aClass, PsiMethod.class);
+ for (final PsiMethod method : augments) {
+ if (method.isConstructor()) constructorsList.add(method);
+ }
+
return constructorsList.toArray(new PsiMethod[constructorsList.size()]);
}
return this;
}
+ @NotNull
public String getCanonicalText() {
return myCanonicalText;
}
return new TextRange(0, getTextLength());
}
+ @NotNull
public String getCanonicalText() {
return myPatternExpression.getCanonicalText();
}
return false;
}
+ @NotNull
public String getCanonicalText() {
return myName;
}
return this;
}
+ @NotNull
public String getCanonicalText() {
String name = getQualifiedName();
if (name == null) return null;
return this;
}
+ @NotNull
public String getCanonicalText() {
String name = getQualifiedName();
if (name == null) return null;
return this;
}
+ @NotNull
public String getCanonicalText(){
return getText();
}
return advancedResolve(false).getElement();
}
+ @NotNull
public String getCanonicalText() {
return getContainingClass().getName();
}
return new TextRange(startOffset, startOffset + nameChild.getTextLength());
}
+ @NotNull
public String getCanonicalText() {
String canonicalText = myCanonicalText;
if (canonicalText == null) {
}
}
+ @NotNull
public String getCanonicalText() {
switch (getKind()) {
case CLASS_NAME_KIND:
return null;
}
+ @NotNull
public String getCanonicalText(){
return getElement().getText();
}
return false;
}
+ @NotNull
public String getCanonicalText() {
return getNameElement().getText();
}
import com.intellij.psi.impl.source.tree.Factory;
import com.intellij.psi.impl.source.tree.LeafElement;
import com.intellij.psi.impl.source.tree.SharedImplUtil;
+import com.intellij.psi.infos.CandidateInfo;
import com.intellij.psi.javadoc.PsiDocTagValue;
import com.intellij.psi.javadoc.PsiDocToken;
+import com.intellij.psi.scope.PsiScopeProcessor;
import com.intellij.psi.util.PsiTreeUtil;
-import com.intellij.util.ArrayUtil;
import com.intellij.util.CharTable;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
!(owner instanceof PsiClass)) return null;
final ASTNode valueToken = findChildByType(JavaDocTokenType.DOC_TAG_VALUE_TOKEN);
if (valueToken == null) return null;
- myCachedReference = cachedReference = new PsiReference() {
- public PsiElement resolve() {
- String name = valueToken.getText();
- final PsiElement firstChild = getFirstChild();
- if (firstChild instanceof PsiDocToken && ((PsiDocToken)firstChild).getTokenType().equals(JavaDocTokenType.DOC_TAG_VALUE_LT)) {
- final PsiTypeParameter[] typeParameters = ((PsiTypeParameterListOwner)owner).getTypeParameters();
- for (PsiTypeParameter typeParameter : typeParameters) {
- if (typeParameter.getName().equals(name)) return typeParameter;
- }
+ final String name = valueToken.getText();
+ PsiElement reference = null;
+ final PsiElement firstChild = getFirstChild();
+ if (firstChild instanceof PsiDocToken && ((PsiDocToken)firstChild).getTokenType().equals(JavaDocTokenType.DOC_TAG_VALUE_LT)) {
+ final PsiTypeParameter[] typeParameters = ((PsiTypeParameterListOwner)owner).getTypeParameters();
+ for (PsiTypeParameter typeParameter : typeParameters) {
+ if (typeParameter.getName().equals(name)) {
+ reference = typeParameter;
}
- else if (owner instanceof PsiMethod) {
- final PsiParameter[] parameters = ((PsiMethod)owner).getParameterList().getParameters();
- for (PsiParameter parameter : parameters) {
- if (parameter.getName().equals(name)) return parameter;
- }
+ }
+ }
+ else if (owner instanceof PsiMethod) {
+ final PsiParameter[] parameters = ((PsiMethod)owner).getParameterList().getParameters();
+ for (PsiParameter parameter : parameters) {
+ if (parameter.getName().equals(name)) {
+ reference = parameter;
}
+ }
+ }
- return null;
+ final PsiElement resultReference = reference;
+ myCachedReference = cachedReference = new PsiJavaReference() {
+ public PsiElement resolve() {
+ return resultReference;
}
+ @NotNull
public String getCanonicalText() {
return valueToken.getText();
}
}
@NotNull
- public Object[] getVariants() {
+ public PsiElement[] getVariants() {
final PsiElement firstChild = getFirstChild();
if (firstChild instanceof PsiDocToken && ((PsiDocToken)firstChild).getTokenType().equals(JavaDocTokenType.DOC_TAG_VALUE_LT)) {
return ((PsiTypeParameterListOwner)owner).getTypeParameters();
} else if (owner instanceof PsiMethod) {
return ((PsiMethod)owner).getParameterList().getParameters();
}
- return ArrayUtil.EMPTY_OBJECT_ARRAY;
+ return PsiElement.EMPTY_ARRAY;
}
public boolean isSoft(){
public PsiElement getElement() {
return PsiDocParamRef.this;
}
+
+ public void processVariants(PsiScopeProcessor processor) {
+ for (final PsiElement element : getVariants()) {
+ if (!processor.execute(element, ResolveState.initial())) {
+ return;
+ }
+ }
+ }
+
+ @NotNull
+ public JavaResolveResult advancedResolve(boolean incompleteCode) {
+ return resultReference == null ? JavaResolveResult.EMPTY : new CandidateInfo(resultReference, PsiSubstitutor.EMPTY);
+ }
+
+ @NotNull
+ public JavaResolveResult[] multiResolve(boolean incompleteCode) {
+ return resultReference == null
+ ? JavaResolveResult.EMPTY_ARRAY
+ : new JavaResolveResult[]{new CandidateInfo(resultReference, PsiSubstitutor.EMPTY)};
+ }
};
return cachedReference;
}
return myRange;
}
+ @NotNull
public String getCanonicalText() {
return myText;
}
return MethodSignatureUtil.findMethodBySignature(refClass, signature, false);
}
+ @NotNull
public String getCanonicalText() {
String name = getName();
return name != null ? name : PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME;
return null;
}
+ @NotNull
public String getCanonicalText() {
return null;
}
import com.intellij.psi.tree.ChildRoleBase;
import org.jetbrains.annotations.NotNull;
-public class PsiPackageStatementImpl extends CompositePsiElement implements PsiPackageStatement, Constants {
+public class PsiPackageStatementImpl extends CompositePsiElement implements PsiPackageStatement {
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.source.tree.java.PsiPackageStatementImpl");
public PsiPackageStatementImpl() {
- super(PACKAGE_STATEMENT);
+ super(Constants.PACKAGE_STATEMENT);
}
public PsiJavaCodeReferenceElement getPackageReference() {
public String getPackageName() {
PsiJavaCodeReferenceElement ref = getPackageReference();
- return SourceUtil.getTextSkipWhiteSpaceAndComments(SourceTreeToPsiMap.psiElementToTree(ref));
+ return ref == null ? null : SourceUtil.getTextSkipWhiteSpaceAndComments(SourceTreeToPsiMap.psiElementToTree(ref));
}
public PsiModifierList getAnnotationList() {
return null;
case ChildRole.PACKAGE_KEYWORD:
- return findChildByType(PACKAGE_KEYWORD);
+ return findChildByType(Constants.PACKAGE_KEYWORD);
case ChildRole.PACKAGE_REFERENCE:
- return findChildByType(JAVA_CODE_REFERENCE);
+ return findChildByType(Constants.JAVA_CODE_REFERENCE);
case ChildRole.CLOSING_SEMICOLON:
- return TreeUtil.findChildBackward(this, SEMICOLON);
+ return TreeUtil.findChildBackward(this, Constants.SEMICOLON);
case ChildRole.MODIFIER_LIST:
- return findChildByType(MODIFIER_LIST);
+ return findChildByType(Constants.MODIFIER_LIST);
}
}
public int getChildRole(ASTNode child) {
LOG.assertTrue(child.getTreeParent() == this);
IElementType i = child.getElementType();
- if (i == PACKAGE_KEYWORD) {
+ if (i == Constants.PACKAGE_KEYWORD) {
return ChildRole.PACKAGE_KEYWORD;
}
- else if (i == JAVA_CODE_REFERENCE) {
+ else if (i == Constants.JAVA_CODE_REFERENCE) {
return ChildRole.PACKAGE_REFERENCE;
}
- else if (i == SEMICOLON) {
+ else if (i == Constants.SEMICOLON) {
return ChildRole.CLOSING_SEMICOLON;
}
- else if (i == MODIFIER_LIST) {
+ else if (i == Constants.MODIFIER_LIST) {
return ChildRole.MODIFIER_LIST;
}
else {
return (JavaResolveResult[])results;
}
+ @NotNull
public String getCanonicalText() {
PsiElement element = resolve();
if (element instanceof PsiClass) return ((PsiClass)element).getQualifiedName();
protected boolean preprocessUsages(Ref<UsageInfo[]> refUsages) {
MultiMap<PsiElement, String> conflictDescriptions = new MultiMap<PsiElement, String>();
- UsageInfo[] usagesIn = refUsages.get();
+ final UsageInfo[] usagesIn = refUsages.get();
addMethodConflicts(conflictDescriptions);
RenameUtil.addConflictDescriptions(usagesIn, conflictDescriptions);
Set<UsageInfo> usagesSet = new HashSet<UsageInfo>(Arrays.asList(usagesIn));
}
if (myPrepareSuccessfulSwingThreadCallback != null && !conflictDescriptions.isEmpty()) {
- ConflictsDialog dialog = new ConflictsDialog(myProject, conflictDescriptions);
+ ConflictsDialog dialog = new ConflictsDialog(myProject, conflictDescriptions, new Runnable(){
+ public void run() {
+ execute(usagesIn);
+ }
+ });
dialog.show();
if (!dialog.isOK()){
if (dialog.isShowConflicts()) prepareSuccessful();
LOG.error(e);
}
- return showConflicts(conflicts);
+ return showConflicts(conflicts, usagesIn);
}
private void addInaccessibilityConflicts(final UsageInfo[] usages, final MultiMap<PsiElement, String> conflicts) throws IncorrectOperationException {
}
}
}
- return showConflicts(conflicts);
+ return showConflicts(conflicts, refUsages.get());
}
private void checkExistingMethods(PsiMethod[] prototypes, MultiMap<PsiElement, String> conflicts, boolean isGetter) {
if (!myGenerateAccessors) {
calculateInitializersConflicts(conflicts);
- final NecessaryAccessorsVisitor visitor = new NecessaryAccessorsVisitor();
- for (PsiField field : fields) {
- field.accept(visitor);
- }
- for (PsiMethod method : methods) {
- method.accept(visitor);
- }
- for (PsiClass innerClass : innerClasses) {
- innerClass.accept(visitor);
- }
-
- final Set<PsiField> fieldsNeedingGetter = visitor.getFieldsNeedingGetter();
+ final NecessaryAccessorsVisitor visitor = checkNecessaryGettersSetters4ExtractedClass();
+ final NecessaryAccessorsVisitor srcVisitor = checkNecessaryGettersSetters4SourceClass();
+ final Set<PsiField> fieldsNeedingGetter = new LinkedHashSet<PsiField>();
+ fieldsNeedingGetter.addAll(visitor.getFieldsNeedingGetter());
+ fieldsNeedingGetter.addAll(srcVisitor.getFieldsNeedingGetter());
for (PsiField field : fieldsNeedingGetter) {
conflicts.putValue(field, "Field \'" + field.getName() + "\' needs getter");
}
- final Set<PsiField> fieldsNeedingSetter = visitor.getFieldsNeedingSetter();
+ final Set<PsiField> fieldsNeedingSetter = new LinkedHashSet<PsiField>();
+ fieldsNeedingSetter.addAll(visitor.getFieldsNeedingSetter());
+ fieldsNeedingSetter.addAll(srcVisitor.getFieldsNeedingSetter());
for (PsiField field : fieldsNeedingSetter) {
- conflicts.putValue(field, "Field \'" + field.getName() + "\' needs getter");
+ conflicts.putValue(field, "Field \'" + field.getName() + "\' needs setter");
}
}
- return showConflicts(conflicts);
+ return showConflicts(conflicts, refUsages.get());
}
-
+
private void calculateInitializersConflicts(MultiMap<PsiElement, String> conflicts) {
final PsiClassInitializer[] initializers = sourceClass.getInitializers();
for (PsiClassInitializer initializer : initializers) {
}
if (myGenerateAccessors) {
- final NecessaryAccessorsVisitor visitor = new NecessaryAccessorsVisitor();
- for (PsiField field : fields) {
- field.accept(visitor);
- }
- for (PsiMethod method : methods) {
- method.accept(visitor);
- }
- for (PsiClass innerClass : innerClasses) {
- innerClass.accept(visitor);
- }
+ final NecessaryAccessorsVisitor visitor = checkNecessaryGettersSetters4SourceClass();
for (PsiField field : visitor.getFieldsNeedingGetter()) {
sourceClass.add(PropertyUtil.generateGetterPrototype(field));
}
}
}
+ private NecessaryAccessorsVisitor checkNecessaryGettersSetters4SourceClass() {
+ final NecessaryAccessorsVisitor visitor = new NecessaryAccessorsVisitor() {
+ @Override
+ protected boolean hasGetterOrSetter(PsiMethod[] getters) {
+ for (PsiMethod getter : getters) {
+ if (!isInMovedElement(getter)) return true;
+ }
+ return false;
+ }
+
+ @Override
+ protected boolean isProhibitedReference(PsiField field) {
+ if (fields.contains(field)) {
+ return false;
+ }
+ if (innerClasses.contains(field.getContainingClass())) {
+ return false;
+ }
+ return true;
+ }
+ };
+ for (PsiField field : fields) {
+ field.accept(visitor);
+ }
+ for (PsiMethod method : methods) {
+ method.accept(visitor);
+ }
+ for (PsiClass innerClass : innerClasses) {
+ innerClass.accept(visitor);
+ }
+ return visitor;
+ }
+
+ private NecessaryAccessorsVisitor checkNecessaryGettersSetters4ExtractedClass() {
+ final NecessaryAccessorsVisitor visitor = new NecessaryAccessorsVisitor() {
+ @Override
+ protected boolean hasGetterOrSetter(PsiMethod[] getters) {
+ for (PsiMethod getter : getters) {
+ if (isInMovedElement(getter)) return true;
+ }
+ return false;
+ }
+
+ @Override
+ protected boolean isProhibitedReference(PsiField field) {
+ if (fields.contains(field)) {
+ return true;
+ }
+ if (innerClasses.contains(field.getContainingClass())) {
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public void visitMethod(PsiMethod method) {
+ if (methods.contains(method)) return;
+ super.visitMethod(method);
+ }
+
+ @Override
+ public void visitField(PsiField field) {
+ if (fields.contains(field)) return;
+ super.visitField(field);
+ }
+
+ @Override
+ public void visitClass(PsiClass aClass) {
+ if (innerClasses.contains(aClass)) return;
+ super.visitClass(aClass);
+ }
+
+ };
+ sourceClass.accept(visitor);
+ return visitor;
+ }
+
private void buildDelegate() {
final PsiManager manager = sourceClass.getManager();
final GlobalSearchScope scope = GlobalSearchScope.allScope(project);
final String qualifiedName = StringUtil.getQualifiedName(newPackageName, newClassName);
- @NonNls final String getter = PropertyUtil.suggestGetterName(myProject, field);
- @NonNls final String setter = PropertyUtil.suggestSetterName(myProject, field);
+ @NonNls String getter = null;
+ if (myGenerateAccessors) {
+ getter = PropertyUtil.suggestGetterName(myProject, field);
+ } else {
+ final PsiMethod fieldGetter = PropertyUtil.findPropertyGetter(sourceClass, field.getName(), false, false);
+ if (fieldGetter != null && isInMovedElement(fieldGetter)) {
+ getter = fieldGetter.getName();
+ }
+ }
+
+ @NonNls String setter = null;
+ if (myGenerateAccessors) {
+ setter = PropertyUtil.suggestSetterName(myProject, field);
+ } else {
+ final PsiMethod fieldSetter = PropertyUtil.findPropertySetter(sourceClass, field.getName(), false, false);
+ if (fieldSetter != null && isInMovedElement(fieldSetter)) {
+ setter = fieldSetter.getName();
+ }
+ }
final boolean isStatic = field.hasModifierProperty(PsiModifier.STATIC);
for (PsiReference reference : ReferencesSearch.search(field, scope)) {
if (RefactoringUtil.isPlusPlusOrMinusMinus(exp.getParent())) {
usages.add(isStatic
? new ReplaceStaticVariableIncrementDecrement(exp, qualifiedName)
- : new ReplaceInstanceVariableIncrementDecrement(exp, delegateFieldName, setter, getter));
+ : new ReplaceInstanceVariableIncrementDecrement(exp, delegateFieldName, setter, getter, field.getName()));
}
else if (RefactoringUtil.isAssignmentLHS(exp)) {
usages.add(isStatic
? new ReplaceStaticVariableAssignment(exp, qualifiedName)
: new ReplaceInstanceVariableAssignment(PsiTreeUtil.getParentOfType(exp, PsiAssignmentExpression.class),
- delegateFieldName, setter, getter));
+ delegateFieldName, setter, getter, field.getName()));
}
else {
usages.add(isStatic
? new ReplaceStaticVariableAccess(exp, qualifiedName)
- : new ReplaceInstanceVariableAccess(exp, delegateFieldName, getter));
+ : new ReplaceInstanceVariableAccess(exp, delegateFieldName, getter, field.getName()));
}
if (!isStatic) {
}
}
- private boolean hasGetter(final PsiField field) {
- return hasGetterOrSetter(sourceClass.findMethodsBySignature(PropertyUtil.generateGetterPrototype(field), false));
- }
-
- private boolean hasSetter(final PsiField field) {
- return hasGetterOrSetter(sourceClass.findMethodsBySignature(PropertyUtil.generateSetterPrototype(field), false));
- }
-
- private boolean hasGetterOrSetter(final PsiMethod[] getters) {
- for (PsiMethod getter : getters) {
- if (!isInMovedElement(getter)) return true;
- }
- return false;
- }
-
private PsiClass buildClass() {
final PsiManager manager = sourceClass.getManager();
extractedClassBuilder.setInterfaces(interfaces);
if (myGenerateAccessors) {
- final NecessaryAccessorsVisitor visitor = new NecessaryAccessorsVisitor() {
- @Override
- protected boolean isProhibitedReference(PsiField field) {
- if (fields.contains(field)) {
- return true;
- }
- if (innerClasses.contains(field.getContainingClass())) {
- return true;
- }
- return false;
- }
- };
+ final NecessaryAccessorsVisitor visitor = checkNecessaryGettersSetters4ExtractedClass();
sourceClass.accept(visitor);
extractedClassBuilder.setFieldsNeedingGetters(visitor.getFieldsNeedingGetter());
extractedClassBuilder.setFieldsNeedingSetters(visitor.getFieldsNeedingSetter());
return true;
}
- private class NecessaryAccessorsVisitor extends JavaRecursiveElementWalkingVisitor {
+ private abstract class NecessaryAccessorsVisitor extends JavaRecursiveElementWalkingVisitor {
private final Set<PsiField> fieldsNeedingGetter = new HashSet<PsiField>();
private final Set<PsiField> fieldsNeedingSetter = new HashSet<PsiField>();
super.visitReferenceExpression(expression);
if (isProhibitedReference(expression)) {
final PsiField field = getReferencedField(expression);
- if (!hasGetter(field) && !isStaticFinal(field)) {
+ if (!hasGetter(field) && !isStaticFinal(field) && !field.getModifierList().hasModifierProperty(PsiModifier.PUBLIC)) {
fieldsNeedingGetter.add(field);
}
}
final PsiExpression lhs = expression.getLExpression();
if (isProhibitedReference(lhs)) {
final PsiField field = getReferencedField(lhs);
- if (!hasGetter(field) && !isStaticFinal(field)) {
+ if (!hasGetter(field) && !isStaticFinal(field) && !field.getModifierList().hasModifierProperty(PsiModifier.PUBLIC)) {
fieldsNeedingSetter.add(field);
}
}
return fieldsNeedingSetter;
}
+ private boolean hasGetter(final PsiField field) {
+ return hasGetterOrSetter(sourceClass.findMethodsBySignature(PropertyUtil.generateGetterPrototype(field), false));
+ }
+
+ private boolean hasSetter(final PsiField field) {
+ return hasGetterOrSetter(sourceClass.findMethodsBySignature(PropertyUtil.generateSetterPrototype(field), false));
+ }
+
+ protected abstract boolean hasGetterOrSetter(final PsiMethod[] getters);
protected boolean isProhibitedReference(PsiExpression expression) {
return BackpointerUtil.isBackpointerReference(expression, new Condition<PsiField>() {
});
}
- protected boolean isProhibitedReference(PsiField field) {
- if (fields.contains(field)) {
- return false;
- }
- if (innerClasses.contains(field.getContainingClass())) {
- return false;
- }
- return true;
- }
+ protected abstract boolean isProhibitedReference(PsiField field);
private PsiField getReferencedField(PsiExpression expression) {
if (expression instanceof PsiParenthesizedExpression) {
public class ReplaceInstanceVariableAccess extends FixableUsageInfo {
private final PsiReferenceExpression expression;
+ private final String fieldName;
private final String getterName;
private final String delegateName;
- public ReplaceInstanceVariableAccess(PsiReferenceExpression expression, String delegateName, String getterName) {
+ public ReplaceInstanceVariableAccess(PsiReferenceExpression expression, String delegateName, String getterName, String name) {
super(expression);
this.getterName = getterName;
this.delegateName = delegateName;
this.expression = expression;
+ fieldName = name;
}
public void fixUsage() throws IncorrectOperationException {
final PsiElement qualifier = expression.getQualifier();
- final String callString = delegateName + '.' + getterName + "()";
+ final String callString = delegateName + '.' + (getterName != null ? getterName + "()" : fieldName);
if (qualifier != null) {
final String qualifierText = qualifier.getText();
MutationUtils.replaceExpression(qualifierText + '.' + callString, expression);
import com.intellij.util.IncorrectOperationException;
public class ReplaceInstanceVariableAssignment extends FixableUsageInfo {
- private final String setterName;
- private final PsiAssignmentExpression assignment;
- private final String getterName;
- private final String delegateName;
+ private final String setterName;
+ private final PsiAssignmentExpression assignment;
+ private final String getterName;
+ private final String delegateName;
+ private final String fieldName;
- public ReplaceInstanceVariableAssignment(PsiAssignmentExpression assignment,
- String delegateName,
- String setterName,
- String getterName) {
- super(assignment);
- this.assignment = assignment;
- this.getterName = getterName;
- this.setterName = setterName;
- this.delegateName = delegateName;
- }
+ public ReplaceInstanceVariableAssignment(PsiAssignmentExpression assignment,
+ String delegateName,
+ String setterName,
+ String getterName, String name) {
+ super(assignment);
+ this.assignment = assignment;
+ this.getterName = getterName;
+ this.setterName = setterName;
+ this.delegateName = delegateName;
+ fieldName = name;
+ }
- public void fixUsage() throws IncorrectOperationException {
- final PsiReferenceExpression lhs =
- (PsiReferenceExpression) assignment.getLExpression();
- final PsiExpression rhs = assignment.getRExpression();
- assert rhs != null;
- final PsiElement qualifier = lhs.getQualifier();
- final PsiJavaToken sign = assignment.getOperationSign();
- final String operator = sign.getText();
- final String rhsText = rhs.getText();
- final String newExpression;
- if (qualifier != null) {
- final String qualifierText = qualifier.getText();
- if ("=".equals(operator)) {
- newExpression = qualifierText + '.' + delegateName + '.' + setterName + "( " + rhsText + ')';
- } else {
- final String strippedOperator = getStrippedOperator(operator);
- newExpression = qualifierText + '.'+delegateName + '.' + setterName + '(' + qualifierText + '.'+delegateName + '.' + getterName + "()" + strippedOperator + rhsText + ')';
- }
- } else {
- if ("=".equals(operator)) {
- newExpression = delegateName + '.' + setterName + "( " + rhsText + ')';
- } else {
- final String strippedOperator = getStrippedOperator(operator);
- newExpression = delegateName + '.' + setterName + '(' + delegateName + '.' + getterName + "()" + strippedOperator + rhsText + ')';
- }
- }
- MutationUtils.replaceExpression(newExpression, assignment);
+ public void fixUsage() throws IncorrectOperationException {
+ final PsiReferenceExpression lhs =
+ (PsiReferenceExpression)assignment.getLExpression();
+ final PsiExpression rhs = assignment.getRExpression();
+ assert rhs != null;
+ final PsiElement qualifier = lhs.getQualifier();
+ final PsiJavaToken sign = assignment.getOperationSign();
+ final String operator = sign.getText();
+ final String rhsText = rhs.getText();
+ final String newExpression;
+ if (qualifier != null) {
+ final String qualifierText = qualifier.getText();
+ if ("=".equals(operator)) {
+ newExpression = qualifierText + '.' + delegateName + '.' + callSetter(rhsText);
+ }
+ else {
+ final String strippedOperator = getStrippedOperator(operator);
+ newExpression = qualifierText +
+ '.' +
+ delegateName +
+ '.' +
+ callSetter(
+ qualifierText +
+ '.' +
+ delegateName +
+ '.' +
+ callGetter() + strippedOperator + rhsText);
+ }
}
-
- private static String getStrippedOperator(String operator) {
- return operator.substring(0, operator.length() - 1);
+ else {
+ if ("=".equals(operator)) {
+ newExpression = delegateName + '.' + callSetter(rhsText);
+ }
+ else {
+ final String strippedOperator = getStrippedOperator(operator);
+ newExpression = delegateName + '.' + callSetter(delegateName + '.' + callGetter() + strippedOperator + rhsText);
+ }
}
+ MutationUtils.replaceExpression(newExpression, assignment);
+ }
+
+ private String callSetter(String rhsText) {
+ return setterName != null ? setterName + "( " + rhsText + ")" : fieldName + "=" + rhsText;
+ }
+
+ private String callGetter() {
+ return getterName != null ? getterName + "()" : fieldName;
+ }
+
+ private static String getStrippedOperator(String operator) {
+ return operator.substring(0, operator.length() - 1);
+ }
}
import com.intellij.refactoring.psi.MutationUtils;
import com.intellij.refactoring.util.FixableUsageInfo;
import com.intellij.util.IncorrectOperationException;
+import org.jetbrains.annotations.Nullable;
public class ReplaceInstanceVariableIncrementDecrement extends FixableUsageInfo {
private final PsiExpression reference;
- private final String setterName;
- private final String getterName;
+ private final @Nullable String setterName;
+ private final @Nullable String getterName;
private final String delegateName;
+ private final String fieldName;
- public ReplaceInstanceVariableIncrementDecrement(PsiExpression reference, String delegateName, String setterName, String getterName) {
+ public ReplaceInstanceVariableIncrementDecrement(PsiExpression reference,
+ String delegateName,
+ String setterName,
+ String getterName,
+ String name) {
super(reference);
this.getterName = getterName;
this.setterName = setterName;
this.delegateName = delegateName;
+ fieldName = name;
final PsiPrefixExpression prefixExpr = PsiTreeUtil.getParentOfType(reference, PsiPrefixExpression.class);
if (prefixExpr != null) {
this.reference = prefixExpr;
final PsiElement qualifier = lhs.getQualifier();
final String operator = sign.getText();
final String newExpression;
+ final String strippedOperator = getStrippedOperator(operator);
if (qualifier != null) {
final String qualifierText = qualifier.getText();
- final String strippedOperator = getStrippedOperator(operator);
- newExpression = qualifierText +
- '.' +
- delegateName +
- '.' +
- setterName +
- '(' +
- qualifierText +
- '.' +
- delegateName +
- '.' +
- getterName +
- "()" +
- strippedOperator +
- "1)";
+ newExpression = qualifierText + '.' + delegateName + '.' +
+ callSetter(qualifierText + '.' + delegateName + '.' + callGetter() + strippedOperator + "1");
}
else {
- final String strippedOperator = getStrippedOperator(operator);
- newExpression = delegateName + '.' + setterName + '(' + delegateName + '.' + getterName + "()" + strippedOperator + "1)";
+ newExpression = delegateName + '.' + callSetter(delegateName + '.' + callGetter() + strippedOperator + "1");
}
MutationUtils.replaceExpression(newExpression, reference);
}
+ private String callGetter() {
+ return (getterName != null ? getterName + "()" : fieldName);
+ }
+
+ private String callSetter(String rhsText) {
+ return setterName != null ? setterName + "(" + rhsText + ")" : fieldName + "=" + rhsText;
+ }
+
private static String getStrippedOperator(String operator) {
return operator.substring(0, operator.length() - 1);
}
}
protected boolean preprocessUsages(Ref<UsageInfo[]> refUsages) {
- UsageInfo[] usagesIn = refUsages.get();
+ final UsageInfo[] usagesIn = refUsages.get();
ArrayList<UsageInfo> oldUsages = new ArrayList<UsageInfo>();
addAll(oldUsages, usagesIn);
final ObjectUpcastedUsageInfo[] objectUpcastedUsageInfos = objectUpcastedUsages(usagesIn);
analyzeConflicts(usagesIn, conflicts);
if (!conflicts.isEmpty()) {
ConflictsDialog conflictsDialog =
- new ConflictsDialog(myProject, conflicts);
+ new ConflictsDialog(myProject, conflicts, new Runnable() {
+ public void run() {
+ execute(usagesIn);
+ }
+ });
conflictsDialog.show();
if (!conflictsDialog.isOK()){
if (conflictsDialog.isShowConflicts()) prepareSuccessful();
}
}
- return showConflicts(conflicts);
+ return showConflicts(conflicts, usagesIn);
}
private static boolean isAccessedForWriting (PsiExpression expr) {
*/
package com.intellij.refactoring.inline;
+import com.intellij.codeInsight.TargetElementUtilBase;
import com.intellij.codeInsight.highlighting.HighlightManager;
import com.intellij.codeInsight.intention.QuickFixFactory;
-import com.intellij.codeInsight.TargetElementUtilBase;
-import com.intellij.lang.refactoring.InlineActionHandler;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.diagnostic.Logger;
}
}
- if (checkRefsInAugmentedAssignment(refsToInline, project, editor, localName)) {
+ if (checkRefsInAugmentedAssignmentOrUnaryModified(refsToInline, project, editor, localName)) {
return;
}
}, RefactoringBundle.message("inline.command", localName), null);
}
- private static boolean checkRefsInAugmentedAssignment(final PsiElement[] refsToInline, final Project project, final Editor editor,
+ private static boolean checkRefsInAugmentedAssignmentOrUnaryModified(final PsiElement[] refsToInline, final Project project, final Editor editor,
final String localName) {
- for(PsiElement element: refsToInline) {
- if (element.getParent() instanceof PsiAssignmentExpression) {
- PsiAssignmentExpression assignmentExpression = (PsiAssignmentExpression) element.getParent();
- if (element == assignmentExpression.getLExpression()) {
- EditorColorsManager manager = EditorColorsManager.getInstance();
- final TextAttributes writeAttributes = manager.getGlobalScheme().getAttributes(EditorColors.WRITE_SEARCH_RESULT_ATTRIBUTES);
- HighlightManager.getInstance(project).addOccurrenceHighlights(editor, new PsiElement[]{element}, writeAttributes, true, null);
-
- String message = RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("variable.is.accessed.for.writing", localName));
- CommonRefactoringUtil.showErrorHint(project, editor, message, REFACTORING_NAME, HelpID.INLINE_VARIABLE);
- WindowManager.getInstance().getStatusBar(project).setInfo(RefactoringBundle.message("press.escape.to.remove.the.highlighting"));
- return true;
- }
+ for (PsiElement element : refsToInline) {
+
+ PsiElement parent = element.getParent();
+ if (parent instanceof PsiArrayAccessExpression) {
+ element = parent;
+ parent = parent.getParent();
+ }
+
+ if (parent instanceof PsiAssignmentExpression && element == ((PsiAssignmentExpression)parent).getLExpression() ||
+ parent instanceof PsiPrefixExpression || parent instanceof PsiPostfixExpression ) {
+
+ EditorColorsManager manager = EditorColorsManager.getInstance();
+ final TextAttributes writeAttributes = manager.getGlobalScheme().getAttributes(EditorColors.WRITE_SEARCH_RESULT_ATTRIBUTES);
+ HighlightManager.getInstance(project).addOccurrenceHighlights(editor, new PsiElement[]{element}, writeAttributes, true, null);
+ String message = RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("variable.is.accessed.for.writing", localName));
+ CommonRefactoringUtil.showErrorHint(project, editor, message, REFACTORING_NAME, HelpID.INLINE_VARIABLE);
+ WindowManager.getInstance().getStatusBar(project).setInfo(RefactoringBundle.message("press.escape.to.remove.the.highlighting"));
+ return true;
}
}
return false;
if (!myInlineThisOnly) {
if (!CommonRefactoringUtil.checkReadOnlyStatus(myProject, myMethod)) return false;
}
- return showConflicts(conflicts);
+ return showConflicts(conflicts, usagesIn);
}
private void addInaccessibleSuperCallsConflicts(final UsageInfo[] usagesIn, final MultiMap<PsiElement, String> conflicts) {
parent = parent.getParent();
}
if (parent instanceof PsiClass) {
- final PsiClass parentClass = (PsiClass)parent;
+ PsiClass parentClass = (PsiClass)parent;
final PsiClass containingClass = myMethod.getContainingClass();
if (InheritanceUtil.isInheritorOrSelf(parentClass, containingClass, true)) {
qualifier = myFactory.createExpressionFromText("this", null);
}
else {
- String name = containingClass.getName();
- if (name != null) {
- qualifier = myFactory.createExpressionFromText(name + ".this", null);
- }
- else { //?
- qualifier = myFactory.createExpressionFromText("this", null);
+ if (PsiTreeUtil.isAncestor(containingClass, parent, false)) {
+ String name = containingClass.getName();
+ if (name != null) {
+ qualifier = myFactory.createExpressionFromText(name + ".this", null);
+ }
+ else { //?
+ qualifier = myFactory.createExpressionFromText("this", null);
+ }
+ } else { // we are inside the inheritor
+ do {
+ parentClass = PsiTreeUtil.getParentOfType(parentClass, PsiClass.class, true);
+ if (InheritanceUtil.isInheritorOrSelf(parentClass, containingClass, true)) {
+ LOG.assertTrue(parentClass != null);
+ final String childClassName = parentClass.getName();
+ qualifier = myFactory.createExpressionFromText(childClassName != null ? childClassName + ".this" : "this", null);
+ break;
+ }
+ }
+ while (parentClass != null);
}
}
}
PsiClassInitializer classInitializer = myFactory.createClassInitializer();
final PsiClass containingClass = field.getContainingClass();
classInitializer = (PsiClassInitializer)containingClass.addAfter(classInitializer, field);
- containingClass.addAfter(CodeEditUtil.createLineFeed(field.getManager()), field);
+ containingClass.addAfter(CodeEditUtil.createLineFeed(field.getManager()), field);
final PsiCodeBlock body = classInitializer.getBody();
PsiExpressionStatement statement = (PsiExpressionStatement)myFactory.createStatementFromText(field.getName() + " = 0;", body);
statement = (PsiExpressionStatement)body.add(statement);
}
}
}
- return showConflicts(conflicts);
+ return showConflicts(conflicts, usages);
}
private static boolean isAccessedForWriting (PsiExpression expr) {
protected boolean preprocessUsages(final Ref<UsageInfo[]> refUsages) {
MultiMap<PsiElement, String> conflicts = getConflicts(refUsages.get());
if (!conflicts.isEmpty()) {
- return showConflicts(conflicts);
+ return showConflicts(conflicts, refUsages.get());
}
return super.preprocessUsages(refUsages);
}
conflicts.put(element, conflictsMap.get(element));
}
checkConflicts(refUsages, conflicts);
- return showConflicts(conflicts);
+ return showConflicts(conflicts, refUsages.get());
}
protected void performRefactoring(final UsageInfo[] usages) {
new PushDownProcessor(mySuperClass.getProject(), myMemberInfos, mySuperClass, new DocCommentPolicy(DocCommentPolicy.ASIS)){
//push down conflicts are already collected
@Override
- protected boolean showConflicts(MultiMap<PsiElement, String> conflicts) {
+ protected boolean showConflicts(MultiMap<PsiElement, String> conflicts, UsageInfo[] usages) {
return true;
}
}.run();
final int offset = editor.getCaretModel().getOffset();
final PsiElement[] statementsInRange = IntroduceVariableBase.findStatementsAtOffset(editor, file, offset);
+
if (statementsInRange.length == 1 && PsiUtil.hasErrorElementChild(statementsInRange[0])) {
editor.getSelectionModel().selectLineAtCaret();
- } else {
+ final ElementToWorkOn elementToWorkOn = getElementToWorkOn(editor, file, refactoringName, helpId, project, localVar, expr);
+ if (elementToWorkOn == null || elementToWorkOn.getLocalVariable() == null && elementToWorkOn.getExpression() == null) {
+ editor.getSelectionModel().removeSelection();
+ }
+ }
+
+ if (!editor.getSelectionModel().hasSelection()){
final List<PsiExpression> expressions = IntroduceVariableBase.collectExpressions(file, editor, offset, statementsInRange);
if (expressions.isEmpty()) {
editor.getSelectionModel().selectLineAtCaret();
processor.findConflicts(this, refUsages.get(), conflicts);
}
- return showConflicts(conflicts);
+ return showConflicts(conflicts, usagesIn);
}
private void detectAccessibilityConflicts(final UsageInfo[] usageArray, MultiMap<PsiElement, String> conflicts) {
protected static String REFACTORING_NAME = RefactoringBundle.message("introduce.variable.title");
public void invoke(@NotNull final Project project, final Editor editor, final PsiFile file, DataContext dataContext) {
- if (!editor.getSelectionModel().hasSelection()) {
+ final SelectionModel selectionModel = editor.getSelectionModel();
+ if (!selectionModel.hasSelection()) {
final int offset = editor.getCaretModel().getOffset();
final PsiElement[] statementsInRange = findStatementsAtOffset(editor, file, offset);
+
+ //try line selection
if (statementsInRange.length == 1 && (PsiUtil.hasErrorElementChild(statementsInRange[0]) || isPreferStatements())) {
- editor.getSelectionModel().selectLineAtCaret();
- } else {
+ selectionModel.selectLineAtCaret();
+ if (findExpressionInRange(project, file, selectionModel.getSelectionStart(), selectionModel.getSelectionEnd()) == null) {
+ selectionModel.removeSelection();
+ }
+ }
+
+ if (!selectionModel.hasSelection()) {
final List<PsiExpression> expressions = collectExpressions(file, editor, offset, statementsInRange);
if (expressions.isEmpty()) {
- editor.getSelectionModel().selectLineAtCaret();
+ selectionModel.selectLineAtCaret();
} else if (expressions.size() == 1) {
final TextRange textRange = expressions.get(0).getTextRange();
- editor.getSelectionModel().setSelection(textRange.getStartOffset(), textRange.getEndOffset());
+ selectionModel.setSelection(textRange.getStartOffset(), textRange.getEndOffset());
}
else {
showChooser(editor, expressions, new Pass<PsiExpression>(){
}
}
}
- if (invoke(project, editor, file, editor.getSelectionModel().getSelectionStart(), editor.getSelectionModel().getSelectionEnd())) {
- editor.getSelectionModel().removeSelection();
+ if (invoke(project, editor, file, selectionModel.getSelectionStart(), selectionModel.getSelectionEnd())) {
+ selectionModel.removeSelection();
}
}
PsiDocumentManager.getInstance(project).commitAllDocuments();
+ return invokeImpl(project, findExpressionInRange(project, file, startOffset, endOffset), editor);
+ }
+
+ private static PsiExpression findExpressionInRange(Project project, PsiFile file, int startOffset, int endOffset) {
PsiExpression tempExpr = CodeInsightUtil.findExpressionInRange(file, startOffset, endOffset);
if (tempExpr == null) {
PsiElement[] statements = CodeInsightUtil.findStatementsInRange(file, startOffset, endOffset);
if (tempExpr == null) {
tempExpr = getSelectedExpression(project, file, startOffset, endOffset);
}
- return invokeImpl(project, tempExpr, editor);
+ return tempExpr;
}
public static PsiExpression getSelectedExpression(final Project project, final PsiFile file, final int startOffset, final int endOffset) {
}
}
}
- return showConflicts(conflicts);
+ return showConflicts(conflicts, refUsages.get());
}
public void findUsages(@NotNull List<FixableUsageInfo> usages) {
return new MakeMethodOrClassStaticViewDescriptor(myMember);
}
- protected final boolean preprocessUsages(Ref<UsageInfo[]> refUsages) {
+ protected final boolean preprocessUsages(final Ref<UsageInfo[]> refUsages) {
UsageInfo[] usagesIn = refUsages.get();
if (myPrepareSuccessfulSwingThreadCallback != null) {
MultiMap<PsiElement, String> conflicts = getConflictDescriptions(usagesIn);
if (conflicts.size() > 0) {
- ConflictsDialog conflictsDialog = new ConflictsDialog(myProject, conflicts);
+ ConflictsDialog conflictsDialog = new ConflictsDialog(myProject, conflicts, new Runnable(){
+ public void run() {
+ execute(refUsages.get());
+ }
+ });
conflictsDialog.show();
if (!conflictsDialog.isOK()) {
if (conflictsDialog.isShowConflicts()) prepareSuccessful();
myCreateClassDlg = CreateSubclassAction.chooseSubclassToCreate(myClass);
if (myCreateClassDlg != null) {
pushDownConflicts.checkTargetClassConflicts(null, false, myCreateClassDlg.getTargetDirectory());
- return showConflicts(pushDownConflicts.getConflicts());
+ return showConflicts(pushDownConflicts.getConflicts(), usagesIn);
} else {
return false;
}
}
}
- return showConflicts(pushDownConflicts.getConflicts());
+ return showConflicts(pushDownConflicts.getConflicts(), usagesIn);
}
protected void refreshElements(PsiElement[] elements) {
removeFromTargetClass();
}
catch (IncorrectOperationException e) {
- LOG.assertTrue(false);
+ LOG.error(e);
}
}
}
protected boolean preprocessUsages(final Ref<UsageInfo[]> refUsages) {
- return showConflicts(getConflicts(refUsages.get()));
+ final UsageInfo[] usages = refUsages.get();
+ return showConflicts(getConflicts(usages), usages);
}
protected void refreshElements(final PsiElement[] elements) {
}
refUsages.set(filteredUsages.toArray(new UsageInfo[filteredUsages.size()]));
- return showConflicts(conflicts);
+ return showConflicts(conflicts, usages);
}
private boolean isInsideMoved(PsiElement place) {
conflicts.putValue(psiFile, e.getMessage());
}
}
- return showConflicts(conflicts);
+ return showConflicts(conflicts, refUsages.get());
}
@Override
// if (myInnerClass.hasModifierProperty(PsiModifier.)) {
myOuterClass.accept(new Visitor());
- return showConflicts(conflicts);
+ return showConflicts(conflicts, refUsages.get());
}
private static boolean isInPackage(final PsiFile containingFile, PsiPackage aPackage) {
}
catch (IncorrectOperationException e) {}
- return showConflicts(conflicts);
+ return showConflicts(conflicts, usages);
}
@NotNull
}
analyzeMoveConflicts(myMembersToMove, myTargetClass, myNewVisibility, conflicts);
RefactoringConflictsUtil.analyzeModuleConflicts(myProject, myMembersToMove, usages, myTargetClass, conflicts);
- return showConflicts(conflicts);
+ return showConflicts(conflicts, usages);
}
private void addInaccessiblleConflicts(final MultiMap<PsiElement, String> conflicts, final UsageInfo[] usages) throws IncorrectOperationException {
}
}
}
- return showConflicts(conflicts);
+ return showConflicts(conflicts, refUsages.get());
}
private void processUsagesForMethod(final boolean deleteMethodHierarchy, PsiMethod method, int[] paramPermutation, String getterName, PsiMethod delegatedMethod,
type = ((PsiEllipsisType)type).toArrayType();
}
field = myElementFactory.createField(parameterData.getFieldName(), type);
- builderClass.add(field);
+ field = (PsiField)builderClass.add(field);
}
final String defaultValue = parameterData.getDefaultValue();
conflicts.putValue(null, "Found constructors are not reducible to simple chain");
}
- return showConflicts(conflicts);
+ return showConflicts(conflicts, refUsages.get());
}
protected String getCommandName() {
}
- return showConflicts(conflicts);
+ return showConflicts(conflicts, usages);
}
private PsiClass getConstructorContainingClass() {
conflicts.putValue(existingClass, RefactorJBundle.message("there.already.exists.a.class.with.the.selected.name"));
}
}
- return showConflicts(conflicts);
+ return showConflicts(conflicts, refUsages.get());
}
protected void performRefactoring(UsageInfo[] usageInfos) {
+++ /dev/null
-public class Extracted {
- int myT;
-
- public Extracted() {
- }
-}
\ No newline at end of file
class Test {
- final Extracted extracted = new Extracted();
-
- public int getMyT() {
- return extracted.getMyT();
+ int myT;
+ public int getMyT() {
+ return myT;
}
void bar(){
- int i = extracted.getMyT();
+ int i = myT;
}
}
\ No newline at end of file
void foo(T t){}
void bar(){
- foo(extracted.getMyT());
+ foo(extracted.myT);
}
}
\ No newline at end of file
--- /dev/null
+public class Parent {
+ void execute(){}
+ void foo<caret>execute(){
+ execute();
+ }
+}
+
+class Child extends Parent {
+ void foo() {
+ fooexecute();
+ new Runnable() {
+ public void run() {
+ fooexecute();
+ }
+ }.run();
+ }
+
+ class InnerChild {
+ void bar() {
+ Child.this.fooexecute();
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+public class Parent {
+ void execute(){}
+}
+
+class Child extends Parent {
+ void foo() {
+ execute();
+ new Runnable() {
+ public void run() {
+ execute();
+ }
+ }.run();
+ }
+
+ class InnerChild {
+ void bar() {
+ execute();
+ }
+ }
+}
\ No newline at end of file
public class Builder {
- private int i;
+ private int i = 2;
public Builder setI(int i) {
this.i = i;
package com.intellij;
import com.intellij.openapi.application.PathManager;
+import com.intellij.testFramework.TestRunnerUtil;
+import junit.framework.TestCase;
import org.jetbrains.annotations.NonNls;
+import org.jetbrains.annotations.Nullable;
import java.io.File;
+import java.util.*;
+
+import static com.intellij.openapi.util.io.FileUtil.toSystemDependentName;
+import static java.util.Arrays.asList;
/**
* @author yole
*/
public class JavaTestUtil {
+
@NonNls private static final String JAVA_TEST_DATA = "java/java-tests/testData";
public static String getJavaTestDataPath() {
}
return new File(homePath, JAVA_TEST_DATA).getPath();
}
+
+ private enum TestGroup {
+ ULTIMATE, COMMUNITY
+ }
+
+ /**
+ * It's assumed that test data location for both <code>community</code> and <code>ultimate</code> tests follows the same template:
+ * <code>'<IDEA_HOME>/<RELATIVE_PATH>'</code>.
+ * <p/>
+ * <code>'IDEA_HOME'</code> here stands for path to IDEA installation; <code>'RELATIVE_PATH'</code> defines a path to
+ * test data relative to IDEA installation path. That relative path may be different for <code>community</code>
+ * and <code>ultimate</code> tests.
+ * <p/>
+ * This collection contains mappings from test group type to relative paths to use, i.e. it's possible to define more than one
+ * relative path for the single test group. It's assumed that path definition algorithm iterates them and checks if
+ * resulting absolute path points to existing directory. The one is returned in case of success; last path is returned otherwise.
+ * <p/>
+ * Hence, the order of relative paths for the single test group matters.
+ */
+ private static final Map<TestGroup, List<String>> TEST_DATA_RELATIVE_PATHS = new EnumMap<TestGroup, List<String>>(TestGroup.class);
+ static {
+ TEST_DATA_RELATIVE_PATHS.put(TestGroup.ULTIMATE, Collections.singletonList(toSystemDependentName("/testData")));
+
+ List<String> communityPathEndings = new ArrayList<String>();
+ String communityEnding = toSystemDependentName("java/java-tests/testData");
+ communityPathEndings.add(toSystemDependentName("community/" + communityEnding));
+ communityPathEndings.add(communityEnding);
+ TEST_DATA_RELATIVE_PATHS.put(TestGroup.COMMUNITY, communityPathEndings);
+ }
+
+ private JavaTestUtil() {
+ }
+
+ @NonNls
+ public static String getJavaTestDataPath2() {
+ String homePath = PathManager.getHomePath();
+ TestGroup testGroup = determineTestGroup();
+ List<String> relativePaths = TEST_DATA_RELATIVE_PATHS.get(testGroup);
+ if (relativePaths.isEmpty()) {
+ throw new IllegalStateException(
+ String.format("Can't determine test data path. Reason: no predefined relative paths are configured for test group %s. "
+ + "Configured mappings: %s", testGroup, TEST_DATA_RELATIVE_PATHS)
+ );
+ }
+
+ File candidate = null;
+ for (String relativePath : relativePaths) {
+ candidate = new File(homePath, relativePath);
+ if (candidate.isDirectory()) {
+ return candidate.getPath();
+ }
+ }
+
+ if (candidate == null) {
+ throw new IllegalStateException("Can't determine test data path. Looks like programming error - reached 'if' block that was "
+ + "never expected to be executed");
+ }
+ return candidate.getPath();
+ }
+
+ @SuppressWarnings({"ThrowableInstanceNeverThrown"})
+ private static TestGroup determineTestGroup() {
+ for (StackTraceElement stackTraceElement : new Exception().getStackTrace()) {
+ Class<?> clazz = loadClass(stackTraceElement.getClassName());
+ if (isJUnitClass(clazz)) {
+ return determineTestGroup(clazz);
+ }
+ }
+ return TestGroup.ULTIMATE;
+ }
+
+ private static Class<?> loadClass(String className) {
+ Class<?> clazz = null;
+ ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
+ ClassLoader definingClassLoader = JavaTestUtil.class.getClassLoader();
+ ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
+
+ List<ClassLoader> classLoaders = asList(contextClassLoader, definingClassLoader, systemClassLoader);
+ for (ClassLoader classLoader : classLoaders) {
+ clazz = loadClass(className, classLoader);
+ if (clazz != null) {
+ break;
+ }
+ }
+
+ if (clazz == null) {
+ throw new IllegalStateException(String.format("Can't load class '%s'. Tried to do that via thread context class loader(%s), "
+ + "defining class loader(%s) and system class loader(%s)",
+ className, contextClassLoader, definingClassLoader, systemClassLoader));
+ }
+ return clazz;
+ }
+
+ @Nullable
+ private static Class<?> loadClass(String className, ClassLoader classLoader) {
+ try {
+ return Class.forName(className, true, classLoader);
+ }
+ catch (ClassNotFoundException e) {
+ return null;
+ }
+ }
+
+ private static boolean isJUnitClass(Class<?> clazz) {
+ return TestCase.class.isAssignableFrom(clazz) || TestRunnerUtil.isJUnit4TestClass(clazz);
+ }
+
+ public static TestGroup determineTestGroup(Class<?> clazz) {
+ String rootPath = PathManager.getResourceRoot(clazz, toSystemDependentName(clazz.getName().replace('.', '/') + ".class"));
+ return rootPath != null && rootPath.indexOf("community") >= 0 ? TestGroup.COMMUNITY : TestGroup.ULTIMATE;
+ }
}
--- /dev/null
+/*
+ * Copyright 2000-2010 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.intellij.psi.formatter;
+
+import com.intellij.JavaTestUtil;
+import com.intellij.openapi.application.ApplicationManager;
+import com.intellij.openapi.command.CommandProcessor;
+import com.intellij.openapi.editor.Document;
+import com.intellij.openapi.editor.EditorFactory;
+import com.intellij.openapi.editor.ex.DocumentEx;
+import com.intellij.openapi.editor.impl.DocumentImpl;
+import com.intellij.openapi.util.TextRange;
+import com.intellij.openapi.util.io.FileUtil;
+import com.intellij.openapi.util.text.StringUtil;
+import com.intellij.psi.PsiDocumentManager;
+import com.intellij.psi.PsiFile;
+import com.intellij.psi.codeStyle.CodeStyleManager;
+import com.intellij.psi.codeStyle.CodeStyleSettings;
+import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
+import com.intellij.testFramework.LightIdeaTestCase;
+import com.intellij.util.IncorrectOperationException;
+
+import java.io.File;
+
+/**
+ * Base class for java formatter tests that holds utility methods.
+ *
+ * @author Denis Zhdanov
+ * @since Apr 27, 2010 6:26:29 PM
+ */
+public abstract class AbstractJavaFormattingTest extends LightIdeaTestCase {
+
+ private static final String BASE_PATH = JavaTestUtil.getJavaTestDataPath() + "/psi/formatter/java";
+
+ public TextRange myTextRange;
+ public TextRange myLineRange;
+
+ public static CodeStyleSettings getSettings() {
+ return CodeStyleSettingsManager.getSettings(getProject());
+ }
+
+ public void doTest() throws Exception {
+ doTest(getTestName(false) + ".java", getTestName(false) + "_after.java");
+ }
+
+ public void doTest(String fileNameBefore, String fileNameAfter) throws Exception {
+ doTextTest(loadFile(fileNameBefore), loadFile(fileNameAfter));
+ }
+
+ public void doTextTest(final String text, String textAfter) throws IncorrectOperationException {
+ final PsiFile file = createPseudoPhysicalFile("A.java", text);
+
+ if (myLineRange != null) {
+ final DocumentImpl document = new DocumentImpl(text);
+ myTextRange =
+ new TextRange(document.getLineStartOffset(myLineRange.getStartOffset()), document.getLineEndOffset(myLineRange.getEndOffset()));
+ }
+
+ /*
+ CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
+ public void run() {
+ ApplicationManager.getApplication().runWriteAction(new Runnable() {
+ public void run() {
+ performFormatting(file);
+ }
+ });
+ }
+ }, null, null);
+
+ assertEquals(prepareText(textAfter), prepareText(file.getText()));
+
+
+ */
+
+ final PsiDocumentManager manager = PsiDocumentManager.getInstance(getProject());
+ final Document document = manager.getDocument(file);
+
+
+ CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
+ public void run() {
+ ApplicationManager.getApplication().runWriteAction(new Runnable() {
+ public void run() {
+ document.replaceString(0, document.getTextLength(), text);
+ manager.commitDocument(document);
+ try {
+ if (myTextRange != null) {
+ CodeStyleManager.getInstance(getProject()).reformatText(file, myTextRange.getStartOffset(), myTextRange.getEndOffset());
+ }
+ else {
+ CodeStyleManager.getInstance(getProject())
+ .reformatText(file, file.getTextRange().getStartOffset(), file.getTextRange().getEndOffset());
+ }
+ }
+ catch (IncorrectOperationException e) {
+ assertTrue(e.getLocalizedMessage(), false);
+ }
+ }
+ });
+ }
+ }, "", "");
+
+
+ if (document == null) {
+ fail("Don't expect the document to be null");
+ return;
+ }
+ assertEquals(prepareText(textAfter), prepareText(document.getText()));
+ manager.commitDocument(document);
+ assertEquals(prepareText(textAfter), prepareText(file.getText()));
+
+ }
+
+ public void doMethodTest(final String before, final String after) throws Exception {
+ doTextTest("class Foo{\n" + " void foo() {\n" + before + '\n' + " }\n" + "}",
+ "class Foo {\n" + " void foo() {\n" + StringUtil.shiftIndentInside(after, 8, false) + '\n' + " }\n" + "}");
+ }
+
+ public void doClassTest(final String before, final String after) throws Exception {
+ doTextTest("class Foo{\n" + before + '\n' + "}", "class Foo {\n" + StringUtil.shiftIndentInside(after, 4, false) + '\n' + "}");
+ }
+
+ private static String prepareText(String actual) {
+ if (actual.startsWith("\n")) {
+ actual = actual.substring(1);
+ }
+ if (actual.startsWith("\n")) {
+ actual = actual.substring(1);
+ }
+
+ // Strip trailing spaces
+ final Document doc = EditorFactory.getInstance().createDocument(actual);
+ CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
+ public void run() {
+ ApplicationManager.getApplication().runWriteAction(new Runnable() {
+ public void run() {
+ ((DocumentEx)doc).stripTrailingSpaces(false);
+ }
+ });
+ }
+ }, "formatting", null);
+
+ return doc.getText();
+ }
+
+ private static String loadFile(String name) throws Exception {
+ String fullName = BASE_PATH + File.separatorChar + name;
+ String text = new String(FileUtil.loadFileText(new File(fullName)));
+ text = StringUtil.convertLineSeparators(text);
+ return text;
+ }
+}
--- /dev/null
+/*
+ * Copyright 2000-2010 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.intellij.psi.formatter;
+
+import com.intellij.openapi.fileTypes.StdFileTypes;
+import com.intellij.psi.codeStyle.CodeStyleSettings;
+
+/**
+ * Is intended to hold specific java formatting tests for alignment settings (
+ * <code>Project Settings - Code Style - Alignment and Braces</code>).
+ *
+ * @author Denis Zhdanov
+ * @since Apr 27, 2010 6:42:00 PM
+ */
+public class JavaFormatterAlignmentTest extends AbstractJavaFormattingTest {
+
+ public void testChainedMethodsAlignment() throws Exception {
+ // Inspired by IDEA-30369
+ getSettings().ALIGN_MULTILINE_CHAINED_METHODS = true;
+ getSettings().METHOD_CALL_CHAIN_WRAP = CodeStyleSettings.WRAP_AS_NEEDED;
+ getSettings().getIndentOptions(StdFileTypes.JAVA).CONTINUATION_INDENT_SIZE = 8;
+ doTest();
+ }
+
+}
--- /dev/null
+/*
+ * Copyright 2000-2010 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.intellij.psi.formatter;
+
+/**
+ * Is intended to hold specific java formatting tests for <code>'Place on New Line'</code> settings (
+ * <code>Project Settings - Code Style - Alignment and Braces - Place on New Line</code>).
+ *
+ * @author Denis Zhdanov
+ * @since Apr 28, 2010 12:12:13 PM
+ */
+public class JavaFormatterNewLineTest extends AbstractJavaFormattingTest {
+
+ public void testAutomaticElseUnwrapping() throws Exception {
+ getSettings().ELSE_ON_NEW_LINE = false;
+ getSettings().KEEP_LINE_BREAKS = true;
+
+ // Inspired by IDEA-47809
+ doMethodTest(
+
+ "if (b) {\n" +
+ "}\n" +
+ "else {\n" +
+ "}",
+
+ "if (b) {\n" +
+ "} else {\n" +
+ "}"
+ );
+ }
+
+ public void testAutomaticCatchUnwrapping() throws Exception {
+ getSettings().CATCH_ON_NEW_LINE = false;
+ getSettings().KEEP_LINE_BREAKS = true;
+
+ // Inspired by IDEA-47809
+ doMethodTest(
+
+ "try {\n" +
+ "}\n" +
+ "catch (Exception e) {\n" +
+ "}",
+
+ "try {\n" +
+ "} catch (Exception e) {\n" +
+ "}"
+ );
+ }
+
+ public void testAutomaticFinallyUnwrapping() throws Exception {
+ getSettings().FINALLY_ON_NEW_LINE = false;
+ getSettings().KEEP_LINE_BREAKS = true;
+
+ // Inspired by IDEA-47809
+ doMethodTest(
+
+ "try {\n" +
+ "}\n" +
+ "finally {\n" +
+ "}",
+
+ "try {\n" +
+ "} finally {\n" +
+ "}"
+ );
+ }
+
+ public void testAutomaticCatchFinallyUnwrapping() throws Exception {
+ getSettings().CATCH_ON_NEW_LINE = false;
+ getSettings().FINALLY_ON_NEW_LINE = false;
+ getSettings().KEEP_LINE_BREAKS = true;
+
+ // Inspired by IDEA-47809
+ doMethodTest(
+
+ "try {\n" +
+ "}\n" +
+ "catch (Exception e) {\n" +
+ "}\n" +
+ "finally {\n" +
+ "}",
+
+ "try {\n" +
+ "} catch (Exception e) {\n" +
+ "} finally {\n" +
+ "}"
+ );
+ }
+}
package com.intellij.psi.formatter;
-import com.intellij.JavaTestUtil;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
-import com.intellij.openapi.editor.Document;
-import com.intellij.openapi.editor.EditorFactory;
-import com.intellij.openapi.editor.ex.DocumentEx;
-import com.intellij.openapi.editor.impl.DocumentImpl;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.roots.LanguageLevelProjectExtension;
import com.intellij.openapi.util.TextRange;
-import com.intellij.openapi.util.io.FileUtil;
-import com.intellij.openapi.util.text.StringUtil;
import com.intellij.pom.java.LanguageLevel;
-import com.intellij.psi.*;
+import com.intellij.psi.JavaPsiFacade;
+import com.intellij.psi.PsiCodeFragment;
+import com.intellij.psi.PsiElement;
+import com.intellij.psi.PsiElementFactory;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
-import com.intellij.testFramework.LightIdeaTestCase;
import com.intellij.util.IncorrectOperationException;
-import java.io.File;
-
+/**
+ * <b>Note:</b> this class is too huge and hard to use. It's tests are intended to be split in multiple more fine-grained
+ * java formatting test classes.
+ */
@SuppressWarnings({"Deprecation"})
-public class JavaFormatterTest extends LightIdeaTestCase {
- private TextRange myTextRange;
- private TextRange myLineRange;
- private static final String BASE_PATH = JavaTestUtil.getJavaTestDataPath() + "/psi/formatter/java";
-
- public void testSCR915() throws Exception {
- getSettings().SPACE_AROUND_ADDITIVE_OPERATORS = false;
- doTest("SCR915.java", "SCR915_after.java");
- }
+public class JavaFormatterTest extends AbstractJavaFormattingTest {
public void testForEach() throws Exception {
doTest("ForEach.java", "ForEach_after.java");
doTest();
}
- public void testChainedMethodsAlignment() throws Exception {
- getSettings().ALIGN_MULTILINE_CHAINED_METHODS = true;
- getSettings().METHOD_CALL_CHAIN_WRAP = CodeStyleSettings.WRAP_AS_NEEDED;
- getSettings().getIndentOptions(StdFileTypes.JAVA).CONTINUATION_INDENT_SIZE = 8;
- doTest();
- }
-
- public void testNestedMethodsIndentation() throws Exception {
- // Inspired by IDEA-43962
-
- getSettings().getIndentOptions(StdFileTypes.JAVA).CONTINUATION_INDENT_SIZE = 4;
-
- doMethodTest(
- "BigDecimal.ONE\n" +
- " .add(BigDecimal.ONE\n" +
- " .add(BigDecimal.ONE\n" +
- " .add(BigDecimal.ONE\n" +
- " .add(BigDecimal.ONE\n" +
- ".add(BigDecimal.ONE\n" +
- " .add(BigDecimal.ONE\n" +
- " .add(BigDecimal.ONE\n" +
- " .add(BigDecimal.ONE\n" +
- " .add(BigDecimal.ONE)))))))));",
- "BigDecimal.ONE\n" +
- " .add(BigDecimal.ONE\n" +
- " .add(BigDecimal.ONE\n" +
- " .add(BigDecimal.ONE\n" +
- " .add(BigDecimal.ONE\n" +
- " .add(BigDecimal.ONE\n" +
- " .add(BigDecimal.ONE\n" +
- " .add(BigDecimal.ONE\n" +
- " .add(BigDecimal.ONE\n" +
- " .add(BigDecimal.ONE)))))))));"
- );
- }
-
public void testSwitch() throws Exception {
doTest();
}
doTest();
}
- public void testSCR260() throws Exception {
- final CodeStyleSettings settings = getSettings();
- settings.IF_BRACE_FORCE = CodeStyleSettings.FORCE_BRACES_ALWAYS;
- settings.BRACE_STYLE = CodeStyleSettings.END_OF_LINE;
- settings.KEEP_LINE_BREAKS = false;
- doTest();
- }
-
- public void testSCR114() throws Exception {
- final CodeStyleSettings settings = getSettings();
- settings.BRACE_STYLE = CodeStyleSettings.NEXT_LINE;
- settings.CATCH_ON_NEW_LINE = true;
- doTest();
- }
-
- public void testSCR259() throws Exception {
- myTextRange = new TextRange(36, 60);
- final CodeStyleSettings settings = getSettings();
- settings.IF_BRACE_FORCE = CodeStyleSettings.FORCE_BRACES_ALWAYS;
- settings.KEEP_LINE_BREAKS = false;
- doTest();
- }
-
- public void testSCR279() throws Exception {
- final CodeStyleSettings settings = getSettings();
- settings.ALIGN_MULTILINE_BINARY_OPERATION = true;
- doTest();
- }
-
public void testBinaryOperation() throws IncorrectOperationException {
final CodeStyleSettings settings = getSettings();
doTest();
}
- public void testSCR395() throws Exception {
- final CodeStyleSettings settings = getSettings();
- settings.METHOD_BRACE_STYLE = CodeStyleSettings.END_OF_LINE;
- doTest();
- }
-
-
public void testBraces() throws Exception {
final CodeStyleSettings settings = getSettings();
}
- public void testSCR429() throws Exception {
- final CodeStyleSettings settings = getSettings();
- settings.KEEP_BLANK_LINES_IN_CODE = 2;
- settings.KEEP_BLANK_LINES_BEFORE_RBRACE = 2;
- settings.KEEP_BLANK_LINES_IN_DECLARATIONS = 2;
- doTest();
- }
-
- public void testSCR548() throws Exception {
- final CodeStyleSettings settings = getSettings();
- settings.getIndentOptions(StdFileTypes.JAVA).INDENT_SIZE = 4;
- settings.getIndentOptions(StdFileTypes.JAVA).CONTINUATION_INDENT_SIZE = 2;
- doTest();
- }
-
public void testExtendsList() throws Exception {
final CodeStyleSettings settings = getSettings();
settings.ALIGN_MULTILINE_EXTENDS_LIST = true;
"}");
}
- public void testSCR11799() throws Exception {
- final CodeStyleSettings settings = getSettings();
- settings.getIndentOptions(StdFileTypes.JAVA).CONTINUATION_INDENT_SIZE = 4;
- settings.CLASS_BRACE_STYLE = CodeStyleSettings.NEXT_LINE;
- settings.METHOD_BRACE_STYLE = CodeStyleSettings.NEXT_LINE;
- doTest();
- }
-
- public void testSCR501() throws Exception {
- final CodeStyleSettings settings = getSettings();
- settings.KEEP_FIRST_COLUMN_COMMENT = true;
- doTest();
- }
-
- public void testSCR879() throws Exception {
- final CodeStyleSettings settings = getSettings();
- settings.BRACE_STYLE = CodeStyleSettings.NEXT_LINE;
- doTest();
- }
-
public void testDoNotIndentCaseFromSwitch() throws Exception {
final CodeStyleSettings settings = getSettings();
settings.INDENT_CASE_FROM_SWITCH = false;
"}");
}
- public void testSCR547() throws Exception {
- doTextTest("class Foo { \n" +
- " Object[] objs = { \n" +
- " new Object() { \n" +
- " public String toString() { \n" +
- " return \"x\"; \n" +
- " } \n" +
- " } \n" +
- " }; \n" +
-"}", "class Foo {\n" +
- " Object[] objs = {\n" +
- " new Object() {\n" +
- " public String toString() {\n" +
- " return \"x\";\n" +
- " }\n" +
- " }\n" +
- " };\n" +
- "}");
- }
-
- public void testSCR11296() throws Exception {
- final CodeStyleSettings settings = getSettings();
- settings.RIGHT_MARGIN = 50;
- settings.WRAP_COMMENTS = true;
- settings.ENABLE_JAVADOC_FORMATTING = true;
- settings.JD_P_AT_EMPTY_LINES = false;
- settings.JD_KEEP_EMPTY_LINES = false;
- doTest();
- }
-
public void testClass2() throws Exception {
final CodeStyleSettings settings = getSettings();
settings.KEEP_FIRST_COLUMN_COMMENT = false;
"class Foo {\n" + " void foo() {\n" + " return name != null ?1 :2;\n" + " }\n" + "}");
}
- public void testSCR479() throws Exception {
- final CodeStyleSettings settings = getSettings();
- settings.RIGHT_MARGIN = 80;
- settings.TERNARY_OPERATION_WRAP = CodeStyleSettings.WRAP_AS_NEEDED;
- doTextTest("public class Foo {\n" +
- " public static void main(String[] args) {\n" +
- " if (name != null ? !name.equals(that.name) : that.name != null)\n" +
- " return false;\n" +
- " }\n" +
-"}", "public class Foo {\n" +
- " public static void main(String[] args) {\n" +
- " if (name != null ? !name.equals(that.name) : that.name != null)\n" +
- " return false;\n" +
- " }\n" +
- "}");
- }
-
- public void testSCR190() throws Exception {
- final CodeStyleSettings settings = getSettings();
- settings.KEEP_LINE_BREAKS = false;
- doTextTest("public class EntityObject \n" +
- "{ \n" +
- " private Integer id; \n" +
- "\n" +
- " public Integer getId() \n" +
- " { \n" +
- " return id; \n" +
- " } \n" +
- "\n" +
- " public void setId(Integer id) \n" +
- " { \n" +
- " this.id = id; \n" +
- " } \n" +
-"}", "public class EntityObject {\n" +
- " private Integer id;\n" +
- "\n" +
- " public Integer getId() {\n" +
- " return id;\n" +
- " }\n" +
- "\n" +
- " public void setId(Integer id) {\n" +
- " this.id = id;\n" +
- " }\n" +
- "}");
- }
-
public void testMethodCallChain() throws Exception {
doTextTest("class Foo{\n" +
" void foo(){\n" +
"}");
}
- public void testSCR1535() throws Exception {
- final CodeStyleSettings settings = getSettings();
- settings.BRACE_STYLE = CodeStyleSettings.NEXT_LINE;
- settings.CLASS_BRACE_STYLE = CodeStyleSettings.NEXT_LINE;
- settings.METHOD_BRACE_STYLE = CodeStyleSettings.NEXT_LINE;
- doTextTest("public class Foo {\n" +
- " public int foo() {\n" +
- " if (a) {\n" +
- " return;\n" +
- " }\n" +
- " }\n" +
-"}", "public class Foo\n" +
- "{\n" +
- " public int foo()\n" +
- " {\n" +
- " if (a)\n" +
- " {\n" +
- " return;\n" +
- " }\n" +
- " }\n" +
- "}");
- }
-
public void testComment1() throws Exception {
doTextTest("class Foo {\n" +
" public boolean mErrorFlage;\n" +
doTest("SpacesBeforeLBrace.java", "SpacesBeforeLBrace.java");
}
- public void testSCR970() throws Exception {
- final CodeStyleSettings settings = getSettings();
- settings.THROWS_KEYWORD_WRAP = CodeStyleSettings.WRAP_ALWAYS;
- settings.THROWS_LIST_WRAP = CodeStyleSettings.WRAP_AS_NEEDED;
- settings.METHOD_PARAMETERS_WRAP = CodeStyleSettings.WRAP_AS_NEEDED;
- doTest();
- }
-
public void testCommentBeforeField() throws Exception {
final CodeStyleSettings settings = getSettings();
settings.KEEP_LINE_BREAKS = false;
}
- private static CodeStyleSettings getSettings() {
- return CodeStyleSettingsManager.getSettings(getProject());
- }
-
public void testElseOnNewLine() throws Exception {
doTextTest("class Foo{\n" + "void foo() {\n" + "if (a)\n" + "return;\n" + "else\n" + "return;\n" + "}\n" + "}", "class Foo {\n" +
" void foo() {\n" +
"}");
}
- public void testSCR1047() throws Exception {
- doTextTest("class Foo{\n" + " void foo(){\n" + " String field1, field2;\n" + " }\n" + "}",
- "class Foo {\n" + " void foo() {\n" + " String field1, field2;\n" + " }\n" + "}");
- }
-
- public void testSCR524() throws Exception {
- getSettings().METHOD_BRACE_STYLE = CodeStyleSettings.NEXT_LINE_SHIFTED;
- getSettings().KEEP_SIMPLE_METHODS_IN_ONE_LINE = true;
- getSettings().KEEP_SIMPLE_BLOCKS_IN_ONE_LINE = false;
- doTextTest("class Foo {\n" + " void foo() { return;}" + "}", "class Foo {\n" + " void foo() { return;}\n" + "}");
-
- getSettings().BRACE_STYLE = CodeStyleSettings.NEXT_LINE_SHIFTED2;
- getSettings().KEEP_SIMPLE_METHODS_IN_ONE_LINE = false;
- getSettings().KEEP_SIMPLE_BLOCKS_IN_ONE_LINE = true;
- getSettings().METHOD_BRACE_STYLE = CodeStyleSettings.END_OF_LINE;
-
- doTextTest("class Foo{\n" +
- "void foo() {\n" +
- "if(a) {return;}\n" +
- "for(a = 0; a < 10; a++) {return;}\n" +
- "switch(a) {case 1: return;}\n" +
- "do{return;} while (a);\n" +
- "while(a){return;}\n" +
- "try{return;} catch(Ex e){return;} finally{return;}\n" +
- "}\n" +
-"}", "class Foo {\n" +
- " void foo() {\n" +
- " if (a) {return;}\n" +
- " for (a = 0; a < 10; a++) {return;}\n" +
- " switch (a)\n" +
- " {\n" +
- " case 1:\n" +
- " return;\n" +
- " }\n" +
- " do {return;} while (a);\n" +
- " while (a) {return;}\n" +
- " try {return;} catch (Ex e) {return;} finally {return;}\n" +
- " }\n" +
- "}");
- }
-
public void testFirstArgumentWrapping() throws Exception {
getSettings().RIGHT_MARGIN = 20;
getSettings().CALL_PARAMETERS_WRAP = CodeStyleSettings.WRAP_AS_NEEDED;
"class Foo {\n" + " void foo() {\n" + "\n" + " }\n" + "}");
}
- public void testSCR2632() throws Exception {
- getSettings().ENABLE_JAVADOC_FORMATTING = true;
- getSettings().WRAP_COMMENTS = true;
- getSettings().RIGHT_MARGIN = 20;
-
- doTextTest("/**\n" + " * <p />\n" + " * Another paragraph of the description placed after blank line.\n" + " */\n" + "class A{}",
- "/**\n" +
- " * <p/>\n" +
- " * Another paragraph\n" +
- " * of the description\n" +
- " * placed after\n" +
- " * blank line.\n" +
- " */\n" +
- "class A {\n" +
- "}");
- }
-
- public void testSCR1486() throws Exception {
- doTextTest("public class Test {\n" + " private BigDecimal\n" + "}", "public class Test {\n" + " private BigDecimal\n" + "}");
-
- doTextTest("public class Test {\n" + " @NotNull private BigDecimal\n" + "}",
- "public class Test {\n" + " @NotNull\n" + " private BigDecimal\n" + "}");
-
- }
-
public void testJavaDocLeadingAsterisksAreDisabled() throws Exception {
getSettings().JD_LEADING_ASTERISKS_ARE_ENABLED = false;
doTextTest("class Foo {\n" +
assertEquals("a = 1;\n" + "int b = 2;", result[0].getText());
}
- public void test1607() throws Exception {
- getSettings().RIGHT_MARGIN = 30;
- getSettings().METHOD_BRACE_STYLE = CodeStyleSettings.NEXT_LINE;
- getSettings().KEEP_SIMPLE_METHODS_IN_ONE_LINE = true;
- getSettings().ALIGN_MULTILINE_PARAMETERS = true;
- getSettings().METHOD_PARAMETERS_WRAP = CodeStyleSettings.WRAP_AS_NEEDED;
- doTextTest("class TEst {\n" + "void foo(A a,B b){ /* compiled code */ }\n" + "}",
- "class TEst {\n" + " void foo(A a, B b)\n" + " { /* compiled code */ }\n" + "}");
- }
-
- public void testSCR1615() throws Exception {
- getSettings().CLASS_BRACE_STYLE = CodeStyleSettings.NEXT_LINE_SHIFTED;
- getSettings().METHOD_BRACE_STYLE = CodeStyleSettings.NEXT_LINE_SHIFTED;
- getSettings().BRACE_STYLE = CodeStyleSettings.NEXT_LINE_SHIFTED;
-
- doTextTest(
- "public class ZZZZ \n" + " { \n" + " public ZZZZ() \n" + " { \n" + " if (a){\n" + "foo();}\n" + " } \n" + " }",
- "public class ZZZZ\n" +
- " {\n" +
- " public ZZZZ()\n" +
- " {\n" +
- " if (a)\n" +
- " {\n" +
- " foo();\n" +
- " }\n" +
- " }\n" +
- " }");
- }
-
public void testNewLineAfterJavaDocs() throws Exception {
doTextTest("/** @noinspection InstanceVariableNamingConvention*/class Foo{\n" +
"/** @noinspection InstanceVariableNamingConvention*/int myFoo;\n" +
}
- public void testSCR3062() throws Exception {
- getSettings().KEEP_LINE_BREAKS = false;
- getSettings().METHOD_CALL_CHAIN_WRAP = CodeStyleSettings.WRAP_AS_NEEDED;
- getSettings().CALL_PARAMETERS_WRAP = CodeStyleSettings.WRAP_AS_NEEDED;
- getSettings().ALIGN_MULTILINE_PARAMETERS_IN_CALLS = true;
- getSettings().RIGHT_MARGIN = 80;
-
- getSettings().PREFER_PARAMETERS_WRAP = true;
-
- doTextTest("public class Foo { \n" +
- " public static void main() { \n" +
- " foo.foobelize().foobelize().foobelize().bar(\"The quick brown\", \n" +
- " \"fox jumped over\", \n" +
- " \"the lazy\", \"dog\"); \n" +
- " } \n" +
-"}", "public class Foo {\n" +
- " public static void main() {\n" +
- " foo.foobelize().foobelize().foobelize().bar(\"The quick brown\",\n" +
- " \"fox jumped over\",\n" +
- " \"the lazy\", \"dog\");\n" +
- " }\n" +
- "}");
-
- getSettings().PREFER_PARAMETERS_WRAP = false;
-
- doTextTest("public class Foo { \n" +
- " public static void main() { \n" +
- " foo.foobelize().foobelize().foobelize().bar(\"The quick brown\", \n" +
- " \"fox jumped over\", \n" +
- " \"the lazy\", \"dog\"); \n" +
- " } \n" +
-"}", "public class Foo {\n" +
- " public static void main() {\n" +
- " foo.foobelize().foobelize().foobelize()\n" +
- " .bar(\"The quick brown\", \"fox jumped over\", \"the lazy\", \"dog\");\n" +
- " }\n" +
- "}");
-
- }
-
- public void testSCR1658() throws Exception {
- doTextTest("/** \n" + " * @author\tMike\n" + " */\n" + "public class Foo {\n" + "}",
- "/**\n" + " * @author Mike\n" + " */\n" + "public class Foo {\n" + "}");
- }
-
- public void testSCR1699() throws Exception {
- doTextTest("class Test {\n" + " Test(String t1 , String t2) {\n" + " }\n" + "}",
- "class Test {\n" + " Test(String t1, String t2) {\n" + " }\n" + "}");
- }
-
- public void testSCR1700() throws Exception {
- doTextTest("class Test {\n" + " Test(String t1 , String t2) {\n" + " }\n" + "}",
- "class Test {\n" + " Test(String t1, String t2) {\n" + " }\n" + "}");
- }
-
- public void testSCR1701() throws Exception {
- getSettings().SPACE_WITHIN_METHOD_CALL_PARENTHESES = true;
- getSettings().SPACE_WITHIN_METHOD_PARENTHESES = false;
- getSettings().CALL_PARAMETERS_WRAP = CodeStyleSettings.DO_NOT_WRAP;
- getSettings().CALL_PARAMETERS_LPAREN_ON_NEXT_LINE = true;
- getSettings().CALL_PARAMETERS_RPAREN_ON_NEXT_LINE = true;
- doTextTest("class Foo {\n" + " void foo() {\n" + " foo(a,b);" + " }\n" + "}",
- "class Foo {\n" + " void foo() {\n" + " foo( a, b );\n" + " }\n" + "}");
- }
-
- public void testSCR1703() throws Exception {
- getSettings().BRACE_STYLE = CodeStyleSettings.NEXT_LINE;
- doTextTest("class Foo{\n" +
- " void foo() {\n" +
- " for (Object o : localizations) {\n" +
- " //do something \n" +
- " }\n" +
- " }\n" +
-"}", "class Foo {\n" +
- " void foo() {\n" +
- " for (Object o : localizations)\n" +
- " {\n" +
- " //do something \n" +
- " }\n" +
- " }\n" +
- "}");
- }
-
-
public void testJavaDocIndentation() throws Exception {
getSettings().getIndentOptions(StdFileTypes.JAVA).INDENT_SIZE = 2;
getSettings().getIndentOptions(StdFileTypes.JAVA).CONTINUATION_INDENT_SIZE = 2;
"}");
}
- public void testSCR1804() throws Exception {
- getSettings().ALIGN_MULTILINE_ASSIGNMENT = true;
- doTextTest(
- "class Foo {\n" + " void foo() {\n" + " int i;\n" + " i = \n" + " 1 + 2;\n" + " }\n" + "}",
- "class Foo {\n" + " void foo() {\n" + " int i;\n" + " i =\n" + " 1 + 2;\n" + " }\n" + "}");
-
- doTextTest("class Foo {\n" + " void foo() {\n" + " i = j =\n" + " k = l = 1 + 2;\n" + " }\n" + "}",
- "class Foo {\n" + " void foo() {\n" + " i = j =\n" + " k = l = 1 + 2;\n" + " }\n" + "}");
-
- }
-
- public void testSCR1795() throws Exception {
- getSettings().BRACE_STYLE = CodeStyleSettings.NEXT_LINE_IF_WRAPPED;
- doTextTest("public class Test {\n" +
- " public static void main(String[] args) {\n" +
- " do {\n" +
- " // ...\n" +
- " } while (true);\n" +
- " }\n" +
-"}", "public class Test {\n" +
- " public static void main(String[] args) {\n" +
- " do {\n" +
- " // ...\n" +
- " } while (true);\n" +
- " }\n" +
- "}");
- }
-
- public void testSCR1936() throws Exception {
- getSettings().BLANK_LINES_AFTER_CLASS_HEADER = 4;
- doTextTest("/**\n" + " * Foo - test class\n" + " */\n" + "class Foo{\n" + "}",
- "/**\n" + " * Foo - test class\n" + " */\n" + "class Foo {\n" + "\n" + "\n" + "\n" + "\n" + "}");
-
- doTextTest("/**\n" + " * Foo - test class\n" + " */\n" + "class Foo{\n" + " int myFoo;\n" + "}",
- "/**\n" + " * Foo - test class\n" + " */\n" + "class Foo {\n" + "\n" + "\n" + "\n" + "\n" + " int myFoo;\n" + "}");
-
- }
-
public void testRemoveLineBreak() throws Exception {
getSettings().KEEP_LINE_BREAKS = true;
getSettings().CLASS_BRACE_STYLE = CodeStyleSettings.END_OF_LINE;
}
- public void test1980() throws Exception {
- getSettings().RIGHT_MARGIN = 144;
- getSettings().TERNARY_OPERATION_WRAP = CodeStyleSettings.WRAP_ON_EVERY_ITEM;
- getSettings().METHOD_CALL_CHAIN_WRAP = CodeStyleSettings.WRAP_AS_NEEDED;
- getSettings().ALIGN_MULTILINE_TERNARY_OPERATION = true;
- getSettings().TERNARY_OPERATION_SIGNS_ON_NEXT_LINE = true;
- doTextTest("class Foo{\n" +
- " void foo() {\n" +
- "final VirtualFile moduleRoot = moduleRelativePath.equals(\"\") ? projectRootDirAfter : projectRootDirAfter.findFileByRelativePath(moduleRelativePath);\n" +
- " }\n" +
-"}", "class Foo {\n" +
- " void foo() {\n" +
- " final VirtualFile moduleRoot = moduleRelativePath.equals(\"\")\n" +
- " ? projectRootDirAfter\n" +
- " : projectRootDirAfter.findFileByRelativePath(moduleRelativePath);\n" +
- " }\n" +
- "}");
- }
-
public void testStaticBlockBraces() throws Exception {
getSettings().BRACE_STYLE = CodeStyleSettings.END_OF_LINE;
doTextTest("class Foo {\n" + " static {\n" + " //comment\n" + " i = foo();\n" + " }\n" + "}",
}
- public void testSCR2089() throws Exception {
- doTextTest("class Test { \n" +
- " void test(int i) { \n" +
- " switch (i) { \n" +
- " case 1: { \n" +
- " int x = 0; \n" +
- " System.out.println(x); \n" +
- " } \n" +
- " break; \n" +
- " case 2: { \n" +
- " int y = 0; \n" +
- " System.out.println(y); \n" +
- " } \n" +
- " break; \n" +
- " } \n" +
- " } \n" +
-"}", "class Test {\n" +
- " void test(int i) {\n" +
- " switch (i) {\n" +
- " case 1: {\n" +
- " int x = 0;\n" +
- " System.out.println(x);\n" +
- " }\n" +
- " break;\n" +
- " case 2: {\n" +
- " int y = 0;\n" +
- " System.out.println(y);\n" +
- " }\n" +
- " break;\n" +
- " }\n" +
- " }\n" +
- "}");
- }
-
public void testBraces2() throws Exception {
getSettings().BRACE_STYLE = CodeStyleSettings.NEXT_LINE_IF_WRAPPED;
doTextTest("class Foo {\n" +
}
- public void testSCR2122() throws Exception {
- getSettings().BLANK_LINES_AFTER_CLASS_HEADER = 3;
-
- doTextTest("class Foo {\n" +
- " void foo() {\n" +
- " new Runnable() {\n" +
- " public void run() {\n" +
- " }\n" +
- " }\n" +
- " }\n" +
-"}", "class Foo {\n" +
- "\n" +
- "\n" +
- "\n" +
- " void foo() {\n" +
- " new Runnable() {\n" +
- " public void run() {\n" +
- " }\n" +
- " }\n" +
- " }\n" +
- "}");
- }
-
public void testSynchronized() throws Exception {
getSettings().BRACE_STYLE = CodeStyleSettings.END_OF_LINE;
}
- public void testSCR2132() throws Exception {
- getSettings().BRACE_STYLE = CodeStyleSettings.NEXT_LINE_IF_WRAPPED;
- getSettings().ELSE_ON_NEW_LINE = true;
+ public void testNextLineShiftedForBlockStatement() throws Exception {
+ getSettings().BRACE_STYLE = CodeStyleSettings.NEXT_LINE_SHIFTED;
+
+ doTextTest("class Foo {\n" + " void foo() {\n" + " if (a)\n" + " foo();\n" + " }\n" + "}",
+ "class Foo {\n" + " void foo() {\n" + " if (a)\n" + " foo();\n" + " }\n" + "}");
+ }
+
+ public void testFieldWithJavadocAndAnnotation() throws Exception {
+ doTextTest("class Foo {\n" + " /**\n" + " * java doc\n" + " */\n" + " @NoInspection\n" + " String field;\n" + "}",
+ "class Foo {\n" + " /**\n" + " * java doc\n" + " */\n" + " @NoInspection\n" + " String field;\n" + "}");
+ }
+ public void testLongCallChainAfterElse() throws Exception {
+ getSettings().BRACE_STYLE = CodeStyleSettings.NEXT_LINE;
+ getSettings().KEEP_CONTROL_STATEMENT_IN_ONE_LINE = true;
+ getSettings().KEEP_SIMPLE_METHODS_IN_ONE_LINE = true;
+ getSettings().ELSE_ON_NEW_LINE = false;
+ getSettings().RIGHT_MARGIN = 110;
+ getSettings().KEEP_LINE_BREAKS = false;
doTextTest("class Foo {\n" +
" void foo() {\n" +
- " if (!rightPanel.isAncestorOf(validationPanel)) \n" +
- " {\n" +
- " splitPane.setDividerLocation(1.0);\n" +
- " }\n" +
- " else\n" +
- " {\n" +
- " splitPane.setDividerLocation(0.7);\n" +
- " }" +
+ " if (types.length > 1) // returns multiple columns\n" +
+ " {\n" +
+ " } else\n" +
+ " result.add(initializeObject(os, types[0], initializeCollections, initializeAssociations, initializeChildren));" +
" }\n" +
"}", "class Foo {\n" +
" void foo() {\n" +
- " if (!rightPanel.isAncestorOf(validationPanel)) {\n" +
- " splitPane.setDividerLocation(1.0);\n" +
- " }\n" +
- " else {\n" +
- " splitPane.setDividerLocation(0.7);\n" +
- " }\n" +
+ " if (types.length > 1) // returns multiple columns\n" +
+ " {\n" +
+ " } else\n" +
+ " result.add(initializeObject(os, types[0], initializeCollections, initializeAssociations, initializeChildren));\n" +
" }\n" +
"}");
}
- public void testNextLineShiftedForBlockStatement() throws Exception {
- getSettings().BRACE_STYLE = CodeStyleSettings.NEXT_LINE_SHIFTED;
-
- doTextTest("class Foo {\n" + " void foo() {\n" + " if (a)\n" + " foo();\n" + " }\n" + "}",
- "class Foo {\n" + " void foo() {\n" + " if (a)\n" + " foo();\n" + " }\n" + "}");
- }
+ public void testSpacesIncode() throws Exception {
- private void doTest() throws Exception {
- doTest(getTestName(false) + ".java", getTestName(false) + "_after.java");
- }
+ final JavaPsiFacade facade = getJavaFacade();
+ final LanguageLevel level = LanguageLevelProjectExtension.getInstance(facade.getProject()).getLanguageLevel();
- private void doTest(String fileNameBefore, String fileNameAfter) throws Exception {
+ LanguageLevelProjectExtension.getInstance(facade.getProject()).setLanguageLevel(LanguageLevel.JDK_1_5);
- doTextTest(loadFile(fileNameBefore), loadFile(fileNameAfter));
+ try {
+ doTextTest("class C<Y, X> {\n" + "}", "class C<Y, X> {\n" + "}");
+ getSettings().SPACE_BEFORE_METHOD_LBRACE = true;
+ getSettings().KEEP_SIMPLE_METHODS_IN_ONE_LINE = true;
- }
+ doTextTest("enum En {\n" + " A(10) {},\n" + " B(10) {},\n" + " C(10);\n" + "\n" + " En(int i) { }\n" + "}",
+ "enum En {\n" + " A(10) {},\n" + " B(10) {},\n" + " C(10);\n" + "\n" + " En(int i) { }\n" + "}");
- private void doTextTest(final String text, String textAfter) throws IncorrectOperationException {
- final PsiFile file = createPseudoPhysicalFile("A.java", text);
+ doTextTest("class C {\n" +
+ " void foo (Map<?, String> s) {\n" +
+ " Set<? extends Map<?, String>.Entry<?, String>> temp = s.entries();\n" +
+ " }\n" +
+"}", "class C {\n" +
+ " void foo(Map<?, String> s) {\n" +
+ " Set<? extends Map<?, String>.Entry<?, String>> temp = s.entries();\n" +
+ " }\n" +
+ "}");
- if (myLineRange != null) {
- final DocumentImpl document = new DocumentImpl(text);
- myTextRange =
- new TextRange(document.getLineStartOffset(myLineRange.getStartOffset()), document.getLineEndOffset(myLineRange.getEndOffset()));
+ doTextTest("class B {\n" +
+ " public final A<String> myDelegate = new A<String>();\n" +
+ "\n" +
+ " public List<? extends String> method1() {\n" +
+ " return myDelegate.method1();\n" +
+ " }\n" +
+ "\n" +
+ " public String method2(String t) {\n" +
+ " return myDelegate.method2(t);\n" +
+ " }\n" +
+"}", "class B {\n" +
+ " public final A<String> myDelegate = new A<String>();\n" +
+ "\n" +
+ " public List<? extends String> method1() {\n" +
+ " return myDelegate.method1();\n" +
+ " }\n" +
+ "\n" +
+ " public String method2(String t) {\n" +
+ " return myDelegate.method2(t);\n" +
+ " }\n" +
+ "}");
+ }
+ finally {
+ LanguageLevelProjectExtension.getInstance(facade.getProject()).setLanguageLevel(level);
}
- /*
- CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
- public void run() {
- ApplicationManager.getApplication().runWriteAction(new Runnable() {
- public void run() {
- performFormatting(file);
- }
- });
- }
- }, null, null);
-
- assertEquals(prepareText(textAfter), prepareText(file.getText()));
-
-
- */
-
- final PsiDocumentManager manager = PsiDocumentManager.getInstance(getProject());
- final Document document = manager.getDocument(file);
+ }
+ ///IDEA-7761
+ public void testKeepBlankLineInCodeBeforeComment() throws Exception {
+ getSettings().KEEP_BLANK_LINES_IN_CODE = 1;
+ getSettings().KEEP_BLANK_LINES_IN_DECLARATIONS = 0;
+ getSettings().KEEP_FIRST_COLUMN_COMMENT = false;
- CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
- public void run() {
- ApplicationManager.getApplication().runWriteAction(new Runnable() {
- public void run() {
- document.replaceString(0, document.getTextLength(), text);
- manager.commitDocument(document);
- try {
- if (myTextRange != null) {
- CodeStyleManager.getInstance(getProject()).reformatText(file, myTextRange.getStartOffset(), myTextRange.getEndOffset());
- }
- else {
- CodeStyleManager.getInstance(getProject())
- .reformatText(file, file.getTextRange().getStartOffset(), file.getTextRange().getEndOffset());
- }
- }
- catch (IncorrectOperationException e) {
- assertTrue(e.getLocalizedMessage(), false);
- }
- }
- });
- }
- }, "", "");
+ doTextTest("public class ReformatProblem {\n" +
+ "\n" +
+ " //comment in declaration\n" +
+ " public static void main(String[] args) {\n" +
+ " for (String arg : args) {\n" +
+ " \n" +
+ " // a first system out\n" +
+ " System.out.println(\"\");\n" +
+ " \n" +
+ " // another system out\n" +
+ " System.out.println(\"arg = \" + arg);\n" +
+ " }\n" +
+ " }\n" +
+"}", "public class ReformatProblem {\n" +
+ " //comment in declaration\n" +
+ " public static void main(String[] args) {\n" +
+ " for (String arg : args) {\n" +
+ "\n" +
+ " // a first system out\n" +
+ " System.out.println(\"\");\n" +
+ "\n" +
+ " // another system out\n" +
+ " System.out.println(\"arg = \" + arg);\n" +
+ " }\n" +
+ " }\n" +
+ "}");
+ getSettings().KEEP_BLANK_LINES_IN_CODE = 0;
+ getSettings().KEEP_BLANK_LINES_IN_DECLARATIONS = 1;
+ getSettings().KEEP_FIRST_COLUMN_COMMENT = false;
- if (document == null) {
- fail("Don't expect the document to be null");
- return;
- }
- assertEquals(prepareText(textAfter), prepareText(document.getText()));
- manager.commitDocument(document);
- assertEquals(prepareText(textAfter), prepareText(file.getText()));
+ doTextTest("public class ReformatProblem {\n" +
+ "\n" +
+ " //comment in declaration\n" +
+ " public static void main(String[] args) {\n" +
+ " for (String arg : args) {\n" +
+ " \n" +
+ " // a first system out\n" +
+ " System.out.println(\"\");\n" +
+ " \n" +
+ " // another system out\n" +
+ " System.out.println(\"arg = \" + arg);\n" +
+ " }\n" +
+ " }\n" +
+"}", "public class ReformatProblem {\n" +
+ "\n" +
+ " //comment in declaration\n" +
+ " public static void main(String[] args) {\n" +
+ " for (String arg : args) {\n" +
+ " // a first system out\n" +
+ " System.out.println(\"\");\n" +
+ " // another system out\n" +
+ " System.out.println(\"arg = \" + arg);\n" +
+ " }\n" +
+ " }\n" +
+ "}");
}
- public void testIDEADEV1047() throws Exception {
- doTextTest("class Foo{\n" + "String field1\n" + ",\n" + "field2\n" + ";" + "}",
- "class Foo {\n" + " String field1,\n" + " field2;\n" + "}");
-
- doTextTest("class Foo{\n" + "void foo() {\n" + " String var1\n" + ",\n" + "var2\n" + ";\n" + " }\n" + "}",
- "class Foo {\n" + " void foo() {\n" + " String var1,\n" + " var2;\n" + " }\n" + "}");
+ public void testSpaceBeforeTryBrace() throws Exception {
+ getSettings().SPACE_BEFORE_TRY_LBRACE = false;
+ getSettings().SPACE_BEFORE_FINALLY_LBRACE = true;
+ doTextTest("class Foo{\n" + " void foo() {\n" + " try {\n" + " } finally {\n" + " }\n" + " }\n" + "}",
+ "class Foo {\n" + " void foo() {\n" + " try{\n" + " } finally {\n" + " }\n" + " }\n" + "}");
- }
+ getSettings().SPACE_BEFORE_TRY_LBRACE = true;
+ getSettings().SPACE_BEFORE_FINALLY_LBRACE = false;
- public void testIDEADEV1047_2() throws Exception {
- doTextTest("class Foo{\n" + "String field1\n" + ",\n" + "field2\n" + "; String field3;" + "}",
- "class Foo {\n" + " String field1,\n" + " field2;\n" + " String field3;\n" + "}");
+ doTextTest("class Foo{\n" + " void foo() {\n" + " try {\n" + " } finally {\n" + " }\n" + " }\n" + "}",
+ "class Foo {\n" + " void foo() {\n" + " try {\n" + " } finally{\n" + " }\n" + " }\n" + "}");
}
- public void testFieldWithJavadocAndAnnotation() throws Exception {
- doTextTest("class Foo {\n" + " /**\n" + " * java doc\n" + " */\n" + " @NoInspection\n" + " String field;\n" + "}",
- "class Foo {\n" + " /**\n" + " * java doc\n" + " */\n" + " @NoInspection\n" + " String field;\n" + "}");
+ public void testFormatComments() throws Exception {
+ getSettings().ENABLE_JAVADOC_FORMATTING = true;
+ doTextTest("public class Test {\n" + "\n" + " /**\n" + " * The s property.\n" + " */\n" + " private String s;\n" + "}",
+ "public class Test {\n" + "\n" + " /**\n" + " * The s property.\n" + " */\n" + " private String s;\n" + "}");
+
}
- public void testSCR2241() throws Exception {
- getSettings().BRACE_STYLE = CodeStyleSettings.NEXT_LINE_SHIFTED;
- getSettings().SPECIAL_ELSE_IF_TREATMENT = true;
- getSettings().ELSE_ON_NEW_LINE = true;
- doTextTest("class Foo {\n" +
- " void foo() {\n" +
- " if (a)\n" +
- " {\n" +
- " }\n" +
- " else\n" +
- " {\n" +
+ public void testDoNotWrapLBrace() throws IncorrectOperationException {
+ getSettings().BRACE_STYLE = CodeStyleSettings.END_OF_LINE;
+ getSettings().RIGHT_MARGIN = 66;
+ doTextTest("public class Test {\n" +
+ " void foo(){\n" +
+ " if (veryLongIdentifier1 == 1 && veryLongIdentifier2 == 2) {\n" +
+ " doSmth();\n" +
" }\n" +
" }\n" +
-"}", "class Foo {\n" +
+"}", "public class Test {\n" +
" void foo() {\n" +
- " if (a)\n" +
- " {\n" +
- " }\n" +
- " else\n" +
- " {\n" +
- " }\n" +
+ " if (veryLongIdentifier1 == 1 && veryLongIdentifier2 == 2) {\n" +
+ " doSmth();\n" +
+ " }\n" +
" }\n" +
"}");
}
- public void testLongCallChainAfterElse() throws Exception {
- getSettings().BRACE_STYLE = CodeStyleSettings.NEXT_LINE;
- getSettings().KEEP_CONTROL_STATEMENT_IN_ONE_LINE = true;
- getSettings().KEEP_SIMPLE_METHODS_IN_ONE_LINE = true;
- getSettings().ELSE_ON_NEW_LINE = false;
- getSettings().RIGHT_MARGIN = 110;
- getSettings().KEEP_LINE_BREAKS = false;
- doTextTest("class Foo {\n" +
- " void foo() {\n" +
- " if (types.length > 1) // returns multiple columns\n" +
- " {\n" +
- " } else\n" +
- " result.add(initializeObject(os, types[0], initializeCollections, initializeAssociations, initializeChildren));" +
- " }\n" +
-"}", "class Foo {\n" +
- " void foo() {\n" +
- " if (types.length > 1) // returns multiple columns\n" +
- " {\n" +
- " } else\n" +
- " result.add(initializeObject(os, types[0], initializeCollections, initializeAssociations, initializeChildren));\n" +
- " }\n" +
- "}");
+ public void testNewLinesAroundArrayInitializer() throws IncorrectOperationException {
+ getSettings().ARRAY_INITIALIZER_WRAP = CodeStyleSettings.WRAP_AS_NEEDED;
+ getSettings().ARRAY_INITIALIZER_LBRACE_ON_NEXT_LINE = true;
+ getSettings().ARRAY_INITIALIZER_RBRACE_ON_NEXT_LINE = true;
+ getSettings().RIGHT_MARGIN = 40;
+ doTextTest("class Foo {\n" + " int[] a = new int[]{1,2,0x0052,0x0053,0x0054,0x0054,0x0054};\n" + "}", "class Foo {\n" +
+ " int[] a = new int[]{\n" +
+ " 1, 2, 0x0052, 0x0053,\n" +
+ " 0x0054, 0x0054, 0x0054\n" +
+ " };\n" +
+ "}");
}
- public void testSCRIDEA_4783() throws IncorrectOperationException {
- getSettings().ASSIGNMENT_WRAP = CodeStyleSettings.WRAP_AS_NEEDED;
- getSettings().METHOD_CALL_CHAIN_WRAP = CodeStyleSettings.WRAP_AS_NEEDED;
- getSettings().RIGHT_MARGIN = 80;
+ public void testSpaceAfterCommaInEnum() throws IncorrectOperationException {
+ getSettings().SPACE_AFTER_COMMA = true;
- doTextTest("class Foo{\n" +
- " void foo() {\n" +
- " final CommandRouterProtocolHandler protocolHandler = (CommandRouterProtocolHandler) connection.getProtocolHandler()\n" +
- " }\n" +
-"}", "class Foo {\n" +
- " void foo() {\n" +
- " final CommandRouterProtocolHandler protocolHandler =\n" +
- " (CommandRouterProtocolHandler) connection.getProtocolHandler()\n" +
- " }\n" +
- "}");
-
-
- doTextTest("class Foo{\n" +
- " void foo() {\n" +
- " protocolHandlerCommandRouterProtocolHandler = (CommandRouterProtocolHandler) connection.getProtocolHandler()\n" +
- " }\n" +
-"}", "class Foo {\n" +
- " void foo() {\n" +
- " protocolHandlerCommandRouterProtocolHandler =\n" +
- " (CommandRouterProtocolHandler) connection.getProtocolHandler()\n" +
- " }\n" +
- "}");
+ final JavaPsiFacade facade = getJavaFacade();
+ final LanguageLevel effectiveLanguageLevel = LanguageLevelProjectExtension.getInstance(facade.getProject()).getLanguageLevel();
+ try {
+ LanguageLevelProjectExtension.getInstance(facade.getProject()).setLanguageLevel(LanguageLevel.JDK_1_5);
- doTextTest("class Foo{\n" +
- " final CommandRouterProtocolHandler protocolHandler = (CommandRouterProtocolHandler) connection.getProtocolHandler()\n" +
-"}", "class Foo {\n" +
- " final CommandRouterProtocolHandler protocolHandler =\n" +
- " (CommandRouterProtocolHandler) connection.getProtocolHandler()\n" +
- "}");
- getSettings().PLACE_ASSIGNMENT_SIGN_ON_NEXT_LINE = true;
+ doTextTest("public enum StringExDirection {\n" + "\n" + " RIGHT_TO_LEFT, LEFT_TO_RIGHT\n" + "\n" + "}",
+ "public enum StringExDirection {\n" + "\n" + " RIGHT_TO_LEFT, LEFT_TO_RIGHT\n" + "\n" + "}");
+ }
+ finally {
+ LanguageLevelProjectExtension.getInstance(facade.getProject()).setLanguageLevel(effectiveLanguageLevel);
+ }
+ }
- doTextTest("class Foo{\n" +
- " void foo() {\n" +
- " final CommandRouterProtocolHandler protocolHandler = (CommandRouterProtocolHandler) connection.getProtocolHandler()\n" +
+ public void testRemoveBraceBeforeInstanceOf() throws IncorrectOperationException {
+ doTextTest("class ReformatInstanceOf {\n" +
+ " void foo(Object string) {\n" +
+ " if (string.toString() instanceof String) {} // reformat me\n" +
" }\n" +
-"}", "class Foo {\n" +
- " void foo() {\n" +
- " final CommandRouterProtocolHandler protocolHandler\n" +
- " = (CommandRouterProtocolHandler) connection.getProtocolHandler()\n" +
+"}", "class ReformatInstanceOf {\n" +
+ " void foo(Object string) {\n" +
+ " if (string.toString() instanceof String) {\n" +
+ " } // reformat me\n" +
" }\n" +
"}");
+ }
- doTextTest("class Foo{\n" +
- " void foo() {\n" +
- " protocolHandlerCommandRouterProtocolHandler = (CommandRouterProtocolHandler) connection.getProtocolHandler()\n" +
- " }\n" +
-"}", "class Foo {\n" +
- " void foo() {\n" +
- " protocolHandlerCommandRouterProtocolHandler\n" +
- " = (CommandRouterProtocolHandler) connection.getProtocolHandler()\n" +
- " }\n" +
- "}");
+ public void testAnnotationBeforePackageLocalConstructor() throws IncorrectOperationException {
+ doTextTest("class Foo {\n" + " @MyAnnotation Foo() {\n" + " }\n" + "}",
+ "class Foo {\n" + " @MyAnnotation\n" + " Foo() {\n" + " }\n" + "}");
+ }
+ public void testLongAnnotationsAreNotWrapped() throws Exception {
+ getSettings().ARRAY_INITIALIZER_WRAP = CodeStyleSettings.WRAP_AS_NEEDED;
+ doTest();
+ }
- doTextTest("class Foo{\n" +
- " final CommandRouterProtocolHandler protocolHandler = (CommandRouterProtocolHandler) connection.getProtocolHandler()\n" +
-"}", "class Foo {\n" +
- " final CommandRouterProtocolHandler protocolHandler\n" +
- " = (CommandRouterProtocolHandler) connection.getProtocolHandler()\n" +
- "}");
+ public void testWrapExtendsList() throws Exception {
+ getSettings().RIGHT_MARGIN = 50;
+ getSettings().EXTENDS_LIST_WRAP = CodeStyleSettings.WRAP_ON_EVERY_ITEM;
+ getSettings().EXTENDS_KEYWORD_WRAP = CodeStyleSettings.WRAP_AS_NEEDED;
+ doTextTest("class ColtreDataProvider extends DataProvider, AgentEventListener, ParameterDataEventListener {\n}",
+ "class ColtreDataProvider extends DataProvider,\n" +
+ " AgentEventListener,\n" +
+ " ParameterDataEventListener {\n}");
}
- public void testSCRIDEADEV_2292() throws IncorrectOperationException {
- getSettings().KEEP_CONTROL_STATEMENT_IN_ONE_LINE = false;
- getSettings().WHILE_ON_NEW_LINE = true;
-
- final JavaPsiFacade facade = getJavaFacade();
- final LanguageLevel stored = LanguageLevelProjectExtension.getInstance(facade.getProject()).getLanguageLevel();
- LanguageLevelProjectExtension.getInstance(facade.getProject()).setLanguageLevel(LanguageLevel.JDK_1_5);
+ public void testWrapLongExpression() throws Exception {
+ getSettings().RIGHT_MARGIN = 80;
+ getSettings().BINARY_OPERATION_WRAP = CodeStyleSettings.WRAP_AS_NEEDED;
+ getSettings().ALIGN_MULTILINE_BINARY_OPERATION = true;
+ doTextTest("class Foo {\n" +
+ " void foo () {\n" +
+ " return (interval1.getEndIndex() >= interval2.getStartIndex() && interval3.getStartIndex() <= interval4.getEndIndex()) || (interval5.getEndIndex() >= interval6.getStartIndex() && interval7.getStartIndex() <= interval8.getEndIndex());" +
+ " }\n" +
+ "}", "class Foo {\n" +
+ " void foo() {\n" +
+ " return (interval1.getEndIndex() >= interval2.getStartIndex() &&\n" +
+ " interval3.getStartIndex() <= interval4.getEndIndex()) ||\n" +
+ " (interval5.getEndIndex() >= interval6.getStartIndex() &&\n" +
+ " interval7.getStartIndex() <= interval8.getEndIndex());\n" +
+ " }\n" +
+ "}");
+ }
- try {
- doTextTest("class Foo {\n" + " void foo() {\n" + " if (a) foo();\n" + " else bar();\n" + " }\n" + "}",
- "class Foo {\n" +
- " void foo() {\n" +
- " if (a)\n" +
- " foo();\n" +
- " else\n" +
- " bar();\n" +
- " }\n" +
- "}");
+ public void testDoNotWrapCallChainIfParametersWrapped() throws Exception {
+ getSettings().RIGHT_MARGIN = 87;
+ getSettings().CALL_PARAMETERS_WRAP = CodeStyleSettings.WRAP_AS_NEEDED;
+ getSettings().METHOD_CALL_CHAIN_WRAP = CodeStyleSettings.WRAP_AS_NEEDED;
+ getSettings().ALIGN_MULTILINE_PARAMETERS_IN_CALLS = true;
+ //getSettings().PREFER_PARAMETERS_WRAP = true;
+ doMethodTest(
+ //9 30 70 80 86
+ "descriptors = manager.createProblemDescriptor(parameter1, parameter2, parameterparameterpar3,parameter4);",
- doTextTest("class Foo {\n" + " void foo() {\n" + " for (int i = 0; i < 10; i++) foo();\n" + " }\n" + "}",
- "class Foo {\n" +
- " void foo() {\n" +
- " for (int i = 0; i < 10; i++)\n" +
- " foo();\n" +
- " }\n" +
- "}");
+ "descriptors = manager.createProblemDescriptor(parameter1, parameter2,\n" +
+ " parameterparameterpar3,\n" +
+ " parameter4);"
+ );
+ }
- doTextTest("class Foo {\n" + " void foo() {\n" + " for (int var : vars) foo();\n" + " }\n" + "}",
- "class Foo {\n" + " void foo() {\n" + " for (int var : vars)\n" + " foo();\n" + " }\n" + "}");
+ public void testAlignTernaryOperation() throws Exception {
+ getSettings().ALIGN_MULTILINE_TERNARY_OPERATION = true;
+ doMethodTest("String s = x == 0 ? \"hello\" :\n" +
+ " x == 5 ? \"something else\" :\n" +
+ " x > 0 ? \"bla, bla\" :\n" +
+ " \"\";", "String s = x == 0 ? \"hello\" :\n" +
+ " x == 5 ? \"something else\" :\n" +
+ " x > 0 ? \"bla, bla\" :\n" +
+ " \"\";");
+ getSettings().TERNARY_OPERATION_SIGNS_ON_NEXT_LINE = true;
- doTextTest("class Foo {\n" + " void foo() {\n" + " do foo(); while (true);\n" + " }\n" + "}", "class Foo {\n" +
- " void foo() {\n" +
- " do\n" +
- " foo();\n" +
- " while (true);\n" +
- " }\n" +
- "}");
+ doMethodTest("int someVariable = a ?\n" + "x :\n" + "y;",
+ "int someVariable = a ?\n" + " x :\n" + " y;");
+ }
- doTextTest("class Foo {\n" + " void foo() {\n" + " while(true) foo();\n" + " }\n" + "}",
- "class Foo {\n" + " void foo() {\n" + " while (true)\n" + " foo();\n" + " }\n" + "}");
- getSettings().KEEP_CONTROL_STATEMENT_IN_ONE_LINE = true;
- getSettings().WHILE_ON_NEW_LINE = false;
+ public void testRightMargin() throws Exception {
+ getSettings().WRAP_COMMENTS = true;
+ getSettings().RIGHT_MARGIN = 35;// |
+ doTextTest(
+ "/** Here is one-line java-doc comment */" +
+ "class Foo {\n" +
+ "}",
+ "/**\n" +
+ " * Here is one-line java-doc\n" +
+ " * comment\n" +
+ " */\n" +
+ "class Foo {\n" +
+ "}");
- doTextTest("class Foo {\n" + " void foo() {\n" + " if (a) foo();\n" + " else bar();\n" + " }\n" + "}",
- "class Foo {\n" + " void foo() {\n" + " if (a) foo();\n" + " else bar();\n" + " }\n" + "}");
+ }
- doTextTest("class Foo {\n" + " void foo() {\n" + " for (int i = 0; i < 10; i++) foo();\n" + " }\n" + "}",
- "class Foo {\n" + " void foo() {\n" + " for (int i = 0; i < 10; i++) foo();\n" + " }\n" + "}");
+ public void testRightMargin_2() throws Exception {
+ getSettings().RIGHT_MARGIN = 65;
+ getSettings().ASSIGNMENT_WRAP = CodeStyleSettings.WRAP_AS_NEEDED;
+ getSettings().PLACE_ASSIGNMENT_SIGN_ON_NEXT_LINE = true;
+ getSettings().KEEP_LINE_BREAKS = false;
+ doClassTest(
+ "public static final Map<LongType, LongType> longVariableName =\n" +
+ "variableValue;",
+ "public static final Map<LongType, LongType> longVariableName\n" +
+ " = variableValue;");
+ }
- doTextTest("class Foo {\n" + " void foo() {\n" + " for (int var : vars) foo();\n" + " }\n" + "}",
- "class Foo {\n" + " void foo() {\n" + " for (int var : vars) foo();\n" + " }\n" + "}");
+ public void testRightMargin_3() throws Exception {
+ getSettings().RIGHT_MARGIN = 65;
+ getSettings().ASSIGNMENT_WRAP = CodeStyleSettings.WRAP_AS_NEEDED;
+ getSettings().PLACE_ASSIGNMENT_SIGN_ON_NEXT_LINE = false;
+ getSettings().KEEP_LINE_BREAKS = false;
+ doClassTest(
+ "public static final Map<LongType, LongType> longVariableName =\n" +
+ "variableValue;",
+ "public static final Map<LongType, LongType>\n" +
+ " longVariableName = variableValue;");
+ }
- doTextTest("class Foo {\n" + " void foo() {\n" + " do foo(); while (true);\n" + " }\n" + "}",
- "class Foo {\n" + " void foo() {\n" + " do foo(); while (true);\n" + " }\n" + "}");
+ public void testDoNotRemoveLineBreaksBetweenComments(){
+ getSettings().KEEP_LINE_BREAKS = false;
+ getSettings().KEEP_FIRST_COLUMN_COMMENT = false;
+ doTextTest(
+ "public class Foo {\n" +
+ " //here is a comment\n" +
+ " //line 2 of comment\n" +
+ " public void myMethod() {\n" +
+ " //a comment\n" +
+ " //... another comment\n" +
+ " }\n" +
+ "\n" +
+ "//save for later\n" +
+ "// public void incompleteMethod() {\n" +
+ "// int blah = 0;\n" +
+ "// callSomeMethod();\n" +
+ "// callSomeOtherMethod();\n" +
+ "// doSomethingElse();\n" +
+ "// }\n" +
+ "\n" +
+ "//comment at first line\n" +
+ "}",
+ "public class Foo {\n" +
+ " //here is a comment\n" +
+ " //line 2 of comment\n" +
+ " public void myMethod() {\n" +
+ " //a comment\n" +
+ " //... another comment\n" +
+ " }\n" +
+ "\n" +
+ " //save for later\n" +
+ " // public void incompleteMethod() {\n" +
+ " // int blah = 0;\n" +
+ " // callSomeMethod();\n" +
+ " // callSomeOtherMethod();\n" +
+ " // doSomethingElse();\n" +
+ " // }\n" +
+ "\n" +
+ " //comment at first line\n" +
+ "}");
+ }
- doTextTest("class Foo {\n" + " void foo() {\n" + " while(true) foo();\n" + " }\n" + "}",
- "class Foo {\n" + " void foo() {\n" + " while (true) foo();\n" + " }\n" + "}");
+ public void testWrapParamsOnEveryItem() throws Exception {
+ CodeStyleSettings codeStyleSettings = CodeStyleSettingsManager.getSettings(getProject());
- getSettings().RIGHT_MARGIN = 17;
+ int oldMargin = codeStyleSettings.RIGHT_MARGIN;
+ boolean oldKeep = codeStyleSettings.KEEP_LINE_BREAKS;
+ int oldWrap = codeStyleSettings.METHOD_PARAMETERS_WRAP;
- doTextTest("class Foo {\n" + " void foo() {\n" + " if (a) foo();\n" + " else bar();\n" + " }\n" + "}",
- "class Foo {\n" +
- " void foo() {\n" +
- " if (a)\n" +
- " foo();\n" +
- " else\n" +
- " bar();\n" +
- " }\n" +
- "}");
-
- getSettings().RIGHT_MARGIN = 30;
-
- doTextTest("class Foo {\n" + " void foo() {\n" + " for (int i = 0; i < 10; i++) foo();\n" + " }\n" + "}",
- "class Foo {\n" +
- " void foo() {\n" +
- " for (int i = 0; i < 10; i++)\n" +
- " foo();\n" +
- " }\n" +
- "}");
+ try {
+ codeStyleSettings.RIGHT_MARGIN = 80;
+ codeStyleSettings.KEEP_LINE_BREAKS = false;
+ codeStyleSettings.METHOD_PARAMETERS_WRAP = CodeStyleSettings.WRAP_ON_EVERY_ITEM;
- getSettings().RIGHT_MARGIN = 32;
- doTextTest("class Foo {\n" + " void foo() {\n" + " for (int var : vars) foo();\n" + " }\n" + "}",
- "class Foo {\n" + " void foo() {\n" + " for (int var : vars)\n" + " foo();\n" + " }\n" + "}");
+ doClassTest(
+ "public void foo(String p1,\n" +
+ " String p2,\n" +
+ " String p3,\n" +
+ " String p4,\n" +
+ " String p5,\n" +
+ " String p6,\n" +
+ " String p7) {\n" +
+ " //To change body of implemented methods use File | Settings | File Templates.\n" +
+ "}",
+ "public void foo(String p1,\n" +
+ " String p2,\n" +
+ " String p3,\n" +
+ " String p4,\n" +
+ " String p5,\n" +
+ " String p6,\n" +
+ " String p7) {\n" +
+ " //To change body of implemented methods use File | Settings | File Templates.\n" +
+ "}");
+ }
+ finally {
+ codeStyleSettings.RIGHT_MARGIN = oldMargin;
+ codeStyleSettings.KEEP_LINE_BREAKS = oldKeep;
+ codeStyleSettings.METHOD_PARAMETERS_WRAP = oldWrap;
+ }
+ }
- getSettings().RIGHT_MARGIN = 12;
- doTextTest("class Foo {\n" + " void foo() {\n" + " do foo(); while (true);\n" + " }\n" + "}", "class Foo {\n" +
- " void foo() {\n" +
- " do\n" +
- " foo();\n" +
- " while (true);\n" +
- " }\n" +
- "}");
+ public void testCommentAfterDeclaration() throws Exception {
+ CodeStyleSettings codeStyleSettings = CodeStyleSettingsManager.getSettings(getProject());
- getSettings().RIGHT_MARGIN = 23;
+ int oldMargin = codeStyleSettings.RIGHT_MARGIN;
- doTextTest("class Foo {\n" + " void foo() {\n" + " while(true) foo();\n" + " }\n" + "}",
- "class Foo {\n" + " void foo() {\n" + " while (true)\n" + " foo();\n" + " }\n" + "}");
+ try {
+ codeStyleSettings.RIGHT_MARGIN = 20;
+ codeStyleSettings.ASSIGNMENT_WRAP = CodeStyleSettings.WRAP_AS_NEEDED;
+ doMethodTest(
+ "int i=0; //comment comment",
+ "int i =\n" +
+ " 0; //comment comment"
+ );
}
finally {
- LanguageLevelProjectExtension.getInstance(facade.getProject()).setLanguageLevel(stored);
+ codeStyleSettings.RIGHT_MARGIN = oldMargin;
}
-
-
}
- public void testSCR3115() throws Exception {
- final CodeStyleSettings.IndentOptions indentOptions = getSettings().getIndentOptions(StdFileTypes.JAVA);
- indentOptions.USE_TAB_CHARACTER = true;
- indentOptions.SMART_TABS = true;
-
- getSettings().ALIGN_MULTILINE_ARRAY_INITIALIZER_EXPRESSION = true;
+ // ------------------------------------------------
+ // Tickets-implied tests
+ // ------------------------------------------------
- doTextTest("class Foo {\n" +
- "\tpublic void test(String[] args) {\n" +
- "\t\tfoo(new String[] {\n" +
- "\t\t\t\t\"1\",\n" +
- "\t\t \"2\",\n" +
- "\t\t \"3\"});\n" +
- "\t}\n" +
-"}", "class Foo {\n" +
- "\tpublic void test(String[] args) {\n" +
- "\t\tfoo(new String[]{\n" +
- "\t\t\t\t\"1\",\n" +
- "\t\t\t\t\"2\",\n" +
- "\t\t\t\t\"3\"});\n" +
- "\t}\n" +
- "}");
+ public void testSCR915() throws Exception {
+ getSettings().SPACE_AROUND_ADDITIVE_OPERATORS = false;
+ doTest("SCR915.java", "SCR915_after.java");
}
- public void testSpacesIncode() throws Exception {
-
- final JavaPsiFacade facade = getJavaFacade();
- final LanguageLevel level = LanguageLevelProjectExtension.getInstance(facade.getProject()).getLanguageLevel();
-
- LanguageLevelProjectExtension.getInstance(facade.getProject()).setLanguageLevel(LanguageLevel.JDK_1_5);
-
- try {
- doTextTest("class C<Y, X> {\n" + "}", "class C<Y, X> {\n" + "}");
-
- getSettings().SPACE_BEFORE_METHOD_LBRACE = true;
- getSettings().KEEP_SIMPLE_METHODS_IN_ONE_LINE = true;
-
- doTextTest("enum En {\n" + " A(10) {},\n" + " B(10) {},\n" + " C(10);\n" + "\n" + " En(int i) { }\n" + "}",
- "enum En {\n" + " A(10) {},\n" + " B(10) {},\n" + " C(10);\n" + "\n" + " En(int i) { }\n" + "}");
+ public void testSCR429() throws Exception {
+ final CodeStyleSettings settings = getSettings();
+ settings.KEEP_BLANK_LINES_IN_CODE = 2;
+ settings.KEEP_BLANK_LINES_BEFORE_RBRACE = 2;
+ settings.KEEP_BLANK_LINES_IN_DECLARATIONS = 2;
+ doTest();
+ }
- doTextTest("class C {\n" +
- " void foo (Map<?, String> s) {\n" +
- " Set<? extends Map<?, String>.Entry<?, String>> temp = s.entries();\n" +
- " }\n" +
-"}", "class C {\n" +
- " void foo(Map<?, String> s) {\n" +
- " Set<? extends Map<?, String>.Entry<?, String>> temp = s.entries();\n" +
- " }\n" +
- "}");
+ public void testSCR548() throws Exception {
+ final CodeStyleSettings settings = getSettings();
+ settings.getIndentOptions(StdFileTypes.JAVA).INDENT_SIZE = 4;
+ settings.getIndentOptions(StdFileTypes.JAVA).CONTINUATION_INDENT_SIZE = 2;
+ doTest();
+ }
- doTextTest("class B {\n" +
- " public final A<String> myDelegate = new A<String>();\n" +
- "\n" +
- " public List<? extends String> method1() {\n" +
- " return myDelegate.method1();\n" +
- " }\n" +
- "\n" +
- " public String method2(String t) {\n" +
- " return myDelegate.method2(t);\n" +
- " }\n" +
-"}", "class B {\n" +
- " public final A<String> myDelegate = new A<String>();\n" +
- "\n" +
- " public List<? extends String> method1() {\n" +
- " return myDelegate.method1();\n" +
- " }\n" +
- "\n" +
- " public String method2(String t) {\n" +
- " return myDelegate.method2(t);\n" +
- " }\n" +
- "}");
- }
- finally {
- LanguageLevelProjectExtension.getInstance(facade.getProject()).setLanguageLevel(level);
- }
+ public void testIDEADEV_3666() throws Exception {
+ getSettings().SPACE_AFTER_COMMA = true;
+ doTextTest("class Foo {\n" + "Map<String,String> map() {}\n" + "}",
+ "class Foo {\n" + " Map<String, String> map() {\n" + " }\n" + "}");
}
- ///IDEA-7761
- public void testKeepBlankLineInCodeBeforeComment() throws Exception {
- getSettings().KEEP_BLANK_LINES_IN_CODE = 1;
- getSettings().KEEP_BLANK_LINES_IN_DECLARATIONS = 0;
- getSettings().KEEP_FIRST_COLUMN_COMMENT = false;
-
- doTextTest("public class ReformatProblem {\n" +
+ public void testIDEADEV_18529() throws Exception {
+ doTextTest("public class TestBed\n" +
+ "{\n" +
+ " public void methodOne()\n" +
+ " {\n" +
+ " //code...\n" +
+ " }\n" +
"\n" +
- " //comment in declaration\n" +
- " public static void main(String[] args) {\n" +
- " for (String arg : args) {\n" +
- " \n" +
- " // a first system out\n" +
- " System.out.println(\"\");\n" +
- " \n" +
- " // another system out\n" +
- " System.out.println(\"arg = \" + arg);\n" +
- " }\n" +
+ " @SomeAnnotation\n" +
+ " <T extends Comparable> void methodTwo(T item) {\n" +
+ " //code...\n" +
" }\n" +
-"}", "public class ReformatProblem {\n" +
- " //comment in declaration\n" +
- " public static void main(String[] args) {\n" +
- " for (String arg : args) {\n" +
- "\n" +
- " // a first system out\n" +
- " System.out.println(\"\");\n" +
- "\n" +
- " // another system out\n" +
- " System.out.println(\"arg = \" + arg);\n" +
- " }\n" +
- " }\n" +
- "}");
-
- getSettings().KEEP_BLANK_LINES_IN_CODE = 0;
- getSettings().KEEP_BLANK_LINES_IN_DECLARATIONS = 1;
- getSettings().KEEP_FIRST_COLUMN_COMMENT = false;
-
- doTextTest("public class ReformatProblem {\n" +
"\n" +
- " //comment in declaration\n" +
- " public static void main(String[] args) {\n" +
- " for (String arg : args) {\n" +
- " \n" +
- " // a first system out\n" +
- " System.out.println(\"\");\n" +
- " \n" +
- " // another system out\n" +
- " System.out.println(\"arg = \" + arg);\n" +
- " }\n" +
+ " private void methodThree(String s) {\n" +
+ " //code...\n" +
" }\n" +
-"}", "public class ReformatProblem {\n" +
- "\n" +
- " //comment in declaration\n" +
- " public static void main(String[] args) {\n" +
- " for (String arg : args) {\n" +
- " // a first system out\n" +
- " System.out.println(\"\");\n" +
- " // another system out\n" +
- " System.out.println(\"arg = \" + arg);\n" +
- " }\n" +
- " }\n" +
- "}");
-
+ "}", "public class TestBed {\n" +
+ " public void methodOne() {\n" +
+ " //code...\n" +
+ " }\n" +
+ "\n" +
+ " @SomeAnnotation\n" +
+ " <T extends Comparable> void methodTwo(T item) {\n" +
+ " //code...\n" +
+ " }\n" +
+ "\n" +
+ " private void methodThree(String s) {\n" +
+ " //code...\n" +
+ " }\n" +
+ "}");
}
- public void testSpaceBeforeTryBrace() throws Exception {
- getSettings().SPACE_BEFORE_TRY_LBRACE = false;
- getSettings().SPACE_BEFORE_FINALLY_LBRACE = true;
- doTextTest("class Foo{\n" + " void foo() {\n" + " try {\n" + " } finally {\n" + " }\n" + " }\n" + "}",
- "class Foo {\n" + " void foo() {\n" + " try{\n" + " } finally {\n" + " }\n" + " }\n" + "}");
- getSettings().SPACE_BEFORE_TRY_LBRACE = true;
- getSettings().SPACE_BEFORE_FINALLY_LBRACE = false;
-
- doTextTest("class Foo{\n" + " void foo() {\n" + " try {\n" + " } finally {\n" + " }\n" + " }\n" + "}",
- "class Foo {\n" + " void foo() {\n" + " try {\n" + " } finally{\n" + " }\n" + " }\n" + "}");
-
- }
+ public void testIDEA_18299() throws Exception {
+ getSettings().RIGHT_MARGIN = 80;
+ getSettings().ARRAY_INITIALIZER_WRAP = CodeStyleSettings.WRAP_AS_NEEDED;
+ doTextTest(
+ "@AttributeOverrides( { @AttributeOverride(name = \"id\", column = @Column(name = \"recovery_id\"))," +
+ "@AttributeOverride(name = \"transactionReference\", column = @Column(name = \"deal_reference\"))," +
+ "@AttributeOverride(name = \"eventDate\", column = @Column(name = \"recovery_date\"))," +
+ "@AttributeOverride(name = \"amount\", column = @Column(name = \"recovery_amount\"))," +
+ "@AttributeOverride(name = \"currency\", column = @Column(name = \"local_currency\"))," +
+ "@AttributeOverride(name = \"exchangeRate\", column = @Column(name = \"exchange_rate\"))," +
+ "@AttributeOverride(name = \"exchangeRateDate\", column = @Column(name = \"recovery_date\", insertable = false, updatable = false))," +
+ "@AttributeOverride(name = \"exchangeRateAlterationJustification\", column = @Column(name = \"exchange_rate_justification\"))," +
+ "@AttributeOverride(name = \"systemExchangeRate\", column = @Column(name = \"system_exchange_rate\")) })\n" +
+ "class Foo {\n" +
+ "}",
+ "@AttributeOverrides({\n" +
+ " @AttributeOverride(name = \"id\", column = @Column(name = \"recovery_id\")),\n" +
+ " @AttributeOverride(name = \"transactionReference\", column = @Column(name = \"deal_reference\")),\n" +
+ " @AttributeOverride(name = \"eventDate\", column = @Column(name = \"recovery_date\")),\n" +
+ " @AttributeOverride(name = \"amount\", column = @Column(name = \"recovery_amount\")),\n" +
+ " @AttributeOverride(name = \"currency\", column = @Column(name = \"local_currency\")),\n" +
+ " @AttributeOverride(name = \"exchangeRate\", column = @Column(name = \"exchange_rate\")),\n" +
+ " @AttributeOverride(name = \"exchangeRateDate\", column = @Column(name = \"recovery_date\", insertable = false, updatable = false)),\n" +
+ " @AttributeOverride(name = \"exchangeRateAlterationJustification\", column = @Column(name = \"exchange_rate_justification\")),\n" +
+ " @AttributeOverride(name = \"systemExchangeRate\", column = @Column(name = \"system_exchange_rate\"))})\n" +
+ "class Foo {\n" +
+ "}"
+ );
+ }
- public void testIDEADEV_6239() throws Exception {
- getSettings().ENABLE_JAVADOC_FORMATTING = true;
- doTextTest("public class Test {\n" +
+ public void testIDEA_18051() throws Exception {
+ getSettings().RIGHT_MARGIN = 80;
+ doTextTest("package formatting;\n" +
"\n" +
- " /**\n" +
- " * The s property.\n" +
- " *\n" +
- " * @deprecated don't use it\n" +
- " */\n" +
- " private String s;\n" +
-"}", "public class Test {\n" +
- "\n" +
- " /**\n" +
- " * The s property.\n" +
- " *\n" +
- " * @deprecated don't use it\n" +
- " */\n" +
- " private String s;\n" +
- "}");
+ "public class EnumInAnnotationFormatting {\n" +
+ "\n" +
+ " public enum TheEnum {\n" +
+ "\n" +
+ " FIRST,\n" +
+ " SECOND,\n" +
+ " THIRD,\n" +
+ "\n" +
+ " }\n" +
+ "\n" +
+ " public @interface TheAnnotation {\n" +
+ "\n" +
+ " TheEnum[] value();\n" +
+ "\n" +
+ " String comment();\n" +
+ "\n" +
+ " }\n" +
+ "\n" +
+ "\n" +
+ " @TheAnnotation(value = {TheEnum.FIRST, TheEnum.SECOND}, comment = \"some long comment that goes longer that right margin 012345678901234567890\")\n" +
+ " public class Test {\n" +
+ "\n" +
+ " }\n" +
+ "\n" +
+ "}", "package formatting;\n" +
+ "\n" +
+ "public class EnumInAnnotationFormatting {\n" +
+ "\n" +
+ " public enum TheEnum {\n" +
+ "\n" +
+ " FIRST,\n" +
+ " SECOND,\n" +
+ " THIRD,\n" +
+ "\n" +
+ " }\n" +
+ "\n" +
+ " public @interface TheAnnotation {\n" +
+ "\n" +
+ " TheEnum[] value();\n" +
+ "\n" +
+ " String comment();\n" +
+ "\n" +
+ " }\n" +
+ "\n" +
+ "\n" +
+ " @TheAnnotation(value = {TheEnum.FIRST, TheEnum.SECOND}, comment = \"some long comment that goes longer that right margin 012345678901234567890\")\n" +
+ " public class Test {\n" +
+ "\n" +
+ " }\n" +
+ "\n" +
+ "}");
}
- public void testFormatComments() throws Exception {
- getSettings().ENABLE_JAVADOC_FORMATTING = true;
- doTextTest("public class Test {\n" + "\n" + " /**\n" + " * The s property.\n" + " */\n" + " private String s;\n" + "}",
- "public class Test {\n" + "\n" + " /**\n" + " * The s property.\n" + " */\n" + " private String s;\n" + "}");
-
+ public void testIDEA_17870() throws Exception {
+ doClassTest("public Test(@Qualifier(\"blah\") AType blah){}", "public Test(@Qualifier(\"blah\") AType blah) {\n" + "}");
}
- public void testDoNotWrapLBrace() throws IncorrectOperationException {
- getSettings().BRACE_STYLE = CodeStyleSettings.END_OF_LINE;
- getSettings().RIGHT_MARGIN = 66;
- doTextTest("public class Test {\n" +
- " void foo(){\n" +
- " if (veryLongIdentifier1 == 1 && veryLongIdentifier2 == 2) {\n" +
- " doSmth();\n" +
- " }\n" +
- " }\n" +
-"}", "public class Test {\n" +
- " void foo() {\n" +
- " if (veryLongIdentifier1 == 1 && veryLongIdentifier2 == 2) {\n" +
- " doSmth();\n" +
- " }\n" +
- " }\n" +
- "}");
- }
+ public void testIDEA_16151() throws Exception {
+ doClassTest("@ValidateNestedProperties({\n" +
+ "@Validate(field=\"name\", required=true, maxlength=Trip.NAME),\n" +
+ "@Validate(field=\"name\", required=true, maxlength=Trip.NAME)\n" +
+ "})" +
+ "public Trip getTrip() {\n" +
+ "}", "@ValidateNestedProperties({\n" +
+ " @Validate(field = \"name\", required = true, maxlength = Trip.NAME),\n" +
+ " @Validate(field = \"name\", required = true, maxlength = Trip.NAME)\n" +
+ "})\n" +
+ "public Trip getTrip() {\n" +
+ "}");
- public void testNewLinesAroundArrayInitializer() throws IncorrectOperationException {
- getSettings().ARRAY_INITIALIZER_WRAP = CodeStyleSettings.WRAP_AS_NEEDED;
- getSettings().ARRAY_INITIALIZER_LBRACE_ON_NEXT_LINE = true;
- getSettings().ARRAY_INITIALIZER_RBRACE_ON_NEXT_LINE = true;
- getSettings().RIGHT_MARGIN = 40;
- doTextTest("class Foo {\n" + " int[] a = new int[]{1,2,0x0052,0x0053,0x0054,0x0054,0x0054};\n" + "}", "class Foo {\n" +
- " int[] a = new int[]{\n" +
- " 1, 2, 0x0052, 0x0053,\n" +
- " 0x0054, 0x0054, 0x0054\n" +
- " };\n" +
- "}");
}
- public void testSpaceAfterCommaInEnum() throws IncorrectOperationException {
- getSettings().SPACE_AFTER_COMMA = true;
+ public void testIDEA_14324() throws Exception {
+ getSettings().ALIGN_MULTILINE_ARRAY_INITIALIZER_EXPRESSION = true;
- final JavaPsiFacade facade = getJavaFacade();
- final LanguageLevel effectiveLanguageLevel = LanguageLevelProjectExtension.getInstance(facade.getProject()).getLanguageLevel();
- try {
- LanguageLevelProjectExtension.getInstance(facade.getProject()).setLanguageLevel(LanguageLevel.JDK_1_5);
+ doClassTest(
+ "@Ann1({ @Ann2,\n" +
+ " @Ann3})\n" +
+ "public AuthorAddress getAddress() {\n" +
+ " return address;\n" +
+ "}",
+ "@Ann1({@Ann2,\n" +
+ " @Ann3})\n" +
+ "public AuthorAddress getAddress() {\n" +
+ " return address;\n" +
+ "}");
+ doClassTest("@AttributeOverrides({ @AttributeOverride(name = \"address\", column = @Column(name = \"ADDR\")),\n" +
+ " @AttributeOverride(name = \"country\", column = @Column(name = \"NATION\")) })\n" +
+ "public AuthorAddress getAddress() {\n" +
+ " return address;\n" +
+ "}",
+ "@AttributeOverrides({@AttributeOverride(name = \"address\", column = @Column(name = \"ADDR\")),\n" +
+ " @AttributeOverride(name = \"country\", column = @Column(name = \"NATION\"))})\n" +
+ "public AuthorAddress getAddress() {\n" +
+ " return address;\n" +
+ "}"
- doTextTest("public enum StringExDirection {\n" + "\n" + " RIGHT_TO_LEFT, LEFT_TO_RIGHT\n" + "\n" + "}",
- "public enum StringExDirection {\n" + "\n" + " RIGHT_TO_LEFT, LEFT_TO_RIGHT\n" + "\n" + "}");
- }
- finally {
- LanguageLevelProjectExtension.getInstance(facade.getProject()).setLanguageLevel(effectiveLanguageLevel);
- }
+ );
}
- public void testRemoveBraceBeforeInstanceOf() throws IncorrectOperationException {
- doTextTest("class ReformatInstanceOf {\n" +
- " void foo(Object string) {\n" +
- " if (string.toString() instanceof String) {} // reformat me\n" +
- " }\n" +
-"}", "class ReformatInstanceOf {\n" +
- " void foo(Object string) {\n" +
- " if (string.toString() instanceof String) {\n" +
- " } // reformat me\n" +
- " }\n" +
- "}");
+public void testSCR260() throws Exception {
+ final CodeStyleSettings settings = getSettings();
+ settings.IF_BRACE_FORCE = CodeStyleSettings.FORCE_BRACES_ALWAYS;
+ settings.BRACE_STYLE = CodeStyleSettings.END_OF_LINE;
+ settings.KEEP_LINE_BREAKS = false;
+ doTest();
}
- public void testAnnotationBeforePackageLocalConstructor() throws IncorrectOperationException {
- doTextTest("class Foo {\n" + " @MyAnnotation Foo() {\n" + " }\n" + "}",
- "class Foo {\n" + " @MyAnnotation\n" + " Foo() {\n" + " }\n" + "}");
+ public void testSCR114() throws Exception {
+ final CodeStyleSettings settings = getSettings();
+ settings.BRACE_STYLE = CodeStyleSettings.NEXT_LINE;
+ settings.CATCH_ON_NEW_LINE = true;
+ doTest();
}
- public void testLongAnnotationsAreNotWrapped() throws Exception {
- getSettings().ARRAY_INITIALIZER_WRAP = CodeStyleSettings.WRAP_AS_NEEDED;
+ public void testSCR259() throws Exception {
+ myTextRange = new TextRange(36, 60);
+ final CodeStyleSettings settings = getSettings();
+ settings.IF_BRACE_FORCE = CodeStyleSettings.FORCE_BRACES_ALWAYS;
+ settings.KEEP_LINE_BREAKS = false;
doTest();
}
- public void testIDEADEV_8755() throws IncorrectOperationException {
- getSettings().KEEP_LINE_BREAKS = false;
- doTextTest("class Foo {\n" +
- "void foo(){\n" +
- "System\n" +
- ".out\n" +
- ".println(\"Sleeping \" \n" +
- "+ thinkAboutItTime\n" +
- "+ \" seconds !\");" +
- "}\n" +
- "}", "class Foo {\n" +
- " void foo() {\n" +
- " System.out.println(\"Sleeping \" + thinkAboutItTime + \" seconds !\");\n" +
- " }\n" +
- "}");
+ public void testSCR279() throws Exception {
+ final CodeStyleSettings settings = getSettings();
+ settings.ALIGN_MULTILINE_BINARY_OPERATION = true;
+ doTest();
}
- public void testIDEADEV_24168() throws IncorrectOperationException {
- doTextTest(
- "class Foo {\n" + "@AnExampleMethod\n" + "public String\n" + "getMeAString()\n" + "throws AnException\n" + "{\n" + "\n" + "}\n" + "}",
- "class Foo {\n" +
- " @AnExampleMethod\n" +
- " public String\n" +
- " getMeAString()\n" +
- " throws AnException {\n" +
- "\n" +
- " }\n" +
- "}");
+ public void testSCR395() throws Exception {
+ final CodeStyleSettings settings = getSettings();
+ settings.METHOD_BRACE_STYLE = CodeStyleSettings.END_OF_LINE;
+ doTest();
}
-
- public void testIDEADEV_2541() throws IncorrectOperationException {
- myTextRange = new TextRange(0, 15);
- doTextTest("/** @param q */\nclass Foo {\n}", "/**\n" + " * @param q\n" + " */\n" + "class Foo {\n" + "}");
+ public void testSCR11799() throws Exception {
+ final CodeStyleSettings settings = getSettings();
+ settings.getIndentOptions(StdFileTypes.JAVA).CONTINUATION_INDENT_SIZE = 4;
+ settings.CLASS_BRACE_STYLE = CodeStyleSettings.NEXT_LINE;
+ settings.METHOD_BRACE_STYLE = CodeStyleSettings.NEXT_LINE;
+ doTest();
}
- public void testIDEADEV_6434() throws IncorrectOperationException {
- getSettings().ALIGN_MULTILINE_BINARY_OPERATION = true;
- getSettings().ALIGN_MULTILINE_ASSIGNMENT = true;
- doTextTest("class Foo {\n" +
- "void foo(){\n" +
- "return (interval1.getEndIndex() >= interval2.getStartIndex() &&\n" +
- " interval1.getStartIndex() <= interval2.getEndIndex()) ||\n" +
- " (interval2.getEndIndex() >= interval1.getStartIndex() &&\n" +
- " interval2.getStartIndex() <= interval1.getEndIndex());\n" +
- "}\n" +
- "}", "class Foo {\n" +
- " void foo() {\n" +
- " return (interval1.getEndIndex() >= interval2.getStartIndex() &&\n" +
- " interval1.getStartIndex() <= interval2.getEndIndex()) ||\n" +
- " (interval2.getEndIndex() >= interval1.getStartIndex() &&\n" +
- " interval2.getStartIndex() <= interval1.getEndIndex());\n" +
- " }\n" +
- "}");
+ public void testSCR501() throws Exception {
+ final CodeStyleSettings settings = getSettings();
+ settings.KEEP_FIRST_COLUMN_COMMENT = true;
+ doTest();
}
- public void testIDEADEV_12836() throws IncorrectOperationException {
- getSettings().SPECIAL_ELSE_IF_TREATMENT = true;
- getSettings().RIGHT_MARGIN = 80;
- doTextTest("class Foo {\n" +
- "void foo(){\n" +
- "if (true){\n" +
- "} else if (\" \" != null) {\n" +
- "}\n" +
- "}\n" +
- "}", "class Foo {\n" +
- " void foo() {\n" +
- "