Search in sources :

Example 41 with MultiTextEdit

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

the class SelfEncapsulateFieldRefactoring method createEdits.

private void createEdits(ICompilationUnit unit, ASTRewrite rewriter, List<TextEditGroup> groups, ImportRewrite importRewrite) throws CoreException {
    TextChange change = fChangeManager.get(unit);
    MultiTextEdit root = new MultiTextEdit();
    change.setEdit(root);
    root.addChild(importRewrite.rewriteImports(null));
    root.addChild(rewriter.rewriteAST());
    for (Iterator<TextEditGroup> iter = groups.iterator(); iter.hasNext(); ) {
        change.addTextEditGroup(iter.next());
    }
}
Also used : TextChange(org.eclipse.ltk.core.refactoring.TextChange) TextEditGroup(org.eclipse.text.edits.TextEditGroup) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit)

Example 42 with MultiTextEdit

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

the class CompilationUnitRewrite method attachChange.

/**
	 * Attaches the changes of this compilation unit rewrite to the given CU Change. The given
	 * change <b>must</b> either have no root edit, or a MultiTextEdit as a root edit.
	 * The edits in the given change <b>must not</b> overlap with the changes of
	 * this compilation unit.
	 *
	 * @param cuChange existing CompilationUnitChange with a MultiTextEdit root or no root at all.
	 * @param generateGroups <code>true</code> to generate text edit groups, <code>false</code> otherwise
	 * @param monitor the progress monitor or <code>null</code>
	 * @return a change combining the changes of this rewrite and the given rewrite, or <code>null</code> for an empty change
	 * @throws CoreException when text buffer acquisition or import rewrite text edit creation fails
	 */
public CompilationUnitChange attachChange(CompilationUnitChange cuChange, boolean generateGroups, IProgressMonitor monitor) throws CoreException {
    try {
        // TODO: do we need something like ASTRewrite#hasChanges() here?
        boolean needsAstRewrite = fRewrite != null;
        boolean needsImportRemoval = fImportRemover != null && fImportRemover.hasRemovedNodes();
        boolean needsImportRewrite = fImportRewrite != null && fImportRewrite.hasRecordedChanges() || needsImportRemoval;
        if (!needsAstRewrite && !needsImportRemoval && !needsImportRewrite)
            return null;
        MultiTextEdit multiEdit = (MultiTextEdit) cuChange.getEdit();
        if (multiEdit == null) {
            multiEdit = new MultiTextEdit();
            cuChange.setEdit(multiEdit);
        }
        if (needsAstRewrite) {
            // clean up garbage from earlier calls to ASTRewrite#rewriteAST(..), see https://bugs.eclipse.org/bugs/show_bug.cgi?id=408334#c2
            clearGroupDescriptionEdits();
            TextEdit rewriteEdit;
            if (fRememberContent != null) {
                rewriteEdit = fRewrite.rewriteAST(fRememberContent, fCu.getJavaProject().getOptions(true));
            } else {
                rewriteEdit = fRewrite.rewriteAST();
            }
            if (!isEmptyEdit(rewriteEdit)) {
                multiEdit.addChild(rewriteEdit);
                if (generateGroups) {
                    for (Iterator<TextEditGroup> iter = fTextEditGroups.iterator(); iter.hasNext(); ) {
                        TextEditGroup group = iter.next();
                        cuChange.addTextEditGroup(group);
                    }
                }
            }
        }
        if (needsImportRemoval) {
            fImportRemover.applyRemoves(getImportRewrite());
        }
        if (needsImportRewrite) {
            TextEdit importsEdit = fImportRewrite.rewriteImports(monitor);
            if (!isEmptyEdit(importsEdit)) {
                multiEdit.addChild(importsEdit);
                String importUpdateName = RefactoringCoreMessages.ASTData_update_imports;
                cuChange.addTextEditGroup(new TextEditGroup(importUpdateName, importsEdit));
            }
        } else {
        }
        if (isEmptyEdit(multiEdit))
            return null;
        return cuChange;
    } finally {
        if (monitor != null)
            monitor.done();
    }
}
Also used : MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) TextEdit(org.eclipse.text.edits.TextEdit) CategorizedTextEditGroup(org.eclipse.ltk.core.refactoring.CategorizedTextEditGroup) TextEditGroup(org.eclipse.text.edits.TextEditGroup) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit)

