Search in sources :

Example 1 with TextEdit

use of org.eclipse.text.edits.TextEdit in project che by eclipse.

the class OrganizeImportsOperation method createTextEdit.

public TextEdit createTextEdit(IProgressMonitor monitor) throws CoreException, OperationCanceledException {
    if (monitor == null) {
        monitor = new NullProgressMonitor();
    }
    try {
        fNumberOfImportsAdded = 0;
        fNumberOfImportsRemoved = 0;
        monitor.beginTask(Messages.format(CodeGenerationMessages.OrganizeImportsOperation_description, BasicElementLabels.getFileName(fCompilationUnit)), 9);
        CompilationUnit astRoot = fASTRoot;
        if (astRoot == null) {
            astRoot = SharedASTProvider.getAST(fCompilationUnit, SharedASTProvider.WAIT_YES, new SubProgressMonitor(monitor, 2));
            if (monitor.isCanceled())
                throw new OperationCanceledException();
        } else {
            monitor.worked(2);
        }
        ImportRewrite importsRewrite = StubUtility.createImportRewrite(astRoot, false);
        Set<String> oldSingleImports = new HashSet<>();
        Set<String> oldDemandImports = new HashSet<>();
        List<SimpleName> typeReferences = new ArrayList<>();
        List<SimpleName> staticReferences = new ArrayList<>();
        if (!collectReferences(astRoot, typeReferences, staticReferences, oldSingleImports, oldDemandImports))
            return null;
        monitor.worked(1);
        processor = new TypeReferenceProcessor(oldSingleImports, oldDemandImports, astRoot, importsRewrite, fIgnoreLowerCaseNames);
        Iterator<SimpleName> refIterator = typeReferences.iterator();
        while (refIterator.hasNext()) {
            SimpleName typeRef = refIterator.next();
            processor.add(typeRef);
        }
        hasOpenChoices = processor.process(new SubProgressMonitor(monitor, 3));
        addStaticImports(staticReferences, importsRewrite);
        if (hasOpenChoices) {
            choices = processor.getChoices();
            ISourceRange[] ranges = processor.getChoicesSourceRanges();
            if (fChooseImportQuery != null) {
                TypeNameMatch[] chosen = fChooseImportQuery.chooseImports(choices, ranges);
                for (int i = 0; i < chosen.length; i++) {
                    TypeNameMatch typeInfo = chosen[i];
                    importsRewrite.addImport(typeInfo.getFullyQualifiedName());
                }
            } else if (chosenFQN != null) {
                chosenFQN.forEach(importsRewrite::addImport);
            }
        }
        TextEdit result = importsRewrite.rewriteImports(new SubProgressMonitor(monitor, 3));
        determineImportDifferences(importsRewrite, oldSingleImports, oldDemandImports);
        return result;
    } finally {
        monitor.done();
    }
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) SimpleName(org.eclipse.jdt.core.dom.SimpleName) ArrayList(java.util.ArrayList) SubProgressMonitor(org.eclipse.core.runtime.SubProgressMonitor) TypeNameMatch(org.eclipse.jdt.core.search.TypeNameMatch) TextEdit(org.eclipse.text.edits.TextEdit) HashSet(java.util.HashSet) ISourceRange(org.eclipse.jdt.core.ISourceRange)

Example 2 with TextEdit

use of org.eclipse.text.edits.TextEdit in project che by eclipse.

the class ASTNodes method asFormattedString.

public static String asFormattedString(ASTNode node, int indent, String lineDelim, Map<String, String> options) {
    String unformatted = asString(node);
    TextEdit edit = CodeFormatterUtil.format2(node, unformatted, indent, lineDelim, options);
    if (edit != null) {
        Document document = new Document(unformatted);
        try {
            edit.apply(document, TextEdit.NONE);
        } catch (BadLocationException e) {
            JavaPlugin.log(e);
        }
        return document.get();
    }
    // unknown node
    return unformatted;
}
Also used : TextEdit(org.eclipse.text.edits.TextEdit) Document(org.eclipse.jface.text.Document) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 3 with TextEdit

use of org.eclipse.text.edits.TextEdit in project che by eclipse.

the class DelegateCreator method createEdit.

