Search in sources :

Example 81 with RangeMarker

use of com.intellij.openapi.editor.RangeMarker in project intellij-community by JetBrains.

the class GrCreateSubclassAction method startTemplate.

private static void startTemplate(GrTypeParameterList oldTypeParameterList, final Project project, final GrTypeDefinition psiClass, final GrTypeDefinition targetClass, boolean includeClassName) {
    PsiElementFactory jfactory = JavaPsiFacade.getElementFactory(project);
    final GroovyPsiElementFactory elementFactory = GroovyPsiElementFactory.getInstance(project);
    GrCodeReferenceElement stubRef = elementFactory.createCodeReferenceElementFromClass(psiClass);
    try {
        GrReferenceList clause = psiClass.isInterface() ? targetClass.getImplementsClause() : targetClass.getExtendsClause();
        if (clause == null) {
            GrReferenceList stubRefList = psiClass.isInterface() ? elementFactory.createImplementsClause() : elementFactory.createExtendsClause();
            clause = (GrExtendsClause) targetClass.addAfter(stubRefList, targetClass.getNameIdentifierGroovy());
        }
        GrCodeReferenceElement ref = (GrCodeReferenceElement) clause.add(stubRef);
        if (psiClass.hasTypeParameters() || includeClassName) {
            final Editor editor = CodeInsightUtil.positionCursorAtLBrace(project, targetClass.getContainingFile(), targetClass);
            final TemplateBuilderImpl templateBuilder = editor == null || ApplicationManager.getApplication().isUnitTestMode() ? null : (TemplateBuilderImpl) TemplateBuilderFactory.getInstance().createTemplateBuilder(targetClass);
            if (includeClassName && templateBuilder != null) {
                templateBuilder.replaceElement(targetClass.getNameIdentifier(), targetClass.getName());
            }
            if (oldTypeParameterList != null && oldTypeParameterList.getTypeParameters().length > 0) {
                GrTypeArgumentList existingList = ref.getTypeArgumentList();
                final GrTypeParameterList typeParameterList = (GrTypeParameterList) targetClass.addAfter(elementFactory.createTypeParameterList(), targetClass.getNameIdentifierGroovy());
                GrTypeArgumentList argList;
                if (existingList == null) {
                    GrCodeReferenceElement codeRef = elementFactory.createCodeReferenceElementFromText("A<T>");
                    argList = ((GrTypeArgumentList) ref.add(codeRef.getTypeArgumentList()));
                    argList.getTypeArgumentElements()[0].delete();
                } else {
                    argList = existingList;
                }
                for (PsiTypeParameter parameter : oldTypeParameterList.getTypeParameters()) {
                    final PsiElement param = argList.add(elementFactory.createTypeElement(jfactory.createType(parameter)));
                    if (templateBuilder != null) {
                        templateBuilder.replaceElement(param, param.getText());
                    }
                    typeParameterList.add(elementFactory.createTypeParameter(parameter.getName(), parameter.getExtendsListTypes()));
                }
            }
            if (templateBuilder != null) {
                templateBuilder.setEndVariableBefore(ref);
                final Template template = templateBuilder.buildTemplate();
                template.addEndVariable();
                final PsiFile containingFile = targetClass.getContainingFile();
                PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.getDocument());
                final TextRange textRange = targetClass.getTextRange();
                final RangeMarker startClassOffset = editor.getDocument().createRangeMarker(textRange.getStartOffset(), textRange.getEndOffset());
                startClassOffset.setGreedyToLeft(true);
                startClassOffset.setGreedyToRight(true);
                editor.getDocument().deleteString(textRange.getStartOffset(), textRange.getEndOffset());
                CreateFromUsageBaseFix.startTemplate(editor, template, project, new TemplateEditingAdapter() {

                    @Override
                    public void templateFinished(Template template, boolean brokenOff) {
                        chooseAndImplement(psiClass, project, PsiTreeUtil.getParentOfType(containingFile.findElementAt(startClassOffset.getStartOffset()), GrTypeDefinition.class), editor);
                    }
                }, getTitle(psiClass));
            }
        }
    } catch (IncorrectOperationException e) {
        LOG.error(e);
    }
}
Also used : GrTypeParameterList(org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeParameterList) TemplateEditingAdapter(com.intellij.codeInsight.template.TemplateEditingAdapter) TextRange(com.intellij.openapi.util.TextRange) RangeMarker(com.intellij.openapi.editor.RangeMarker) Template(com.intellij.codeInsight.template.Template) GroovyPsiElementFactory(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory) GrCodeReferenceElement(org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement) TemplateBuilderImpl(com.intellij.codeInsight.template.TemplateBuilderImpl) GroovyPsiElementFactory(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory) GrReferenceList(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrReferenceList) IncorrectOperationException(com.intellij.util.IncorrectOperationException) Editor(com.intellij.openapi.editor.Editor) GrTypeArgumentList(org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeArgumentList)