Example 43 with MultiTextEdit

use of org.eclipse.text.edits.MultiTextEdit in project bndtools by bndtools.

the class PkgRenameParticipant method createChange.

@Override
public Change createChange(IProgressMonitor pm) throws CoreException, OperationCanceledException {
    final Map<IFile, TextChange> fileChanges = new HashMap<IFile, TextChange>();
    IResourceProxyVisitor visitor = new IResourceProxyVisitor() {

        @Override
        public boolean visit(IResourceProxy proxy) throws CoreException {
            if ((proxy.getType() == IResource.FOLDER) || (proxy.getType() == IResource.PROJECT)) {
                return true;
            }
            if (!((proxy.getType() == IResource.FILE) && proxy.getName().toLowerCase().endsWith(".bnd"))) {
                return false;
            }
            /* we're dealing with a *.bnd file */
            /* get the proxied file */
            IFile resource = (IFile) proxy.requestResource();
            /* read the file as a single string */
            String bndFileText = null;
            try {
                bndFileText = FileUtils.readFully(resource).get();
            } catch (Exception e) {
                String str = "Could not read file " + proxy.getName();
                logger.logError(str, e);
                throw new OperationCanceledException(str);
            }
            /*
                 * get the previous change for this file if it exists, or otherwise create a new change for it, but do
                 * not store it yet: wait until we know if there are actually changes in the file
                 */
            TextChange fileChange = getTextChange(resource);
            final boolean fileChangeIsNew = (fileChange == null);
            if (fileChange == null) {
                fileChange = new TextFileChange(proxy.getName(), resource);
                fileChange.setEdit(new MultiTextEdit());
            }
            TextEdit rootEdit = fileChange.getEdit();
            BndEditModel model = new BndEditModel();
            Document document = new Document(bndFileText);
            try {
                model.loadFrom(document);
            } catch (IOException e) {
                String str = "Could not load document " + proxy.getName();
                logger.logError(str, e);
                throw new OperationCanceledException(str);
            }
            /* loop over all renames to perform */
            for (Map.Entry<IPackageFragment, RenameArguments> entry : pkgFragments.entrySet()) {
                IPackageFragment pkgFragment = entry.getKey();
                RenameArguments arguments = entry.getValue();
                final String oldName = pkgFragment.getElementName();
                final String newName = arguments.getNewName();
                List<ImportPattern> newImportedPackages = makeNewHeaders(model.getImportPatterns(), oldName, newName);
                if (newImportedPackages != null) {
                    model.setImportPatterns(newImportedPackages);
                }
                List<ExportedPackage> newExportedPackages = makeNewHeaders(model.getExportedPackages(), oldName, newName);
                if (newExportedPackages != null) {
                    model.setExportedPackages(newExportedPackages);
                }
                List<String> newPrivatePackages = makeNewHeaders(model.getPrivatePackages(), oldName, newName);
                if (newPrivatePackages != null) {
                    model.setPrivatePackages(newPrivatePackages);
                }
                Map<String, String> changes = model.getDocumentChanges();
                for (Iterator<Entry<String, String>> iter = changes.entrySet().iterator(); iter.hasNext(); ) {
                    Entry<String, String> change = iter.next();
                    String propertyName = change.getKey();
                    String stringValue = change.getValue();
                    addEdit(document, rootEdit, propertyName, stringValue);
                    iter.remove();
                }
                Pattern pattern = Pattern.compile(/* match start boundary */
                "(^|" + grammarSeparator + ")" + /* match bundle activator */
                "(Bundle-Activator\\s*:\\s*)" + /* match itself / package name */
                "(" + Pattern.quote(oldName) + ")" + /* match class name */
                "(\\.[^\\.]+)" + /* match end boundary */
                "(" + grammarSeparator + "|" + Pattern.quote("\\") + "|$)");
                /* find all matches to replace and add them to the root edit */
                Matcher matcher = pattern.matcher(bndFileText);
                while (matcher.find()) {
                    rootEdit.addChild(new ReplaceEdit(matcher.start(3), matcher.group(3).length(), newName));
                }
            }
            /*
                 * only store the changes when no changes were stored before for this file and when there are actually
                 * changes.
                 */
            if (fileChangeIsNew && rootEdit.hasChildren()) {
                fileChanges.put(resource, fileChange);
            }
            return false;
        }
    };
    /* determine which projects have to be visited */
    Set<IProject> projectsToVisit = new HashSet<IProject>();
    for (IPackageFragment pkgFragment : pkgFragments.keySet()) {
        projectsToVisit.add(pkgFragment.getResource().getProject());
        for (IProject projectToVisit : pkgFragment.getResource().getProject().getReferencingProjects()) {
            projectsToVisit.add(projectToVisit);
        }
        for (IProject projectToVisit : pkgFragment.getResource().getProject().getReferencedProjects()) {
            projectsToVisit.add(projectToVisit);
        }
    }
    /* visit the projects */
    for (IProject projectToVisit : projectsToVisit) {
        projectToVisit.accept(visitor, IContainer.NONE);
    }
    if (fileChanges.isEmpty()) {
        /* no changes at all */
        return null;
    }
    /* build a composite change with all changes */
    CompositeChange cs = new CompositeChange(changeTitle);
    for (TextChange fileChange : fileChanges.values()) {
        cs.add(fileChange);
    }
    return cs;
}
Also used : IFile(org.eclipse.core.resources.IFile) IResourceProxyVisitor(org.eclipse.core.resources.IResourceProxyVisitor) HashMap(java.util.HashMap) RenameArguments(org.eclipse.ltk.core.refactoring.participants.RenameArguments) Matcher(java.util.regex.Matcher) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) IDocument(aQute.bnd.properties.IDocument) Document(aQute.bnd.properties.Document) Entry(java.util.Map.Entry) IResourceProxy(org.eclipse.core.resources.IResourceProxy) CompositeChange(org.eclipse.ltk.core.refactoring.CompositeChange) BndEditModel(aQute.bnd.build.model.BndEditModel) HashSet(java.util.HashSet) ImportPattern(aQute.bnd.build.model.clauses.ImportPattern) Pattern(java.util.regex.Pattern) IPackageFragment(org.eclipse.jdt.core.IPackageFragment) TextChange(org.eclipse.ltk.core.refactoring.TextChange) IOException(java.io.IOException) TextFileChange(org.eclipse.ltk.core.refactoring.TextFileChange) CoreException(org.eclipse.core.runtime.CoreException) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) IOException(java.io.IOException) IProject(org.eclipse.core.resources.IProject) ImportPattern(aQute.bnd.build.model.clauses.ImportPattern) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) TextEdit(org.eclipse.text.edits.TextEdit) ExportedPackage(aQute.bnd.build.model.clauses.ExportedPackage) ReplaceEdit(org.eclipse.text.edits.ReplaceEdit) HashMap(java.util.HashMap) Map(java.util.Map) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit)