/**
	 * Performs the actual rewriting and adds an edit to the ASTRewrite set with
	 * {@link #setSourceRewrite(CompilationUnitRewrite)}.
	 *
	 * @throws JavaModelException
	 */
public void createEdit() throws JavaModelException {
    try {
        IDocument document = new Document(fDelegateRewrite.getCu().getBuffer().getContents());
        TextEdit edit = fDelegateRewrite.getASTRewrite().rewriteAST(document, fDelegateRewrite.getCu().getJavaProject().getOptions(true));
        edit.apply(document, TextEdit.UPDATE_REGIONS);
        String newSource = Strings.trimIndentation(document.get(fTrackedPosition.getStartPosition(), fTrackedPosition.getLength()), fPreferences.tabWidth, fPreferences.indentWidth, false);
        ASTNode placeholder = fOriginalRewrite.getASTRewrite().createStringPlaceholder(newSource, fDeclaration.getNodeType());
        CategorizedTextEditGroup groupDescription = fOriginalRewrite.createCategorizedGroupDescription(getTextEditGroupLabel(), CATEGORY_DELEGATE);
        ListRewrite bodyDeclarationsListRewrite = fOriginalRewrite.getASTRewrite().getListRewrite(fDeclaration.getParent(), getTypeBodyDeclarationsProperty());
        if (fCopy)
            if (fInsertBefore)
                bodyDeclarationsListRewrite.insertBefore(placeholder, fDeclaration, groupDescription);
            else
                bodyDeclarationsListRewrite.insertAfter(placeholder, fDeclaration, groupDescription);
        else
            bodyDeclarationsListRewrite.replace(fDeclaration, placeholder, groupDescription);
    } catch (BadLocationException e) {
        JavaPlugin.log(e);
    }
}
Also used : TextEdit(org.eclipse.text.edits.TextEdit) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) Document(org.eclipse.jface.text.Document) IDocument(org.eclipse.jface.text.IDocument) IDocument(org.eclipse.jface.text.IDocument) BadLocationException(org.eclipse.jface.text.BadLocationException) CategorizedTextEditGroup(org.eclipse.ltk.core.refactoring.CategorizedTextEditGroup)

Example 4 with TextEdit

use of org.eclipse.text.edits.TextEdit in project che by eclipse.

the class SourceProvider method getCodeBlocks.

public String[] getCodeBlocks(CallContext context, ImportRewrite importRewrite) throws CoreException {
    final ASTRewrite rewriter = ASTRewrite.create(fDeclaration.getAST());
    replaceParameterWithExpression(rewriter, context, importRewrite);
    updateImplicitReceivers(rewriter, context);
    makeNamesUnique(rewriter, context.scope);
    updateTypeReferences(rewriter, context);
    updateStaticReferences(rewriter, context);
    updateTypeVariables(rewriter, context);
    updateMethodTypeVariable(rewriter, context);
    List<IRegion> ranges = null;
    if (hasReturnValue()) {
        if (context.callMode == ASTNode.RETURN_STATEMENT) {
            ranges = getStatementRanges();
        } else {
            ranges = getExpressionRanges();
        }
    } else {
        ASTNode last = getLastStatement();
        if (last != null && last.getNodeType() == ASTNode.RETURN_STATEMENT) {
            ranges = getReturnStatementRanges();
        } else {
            ranges = getStatementRanges();
        }
    }
    final TextEdit dummy = rewriter.rewriteAST(fDocument, fTypeRoot.getJavaProject().getOptions(true));
    int size = ranges.size();
    RangeMarker[] markers = new RangeMarker[size];
    for (int i = 0; i < markers.length; i++) {
        IRegion range = ranges.get(i);
        markers[i] = new RangeMarker(range.getOffset(), range.getLength());
    }
    int split;
    if (size <= 1) {
        split = Integer.MAX_VALUE;
    } else {
        IRegion region = ranges.get(0);
        split = region.getOffset() + region.getLength();
    }
    TextEdit[] edits = dummy.removeChildren();
    for (int i = 0; i < edits.length; i++) {
        TextEdit edit = edits[i];
        int pos = edit.getOffset() >= split ? 1 : 0;
        markers[pos].addChild(edit);
    }
    MultiTextEdit root = new MultiTextEdit(0, fDocument.getLength());
    root.addChildren(markers);
    try {
        TextEditProcessor processor = new TextEditProcessor(fDocument, root, TextEdit.CREATE_UNDO | TextEdit.UPDATE_REGIONS);
        UndoEdit undo = processor.performEdits();
        String[] result = getBlocks(markers);
        // It is faster to undo the changes than coping the buffer over and over again.
        processor = new TextEditProcessor(fDocument, undo, TextEdit.UPDATE_REGIONS);
        processor.performEdits();
        return result;
    } catch (MalformedTreeException exception) {
        JavaPlugin.log(exception);
    } catch (BadLocationException exception) {
        JavaPlugin.log(exception);
    }
    return new String[] {};
}
Also used : TextEditProcessor(org.eclipse.text.edits.TextEditProcessor) MalformedTreeException(org.eclipse.text.edits.MalformedTreeException) RangeMarker(org.eclipse.text.edits.RangeMarker) IRegion(org.eclipse.jface.text.IRegion) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) TextEdit(org.eclipse.text.edits.TextEdit) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) UndoEdit(org.eclipse.text.edits.UndoEdit) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 5 with TextEdit

