Search in sources :

Example 46 with CodeStyleManager

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

the class FunctionalExpressionCompletionProvider method addFunctionalVariants.

static void addFunctionalVariants(@NotNull CompletionParameters parameters, boolean smart, boolean addInheritors, CompletionResultSet result) {
    if (!PsiUtil.isLanguageLevel8OrHigher(parameters.getOriginalFile()) || !isLambdaContext(parameters.getPosition()))
        return;
    ExpectedTypeInfo[] expectedTypes = JavaSmartCompletionContributor.getExpectedTypes(parameters);
    for (ExpectedTypeInfo expectedType : expectedTypes) {
        final PsiType defaultType = expectedType.getDefaultType();
        if (LambdaUtil.isFunctionalType(defaultType)) {
            final PsiType functionalInterfaceType = FunctionalInterfaceParameterizationUtil.getGroundTargetType(defaultType);
            final PsiMethod functionalInterfaceMethod = LambdaUtil.getFunctionalInterfaceMethod(functionalInterfaceType);
            if (functionalInterfaceMethod != null) {
                PsiParameter[] params = PsiParameter.EMPTY_ARRAY;
                final PsiElement originalPosition = parameters.getPosition();
                final PsiSubstitutor substitutor = LambdaUtil.getSubstitutor(functionalInterfaceMethod, PsiUtil.resolveGenericsClassInType(functionalInterfaceType));
                if (!functionalInterfaceMethod.hasTypeParameters()) {
                    params = functionalInterfaceMethod.getParameterList().getParameters();
                    final Project project = functionalInterfaceMethod.getProject();
                    final JVMElementFactory jvmElementFactory = JVMElementFactories.getFactory(originalPosition.getLanguage(), project);
                    final JavaCodeStyleManager javaCodeStyleManager = JavaCodeStyleManager.getInstance(project);
                    if (jvmElementFactory != null) {
                        params = GenerateMembersUtil.overriddenParameters(params, jvmElementFactory, javaCodeStyleManager, substitutor, originalPosition);
                    }
                    String paramsString = params.length == 1 ? getParamName(params[0], originalPosition) : "(" + StringUtil.join(params, parameter -> getParamName(parameter, originalPosition), ",") + ")";
                    final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
                    PsiLambdaExpression lambdaExpression = (PsiLambdaExpression) JavaPsiFacade.getElementFactory(project).createExpressionFromText(paramsString + " -> {}", null);
                    lambdaExpression = (PsiLambdaExpression) codeStyleManager.reformat(lambdaExpression);
                    paramsString = lambdaExpression.getParameterList().getText();
                    final LookupElementBuilder builder = LookupElementBuilder.create(functionalInterfaceMethod, paramsString + " -> ").withPresentableText(paramsString + " -> {}").withTypeText(functionalInterfaceType.getPresentableText()).withIcon(AllIcons.Nodes.Function);
                    LookupElement lambdaElement = builder.withAutoCompletionPolicy(AutoCompletionPolicy.NEVER_AUTOCOMPLETE);
                    result.addElement(smart ? lambdaElement : PrioritizedLookupElement.withPriority(lambdaElement, 1));
                }
                addMethodReferenceVariants(smart, addInheritors, parameters, result.getPrefixMatcher(), functionalInterfaceType, functionalInterfaceMethod, params, originalPosition, substitutor, element -> result.addElement(smart ? JavaSmartCompletionContributor.decorate(element, Arrays.asList(expectedTypes)) : element));
            }
        }
    }
}
Also used : TypeConversionUtil(com.intellij.psi.util.TypeConversionUtil) java.util(java.util) AllIcons(com.intellij.icons.AllIcons) JBIterable(com.intellij.util.containers.JBIterable) ExpectedTypeInfo(com.intellij.codeInsight.ExpectedTypeInfo) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) PsiTreeUtil(com.intellij.psi.util.PsiTreeUtil) Comparing(com.intellij.openapi.util.Comparing) Project(com.intellij.openapi.project.Project) JavaResolveUtil(com.intellij.psi.impl.source.resolve.JavaResolveUtil) PsiUtil(com.intellij.psi.util.PsiUtil) ProcessingContext(com.intellij.util.ProcessingContext) LookupElementBuilder(com.intellij.codeInsight.lookup.LookupElementBuilder) LookupElement(com.intellij.codeInsight.lookup.LookupElement) StringUtil(com.intellij.openapi.util.text.StringUtil) GenerateMembersUtil(com.intellij.codeInsight.generation.GenerateMembersUtil) AutoCompletionPolicy(com.intellij.codeInsight.lookup.AutoCompletionPolicy) MethodReferenceResolver(com.intellij.psi.impl.source.tree.java.MethodReferenceResolver) Nullable(org.jetbrains.annotations.Nullable) CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) FunctionalInterfaceParameterizationUtil(com.intellij.psi.impl.source.resolve.graphInference.FunctionalInterfaceParameterizationUtil) ObjectUtils(com.intellij.util.ObjectUtils) com.intellij.psi(com.intellij.psi) NotNull(org.jetbrains.annotations.NotNull) Consumer(com.intellij.util.Consumer) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) LookupElement(com.intellij.codeInsight.lookup.LookupElement) Project(com.intellij.openapi.project.Project) ExpectedTypeInfo(com.intellij.codeInsight.ExpectedTypeInfo) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) LookupElementBuilder(com.intellij.codeInsight.lookup.LookupElementBuilder)