Example 82 with RangeMarker

use of com.intellij.openapi.editor.RangeMarker in project intellij-community by JetBrains.

the class GrSetStrongTypeIntention method processIntention.

@Override
protected void processIntention(@NotNull PsiElement element, @NotNull Project project, final Editor editor) throws IncorrectOperationException {
    PsiElement parent = element.getParent();
    PsiElement elementToBuildTemplate;
    GrVariable[] variables;
    if (parent instanceof GrVariable && parent.getParent() instanceof GrVariableDeclaration) {
        variables = ((GrVariableDeclaration) parent.getParent()).getVariables();
        elementToBuildTemplate = parent.getParent();
    } else if (parent instanceof GrVariable && parent.getParent() instanceof GrForInClause) {
        variables = new GrVariable[] { (GrVariable) parent };
        elementToBuildTemplate = parent.getParent().getParent();
    } else if (parent instanceof GrVariableDeclaration) {
        variables = ((GrVariableDeclaration) parent).getVariables();
        elementToBuildTemplate = parent;
    } else if (parent instanceof GrParameter && parent.getParent() instanceof GrParameterList) {
        variables = new GrVariable[] { (GrVariable) parent };
        elementToBuildTemplate = parent.getParent().getParent();
    } else if (parent instanceof GrVariable) {
        variables = new GrVariable[] { ((GrVariable) parent) };
        elementToBuildTemplate = parent;
    } else {
        return;
    }
    ArrayList<TypeConstraint> types = new ArrayList<>();
    if (parent.getParent() instanceof GrForInClause) {
        types.add(SupertypeConstraint.create(PsiUtil.extractIteratedType((GrForInClause) parent.getParent())));
    } else {
        for (GrVariable variable : variables) {
            GrExpression initializer = variable.getInitializerGroovy();
            if (initializer != null) {
                PsiType type = initializer.getType();
                if (type != null) {
                    types.add(SupertypeConstraint.create(type));
                }
            }
            if (variable instanceof GrParameter) {
                final PsiParameter parameter = (PsiParameter) variable;
                final PsiType type = getClosureParameterType(parameter);
                if (type != null) {
                    types.add(SupertypeConstraint.create(type));
                }
            }
        }
    }
    final String originalText = elementToBuildTemplate.getText();
    final TypeInfo typeInfo = getOrCreateTypeElement(parent, elementToBuildTemplate);
    final PsiElement replaceElement = typeInfo.elementToReplace;
    TypeConstraint[] constraints = types.toArray(new TypeConstraint[types.size()]);
    ChooseTypeExpression chooseTypeExpression = new ChooseTypeExpression(constraints, element.getManager(), replaceElement.getResolveScope());
    TemplateBuilderImpl builder = new TemplateBuilderImpl(elementToBuildTemplate);
    builder.replaceElement(replaceElement, chooseTypeExpression);
    final Document document = editor.getDocument();
    final RangeMarker rangeMarker = document.createRangeMarker(elementToBuildTemplate.getTextRange());
    rangeMarker.setGreedyToRight(true);
    rangeMarker.setGreedyToLeft(true);
    final PsiElement afterPostprocess = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(elementToBuildTemplate);
    final Template template = builder.buildTemplate();
    TextRange range = afterPostprocess.getTextRange();
    document.deleteString(range.getStartOffset(), range.getEndOffset());
    TemplateManager templateManager = TemplateManager.getInstance(project);
    templateManager.startTemplate(editor, template, new TemplateEditingAdapter() {

        @Override
        public void templateFinished(Template template, boolean brokenOff) {
            if (brokenOff) {
                ApplicationManager.getApplication().runWriteAction(() -> {
                    if (rangeMarker.isValid()) {
                        document.replaceString(rangeMarker.getStartOffset(), rangeMarker.getEndOffset(), originalText);
                        editor.getCaretModel().moveToOffset(rangeMarker.getStartOffset() + typeInfo.originalOffset);
                    }
                });
            }
        }
    });
}
Also used : GrParameterList(org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameterList) ArrayList(java.util.ArrayList) GrParameter(org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter) Document(com.intellij.openapi.editor.Document) ChooseTypeExpression(org.jetbrains.plugins.groovy.template.expressions.ChooseTypeExpression) Template(com.intellij.codeInsight.template.Template) GrVariable(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable) TemplateBuilderImpl(com.intellij.codeInsight.template.TemplateBuilderImpl) TemplateManager(com.intellij.codeInsight.template.TemplateManager) PsiElement(com.intellij.psi.PsiElement) PsiType(com.intellij.psi.PsiType) TemplateEditingAdapter(com.intellij.codeInsight.template.TemplateEditingAdapter) GrExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression) TextRange(com.intellij.openapi.util.TextRange) RangeMarker(com.intellij.openapi.editor.RangeMarker) GrVariableDeclaration(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration) PsiParameter(com.intellij.psi.PsiParameter) GrForInClause(org.jetbrains.plugins.groovy.lang.psi.api.statements.clauses.GrForInClause) TypeConstraint(org.jetbrains.plugins.groovy.lang.psi.expectedTypes.TypeConstraint)

