Search in sources :

Example 91 with JavaCodeStyleManager

use of com.intellij.psi.codeStyle.JavaCodeStyleManager in project intellij-community by JetBrains.

the class AssignFieldFromParameterAction method findFieldToAssign.

@Nullable
private static PsiField findFieldToAssign(@NotNull Project project, @NotNull PsiParameter myParameter) {
    final JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(project);
    final String parameterName = myParameter.getName();
    final String propertyName = styleManager.variableNameToPropertyName(parameterName, VariableKind.PARAMETER);
    final PsiMethod method = (PsiMethod) myParameter.getDeclarationScope();
    final boolean isMethodStatic = method.hasModifierProperty(PsiModifier.STATIC);
    final VariableKind kind = isMethodStatic ? VariableKind.STATIC_FIELD : VariableKind.FIELD;
    final SuggestedNameInfo suggestedNameInfo = styleManager.suggestVariableName(kind, propertyName, null, FieldFromParameterUtils.getSubstitutedType(myParameter));
    final String fieldName = suggestedNameInfo.names[0];
    PsiClass aClass = method.getContainingClass();
    if (aClass == null)
        return null;
    PsiField field = aClass.findFieldByName(fieldName, false);
    if (field == null)
        return null;
    if (!field.hasModifierProperty(PsiModifier.STATIC) && isMethodStatic)
        return null;
    return field;
}
Also used : JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) SuggestedNameInfo(com.intellij.psi.codeStyle.SuggestedNameInfo) VariableKind(com.intellij.psi.codeStyle.VariableKind) Nullable(org.jetbrains.annotations.Nullable)

Example 92 with JavaCodeStyleManager

use of com.intellij.psi.codeStyle.JavaCodeStyleManager in project intellij-community by JetBrains.

the class JavaWithTryCatchSurrounder method surroundStatements.

@Override
public TextRange surroundStatements(Project project, Editor editor, PsiElement container, PsiElement[] statements) throws IncorrectOperationException {
    PsiManager manager = PsiManager.getInstance(project);
    PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
    JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project);
    statements = SurroundWithUtil.moveDeclarationsOut(container, statements, true);
    if (statements.length == 0) {
        return null;
    }
    List<PsiClassType> exceptions = ExceptionUtil.getUnhandledExceptions(statements);
    if (exceptions.isEmpty()) {
        exceptions = ExceptionUtil.getThrownExceptions(statements);
        if (exceptions.isEmpty()) {
            exceptions = Collections.singletonList(factory.createTypeByFQClassName("java.lang.Exception", container.getResolveScope()));
        }
    }
    @NonNls StringBuilder buffer = new StringBuilder();
    buffer.append("try{\n}");
    for (PsiClassType exception : exceptions) {
        buffer.append("catch(Exception e){\n}");
    }
    if (myGenerateFinally) {
        buffer.append("finally{\n}");
    }
    String text = buffer.toString();
    PsiTryStatement tryStatement = (PsiTryStatement) factory.createStatementFromText(text, null);
    tryStatement = (PsiTryStatement) CodeStyleManager.getInstance(project).reformat(tryStatement);
    tryStatement = (PsiTryStatement) container.addAfter(tryStatement, statements[statements.length - 1]);
    PsiCodeBlock tryBlock = tryStatement.getTryBlock();
    SurroundWithUtil.indentCommentIfNecessary(tryBlock, statements);
    tryBlock.addRange(statements[0], statements[statements.length - 1]);
    PsiCatchSection[] catchSections = tryStatement.getCatchSections();
    for (int i = 0; i < exceptions.size(); i++) {
        PsiClassType exception = exceptions.get(i);
        String[] nameSuggestions = codeStyleManager.suggestVariableName(VariableKind.PARAMETER, null, null, exception).names;
        String name = codeStyleManager.suggestUniqueVariableName(nameSuggestions[0], tryBlock, false);
        PsiCatchSection catchSection;
        try {
            catchSection = factory.createCatchSection(exception, name, null);
        } catch (IncorrectOperationException e) {
            Messages.showErrorDialog(project, CodeInsightBundle.message("surround.with.try.catch.incorrect.template.message"), CodeInsightBundle.message("surround.with.try.catch.incorrect.template.title"));
            return null;
        }
        catchSection = (PsiCatchSection) catchSections[i].replace(catchSection);
        codeStyleManager.shortenClassReferences(catchSection);
    }
    container.deleteChildRange(statements[0], statements[statements.length - 1]);
    PsiCodeBlock firstCatch = tryStatement.getCatchBlocks()[0];
    return SurroundWithUtil.getRangeToSelect(firstCatch);
}
Also used : NonNls(org.jetbrains.annotations.NonNls) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) IncorrectOperationException(com.intellij.util.IncorrectOperationException)

Example 93 with JavaCodeStyleManager

use of com.intellij.psi.codeStyle.JavaCodeStyleManager in project intellij-community by JetBrains.

the class ClsParameterImpl method calcNiceParameterName.

private String calcNiceParameterName() {
    String name = null;
    PsiParameterStubImpl stub = (PsiParameterStubImpl) getStub();
    if (!stub.isAutoGeneratedName() || DumbService.getInstance(getProject()).isDumb()) {
        name = stub.getName();
    }
    if (name == null) {
        name = "p";
        JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(getProject());
        String[] nameSuggestions = codeStyleManager.suggestCompiledParameterName(getType()).names;
        if (nameSuggestions.length > 0 && nameSuggestions[0] != null) {
            name = nameSuggestions[0];
        }
        String base = name;
        int n = 0;
        AttemptsLoop: while (true) {
            for (PsiParameter parameter : ((PsiParameterList) getParent()).getParameters()) {
                if (parameter == this)
                    break AttemptsLoop;
                String prevName = ((ClsParameterImpl) parameter).getMirrorName();
                if (name.equals(prevName)) {
                    name = base + (++n);
                    continue AttemptsLoop;
                }
            }
        }
    }
    return name;
}
Also used : PsiParameterStubImpl(com.intellij.psi.impl.java.stubs.impl.PsiParameterStubImpl) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager)