Example 47 with CodeStyleManager

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

the class CreateActionMethodQuickFix method invoke.

@Override
public void invoke(@NotNull final Project project, @NotNull final PsiFile psiFile, @Nullable("is null when called from inspection") final Editor editor, @NotNull final PsiElement startPsiElement, @NotNull final PsiElement endPsiElement) {
    final PsiClass actionClass = (PsiClass) startPsiElement;
    final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(project).getElementFactory();
    PsiMethod actionMethod = elementFactory.createMethodFromText("public java.lang.String " + methodName + "() throws java.lang.Exception { return \"success\"; }", actionClass);
    final JavaCodeStyleManager javaCodeStyleManager = JavaCodeStyleManager.getInstance(project);
    actionMethod = (PsiMethod) javaCodeStyleManager.shortenClassReferences(actionMethod);
    final CodeStyleManager codestylemanager = CodeStyleManager.getInstance(project);
    actionMethod = (PsiMethod) codestylemanager.reformat(actionMethod);
    final PsiMethod element = (PsiMethod) actionClass.add(actionMethod);
    //noinspection ConstantConditions
    OpenSourceUtil.navigate((Navigatable) element.getBody().getNavigationElement());
}
Also used : JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager)

Example 48 with CodeStyleManager

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

the class HbTypedHandler method adjustMustacheFormatting.

/**
   * When appropriate, adjusts the formatting for some 'staches, particularily close 'staches
   * and simple inverses ("{{^}}" and "{{else}}")
   */
private static void adjustMustacheFormatting(Project project, int offset, Editor editor, PsiFile file, FileViewProvider provider) {
    if (!HbConfig.isFormattingEnabled()) {
        // formatting disabled; nothing to do
        return;
    }
    PsiElement elementAtCaret = provider.findElementAt(offset - 1, HbLanguage.class);
    PsiElement closeOrSimpleInverseParent = PsiTreeUtil.findFirstParent(elementAtCaret, true, element -> element != null && (element instanceof HbSimpleInverse || element instanceof HbCloseBlockMustache));
    // run the formatter if the user just completed typing a SIMPLE_INVERSE or a CLOSE_BLOCK_STACHE
    if (closeOrSimpleInverseParent != null) {
        // grab the current caret position (AutoIndentLinesHandler is about to mess with it)
        PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
        CaretModel caretModel = editor.getCaretModel();
        CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
        codeStyleManager.adjustLineIndent(file, editor.getDocument().getLineStartOffset(caretModel.getLogicalPosition().line));
    }
}
Also used : CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) CaretModel(com.intellij.openapi.editor.CaretModel) PsiElement(com.intellij.psi.PsiElement)

Example 49 with CodeStyleManager

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

the class GherkinInplaceRenamer method finish.

@Override
public void finish(boolean success) {
    super.finish(success);
    if (success) {
        final PsiNamedElement newVariable = getVariable();
        if (newVariable != null) {
            final GherkinScenarioOutline scenario = PsiTreeUtil.getParentOfType(newVariable, GherkinScenarioOutline.class);
            if (scenario != null) {
                final CodeStyleManager csManager = CodeStyleManager.getInstance(newVariable.getProject());
                csManager.reformat(scenario);
            }
        }
    }
}
Also used : CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) PsiNamedElement(com.intellij.psi.PsiNamedElement) GherkinScenarioOutline(org.jetbrains.plugins.cucumber.psi.GherkinScenarioOutline)

Example 50 with CodeStyleManager

use of com.intellij.psi.codeStyle.CodeStyleManager in project android by JetBrains.

the class HtmlLinkManager method handleNewClassUrl.