Example 83 with RangeMarker

use of com.intellij.openapi.editor.RangeMarker in project intellij-community by JetBrains.

the class GrAliasImportIntention method runTemplate.

private static void runTemplate(Project project, final GrImportStatement context, PsiMember resolved, final GroovyFileBase file, final List<UsageInfo> usages, GrImportStatement templateImport) {
    PostprocessReformattingAspect.getInstance(project).doPostponedFormatting();
    TemplateBuilderImpl templateBuilder = new TemplateBuilderImpl(templateImport);
    LinkedHashSet<String> names = getSuggestedNames(resolved, context);
    final PsiElement aliasNameElement = templateImport.getAliasNameElement();
    assert aliasNameElement != null;
    templateBuilder.replaceElement(aliasNameElement, new MyLookupExpression(resolved.getName(), names, (PsiNamedElement) resolved, resolved, true, null));
    Template built = templateBuilder.buildTemplate();
    final Editor newEditor = IntentionUtils.positionCursor(project, file, templateImport);
    final Document document = newEditor.getDocument();
    final RangeMarker contextImportPointer = document.createRangeMarker(context.getTextRange());
    final TextRange range = templateImport.getTextRange();
    document.deleteString(range.getStartOffset(), range.getEndOffset());
    final String name = resolved.getName();
    TemplateManager manager = TemplateManager.getInstance(project);
    manager.startTemplate(newEditor, built, new TemplateEditingAdapter() {

        @Override
        public void templateFinished(Template template, boolean brokenOff) {
            final GrImportStatement importStatement = ApplicationManager.getApplication().runReadAction(new Computable<GrImportStatement>() {

                @Nullable
                @Override
                public GrImportStatement compute() {
                    return PsiTreeUtil.findElementOfClassAtOffset(file, range.getStartOffset(), GrImportStatement.class, true);
                }
            });
            if (brokenOff) {
                if (importStatement != null) {
                    ApplicationManager.getApplication().runWriteAction(() -> importStatement.delete());
                }
                return;
            }
            updateRefs(usages, name, importStatement);
            ApplicationManager.getApplication().runWriteAction(() -> {
                final GrImportStatement context1 = PsiTreeUtil.findElementOfClassAtRange(file, contextImportPointer.getStartOffset(), contextImportPointer.getEndOffset(), GrImportStatement.class);
                if (context1 != null) {
                    context1.delete();
                }
            });
        }
    });
}
Also used : MyLookupExpression(com.intellij.refactoring.rename.inplace.MyLookupExpression) TemplateEditingAdapter(com.intellij.codeInsight.template.TemplateEditingAdapter) TextRange(com.intellij.openapi.util.TextRange) RangeMarker(com.intellij.openapi.editor.RangeMarker) Document(com.intellij.openapi.editor.Document) GrImportStatement(org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement) Template(com.intellij.codeInsight.template.Template) TemplateBuilderImpl(com.intellij.codeInsight.template.TemplateBuilderImpl) TemplateManager(com.intellij.codeInsight.template.TemplateManager) Editor(com.intellij.openapi.editor.Editor) Computable(com.intellij.openapi.util.Computable)

Example 84 with RangeMarker

use of com.intellij.openapi.editor.RangeMarker in project intellij-community by JetBrains.

the class ConvertFromGeeseBracesIntention method processIntention.