Example 44 with MultiTextEdit

use of org.eclipse.text.edits.MultiTextEdit in project eclipse.platform.text by eclipse.

the class TemplateContextType method resolve.

/**
 * Resolves the variables in <code>buffer</code> within <code>context</code>
 * and edits the template buffer to reflect the resolved variables.
 *
 * @param buffer the template buffer
 * @param context the template context
 * @throws MalformedTreeException if the positions in the buffer overlap
 * @throws BadLocationException if the buffer cannot be successfully modified
 */
public void resolve(TemplateBuffer buffer, TemplateContext context) throws MalformedTreeException, BadLocationException {
    Assert.isNotNull(context);
    TemplateVariable[] variables = buffer.getVariables();
    List<RangeMarker> positions = variablesToPositions(variables);
    List<ReplaceEdit> edits = new ArrayList<>(5);
    // iterate over all variables and try to resolve them
    for (int i = 0; i != variables.length; i++) {
        TemplateVariable variable = variables[i];
        if (!variable.isResolved())
            resolve(variable, context);
        String value = variable.getDefaultValue();
        int[] offsets = variable.getOffsets();
        // update buffer to reflect new value
        for (int k = 0; k != offsets.length; k++) edits.add(new ReplaceEdit(offsets[k], variable.getInitialLength(), value));
    }
    IDocument document = new Document(buffer.getString());
    MultiTextEdit edit = new MultiTextEdit(0, document.getLength());
    edit.addChildren(positions.toArray(new TextEdit[positions.size()]));
    edit.addChildren(edits.toArray(new TextEdit[edits.size()]));
    edit.apply(document, TextEdit.UPDATE_REGIONS);
    positionsToVariables(positions, variables);
    buffer.setContent(document.get(), variables);
}
Also used : ArrayList(java.util.ArrayList) RangeMarker(org.eclipse.text.edits.RangeMarker) Document(org.eclipse.jface.text.Document) IDocument(org.eclipse.jface.text.IDocument) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) TextEdit(org.eclipse.text.edits.TextEdit) ReplaceEdit(org.eclipse.text.edits.ReplaceEdit) IDocument(org.eclipse.jface.text.IDocument) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit)