private static void handleNewClassUrl(@NotNull String url, @NotNull Module module) {
    assert url.startsWith(URL_CREATE_CLASS) : url;
    String s = url.substring(URL_CREATE_CLASS.length());
    final Project project = module.getProject();
    String title = "Create Custom View";
    final String className;
    final String packageName;
    int index = s.lastIndexOf('.');
    if (index == -1) {
        className = s;
        packageName = MergedManifest.get(module).getPackage();
        if (packageName == null) {
            return;
        }
    } else {
        packageName = s.substring(0, index);
        className = s.substring(index + 1);
    }
    CreateClassDialog dialog = new CreateClassDialog(project, title, className, packageName, CreateClassKind.CLASS, true, module) {

        @Override
        protected boolean reportBaseInSourceSelectionInTest() {
            return true;
        }
    };
    dialog.show();
    if (dialog.getExitCode() == DialogWrapper.OK_EXIT_CODE) {
        final PsiDirectory targetDirectory = dialog.getTargetDirectory();
        if (targetDirectory != null) {
            PsiClass newClass = new WriteCommandAction<PsiClass>(project, "Create Class") {

                @Override
                protected void run(@NotNull Result<PsiClass> result) throws Throwable {
                    PsiClass targetClass = JavaDirectoryService.getInstance().createClass(targetDirectory, className);
                    PsiManager manager = PsiManager.getInstance(project);
                    final JavaPsiFacade facade = JavaPsiFacade.getInstance(manager.getProject());
                    final PsiElementFactory factory = facade.getElementFactory();
                    // Extend android.view.View
                    PsiJavaCodeReferenceElement superclassReference = factory.createReferenceElementByFQClassName(CLASS_VIEW, targetClass.getResolveScope());
                    PsiReferenceList extendsList = targetClass.getExtendsList();
                    if (extendsList != null) {
                        extendsList.add(superclassReference);
                    }
                    // Add constructor
                    GlobalSearchScope scope = GlobalSearchScope.allScope(project);
                    PsiJavaFile javaFile = (PsiJavaFile) targetClass.getContainingFile();
                    PsiImportList importList = javaFile.getImportList();
                    if (importList != null) {
                        PsiClass contextClass = JavaPsiFacade.getInstance(project).findClass(CLASS_CONTEXT, scope);
                        if (contextClass != null) {
                            importList.add(factory.createImportStatement(contextClass));
                        }
                        PsiClass attributeSetClass = JavaPsiFacade.getInstance(project).findClass(CLASS_ATTRIBUTE_SET, scope);
                        if (attributeSetClass != null) {
                            importList.add(factory.createImportStatement(attributeSetClass));
                        }
                    }
                    PsiMethod constructor = factory.createMethodFromText("public " + className + "(Context context, AttributeSet attrs, int defStyle) {\n" + "  super(context, attrs, defStyle);\n" + "}\n", targetClass);
                    targetClass.add(constructor);
                    // Format class
                    CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(manager.getProject());
                    PsiFile containingFile = targetClass.getContainingFile();
                    if (containingFile != null) {
                        codeStyleManager.reformat(javaFile);
                    }
                    result.setResult(targetClass);
                }
            }.execute().getResultObject();
            if (newClass != null) {
                PsiFile file = newClass.getContainingFile();
                if (file != null) {
                    openEditor(project, file, newClass.getTextOffset());
                }
            }
        }
    }
}
Also used : WriteCommandAction(com.intellij.openapi.command.WriteCommandAction) CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) NotNull(org.jetbrains.annotations.NotNull) Result(com.intellij.openapi.application.Result) Project(com.intellij.openapi.project.Project) CreateClassDialog(com.intellij.codeInsight.intention.impl.CreateClassDialog) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope)

Aggregations

CodeStyleManager (com.intellij.psi.codeStyle.CodeStyleManager)97 JavaCodeStyleManager (com.intellij.psi.codeStyle.JavaCodeStyleManager)29 Project (com.intellij.openapi.project.Project)26 TextRange (com.intellij.openapi.util.TextRange)19 NonNls (org.jetbrains.annotations.NonNls)18 IncorrectOperationException (com.intellij.util.IncorrectOperationException)16 NotNull (org.jetbrains.annotations.NotNull)8 Document (com.intellij.openapi.editor.Document)6 PsiFile (com.intellij.psi.PsiFile)6 Module (com.intellij.openapi.module.Module)5 PsiElement (com.intellij.psi.PsiElement)4 PsiDocComment (com.intellij.psi.javadoc.PsiDocComment)4 Nullable (org.jetbrains.annotations.Nullable)4 CaretModel (com.intellij.openapi.editor.CaretModel)3 CodeStyleSettings (com.intellij.psi.codeStyle.CodeStyleSettings)3 JavaLanguage (com.intellij.lang.java.JavaLanguage)2 FileType (com.intellij.openapi.fileTypes.FileType)2 Comparing (com.intellij.openapi.util.Comparing)2 StringUtil (com.intellij.openapi.util.text.StringUtil)2 com.intellij.psi (com.intellij.psi)2