use of org.eclipse.text.edits.TextEdit in project che by eclipse.

the class PromoteTempToFieldRefactoring method createChange.

/*
     * @see org.eclipse.jdt.internal.corext.refactoring.base.IRefactoring#createChange(org.eclipse.core.runtime.IProgressMonitor)
     */
@Override
public Change createChange(IProgressMonitor pm) throws CoreException {
    //$NON-NLS-1$
    pm.beginTask("", 1);
    try {
        if (fFieldName.length() == 0) {
            fFieldName = getInitialFieldName();
        }
        ASTRewrite rewrite = ASTRewrite.create(fCompilationUnitNode.getAST());
        if (fInitializeIn == INITIALIZE_IN_METHOD && tempHasInitializer())
            addLocalDeclarationSplit(rewrite);
        else
            addLocalDeclarationRemoval(rewrite);
        if (fInitializeIn == INITIALIZE_IN_CONSTRUCTOR)
            addInitializersToConstructors(rewrite);
        addTempRenames(rewrite);
        addFieldDeclaration(rewrite);
        CompilationUnitChange result = new CompilationUnitChange(RefactoringCoreMessages.PromoteTempToFieldRefactoring_name, fCu);
        result.setDescriptor(new RefactoringChangeDescriptor(getRefactoringDescriptor()));
        TextEdit resultingEdits = rewrite.rewriteAST();
        TextChangeCompatibility.addTextEdit(result, RefactoringCoreMessages.PromoteTempToFieldRefactoring_editName, resultingEdits);
        return result;
    } finally {
        pm.done();
    }
}
Also used : TextEdit(org.eclipse.text.edits.TextEdit) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) CompilationUnitChange(org.eclipse.jdt.core.refactoring.CompilationUnitChange) RefactoringChangeDescriptor(org.eclipse.ltk.core.refactoring.RefactoringChangeDescriptor)

Aggregations

TextEdit (org.eclipse.text.edits.TextEdit)190 MultiTextEdit (org.eclipse.text.edits.MultiTextEdit)113 Test (org.junit.Test)49 IDocument (org.eclipse.jface.text.IDocument)48 ReplaceEdit (org.eclipse.text.edits.ReplaceEdit)48 BadLocationException (org.eclipse.jface.text.BadLocationException)34 Document (org.eclipse.jface.text.Document)33 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)32 UndoEdit (org.eclipse.text.edits.UndoEdit)26 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)23 InsertEdit (org.eclipse.text.edits.InsertEdit)22 CoreException (org.eclipse.core.runtime.CoreException)20 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)19 MalformedTreeException (org.eclipse.text.edits.MalformedTreeException)19 DeleteEdit (org.eclipse.text.edits.DeleteEdit)17 MoveSourceEdit (org.eclipse.text.edits.MoveSourceEdit)16 ArrayList (java.util.ArrayList)15 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)15 MoveTargetEdit (org.eclipse.text.edits.MoveTargetEdit)15 TextEditGroup (org.eclipse.text.edits.TextEditGroup)15