@Override
protected void processIntention(@NotNull PsiElement element, @NotNull Project project, Editor editor) throws IncorrectOperationException {
    if (PsiImplUtil.isWhiteSpaceOrNls(element)) {
        element = PsiTreeUtil.prevLeaf(element);
    }
    LOG.assertTrue(GeeseUtil.isClosureRBrace(element));
    PsiDocumentManager.getInstance(project).commitAllDocuments();
    PsiFile file = element.getContainingFile();
    Document document = PsiDocumentManager.getInstance(project).getDocument(file);
    PsiElement first = null;
    PsiElement last = null;
    for (PsiElement cur = element; GeeseUtil.isClosureRBrace(cur); cur = getNext(cur)) {
        last = cur;
    }
    for (PsiElement cur = element; GeeseUtil.isClosureRBrace(cur); cur = getPrev(cur)) {
        first = cur;
    }
    LOG.assertTrue(first != null);
    LOG.assertTrue(last != null);
    RangeMarker rangeMarker = document.createRangeMarker(first.getTextRange().getStartOffset(), last.getTextRange().getEndOffset());
    String text = document.getText();
    for (PsiElement cur = getPrev(last); GeeseUtil.isClosureRBrace(cur); cur = getPrev(cur)) {
        int offset = last.getTextRange().getStartOffset();
        if (!StringUtil.contains(text, cur.getTextRange().getEndOffset(), offset, '\n')) {
            document.insertString(offset, "\n");
        }
        last = cur;
    }
    CodeStyleManager.getInstance(project).reformatText(file, rangeMarker.getStartOffset(), rangeMarker.getEndOffset());
}
Also used : PsiFile(com.intellij.psi.PsiFile) RangeMarker(com.intellij.openapi.editor.RangeMarker) Document(com.intellij.openapi.editor.Document) PsiElement(com.intellij.psi.PsiElement)

Example 85 with RangeMarker

use of com.intellij.openapi.editor.RangeMarker in project intellij-community by JetBrains.

the class ConvertToGeeseBracesIntention method processIntention.

@Override
protected void processIntention(@NotNull PsiElement element, @NotNull Project project, Editor editor) throws IncorrectOperationException {
    if (PsiImplUtil.isWhiteSpaceOrNls(element)) {
        element = PsiTreeUtil.prevLeaf(element);
    }
    LOG.assertTrue(GeeseUtil.isClosureRBrace(element) && GeeseUtil.isClosureContainLF(element));
    PsiDocumentManager.getInstance(project).commitAllDocuments();
    PsiFile file = element.getContainingFile();
    Document document = PsiDocumentManager.getInstance(project).getDocument(file);
    TextRange textRange = findRange(element);
    int startOffset = textRange.getStartOffset();
    int endOffset = textRange.getEndOffset();
    RangeMarker rangeMarker = document.createRangeMarker(textRange);
    String text = document.getText();
    for (int i = endOffset - 1; i >= startOffset; i--) {
        if (text.charAt(i) == '\n')
            document.deleteString(i, i + 1);
    }
    CodeStyleManager.getInstance(project).reformatText(file, rangeMarker.getStartOffset(), rangeMarker.getEndOffset());
}
Also used : PsiFile(com.intellij.psi.PsiFile) TextRange(com.intellij.openapi.util.TextRange) RangeMarker(com.intellij.openapi.editor.RangeMarker) Document(com.intellij.openapi.editor.Document)

Aggregations

RangeMarker (com.intellij.openapi.editor.RangeMarker)111 Document (com.intellij.openapi.editor.Document)33 TextRange (com.intellij.openapi.util.TextRange)20 Project (com.intellij.openapi.project.Project)19 PsiFile (com.intellij.psi.PsiFile)14 PsiElement (com.intellij.psi.PsiElement)13 IncorrectOperationException (com.intellij.util.IncorrectOperationException)13 Editor (com.intellij.openapi.editor.Editor)11 Nullable (org.jetbrains.annotations.Nullable)11 NotNull (org.jetbrains.annotations.NotNull)10 Template (com.intellij.codeInsight.template.Template)8 TemplateBuilderImpl (com.intellij.codeInsight.template.TemplateBuilderImpl)7 TemplateEditingAdapter (com.intellij.codeInsight.template.TemplateEditingAdapter)6 PsiDocumentManager (com.intellij.psi.PsiDocumentManager)6 RangeHighlighterEx (com.intellij.openapi.editor.ex.RangeHighlighterEx)5 THashMap (gnu.trove.THashMap)5 GutterMark (com.intellij.codeInsight.daemon.GutterMark)4 HighlightSeverity (com.intellij.lang.annotation.HighlightSeverity)4 ApplicationManager (com.intellij.openapi.application.ApplicationManager)4 RelativePoint (com.intellij.ui.awt.RelativePoint)4