Example 94 with JavaCodeStyleManager

use of com.intellij.psi.codeStyle.JavaCodeStyleManager in project intellij-plugins by JetBrains.

the class ActionNameCustomReferenceConverter method createReferences.

@NotNull
@Override
public PsiReference[] createReferences(final GenericDomValue<String> genericDomValue, final PsiElement psiElement, final ConvertContext convertContext) {
    final PsiReferenceBase<PsiElement> ref = new PsiReferenceBase<PsiElement>(psiElement) {

        @SuppressWarnings({ "ConstantConditions" })
        public PsiElement resolve() {
            return genericDomValue.getParent().getXmlTag();
        }

        public boolean isSoft() {
            return true;
        }

        // do nothing. the element will be renamed via PsiMetaData
        public PsiElement handleElementRename(final String newElementName) throws IncorrectOperationException {
            return getElement();
        }

        @NotNull
        public Object[] getVariants() {
            final DomElement invocationElement = convertContext.getInvocationElement();
            final Action action = invocationElement.getParentOfType(Action.class, true);
            assert action != null;
            final PsiClass psiClass = action.searchActionClass();
            if (psiClass == null) {
                return EMPTY_ARRAY;
            }
            final Project project = psiClass.getProject();
            final PsiClassType classType = PsiTypesUtil.getClassType(psiClass);
            final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project);
            final SuggestedNameInfo info = codeStyleManager.suggestVariableName(VariableKind.LOCAL_VARIABLE, null, null, classType);
            final Set<String> variants = new HashSet<>(Arrays.asList(info.names));
            variants.remove(ACTION_SUFFIX);
            // remove existing action-names
            final List<Action> actions = action.getStrutsPackage().getActions();
            ContainerUtil.process(actions, action1 -> {
                variants.remove(action1.getName().getStringValue());
                return true;
            });
            return ContainerUtil.map2Array(variants, ACTION_NAME_FUNCTION);
        }
    };
    return new PsiReference[] { ref };
}
Also used : Project(com.intellij.openapi.project.Project) DomElement(com.intellij.util.xml.DomElement) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) SuggestedNameInfo(com.intellij.psi.codeStyle.SuggestedNameInfo) HashSet(java.util.HashSet) NotNull(org.jetbrains.annotations.NotNull)

Example 95 with JavaCodeStyleManager

use of com.intellij.psi.codeStyle.JavaCodeStyleManager in project android-butterknife-zelezny by avast.

the class InjectWriter method run.

@Override
public void run() throws Throwable {
    final IButterKnife butterKnife = ButterKnifeFactory.findButterKnifeForPsiElement(mProject, mFile);
    if (butterKnife == null) {
        // Butterknife library is not available for project
        return;
    }
    if (mCreateHolder) {
        generateAdapter(butterKnife);
    } else {
        if (Utils.getInjectCount(mElements) > 0) {
            generateFields(butterKnife);
        }
        generateInjects(butterKnife);
        if (Utils.getClickCount(mElements) > 0) {
            generateClick();
        }
        Utils.showInfoNotification(mProject, String.valueOf(Utils.getInjectCount(mElements)) + " injections and " + String.valueOf(Utils.getClickCount(mElements)) + " onClick added to " + mFile.getName());
    }
    // reformat class
    JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(mProject);
    styleManager.optimizeImports(mFile);
    styleManager.shortenClassReferences(mClass);
    new ReformatCodeProcessor(mProject, mClass.getContainingFile(), null, false).runWithoutProgress();
}
Also used : JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) IButterKnife(com.avast.android.butterknifezelezny.butterknife.IButterKnife) ReformatCodeProcessor(com.intellij.codeInsight.actions.ReformatCodeProcessor)

Aggregations

JavaCodeStyleManager (com.intellij.psi.codeStyle.JavaCodeStyleManager)96 Project (com.intellij.openapi.project.Project)27 SuggestedNameInfo (com.intellij.psi.codeStyle.SuggestedNameInfo)21 VariableKind (com.intellij.psi.codeStyle.VariableKind)19 IncorrectOperationException (com.intellij.util.IncorrectOperationException)15 NotNull (org.jetbrains.annotations.NotNull)13 CodeStyleManager (com.intellij.psi.codeStyle.CodeStyleManager)12 Nullable (org.jetbrains.annotations.Nullable)12 ArrayList (java.util.ArrayList)10 NonNls (org.jetbrains.annotations.NonNls)8 StringUtil (com.intellij.openapi.util.text.StringUtil)3 UniqueNameGenerator (com.intellij.util.text.UniqueNameGenerator)3 HashSet (java.util.HashSet)3 JavaLanguage (com.intellij.lang.java.JavaLanguage)2 Logger (com.intellij.openapi.diagnostic.Logger)2 Editor (com.intellij.openapi.editor.Editor)2 Comparing (com.intellij.openapi.util.Comparing)2 com.intellij.psi (com.intellij.psi)2 CodeStyleSettings (com.intellij.psi.codeStyle.CodeStyleSettings)2 FunctionalInterfaceParameterizationUtil (com.intellij.psi.impl.source.resolve.graphInference.FunctionalInterfaceParameterizationUtil)2