Example 45 with MultiTextEdit

use of org.eclipse.text.edits.MultiTextEdit in project eclipse.platform.text by eclipse.

the class TextEditTests method testSwap2InSwap1.

@Test
public void testSwap2InSwap1() throws Exception {
    IDocument document = new Document("foo(1, 2), 3");
    CopySourceEdit innerRoot = new CopySourceEdit(0, 9);
    {
        TextEdit e1 = new ReplaceEdit(4, 1, "");
        CopySourceEdit s1 = new CopySourceEdit(4, 1);
        e1.addChild(s1);
        CopyTargetEdit t1 = new CopyTargetEdit(7, s1);
        TextEdit e2 = new ReplaceEdit(7, 1, "");
        CopySourceEdit s2 = new CopySourceEdit(7, 1);
        e2.addChild(s2);
        CopyTargetEdit t2 = new CopyTargetEdit(4, s2);
        innerRoot.addChild(e1);
        innerRoot.addChild(t2);
        innerRoot.addChild(e2);
        innerRoot.addChild(t1);
    }
    MultiTextEdit root = new MultiTextEdit();
    {
        TextEdit e1 = new ReplaceEdit(0, 9, "");
        e1.addChild(innerRoot);
        CopyTargetEdit t1 = new CopyTargetEdit(11, innerRoot);
        TextEdit e2 = new ReplaceEdit(11, 1, "");
        CopySourceEdit s2 = new CopySourceEdit(11, 1);
        e2.addChild(s2);
        CopyTargetEdit t2 = new CopyTargetEdit(0, s2);
        root.addChild(e1);
        root.addChild(t2);
        root.addChild(e2);
        root.addChild(t1);
    }
    root.apply(document);
    String result = "3, foo(2, 1)";
    Assert.assertEquals("Buffer content", result, document.get());
}
Also used : CopySourceEdit(org.eclipse.text.edits.CopySourceEdit) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) TextEdit(org.eclipse.text.edits.TextEdit) ReplaceEdit(org.eclipse.text.edits.ReplaceEdit) CopyTargetEdit(org.eclipse.text.edits.CopyTargetEdit) Document(org.eclipse.jface.text.Document) IDocument(org.eclipse.jface.text.IDocument) IDocument(org.eclipse.jface.text.IDocument) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) Test(org.junit.Test)

Aggregations

MultiTextEdit (org.eclipse.text.edits.MultiTextEdit)51 TextEdit (org.eclipse.text.edits.TextEdit)33 Test (org.junit.Test)18 IDocument (org.eclipse.jface.text.IDocument)13 ReplaceEdit (org.eclipse.text.edits.ReplaceEdit)13 Document (org.eclipse.jface.text.Document)11 TextEditGroup (org.eclipse.text.edits.TextEditGroup)10 CompilationUnitChange (org.eclipse.jdt.core.refactoring.CompilationUnitChange)9 DeleteEdit (org.eclipse.text.edits.DeleteEdit)7 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)6 ArrayList (java.util.ArrayList)5 MalformedTreeException (org.eclipse.text.edits.MalformedTreeException)5 HashSet (java.util.HashSet)4 List (java.util.List)4 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)4 OperationCanceledException (org.eclipse.core.runtime.OperationCanceledException)4 ASTNode (org.eclipse.jdt.core.dom.ASTNode)4 TextChange (org.eclipse.ltk.core.refactoring.TextChange)4 CopySourceEdit (org.eclipse.text.edits.CopySourceEdit)4 TextEditCopier (org.eclipse.text.edits.TextEditCopier)4